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