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