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