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