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