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