JAL-629 suggest not breaking out of the structure processing loop if just one structu...
[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             // you probably want to continue here, not break
416             // break;
417             continue;
418           }
419           File structureFile = null;
420           if (subId.content != null && subId.content.length() != 0)
421           {
422             structureFile = new File(subId.content);
423             Console.debug("Using structure file (from argument) '"
424                     + structureFile.getAbsolutePath() + "'");
425           }
426           /* THIS DOESN'T WORK */
427           else if (seq.getAllPDBEntries() != null
428                   && seq.getAllPDBEntries().size() > 0)
429           {
430             structureFile = new File(
431                     seq.getAllPDBEntries().elementAt(0).getFile());
432             Console.debug("Using structure file (from sequence) '"
433                     + structureFile.getAbsolutePath() + "'");
434           }
435
436           if (structureFile == null)
437           {
438             Console.warn("Not provided structure file with '" + val + "'");
439             continue;
440           }
441
442           if (!structureFile.exists())
443           {
444             Console.warn("Structure file '"
445                     + structureFile.getAbsoluteFile() + "' not found.");
446             continue;
447           }
448
449           Console.debug("Using structure file "
450                   + structureFile.getAbsolutePath());
451
452           // open structure view
453           AlignmentPanel ap = af.alignPanel;
454           StructureChooser.openStructureFileForSequence(ap, seq,
455                   structureFile);
456         }
457       }
458     }
459   }
460
461   protected void processImages(String id)
462   {
463     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
464     AlignFrame af = afMap.get(id);
465
466     if (af == null)
467     {
468       Console.warn("Did not have an alignment window for id=" + id);
469       return;
470     }
471
472     if (ArgParser.getValues(m, Arg.IMAGE) != null)
473     {
474       for (String val : ArgParser.getValues(m, Arg.IMAGE))
475       {
476         SubVal subVal = new SubVal(val);
477         String type = "png"; // default
478         String fileName = subVal.content;
479         File file = new File(fileName);
480         if ("type".equals(subVal.keyName))
481         {
482           type = subVal.keyValue;
483         }
484         else if (fileName != null)
485         {
486           for (String ext : new String[] { "svg", "png", "html" })
487           {
488             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
489             {
490               type = ext;
491             }
492           }
493         }
494         // for moment we disable JSON export
495         Cache.setPropsAreReadOnly(true);
496         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
497
498         switch (type)
499         {
500         case "svg":
501           Console.debug("Outputting type '" + type + "' to " + fileName);
502           af.createSVG(file);
503           break;
504         case "png":
505           Console.debug("Outputting type '" + type + "' to " + fileName);
506           af.createPNG(file);
507           break;
508         case "html":
509           Console.debug("Outputting type '" + type + "' to " + fileName);
510           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
511           htmlSVG.exportHTML(fileName);
512           break;
513         default:
514           Console.warn("--image type '" + type + "' not known. Ignoring");
515           break;
516         }
517       }
518     }
519   }
520
521   private SequenceI getSpecifiedSequence(AlignFrame af, SubVal subId)
522   {
523     AlignmentI al = af.getCurrentView().getAlignment();
524     if (-1 < subId.index && subId.index < al.getSequences().size())
525     {
526       return al.getSequenceAt(subId.index);
527     }
528     else if ("id".equals(subId.keyName))
529     {
530       return al.findName(subId.keyValue);
531     }
532     return null;
533   }
534 }