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