2794b0259e17d22bda36de272f2e52eb201c91e9
[jalview.git] / src / jalview / bin / Commands.java
1 package jalview.bin;
2
3 import java.awt.Color;
4 import java.io.File;
5 import java.io.IOException;
6 import java.net.URISyntaxException;
7 import java.util.ArrayList;
8 import java.util.Arrays;
9 import java.util.Collections;
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 javax.swing.SwingUtilities;
17
18 import jalview.analysis.AlignmentUtils;
19 import jalview.api.structures.JalviewStructureDisplayI;
20 import jalview.bin.Jalview.ExitCode;
21 import jalview.bin.argparser.Arg;
22 import jalview.bin.argparser.ArgParser;
23 import jalview.bin.argparser.ArgValue;
24 import jalview.bin.argparser.ArgValuesMap;
25 import jalview.bin.argparser.SubVals;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.SequenceI;
28 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.AlignmentPanel;
31 import jalview.gui.AppJmol;
32 import jalview.gui.Desktop;
33 import jalview.gui.Preferences;
34 import jalview.gui.StructureChooser;
35 import jalview.gui.StructureViewer;
36 import jalview.gui.StructureViewer.ViewerType;
37 import jalview.io.AppletFormatAdapter;
38 import jalview.io.BackupFiles;
39 import jalview.io.BioJsHTMLOutput;
40 import jalview.io.DataSourceType;
41 import jalview.io.FileFormat;
42 import jalview.io.FileFormatException;
43 import jalview.io.FileFormatI;
44 import jalview.io.FileFormats;
45 import jalview.io.FileLoader;
46 import jalview.io.HtmlSvgOutput;
47 import jalview.io.IdentifyFile;
48 import jalview.io.NewickFile;
49 import jalview.io.exceptions.ImageOutputException;
50 import jalview.schemes.ColourSchemeI;
51 import jalview.schemes.ColourSchemeProperty;
52 import jalview.structure.StructureCommandI;
53 import jalview.structure.StructureImportSettings.TFType;
54 import jalview.structure.StructureSelectionManager;
55 import jalview.util.ColorUtils;
56 import jalview.util.FileUtils;
57 import jalview.util.HttpUtils;
58 import jalview.util.ImageMaker;
59 import jalview.util.ImageMaker.TYPE;
60 import jalview.util.MessageManager;
61 import jalview.util.Platform;
62 import jalview.util.StringUtils;
63 import jalview.util.imagemaker.BitmapImageSizing;
64
65 public class Commands
66 {
67   Desktop desktop;
68
69   private boolean headless;
70
71   private ArgParser argParser;
72
73   private Map<String, AlignFrame> afMap;
74
75   private Map<String, List<StructureViewer>> svMap;
76
77   private boolean commandArgsProvided = false;
78
79   private boolean argsWereParsed = false;
80
81   private List<String> errors = new ArrayList<>();
82
83   public Commands(ArgParser argparser, boolean headless)
84   {
85     this(Desktop.instance, argparser, headless);
86   }
87
88   public Commands(Desktop d, ArgParser argparser, boolean h)
89   {
90     argParser = argparser;
91     headless = h;
92     desktop = d;
93     afMap = new HashMap<>();
94   }
95
96   protected boolean processArgs()
97   {
98     if (argParser == null)
99     {
100       return true;
101     }
102
103     boolean theseArgsWereParsed = false;
104
105     if (argParser != null && argParser.getLinkedIds() != null)
106     {
107       for (String id : argParser.getLinkedIds())
108       {
109         ArgValuesMap avm = argParser.getLinkedArgs(id);
110         theseArgsWereParsed = true;
111         boolean processLinkedOkay = processLinked(id);
112         theseArgsWereParsed &= processLinkedOkay;
113
114         processGroovyScript(id);
115
116         // wait around until alignFrame isn't busy
117         AlignFrame af = afMap.get(id);
118         while (af != null && af.getViewport().isCalcInProgress())
119         {
120           try
121           {
122             Thread.sleep(25);
123           } catch (Exception q)
124           {
125           }
126           ;
127         }
128
129         theseArgsWereParsed &= processImages(id);
130
131         if (processLinkedOkay)
132         {
133           theseArgsWereParsed &= processOutput(id);
134         }
135
136         // close ap
137         if (avm.getBoolean(Arg.CLOSE))
138         {
139           af = afMap.get(id);
140           if (af != null)
141           {
142             af.closeMenuItem_actionPerformed(true);
143           }
144         }
145
146       }
147
148     }
149
150     // report errors - if any
151     String errorsRaised = errorsToString();
152     if (errorsRaised.trim().length() > 0)
153     {
154       Console.warn(
155               "The following errors and warnings occurred whilst processing files:\n"
156                       + errorsRaised);
157     }
158     // gui errors reported in Jalview
159
160     if (argParser.getBoolean(Arg.QUIT))
161     {
162       Jalview.getInstance().exit(
163               "Exiting due to " + Arg.QUIT.argString() + " argument.",
164               ExitCode.OK);
165       return true;
166     }
167     // carry on with jalview.bin.Jalview
168     argsWereParsed = theseArgsWereParsed;
169     return argsWereParsed;
170   }
171
172   public boolean commandArgsProvided()
173   {
174     return commandArgsProvided;
175   }
176
177   public boolean argsWereParsed()
178   {
179     return argsWereParsed;
180   }
181
182   protected boolean processLinked(String id)
183   {
184     boolean theseArgsWereParsed = false;
185     ArgValuesMap avm = argParser.getLinkedArgs(id);
186     if (avm == null)
187     {
188       return true;
189     }
190
191     Boolean isError = Boolean.valueOf(false);
192
193     // set wrap scope here so it can be applied after structures are opened
194     boolean wrap = false;
195
196     if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
197     {
198       commandArgsProvided = true;
199       final long progress = System.currentTimeMillis();
200
201       boolean first = true;
202       boolean progressBarSet = false;
203       AlignFrame af;
204       // Combine the APPEND and OPEN files into one list, along with whether it
205       // was APPEND or OPEN
206       List<ArgValue> openAvList = new ArrayList<>();
207       openAvList.addAll(avm.getArgValueList(Arg.OPEN));
208       openAvList.addAll(avm.getArgValueList(Arg.APPEND));
209       // sort avlist based on av.getArgIndex()
210       Collections.sort(openAvList);
211       for (ArgValue av : openAvList)
212       {
213         Arg a = av.getArg();
214         SubVals sv = av.getSubVals();
215         String openFile = av.getValue();
216         if (openFile == null)
217           continue;
218
219         theseArgsWereParsed = true;
220         if (first)
221         {
222           first = false;
223           if (!headless && desktop != null)
224           {
225             SwingUtilities.invokeLater(new Runnable()
226             {
227               @Override
228               public void run()
229               {
230                 desktop.setProgressBar(
231                         MessageManager.getString(
232                                 "status.processing_commandline_args"),
233                         progress);
234
235               }
236             });
237             progressBarSet = true;
238           }
239         }
240
241         if (!Platform.isJS())
242         /**
243          * ignore in JavaScript -- can't just file existence - could load it?
244          * 
245          * @j2sIgnore
246          */
247         {
248           if (!HttpUtils.startsWithHttpOrHttps(openFile))
249           {
250             if (!(new File(openFile)).exists())
251             {
252               addError("Can't find file '" + openFile + "'");
253               isError = true;
254               continue;
255             }
256           }
257         }
258
259         DataSourceType protocol = AppletFormatAdapter
260                 .checkProtocol(openFile);
261
262         FileFormatI format = null;
263         try
264         {
265           format = new IdentifyFile().identify(openFile, protocol);
266         } catch (FileFormatException e1)
267         {
268           addError("Unknown file format for '" + openFile + "'");
269           isError = true;
270           continue;
271         }
272
273         af = afMap.get(id);
274         // When to open a new AlignFrame
275         if (af == null || "true".equals(av.getSubVal("new"))
276                 || a == Arg.OPEN || format == FileFormat.Jalview)
277         {
278           if (a == Arg.OPEN)
279           {
280             Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
281                     openFile);
282           }
283
284           Console.debug(
285                   "Opening '" + openFile + "' in new alignment frame");
286           FileLoader fileLoader = new FileLoader(!headless);
287           boolean xception = false;
288           try
289           {
290             af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
291                     format);
292           } catch (Throwable thr)
293           {
294             xception = true;
295             addError("Couldn't open '" + openFile + "' as " + format + " "
296                     + thr.getLocalizedMessage()
297                     + " (Enable debug for full stack trace)");
298             isError = true;
299             Console.debug("Exception when opening '" + openFile + "'", thr);
300           } finally
301           {
302             if (af == null && !xception)
303             {
304               addInfo("Ignoring '" + openFile
305                       + "' - no alignment data found.");
306               continue;
307             }
308           }
309
310           // colour alignment
311           String colour = avm.getFromSubValArgOrPref(av, Arg.COLOUR, sv,
312                   null, "DEFAULT_COLOUR_PROT", "");
313           this.colourAlignFrame(af, colour);
314
315           // Change alignment frame title
316           String title = avm.getFromSubValArgOrPref(av, Arg.TITLE, sv, null,
317                   null, null);
318           if (title != null)
319           {
320             af.setTitle(title);
321             Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
322           }
323
324           // Add features
325           String featuresfile = avm.getValueFromSubValOrArg(av,
326                   Arg.FEATURES, sv);
327           if (featuresfile != null)
328           {
329             af.parseFeaturesFile(featuresfile,
330                     AppletFormatAdapter.checkProtocol(featuresfile));
331             Jalview.testoutput(argParser, Arg.FEATURES,
332                     "examples/testdata/plantfdx.features", featuresfile);
333           }
334
335           // Add annotations from file
336           String annotationsfile = avm.getValueFromSubValOrArg(av,
337                   Arg.ANNOTATIONS, sv);
338           if (annotationsfile != null)
339           {
340             af.loadJalviewDataFile(annotationsfile, null, null, null);
341             Jalview.testoutput(argParser, Arg.ANNOTATIONS,
342                     "examples/testdata/plantfdx.annotations",
343                     annotationsfile);
344           }
345
346           // Set or clear the sortbytree flag
347           boolean sortbytree = avm.getBoolFromSubValOrArg(Arg.SORTBYTREE,
348                   sv);
349           if (sortbytree)
350           {
351             af.getViewport().setSortByTree(true);
352             Jalview.testoutput(argParser, Arg.SORTBYTREE);
353           }
354
355           // Load tree from file
356           String treefile = avm.getValueFromSubValOrArg(av, Arg.TREE, sv);
357           if (treefile != null)
358           {
359             try
360             {
361               NewickFile nf = new NewickFile(treefile,
362                       AppletFormatAdapter.checkProtocol(treefile));
363               af.getViewport().setCurrentTree(
364                       af.showNewickTree(nf, treefile).getTree());
365               Jalview.testoutput(argParser, Arg.TREE,
366                       "examples/testdata/uniref50_test_tree", treefile);
367             } catch (IOException e)
368             {
369               addError("Couldn't add tree " + treefile, e);
370               isError = true;
371             }
372           }
373
374           // Show secondary structure annotations?
375           boolean showSSAnnotations = avm.getFromSubValArgOrPref(
376                   Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
377                   "STRUCT_FROM_PDB", true);
378
379           // Show sequence annotations?
380           boolean showAnnotations = avm.getFromSubValArgOrPref(
381                   Arg.SHOWANNOTATIONS, av.getSubVals(), null,
382                   "SHOW_ANNOTATIONS", true);
383
384           boolean hideTFrows = (avm.getBoolean(Arg.NOTEMPFAC));
385           final AlignFrame _af = af;
386           // many of jalview's format/layout methods are only thread safe on the
387           // swingworker thread.
388           // all these methods should be on the alignViewController so it can
389           // coordinate such details
390           try
391           {
392             SwingUtilities.invokeAndWait(new Runnable()
393             {
394
395               @Override
396               public void run()
397               {
398                 _af.setAnnotationsVisibility(showSSAnnotations, true,
399                         false);
400
401                 _af.setAnnotationsVisibility(showAnnotations, false, true);
402
403                 // show temperature factor annotations?
404                 if (hideTFrows)
405                 {
406                   // do this better (annotation types?)
407                   List<String> hideThese = new ArrayList<>();
408                   hideThese.add("Temperature Factor");
409                   hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
410                   AlignmentUtils.showOrHideSequenceAnnotations(
411                           _af.getCurrentView().getAlignment(), hideThese,
412                           null, false, false);
413                 }
414               }
415             });
416           } catch (Exception x)
417           {
418             Console.warn(
419                     "Unexpected exception adjusting annotation row visibility.",
420                     x);
421           }
422
423           // wrap alignment? do this last for formatting reasons
424           wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
425                   "WRAP_ALIGNMENT", false);
426           // af.setWrapFormat(wrap) is applied after structures are opened for
427           // annotation reasons
428
429           // store the AlignFrame for this id
430           afMap.put(id, af);
431
432           // is it its own structure file?
433           if (format.isStructureFile())
434           {
435             StructureSelectionManager ssm = StructureSelectionManager
436                     .getStructureSelectionManager(Desktop.instance);
437             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
438             ssm.computeMapping(false, new SequenceI[] { seq }, null,
439                     openFile, DataSourceType.FILE, null, null, null, false);
440           }
441         }
442         else
443         {
444           Console.debug(
445                   "Opening '" + openFile + "' in existing alignment frame");
446
447           DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
448                   ? DataSourceType.URL
449                   : DataSourceType.FILE;
450
451           FileLoader fileLoader = new FileLoader(!headless);
452           fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
453                   false);
454         }
455
456         Console.debug("Command " + Arg.APPEND + " executed successfully!");
457
458       }
459       if (first) // first=true means nothing opened
460       {
461         if (headless)
462         {
463           Jalview.exit("Could not open any files in headless mode",
464                   ExitCode.NO_FILES);
465         }
466         else
467         {
468           Console.info("No more files to open");
469         }
470       }
471       if (progressBarSet && desktop != null)
472         desktop.setProgressBar(null, progress);
473
474     }
475
476     // open the structure (from same PDB file or given PDBfile)
477     if (!avm.getBoolean(Arg.NOSTRUCTURE))
478     {
479
480       AlignFrame af = afMap.get(id);
481       if (avm.containsArg(Arg.STRUCTURE))
482       {
483         commandArgsProvided = true;
484         for (
485
486         ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
487         {
488           argParser.setStructureFilename(null);
489           String val = av.getValue();
490           SubVals subVals = av.getSubVals();
491           int argIndex = av.getArgIndex();
492           SequenceI seq = getSpecifiedSequence(af, avm, av);
493           if (seq == null)
494           {
495             // Could not find sequence from subId, let's assume the first
496             // sequence in the alignframe
497             AlignmentI al = af.getCurrentView().getAlignment();
498             seq = al.getSequenceAt(0);
499           }
500
501           if (seq == null)
502           {
503             addWarn("Could not find sequence for argument "
504                     + Arg.STRUCTURE.argString() + "=" + val);
505             continue;
506           }
507           String structureFilename = null;
508           File structureFile = null;
509           if (subVals.getContent() != null
510                   && subVals.getContent().length() != 0)
511           {
512             structureFilename = subVals.getContent();
513             Console.debug("Using structure file (from argument) '"
514                     + structureFilename + "'");
515             structureFile = new File(structureFilename);
516           }
517           /* THIS DOESN'T WORK */
518           else if (seq.getAllPDBEntries() != null
519                   && seq.getAllPDBEntries().size() > 0)
520           {
521             structureFile = new File(
522                     seq.getAllPDBEntries().elementAt(0).getFile());
523             if (structureFile != null)
524             {
525               Console.debug("Using structure file (from sequence) '"
526                       + structureFile.getAbsolutePath() + "'");
527             }
528             structureFilename = structureFile.getAbsolutePath();
529           }
530
531           if (structureFilename == null || structureFile == null)
532           {
533             addWarn("Not provided structure file with '" + val + "'");
534             continue;
535           }
536
537           if (!structureFile.exists())
538           {
539             addWarn("Structure file '" + structureFile.getAbsoluteFile()
540                     + "' not found.");
541             continue;
542           }
543
544           Console.debug("Using structure file "
545                   + structureFile.getAbsolutePath());
546
547           argParser.setStructureFilename(structureFilename);
548
549           // open structure view
550           AlignmentPanel ap = af.alignPanel;
551           if (headless)
552           {
553             Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
554                     StructureViewer.ViewerType.JMOL.toString());
555           }
556
557           String structureFilepath = structureFile.getAbsolutePath();
558
559           // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
560           String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
561                   argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
562                   subVals, null, null, null);
563           if (paeFilepath != null)
564           {
565             File paeFile = new File(paeFilepath);
566
567             try
568             {
569               paeFilepath = paeFile.getCanonicalPath();
570             } catch (IOException e)
571             {
572               paeFilepath = paeFile.getAbsolutePath();
573               addWarn("Problem with the PAE file path: '"
574                       + paeFile.getPath() + "'");
575             }
576           }
577
578           // showing annotations from structure file or not
579           boolean ssFromStructure = avm.getFromSubValArgOrPref(
580                   Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
581                   true);
582
583           // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
584           // reference annotations
585           String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
586                   argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
587                   subVals, null, null, null);
588           boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
589                   subVals, null, "ADD_TEMPFACT_ANN", false, true);
590           TFType tft = notempfac ? null : TFType.DEFAULT;
591           if (tftString != null && !notempfac)
592           {
593             // get kind of temperature factor annotation
594             try
595             {
596               tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
597               Console.debug("Obtained Temperature Factor type of '" + tft
598                       + "' for structure '" + structureFilepath + "'");
599             } catch (IllegalArgumentException e)
600             {
601               // Just an error message!
602               StringBuilder sb = new StringBuilder().append("Cannot set ")
603                       .append(Arg.TEMPFAC.argString()).append(" to '")
604                       .append(tft)
605                       .append("', ignoring.  Valid values are: ");
606               Iterator<TFType> it = Arrays.stream(TFType.values())
607                       .iterator();
608               while (it.hasNext())
609               {
610                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
611                 if (it.hasNext())
612                   sb.append(", ");
613               }
614               addWarn(sb.toString());
615             }
616           }
617
618           String sViewerName = avm.getFromSubValArgOrPref(
619                   Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
620                   subVals, null, null, "jmol");
621           ViewerType viewerType = ViewerType.getFromString(sViewerName);
622
623           // TODO use ssFromStructure
624           StructureViewer structureViewer = StructureChooser
625                   .openStructureFileForSequence(null, null, ap, seq, false,
626                           structureFilepath, tft, paeFilepath, false,
627                           ssFromStructure, false, viewerType);
628
629           if (structureViewer == null)
630           {
631             if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
632             {
633               addError("Failed to import and open structure view for file '"
634                       + structureFile + "'.");
635             }
636             continue;
637           }
638           try
639           {
640             long tries = 1000;
641             while (structureViewer.isBusy() && tries > 0)
642             {
643               Thread.sleep(25);
644               if (structureViewer.isBusy())
645               {
646                 tries--;
647                 Console.debug(
648                         "Waiting for viewer for " + structureFilepath);
649               }
650             }
651             if (tries == 0 && structureViewer.isBusy())
652             {
653               addWarn("Gave up waiting for structure viewer to load file '"
654                       + structureFile
655                       + "'. Something may have gone wrong.");
656             }
657           } catch (Exception x)
658           {
659             addError("Exception whilst waiting for structure viewer "
660                     + structureFilepath, x);
661             isError = true;
662           }
663
664           // add StructureViewer to svMap list
665           if (svMap == null)
666           {
667             svMap = new HashMap<>();
668           }
669           if (svMap.get(id) == null)
670           {
671             svMap.put(id, new ArrayList<>());
672           }
673           svMap.get(id).add(structureViewer);
674
675           Console.debug(
676                   "Successfully opened viewer for " + structureFilepath);
677
678           if (avm.containsArg(Arg.STRUCTUREIMAGE))
679           {
680             for (ArgValue structureImageArgValue : avm
681                     .getArgValueList(Arg.STRUCTUREIMAGE))
682             {
683               String structureImageFilename = argParser.makeSubstitutions(
684                       structureImageArgValue.getValue(), id, true);
685               if (structureViewer != null && structureImageFilename != null)
686               {
687                 SubVals structureImageSubVals = null;
688                 structureImageSubVals = structureImageArgValue.getSubVals();
689                 File structureImageFile = new File(structureImageFilename);
690                 String width = avm.getValueFromSubValOrArg(
691                         structureImageArgValue, Arg.WIDTH,
692                         structureImageSubVals);
693                 String height = avm.getValueFromSubValOrArg(
694                         structureImageArgValue, Arg.HEIGHT,
695                         structureImageSubVals);
696                 String scale = avm.getValueFromSubValOrArg(
697                         structureImageArgValue, Arg.SCALE,
698                         structureImageSubVals);
699                 String renderer = avm.getValueFromSubValOrArg(
700                         structureImageArgValue, Arg.TEXTRENDERER,
701                         structureImageSubVals);
702                 String typeS = avm.getValueFromSubValOrArg(
703                         structureImageArgValue, Arg.TYPE,
704                         structureImageSubVals);
705                 if (typeS == null || typeS.length() == 0)
706                 {
707                   typeS = FileUtils.getExtension(structureImageFile);
708                 }
709                 TYPE imageType;
710                 try
711                 {
712                   imageType = Enum.valueOf(TYPE.class,
713                           typeS.toUpperCase(Locale.ROOT));
714                 } catch (IllegalArgumentException e)
715                 {
716                   addWarn("Do not know image format '" + typeS
717                           + "', using PNG");
718                   imageType = TYPE.PNG;
719                 }
720                 BitmapImageSizing userBis = ImageMaker
721                         .parseScaleWidthHeightStrings(scale, width, height);
722
723                 /////
724                 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
725                 if (viewerType != ViewerType.JMOL)
726                 {
727                   addWarn("Cannot export image for structure viewer "
728                           + viewerType.name() + " yet");
729                   continue;
730                 }
731
732                 /////
733                 // Apply the temporary colourscheme to the linked alignment
734                 // TODO: enhance for multiple linked alignments.
735
736                 String imageColour = avm.getValueFromSubValOrArg(
737                         structureImageArgValue, Arg.IMAGECOLOUR,
738                         structureImageSubVals);
739                 ColourSchemeI originalColourScheme = this
740                         .getColourScheme(af);
741                 this.colourAlignFrame(af, imageColour);
742
743                 /////
744                 // custom image background colour
745
746                 String bgcolourstring = avm.getValueFromSubValOrArg(
747                         structureImageArgValue, Arg.BGCOLOUR,
748                         structureImageSubVals);
749                 Color bgcolour = null;
750                 if (bgcolourstring != null && bgcolourstring.length() > 0)
751                 {
752                   bgcolour = ColorUtils.parseColourString(bgcolourstring);
753                   if (bgcolour == null)
754                   {
755                     Console.warn(
756                             "Background colour string '" + bgcolourstring
757                                     + "' not recognised -- using default");
758                   }
759                 }
760
761                 JalviewStructureDisplayI sview = structureViewer
762                         .getJalviewStructureDisplay();
763
764                 File sessionToRestore = null;
765
766                 List<StructureCommandI> extraCommands = new ArrayList<>();
767
768                 if (extraCommands.size() > 0 || bgcolour != null)
769                 {
770                   try
771                   {
772                     sessionToRestore = sview.saveSession();
773                   } catch (Throwable t)
774                   {
775                     Console.warn(
776                             "Unable to save temporary session file before custom structure view export operation.");
777                   }
778                 }
779
780                 ////
781                 // Do temporary ops
782
783                 if (bgcolour != null)
784                 {
785                   sview.getBinding().setBackgroundColour(bgcolour);
786                 }
787
788                 sview.getBinding().executeCommands(extraCommands, false,
789                         "Executing Custom Commands");
790
791                 // and export the view as an image
792                 boolean success = this.checksBeforeWritingToFile(avm,
793                         subVals, false, structureImageFilename,
794                         "structure image", isError);
795
796                 if (!success)
797                 {
798                   continue;
799                 }
800                 Console.debug("Rendering image to " + structureImageFile);
801                 //
802                 // TODO - extend StructureViewer / Binding with makePDBImage so
803                 // we can do this with every viewer
804                 //
805
806                 try
807                 {
808                   // We don't expect class cast exception
809                   AppJmol jmol = (AppJmol) sview;
810                   jmol.makePDBImage(structureImageFile, imageType, renderer,
811                           userBis);
812                   Console.info("Exported structure image to "
813                           + structureImageFile);
814
815                   // RESTORE SESSION AFTER EXPORT IF NEED BE
816                   if (sessionToRestore != null)
817                   {
818                     Console.debug(
819                             "Restoring session from " + sessionToRestore);
820
821                     sview.getBinding().restoreSession(
822                             sessionToRestore.getAbsolutePath());
823
824                   }
825                 } catch (ImageOutputException ioexec)
826                 {
827                   addError(
828                           "Unexpected error when restoring structure viewer session after custom view operations.");
829                   isError = true;
830                   continue;
831                 } finally
832                 {
833                   try
834                   {
835                     this.colourAlignFrame(af, originalColourScheme);
836                   } catch (Exception t)
837                   {
838                     addError(
839                             "Unexpected error when restoring colourscheme to alignment after temporary change for export.",
840                             t);
841                   }
842                 }
843               }
844             }
845           }
846           argParser.setStructureFilename(null);
847         }
848       }
849     }
850
851     if (wrap)
852     {
853
854       AlignFrame af = afMap.get(id);
855       if (af != null)
856       {
857         af.setWrapFormat(wrap, true);
858       }
859     }
860
861     /*
862     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
863     if (doShading)
864     {
865     AlignFrame af = afMap.get(id);
866     for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
867             .findAnnotation(PDBChain.class.getName().toString()))
868     {
869       AnnotationColourGradient acg = new AnnotationColourGradient(aa,
870               af.alignPanel.av.getGlobalColourScheme(), 0);
871       acg.setSeqAssociated(true);
872       af.changeColour(acg);
873       Console.info("Changed colour " + acg.toString());
874     }
875     }
876     */
877
878     return theseArgsWereParsed && !isError;
879   }
880
881   protected void processGroovyScript(String id)
882   {
883     ArgValuesMap avm = argParser.getLinkedArgs(id);
884     AlignFrame af = afMap.get(id);
885
886     if (avm != null && !avm.containsArg(Arg.GROOVY))
887     {
888       // nothing to do
889       return;
890     }
891
892     if (af == null)
893     {
894       addWarn("Groovy script does not have an alignment window.  Proceeding with caution!");
895     }
896
897     if (avm.containsArg(Arg.GROOVY))
898     {
899       for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
900       {
901         String groovyscript = groovyAv.getValue();
902         if (groovyscript != null)
903         {
904           // Execute the groovy script after we've done all the rendering stuff
905           // and before any images or figures are generated.
906           Console.info("Executing script " + groovyscript);
907           Jalview.getInstance().executeGroovyScript(groovyscript, af);
908         }
909       }
910     }
911   }
912
913   protected boolean processImages(String id)
914   {
915     ArgValuesMap avm = argParser.getLinkedArgs(id);
916     AlignFrame af = afMap.get(id);
917
918     if (avm != null && !avm.containsArg(Arg.IMAGE))
919     {
920       // nothing to do
921       return true;
922     }
923
924     if (af == null)
925     {
926       addWarn("Do not have an alignment window to create image from (id="
927               + id + ").  Not proceeding.");
928       return false;
929     }
930
931     Boolean isError = Boolean.valueOf(false);
932     if (avm.containsArg(Arg.IMAGE))
933     {
934       for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
935       {
936         String val = imageAv.getValue();
937         SubVals imageSubVals = imageAv.getSubVals();
938         String fileName = imageSubVals.getContent();
939         File file = new File(fileName);
940         String name = af.getName();
941         String renderer = avm.getValueFromSubValOrArg(imageAv,
942                 Arg.TEXTRENDERER, imageSubVals);
943         if (renderer == null)
944           renderer = "text";
945         String type = "png"; // default
946
947         String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
948                 imageSubVals);
949         String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
950                 imageSubVals);
951         String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
952                 imageSubVals);
953         BitmapImageSizing userBis = ImageMaker
954                 .parseScaleWidthHeightStrings(scale, width, height);
955
956         type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
957         if (type == null && fileName != null)
958         {
959           for (String ext : new String[] { "svg", "png", "html", "eps" })
960           {
961             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
962             {
963               type = ext;
964             }
965           }
966         }
967         // for moment we disable JSON export
968         Cache.setPropsAreReadOnly(true);
969         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
970
971         String imageColour = avm.getValueFromSubValOrArg(imageAv,
972                 Arg.IMAGECOLOUR, imageSubVals);
973         ColourSchemeI originalColourScheme = this.getColourScheme(af);
974         this.colourAlignFrame(af, imageColour);
975
976         Console.info("Writing " + file);
977
978         boolean success = checksBeforeWritingToFile(avm, imageSubVals,
979                 false, fileName, "image", isError);
980         if (!success)
981         {
982           continue;
983         }
984
985         try
986         {
987           switch (type)
988           {
989
990           case "svg":
991             Console.debug("Outputting type '" + type + "' to " + fileName);
992             af.createSVG(file, renderer);
993             break;
994
995           case "png":
996             Console.debug("Outputting type '" + type + "' to " + fileName);
997             af.createPNG(file, null, userBis);
998             break;
999
1000           case "html":
1001             Console.debug("Outputting type '" + type + "' to " + fileName);
1002             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1003             htmlSVG.exportHTML(fileName, renderer);
1004             break;
1005
1006           case "biojs":
1007             Console.debug(
1008                     "Outputting BioJS MSA Viwer HTML file: " + fileName);
1009             try
1010             {
1011               BioJsHTMLOutput.refreshVersionInfo(
1012                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1013             } catch (URISyntaxException e)
1014             {
1015               e.printStackTrace();
1016             }
1017             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1018             bjs.exportHTML(fileName);
1019             break;
1020
1021           case "eps":
1022             Console.debug("Outputting EPS file: " + fileName);
1023             af.createEPS(file, renderer);
1024             break;
1025
1026           case "imagemap":
1027             Console.debug("Outputting ImageMap file: " + fileName);
1028             af.createImageMap(file, name);
1029             break;
1030
1031           default:
1032             addWarn(Arg.IMAGE.argString() + " type '" + type
1033                     + "' not known. Ignoring");
1034             break;
1035           }
1036         } catch (Exception ioex)
1037         {
1038           addError("Unexpected error during export to '" + fileName + "'",
1039                   ioex);
1040           isError = true;
1041         }
1042
1043         this.colourAlignFrame(af, originalColourScheme);
1044       }
1045     }
1046     return !isError;
1047   }
1048
1049   protected boolean processOutput(String id)
1050   {
1051     ArgValuesMap avm = argParser.getLinkedArgs(id);
1052     AlignFrame af = afMap.get(id);
1053
1054     if (avm != null && !avm.containsArg(Arg.OUTPUT))
1055     {
1056       // nothing to do
1057       return true;
1058     }
1059
1060     if (af == null)
1061     {
1062       addWarn("Do not have an alignment window (id=" + id
1063               + ").  Not proceeding.");
1064       return false;
1065     }
1066
1067     Boolean isError = Boolean.valueOf(false);
1068
1069     if (avm.containsArg(Arg.OUTPUT))
1070     {
1071       for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1072       {
1073         String val = av.getValue();
1074         SubVals subVals = av.getSubVals();
1075         String fileName = subVals.getContent();
1076         boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1077         File file = new File(fileName);
1078
1079         String name = af.getName();
1080         String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1081                 subVals);
1082         FileFormats ffs = FileFormats.getInstance();
1083         List<String> validFormats = ffs.getWritableFormats(false);
1084
1085         FileFormatI ff = null;
1086         if (format == null && fileName != null)
1087         {
1088           FORMAT: for (String fname : validFormats)
1089           {
1090             FileFormatI tff = ffs.forName(fname);
1091             String[] extensions = tff.getExtensions().split(",");
1092             for (String ext : extensions)
1093             {
1094               if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1095               {
1096                 ff = tff;
1097                 format = ff.getName();
1098                 break FORMAT;
1099               }
1100             }
1101           }
1102         }
1103         if (ff == null && format != null)
1104         {
1105           ff = ffs.forName(format);
1106         }
1107         if (ff == null)
1108         {
1109           if (stdout)
1110           {
1111             ff = FileFormat.Fasta;
1112           }
1113           else
1114           {
1115             StringBuilder validSB = new StringBuilder();
1116             for (String f : validFormats)
1117             {
1118               if (validSB.length() > 0)
1119                 validSB.append(", ");
1120               validSB.append(f);
1121               FileFormatI tff = ffs.forName(f);
1122               validSB.append(" (");
1123               validSB.append(tff.getExtensions());
1124               validSB.append(")");
1125             }
1126
1127             addError("No valid format specified for "
1128                     + Arg.OUTPUT.argString() + ". Valid formats are "
1129                     + validSB.toString() + ".");
1130             continue;
1131           }
1132         }
1133
1134         boolean success = checksBeforeWritingToFile(avm, subVals, true,
1135                 fileName, ff.getName(), isError);
1136         if (!success)
1137         {
1138           continue;
1139         }
1140
1141         boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1142                 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1143                 !Platform.isHeadless());
1144
1145         Console.info("Writing " + fileName);
1146
1147         af.saveAlignment(fileName, ff, stdout, backups);
1148         if (af.isSaveAlignmentSuccessful())
1149         {
1150           Console.debug("Written alignment '" + name + "' in "
1151                   + ff.getName() + " format to '" + file + "'");
1152         }
1153         else
1154         {
1155           addError("Error writing file '" + file + "' in " + ff.getName()
1156                   + " format!");
1157           isError = true;
1158           continue;
1159         }
1160
1161       }
1162     }
1163     return !isError;
1164   }
1165
1166   private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1167           ArgValue av)
1168   {
1169     SubVals subVals = av.getSubVals();
1170     ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1171     SequenceI seq = null;
1172     if (subVals == null && idAv == null)
1173       return null;
1174     if (af == null || af.getCurrentView() == null)
1175     {
1176       return null;
1177     }
1178     AlignmentI al = af.getCurrentView().getAlignment();
1179     if (al == null)
1180     {
1181       return null;
1182     }
1183     if (subVals != null)
1184     {
1185       if (subVals.has(Arg.SEQID.getName()))
1186       {
1187         seq = al.findName(subVals.get(Arg.SEQID.getName()));
1188       }
1189       else if (-1 < subVals.getIndex()
1190               && subVals.getIndex() < al.getSequences().size())
1191       {
1192         seq = al.getSequenceAt(subVals.getIndex());
1193       }
1194     }
1195     if (seq == null && idAv != null)
1196     {
1197       seq = al.findName(idAv.getValue());
1198     }
1199     return seq;
1200   }
1201
1202   public AlignFrame[] getAlignFrames()
1203   {
1204     AlignFrame[] afs = null;
1205     if (afMap != null)
1206     {
1207       afs = (AlignFrame[]) afMap.values().toArray();
1208     }
1209
1210     return afs;
1211   }
1212
1213   public List<StructureViewer> getStructureViewers()
1214   {
1215     List<StructureViewer> svs = null;
1216     if (svMap != null)
1217     {
1218       for (List<StructureViewer> svList : svMap.values())
1219       {
1220         if (svs == null)
1221         {
1222           svs = new ArrayList<>();
1223         }
1224         svs.addAll(svList);
1225       }
1226     }
1227     return svs;
1228   }
1229
1230   private void colourAlignFrame(AlignFrame af, String colour)
1231   {
1232     // use string "none" to remove colour scheme
1233     if (colour != null && "" != colour)
1234     {
1235       ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1236               af.getViewport(), af.getViewport().getAlignment(), colour);
1237       if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1238       {
1239         addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1240       }
1241       else
1242       {
1243         Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1244         colourAlignFrame(af, cs);
1245       }
1246     }
1247   }
1248
1249   private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1250   {
1251     // Note that cs == null removes colour scheme from af
1252     af.changeColour(cs);
1253   }
1254
1255   private ColourSchemeI getColourScheme(AlignFrame af)
1256   {
1257     return af.getViewport().getGlobalColourScheme();
1258   }
1259
1260   private void addInfo(String errorMessage)
1261   {
1262     Console.info(errorMessage);
1263     errors.add(errorMessage);
1264   }
1265
1266   private void addWarn(String errorMessage)
1267   {
1268     Console.warn(errorMessage);
1269     errors.add(errorMessage);
1270   }
1271
1272   private void addError(String errorMessage)
1273   {
1274     addError(errorMessage, null);
1275   }
1276
1277   private void addError(String errorMessage, Exception e)
1278   {
1279     Console.error(errorMessage, e);
1280     errors.add(errorMessage);
1281   }
1282
1283   private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1284           SubVals subVal, boolean includeBackups, String filename,
1285           String adjective, Boolean isError)
1286   {
1287     File file = new File(filename);
1288
1289     boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1290             null, "OVERWRITE_OUTPUT", false);
1291     boolean stdout = false;
1292     boolean backups = false;
1293     if (includeBackups)
1294     {
1295       stdout = ArgParser.STDOUTFILENAME.equals(filename);
1296       // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1297       // otherwise if headless assume false, if not headless use the user
1298       // preference with default true.
1299       backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1300               Platform.isHeadless() ? null : BackupFiles.ENABLED,
1301               !Platform.isHeadless());
1302     }
1303
1304     if (file.exists() && !(overwrite || backups || stdout))
1305     {
1306       addWarn("Won't overwrite file '" + filename + "' without "
1307               + Arg.OVERWRITE.argString()
1308               + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1309               + " set");
1310       return false;
1311     }
1312
1313     boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1314             "MKDIRS_OUTPUT", false);
1315
1316     if (!FileUtils.checkParentDir(file, mkdirs))
1317     {
1318       addError("Directory '"
1319               + FileUtils.getParentDir(file).getAbsolutePath()
1320               + "' does not exist for " + adjective + " file '" + filename
1321               + "'."
1322               + (mkdirs ? "" : "  Try using " + Arg.MKDIRS.argString()));
1323       isError = true;
1324       return false;
1325     }
1326
1327     return true;
1328   }
1329
1330   public List<String> getErrors()
1331   {
1332     return errors;
1333   }
1334
1335   public String errorsToString()
1336   {
1337     StringBuilder sb = new StringBuilder();
1338     for (String error : errors)
1339     {
1340       if (sb.length() > 0)
1341         sb.append("\n");
1342       sb.append("- " + error);
1343     }
1344     return sb.toString();
1345   }
1346 }