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