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