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