Merge branch 'improvement/JAL-4262_deprecation_warning_when_old_CLI_arguments_are_pro...
[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.HashMap;
10 import java.util.Iterator;
11 import java.util.List;
12 import java.util.Locale;
13 import java.util.Map;
14
15 import jalview.analysis.AlignmentUtils;
16 import jalview.api.structures.JalviewStructureDisplayI;
17 import jalview.bin.Jalview.ExitCode;
18 import jalview.bin.argparser.Arg;
19 import jalview.bin.argparser.ArgParser;
20 import jalview.bin.argparser.ArgParser.Position;
21 import jalview.bin.argparser.ArgValue;
22 import jalview.bin.argparser.ArgValuesMap;
23 import jalview.bin.argparser.SubVals;
24 import jalview.datamodel.AlignmentI;
25 import jalview.datamodel.SequenceI;
26 import jalview.datamodel.annotations.AlphaFoldAnnotationRowBuilder;
27 import jalview.gui.AlignFrame;
28 import jalview.gui.AlignmentPanel;
29 import jalview.gui.AppJmol;
30 import jalview.gui.Desktop;
31 import jalview.gui.Preferences;
32 import jalview.gui.StructureChooser;
33 import jalview.gui.StructureViewer;
34 import jalview.gui.StructureViewer.ViewerType;
35 import jalview.io.AppletFormatAdapter;
36 import jalview.io.BackupFiles;
37 import jalview.io.BioJsHTMLOutput;
38 import jalview.io.DataSourceType;
39 import jalview.io.FileFormat;
40 import jalview.io.FileFormatException;
41 import jalview.io.FileFormatI;
42 import jalview.io.FileFormats;
43 import jalview.io.FileLoader;
44 import jalview.io.HtmlSvgOutput;
45 import jalview.io.IdentifyFile;
46 import jalview.io.NewickFile;
47 import jalview.io.exceptions.ImageOutputException;
48 import jalview.schemes.ColourSchemeI;
49 import jalview.schemes.ColourSchemeProperty;
50 import jalview.structure.StructureImportSettings.TFType;
51 import jalview.structure.StructureSelectionManager;
52 import jalview.util.FileUtils;
53 import jalview.util.HttpUtils;
54 import jalview.util.ImageMaker;
55 import jalview.util.ImageMaker.TYPE;
56 import jalview.util.MessageManager;
57 import jalview.util.Platform;
58 import jalview.util.imagemaker.BitmapImageSizing;
59
60 public class Commands
61 {
62   Desktop desktop;
63
64   private boolean headless;
65
66   private ArgParser argParser;
67
68   private Map<String, AlignFrame> afMap;
69
70   private Map<String, List<StructureViewer>> svMap;
71
72   private boolean commandArgsProvided = false;
73
74   private boolean argsWereParsed = false;
75
76   private List<String> errors = new ArrayList<>();
77
78   public Commands(ArgParser argparser, boolean headless)
79   {
80     this(Desktop.instance, argparser, headless);
81   }
82
83   public Commands(Desktop d, ArgParser argparser, boolean h)
84   {
85     argParser = argparser;
86     headless = h;
87     desktop = d;
88     afMap = new HashMap<>();
89   }
90
91   protected boolean processArgs()
92   {
93     if (argParser == null)
94     {
95       return true;
96     }
97
98     boolean theseArgsWereParsed = false;
99
100     if (argParser != null && argParser.getLinkedIds() != null)
101     {
102       for (String id : argParser.getLinkedIds())
103       {
104         ArgValuesMap avm = argParser.getLinkedArgs(id);
105         theseArgsWereParsed = true;
106         boolean processLinkedOkay = processLinked(id);
107         theseArgsWereParsed &= processLinkedOkay;
108
109         processGroovyScript(id);
110
111         // wait around until alignFrame isn't busy
112         AlignFrame af = afMap.get(id);
113         while (af != null && af.getViewport().isCalcInProgress())
114         {
115           try
116           {
117             Thread.sleep(25);
118           } catch (Exception q)
119           {
120           }
121           ;
122         }
123
124         theseArgsWereParsed &= processImages(id);
125
126         if (processLinkedOkay)
127         {
128           theseArgsWereParsed &= processOutput(id);
129         }
130
131         // close ap
132         if (avm.getBoolean(Arg.CLOSE))
133         {
134           af = afMap.get(id);
135           if (af != null)
136           {
137             af.closeMenuItem_actionPerformed(true);
138           }
139         }
140
141       }
142
143     }
144
145     // report errors
146     StringBuilder sb = new StringBuilder();
147     for (String error : errors)
148     {
149       sb.append("- " + error);
150       sb.append("\n");
151     }
152     if (Platform.isHeadless())
153     {
154       Console.debug("All errors from command line argument commands:\n"
155               + sb.toString());
156     }
157     else
158     {
159       // scrollable dialog box
160
161     }
162
163     if (argParser.getBoolean(Arg.QUIT))
164     {
165       Jalview.getInstance().exit(
166               "Exiting due to " + Arg.QUIT.argString() + " argument.",
167               ExitCode.OK);
168       return true;
169     }
170     // carry on with jalview.bin.Jalview
171     argsWereParsed = theseArgsWereParsed;
172     return argsWereParsed;
173   }
174
175   public boolean commandArgsProvided()
176   {
177     return commandArgsProvided;
178   }
179
180   public boolean argsWereParsed()
181   {
182     return argsWereParsed;
183   }
184
185   protected boolean processLinked(String id)
186   {
187     boolean theseArgsWereParsed = false;
188     ArgValuesMap avm = argParser.getLinkedArgs(id);
189     if (avm == null)
190     {
191       return true;
192     }
193
194     boolean isError = false;
195
196     // set wrap scope here so it can be applied after structures are opened
197     boolean wrap = false;
198
199     if (avm.containsArg(Arg.APPEND) || avm.containsArg(Arg.OPEN))
200     {
201       commandArgsProvided = true;
202       long progress = -1;
203
204       boolean first = true;
205       boolean progressBarSet = false;
206       AlignFrame af;
207       // Combine the APPEND and OPEN files into one list, along with whether it
208       // was APPEND or OPEN
209       List<ArgValue> openAvList = new ArrayList<>();
210       openAvList.addAll(avm.getArgValueList(Arg.OPEN));
211       openAvList.addAll(avm.getArgValueList(Arg.APPEND));
212       // sort avlist based on av.getArgIndex()
213       Collections.sort(openAvList);
214       for (ArgValue av : openAvList)
215       {
216         Arg a = av.getArg();
217         SubVals sv = av.getSubVals();
218         String openFile = av.getValue();
219         if (openFile == null)
220           continue;
221
222         theseArgsWereParsed = true;
223         if (first)
224         {
225           first = false;
226           if (!headless && desktop != null)
227           {
228             desktop.setProgressBar(
229                     MessageManager.getString(
230                             "status.processing_commandline_args"),
231                     progress = System.currentTimeMillis());
232             progressBarSet = true;
233           }
234         }
235
236         if (!Platform.isJS())
237         /**
238          * ignore in JavaScript -- can't just file existence - could load it?
239          * 
240          * @j2sIgnore
241          */
242         {
243           if (!HttpUtils.startsWithHttpOrHttps(openFile))
244           {
245             if (!(new File(openFile)).exists())
246             {
247               addError("Can't find file '" + openFile + "'");
248               isError = true;
249               continue;
250             }
251           }
252         }
253
254         DataSourceType protocol = AppletFormatAdapter
255                 .checkProtocol(openFile);
256
257         FileFormatI format = null;
258         try
259         {
260           format = new IdentifyFile().identify(openFile, protocol);
261         } catch (FileFormatException e1)
262         {
263           addError("Unknown file format for '" + openFile + "'");
264           isError = true;
265           continue;
266         }
267
268         af = afMap.get(id);
269         // When to open a new AlignFrame
270         if (af == null || "true".equals(av.getSubVal("new"))
271                 || a == Arg.OPEN || format == FileFormat.Jalview)
272         {
273           if (a == Arg.OPEN)
274           {
275             Jalview.testoutput(argParser, Arg.OPEN, "examples/uniref50.fa",
276                     openFile);
277           }
278
279           Console.debug(
280                   "Opening '" + openFile + "' in new alignment frame");
281           FileLoader fileLoader = new FileLoader(!headless);
282           boolean xception = false;
283           try
284           {
285             af = fileLoader.LoadFileWaitTillLoaded(openFile, protocol,
286                     format);
287           } catch (Throwable thr)
288           {
289             xception = true;
290             addError("Couldn't open '" + openFile + "' as " + format + " "
291                     + thr.getLocalizedMessage()
292                     + " (Enable debug for full stack trace)");
293             isError = true;
294             Console.debug("Exception when opening '" + openFile + "'", thr);
295           } finally
296           {
297             if (af == null && !xception)
298             {
299               addInfo("Ignoring '" + openFile
300                       + "' - no alignment data found.");
301               continue;
302             }
303           }
304
305           // colour alignment?
306           String colour = ArgParser.getFromSubValArgOrPref(avm, av,
307                   Arg.COLOUR, sv, null, "DEFAULT_COLOUR_PROT", "");
308           if ("" != colour)
309           {
310             ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
311                     af.getViewport(), af.getViewport().getAlignment(),
312                     colour);
313
314             if (cs == null && !"None".equals(colour))
315             {
316               addWarn("Couldn't parse '" + colour + "' as a colourscheme.");
317             }
318             else
319             {
320               af.changeColour(cs);
321             }
322             Jalview.testoutput(argParser, Arg.COLOUR, "zappo", colour);
323           }
324
325           // Change alignment frame title
326           String title = ArgParser.getFromSubValArgOrPref(avm, av,
327                   Arg.TITLE, sv, null, null, null);
328           if (title != null)
329           {
330             af.setTitle(title);
331             Jalview.testoutput(argParser, Arg.TITLE, "test title", title);
332           }
333
334           // Add features
335           String featuresfile = ArgParser.getValueFromSubValOrArg(avm, av,
336                   Arg.FEATURES, sv);
337           if (featuresfile != null)
338           {
339             af.parseFeaturesFile(featuresfile,
340                     AppletFormatAdapter.checkProtocol(featuresfile));
341             Jalview.testoutput(argParser, Arg.FEATURES,
342                     "examples/testdata/plantfdx.features", featuresfile);
343           }
344
345           // Add annotations from file
346           String annotationsfile = ArgParser.getValueFromSubValOrArg(avm,
347                   av, Arg.ANNOTATIONS, sv);
348           if (annotationsfile != null)
349           {
350             af.loadJalviewDataFile(annotationsfile, null, null, null);
351             Jalview.testoutput(argParser, Arg.ANNOTATIONS,
352                     "examples/testdata/plantfdx.annotations",
353                     annotationsfile);
354           }
355
356           // Set or clear the sortbytree flag
357           boolean sortbytree = ArgParser.getBoolFromSubValOrArg(avm,
358                   Arg.SORTBYTREE, sv);
359           if (sortbytree)
360           {
361             af.getViewport().setSortByTree(true);
362             Jalview.testoutput(argParser, Arg.SORTBYTREE);
363           }
364
365           // Load tree from file
366           String treefile = ArgParser.getValueFromSubValOrArg(avm, av,
367                   Arg.TREE, sv);
368           if (treefile != null)
369           {
370             try
371             {
372               NewickFile nf = new NewickFile(treefile,
373                       AppletFormatAdapter.checkProtocol(treefile));
374               af.getViewport().setCurrentTree(
375                       af.showNewickTree(nf, treefile).getTree());
376               Jalview.testoutput(argParser, Arg.TREE,
377                       "examples/testdata/uniref50_test_tree", treefile);
378             } catch (IOException e)
379             {
380               addError("Couldn't add tree " + treefile, e);
381               isError = true;
382             }
383           }
384
385           // Show secondary structure annotations?
386           boolean showSSAnnotations = ArgParser.getFromSubValArgOrPref(avm,
387                   Arg.SHOWSSANNOTATIONS, av.getSubVals(), null,
388                   "STRUCT_FROM_PDB", true);
389           af.setAnnotationsVisibility(showSSAnnotations, true, false);
390
391           // Show sequence annotations?
392           boolean showAnnotations = ArgParser.getFromSubValArgOrPref(avm,
393                   Arg.SHOWANNOTATIONS, av.getSubVals(), null,
394                   "SHOW_ANNOTATIONS", true);
395           af.setAnnotationsVisibility(showAnnotations, false, true);
396
397           // show temperature factor annotations?
398           if (avm.getBoolean(Arg.NOTEMPFAC))
399           {
400             // do this better (annotation types?)
401             List<String> hideThese = new ArrayList<>();
402             hideThese.add("Temperature Factor");
403             hideThese.add(AlphaFoldAnnotationRowBuilder.LABEL);
404             AlignmentUtils.showOrHideSequenceAnnotations(
405                     af.getCurrentView().getAlignment(), hideThese, null,
406                     false, false);
407           }
408
409           // wrap alignment? do this last for formatting reasons
410           wrap = ArgParser.getFromSubValArgOrPref(avm, Arg.WRAP, sv, null,
411                   "WRAP_ALIGNMENT", false);
412           // af.setWrapFormat(wrap) is applied after structures are opened for
413           // annotation reasons
414
415           // store the AlignFrame for this id
416           afMap.put(id, af);
417
418           // is it its own structure file?
419           if (format.isStructureFile())
420           {
421             StructureSelectionManager ssm = StructureSelectionManager
422                     .getStructureSelectionManager(Desktop.instance);
423             SequenceI seq = af.alignPanel.getAlignment().getSequenceAt(0);
424             ssm.computeMapping(false, new SequenceI[] { seq }, null,
425                     openFile, DataSourceType.FILE, null, null, null, false);
426           }
427         }
428         else
429         {
430           Console.debug(
431                   "Opening '" + openFile + "' in existing alignment frame");
432           DataSourceType dst = HttpUtils.startsWithHttpOrHttps(openFile)
433                   ? DataSourceType.URL
434                   : DataSourceType.FILE;
435           FileLoader fileLoader = new FileLoader(!headless);
436           fileLoader.LoadFile(af.getCurrentView(), openFile, dst, null,
437                   false);
438         }
439
440         Console.debug("Command " + Arg.APPEND + " executed successfully!");
441
442       }
443       if (first) // first=true means nothing opened
444       {
445         if (headless)
446         {
447           Jalview.exit("Could not open any files in headless mode",
448                   ExitCode.NO_FILES);
449         }
450         else
451         {
452           Console.info("No more files to open");
453         }
454       }
455       if (progressBarSet && desktop != null)
456         desktop.setProgressBar(null, progress);
457
458     }
459
460     // open the structure (from same PDB file or given PDBfile)
461     if (!avm.getBoolean(Arg.NOSTRUCTURE))
462     {
463       AlignFrame af = afMap.get(id);
464       if (avm.containsArg(Arg.STRUCTURE))
465       {
466         commandArgsProvided = true;
467         for (ArgValue av : avm.getArgValueList(Arg.STRUCTURE))
468         {
469           String val = av.getValue();
470           SubVals subVals = av.getSubVals();
471           SequenceI seq = getSpecifiedSequence(af, avm, av);
472           if (seq == null)
473           {
474             // Could not find sequence from subId, let's assume the first
475             // sequence in the alignframe
476             AlignmentI al = af.getCurrentView().getAlignment();
477             seq = al.getSequenceAt(0);
478           }
479
480           if (seq == null)
481           {
482             addWarn("Could not find sequence for argument "
483                     + Arg.STRUCTURE.argString() + "=" + val);
484             continue;
485           }
486           File structureFile = null;
487           if (subVals.getContent() != null
488                   && subVals.getContent().length() != 0)
489           {
490             structureFile = new File(subVals.getContent());
491             Console.debug("Using structure file (from argument) '"
492                     + structureFile.getAbsolutePath() + "'");
493           }
494           // TRY THIS
495           /*
496            * PDBEntry fileEntry = new AssociatePdbFileWithSeq()
497            * .associatePdbWithSeq(selectedPdbFileName, DataSourceType.FILE,
498            * selectedSequence, true, Desktop.instance);
499            * 
500            * sViewer = launchStructureViewer(ssm, new PDBEntry[] { fileEntry }, ap, new
501            * SequenceI[] { selectedSequence });
502            * 
503            */
504           /* THIS DOESN'T WORK */
505           else if (seq.getAllPDBEntries() != null
506                   && seq.getAllPDBEntries().size() > 0)
507           {
508             structureFile = new File(
509                     seq.getAllPDBEntries().elementAt(0).getFile());
510             Console.debug("Using structure file (from sequence) '"
511                     + structureFile.getAbsolutePath() + "'");
512           }
513
514           if (structureFile == null)
515           {
516             addWarn("Not provided structure file with '" + val + "'");
517             continue;
518           }
519
520           if (!structureFile.exists())
521           {
522             addWarn("Structure file '" + structureFile.getAbsoluteFile()
523                     + "' not found.");
524             continue;
525           }
526
527           Console.debug("Using structure file "
528                   + structureFile.getAbsolutePath());
529
530           // open structure view
531           AlignmentPanel ap = af.alignPanel;
532           if (headless)
533           {
534             Cache.setProperty(Preferences.STRUCTURE_DISPLAY,
535                     StructureViewer.ViewerType.JMOL.toString());
536           }
537
538           String structureFilepath = structureFile.getAbsolutePath();
539
540           // get PAEMATRIX file and label from subvals or Arg.PAEMATRIX
541           String paeFilepath = ArgParser
542                   .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
543                           Arg.PAEMATRIX, Position.AFTER, av, subVals, null,
544                           null, null);
545           if (paeFilepath != null)
546           {
547             File paeFile = new File(paeFilepath);
548
549             try
550             {
551               paeFilepath = paeFile.getCanonicalPath();
552             } catch (IOException e)
553             {
554               paeFilepath = paeFile.getAbsolutePath();
555               addWarn("Problem with the PAE file path: '"
556                       + paeFile.getPath() + "'");
557             }
558           }
559
560           // showing annotations from structure file or not
561           boolean ssFromStructure = ArgParser.getFromSubValArgOrPref(avm,
562                   Arg.SHOWSSANNOTATIONS, subVals, null, "STRUCT_FROM_PDB",
563                   true);
564
565           // get TEMPFAC type from subvals or Arg.TEMPFAC in case user Adds
566           // reference annotations
567           String tftString = ArgParser
568                   .getFromSubValArgOrPrefWithSubstitutions(argParser, avm,
569                           Arg.TEMPFAC, Position.AFTER, av, subVals, null,
570                           null, null);
571           boolean notempfac = ArgParser.getFromSubValArgOrPref(avm,
572                   Arg.NOTEMPFAC, subVals, null, "ADD_TEMPFACT_ANN", false,
573                   true);
574           TFType tft = notempfac ? null : TFType.DEFAULT;
575           if (tftString != null && !notempfac)
576           {
577             // get kind of temperature factor annotation
578             try
579             {
580               tft = TFType.valueOf(tftString.toUpperCase(Locale.ROOT));
581               Console.debug("Obtained Temperature Factor type of '" + tft
582                       + "' for structure '" + structureFilepath + "'");
583             } catch (IllegalArgumentException e)
584             {
585               // Just an error message!
586               StringBuilder sb = new StringBuilder().append("Cannot set ")
587                       .append(Arg.TEMPFAC.argString()).append(" to '")
588                       .append(tft)
589                       .append("', ignoring.  Valid values are: ");
590               Iterator<TFType> it = Arrays.stream(TFType.values())
591                       .iterator();
592               while (it.hasNext())
593               {
594                 sb.append(it.next().toString().toLowerCase(Locale.ROOT));
595                 if (it.hasNext())
596                   sb.append(", ");
597               }
598               addWarn(sb.toString());
599             }
600           }
601
602           String sViewer = ArgParser.getFromSubValArgOrPref(avm,
603                   Arg.STRUCTUREVIEWER, Position.AFTER, av, subVals, null,
604                   null, "jmol");
605           ViewerType viewerType = ViewerType.getFromString(sViewer);
606
607           // TODO use ssFromStructure
608           StructureViewer sv = StructureChooser
609                   .openStructureFileForSequence(null, null, ap, seq, false,
610                           structureFilepath, tft, paeFilepath, false,
611                           ssFromStructure, false, viewerType);
612
613           if (sv == null)
614           {
615             addError("Failed to import and open structure view for file '"
616                     + structureFile + "'.");
617             continue;
618           }
619           try
620           {
621             long tries = 1000;
622             while (sv.isBusy() && tries > 0)
623             {
624               Thread.sleep(25);
625               if (sv.isBusy())
626               {
627                 tries--;
628                 Console.debug(
629                         "Waiting for viewer for " + structureFilepath);
630               }
631             }
632             if (tries == 0 && sv.isBusy())
633             {
634               addWarn("Gave up waiting for structure viewer to load file '"
635                       + structureFile
636                       + "'. Something may have gone wrong.");
637             }
638           } catch (Exception x)
639           {
640             addError("Exception whilst waiting for structure viewer "
641                     + structureFilepath, x);
642             isError = true;
643           }
644
645           // add StructureViewer to svMap list
646           if (svMap == null)
647           {
648             svMap = new HashMap<>();
649           }
650           if (svMap.get(id) == null)
651           {
652             svMap.put(id, new ArrayList<>());
653           }
654           svMap.get(id).add(sv);
655
656           Console.debug(
657                   "Successfully opened viewer for " + structureFilepath);
658           String structureImageFilename = ArgParser.getValueFromSubValOrArg(
659                   avm, av, Arg.STRUCTUREIMAGE, subVals);
660           if (sv != null && structureImageFilename != null)
661           {
662             ArgValue siAv = avm.getClosestNextArgValueOfArg(av,
663                     Arg.STRUCTUREIMAGE);
664             SubVals sisv = null;
665             if (structureImageFilename.equals(siAv.getValue()))
666             {
667               sisv = siAv.getSubVals();
668             }
669             File structureImageFile = new File(structureImageFilename);
670             String width = ArgParser.getValueFromSubValOrArg(avm, av,
671                     Arg.STRUCTUREIMAGEWIDTH, sisv);
672             String height = ArgParser.getValueFromSubValOrArg(avm, av,
673                     Arg.STRUCTUREIMAGEHEIGHT, sisv);
674             String scale = ArgParser.getValueFromSubValOrArg(avm, av,
675                     Arg.STRUCTUREIMAGESCALE, sisv);
676             String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
677                     Arg.STRUCTUREIMAGETEXTRENDERER, sisv);
678             String typeS = ArgParser.getValueFromSubValOrArg(avm, av,
679                     Arg.STRUCTUREIMAGETYPE, sisv);
680             if (typeS == null || typeS.length() == 0)
681             {
682               typeS = FileUtils.getExtension(structureImageFile);
683             }
684             TYPE imageType;
685             try
686             {
687               imageType = Enum.valueOf(TYPE.class,
688                       typeS.toUpperCase(Locale.ROOT));
689             } catch (IllegalArgumentException e)
690             {
691               addWarn("Do not know image format '" + typeS
692                       + "', using PNG");
693               imageType = TYPE.PNG;
694             }
695             BitmapImageSizing userBis = ImageMaker
696                     .parseScaleWidthHeightStrings(scale, width, height);
697             // TODO MAKE THIS VIEWER INDEPENDENT!!
698             switch (StructureViewer.getViewerType())
699             {
700             case JMOL:
701               JalviewStructureDisplayI sview = sv
702                       .getJalviewStructureDisplay();
703               if (sview instanceof AppJmol)
704               {
705                 AppJmol jmol = (AppJmol) sview;
706                 try
707                 {
708                   whatNext wn = this.checksBeforeWritingToFile(avm, subVals,
709                           false, structureImageFilename, "structure image");
710                   if (wn == whatNext.ERROR)
711                   {
712                     isError = true;
713                     continue;
714                   }
715                   else if (wn == whatNext.CONTINUE)
716                   {
717                     continue;
718                   }
719
720                   Console.debug("Rendering image to " + structureImageFile);
721                   jmol.makePDBImage(structureImageFile, imageType, renderer,
722                           userBis);
723                   Console.debug("Finished Rendering image to "
724                           + structureImageFile);
725
726                 } catch (ImageOutputException ioexc)
727                 {
728                   addError("Unexpected error whilst exporting image to "
729                           + structureImageFile, ioexc);
730                   isError = true;
731                   continue;
732                 }
733
734               }
735               break;
736             default:
737               addWarn("Cannot export image for structure viewer "
738                       + sv.getViewerType() + " yet");
739               continue;
740             }
741           }
742         }
743       }
744     }
745
746     if (wrap)
747     {
748       AlignFrame af = afMap.get(id);
749       if (af != null)
750       {
751         af.setWrapFormat(wrap, true);
752       }
753     }
754
755     /*
756     boolean doShading = avm.getBoolean(Arg.TEMPFAC_SHADING);
757     if (doShading)
758     {
759       AlignFrame af = afMap.get(id);
760       for (AlignmentAnnotation aa : af.alignPanel.getAlignment()
761               .findAnnotation(PDBChain.class.getName().toString()))
762       {
763         AnnotationColourGradient acg = new AnnotationColourGradient(aa,
764                 af.alignPanel.av.getGlobalColourScheme(), 0);
765         acg.setSeqAssociated(true);
766         af.changeColour(acg);
767         Console.info("Changed colour " + acg.toString());
768       }
769     }
770     */
771
772     return theseArgsWereParsed && !isError;
773   }
774
775   protected void processGroovyScript(String id)
776   {
777     ArgValuesMap avm = argParser.getLinkedArgs(id);
778     AlignFrame af = afMap.get(id);
779
780     if (af == null)
781     {
782       addWarn("Did not have an alignment window for id=" + id);
783       return;
784     }
785
786     if (avm.containsArg(Arg.GROOVY))
787     {
788       String groovyscript = avm.getValue(Arg.GROOVY);
789       if (groovyscript != null)
790       {
791         // Execute the groovy script after we've done all the rendering stuff
792         // and before any images or figures are generated.
793         Console.info("Executing script " + groovyscript);
794         Jalview.getInstance().executeGroovyScript(groovyscript, af);
795       }
796     }
797   }
798
799   protected boolean processImages(String id)
800   {
801     ArgValuesMap avm = argParser.getLinkedArgs(id);
802     AlignFrame af = afMap.get(id);
803
804     if (af == null)
805     {
806       addWarn("Did not have an alignment window for id=" + id);
807       return false;
808     }
809
810     boolean isError = false;
811     if (avm.containsArg(Arg.IMAGE))
812     {
813       for (ArgValue av : avm.getArgValueList(Arg.IMAGE))
814       {
815         String val = av.getValue();
816         SubVals subVal = av.getSubVals();
817         String fileName = subVal.getContent();
818         File file = new File(fileName);
819         String name = af.getName();
820         String renderer = ArgParser.getValueFromSubValOrArg(avm, av,
821                 Arg.TEXTRENDERER, subVal);
822         if (renderer == null)
823           renderer = "text";
824         String type = "png"; // default
825
826         String scale = ArgParser.getValueFromSubValOrArg(avm, av, Arg.SCALE,
827                 subVal);
828         String width = ArgParser.getValueFromSubValOrArg(avm, av, Arg.WIDTH,
829                 subVal);
830         String height = ArgParser.getValueFromSubValOrArg(avm, av,
831                 Arg.HEIGHT, subVal);
832         BitmapImageSizing userBis = ImageMaker
833                 .parseScaleWidthHeightStrings(scale, width, height);
834
835         type = ArgParser.getValueFromSubValOrArg(avm, av, Arg.TYPE, subVal);
836         if (type == null && fileName != null)
837         {
838           for (String ext : new String[] { "svg", "png", "html", "eps" })
839           {
840             if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
841             {
842               type = ext;
843             }
844           }
845         }
846         // for moment we disable JSON export
847         Cache.setPropsAreReadOnly(true);
848         Cache.setProperty("EXPORT_EMBBED_BIOJSON", "false");
849
850         Console.info("Writing " + file);
851
852         whatNext wn = this.checksBeforeWritingToFile(avm, subVal, false,
853                 fileName, "image");
854         if (wn == whatNext.ERROR)
855         {
856           isError = true;
857           continue;
858         }
859         else if (wn == whatNext.CONTINUE)
860         {
861           continue;
862         }
863
864         try
865         {
866           switch (type)
867           {
868
869           case "svg":
870             Console.debug("Outputting type '" + type + "' to " + fileName);
871             af.createSVG(file, renderer);
872             break;
873
874           case "png":
875             Console.debug("Outputting type '" + type + "' to " + fileName);
876             af.createPNG(file, null, userBis);
877             break;
878
879           case "html":
880             Console.debug("Outputting type '" + type + "' to " + fileName);
881             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
882             htmlSVG.exportHTML(fileName, renderer);
883             break;
884
885           case "biojs":
886             Console.debug(
887                     "Outputting BioJS MSA Viwer HTML file: " + fileName);
888             try
889             {
890               BioJsHTMLOutput.refreshVersionInfo(
891                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
892             } catch (URISyntaxException e)
893             {
894               e.printStackTrace();
895             }
896             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
897             bjs.exportHTML(fileName);
898             break;
899
900           case "eps":
901             Console.debug("Outputting EPS file: " + fileName);
902             af.createEPS(file, renderer);
903             break;
904
905           case "imagemap":
906             Console.debug("Outputting ImageMap file: " + fileName);
907             af.createImageMap(file, name);
908             break;
909
910           default:
911             addWarn(Arg.IMAGE.argString() + " type '" + type
912                     + "' not known. Ignoring");
913             break;
914           }
915         } catch (Exception ioex)
916         {
917           addError("Unexpected error during export to '" + fileName + "'",
918                   ioex);
919           isError = true;
920         }
921       }
922     }
923     return !isError;
924   }
925
926   protected boolean processOutput(String id)
927   {
928     ArgValuesMap avm = argParser.getLinkedArgs(id);
929     AlignFrame af = afMap.get(id);
930
931     if (af == null)
932     {
933       addWarn("Did not have an alignment window for id=" + id);
934       return false;
935     }
936
937     boolean isError = false;
938
939     if (avm.containsArg(Arg.OUTPUT))
940     {
941       for (ArgValue av : avm.getArgValueList(Arg.OUTPUT))
942       {
943         String val = av.getValue();
944         SubVals subVals = av.getSubVals();
945         String fileName = subVals.getContent();
946         boolean stdout = ArgParser.STDOUTFILENAME.equals(fileName);
947         File file = new File(fileName);
948
949         String name = af.getName();
950         String format = ArgParser.getValueFromSubValOrArg(avm, av,
951                 Arg.FORMAT, subVals);
952         FileFormats ffs = FileFormats.getInstance();
953         List<String> validFormats = ffs.getWritableFormats(false);
954
955         FileFormatI ff = null;
956         if (format == null && fileName != null)
957         {
958           FORMAT: for (String fname : validFormats)
959           {
960             FileFormatI tff = ffs.forName(fname);
961             String[] extensions = tff.getExtensions().split(",");
962             for (String ext : extensions)
963             {
964               if (fileName.toLowerCase(Locale.ROOT).endsWith("." + ext))
965               {
966                 ff = tff;
967                 format = ff.getName();
968                 break FORMAT;
969               }
970             }
971           }
972         }
973         if (ff == null && format != null)
974         {
975           ff = ffs.forName(format);
976         }
977         if (ff == null)
978         {
979           if (stdout)
980           {
981             ff = FileFormat.Fasta;
982           }
983           else
984           {
985             StringBuilder validSB = new StringBuilder();
986             for (String f : validFormats)
987             {
988               if (validSB.length() > 0)
989                 validSB.append(", ");
990               validSB.append(f);
991               FileFormatI tff = ffs.forName(f);
992               validSB.append(" (");
993               validSB.append(tff.getExtensions());
994               validSB.append(")");
995             }
996
997             addError("No valid format specified for "
998                     + Arg.OUTPUT.argString() + ". Valid formats are "
999                     + validSB.toString() + ".");
1000             continue;
1001           }
1002         }
1003
1004         whatNext wn = this.checksBeforeWritingToFile(avm, subVals, true,
1005                 fileName, ff.getName());
1006         if (wn == whatNext.ERROR)
1007         {
1008           isError = true;
1009           continue;
1010         }
1011         else if (wn == whatNext.CONTINUE)
1012         {
1013           continue;
1014         }
1015
1016         boolean backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS,
1017                 subVals, null,
1018                 Platform.isHeadless() ? null : BackupFiles.ENABLED,
1019                 !Platform.isHeadless());
1020
1021         Console.info("Writing " + fileName);
1022
1023         af.saveAlignment(fileName, ff, stdout, backups);
1024         if (af.isSaveAlignmentSuccessful())
1025         {
1026           Console.debug("Written alignment '" + name + "' in "
1027                   + ff.getName() + " format to '" + file + "'");
1028         }
1029         else
1030         {
1031           addError("Error writing file '" + file + "' in " + ff.getName()
1032                   + " format!");
1033           isError = true;
1034           continue;
1035         }
1036
1037       }
1038     }
1039     return !isError;
1040   }
1041
1042   private SequenceI getSpecifiedSequence(AlignFrame af, ArgValuesMap avm,
1043           ArgValue av)
1044   {
1045     SubVals subVals = av.getSubVals();
1046     ArgValue idAv = avm.getClosestNextArgValueOfArg(av, Arg.SEQID);
1047     SequenceI seq = null;
1048     if (subVals == null && idAv == null)
1049       return null;
1050     if (af == null || af.getCurrentView() == null)
1051     {
1052       return null;
1053     }
1054     AlignmentI al = af.getCurrentView().getAlignment();
1055     if (al == null)
1056     {
1057       return null;
1058     }
1059     if (subVals != null)
1060     {
1061       if (subVals.has(Arg.SEQID.getName()))
1062       {
1063         seq = al.findName(subVals.get(Arg.SEQID.getName()));
1064       }
1065       else if (-1 < subVals.getIndex()
1066               && subVals.getIndex() < al.getSequences().size())
1067       {
1068         seq = al.getSequenceAt(subVals.getIndex());
1069       }
1070     }
1071     if (seq == null && idAv != null)
1072     {
1073       seq = al.findName(idAv.getValue());
1074     }
1075     return seq;
1076   }
1077
1078   public AlignFrame[] getAlignFrames()
1079   {
1080     AlignFrame[] afs = null;
1081     if (afMap != null)
1082     {
1083       afs = (AlignFrame[]) afMap.values().toArray();
1084     }
1085
1086     return afs;
1087   }
1088
1089   public List<StructureViewer> getStructureViewers()
1090   {
1091     List<StructureViewer> svs = null;
1092     if (svMap != null)
1093     {
1094       for (List<StructureViewer> svList : svMap.values())
1095       {
1096         if (svs == null)
1097         {
1098           svs = new ArrayList<>();
1099         }
1100         svs.addAll(svList);
1101       }
1102     }
1103     return svs;
1104   }
1105
1106   private void addInfo(String errorMessage)
1107   {
1108     Console.info(errorMessage);
1109     errors.add(errorMessage);
1110   }
1111
1112   private void addWarn(String errorMessage)
1113   {
1114     Console.warn(errorMessage);
1115     errors.add(errorMessage);
1116   }
1117
1118   private void addError(String errorMessage)
1119   {
1120     addError(errorMessage, null);
1121   }
1122
1123   private void addError(String errorMessage, Exception e)
1124   {
1125     Console.error(errorMessage, e);
1126     errors.add(errorMessage);
1127   }
1128
1129   private enum whatNext
1130   {
1131     OKAY, CONTINUE, ERROR;
1132   }
1133
1134   private whatNext checksBeforeWritingToFile(ArgValuesMap avm,
1135           SubVals subVal, boolean includeBackups, String filename,
1136           String adjective)
1137   {
1138     File file = new File(filename);
1139
1140     boolean overwrite = ArgParser.getFromSubValArgOrPref(avm, Arg.OVERWRITE,
1141             subVal, null, "OVERWRITE_OUTPUT", false);
1142     boolean stdout = false;
1143     boolean backups = false;
1144     if (includeBackups)
1145     {
1146       stdout = ArgParser.STDOUTFILENAME.equals(filename);
1147       // backups. Use the Arg.BACKUPS or subval "backups" setting first,
1148       // otherwise if headless assume false, if not headless use the user
1149       // preference with default true.
1150       backups = ArgParser.getFromSubValArgOrPref(avm, Arg.BACKUPS, subVal,
1151               null, Platform.isHeadless() ? null : BackupFiles.ENABLED,
1152               !Platform.isHeadless());
1153     }
1154
1155     if (file.exists() && !(overwrite || backups || stdout))
1156     {
1157       addWarn("Won't overwrite file '" + filename + "' without "
1158               + Arg.OVERWRITE.argString()
1159               + (includeBackups ? " or " + Arg.BACKUPS.argString() : "")
1160               + " set");
1161       return whatNext.CONTINUE;
1162     }
1163
1164     boolean mkdirs = ArgParser.getFromSubValArgOrPref(avm, Arg.MKDIRS,
1165             subVal, null, "MKDIRS_OUTPUT", false);
1166
1167     if (!FileUtils.checkParentDir(file, mkdirs))
1168     {
1169       addError("Directory '"
1170               + FileUtils.getParentDir(file).getAbsolutePath()
1171               + "' does not exist for " + adjective + " file '" + filename
1172               + "'."
1173               + (mkdirs ? "" : "  Try using " + Arg.MKDIRS.argString()));
1174       return whatNext.ERROR;
1175     }
1176
1177     return whatNext.OKAY;
1178   }
1179 }