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