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