JAL-629 hacked in --tempfac-shading - hardcoded to use existing colours in per-sequen...
[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         // TOREMOVE COMMENT
344         // @Ben assumed this was the GUI version of above, rather then the
345         // first==false state
346         else
347         {
348           Console.warn("No more files to open");
349           if (desktop != null)
350             desktop.setProgressBar(null, progress);
351         }
352       }
353
354     }
355
356     // load a pAE file if given
357     if (ArgParser.getValues(m, Arg.PAEMATRIX) != null)
358     {
359       AlignFrame af = afMap.get(id);
360       if (af != null)
361       {
362         for (String val : ArgParser.getValues(m, Arg.PAEMATRIX))
363         {
364           SubVal subVal = ArgParser.getSubVal(val);
365           File paeFile = new File(subVal.content);
366           String structId = "structid".equals(subVal.keyName)
367                   ? subVal.keyValue
368                   : null;
369           if (subVal.notSet())
370           {
371             // take structid from pdbfilename
372           }
373           if ("structfile".equals(subVal.keyName))
374           {
375             EBIAlfaFold.addAlphaFoldPAEToStructure(
376                     af.getCurrentView().getAlignment(), paeFile,
377                     subVal.index, subVal.keyValue, false);
378           }
379           else if ("structid".equals(subVal.keyName))
380           {
381             EBIAlfaFold.addAlphaFoldPAEToStructure(
382                     af.getCurrentView().getAlignment(), paeFile,
383                     subVal.index, subVal.keyValue, true);
384           }
385           else
386           {
387             EBIAlfaFold.addAlphaFoldPAEToSequence(
388                     af.getCurrentView().getAlignment(), paeFile,
389                     subVal.index,
390                     "seqid".equals(subVal.keyName) ? subVal.keyValue
391                             : null);
392             // required to readjust the height and position of the pAE
393             // annotation
394           }
395           for (AlignmentViewPanel ap : af.getAlignPanels())
396           {
397             ap.adjustAnnotationHeight();
398           }
399         }
400       }
401     }
402
403     // open the structure (from same PDB file or given PDBfile)
404     if (!ArgParser.getBoolean(m, Arg.NOSTRUCTURE))
405     {
406       AlignFrame af = afMap.get(id);
407       if (ArgParser.getArgValues(m, Arg.STRUCTURE) != null)
408       {
409         for (String val : ArgParser.getValues(m, Arg.STRUCTURE))
410         {
411           SubVal subId = new SubVal(val);
412           SequenceI seq = getSpecifiedSequence(af, subId);
413           if (seq == null)
414           {
415             Console.warn("Could not find sequence for argument --"
416                     + Arg.STRUCTURE + "=" + val);
417             // you probably want to continue here, not break
418             // break;
419             continue;
420           }
421           File structureFile = null;
422           if (subId.content != null && subId.content.length() != 0)
423           {
424             structureFile = new File(subId.content);
425             Console.debug("Using structure file (from argument) '"
426                     + structureFile.getAbsolutePath() + "'");
427           }
428           /* THIS DOESN'T WORK */
429           else if (seq.getAllPDBEntries() != null
430                   && seq.getAllPDBEntries().size() > 0)
431           {
432             structureFile = new File(
433                     seq.getAllPDBEntries().elementAt(0).getFile());
434             Console.debug("Using structure file (from sequence) '"
435                     + structureFile.getAbsolutePath() + "'");
436           }
437
438           if (structureFile == null)
439           {
440             Console.warn("Not provided structure file with '" + val + "'");
441             continue;
442           }
443
444           if (!structureFile.exists())
445           {
446             Console.warn("Structure file '"
447                     + structureFile.getAbsoluteFile() + "' not found.");
448             continue;
449           }
450
451           Console.debug("Using structure file "
452                   + structureFile.getAbsolutePath());
453
454           // open structure view
455           AlignmentPanel ap = af.alignPanel;
456           StructureChooser.openStructureFileForSequence(ap, seq,
457                   structureFile);
458         }
459       }
460     }
461     String shading = ArgParser.getValue(m, Arg.TEMPFAC_SHADING);
462     if (shading != null)
463     {
464       Console.debug(
465               "Annotation colour scheme : " + shading + " (ignored value)");
466       AlignFrame af = afMap.get(id);
467       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
468               .findAnnotation(PDBChain.class.getName().toString()))
469       {
470         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
471                 af.alignPanel.av.getGlobalColourScheme(), 0);
472         acg.setSeqAssociated(true);
473         af.changeColour(acg);
474         Console.info("Changed colour " + acg.toString());
475       }
476
477     }
478   }
479
480   protected void processImages(String id)
481   {
482     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
483     AlignFrame af = afMap.get(id);
484
485     if (af == null)
486     {
487       Console.warn("Did not have an alignment window for id=" + id);
488       return;
489     }
490
491     if (ArgParser.getValues(m, Arg.IMAGE) != null)
492     {
493       for (String val : ArgParser.getValues(m, Arg.IMAGE))
494       {
495         SubVal subVal = new SubVal(val);
496         String type = "png"; // default
497         String fileName = subVal.content;
498         File file = new File(fileName);
499         if ("type".equals(subVal.keyName))
500         {
501           type = subVal.keyValue;
502         }
503         else if (fileName != null)
504         {
505           for (String ext : new String[] { "svg", "png", "html" })
506           {
507             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
508             {
509               type = ext;
510             }
511           }
512         }
513         // for moment we disable JSON export
514         Cache.setPropsAreReadOnly(true);
515         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
516
517         switch (type)
518         {
519         case "svg":
520           Console.debug("Outputting type '" + type + "' to " + fileName);
521           af.createSVG(file);
522           break;
523         case "png":
524           Console.debug("Outputting type '" + type + "' to " + fileName);
525           af.createPNG(file);
526           break;
527         case "html":
528           Console.debug("Outputting type '" + type + "' to " + fileName);
529           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
530           htmlSVG.exportHTML(fileName);
531           break;
532         default:
533           Console.warn("--image type '" + type + "' not known. Ignoring");
534           break;
535         }
536       }
537     }
538   }
539
540   private SequenceI getSpecifiedSequence(AlignFrame af, SubVal subId)
541   {
542     AlignmentI al = af.getCurrentView().getAlignment();
543     if (-1 < subId.index && subId.index < al.getSequences().size())
544     {
545       return al.getSequenceAt(subId.index);
546     }
547     else if ("id".equals(subId.keyName))
548     {
549       return al.findName(subId.keyValue);
550     }
551     return null;
552   }
553 }