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