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