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