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