JAL-629 Change colour scheme shortnames to something consistent and command-line...
[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         SubVals sv = av.getSubVals();
171         String openFile = av.getValue();
172         if (openFile == null)
173           continue;
174
175         theseArgsWereParsed = true;
176         if (first)
177         {
178           first = false;
179           if (!headless && desktop != null)
180           {
181             desktop.setProgressBar(
182                     MessageManager.getString(
183                             "status.processing_commandline_args"),
184                     progress = System.currentTimeMillis());
185             progressBarSet = true;
186           }
187         }
188
189         if (!Platform.isJS())
190         /**
191          * ignore in JavaScript -- can't just file existence - could load it?
192          * 
193          * @j2sIgnore
194          */
195         {
196           if (!HttpUtils.startsWithHttpOrHttps(openFile))
197           {
198             if (!(new File(openFile)).exists())
199             {
200               Console.warn("Can't find file '" + openFile + "'");
201             }
202           }
203         }
204
205         DataSourceType protocol = AppletFormatAdapter
206                 .checkProtocol(openFile);
207
208         FileFormatI format = null;
209         try
210         {
211           format = new IdentifyFile().identify(openFile, protocol);
212         } catch (FileFormatException e1)
213         {
214           Console.error("Unknown file format for '" + openFile + "'");
215         }
216
217         af = afMap.get(id);
218         // When to open a new AlignFrame
219         if (af == null || "true".equals(av.getSubVal("new"))
220                 || a == Arg.OPEN || format == FileFormat.Jalview)
221         {
222           /*
223            * this approach isn't working yet // get default annotations before opening
224            * AlignFrame if (m.get(Arg.SSANNOTATIONS) != null) {
225            * Console.debug("##### SSANNOTATIONS=" + m.get(Arg.SSANNOTATIONS).getBoolean());
226            * } if (m.get(Arg.NOTEMPFAC) != null) { Console.debug( "##### NOTEMPFAC=" +
227            * m.get(Arg.NOTEMPFAC).getBoolean()); } boolean showSecondaryStructure =
228            * (m.get(Arg.SSANNOTATIONS) != null) ? m.get(Arg.SSANNOTATIONS).getBoolean() :
229            * false; boolean showTemperatureFactor = (m.get(Arg.NOTEMPFAC) != null) ?
230            * !m.get(Arg.NOTEMPFAC).getBoolean() : false; Console.debug("##### tempfac=" +
231            * showTemperatureFactor + ", showSS=" + showSecondaryStructure);
232            * StructureSelectionManager ssm = StructureSelectionManager
233            * .getStructureSelectionManager(Desktop.instance); if (ssm != null) {
234            * ssm.setAddTempFacAnnot(showTemperatureFactor);
235            * ssm.setProcessSecondaryStructure(showSecondaryStructure); }
236            */
237
238           Console.debug(
239                   "Opening '" + openFile + "' in new alignment frame");
240           FileLoader fileLoader = new FileLoader(!headless);
241
242           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
243                   format);
244           boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
245                   Arg.ANNOTATIONS, av.getSubVals(), null,
246                   "SHOW_ANNOTATIONS", true);
247           af.setAnnotationsVisibility(showAnnotations, false, true);
248
249           // wrap alignment?
250           boolean wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv,
251                   null, "WRAP_ALIGNMENT", false);
252           af.getCurrentView().setWrapAlignment(wrap);
253
254           // colour aligment?
255           String colour = ArgParser.getFromSubValArgOrPref(avm, Arg.COLOUR,
256                   sv, null, "DEFAULT_COLOUR_PROT", "");
257
258           if ("" != colour)
259           {
260             af.changeColour_actionPerformed(colour);
261           }
262
263           // change alignment frame title
264           String title = ArgParser.getFromSubValArgOrPref(avm, Arg.TITLE,
265                   sv, null, null, null);
266           if (title != null)
267             af.setTitle(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           DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
341                   ? DataSourceType.URL
342                   : DataSourceType.FILE;
343           FileLoader fileLoader = new FileLoader(!headless);
344           fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
345                   false);
346         }
347
348         Console.debug("Command " + Arg.APPEND + " executed successfully!");
349
350       }
351       if (first) // first=true means nothing opened
352       {
353         if (headless)
354         {
355           Jalview.exit("Could not open any files in headless mode", 1);
356         }
357         else
358         {
359           Console.warn("No more files to open");
360         }
361       }
362       if (progressBarSet && desktop != null)
363         desktop.setProgressBar(null, progress);
364
365     }
366
367     // open the structure (from same PDB file or given PDBfile)
368     if (!avm.getBoolean(Arg.NOSTRUCTURE))
369     {
370       AlignFrame af = afMap.get(id);
371       if (avm.containsArg(Arg.STRUCTURE))
372       {
373         commandArgsProvided = true;
374         for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
375         {
376           String val = av.getValue();
377           SubVals subVals = av.getSubVals();
378           SequenceI seq = getSpecifiedSequence(af, subVals);
379           if (seq == null)
380           {
381             // Could not find sequence from subId, let's assume the first
382             // sequence in the alignframe
383             AlignmentI al = af.getCurrentView().getAlignment();
384             seq = al.getSequenceAt(0);
385           }
386
387           if (seq == null)
388           {
389             Console.warn("Could not find sequence for argument "
390                     + Arg.STRUCTURE.argString() + "=" + val);
391             // you probably want to continue here, not break
392             // break;
393             continue;
394           }
395           File structureFile = null;
396           if (subVals.getContent() != null
397                   && subVals.getContent().length() != 0)
398           {
399             structureFile = new File(subVals.getContent());
400             Console.debug("Using structure file (from argument) '"
401                     + structureFile.getAbsolutePath() + "'");
402           }
403           // TRY THIS
404           /*
405            * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
406            * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
407            * selectedSequence, true, Desktop.instance);
408            * 
409            * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
410            * SequenceI[] { selectedSequence });
411            * 
412            */
413           /* THIS DOESN'T WORK */
414           else if (seq.getAllPDBEntries() != null
415                   && seq.getAllPDBEntries().size() > 0)
416           {
417             structureFile = new File(
418                     seq.getAllPDBEntries().elementAt(0).getFile());
419             Console.debug("Using structure file (from sequence) '"
420                     + structureFile.getAbsolutePath() + "'");
421           }
422
423           if (structureFile == null)
424           {
425             Console.warn("Not provided structure file with '" + val + "'");
426             continue;
427           }
428
429           if (!structureFile.exists())
430           {
431             Console.warn("Structure file '"
432                     + structureFile.getAbsoluteFile() + "' not found.");
433             continue;
434           }
435
436           Console.debug("Using structure file "
437                   + structureFile.getAbsolutePath());
438
439           // ##### Does this need to happen? Follow
440           // openStructureFileForSequence() below
441           /*
442           PDBEntry fileEntry = new AssociatePdbFileWithSeq()
443                   .associatePdbWithSeq(structureFile.getAbsolutePath(),
444                           DataSourceType.FILE, seq, true, Desktop.instance);
445                           */
446
447           // open structure view
448           AlignmentPanel ap = af.alignPanel;
449           if (headless)
450           {
451             Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
452                     StructureViewer.ViewerType.JMOL.toString());
453           }
454
455           String structureFilepath = structureFile.getAbsolutePath();
456
457           // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
458           String paeFilepath = subVals.getWithSubstitutions(argParser, id,
459                   "paematrix");
460           String paeLabel = subVals.get("paelabel");
461           ArgValue paeAv = getArgAssociatedWithStructure(Arg.PAEMATRIX, avm,
462                   af, structureFilepath);
463           if (paeFilepath == null && paeAv != null)
464           {
465             SubVals sv = paeAv.getSubVals();
466             File paeFile = new File(sv.getContent());
467
468             paeLabel = sv.get("label");
469             try
470             {
471               paeFilepath = paeFile.getCanonicalPath();
472             } catch (IOException e)
473             {
474               paeFilepath = paeFile.getAbsolutePath();
475               Console.warn("Problem with the PAE file path: '"
476                       + paeFile.getPath() + "'");
477             }
478           }
479
480           // showing annotations from structure file or not
481           boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
482                   Arg.SSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
483                   true);
484
485           // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
486           // reference annotations
487           String tftString = subVals.get("tempfac");
488           TFType tft = avm.getBoolean(Arg.NOTEMPFAC) ? null
489                   : TFType.DEFAULT;
490           ArgValue tftAv = getArgAssociatedWithStructure(Arg.TEMPFAC, avm,
491                   af, structureFilepath);
492           if (tftString == null && tftAv != null)
493           {
494             tftString = tftAv.getSubVals().getContent();
495           }
496           if (tftString != null)
497           {
498             // get kind of temperature factor annotation
499             try
500             {
501               tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
502               Console.debug("Obtained Temperature Factor type of '" + tft
503                       + "' for structure '" + structureFilepath + "'");
504             } catch (IllegalArgumentException e)
505             {
506               // Just an error message!
507               StringBuilder sb = new StringBuilder().append("Cannot set ")
508                       .append(Arg.TEMPFAC.argString()).append(" to '")
509                       .append(tft)
510                       .append("', ignoring.  Valid values are: ");
511               Iterator<TFType> it = Arrays.stream(TFType.values())
512                       .iterator();
513               while (it.hasNext())
514               {
515                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
516                 if (it.hasNext())
517                   sb.append(", ");
518               }
519               Console.warn(sb.toString());
520             }
521           }
522
523           String sViewer = ArgParser.getFromSubValArgOrPref(avm,
524                   Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals,
525                   "viewer", null, "jmol");
526           ViewerType viewerType = null;
527           if (!"none".equals(sViewer))
528           {
529             for (ViewerType v : EnumSet.allOf(ViewerType.class))
530             {
531               String name = v.name().toLowerCase(Locale.ROOT)
532                       .replaceAll(" ", "");
533               if (sViewer.equals(name))
534               {
535                 viewerType = v;
536                 break;
537               }
538             }
539           }
540
541           boolean addTempFac = tft != null
542                   || Cache.getDefault("ADD_TEMPFACT_ANN", false);
543
544           // TODO use ssFromStructure
545           StructureChooser.openStructureFileForSequence(null, null, ap, seq,
546                   false, structureFilepath, tft, paeFilepath, false,
547                   ssFromStructure, false, viewerType);
548         }
549       }
550     }
551
552     /*
553     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
554     if (doShading)
555     {
556       AlignFrame af = afMap.get(id);
557       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
558               .findAnnotation(PDBChain.class.getName().toString()))
559       {
560         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
561                 af.alignPanel.av.getGlobalColourScheme(), 0);
562         acg.setSeqAssociated(true);
563         af.changeColour(acg);
564         Console.info("Changed colour " + acg.toString());
565       }
566     }
567     */
568
569     return theseArgsWereParsed;
570   }
571
572   protected boolean processImages(String id)
573   {
574     ArgValuesMap avm = argParser.linkedArgs(id);
575     AlignFrame af = afMap.get(id);
576
577     if (af == null)
578     {
579       Console.warn("Did not have an alignment window for id=" + id);
580       return false;
581     }
582
583     if (avm.containsArg(Arg.IMAGE))
584     {
585       for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
586       {
587         String val = av.getValue();
588         SubVals subVal = av.getSubVals();
589         String type = "png"; // default
590         String fileName = subVal.getContent();
591         File file = new File(fileName);
592         if (subVal.has("type"))
593         {
594           type = subVal.get("type");
595         }
596         else if (fileName != null)
597         {
598           for (String ext : new String[] { "svg", "png", "html" })
599           {
600             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
601             {
602               type = ext;
603             }
604           }
605         }
606         // for moment we disable JSON export
607         Cache.setPropsAreReadOnly(true);
608         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
609
610         switch (type)
611         {
612         case "svg":
613           Console.debug("Outputting type '" + type + "' to " + fileName);
614           af.createSVG(file);
615           break;
616         case "png":
617           Console.debug("Outputting type '" + type + "' to " + fileName);
618           af.createPNG(file);
619           break;
620         case "html":
621           Console.debug("Outputting type '" + type + "' to " + fileName);
622           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
623           htmlSVG.exportHTML(fileName);
624           break;
625         default:
626           Console.warn(Arg.IMAGE.argString() + " type '" + type
627                   + "' not known. Ignoring");
628           break;
629         }
630       }
631     }
632     return true;
633   }
634
635   private SequenceI getSpecifiedSequence(AlignFrame af, SubVals subId)
636   {
637     if (subId == null)
638       return null;
639     AlignmentI al = af.getCurrentView().getAlignment();
640     if (subId.has("seqid"))
641     {
642       return al.findName(subId.get("seqid"));
643     }
644     else if (-1 < subId.getIndex()
645             && subId.getIndex() < al.getSequences().size())
646     {
647       return al.getSequenceAt(subId.getIndex());
648     }
649     return null;
650   }
651
652   // returns the first Arg value intended for the structure structFilename
653   // (in the given AlignFrame from the ArgValuesMap)
654   private ArgValue getArgAssociatedWithStructure(Arg arg, ArgValuesMap avm,
655           AlignFrame af, String structFilename)
656   {
657     if (af != null)
658     {
659       for (ArgValue av : avm.getArgValueList(arg))
660       {
661         SubVals subVals = av.getSubVals();
662         String structid = subVals.get("structid");
663         String structfile = subVals.get("structfile");
664
665         // let's find a structure
666         if (structfile == null && structid == null)
667         {
668           ArgValue likelyStructure = avm.getClosestPreviousArgValueOfArg(av,
669                   Arg.STRUCTURE);
670           if (likelyStructure != null)
671           {
672             SubVals sv = likelyStructure.getSubVals();
673             if (sv != null && sv.has(ArgValues.ID))
674             {
675               structid = sv.get(ArgValues.ID);
676             }
677             else
678             {
679               structfile = likelyStructure.getValue();
680               Console.debug(
681                       "##### Comparing closest previous structure argument '"
682                               + structfile + "'");
683             }
684           }
685         }
686
687         if (structfile == null && structid != null)
688         {
689           StructureSelectionManager ssm = StructureSelectionManager
690                   .getStructureSelectionManager(Desktop.instance);
691           if (ssm != null)
692           {
693             structfile = ssm.findFileForPDBId(structid);
694           }
695         }
696         if (structfile != null && structfile.equals(structFilename))
697         {
698           return av;
699         }
700       }
701     }
702     return null;
703   }
704 }