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