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