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