JAL-4195 catch thrown exceptions (if any) during image export and report as an error.
[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 (headless)
573           {
574             sv.setAsync(false);
575           }
576
577           String structureImageFilename = ArgParser.getValueFromSubValOrArg(
578                   avm, av, Arg.STRUCTUREIMAGE, subVals);
579           if (sv != null && structureImageFilename != null)
580           {
581             ArgValue siAv = avm.getClosestNextArgValueOfArg(av,
582                     Arg.STRUCTUREIMAGE);
583             SubVals sisv = null;
584             if (structureImageFilename.equals(siAv.getValue()))
585             {
586               sisv = siAv.getSubVals();
587             }
588             File structureImageFile = new File(structureImageFilename);
589             String width = ArgParser.getValueFromSubValOrArg(avm, av,
590                     Arg.STRUCTUREIMAGEWIDTH, sisv);
591             String height = ArgParser.getValueFromSubValOrArg(avm, av,
592                     Arg.STRUCTUREIMAGEHEIGHT, sisv);
593             String scale = ArgParser.getValueFromSubValOrArg(avm, av,
594                     Arg.STRUCTUREIMAGESCALE, sisv);
595             String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
596                     Arg.STRUCTUREIMAGETEXTRENDERER, sisv);
597             String typeS = ArgParser.getValueFromSubValOrArg(avm, av,
598                     Arg.STRUCTUREIMAGETYPE, sisv);
599             if (typeS == null || typeS.length() == 0)
600             {
601               typeS = FileUtils.getExtension(structureImageFile);
602             }
603             TYPE imageType;
604             try
605             {
606               imageType = Enum.valueOf(TYPE.class,
607                       typeS.toUpperCase(Locale.ROOT));
608             } catch (IllegalArgumentException e)
609             {
610               Console.warn("Do not know image format '" + typeS
611                       + "', using PNG");
612               imageType = TYPE.PNG;
613             }
614             BitmapImageSizing userBis = ImageMaker
615                     .parseScaleWidthHeightStrings(scale, width, height);
616             switch (StructureViewer.getViewerType())
617             {
618             case JMOL:
619               try
620               {
621                 Thread.sleep(1000);
622               } catch (InterruptedException e)
623               {
624                 // TODO Auto-generated catch block
625                 e.printStackTrace();
626               }
627               JalviewStructureDisplayI sview = sv
628                       .getJalviewStructureDisplay();
629               if (sview instanceof AppJmol)
630               {
631                 AppJmol jmol = (AppJmol) sview;
632                 jmol.makePDBImage(structureImageFile, imageType, renderer,
633                         userBis);
634               }
635               break;
636             default:
637               Console.warn("Cannot export image for structure viewer "
638                       + sv.getViewerType() + " yet");
639               break;
640             }
641           }
642         }
643       }
644     }
645
646     /*
647     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
648     if (doShading)
649     {
650       AlignFrame af = afMap.get(id);
651       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
652               .findAnnotation(PDBChain.class.getName().toString()))
653       {
654         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
655                 af.alignPanel.av.getGlobalColourScheme(), 0);
656         acg.setSeqAssociated(true);
657         af.changeColour(acg);
658         Console.info("Changed colour " + acg.toString());
659       }
660     }
661     */
662
663     return theseArgsWereParsed;
664   }
665
666   protected void processGroovyScript(String id)
667   {
668     ArgValuesMap avm = argParser.getLinkedArgs(id);
669     AlignFrame af = afMap.get(id);
670
671     if (af == null)
672     {
673       Console.warn("Did not have an alignment window for id=" + id);
674       return;
675     }
676
677     if (avm.containsArg(Arg.GROOVY))
678     {
679       String groovyscript = avm.getValue(Arg.GROOVY);
680       if (groovyscript != null)
681       {
682         // Execute the groovy script after we've done all the rendering stuff
683         // and before any images or figures are generated.
684         Console.info("Executing script " + groovyscript);
685         Jalview.getInstance().executeGroovyScript(groovyscript, af);
686       }
687     }
688   }
689
690   protected boolean processImages(String id)
691   {
692     ArgValuesMap avm = argParser.getLinkedArgs(id);
693     AlignFrame af = afMap.get(id);
694
695     if (af == null)
696     {
697       Console.warn("Did not have an alignment window for id=" + id);
698       return false;
699     }
700
701     if (avm.containsArg(Arg.IMAGE))
702     {
703       for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
704       {
705         String val = av.getValue();
706         SubVals subVal = av.getSubVals();
707         String fileName = subVal.getContent();
708         File file = new File(fileName);
709         String name = af.getName();
710         String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
711                 Arg.TEXTRENDERER, subVal);
712         if (renderer == null)
713           renderer = "text";
714         String type = "png"; // default
715
716         String scale = ArgParser.getValueFromSubValOrArg(avm, av, Arg.SCALE,
717                 subVal);
718         String width = ArgParser.getValueFromSubValOrArg(avm, av, Arg.WIDTH,
719                 subVal);
720         String height = ArgParser.getValueFromSubValOrArg(avm, av,
721                 Arg.HEIGHT, subVal);
722         BitmapImageSizing userBis = ImageMaker
723                 .parseScaleWidthHeightStrings(scale, width, height);
724
725         type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
726         if (type == null && fileName != null)
727         {
728           for (String ext : new String[] { "svg", "png", "html", "eps" })
729           {
730             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
731             {
732               type = ext;
733             }
734           }
735         }
736         // for moment we disable JSON export
737         Cache.setPropsAreReadOnly(true);
738         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
739
740         Console.info("Writing " + file);
741         try {
742         switch (type)
743         {
744
745         case "svg":
746           Console.debug("Outputting type '" + type + "' to " + fileName);
747           af.createSVG(file, renderer);
748           break;
749
750         case "png":
751           Console.debug("Outputting type '" + type + "' to " + fileName);
752           af.createPNG(file, null, userBis);
753           break;
754
755         case "html":
756           Console.debug("Outputting type '" + type + "' to " + fileName);
757           HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
758           htmlSVG.exportHTML(fileName, renderer);
759           break;
760
761         case "biojs":
762           Console.debug("Creating BioJS MSA Viwer HTML file: " + fileName);
763           try
764           {
765             BioJsHTMLOutput.refreshVersionInfo(
766                     BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
767           } catch (URISyntaxException e)
768           {
769             e.printStackTrace();
770           }
771           BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
772           bjs.exportHTML(fileName);
773           break;
774
775         case "eps":
776           Console.debug("Creating EPS file: " + fileName);
777           af.createEPS(file, name);
778           break;
779
780         case "imagemap":
781           Console.debug("Creating ImageMap file: " + fileName);
782           af.createImageMap(file, name);
783           break;
784
785         default:
786           Console.warn(Arg.IMAGE.argString() + " type '" + type
787                   + "' not known. Ignoring");
788           break;
789         }
790         } catch (Exception ioex) {
791           Console.warn("Unexpected error during export",ioex);
792         }
793       }
794     }
795     return true;
796   }
797
798   protected boolean processOutput(String id)
799   {
800     ArgValuesMap avm = argParser.getLinkedArgs(id);
801     AlignFrame af = afMap.get(id);
802
803     if (af == null)
804     {
805       Console.warn("Did not have an alignment window for id=" + id);
806       return false;
807     }
808
809     if (avm.containsArg(Arg.OUTPUT))
810     {
811       for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
812       {
813         String val = av.getValue();
814         SubVals subVals = av.getSubVals();
815         String fileName = subVals.getContent();
816         File file = new File(fileName);
817         boolean overwrite = ArgParser.getFromSubValArgOrPref(avm,
818                 Arg.OVERWRITE, subVals, null, "OVERWRITE_OUTPUT", false);
819         // backups. Use the Arg.BACKUPS or subval "backups" setting first,
820         // otherwise if headless assume false, if not headless use the user
821         // preference with default true.
822         boolean backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS,
823                 subVals, null,
824                 Platform.isHeadless() ? null : BackupFiles.ENABLED,
825                 !Platform.isHeadless());
826
827         // if backups is not true then --overwrite must be specified
828         if (file.exists() && !(overwrite || backups))
829         {
830           Console.error("Won't overwrite file '" + fileName + "' without "
831                   + Arg.OVERWRITE.argString() + " or "
832                   + Arg.BACKUPS.argString() + " set");
833           return false;
834         }
835
836         String name = af.getName();
837         String format = ArgParser.getValueFromSubValOrArg(avm, av,
838                 Arg.FORMAT, subVals);
839         FileFormats ffs = FileFormats.getInstance();
840         List<String> validFormats = ffs.getWritableFormats(false);
841
842         FileFormatI ff = null;
843         if (format == null && fileName != null)
844         {
845           FORMAT: for (String fname : validFormats)
846           {
847             FileFormatI tff = ffs.forName(fname);
848             String[] extensions = tff.getExtensions().split(",");
849             for (String ext : extensions)
850             {
851               if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
852               {
853                 ff = tff;
854                 format = ff.getName();
855                 break FORMAT;
856               }
857             }
858           }
859         }
860         if (ff == null && format != null)
861         {
862           ff = ffs.forName(format);
863         }
864         if (ff == null)
865         {
866           StringBuilder validSB = new StringBuilder();
867           for (String f : validFormats)
868           {
869             if (validSB.length() > 0)
870               validSB.append(", ");
871             validSB.append(f);
872             FileFormatI tff = ffs.forName(f);
873             validSB.append(" (");
874             validSB.append(tff.getExtensions());
875             validSB.append(")");
876           }
877
878           Jalview.exit("No valid format specified for "
879                   + Arg.OUTPUT.argString() + ". Valid formats are "
880                   + validSB.toString() + ".", 1);
881           // this return really shouldn't happen
882           return false;
883         }
884
885         String savedBackupsPreference = Cache
886                 .getDefault(BackupFiles.ENABLED, null);
887         Console.debug("Setting backups to " + backups);
888         Cache.applicationProperties.put(BackupFiles.ENABLED,
889                 Boolean.toString(backups));
890
891         Console.info("Writing " + fileName);
892
893         af.saveAlignment(fileName, ff);
894         Console.debug("Returning backups to " + savedBackupsPreference);
895         if (savedBackupsPreference != null)
896           Cache.applicationProperties.put(BackupFiles.ENABLED,
897                   savedBackupsPreference);
898         if (af.isSaveAlignmentSuccessful())
899         {
900           Console.debug("Written alignment '" + name + "' in "
901                   + ff.getName() + " format to " + file);
902         }
903         else
904         {
905           Console.warn("Error writing file " + file + " in " + ff.getName()
906                   + " format!");
907         }
908
909       }
910     }
911     return true;
912   }
913
914   private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
915           ArgValue av)
916   {
917     SubVals subVals = av.getSubVals();
918     ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID);
919     SequenceI seq = null;
920     if (subVals == null && idAv == null)
921       return null;
922     if (af == null || af.getCurrentView() == null)
923     {
924       return null;
925     }
926     AlignmentI al = af.getCurrentView().getAlignment();
927     if (al == null)
928     {
929       return null;
930     }
931     if (subVals != null)
932     {
933       if (subVals.has(Arg.SEQID.getName()))
934       {
935         seq = al.findName(subVals.get(Arg.SEQID.getName()));
936       }
937       else if (-1 < subVals.getIndex()
938               && subVals.getIndex() < al.getSequences().size())
939       {
940         seq = al.getSequenceAt(subVals.getIndex());
941       }
942     }
943     else if (idAv != null)
944     {
945       seq = al.findName(idAv.getValue());
946     }
947     return seq;
948   }
949 }