JAL-4285 don’t say you are reporting warnings/errors when there are none..
[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.lang.reflect.Field;
7 import java.net.URISyntaxException;
8 import java.util.ArrayList;
9 import java.util.Arrays;
10 import java.util.Collections;
11 import java.util.HashMap;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.Locale;
15 import java.util.Map;
16
17 import jalview.analysis.AlignmentUtils;
18 import jalview.api.structures.JalviewStructureDisplayI;
19 import jalview.bin.Jalview.ExitCode;
20 import jalview.bin.argparser.Arg;
21 import jalview.bin.argparser.ArgParser;
22 import jalview.bin.argparser.ArgValue;
23 import jalview.bin.argparser.ArgValuesMap;
24 import jalview.bin.argparser.SubVals;
25 import jalview.datamodel.AlignmentI;
26 import jalview.datamodel.SequenceI;
27 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
28 import jalview.ext.jmol.JalviewJmolBinding;
29 import jalview.ext.jmol.JmolCommands;
30 import jalview.gui.AlignFrame;
31 import jalview.gui.AlignmentPanel;
32 import jalview.gui.AppJmol;
33 import jalview.gui.Desktop;
34 import jalview.gui.Preferences;
35 import jalview.gui.StructureChooser;
36 import jalview.gui.StructureViewer;
37 import jalview.gui.StructureViewer.ViewerType;
38 import jalview.io.AppletFormatAdapter;
39 import jalview.io.BackupFiles;
40 import jalview.io.BioJsHTMLOutput;
41 import jalview.io.DataSourceType;
42 import jalview.io.FileFormat;
43 import jalview.io.FileFormatException;
44 import jalview.io.FileFormatI;
45 import jalview.io.FileFormats;
46 import jalview.io.FileLoader;
47 import jalview.io.HtmlSvgOutput;
48 import jalview.io.IdentifyFile;
49 import jalview.io.NewickFile;
50 import jalview.io.exceptions.ImageOutputException;
51 import jalview.schemes.ColourSchemeI;
52 import jalview.schemes.ColourSchemeProperty;
53 import jalview.structure.StructureCommandI;
54 import jalview.structure.StructureCommandsI;
55 import jalview.structure.StructureImportSettings.TFType;
56 import jalview.structure.StructureSelectionManager;
57 import jalview.util.ColorUtils;
58 import jalview.util.FileUtils;
59 import jalview.util.HttpUtils;
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 = System.currentTimeMillis());
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           af.setAnnotationsVisibility(showSSAnnotations, true, false);
373
374           // Show sequence annotations?
375           boolean showAnnotations = avm.getFromSubValArgOrPref(
376                   Arg.SHOWANNOTATIONS, av.getSubVals(), null,
377                   "SHOW_ANNOTATIONS", true);
378           af.setAnnotationsVisibility(showAnnotations, false, true);
379
380           // show temperature factor annotations?
381           if (avm.getBoolean(Arg.NOTEMPFAC))
382           {
383             // do this better (annotation types?)
384             List<String> hideThese = new ArrayList<>();
385             hideThese.add("Temperature Factor");
386             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
387             AlignmentUtils.showOrHideSequenceAnnotations(
388                     af.getCurrentView().getAlignment(), hideThese, null,
389                     false, false);
390           }
391
392           // wrap alignment? do this last for formatting reasons
393           wrap = avm.getFromSubValArgOrPref(Arg.WRAP, sv, null,
394                   "WRAP_ALIGNMENT", false);
395           // af.setWrapFormat(wrap) is applied after structures are opened for
396           // annotation reasons
397
398           // store the AlignFrame for this id
399           afMap.put(id, af);
400
401           // is it its own structure file?
402           if (format.isStructureFile())
403           {
404             StructureSelectionManager ssm = StructureSelectionManager
405                     .getStructureSelectionManager(Desktop.instance);
406             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
407             ssm.computeMapping(false, new SequenceI[] { seq }, null,
408                     openFile, DataSourceType.FILE, null, null, null, false);
409           }
410         }
411         else
412         {
413           Console.debug(
414                   "Opening '" + openFile + "' in existing alignment frame");
415           DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
416                   ? DataSourceType.URL
417                   : DataSourceType.FILE;
418           FileLoader fileLoader = new FileLoader(!headless);
419           fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
420                   false);
421         }
422
423         Console.debug("Command " + Arg.APPEND + " executed successfully!");
424
425       }
426       if (first) // first=true means nothing opened
427       {
428         if (headless)
429         {
430           Jalview.exit("Could not open any files in headless mode",
431                   ExitCode.NO_FILES);
432         }
433         else
434         {
435           Console.info("No more files to open");
436         }
437       }
438       if (progressBarSet && desktop != null)
439         desktop.setProgressBar(null, progress);
440
441     }
442
443     // open the structure (from same PDB file or given PDBfile)
444     if (!avm.getBoolean(Arg.NOSTRUCTURE))
445     {
446       AlignFrame af = afMap.get(id);
447       if (avm.containsArg(Arg.STRUCTURE))
448       {
449         commandArgsProvided = true;
450         for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
451         {
452           argParser.setStructureFilename(null);
453           String val = av.getValue();
454           SubVals subVals = av.getSubVals();
455           int argIndex = av.getArgIndex();
456           SequenceI seq = getSpecifiedSequence(af, avm, av);
457           if (seq == null)
458           {
459             // Could not find sequence from subId, let's assume the first
460             // sequence in the alignframe
461             AlignmentI al = af.getCurrentView().getAlignment();
462             seq = al.getSequenceAt(0);
463           }
464
465           if (seq == null)
466           {
467             addWarn("Could not find sequence for argument "
468                     + Arg.STRUCTURE.argString() + "=" + val);
469             continue;
470           }
471           String structureFilename = null;
472           File structureFile = null;
473           if (subVals.getContent() != null
474                   && subVals.getContent().length() != 0)
475           {
476             structureFilename = subVals.getContent();
477             Console.debug("Using structure file (from argument) '"
478                     + structureFilename + "'");
479             structureFile = new File(structureFilename);
480           }
481           /* THIS DOESN'T WORK */
482           else if (seq.getAllPDBEntries() != null
483                   && seq.getAllPDBEntries().size() > 0)
484           {
485             structureFile = new File(
486                     seq.getAllPDBEntries().elementAt(0).getFile());
487             if (structureFile != null)
488             {
489               Console.debug("Using structure file (from sequence) '"
490                       + structureFile.getAbsolutePath() + "'");
491             }
492             structureFilename = structureFile.getAbsolutePath();
493           }
494
495           if (structureFilename == null || structureFile == null)
496           {
497             addWarn("Not provided structure file with '" + val + "'");
498             continue;
499           }
500
501           if (!structureFile.exists())
502           {
503             addWarn("Structure file '" + structureFile.getAbsoluteFile()
504                     + "' not found.");
505             continue;
506           }
507
508           Console.debug("Using structure file "
509                   + structureFile.getAbsolutePath());
510
511           argParser.setStructureFilename(structureFilename);
512
513           // open structure view
514           AlignmentPanel ap = af.alignPanel;
515           if (headless)
516           {
517             Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
518                     StructureViewer.ViewerType.JMOL.toString());
519           }
520
521           String structureFilepath = structureFile.getAbsolutePath();
522
523           // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
524           String paeFilepath = avm.getFromSubValArgOrPrefWithSubstitutions(
525                   argParser, Arg.PAEMATRIX, ArgValuesMap.Position.AFTER, av,
526                   subVals, null, null, null);
527           if (paeFilepath != null)
528           {
529             File paeFile = new File(paeFilepath);
530
531             try
532             {
533               paeFilepath = paeFile.getCanonicalPath();
534             } catch (IOException e)
535             {
536               paeFilepath = paeFile.getAbsolutePath();
537               addWarn("Problem with the PAE file path: '"
538                       + paeFile.getPath() + "'");
539             }
540           }
541
542           // showing annotations from structure file or not
543           boolean ssFromStructure = avm.getFromSubValArgOrPref(
544                   Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
545                   true);
546
547           // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
548           // reference annotations
549           String tftString = avm.getFromSubValArgOrPrefWithSubstitutions(
550                   argParser, Arg.TEMPFAC, ArgValuesMap.Position.AFTER, av,
551                   subVals, null, null, null);
552           boolean notempfac = avm.getFromSubValArgOrPref(Arg.NOTEMPFAC,
553                   subVals, null, "ADD_TEMPFACT_ANN", false, true);
554           TFType tft = notempfac ? null : TFType.DEFAULT;
555           if (tftString != null && !notempfac)
556           {
557             // get kind of temperature factor annotation
558             try
559             {
560               tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
561               Console.debug("Obtained Temperature Factor type of '" + tft
562                       + "' for structure '" + structureFilepath + "'");
563             } catch (IllegalArgumentException e)
564             {
565               // Just an error message!
566               StringBuilder sb = new StringBuilder().append("Cannot set ")
567                       .append(Arg.TEMPFAC.argString()).append(" to '")
568                       .append(tft)
569                       .append("', ignoring.  Valid values are: ");
570               Iterator<TFType> it = Arrays.stream(TFType.values())
571                       .iterator();
572               while (it.hasNext())
573               {
574                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
575                 if (it.hasNext())
576                   sb.append(", ");
577               }
578               addWarn(sb.toString());
579             }
580           }
581
582           String sViewerName = avm.getFromSubValArgOrPref(
583                   Arg.STRUCTUREVIEWER, ArgValuesMap.Position.AFTER, av,
584                   subVals, null, null, "jmol");
585           ViewerType viewerType = ViewerType.getFromString(sViewerName);
586
587           // TODO use ssFromStructure
588           StructureViewer structureViewer = StructureChooser
589                   .openStructureFileForSequence(null, null, ap, seq, false,
590                           structureFilepath, tft, paeFilepath, false,
591                           ssFromStructure, false, viewerType);
592
593           if (structureViewer == null)
594           {
595             if (!StringUtils.equalsIgnoreCase(sViewerName, "none"))
596             {
597               addError("Failed to import and open structure view for file '"
598                       + structureFile + "'.");
599             }
600             continue;
601           }
602           try
603           {
604             long tries = 1000;
605             while (structureViewer.isBusy() && tries > 0)
606             {
607               Thread.sleep(25);
608               if (structureViewer.isBusy())
609               {
610                 tries--;
611                 Console.debug(
612                         "Waiting for viewer for " + structureFilepath);
613               }
614             }
615             if (tries == 0 && structureViewer.isBusy())
616             {
617               addWarn("Gave up waiting for structure viewer to load file '"
618                       + structureFile
619                       + "'. Something may have gone wrong.");
620             }
621           } catch (Exception x)
622           {
623             addError("Exception whilst waiting for structure viewer "
624                     + structureFilepath, x);
625             isError = true;
626           }
627
628           // add StructureViewer to svMap list
629           if (svMap == null)
630           {
631             svMap = new HashMap<>();
632           }
633           if (svMap.get(id) == null)
634           {
635             svMap.put(id, new ArrayList<>());
636           }
637           svMap.get(id).add(structureViewer);
638
639           Console.debug(
640                   "Successfully opened viewer for " + structureFilepath);
641
642           if (avm.containsArg(Arg.STRUCTUREIMAGE))
643           {
644             for (ArgValue structureImageArgValue : avm
645                     .getArgValueList(Arg.STRUCTUREIMAGE))
646             {
647               String structureImageFilename = argParser.makeSubstitutions(
648                       structureImageArgValue.getValue(), id, true);
649               if (structureViewer != null && structureImageFilename != null)
650               {
651                 SubVals structureImageSubVals = null;
652                 structureImageSubVals = structureImageArgValue.getSubVals();
653                 File structureImageFile = new File(structureImageFilename);
654                 String width = avm.getValueFromSubValOrArg(
655                         structureImageArgValue, Arg.WIDTH,
656                         structureImageSubVals);
657                 String height = avm.getValueFromSubValOrArg(
658                         structureImageArgValue, Arg.HEIGHT,
659                         structureImageSubVals);
660                 String scale = avm.getValueFromSubValOrArg(
661                         structureImageArgValue, Arg.SCALE,
662                         structureImageSubVals);
663                 String renderer = avm.getValueFromSubValOrArg(
664                         structureImageArgValue, Arg.TEXTRENDERER,
665                         structureImageSubVals);
666                 String typeS = avm.getValueFromSubValOrArg(
667                         structureImageArgValue, Arg.TYPE,
668                         structureImageSubVals);
669                 if (typeS == null || typeS.length() == 0)
670                 {
671                   typeS = FileUtils.getExtension(structureImageFile);
672                 }
673                 TYPE imageType;
674                 try
675                 {
676                   imageType = Enum.valueOf(TYPE.class,
677                           typeS.toUpperCase(Locale.ROOT));
678                 } catch (IllegalArgumentException e)
679                 {
680                   addWarn("Do not know image format '" + typeS
681                           + "', using PNG");
682                   imageType = TYPE.PNG;
683                 }
684                 BitmapImageSizing userBis = ImageMaker
685                         .parseScaleWidthHeightStrings(scale, width, height);
686
687                 /////
688                 // DON'T TRY TO EXPORT IF VIEWER IS UNSUPPORTED
689                 if (viewerType!=ViewerType.JMOL) {
690                   addWarn("Cannot export image for structure viewer "
691                           + viewerType.name() + " yet");
692                   continue;
693                 }
694
695                 /////
696                 // Apply the temporary colourscheme to the linked alignment
697                 // TODO: enhance for multiple linked alignments.
698                 
699                 String imageColour = avm.getValueFromSubValOrArg(
700                         structureImageArgValue, Arg.IMAGECOLOUR,
701                         structureImageSubVals);
702                 ColourSchemeI originalColourScheme = this
703                         .getColourScheme(af);
704                 this.colourAlignFrame(af, imageColour);
705
706                 /////
707                 // custom image background colour
708
709                 String bgcolourstring = avm.getValueFromSubValOrArg(
710                         structureImageArgValue, Arg.BGCOLOUR,
711                         structureImageSubVals);
712                 Color bgcolour = null;
713                 if (bgcolourstring != null && bgcolourstring.length() > 0)
714                 {
715                   try
716                   {
717                     // 
718                     // FIXME: Why not use ColorUtils.parseColourString(bgcolourstring) - this is consistent and backwards compatible
719                     //
720                     if (bgcolourstring.charAt(0) == '#')
721                     {
722                       bgcolour = Color.decode(bgcolourstring);
723                     }
724                     else
725                     {
726                       Field field = Color.class.getField(bgcolourstring);
727                       bgcolour = (Color) field.get(null);
728                     }
729                   } catch (IllegalArgumentException | NoSuchFieldException
730                           | SecurityException | IllegalAccessException nfe)
731                   {
732                     Console.warn(
733                             "Background colour string '" + bgcolourstring
734                                     + "' not recognised -- using default");
735                     //bgcolour = Color.black;
736                   }
737                 }
738
739                 JalviewStructureDisplayI sview = structureViewer
740                         .getJalviewStructureDisplay();
741
742                 File sessionToRestore = null;
743                 
744                 List<StructureCommandI> extraCommands=new ArrayList<>();
745                 
746                 if (extraCommands.size() > 0 || bgcolour!=null)
747                 {
748                   try {
749                     sessionToRestore = sview.saveSession();
750                   } catch (Throwable t)
751                   {
752                     Console.warn("Unable to save temporary session file before custom structure view export operation.");
753                   }
754                 }
755                 
756                 ////
757                 // Do temporary ops 
758
759                 sview.getBinding().setBackgroundColour(bgcolour);
760                 
761                 sview.getBinding().executeCommands(extraCommands, false, "Executing Custom Commands");
762                 
763                 // and export the view as an image
764                 boolean success = this.checksBeforeWritingToFile(avm,
765                         subVals, false, structureImageFilename,
766                         "structure image", isError);
767                 
768                 if (!success)
769                 {
770                   continue;
771                 }
772                 Console.debug(
773                         "Rendering image to " + structureImageFile);
774                 // 
775                 // TODO - extend StructureViewer / Binding with makePDBImage so we can do this with every viewer
776                 // 
777                 
778                 try {
779                   // We don't expect class cast exception
780                   AppJmol jmol = (AppJmol) sview;
781                   jmol.makePDBImage(structureImageFile, imageType,
782                               renderer, userBis);
783                   Console.debug("Finished Rendering image to "
784                           + structureImageFile);
785     
786                   // RESTORE SESSION AFTER EXPORT IF NEED BE
787                   if (sessionToRestore != null)
788                   {
789                     Console.debug("Restoring session from "
790                             + sessionToRestore);
791                     
792                     sview.getBinding().restoreSession(sessionToRestore.getAbsolutePath());
793
794                   }
795                 } catch (ImageOutputException ioexc)
796                 {
797                   addError("Unexpected error whilst exporting image to "
798                           + structureImageFile, ioexc);
799                   isError = true;
800                   continue;
801                 }
802                 finally
803                 {
804                   try {
805                     this.colourAlignFrame(af, originalColourScheme);
806                   } catch (Exception t)
807                   {
808                     addError("Unexpected error when restoring colourscheme to alignment after temporary change for export.",t);
809                   }
810                 }
811               }
812             }
813           }
814           argParser.setStructureFilename(null);
815         }
816       }
817     }
818
819     if (wrap)
820     {
821       AlignFrame af = afMap.get(id);
822       if (af != null)
823       {
824         af.setWrapFormat(wrap, true);
825       }
826     }
827
828     /*
829     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
830     if (doShading)
831     {
832       AlignFrame af = afMap.get(id);
833       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
834               .findAnnotation(PDBChain.class.getName().toString()))
835       {
836         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
837                 af.alignPanel.av.getGlobalColourScheme(), 0);
838         acg.setSeqAssociated(true);
839         af.changeColour(acg);
840         Console.info("Changed colour " + acg.toString());
841       }
842     }
843     */
844
845     return theseArgsWereParsed && !isError;
846   }
847
848   protected void processGroovyScript(String id)
849   {
850     ArgValuesMap avm = argParser.getLinkedArgs(id);
851     AlignFrame af = afMap.get(id);
852
853     if (af == null)
854     {
855       addWarn("Did not have an alignment window for id=" + id);
856       return;
857     }
858
859     if (avm.containsArg(Arg.GROOVY))
860     {
861       String groovyscript = avm.getValue(Arg.GROOVY);
862       if (groovyscript != null)
863       {
864         // Execute the groovy script after we've done all the rendering stuff
865         // and before any images or figures are generated.
866         Console.info("Executing script " + groovyscript);
867         Jalview.getInstance().executeGroovyScript(groovyscript, af);
868       }
869     }
870   }
871
872   protected boolean processImages(String id)
873   {
874     ArgValuesMap avm = argParser.getLinkedArgs(id);
875     AlignFrame af = afMap.get(id);
876
877     if (af == null)
878     {
879       addWarn("Did not have an alignment window for id=" + id);
880       return false;
881     }
882
883     Boolean isError = Boolean.valueOf(false);
884     if (avm.containsArg(Arg.IMAGE))
885     {
886       for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
887       {
888         String val = imageAv.getValue();
889         SubVals imageSubVals = imageAv.getSubVals();
890         String fileName = imageSubVals.getContent();
891         File file = new File(fileName);
892         String name = af.getName();
893         String renderer = avm.getValueFromSubValOrArg(imageAv,
894                 Arg.TEXTRENDERER, imageSubVals);
895         if (renderer == null)
896           renderer = "text";
897         String type = "png"; // default
898
899         String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
900                 imageSubVals);
901         String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
902                 imageSubVals);
903         String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
904                 imageSubVals);
905         BitmapImageSizing userBis = ImageMaker
906                 .parseScaleWidthHeightStrings(scale, width, height);
907
908         type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
909         if (type == null && fileName != null)
910         {
911           for (String ext : new String[] { "svg", "png", "html", "eps" })
912           {
913             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
914             {
915               type = ext;
916             }
917           }
918         }
919         // for moment we disable JSON export
920         Cache.setPropsAreReadOnly(true);
921         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
922
923         String imageColour = avm.getValueFromSubValOrArg(imageAv,
924                 Arg.IMAGECOLOUR, imageSubVals);
925         ColourSchemeI originalColourScheme = this.getColourScheme(af);
926         this.colourAlignFrame(af, imageColour);
927
928         Console.info("Writing " + file);
929
930         boolean success = checksBeforeWritingToFile(avm, imageSubVals,
931                 false, fileName, "image", isError);
932         if (!success)
933         {
934           continue;
935         }
936
937         try
938         {
939           switch (type)
940           {
941
942           case "svg":
943             Console.debug("Outputting type '" + type + "' to " + fileName);
944             af.createSVG(file, renderer);
945             break;
946
947           case "png":
948             Console.debug("Outputting type '" + type + "' to " + fileName);
949             af.createPNG(file, null, userBis);
950             break;
951
952           case "html":
953             Console.debug("Outputting type '" + type + "' to " + fileName);
954             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
955             htmlSVG.exportHTML(fileName, renderer);
956             break;
957
958           case "biojs":
959             Console.debug(
960                     "Outputting BioJS MSA Viwer HTML file: " + fileName);
961             try
962             {
963               BioJsHTMLOutput.refreshVersionInfo(
964                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
965             } catch (URISyntaxException e)
966             {
967               e.printStackTrace();
968             }
969             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
970             bjs.exportHTML(fileName);
971             break;
972
973           case "eps":
974             Console.debug("Outputting EPS file: " + fileName);
975             af.createEPS(file, renderer);
976             break;
977
978           case "imagemap":
979             Console.debug("Outputting ImageMap file: " + fileName);
980             af.createImageMap(file, name);
981             break;
982
983           default:
984             addWarn(Arg.IMAGE.argString() + " type '" + type
985                     + "' not known. Ignoring");
986             break;
987           }
988         } catch (Exception ioex)
989         {
990           addError("Unexpected error during export to '" + fileName + "'",
991                   ioex);
992           isError = true;
993         }
994
995         this.colourAlignFrame(af, originalColourScheme);
996       }
997     }
998     return !isError;
999   }
1000
1001   protected boolean processOutput(String id)
1002   {
1003     ArgValuesMap avm = argParser.getLinkedArgs(id);
1004     AlignFrame af = afMap.get(id);
1005
1006     if (af == null)
1007     {
1008       addWarn("Did not have an alignment window for id=" + id);
1009       return false;
1010     }
1011
1012     Boolean isError = Boolean.valueOf(false);
1013
1014     if (avm.containsArg(Arg.OUTPUT))
1015     {
1016       for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1017       {
1018         String val = av.getValue();
1019         SubVals subVals = av.getSubVals();
1020         String fileName = subVals.getContent();
1021         boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1022         File file = new File(fileName);
1023
1024         String name = af.getName();
1025         String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1026                 subVals);
1027         FileFormats ffs = FileFormats.getInstance();
1028         List<String> validFormats = ffs.getWritableFormats(false);
1029
1030         FileFormatI ff = null;
1031         if (format == null && fileName != null)
1032         {
1033           FORMAT: for (String fname : validFormats)
1034           {
1035             FileFormatI tff = ffs.forName(fname);
1036             String[] extensions = tff.getExtensions().split(",");
1037             for (String ext : extensions)
1038             {
1039               if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1040               {
1041                 ff = tff;
1042                 format = ff.getName();
1043                 break FORMAT;
1044               }
1045             }
1046           }
1047         }
1048         if (ff == null && format != null)
1049         {
1050           ff = ffs.forName(format);
1051         }
1052         if (ff == null)
1053         {
1054           if (stdout)
1055           {
1056             ff = FileFormat.Fasta;
1057           }
1058           else
1059           {
1060             StringBuilder validSB = new StringBuilder();
1061             for (String f : validFormats)
1062             {
1063               if (validSB.length() > 0)
1064                 validSB.append(", ");
1065               validSB.append(f);
1066               FileFormatI tff = ffs.forName(f);
1067               validSB.append(" (");
1068               validSB.append(tff.getExtensions());
1069               validSB.append(")");
1070             }
1071
1072             addError("No valid format specified for "
1073                     + Arg.OUTPUT.argString() + ". Valid formats are "
1074                     + validSB.toString() + ".");
1075             continue;
1076           }
1077         }
1078
1079         boolean success = checksBeforeWritingToFile(avm, subVals, true,
1080                 fileName, ff.getName(), isError);
1081         if (!success)
1082         {
1083           continue;
1084         }
1085
1086         boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1087                 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1088                 !Platform.isHeadless());
1089
1090         Console.info("Writing " + fileName);
1091
1092         af.saveAlignment(fileName, ff, stdout, backups);
1093         if (af.isSaveAlignmentSuccessful())
1094         {
1095           Console.debug("Written alignment '" + name + "' in "
1096                   + ff.getName() + " format to '" + file + "'");
1097         }
1098         else
1099         {
1100           addError("Error writing file '" + file + "' in " + ff.getName()
1101                   + " format!");
1102           isError = true;
1103           continue;
1104         }
1105
1106       }
1107     }
1108     return !isError;
1109   }
1110
1111   private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1112           ArgValue av)
1113   {
1114     SubVals subVals = av.getSubVals();
1115     ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1116     SequenceI seq = null;
1117     if (subVals == null && idAv == null)
1118       return null;
1119     if (af == null || af.getCurrentView() == null)
1120     {
1121       return null;
1122     }
1123     AlignmentI al = af.getCurrentView().getAlignment();
1124     if (al == null)
1125     {
1126       return null;
1127     }
1128     if (subVals != null)
1129     {
1130       if (subVals.has(Arg.SEQID.getName()))
1131       {
1132         seq = al.findName(subVals.get(Arg.SEQID.getName()));
1133       }
1134       else if (-1 < subVals.getIndex()
1135               && subVals.getIndex() < al.getSequences().size())
1136       {
1137         seq = al.getSequenceAt(subVals.getIndex());
1138       }
1139     }
1140     if (seq == null && idAv != null)
1141     {
1142       seq = al.findName(idAv.getValue());
1143     }
1144     return seq;
1145   }
1146
1147   public AlignFrame[] getAlignFrames()
1148   {
1149     AlignFrame[] afs = null;
1150     if (afMap != null)
1151     {
1152       afs = (AlignFrame[]) afMap.values().toArray();
1153     }
1154
1155     return afs;
1156   }
1157
1158   public List<StructureViewer> getStructureViewers()
1159   {
1160     List<StructureViewer> svs = null;
1161     if (svMap != null)
1162     {
1163       for (List<StructureViewer> svList : svMap.values())
1164       {
1165         if (svs == null)
1166         {
1167           svs = new ArrayList<>();
1168         }
1169         svs.addAll(svList);
1170       }
1171     }
1172     return svs;
1173   }
1174
1175   private void colourAlignFrame(AlignFrame af, String colour)
1176   {
1177     // use string "none" to remove colour scheme
1178     if (colour != null && "" != colour)
1179     {
1180       ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1181               af.getViewport(), af.getViewport().getAlignment(), colour);
1182       if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1183       {
1184         addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1185       }
1186       else
1187       {
1188         Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1189         colourAlignFrame(af, cs);
1190       }
1191     }
1192   }
1193
1194   private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1195   {
1196     // Note that cs == null removes colour scheme from af
1197     af.changeColour(cs);
1198   }
1199
1200   private ColourSchemeI getColourScheme(AlignFrame af)
1201   {
1202     return af.getViewport().getGlobalColourScheme();
1203   }
1204
1205   private void addInfo(String errorMessage)
1206   {
1207     Console.info(errorMessage);
1208     errors.add(errorMessage);
1209   }
1210
1211   private void addWarn(String errorMessage)
1212   {
1213     Console.warn(errorMessage);
1214     errors.add(errorMessage);
1215   }
1216
1217   private void addError(String errorMessage)
1218   {
1219     addError(errorMessage, null);
1220   }
1221
1222   private void addError(String errorMessage, Exception e)
1223   {
1224     Console.error(errorMessage, e);
1225     errors.add(errorMessage);
1226   }
1227
1228   private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1229           SubVals subVal, boolean includeBackups, String filename,
1230           String adjective, Boolean isError)
1231   {
1232     File file = new File(filename);
1233
1234     boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1235             null, "OVERWRITE_OUTPUT", false);
1236     boolean stdout = false;
1237     boolean backups = false;
1238     if (includeBackups)
1239     {
1240       stdout = ArgParser.STDOUTFILENAME.equals(filename);
1241       // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1242       // otherwise if headless assume false, if not headless use the user
1243       // preference with default true.
1244       backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1245               Platform.isHeadless() ? null : BackupFiles.ENABLED,
1246               !Platform.isHeadless());
1247     }
1248
1249     if (file.exists() && !(overwrite || backups || stdout))
1250     {
1251       addWarn("Won't overwrite file '" + filename + "' without "
1252               + Arg.OVERWRITE.argString()
1253               + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1254               + " set");
1255       return false;
1256     }
1257
1258     boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1259             "MKDIRS_OUTPUT", false);
1260
1261     if (!FileUtils.checkParentDir(file, mkdirs))
1262     {
1263       addError("Directory '"
1264               + FileUtils.getParentDir(file).getAbsolutePath()
1265               + "' does not exist for " + adjective + " file '" + filename
1266               + "'."
1267               + (mkdirs ? "" : "  Try using " + Arg.MKDIRS.argString()));
1268       isError = true;
1269       return false;
1270     }
1271
1272     return true;
1273   }
1274
1275   public List<String> getErrors()
1276   {
1277     return errors;
1278   }
1279
1280   public String errorsToString()
1281   {
1282     StringBuilder sb = new StringBuilder();
1283     for (String error : errors)
1284     {
1285       if (sb.length() > 0)
1286         sb.append("\n");
1287       sb.append("- " + error);
1288     }
1289     return sb.toString();
1290   }
1291 }