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