5f723c112431113512442750158c0c8797ed43f9
[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     af.setAnnotationsVisibility(showSSAnnotations, true, false);
912     af.setAnnotationsVisibility(showAnnotations, false, true);
913
914     // show temperature factor annotations?
915     if (hideTFrows)
916     {
917       // do this better (annotation types?)
918       List<String> hideThese = new ArrayList<>();
919       hideThese.add("Temperature Factor");
920       hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
921       AlignmentUtils.showOrHideSequenceAnnotations(
922               af.getCurrentView().getAlignment(), hideThese, null, false,
923               false);
924     }
925   }
926
927   protected void processGroovyScript(String id)
928   {
929     ArgValuesMap avm = argParser.getLinkedArgs(id);
930     AlignFrame af = afMap.get(id);
931
932     if (avm != null && !avm.containsArg(Arg.GROOVY))
933     {
934       // nothing to do
935       return;
936     }
937
938     if (af == null)
939     {
940       addWarn("Groovy script does not have an alignment window.  Proceeding with caution!");
941     }
942
943     if (avm.containsArg(Arg.GROOVY))
944     {
945       for (ArgValue groovyAv : avm.getArgValueList(Arg.GROOVY))
946       {
947         String groovyscript = groovyAv.getValue();
948         if (groovyscript != null)
949         {
950           // Execute the groovy script after we've done all the rendering stuff
951           // and before any images or figures are generated.
952           Console.info("Executing script " + groovyscript);
953           Jalview.getInstance().executeGroovyScript(groovyscript, af);
954         }
955       }
956     }
957   }
958
959   protected boolean processImages(String id)
960   {
961     ArgValuesMap avm = argParser.getLinkedArgs(id);
962     AlignFrame af = afMap.get(id);
963
964     if (avm != null && !avm.containsArg(Arg.IMAGE))
965     {
966       // nothing to do
967       return true;
968     }
969
970     if (af == null)
971     {
972       addWarn("Do not have an alignment window to create image from (id="
973               + id + ").  Not proceeding.");
974       return false;
975     }
976
977     Boolean isError = Boolean.valueOf(false);
978     if (avm.containsArg(Arg.IMAGE))
979     {
980       for (ArgValue imageAv : avm.getArgValueList(Arg.IMAGE))
981       {
982         String val = imageAv.getValue();
983         SubVals imageSubVals = imageAv.getSubVals();
984         String fileName = imageSubVals.getContent();
985         File file = new File(fileName);
986         String name = af.getName();
987         String renderer = avm.getValueFromSubValOrArg(imageAv,
988                 Arg.TEXTRENDERER, imageSubVals);
989         if (renderer == null)
990           renderer = "text";
991         String type = "png"; // default
992
993         String scale = avm.getValueFromSubValOrArg(imageAv, Arg.SCALE,
994                 imageSubVals);
995         String width = avm.getValueFromSubValOrArg(imageAv, Arg.WIDTH,
996                 imageSubVals);
997         String height = avm.getValueFromSubValOrArg(imageAv, Arg.HEIGHT,
998                 imageSubVals);
999         BitmapImageSizing userBis = ImageMaker
1000                 .parseScaleWidthHeightStrings(scale, width, height);
1001
1002         type = avm.getValueFromSubValOrArg(imageAv, Arg.TYPE, imageSubVals);
1003         if (type == null && fileName != null)
1004         {
1005           for (String ext : new String[] { "svg", "png", "html", "eps" })
1006           {
1007             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1008             {
1009               type = ext;
1010             }
1011           }
1012         }
1013         // for moment we disable JSON export
1014         Cache.setPropsAreReadOnly(true);
1015         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
1016
1017         String imageColour = avm.getValueFromSubValOrArg(imageAv,
1018                 Arg.IMAGECOLOUR, imageSubVals);
1019         ColourSchemeI originalColourScheme = this.getColourScheme(af);
1020         this.colourAlignFrame(af, imageColour);
1021
1022         Console.info("Writing " + file);
1023
1024         boolean success = checksBeforeWritingToFile(avm, imageSubVals,
1025                 false, fileName, "image", isError);
1026         if (!success)
1027         {
1028           continue;
1029         }
1030
1031         try
1032         {
1033           switch (type)
1034           {
1035
1036           case "svg":
1037             Console.debug("Outputting type '" + type + "' to " + fileName);
1038             af.createSVG(file, renderer);
1039             break;
1040
1041           case "png":
1042             Console.debug("Outputting type '" + type + "' to " + fileName);
1043             af.createPNG(file, null, userBis);
1044             break;
1045
1046           case "html":
1047             Console.debug("Outputting type '" + type + "' to " + fileName);
1048             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1049             htmlSVG.exportHTML(fileName, renderer);
1050             break;
1051
1052           case "biojs":
1053             Console.debug(
1054                     "Outputting BioJS MSA Viwer HTML file: " + fileName);
1055             try
1056             {
1057               BioJsHTMLOutput.refreshVersionInfo(
1058                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1059             } catch (URISyntaxException e)
1060             {
1061               e.printStackTrace();
1062             }
1063             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1064             bjs.exportHTML(fileName);
1065             break;
1066
1067           case "eps":
1068             Console.debug("Outputting EPS file: " + fileName);
1069             af.createEPS(file, renderer);
1070             break;
1071
1072           case "imagemap":
1073             Console.debug("Outputting ImageMap file: " + fileName);
1074             af.createImageMap(file, name);
1075             break;
1076
1077           default:
1078             addWarn(Arg.IMAGE.argString() + " type '" + type
1079                     + "' not known. Ignoring");
1080             break;
1081           }
1082         } catch (Exception ioex)
1083         {
1084           addError("Unexpected error during export to '" + fileName + "'",
1085                   ioex);
1086           isError = true;
1087         }
1088
1089         this.colourAlignFrame(af, originalColourScheme);
1090       }
1091     }
1092     return !isError;
1093   }
1094
1095   protected boolean processOutput(String id)
1096   {
1097     ArgValuesMap avm = argParser.getLinkedArgs(id);
1098     AlignFrame af = afMap.get(id);
1099
1100     if (avm != null && !avm.containsArg(Arg.OUTPUT))
1101     {
1102       // nothing to do
1103       return true;
1104     }
1105
1106     if (af == null)
1107     {
1108       addWarn("Do not have an alignment window (id=" + id
1109               + ").  Not proceeding.");
1110       return false;
1111     }
1112
1113     Boolean isError = Boolean.valueOf(false);
1114
1115     if (avm.containsArg(Arg.OUTPUT))
1116     {
1117       for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
1118       {
1119         String val = av.getValue();
1120         SubVals subVals = av.getSubVals();
1121         String fileName = subVals.getContent();
1122         boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
1123         File file = new File(fileName);
1124
1125         String name = af.getName();
1126         String format = avm.getValueFromSubValOrArg(av, Arg.FORMAT,
1127                 subVals);
1128         FileFormats ffs = FileFormats.getInstance();
1129         List<String> validFormats = ffs.getWritableFormats(false);
1130
1131         FileFormatI ff = null;
1132         if (format == null && fileName != null)
1133         {
1134           FORMAT: for (String fname : validFormats)
1135           {
1136             FileFormatI tff = ffs.forName(fname);
1137             String[] extensions = tff.getExtensions().split(",");
1138             for (String ext : extensions)
1139             {
1140               if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
1141               {
1142                 ff = tff;
1143                 format = ff.getName();
1144                 break FORMAT;
1145               }
1146             }
1147           }
1148         }
1149         if (ff == null && format != null)
1150         {
1151           ff = ffs.forName(format);
1152         }
1153         if (ff == null)
1154         {
1155           if (stdout)
1156           {
1157             ff = FileFormat.Fasta;
1158           }
1159           else
1160           {
1161             StringBuilder validSB = new StringBuilder();
1162             for (String f : validFormats)
1163             {
1164               if (validSB.length() > 0)
1165                 validSB.append(", ");
1166               validSB.append(f);
1167               FileFormatI tff = ffs.forName(f);
1168               validSB.append(" (");
1169               validSB.append(tff.getExtensions());
1170               validSB.append(")");
1171             }
1172
1173             addError("No valid format specified for "
1174                     + Arg.OUTPUT.argString() + ". Valid formats are "
1175                     + validSB.toString() + ".");
1176             continue;
1177           }
1178         }
1179
1180         boolean success = checksBeforeWritingToFile(avm, subVals, true,
1181                 fileName, ff.getName(), isError);
1182         if (!success)
1183         {
1184           continue;
1185         }
1186
1187         boolean backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVals,
1188                 null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1189                 !Platform.isHeadless());
1190
1191         Console.info("Writing " + fileName);
1192
1193         af.saveAlignment(fileName, ff, stdout, backups);
1194         if (af.isSaveAlignmentSuccessful())
1195         {
1196           Console.debug("Written alignment '" + name + "' in "
1197                   + ff.getName() + " format to '" + file + "'");
1198         }
1199         else
1200         {
1201           addError("Error writing file '" + file + "' in " + ff.getName()
1202                   + " format!");
1203           isError = true;
1204           continue;
1205         }
1206
1207       }
1208     }
1209     return !isError;
1210   }
1211
1212   private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1213           ArgValue av)
1214   {
1215     SubVals subVals = av.getSubVals();
1216     ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID, true);
1217     SequenceI seq = null;
1218     if (subVals == null && idAv == null)
1219       return null;
1220     if (af == null || af.getCurrentView() == null)
1221     {
1222       return null;
1223     }
1224     AlignmentI al = af.getCurrentView().getAlignment();
1225     if (al == null)
1226     {
1227       return null;
1228     }
1229     if (subVals != null)
1230     {
1231       if (subVals.has(Arg.SEQID.getName()))
1232       {
1233         seq = al.findName(subVals.get(Arg.SEQID.getName()));
1234       }
1235       else if (-1 < subVals.getIndex()
1236               && subVals.getIndex() < al.getSequences().size())
1237       {
1238         seq = al.getSequenceAt(subVals.getIndex());
1239       }
1240     }
1241     if (seq == null && idAv != null)
1242     {
1243       seq = al.findName(idAv.getValue());
1244     }
1245     return seq;
1246   }
1247
1248   public AlignFrame[] getAlignFrames()
1249   {
1250     AlignFrame[] afs = null;
1251     if (afMap != null)
1252     {
1253       afs = (AlignFrame[]) afMap.values().toArray();
1254     }
1255
1256     return afs;
1257   }
1258
1259   public List<StructureViewer> getStructureViewers()
1260   {
1261     List<StructureViewer> svs = null;
1262     if (svMap != null)
1263     {
1264       for (List<StructureViewer> svList : svMap.values())
1265       {
1266         if (svs == null)
1267         {
1268           svs = new ArrayList<>();
1269         }
1270         svs.addAll(svList);
1271       }
1272     }
1273     return svs;
1274   }
1275
1276   private void colourAlignFrame(AlignFrame af, String colour)
1277   {
1278     // use string "none" to remove colour scheme
1279     if (colour != null && "" != colour)
1280     {
1281       ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
1282               af.getViewport(), af.getViewport().getAlignment(), colour);
1283       if (cs == null && !StringUtils.equalsIgnoreCase(colour, "none"))
1284       {
1285         addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
1286       }
1287       else
1288       {
1289         Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
1290         colourAlignFrame(af, cs);
1291       }
1292     }
1293   }
1294
1295   private void colourAlignFrame(AlignFrame af, ColourSchemeI cs)
1296   {
1297     // Note that cs == null removes colour scheme from af
1298     af.changeColour(cs);
1299   }
1300
1301   private ColourSchemeI getColourScheme(AlignFrame af)
1302   {
1303     return af.getViewport().getGlobalColourScheme();
1304   }
1305
1306   private void addInfo(String errorMessage)
1307   {
1308     Console.info(errorMessage);
1309     errors.add(errorMessage);
1310   }
1311
1312   private void addWarn(String errorMessage)
1313   {
1314     Console.warn(errorMessage);
1315     errors.add(errorMessage);
1316   }
1317
1318   private void addError(String errorMessage)
1319   {
1320     addError(errorMessage, null);
1321   }
1322
1323   private void addError(String errorMessage, Exception e)
1324   {
1325     Console.error(errorMessage, e);
1326     errors.add(errorMessage);
1327   }
1328
1329   private boolean checksBeforeWritingToFile(ArgValuesMap avm,
1330           SubVals subVal, boolean includeBackups, String filename,
1331           String adjective, Boolean isError)
1332   {
1333     File file = new File(filename);
1334
1335     boolean overwrite = avm.getFromSubValArgOrPref(Arg.OVERWRITE, subVal,
1336             null, "OVERWRITE_OUTPUT", false);
1337     boolean stdout = false;
1338     boolean backups = false;
1339     if (includeBackups)
1340     {
1341       stdout = ArgParser.STDOUTFILENAME.equals(filename);
1342       // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1343       // otherwise if headless assume false, if not headless use the user
1344       // preference with default true.
1345       backups = avm.getFromSubValArgOrPref(Arg.BACKUPS, subVal, null,
1346               Platform.isHeadless() ? null : BackupFiles.ENABLED,
1347               !Platform.isHeadless());
1348     }
1349
1350     if (file.exists() && !(overwrite || backups || stdout))
1351     {
1352       addWarn("Won't overwrite file '" + filename + "' without "
1353               + Arg.OVERWRITE.argString()
1354               + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1355               + " set");
1356       return false;
1357     }
1358
1359     boolean mkdirs = avm.getFromSubValArgOrPref(Arg.MKDIRS, subVal, null,
1360             "MKDIRS_OUTPUT", false);
1361
1362     if (!FileUtils.checkParentDir(file, mkdirs))
1363     {
1364       addError("Directory '"
1365               + FileUtils.getParentDir(file).getAbsolutePath()
1366               + "' does not exist for " + adjective + " file '" + filename
1367               + "'."
1368               + (mkdirs ? "" : "  Try using " + Arg.MKDIRS.argString()));
1369       isError = true;
1370       return false;
1371     }
1372
1373     return true;
1374   }
1375
1376   public List<String> getErrors()
1377   {
1378     return errors;
1379   }
1380
1381   public String errorsToString()
1382   {
1383     StringBuilder sb = new StringBuilder();
1384     for (String error : errors)
1385     {
1386       if (sb.length() > 0)
1387         sb.append("\n");
1388       sb.append("- " + error);
1389     }
1390     return sb.toString();
1391   }
1392 }