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