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