JAL-629 Added --opennew --nonews --nosplash. Added java globbing for = e.g. --open...
[jalview.git] / src / jalview / bin / Commands.java
1 package jalview.bin;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.util.AbstractMap;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.HashMap;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Locale;
13 import java.util.Map;
14 import java.util.Map.Entry;
15
16 import jalview.analysis.AlignmentUtils;
17 import jalview.api.AlignmentViewPanel;
18 import jalview.bin.argparser.Arg;
19 import jalview.bin.argparser.ArgParser;
20 import jalview.bin.argparser.ArgValue;
21 import jalview.bin.argparser.ArgValues;
22 import jalview.bin.argparser.ArgValuesMap;
23 import jalview.bin.argparser.SubVals;
24 import jalview.datamodel.AlignmentAnnotation;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.AlignmentPanel;
31 import jalview.gui.AssociatePdbFileWithSeq;
32 import jalview.gui.Desktop;
33 import jalview.gui.Preferences;
34 import jalview.gui.StructureChooser;
35 import jalview.gui.StructureViewer;
36 import jalview.io.AppletFormatAdapter;
37 import jalview.io.DataSourceType;
38 import jalview.io.FileFormat;
39 import jalview.io.FileFormatException;
40 import jalview.io.FileFormatI;
41 import jalview.io.FileLoader;
42 import jalview.io.HtmlSvgOutput;
43 import jalview.io.IdentifyFile;
44 import jalview.schemes.AnnotationColourGradient;
45 import jalview.structure.StructureImportSettings;
46 import jalview.structure.StructureImportSettings.TFType;
47 import jalview.structure.StructureSelectionManager;
48 import jalview.util.HttpUtils;
49 import jalview.util.MessageManager;
50 import jalview.util.Platform;
51 import jalview.ws.dbsources.EBIAlfaFold;
52 import mc_view.PDBChain;
53
54 public class Commands
55 {
56   Desktop desktop;
57
58   private boolean headless;
59
60   private ArgParser argParser;
61
62   private Map<String, AlignFrame> afMap;
63
64   private boolean commandArgsProvided = false;
65
66   private boolean argsWereParsed = false;
67
68   public Commands(ArgParser argparser, boolean headless)
69   {
70     this(Desktop.instance, argparser, headless);
71   }
72
73   public Commands(Desktop d, ArgParser argparser, boolean h)
74   {
75     argParser = argparser;
76     headless = h;
77     desktop = d;
78     afMap = new HashMap<String, AlignFrame>();
79     if (argparser != null)
80     {
81       processArgs(argparser, headless);
82     }
83   }
84
85   private boolean processArgs(ArgParser argparser, boolean h)
86   {
87     argParser = argparser;
88     headless = h;
89     boolean theseArgsWereParsed = false;
90
91     if (argParser != null && argParser.linkedIds() != null)
92     {
93       for (String id : argParser.linkedIds())
94       {
95         ArgValuesMap avm = argParser.linkedArgs(id);
96         theseArgsWereParsed = true;
97         if (id == null)
98         {
99           theseArgsWereParsed &= processUnlinked(id);
100         }
101         else
102         {
103           theseArgsWereParsed &= processLinked(id);
104         }
105         theseArgsWereParsed &= processImages(id);
106
107         // close ap
108         if (avm.getBoolean(Arg.CLOSE))
109         {
110           AlignFrame af = afMap.get(id);
111           if (af != null)
112           {
113             af.closeMenuItem_actionPerformed(true);
114           }
115         }
116
117       }
118
119     }
120     if (argParser.getBool(Arg.QUIT))
121     {
122       Jalview.getInstance().quit();
123       return true;
124     }
125     // carry on with jalview.bin.Jalview
126     argsWereParsed = theseArgsWereParsed;
127     return argsWereParsed;
128   }
129
130   public boolean commandArgsProvided()
131   {
132     return commandArgsProvided;
133   }
134
135   public boolean argsWereParsed()
136   {
137     return argsWereParsed;
138   }
139
140   protected boolean processUnlinked(String id)
141   {
142     return processLinked(id);
143   }
144
145   protected boolean processLinked(String id)
146   {
147     boolean theseArgsWereParsed = false;
148     ArgValuesMap avm = argParser.linkedArgs(id);
149     if (avm == null)
150       return true;
151
152     /*
153     // script to execute after all loading is completed one way or another
154     String groovyscript = m.get(Arg.GROOVY) == null ? null
155             : m.get(Arg.GROOVY).getValue();
156     String file = m.get(Arg.OPEN) == null ? null
157             : m.get(Arg.OPEN).getValue();
158     String data = null;
159     FileFormatI format = null;
160     DataSourceType protocol = null;
161     */
162     if (avm.containsArg(Arg.OPEN) || avm.containsArg(Arg.OPENNEW))
163     {
164       commandArgsProvided = true;
165       long progress = -1;
166
167       boolean first = true;
168       boolean progressBarSet = false;
169       AlignFrame af;
170       // Combine the OPEN and OPENNEW files into one list, along with whether it
171       // was OPEN or OPENNEW
172       List<Entry<Arg, ArgValue>> openAvList = new ArrayList<>();
173       avm.getArgValueList(Arg.OPEN).stream()
174               .forEachOrdered(av -> openAvList.add(
175                       new AbstractMap.SimpleEntry<Arg, ArgValue>(Arg.OPEN,
176                               av)));
177       avm.getArgValueList(Arg.OPENNEW).stream()
178               .forEachOrdered(av -> openAvList
179                       .add(new AbstractMap.SimpleEntry<Arg, ArgValue>(
180                               Arg.OPENNEW, av)));
181       for (Entry<Arg, ArgValue> aav : openAvList)
182       {
183         Arg a = aav.getKey();
184         ArgValue av = aav.getValue();
185         String openFile = av.getValue();
186         if (openFile == null)
187           continue;
188
189         theseArgsWereParsed = true;
190         if (first)
191         {
192           first = false;
193           if (!headless && desktop != null)
194           {
195             desktop.setProgressBar(
196                     MessageManager.getString(
197                             "status.processing_commandline_args"),
198                     progress = System.currentTimeMillis());
199             progressBarSet = true;
200           }
201         }
202
203         if (!Platform.isJS())
204         /**
205          * ignore in JavaScript -- can't just file existence - could load it?
206          * 
207          * @j2sIgnore
208          */
209         {
210           if (!HttpUtils.startsWithHttpOrHttps(openFile))
211           {
212             if (!(new File(openFile)).exists())
213             {
214               Console.warn("Can't find file '" + openFile + "'");
215             }
216           }
217         }
218
219         DataSourceType protocol = AppletFormatAdapter
220                 .checkProtocol(openFile);
221
222         FileFormatI format = null;
223         try
224         {
225           format = new IdentifyFile().identify(openFile, protocol);
226         } catch (FileFormatException e1)
227         {
228           Console.error("Unknown file format for '" + openFile + "'");
229         }
230
231         af = afMap.get(id);
232         if (af == null || "true".equals(av.getSubVal("new"))
233                 || a == Arg.OPENNEW || format == FileFormat.Jalview)
234         {
235           /*
236            * this approach isn't working yet
237           // get default annotations before opening AlignFrame
238           if (m.get(Arg.SSANNOTATION) != null)
239           {
240             Console.debug("***** SSANNOTATION="
241                     + m.get(Arg.SSANNOTATION).getBoolean());
242           }
243           if (m.get(Arg.NOTEMPFAC) != null)
244           {
245             Console.debug(
246                     "***** NOTEMPFAC=" + m.get(Arg.NOTEMPFAC).getBoolean());
247           }
248           boolean showSecondaryStructure = (m.get(Arg.SSANNOTATION) != null)
249                   ? m.get(Arg.SSANNOTATION).getBoolean()
250                   : false;
251           boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null)
252                   ? !m.get(Arg.NOTEMPFAC).getBoolean()
253                   : false;
254           Console.debug("***** tempfac=" + showTemperatureFactor
255                   + ", showSS=" + showSecondaryStructure);
256           StructureSelectionManager ssm = StructureSelectionManager
257                   .getStructureSelectionManager(Desktop.instance);
258           if (ssm != null)
259           {
260             ssm.setAddTempFacAnnot(showTemperatureFactor);
261             ssm.setProcessSecondaryStructure(showSecondaryStructure);
262           }
263            */
264
265           // get kind of temperature factor annotation
266           StructureImportSettings.TFType tempfacType = TFType.DEFAULT;
267           if ((!avm.getBoolean(Arg.NOTEMPFAC))
268                   && avm.containsArg(Arg.TEMPFAC))
269           {
270             try
271             {
272               tempfacType = StructureImportSettings.TFType
273                       .valueOf(avm.getArgValue(Arg.TEMPFAC).getValue()
274                               .toUpperCase(Locale.ROOT));
275               Console.debug("Obtained Temperature Factor type of '"
276                       + tempfacType + "'");
277             } catch (IllegalArgumentException e)
278             {
279               // Just an error message!
280               StringBuilder sb = new StringBuilder().append("Cannot set --")
281                       .append(Arg.TEMPFAC.getName()).append(" to '")
282                       .append(tempfacType)
283                       .append("', ignoring.  Valid values are: ");
284               Iterator<StructureImportSettings.TFType> it = Arrays
285                       .stream(StructureImportSettings.TFType.values())
286                       .iterator();
287               while (it.hasNext())
288               {
289                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
290                 if (it.hasNext())
291                   sb.append(", ");
292               }
293               Console.warn(sb.toString());
294             }
295           }
296
297           Console.debug(
298                   "Opening '" + openFile + "' in new alignment frame");
299           FileLoader fileLoader = new FileLoader(!headless);
300
301           StructureImportSettings.setTemperatureFactorType(tempfacType);
302
303           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
304                   format);
305
306           // wrap alignment?
307           if (avm.getBoolean(Arg.WRAP))
308           {
309             af.getCurrentView().setWrapAlignment(true);
310           }
311
312           // colour aligment?
313           if (avm.containsArg(Arg.COLOUR))
314           {
315             af.changeColour_actionPerformed(avm.getValue(Arg.COLOUR));
316           }
317
318           // change alignment frame title
319           if (avm.containsArg(Arg.TITLE))
320             af.setTitle(avm.getValue(Arg.TITLE));
321
322           /* hacky approach to hiding the annotations */
323           // show secondary structure annotations?
324           if (avm.getBoolean(Arg.SSANNOTATION))
325           {
326             // do this better (annotation types?)
327             AlignmentUtils.showOrHideSequenceAnnotations(
328                     af.getCurrentView().getAlignment(),
329                     Collections.singleton("Secondary Structure"), null,
330                     false, false);
331           }
332
333           // show temperature factor annotations?
334           if (avm.getBoolean(Arg.NOTEMPFAC))
335           {
336             // do this better (annotation types?)
337             List<String> hideThese = new ArrayList<>();
338             hideThese.add("Temperature Factor");
339             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
340             AlignmentUtils.showOrHideSequenceAnnotations(
341                     af.getCurrentView().getAlignment(), hideThese, null,
342                     false, false);
343           }
344           else
345           /* comment out hacky approach up to here and add this line:
346            if (showTemperatureFactor)
347              */
348           {
349             if (avm.containsArg(Arg.TEMPFAC_LABEL))
350             {
351               AlignmentAnnotation aa = AlignmentUtils
352                       .getFirstSequenceAnnotationOfType(
353                               af.getCurrentView().getAlignment(),
354                               AlignmentAnnotation.LINE_GRAPH);
355               String label = avm.getValue(Arg.TEMPFAC_LABEL);
356               if (aa != null)
357               {
358                 aa.label = label;
359               }
360               else
361               {
362                 Console.info(
363                         "Could not find annotation to apply tempfac_label '"
364                                 + label);
365               }
366             }
367           }
368
369           // store the AlignFrame for this id
370           afMap.put(id, af);
371
372           // is it its own structure file?
373           if (format.isStructureFile())
374           {
375             StructureSelectionManager ssm = StructureSelectionManager
376                     .getStructureSelectionManager(Desktop.instance);
377             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
378             ssm.computeMapping(false, new SequenceI[] { seq }, null,
379                     openFile, DataSourceType.FILE, null, null, null);
380           }
381         }
382         else
383         {
384           Console.debug(
385                   "Opening '" + openFile + "' in existing alignment frame");
386           af.getCurrentView().addFile(new File(openFile), format, false);
387         }
388
389         Console.debug("Command " + Arg.OPEN + " executed successfully!");
390
391       }
392       if (first) // first=true means nothing opened
393       {
394         if (headless)
395         {
396           Jalview.exit("Could not open any files in headless mode", 1);
397         }
398         else
399         {
400           Console.warn("No more files to open");
401         }
402       }
403       if (progressBarSet && desktop != null)
404         desktop.setProgressBar(null, progress);
405
406     }
407
408     // open the structure (from same PDB file or given PDBfile)
409     if (!avm.getBoolean(Arg.NOSTRUCTURE))
410     {
411       AlignFrame af = afMap.get(id);
412       if (avm.containsArg(Arg.STRUCTURE))
413       {
414         commandArgsProvided = true;
415         for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
416         {
417           String val = av.getValue();
418           SubVals subId = new SubVals(val);
419           SequenceI seq = getSpecifiedSequence(af, subId);
420           if (seq == null)
421           {
422             Console.warn("Could not find sequence for argument --"
423                     + Arg.STRUCTURE + "=" + val);
424             // you probably want to continue here, not break
425             // break;
426             continue;
427           }
428           File structureFile = null;
429           if (subId.getContent() != null
430                   && subId.getContent().length() != 0)
431           {
432             structureFile = new File(subId.getContent());
433             Console.debug("Using structure file (from argument) '"
434                     + structureFile.getAbsolutePath() + "'");
435           }
436
437           // TRY THIS
438           /*
439            PDBEntry fileEntry = new AssociatePdbFileWithSeq()
440                   .associatePdbWithSeq(selectedPdbFileName,
441                           DataSourceType.FILE, selectedSequence, true,
442                           Desktop.instance);
443                           
444            sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry },
445                   ap, new SequenceI[]
446                   { selectedSequence });
447           
448            */
449
450           /* THIS DOESN'T WORK */
451           else if (seq.getAllPDBEntries() != null
452                   && seq.getAllPDBEntries().size() > 0)
453           {
454             structureFile = new File(
455                     seq.getAllPDBEntries().elementAt(0).getFile());
456             Console.debug("Using structure file (from sequence) '"
457                     + structureFile.getAbsolutePath() + "'");
458           }
459
460           if (structureFile == null)
461           {
462             Console.warn("Not provided structure file with '" + val + "'");
463             continue;
464           }
465
466           if (!structureFile.exists())
467           {
468             Console.warn("Structure file '"
469                     + structureFile.getAbsoluteFile() + "' not found.");
470             continue;
471           }
472
473           Console.debug("Using structure file "
474                   + structureFile.getAbsolutePath());
475
476           PDBEntry fileEntry = new AssociatePdbFileWithSeq()
477                   .associatePdbWithSeq(structureFile.getAbsolutePath(),
478                           DataSourceType.FILE, seq, true, Desktop.instance);
479
480           // open structure view
481           AlignmentPanel ap = af.alignPanel;
482           if (headless)
483           {
484             Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
485                     StructureViewer.ViewerType.JMOL.toString());
486           }
487
488           // get tft, paeFilename, label?
489           /*
490           ArgValue tftAv = avm.getArgValuesReferringTo("structid", structId,
491                   Arg.TEMPFAC);
492            */
493           StructureChooser.openStructureFileForSequence(null, null, ap, seq,
494                   false, structureFile.getAbsolutePath(), null, null); // tft,
495                                                                        // paeFilename);
496         }
497       }
498     }
499
500     // load a pAE file if given
501     if (avm.containsArg(Arg.PAEMATRIX))
502     {
503       AlignFrame af = afMap.get(id);
504       if (af != null)
505       {
506         for (ArgValue av : avm.getArgValueList(Arg.PAEMATRIX))
507         {
508           String val = av.getValue();
509           SubVals subVals = ArgParser.getSubVals(val);
510           String paeLabel = subVals.get("label");
511           File paeFile = new File(subVals.getContent());
512           String paePath = null;
513           try
514           {
515             paePath = paeFile.getCanonicalPath();
516           } catch (IOException e)
517           {
518             paePath = paeFile.getAbsolutePath();
519             Console.warn(
520                     "Problem with the PAE file path: '" + paePath + "'");
521           }
522           String structid = null;
523           String structfile = null;
524           String seqid = null;
525           if (subVals.notSet())
526           {
527             ArgValue likelyStructure = avm
528                     .getClosestPreviousArgValueOfArg(av, Arg.STRUCTURE);
529             if (likelyStructure != null)
530             {
531               SubVals sv = likelyStructure.getSubVals();
532               if (sv != null && sv.has(ArgValues.ID))
533               {
534                 structid = sv.get(ArgValues.ID);
535               }
536               else
537               {
538                 structfile = likelyStructure.getValue();
539               }
540             }
541           }
542           else if (subVals.has("structfile"))
543           {
544             structfile = subVals.get("structfile");
545           }
546           else if (subVals.has("structid"))
547           {
548             structid = subVals.get("structid");
549           }
550           if (structfile != null)
551           {
552             Console.info("***** Attaching paeFile '" + paePath + "' to "
553                     + "structfile=" + subVals.get("structfile"));
554             EBIAlfaFold.addAlphaFoldPAE(af.getCurrentView().getAlignment(),
555                     paeFile, subVals.getIndex(), subVals.get("structfile"),
556                     true, false, paeLabel);
557           }
558           else if (structid != null)
559           {
560             Console.info("***** Attaching paeFile '" + paePath + "' to "
561                     + "structid=" + subVals.get("structid"));
562             EBIAlfaFold.addAlphaFoldPAE(af.getCurrentView().getAlignment(),
563                     paeFile, subVals.getIndex(), subVals.get("structid"),
564                     true, true, paeLabel);
565           }
566           else
567           {
568             Console.debug("***** Attaching paeFile '" + paePath
569                     + "' to sequence index " + subVals.getIndex());
570             EBIAlfaFold.addAlphaFoldPAE(af.getCurrentView().getAlignment(),
571                     paeFile, subVals.getIndex(), null, false, false,
572                     paeLabel);
573             // required to readjust the height and position of the pAE
574             // annotation
575           }
576           for (AlignmentViewPanel ap : af.getAlignPanels())
577           {
578             ap.adjustAnnotationHeight();
579           }
580         }
581       }
582     }
583
584     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
585     if (doShading)
586     {
587       AlignFrame af = afMap.get(id);
588       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
589               .findAnnotation(PDBChain.class.getName().toString()))
590       {
591         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
592                 af.alignPanel.av.getGlobalColourScheme(), 0);
593         acg.setSeqAssociated(true);
594         af.changeColour(acg);
595         Console.info("Changed colour " + acg.toString());
596       }
597     }
598
599     return theseArgsWereParsed;
600   }
601
602   protected boolean processImages(String id)
603   {
604     ArgValuesMap avm = argParser.linkedArgs(id);
605     AlignFrame af = afMap.get(id);
606
607     if (af == null)
608     {
609       Console.warn("Did not have an alignment window for id=" + id);
610       return false;
611     }
612
613     if (avm.containsArg(Arg.IMAGE))
614     {
615       for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
616       {
617         String val = av.getValue();
618         SubVals subVal = new SubVals(val);
619         String type = "png"; // default
620         String fileName = subVal.getContent();
621         File file = new File(fileName);
622         if (subVal.has("type"))
623         {
624           type = subVal.get("type");
625         }
626         else if (fileName != null)
627         {
628           for (String ext : new String[] { "svg", "png", "html" })
629           {
630             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
631             {
632               type = ext;
633             }
634           }
635         }
636         // for moment we disable JSON export
637         Cache.setPropsAreReadOnly(true);
638         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
639
640         switch (type)
641         {
642         case "svg":
643           Console.debug("Outputting type '" + type + "' to " + fileName);
644           af.createSVG(file);
645           break;
646         case "png":
647           Console.debug("Outputting type '" + type + "' to " + fileName);
648           af.createPNG(file);
649           break;
650         case "html":
651           Console.debug("Outputting type '" + type + "' to " + fileName);
652           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
653           htmlSVG.exportHTML(fileName);
654           break;
655         default:
656           Console.warn("--image type '" + type + "' not known. Ignoring");
657           break;
658         }
659       }
660     }
661     return true;
662   }
663
664   private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
665   {
666     AlignmentI al = af.getCurrentView().getAlignment();
667     if (-1 < subId.getIndex()
668             && subId.getIndex() < al.getSequences().size())
669     {
670       return al.getSequenceAt(subId.getIndex());
671     }
672     else if (subId.has("seqid"))
673     {
674       return al.findName(subId.get("seqid"));
675     }
676     return null;
677   }
678 }