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