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