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