JAL-629 Fasta sequence id reading whitespace fix. Flexioble pae json keys and structu...
[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.ArgValues;
18 import jalview.bin.ArgParser.SubVal;
19 import jalview.datamodel.AlignmentAnnotation;
20 import jalview.datamodel.AlignmentI;
21 import jalview.datamodel.SequenceI;
22 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
23 import jalview.gui.AlignFrame;
24 import jalview.gui.AlignmentPanel;
25 import jalview.gui.Desktop;
26 import jalview.gui.StructureChooser;
27 import jalview.io.AppletFormatAdapter;
28 import jalview.io.DataSourceType;
29 import jalview.io.FileFormatException;
30 import jalview.io.FileFormatI;
31 import jalview.io.FileLoader;
32 import jalview.io.HtmlSvgOutput;
33 import jalview.io.IdentifyFile;
34 import jalview.schemes.AnnotationColourGradient;
35 import jalview.structure.StructureImportSettings;
36 import jalview.structure.StructureImportSettings.TFType;
37 import jalview.structure.StructureSelectionManager;
38 import jalview.util.HttpUtils;
39 import jalview.util.MessageManager;
40 import jalview.util.Platform;
41 import jalview.ws.dbsources.EBIAlfaFold;
42 import mc_view.PDBChain;
43
44 public class Commands
45 {
46   Desktop desktop;
47
48   private static boolean headless;
49
50   private static ArgParser argParser;
51
52   private Map<String, AlignFrame> afMap;
53
54   public static boolean processArgs(ArgParser ap, boolean h)
55   {
56     argParser = ap;
57     headless = h;
58     boolean argsWereParsed = false;
59     if (headless)
60     {
61       System.setProperty("java.awt.headless", "true");
62     }
63
64     if (argParser != null && argParser.linkedIds() != null)
65     {
66       for (String id : argParser.linkedIds())
67       {
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           // colour aligment?
262           if (ArgParser.hasValue(m, Arg.COLOUR))
263           {
264             af.changeColour_actionPerformed(
265                     ArgParser.getValue(m, Arg.COLOUR));
266           }
267
268           // change alignment frame title
269           if (ArgParser.getValue(m, Arg.TITLE) != null)
270             af.setTitle(ArgParser.getValue(m, Arg.TITLE));
271
272           /* hacky approach to hiding the annotations */
273           // show secondary structure annotations?
274           if (ArgParser.getBoolean(m, Arg.SSANNOTATION))
275           {
276             // do this better (annotation types?)
277             AlignmentUtils.showOrHideSequenceAnnotations(
278                     af.getCurrentView().getAlignment(),
279                     Collections.singleton("Secondary Structure"), null,
280                     false, false);
281           }
282
283           // show temperature factor annotations?
284           if (ArgParser.getBoolean(m, Arg.NOTEMPFAC))
285           {
286             // do this better (annotation types?)
287             List<String> hideThese = new ArrayList<>();
288             hideThese.add("Temperature Factor");
289             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
290             AlignmentUtils.showOrHideSequenceAnnotations(
291                     af.getCurrentView().getAlignment(), hideThese, null,
292                     false, false);
293           }
294           else
295           /* comment out hacky approach up to here and add this line:
296            if (showTemperatureFactor)
297              */
298           {
299             if (ArgParser.getValue(m, Arg.TEMPFAC_LABEL) != null)
300             {
301               AlignmentAnnotation aa = AlignmentUtils
302                       .getFirstSequenceAnnotationOfType(
303                               af.getCurrentView().getAlignment(),
304                               AlignmentAnnotation.LINE_GRAPH);
305               String label = ArgParser.getValue(m, Arg.TEMPFAC_LABEL);
306               if (aa != null)
307               {
308                 aa.label = label;
309               }
310               else
311               {
312                 Console.info(
313                         "Could not find annotation to apply tempfac_label '"
314                                 + label);
315               }
316             }
317           }
318
319           // store the AlignFrame for this id
320           afMap.put(id, af);
321
322           // is it its own structure file?
323           if (format.isStructureFile())
324           {
325             StructureSelectionManager ssm = StructureSelectionManager
326                     .getStructureSelectionManager(Desktop.instance);
327             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
328             ssm.computeMapping(false, new SequenceI[] { seq }, null,
329                     openFile, DataSourceType.FILE, null);
330           }
331         }
332         else
333         {
334           Console.debug(
335                   "Opening '" + openFile + "' in existing alignment frame");
336           af.getCurrentView().addFile(new File(openFile), format);
337         }
338
339         Console.debug("Command " + Arg.OPEN + " executed successfully!");
340
341       }
342       if (first) // first=true means nothing opened
343       {
344         if (headless)
345         {
346           Console.error("Could not open any files in headless mode");
347           System.exit(1);
348         }
349         else
350         {
351           Console.warn("No more files to open");
352           if (desktop != null)
353             desktop.setProgressBar(null, progress);
354         }
355       }
356
357     }
358
359     // open the structure (from same PDB file or given PDBfile)
360     if (!ArgParser.getBoolean(m, Arg.NOSTRUCTURE))
361     {
362       AlignFrame af = afMap.get(id);
363       if (ArgParser.getArgValues(m, Arg.STRUCTURE) != null)
364       {
365         for (String val : ArgParser.getValues(m, Arg.STRUCTURE))
366         {
367           SubVal subId = new SubVal(val);
368           SequenceI seq = getSpecifiedSequence(af, subId);
369           if (seq == null)
370           {
371             Console.warn("Could not find sequence for argument --"
372                     + Arg.STRUCTURE + "=" + val);
373             // you probably want to continue here, not break
374             // break;
375             continue;
376           }
377           File structureFile = null;
378           if (subId.content != null && subId.content.length() != 0)
379           {
380             structureFile = new File(subId.content);
381             Console.debug("Using structure file (from argument) '"
382                     + structureFile.getAbsolutePath() + "'");
383           }
384           /* THIS DOESN'T WORK */
385           else if (seq.getAllPDBEntries() != null
386                   && seq.getAllPDBEntries().size() > 0)
387           {
388             structureFile = new File(
389                     seq.getAllPDBEntries().elementAt(0).getFile());
390             Console.debug("Using structure file (from sequence) '"
391                     + structureFile.getAbsolutePath() + "'");
392           }
393
394           if (structureFile == null)
395           {
396             Console.warn("Not provided structure file with '" + val + "'");
397             continue;
398           }
399
400           if (!structureFile.exists())
401           {
402             Console.warn("Structure file '"
403                     + structureFile.getAbsoluteFile() + "' not found.");
404             continue;
405           }
406
407           Console.debug("Using structure file "
408                   + structureFile.getAbsolutePath());
409
410           // open structure view
411           AlignmentPanel ap = af.alignPanel;
412           StructureChooser.openStructureFileForSequence(ap, seq,
413                   structureFile);
414         }
415       }
416     }
417
418     // load a pAE file if given
419     if (ArgParser.getValues(m, Arg.PAEMATRIX) != null)
420     {
421       AlignFrame af = afMap.get(id);
422       if (af != null)
423       {
424         for (String val : ArgParser.getValues(m, Arg.PAEMATRIX))
425         {
426           SubVal subVal = ArgParser.getSubVal(val);
427           File paeFile = new File(subVal.content);
428           String paePath = null;
429           try
430           {
431             paePath = paeFile.getCanonicalPath();
432           } catch (IOException e)
433           {
434             paePath = paeFile.getAbsolutePath();
435             Console.warn(
436                     "Problem with the PAE file path: '" + paePath + "'");
437           }
438           String structId = "structid".equals(subVal.keyName)
439                   ? subVal.keyValue
440                   : null;
441           if (subVal.notSet())
442           {
443             // take structid from pdbfilename
444           }
445           if ("structfile".equals(subVal.keyName))
446           {
447             Console.info("***** Attaching paeFile '" + paePath + "' to "
448                     + subVal.keyName + "=" + subVal.keyValue);
449             EBIAlfaFold.addAlphaFoldPAEToStructure(
450                     af.getCurrentView().getAlignment(), paeFile,
451                     subVal.index, subVal.keyValue, false);
452           }
453           else if ("structid".equals(subVal.keyName))
454           {
455             Console.info("***** Attaching paeFile '" + paePath + "' to "
456                     + subVal.keyName + "=" + subVal.keyValue);
457             EBIAlfaFold.addAlphaFoldPAEToStructure(
458                     af.getCurrentView().getAlignment(), paeFile,
459                     subVal.index, subVal.keyValue, true);
460           }
461           else
462           {
463             Console.debug("***** Attaching paeFile '" + paePath
464                     + "' to sequence index " + subVal.index);
465             EBIAlfaFold.addAlphaFoldPAEToSequence(
466                     af.getCurrentView().getAlignment(), paeFile,
467                     subVal.index, null);
468             // required to readjust the height and position of the pAE
469             // annotation
470           }
471           for (AlignmentViewPanel ap : af.getAlignPanels())
472           {
473             ap.adjustAnnotationHeight();
474           }
475         }
476       }
477     }
478
479     boolean doShading = ArgParser.getBoolean(m, Arg.TEMPFAC_SHADING);
480     if (doShading)
481     {
482       AlignFrame af = afMap.get(id);
483       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
484               .findAnnotation(PDBChain.class.getName().toString()))
485       {
486         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
487                 af.alignPanel.av.getGlobalColourScheme(), 0);
488         acg.setSeqAssociated(true);
489         af.changeColour(acg);
490         Console.info("Changed colour " + acg.toString());
491       }
492     }
493   }
494
495   protected void processImages(String id)
496   {
497     Map<Arg, ArgValues> m = argParser.linkedArgs(id);
498     AlignFrame af = afMap.get(id);
499
500     if (af == null)
501     {
502       Console.warn("Did not have an alignment window for id=" + id);
503       return;
504     }
505
506     if (ArgParser.getValues(m, Arg.IMAGE) != null)
507     {
508       for (String val : ArgParser.getValues(m, Arg.IMAGE))
509       {
510         SubVal subVal = new SubVal(val);
511         String type = "png"; // default
512         String fileName = subVal.content;
513         File file = new File(fileName);
514         if ("type".equals(subVal.keyName))
515         {
516           type = subVal.keyValue;
517         }
518         else if (fileName != null)
519         {
520           for (String ext : new String[] { "svg", "png", "html" })
521           {
522             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
523             {
524               type = ext;
525             }
526           }
527         }
528         // for moment we disable JSON export
529         Cache.setPropsAreReadOnly(true);
530         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
531
532         switch (type)
533         {
534         case "svg":
535           Console.debug("Outputting type '" + type + "' to " + fileName);
536           af.createSVG(file);
537           break;
538         case "png":
539           Console.debug("Outputting type '" + type + "' to " + fileName);
540           af.createPNG(file);
541           break;
542         case "html":
543           Console.debug("Outputting type '" + type + "' to " + fileName);
544           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
545           htmlSVG.exportHTML(fileName);
546           break;
547         default:
548           Console.warn("--image type '" + type + "' not known. Ignoring");
549           break;
550         }
551       }
552     }
553   }
554
555   private SequenceI getSpecifiedSequence(AlignFrame af, SubVal subId)
556   {
557     AlignmentI al = af.getCurrentView().getAlignment();
558     if (-1 < subId.index && subId.index < al.getSequences().size())
559     {
560       return al.getSequenceAt(subId.index);
561     }
562     else if ("id".equals(subId.keyName))
563     {
564       return al.findName(subId.keyValue);
565     }
566     return null;
567   }
568 }