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