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