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