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