d7d1ea34fa42e9ad2d238a32c5650ad9ac2c3d9f
[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.net.URISyntaxException;
6 import java.util.ArrayList;
7 import java.util.Arrays;
8 import java.util.Collections;
9 import java.util.EnumSet;
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Locale;
14 import java.util.Map;
15
16 import jalview.analysis.AlignmentUtils;
17 import jalview.api.structures.JalviewStructureDisplayI;
18 import jalview.bin.argparser.Arg;
19 import jalview.bin.argparser.ArgParser;
20 import jalview.bin.argparser.ArgParser.Position;
21 import jalview.bin.argparser.ArgValue;
22 import jalview.bin.argparser.ArgValuesMap;
23 import jalview.bin.argparser.SubVals;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.SequenceI;
26 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
27 import jalview.gui.AlignFrame;
28 import jalview.gui.AlignmentPanel;
29 import jalview.gui.AppJmol;
30 import jalview.gui.Desktop;
31 import jalview.gui.Preferences;
32 import jalview.gui.StructureChooser;
33 import jalview.gui.StructureViewer;
34 import jalview.gui.StructureViewer.ViewerType;
35 import jalview.io.AppletFormatAdapter;
36 import jalview.io.BackupFiles;
37 import jalview.io.BioJsHTMLOutput;
38 import jalview.io.DataSourceType;
39 import jalview.io.FileFormat;
40 import jalview.io.FileFormatException;
41 import jalview.io.FileFormatI;
42 import jalview.io.FileFormats;
43 import jalview.io.FileLoader;
44 import jalview.io.HtmlSvgOutput;
45 import jalview.io.IdentifyFile;
46 import jalview.io.NewickFile;
47 import jalview.io.exceptions.ImageOutputException;
48 import jalview.schemes.ColourSchemeI;
49 import jalview.schemes.ColourSchemeProperty;
50 import jalview.structure.StructureImportSettings.TFType;
51 import jalview.structure.StructureSelectionManager;
52 import jalview.util.FileUtils;
53 import jalview.util.HttpUtils;
54 import jalview.util.ImageMaker;
55 import jalview.util.ImageMaker.TYPE;
56 import jalview.util.MessageManager;
57 import jalview.util.Platform;
58 import jalview.util.imagemaker.BitmapImageSizing;
59
60 public class Commands
61 {
62   Desktop desktop;
63
64   private boolean headless;
65
66   private ArgParser argParser;
67
68   private Map<String, AlignFrame> afMap;
69
70   private boolean commandArgsProvided = false;
71
72   private boolean argsWereParsed = false;
73
74   public Commands(ArgParser argparser, boolean headless)
75   {
76     this(Desktop.instance, argparser, headless);
77   }
78
79   public Commands(Desktop d, ArgParser argparser, boolean h)
80   {
81     argParser = argparser;
82     headless = h;
83     desktop = d;
84     afMap = new HashMap<>();
85     if (argparser != null)
86     {
87       processArgs(argparser, headless);
88     }
89   }
90
91   private boolean processArgs(ArgParser argparser, boolean h)
92   {
93     argParser = argparser;
94     headless = h;
95     boolean theseArgsWereParsed = false;
96
97     if (argParser != null && argParser.getLinkedIds() != null)
98     {
99       for (String id : argParser.getLinkedIds())
100       {
101         ArgValuesMap avm = argParser.getLinkedArgs(id);
102         theseArgsWereParsed = true;
103         theseArgsWereParsed &= processLinked(id);
104         processGroovyScript(id);
105         boolean processLinkedOkay = theseArgsWereParsed;
106         
107         // wait around until alignFrame isn't busy
108         AlignFrame af=afMap.get(id);
109         while (af!=null && af.getViewport().isCalcInProgress())
110         {
111           try {
112             Thread.sleep(25);
113           } catch (Exception q) {};
114         }
115         
116         theseArgsWereParsed &= processImages(id);
117         if (processLinkedOkay)
118           theseArgsWereParsed &= processOutput(id);
119
120         // close ap
121         if (avm.getBoolean(Arg.CLOSE))
122         {
123           af = afMap.get(id);
124           if (af != null)
125           {
126             af.closeMenuItem_actionPerformed(true);
127           }
128         }
129
130       }
131
132     }
133     if (argParser.getBoolean(Arg.QUIT))
134     {
135       Jalview.getInstance().quit();
136       return true;
137     }
138     // carry on with jalview.bin.Jalview
139     argsWereParsed = theseArgsWereParsed;
140     return argsWereParsed;
141   }
142
143   public boolean commandArgsProvided()
144   {
145     return commandArgsProvided;
146   }
147
148   public boolean argsWereParsed()
149   {
150     return argsWereParsed;
151   }
152
153   protected boolean processUnlinked(String id)
154   {
155     return processLinked(id);
156   }
157
158   protected boolean processLinked(String id)
159   {
160     boolean theseArgsWereParsed = false;
161     ArgValuesMap avm = argParser.getLinkedArgs(id);
162     if (avm == null)
163       return true;
164
165     /*
166      * // script to execute after all loading is completed one way or another String
167      * groovyscript = m.get(Arg.GROOVY) == null ? null :
168      * m.get(Arg.GROOVY).getValue(); String file = m.get(Arg.OPEN) == null ? null :
169      * m.get(Arg.OPEN).getValue(); String data = null; FileFormatI format = null;
170      * DataSourceType protocol = null;
171      */
172     if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
173     {
174       commandArgsProvided = true;
175       long progress = -1;
176
177       boolean first = true;
178       boolean progressBarSet = false;
179       AlignFrame af;
180       // Combine the APPEND and OPEN files into one list, along with whether it
181       // was APPEND or OPEN
182       List<ArgValue> openAvList = new ArrayList<>();
183       openAvList.addAll(avm.getArgValueList(Arg.OPEN));
184       openAvList.addAll(avm.getArgValueList(Arg.APPEND));
185       // sort avlist based on av.getArgIndex()
186       Collections.sort(openAvList);
187       for (ArgValue av : openAvList)
188       {
189         Arg a = av.getArg();
190         SubVals sv = av.getSubVals();
191         String openFile = av.getValue();
192         if (openFile == null)
193           continue;
194
195         theseArgsWereParsed = true;
196         if (first)
197         {
198           first = false;
199           if (!headless && desktop != null)
200           {
201             desktop.setProgressBar(
202                     MessageManager.getString(
203                             "status.processing_commandline_args"),
204                     progress = System.currentTimeMillis());
205             progressBarSet = true;
206           }
207         }
208
209         if (!Platform.isJS())
210         /**
211          * ignore in JavaScript -- can't just file existence - could load it?
212          * 
213          * @j2sIgnore
214          */
215         {
216           if (!HttpUtils.startsWithHttpOrHttps(openFile))
217           {
218             if (!(new File(openFile)).exists())
219             {
220               Console.warn("Can't find file '" + openFile + "'");
221             }
222           }
223         }
224
225         DataSourceType protocol = AppletFormatAdapter
226                 .checkProtocol(openFile);
227
228         FileFormatI format = null;
229         try
230         {
231           format = new IdentifyFile().identify(openFile, protocol);
232         } catch (FileFormatException e1)
233         {
234           Console.error("Unknown file format for '" + openFile + "'");
235         }
236
237         af = afMap.get(id);
238         // When to open a new AlignFrame
239         if (af == null || "true".equals(av.getSubVal("new"))
240                 || a == Arg.OPEN || format == FileFormat.Jalview)
241         {
242           if (a == Arg.OPEN)
243           {
244             Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
245                     openFile);
246           }
247
248           Console.debug(
249                   "Opening '" + openFile + "' in new alignment frame");
250           FileLoader fileLoader = new FileLoader(!headless);
251
252           af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
253                   format);
254
255           // wrap alignment?
256           boolean wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv,
257                   null, "WRAP_ALIGNMENT", false);
258           af.getCurrentView().setWrapAlignment(wrap);
259
260           // colour alignment?
261           String colour = ArgParser.getFromSubValArgOrPref(avm, av,
262                   Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
263           if ("" != colour)
264           {
265             ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
266                     af.getViewport(), af.getViewport().getAlignment(), colour);
267             
268             if (cs==null && !"None".equals(colour))
269             {
270               Console.warn("Couldn't parse '"+colour+"' as a colourscheme.");
271             } else {
272               af.changeColour(cs);
273             }
274             Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
275           }
276
277           // Change alignment frame title
278           String title = ArgParser.getFromSubValArgOrPref(avm, av,
279                   Arg.TITLE, sv, null, null, null);
280           if (title != null)
281           {
282             af.setTitle(title);
283             Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
284           }
285
286           // Add features
287           String featuresfile = ArgParser.getValueFromSubValOrArg(avm, av,
288                   Arg.FEATURES, sv);
289           if (featuresfile != null)
290           {
291             af.parseFeaturesFile(featuresfile,
292                     AppletFormatAdapter.checkProtocol(featuresfile));
293             Jalview.testoutput(argParser, Arg.FEATURES,
294                     "examples/testdata/plantfdx.features", featuresfile);
295           }
296
297           // Add annotations from file
298           String annotationsfile = ArgParser.getValueFromSubValOrArg(avm,
299                   av, Arg.ANNOTATIONS, sv);
300           if (annotationsfile != null)
301           {
302             af.loadJalviewDataFile(annotationsfile, null, null, null);
303             Jalview.testoutput(argParser, Arg.ANNOTATIONS,
304                     "examples/testdata/plantfdx.annotations",
305                     annotationsfile);
306           }
307
308           // Set or clear the sortbytree flag
309           boolean sortbytree = ArgParser.getBoolFromSubValOrArg(avm,
310                   Arg.SORTBYTREE, sv);
311           if (sortbytree)
312           {
313             af.getViewport().setSortByTree(true);
314             Jalview.testoutput(argParser, Arg.SORTBYTREE);
315           }
316
317           // Load tree from file
318           String treefile = ArgParser.getValueFromSubValOrArg(avm, av,
319                   Arg.TREE, sv);
320           if (treefile != null)
321           {
322             try
323             {
324               NewickFile nf = new NewickFile(treefile,
325                       AppletFormatAdapter.checkProtocol(treefile));
326               af.getViewport().setCurrentTree(
327                       af.showNewickTree(nf, treefile).getTree());
328               Jalview.testoutput(argParser, Arg.TREE,
329                       "examples/testdata/uniref50_test_tree", treefile);
330             } catch (IOException e)
331             {
332               Console.warn("Couldn't add tree " + treefile, e);
333             }
334           }
335
336           // Show secondary structure annotations?
337           boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
338                   Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
339                   "STRUCT_FROM_PDB", true);
340           af.setAnnotationsVisibility(showSSAnnotations, true, false);
341
342           // Show sequence annotations?
343           boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
344                   Arg.SHOWANNOTATIONS, av.getSubVals(), null,
345                   "SHOW_ANNOTATIONS", true);
346           af.setAnnotationsVisibility(showAnnotations, false, true);
347
348           // show temperature factor annotations?
349           if (avm.getBoolean(Arg.NOTEMPFAC))
350           {
351             // do this better (annotation types?)
352             List<String> hideThese = new ArrayList<>();
353             hideThese.add("Temperature Factor");
354             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
355             AlignmentUtils.showOrHideSequenceAnnotations(
356                     af.getCurrentView().getAlignment(), hideThese, null,
357                     false, false);
358           }
359
360           // store the AlignFrame for this id
361           afMap.put(id, af);
362
363           // is it its own structure file?
364           if (format.isStructureFile())
365           {
366             StructureSelectionManager ssm = StructureSelectionManager
367                     .getStructureSelectionManager(Desktop.instance);
368             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
369             ssm.computeMapping(false, new SequenceI[] { seq }, null,
370                     openFile, DataSourceType.FILE, null, null, null, false);
371           }
372         }
373         else
374         {
375           Console.debug(
376                   "Opening '" + openFile + "' in existing alignment frame");
377           DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
378                   ? DataSourceType.URL
379                   : DataSourceType.FILE;
380           FileLoader fileLoader = new FileLoader(!headless);
381           fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
382                   false);
383         }
384
385         Console.debug("Command " + Arg.APPEND + " executed successfully!");
386
387       }
388       if (first) // first=true means nothing opened
389       {
390         if (headless)
391         {
392           Jalview.exit("Could not open any files in headless mode", 1);
393         }
394         else
395         {
396           Console.warn("No more files to open");
397         }
398       }
399       if (progressBarSet && desktop != null)
400         desktop.setProgressBar(null, progress);
401
402     }
403
404     // open the structure (from same PDB file or given PDBfile)
405     if (!avm.getBoolean(Arg.NOSTRUCTURE))
406     {
407       AlignFrame af = afMap.get(id);
408       if (avm.containsArg(Arg.STRUCTURE))
409       {
410         commandArgsProvided = true;
411         for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
412         {
413           String val = av.getValue();
414           SubVals subVals = av.getSubVals();
415           SequenceI seq = getSpecifiedSequence(af, avm, av);
416           if (seq == null)
417           {
418             // Could not find sequence from subId, let's assume the first
419             // sequence in the alignframe
420             AlignmentI al = af.getCurrentView().getAlignment();
421             seq = al.getSequenceAt(0);
422           }
423
424           if (seq == null)
425           {
426             Console.warn("Could not find sequence for argument "
427                     + Arg.STRUCTURE.argString() + "=" + val);
428             // you probably want to continue here, not break
429             // break;
430             continue;
431           }
432           File structureFile = null;
433           if (subVals.getContent() != null
434                   && subVals.getContent().length() != 0)
435           {
436             structureFile = new File(subVals.getContent());
437             Console.debug("Using structure file (from argument) '"
438                     + structureFile.getAbsolutePath() + "'");
439           }
440           // TRY THIS
441           /*
442            * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
443            * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
444            * selectedSequence, true, Desktop.instance);
445            * 
446            * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
447            * SequenceI[] { selectedSequence });
448            * 
449            */
450           /* THIS DOESN'T WORK */
451           else if (seq.getAllPDBEntries() != null
452                   && seq.getAllPDBEntries().size() > 0)
453           {
454             structureFile = new File(
455                     seq.getAllPDBEntries().elementAt(0).getFile());
456             Console.debug("Using structure file (from sequence) '"
457                     + structureFile.getAbsolutePath() + "'");
458           }
459
460           if (structureFile == null)
461           {
462             Console.warn("Not provided structure file with '" + val + "'");
463             continue;
464           }
465
466           if (!structureFile.exists())
467           {
468             Console.warn("Structure file '"
469                     + structureFile.getAbsoluteFile() + "' not found.");
470             continue;
471           }
472
473           Console.debug("Using structure file "
474                   + structureFile.getAbsolutePath());
475
476           // open structure view
477           AlignmentPanel ap = af.alignPanel;
478           if (headless)
479           {
480             Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
481                     StructureViewer.ViewerType.JMOL.toString());
482           }
483
484           String structureFilepath = structureFile.getAbsolutePath();
485
486           // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
487           String paeFilepath = ArgParser
488                   .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
489                           Arg.PAEMATRIX, Position.AFTER, av, subVals, null,
490                           null, null);
491           if (paeFilepath != null)
492           {
493             File paeFile = new File(paeFilepath);
494
495             try
496             {
497               paeFilepath = paeFile.getCanonicalPath();
498             } catch (IOException e)
499             {
500               paeFilepath = paeFile.getAbsolutePath();
501               Console.warn("Problem with the PAE file path: '"
502                       + paeFile.getPath() + "'");
503             }
504           }
505
506           // showing annotations from structure file or not
507           boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
508                   Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
509                   true);
510
511           // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
512           // reference annotations
513           String tftString = ArgParser
514                   .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
515                           Arg.TEMPFAC, Position.AFTER, av, subVals, null,
516                           null, null);
517           boolean notempfac = ArgParser.getFromSubValArgOrPref(avm,
518                   Arg.NOTEMPFAC, subVals, null, "ADD_TEMPFACT_ANN", false,
519                   true);
520           TFType tft = notempfac ? null : TFType.DEFAULT;
521           if (tftString != null && !notempfac)
522           {
523             // get kind of temperature factor annotation
524             try
525             {
526               tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
527               Console.debug("Obtained Temperature Factor type of '" + tft
528                       + "' for structure '" + structureFilepath + "'");
529             } catch (IllegalArgumentException e)
530             {
531               // Just an error message!
532               StringBuilder sb = new StringBuilder().append("Cannot set ")
533                       .append(Arg.TEMPFAC.argString()).append(" to '")
534                       .append(tft)
535                       .append("', ignoring.  Valid values are: ");
536               Iterator<TFType> it = Arrays.stream(TFType.values())
537                       .iterator();
538               while (it.hasNext())
539               {
540                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
541                 if (it.hasNext())
542                   sb.append(", ");
543               }
544               Console.warn(sb.toString());
545             }
546           }
547
548           String sViewer = ArgParser.getFromSubValArgOrPref(avm,
549                   Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals, null,
550                   null, "jmol");
551           ViewerType viewerType = null;
552           if (!"none".equals(sViewer))
553           {
554             for (ViewerType v : EnumSet.allOf(ViewerType.class))
555             {
556               String name = v.name().toLowerCase(Locale.ROOT)
557                       .replaceAll(" ", "");
558               if (sViewer.equals(name))
559               {
560                 viewerType = v;
561                 break;
562               }
563             }
564           }
565
566           // TODO use ssFromStructure
567           StructureViewer sv = StructureChooser
568                   .openStructureFileForSequence(null, null, ap, seq, false,
569                           structureFilepath, tft, paeFilepath, false,
570                           ssFromStructure, false, viewerType);
571
572           if (sv==null)
573           {
574             Console.error("Failed to import and open structure view.");
575             continue;
576           }
577           try
578           {
579             long tries=1000;
580             while (sv.isBusy() && tries>0)
581             {
582               Thread.sleep(25);
583               if (sv.isBusy())
584               {
585                 tries--;
586                 Console.debug(
587                         "Waiting for viewer for " + structureFilepath);
588               }
589             }
590             if (tries==0 && sv.isBusy())
591             {
592               Console.warn("Gave up waiting for structure viewer to load. Something may have gone wrong.");
593             }
594           } catch (Exception x)
595           {
596             Console.warn("Exception whilst waiting for structure viewer "+structureFilepath,x);
597           }
598           Console.debug("Successfully opened viewer for "+structureFilepath);
599           String structureImageFilename = ArgParser.getValueFromSubValOrArg(
600                   avm, av, Arg.STRUCTUREIMAGE, subVals);
601           if (sv != null && structureImageFilename != null)
602           {
603             ArgValue siAv = avm.getClosestNextArgValueOfArg(av,
604                     Arg.STRUCTUREIMAGE);
605             SubVals sisv = null;
606             if (structureImageFilename.equals(siAv.getValue()))
607             {
608               sisv = siAv.getSubVals();
609             }
610             File structureImageFile = new File(structureImageFilename);
611             String width = ArgParser.getValueFromSubValOrArg(avm, av,
612                     Arg.STRUCTUREIMAGEWIDTH, sisv);
613             String height = ArgParser.getValueFromSubValOrArg(avm, av,
614                     Arg.STRUCTUREIMAGEHEIGHT, sisv);
615             String scale = ArgParser.getValueFromSubValOrArg(avm, av,
616                     Arg.STRUCTUREIMAGESCALE, sisv);
617             String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
618                     Arg.STRUCTUREIMAGETEXTRENDERER, sisv);
619             String typeS = ArgParser.getValueFromSubValOrArg(avm, av,
620                     Arg.STRUCTUREIMAGETYPE, sisv);
621             if (typeS == null || typeS.length() == 0)
622             {
623               typeS = FileUtils.getExtension(structureImageFile);
624             }
625             TYPE imageType;
626             try
627             {
628               imageType = Enum.valueOf(TYPE.class,
629                       typeS.toUpperCase(Locale.ROOT));
630             } catch (IllegalArgumentException e)
631             {
632               Console.warn("Do not know image format '" + typeS
633                       + "', using PNG");
634               imageType = TYPE.PNG;
635             }
636             BitmapImageSizing userBis = ImageMaker
637                     .parseScaleWidthHeightStrings(scale, width, height);
638             // TODO MAKE THIS VIEWER INDEPENDENT!!
639             switch (StructureViewer.getViewerType())
640             {
641             case JMOL:
642               try
643               {
644                 Thread.sleep(1000); // WHY ???
645               } catch (InterruptedException e)
646               {
647                 // TODO Auto-generated catch block
648                 e.printStackTrace();
649               }
650               JalviewStructureDisplayI sview = sv
651                       .getJalviewStructureDisplay();
652               if (sview instanceof AppJmol)
653               {
654                 AppJmol jmol = (AppJmol) sview;
655                 try { 
656                   Console.debug("Rendering image to "+structureImageFile);
657                   jmol.makePDBImage(structureImageFile, imageType, renderer,
658                         userBis);
659                   Console.debug("Finished Rendering image to "+structureImageFile);
660
661                 }
662                 catch (ImageOutputException ioexc)
663                 {
664                   Console.warn("Unexpected error whilst exporting image to "+structureImageFile,ioexc);
665                 }
666
667               }
668               break;
669             default:
670               Console.warn("Cannot export image for structure viewer "
671                       + sv.getViewerType() + " yet");
672               break;
673             }
674           }
675         }
676       }
677     }
678
679     /*
680     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
681     if (doShading)
682     {
683       AlignFrame af = afMap.get(id);
684       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
685               .findAnnotation(PDBChain.class.getName().toString()))
686       {
687         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
688                 af.alignPanel.av.getGlobalColourScheme(), 0);
689         acg.setSeqAssociated(true);
690         af.changeColour(acg);
691         Console.info("Changed colour " + acg.toString());
692       }
693     }
694     */
695
696     return theseArgsWereParsed;
697   }
698
699   protected void processGroovyScript(String id)
700   {
701     ArgValuesMap avm = argParser.getLinkedArgs(id);
702     AlignFrame af = afMap.get(id);
703
704     if (af == null)
705     {
706       Console.warn("Did not have an alignment window for id=" + id);
707       return;
708     }
709
710     if (avm.containsArg(Arg.GROOVY))
711     {
712       String groovyscript = avm.getValue(Arg.GROOVY);
713       if (groovyscript != null)
714       {
715         // Execute the groovy script after we've done all the rendering stuff
716         // and before any images or figures are generated.
717         Console.info("Executing script " + groovyscript);
718         Jalview.getInstance().executeGroovyScript(groovyscript, af);
719       }
720     }
721   }
722
723   protected boolean processImages(String id)
724   {
725     ArgValuesMap avm = argParser.getLinkedArgs(id);
726     AlignFrame af = afMap.get(id);
727
728     if (af == null)
729     {
730       Console.warn("Did not have an alignment window for id=" + id);
731       return false;
732     }
733
734     if (avm.containsArg(Arg.IMAGE))
735     {
736       for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
737       {
738         String val = av.getValue();
739         SubVals subVal = av.getSubVals();
740         String fileName = subVal.getContent();
741         File file = new File(fileName);
742         String name = af.getName();
743         String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
744                 Arg.TEXTRENDERER, subVal);
745         if (renderer == null)
746           renderer = "text";
747         String type = "png"; // default
748
749         String scale = ArgParser.getValueFromSubValOrArg(avm, av, Arg.SCALE,
750                 subVal);
751         String width = ArgParser.getValueFromSubValOrArg(avm, av, Arg.WIDTH,
752                 subVal);
753         String height = ArgParser.getValueFromSubValOrArg(avm, av,
754                 Arg.HEIGHT, subVal);
755         BitmapImageSizing userBis = ImageMaker
756                 .parseScaleWidthHeightStrings(scale, width, height);
757
758         type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
759         if (type == null && fileName != null)
760         {
761           for (String ext : new String[] { "svg", "png", "html", "eps" })
762           {
763             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
764             {
765               type = ext;
766             }
767           }
768         }
769         // for moment we disable JSON export
770         Cache.setPropsAreReadOnly(true);
771         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
772
773         Console.info("Writing " + file);
774         try {
775         switch (type)
776         {
777
778         case "svg":
779           Console.debug("Outputting type '" + type + "' to " + fileName);
780           af.createSVG(file, renderer);
781           break;
782
783         case "png":
784           Console.debug("Outputting type '" + type + "' to " + fileName);
785           af.createPNG(file, null, userBis);
786           break;
787
788         case "html":
789           Console.debug("Outputting type '" + type + "' to " + fileName);
790           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
791           htmlSVG.exportHTML(fileName, renderer);
792           break;
793
794         case "biojs":
795           Console.debug("Creating BioJS MSA Viwer HTML file: " + fileName);
796           try
797           {
798             BioJsHTMLOutput.refreshVersionInfo(
799                     BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
800           } catch (URISyntaxException e)
801           {
802             e.printStackTrace();
803           }
804           BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
805           bjs.exportHTML(fileName);
806           break;
807
808         case "eps":
809           Console.debug("Creating EPS file: " + fileName);
810           af.createEPS(file, name);
811           break;
812
813         case "imagemap":
814           Console.debug("Creating ImageMap file: " + fileName);
815           af.createImageMap(file, name);
816           break;
817
818         default:
819           Console.warn(Arg.IMAGE.argString() + " type '" + type
820                   + "' not known. Ignoring");
821           break;
822         }
823         } catch (Exception ioex) {
824           Console.warn("Unexpected error during export",ioex);
825         }
826       }
827     }
828     return true;
829   }
830
831   protected boolean processOutput(String id)
832   {
833     ArgValuesMap avm = argParser.getLinkedArgs(id);
834     AlignFrame af = afMap.get(id);
835
836     if (af == null)
837     {
838       Console.warn("Did not have an alignment window for id=" + id);
839       return false;
840     }
841
842     if (avm.containsArg(Arg.OUTPUT))
843     {
844       for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
845       {
846         String val = av.getValue();
847         SubVals subVals = av.getSubVals();
848         String fileName = subVals.getContent();
849         File file = new File(fileName);
850         boolean overwrite = ArgParser.getFromSubValArgOrPref(avm,
851                 Arg.OVERWRITE, subVals, null, "OVERWRITE_OUTPUT", false);
852         // backups. Use the Arg.BACKUPS or subval "backups" setting first,
853         // otherwise if headless assume false, if not headless use the user
854         // preference with default true.
855         boolean backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS,
856                 subVals, null,
857                 Platform.isHeadless() ? null : BackupFiles.ENABLED,
858                 !Platform.isHeadless());
859
860         // if backups is not true then --overwrite must be specified
861         if (file.exists() && !(overwrite || backups))
862         {
863           Console.error("Won't overwrite file '" + fileName + "' without "
864                   + Arg.OVERWRITE.argString() + " or "
865                   + Arg.BACKUPS.argString() + " set");
866           return false;
867         }
868
869         String name = af.getName();
870         String format = ArgParser.getValueFromSubValOrArg(avm, av,
871                 Arg.FORMAT, subVals);
872         FileFormats ffs = FileFormats.getInstance();
873         List<String> validFormats = ffs.getWritableFormats(false);
874
875         FileFormatI ff = null;
876         if (format == null && fileName != null)
877         {
878           FORMAT: for (String fname : validFormats)
879           {
880             FileFormatI tff = ffs.forName(fname);
881             String[] extensions = tff.getExtensions().split(",");
882             for (String ext : extensions)
883             {
884               if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
885               {
886                 ff = tff;
887                 format = ff.getName();
888                 break FORMAT;
889               }
890             }
891           }
892         }
893         if (ff == null && format != null)
894         {
895           ff = ffs.forName(format);
896         }
897         if (ff == null)
898         {
899           StringBuilder validSB = new StringBuilder();
900           for (String f : validFormats)
901           {
902             if (validSB.length() > 0)
903               validSB.append(", ");
904             validSB.append(f);
905             FileFormatI tff = ffs.forName(f);
906             validSB.append(" (");
907             validSB.append(tff.getExtensions());
908             validSB.append(")");
909           }
910
911           Jalview.exit("No valid format specified for "
912                   + Arg.OUTPUT.argString() + ". Valid formats are "
913                   + validSB.toString() + ".", 1);
914           // this return really shouldn't happen
915           return false;
916         }
917
918         String savedBackupsPreference = Cache
919                 .getDefault(BackupFiles.ENABLED, null);
920         Console.debug("Setting backups to " + backups);
921         Cache.applicationProperties.put(BackupFiles.ENABLED,
922                 Boolean.toString(backups));
923
924         Console.info("Writing " + fileName);
925
926         af.saveAlignment(fileName, ff);
927         Console.debug("Returning backups to " + savedBackupsPreference);
928         if (savedBackupsPreference != null)
929           Cache.applicationProperties.put(BackupFiles.ENABLED,
930                   savedBackupsPreference);
931         if (af.isSaveAlignmentSuccessful())
932         {
933           Console.debug("Written alignment '" + name + "' in "
934                   + ff.getName() + " format to " + file);
935         }
936         else
937         {
938           Console.warn("Error writing file " + file + " in " + ff.getName()
939                   + " format!");
940         }
941
942       }
943     }
944     return true;
945   }
946
947   private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
948           ArgValue av)
949   {
950     SubVals subVals = av.getSubVals();
951     ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID);
952     SequenceI seq = null;
953     if (subVals == null && idAv == null)
954       return null;
955     if (af == null || af.getCurrentView() == null)
956     {
957       return null;
958     }
959     AlignmentI al = af.getCurrentView().getAlignment();
960     if (al == null)
961     {
962       return null;
963     }
964     if (subVals != null)
965     {
966       if (subVals.has(Arg.SEQID.getName()))
967       {
968         seq = al.findName(subVals.get(Arg.SEQID.getName()));
969       }
970       else if (-1 < subVals.getIndex()
971               && subVals.getIndex() < al.getSequences().size())
972       {
973         seq = al.getSequenceAt(subVals.getIndex());
974       }
975     }
976     else if (idAv != null)
977     {
978       seq = al.findName(idAv.getValue());
979     }
980     return seq;
981   }
982 }