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