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