90eb45c281ddc14cda5e9303575772889a2c43c4
[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.net.URISyntaxException;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.EnumSet;
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Locale;
14 import java.util.Map;
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.BioJsHTMLOutput;
36 import jalview.io.DataSourceType;
37 import jalview.io.FileFormat;
38 import jalview.io.FileFormatException;
39 import jalview.io.FileFormatI;
40 import jalview.io.FileLoader;
41 import jalview.io.HtmlSvgOutput;
42 import jalview.io.IdentifyFile;
43 import jalview.structure.StructureImportSettings.TFType;
44 import jalview.structure.StructureSelectionManager;
45 import jalview.util.HttpUtils;
46 import jalview.util.MessageManager;
47 import jalview.util.Platform;
48
49 public class Commands
50 {
51   Desktop desktop;
52
53   private boolean headless;
54
55   private ArgParser argParser;
56
57   private Map<String, AlignFrame> afMap;
58
59   private boolean commandArgsProvided = false;
60
61   private boolean argsWereParsed = false;
62
63   public Commands(ArgParser argparser, boolean headless)
64   {
65     this(Desktop.instance, argparser, headless);
66   }
67
68   public Commands(Desktop d, ArgParser argparser, boolean h)
69   {
70     argParser = argparser;
71     headless = h;
72     desktop = d;
73     afMap = new HashMap<String, AlignFrame>();
74     if (argparser != null)
75     {
76       processArgs(argparser, headless);
77     }
78   }
79
80   private boolean processArgs(ArgParser argparser, boolean h)
81   {
82     argParser = argparser;
83     headless = h;
84     boolean theseArgsWereParsed = false;
85
86     if (argParser != null && argParser.getLinkedIds() != null)
87     {
88       for (String id : argParser.getLinkedIds())
89       {
90         ArgValuesMap avm = argParser.getLinkedArgs(id);
91         theseArgsWereParsed = true;
92         theseArgsWereParsed &= processLinked(id);
93         theseArgsWereParsed &= processImages(id);
94
95         // close ap
96         if (avm.getBoolean(Arg.CLOSE))
97         {
98           AlignFrame af = afMap.get(id);
99           if (af != null)
100           {
101             af.closeMenuItem_actionPerformed(true);
102           }
103         }
104
105       }
106
107     }
108     if (argParser.getBool(Arg.QUIT))
109     {
110       Jalview.getInstance().quit();
111       return true;
112     }
113     // carry on with jalview.bin.Jalview
114     argsWereParsed = theseArgsWereParsed;
115     return argsWereParsed;
116   }
117
118   public boolean commandArgsProvided()
119   {
120     return commandArgsProvided;
121   }
122
123   public boolean argsWereParsed()
124   {
125     return argsWereParsed;
126   }
127
128   protected boolean processUnlinked(String id)
129   {
130     return processLinked(id);
131   }
132
133   protected boolean processLinked(String id)
134   {
135     boolean theseArgsWereParsed = false;
136     ArgValuesMap avm = argParser.getLinkedArgs(id);
137     if (avm == null)
138       return true;
139
140     /*
141      * // script to execute after all loading is completed one way or another String
142      * groovyscript = m.get(Arg.GROOVY) == null ? null :
143      * m.get(Arg.GROOVY).getValue(); String file = m.get(Arg.OPEN) == null ? null :
144      * m.get(Arg.OPEN).getValue(); String data = null; FileFormatI format = null;
145      * DataSourceType protocol = null;
146      */
147     if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
148     {
149       commandArgsProvided = true;
150       long progress = -1;
151
152       boolean first = true;
153       boolean progressBarSet = false;
154       AlignFrame af;
155       // Combine the APPEND and OPEN files into one list, along with whether it
156       // was APPEND or OPEN
157       List<ArgValue> openAvList = new ArrayList<>();
158       openAvList.addAll(avm.getArgValueList(Arg.OPEN));
159       openAvList.addAll(avm.getArgValueList(Arg.APPEND));
160       // sort avlist based on av.getArgIndex()
161       Collections.sort(openAvList);
162       for (ArgValue av : openAvList)
163       {
164         Arg a = av.getArg();
165         SubVals sv = av.getSubVals();
166         String openFile = av.getValue();
167         if (openFile == null)
168           continue;
169
170         theseArgsWereParsed = true;
171         if (first)
172         {
173           first = false;
174           if (!headless && desktop != null)
175           {
176             desktop.setProgressBar(
177                     MessageManager.getString(
178                             "status.processing_commandline_args"),
179                     progress = System.currentTimeMillis());
180             progressBarSet = true;
181           }
182         }
183
184         if (!Platform.isJS())
185         /**
186          * ignore in JavaScript -- can't just file existence - could load it?
187          * 
188          * @j2sIgnore
189          */
190         {
191           if (!HttpUtils.startsWithHttpOrHttps(openFile))
192           {
193             if (!(new File(openFile)).exists())
194             {
195               Console.warn("Can't find file '" + openFile + "'");
196             }
197           }
198         }
199
200         DataSourceType protocol = AppletFormatAdapter
201                 .checkProtocol(openFile);
202
203         FileFormatI format = null;
204         try
205         {
206           format = new IdentifyFile().identify(openFile, protocol);
207         } catch (FileFormatException e1)
208         {
209           Console.error("Unknown file format for '" + openFile + "'");
210         }
211
212         af = afMap.get(id);
213         // When to open a new AlignFrame
214         if (af == null || "true".equals(av.getSubVal("new"))
215                 || a == Arg.OPEN || format == FileFormat.Jalview)
216         {
217           /*
218            * this approach isn't working yet // get default annotations before opening
219            * AlignFrame if (m.get(Arg.SSANNOTATIONS) != null) {
220            * Console.debug("##### SSANNOTATIONS=" + m.get(Arg.SSANNOTATIONS).getBoolean());
221            * } if (m.get(Arg.NOTEMPFAC) != null) { Console.debug( "##### NOTEMPFAC=" +
222            * m.get(Arg.NOTEMPFAC).getBoolean()); } boolean showSecondaryStructure =
223            * (m.get(Arg.SSANNOTATIONS) != null) ? m.get(Arg.SSANNOTATIONS).getBoolean() :
224            * false; boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null) ?
225            * !m.get(Arg.NOTEMPFAC).getBoolean() : false; Console.debug("##### tempfac=" +
226            * showTemperatureFactor + ", showSS=" + showSecondaryStructure);
227            * StructureSelectionManager ssm = StructureSelectionManager
228            * .getStructureSelectionManager(Desktop.instance); if (ssm != null) {
229            * ssm.setAddTempFacAnnot(showTemperatureFactor);
230            * ssm.setProcessSecondaryStructure(showSecondaryStructure); }
231            */
232
233           Console.debug(
234                   "Opening '" + openFile + "' in new alignment frame");
235           FileLoader fileLoader = new FileLoader(!headless);
236
237           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
238                   format);
239           boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
240                   Arg.ANNOTATIONS, av.getSubVals(), null,
241                   "SHOW_ANNOTATIONS", true);
242           af.setAnnotationsVisibility(showAnnotations, false, true);
243
244           // wrap alignment?
245           boolean wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv,
246                   null, "WRAP_ALIGNMENT", false);
247           af.getCurrentView().setWrapAlignment(wrap);
248
249           // colour aligment?
250           String colour = ArgParser.getFromSubValArgOrPref(avm, av,
251                   Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
252
253           if ("" != colour)
254           {
255             af.changeColour_actionPerformed(colour);
256           }
257
258           // change alignment frame title
259           String title = ArgParser.getFromSubValArgOrPref(avm, av,
260                   Arg.TITLE, sv, null, null, null);
261           if (title != null)
262             af.setTitle(title);
263
264           // show secondary structure annotations?
265           boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
266                   Arg.SSANNOTATIONS, av.getSubVals(), null,
267                   "STRUCT_FROM_PDB", true);
268           if (avm.getBoolean(Arg.SSANNOTATIONS))
269           {
270             af.setAnnotationsVisibility(showSSAnnotations, true, false);
271             /*
272             AlignmentUtils.showOrHideSequenceAnnotations(
273                     af.getCurrentView().getAlignment(),
274                     Collections.singleton("Secondary Structure"), null,
275                     false, false);
276              */
277           }
278
279           // show temperature factor annotations?
280           if (avm.getBoolean(Arg.NOTEMPFAC))
281           {
282             // do this better (annotation types?)
283             List<String> hideThese = new ArrayList<>();
284             hideThese.add("Temperature Factor");
285             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
286             AlignmentUtils.showOrHideSequenceAnnotations(
287                     af.getCurrentView().getAlignment(), hideThese, null,
288                     false, false);
289           }
290           else
291           /*
292            * comment out hacky approach up to here and add this line: if
293            * (showTemperatureFactor)
294            */
295           {
296             /*
297             if (avm.containsArg(Arg.TEMPFAC_LABEL))
298             {
299               AlignmentAnnotation aa = AlignmentUtils
300                       .getFirstSequenceAnnotationOfType(
301                               af.getCurrentView().getAlignment(),
302                               AlignmentAnnotation.LINE_GRAPH);
303               String label = avm.getValue(Arg.TEMPFAC_LABEL);
304               if (aa != null)
305               {
306                 aa.label = label;
307               }
308               else
309               {
310                 Console.info(
311                         "Could not find annotation to apply tempfac_label '"
312                                 + label);
313               }
314             }
315             */
316           }
317
318           // store the AlignFrame for this id
319           afMap.put(id, af);
320
321           // is it its own structure file?
322           if (format.isStructureFile())
323           {
324             StructureSelectionManager ssm = StructureSelectionManager
325                     .getStructureSelectionManager(Desktop.instance);
326             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
327             ssm.computeMapping(false, new SequenceI[] { seq }, null,
328                     openFile, DataSourceType.FILE, null, null, null, false);
329           }
330         }
331         else
332         {
333           Console.debug(
334                   "Opening '" + openFile + "' in existing alignment frame");
335           DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
336                   ? DataSourceType.URL
337                   : DataSourceType.FILE;
338           FileLoader fileLoader = new FileLoader(!headless);
339           fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
340                   false);
341         }
342
343         Console.debug("Command " + Arg.APPEND + " 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.getLinkedArgs(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         String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
588                 Arg.RENDERER, subVal);
589         if (renderer == null)
590           renderer = "text";
591         type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
592         if (type == null && fileName != null)
593         {
594           for (String ext : new String[] { "svg", "png", "html", "eps" })
595           {
596             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
597             {
598               type = ext;
599             }
600           }
601         }
602         // for moment we disable JSON export
603         Cache.setPropsAreReadOnly(true);
604         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
605
606         switch (type)
607         {
608
609         case "svg":
610           Console.debug("Outputting type '" + type + "' to " + fileName);
611           af.createSVG(file, renderer);
612           break;
613
614         case "png":
615           Console.debug("Outputting type '" + type + "' to " + fileName);
616           af.createPNG(file);
617           break;
618
619         case "html":
620           Console.debug("Outputting type '" + type + "' to " + fileName);
621           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
622           htmlSVG.exportHTML(fileName, renderer);
623           break;
624
625         case "biojs":
626           try
627           {
628             BioJsHTMLOutput.refreshVersionInfo(
629                     BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
630           } catch (URISyntaxException e)
631           {
632             e.printStackTrace();
633           }
634           BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
635           bjs.exportHTML(fileName);
636           Console.debug("Creating BioJS MSA Viwer HTML file: " + fileName);
637           break;
638
639         default:
640           Console.warn(Arg.IMAGE.argString() + " type '" + type
641                   + "' not known. Ignoring");
642           break;
643         }
644       }
645     }
646     return true;
647   }
648
649   private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
650   {
651     if (subId == null)
652       return null;
653     AlignmentI al = af.getCurrentView().getAlignment();
654     if (subId.has("seqid"))
655     {
656       return al.findName(subId.get("seqid"));
657     }
658     else if (-1 < subId.getIndex()
659             && subId.getIndex() < al.getSequences().size())
660     {
661       return al.getSequenceAt(subId.getIndex());
662     }
663     return null;
664   }
665
666   // returns the first Arg value intended for the structure structFilename
667   // (in the given AlignFrame from the ArgValuesMap)
668   private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
669           AlignFrame af, String structFilename)
670   {
671     if (af != null)
672     {
673       for (ArgValue av : avm.getArgValueList(arg))
674       {
675         SubVals subVals = av.getSubVals();
676         String structid = subVals.get("structid");
677         String structfile = subVals.get("structfile");
678
679         // let's find a structure
680         if (structfile == null && structid == null)
681         {
682           ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
683                   Arg.STRUCTURE);
684           if (likelyStructure != null)
685           {
686             SubVals sv = likelyStructure.getSubVals();
687             if (sv != null && sv.has(ArgValues.ID))
688             {
689               structid = sv.get(ArgValues.ID);
690             }
691             else
692             {
693               structfile = likelyStructure.getValue();
694             }
695           }
696         }
697
698         if (structfile == null && structid != null)
699         {
700           StructureSelectionManager ssm = StructureSelectionManager
701                   .getStructureSelectionManager(Desktop.instance);
702           if (ssm != null)
703           {
704             structfile = ssm.findFileForPDBId(structid);
705           }
706         }
707         if (structfile != null && structfile.equals(structFilename))
708         {
709           return av;
710         }
711       }
712     }
713     return null;
714   }
715 }