3253-omnibus save
[jalview.git] / src / jalview / bin / Jalview.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 package jalview.bin;
22
23 import jalview.api.AlignCalcWorkerI;
24 import jalview.api.AlignFrameI;
25 import jalview.api.AlignViewportI;
26 import jalview.api.JalviewApp;
27 import jalview.api.StructureSelectionManagerProvider;
28 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
29 import jalview.datamodel.ColumnSelection;
30 import jalview.datamodel.HiddenColumns;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.SequenceGroup;
33 import jalview.datamodel.SequenceI;
34 import jalview.ext.so.SequenceOntology;
35 import jalview.gui.AlignFrame;
36 import jalview.gui.AlignViewport;
37 import jalview.gui.AlignmentPanel;
38 import jalview.gui.CalculationChooser;
39 import jalview.gui.Desktop;
40 import jalview.gui.Preferences;
41 import jalview.gui.PromptUserConfig;
42 import jalview.gui.StructureViewer;
43 import jalview.io.AppletFormatAdapter;
44 import jalview.io.BioJsHTMLOutput;
45 import jalview.io.DataSourceType;
46 import jalview.io.FileFormat;
47 import jalview.io.FileFormatException;
48 import jalview.io.FileFormatI;
49 import jalview.io.FileFormats;
50 import jalview.io.FileLoader;
51 import jalview.io.HtmlSvgOutput;
52 import jalview.io.IdentifyFile;
53 import jalview.io.NewickFile;
54 import jalview.io.gff.SequenceOntologyFactory;
55 import jalview.javascript.JSFunctionExec;
56 import jalview.javascript.MouseOverStructureListener;
57 import jalview.renderer.seqfeatures.FeatureRenderer;
58 import jalview.schemes.ColourSchemeI;
59 import jalview.schemes.ColourSchemeProperty;
60 import jalview.structure.SelectionSource;
61 import jalview.structure.VamsasSource;
62 import jalview.util.MessageManager;
63 import jalview.util.Platform;
64 import jalview.ws.jws2.Jws2Discoverer;
65
66 import java.applet.AppletContext;
67 import java.io.BufferedReader;
68 import java.io.File;
69 import java.io.FileOutputStream;
70 import java.io.IOException;
71 import java.io.InputStreamReader;
72 import java.io.OutputStreamWriter;
73 import java.io.PrintWriter;
74 import java.net.MalformedURLException;
75 import java.net.URI;
76 import java.net.URISyntaxException;
77 import java.net.URL;
78 import java.security.AllPermission;
79 import java.security.CodeSource;
80 import java.security.PermissionCollection;
81 import java.security.Permissions;
82 import java.security.Policy;
83 import java.util.HashMap;
84 import java.util.Hashtable;
85 import java.util.Map;
86 import java.util.Vector;
87
88 import javax.swing.LookAndFeel;
89 import javax.swing.SwingUtilities;
90 import javax.swing.UIManager;
91
92 import groovy.lang.Binding;
93 import groovy.util.GroovyScriptEngine;
94 import netscape.javascript.JSObject;
95
96 /**
97  * Main class for Jalview Application <br>
98  * <br>
99  * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
100  * jalview.bin.Jalview
101  * 
102  * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
103  * jalview.bin.Jalview jalview.bin.Jalview
104  * 
105  * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
106  * embellish '*' to e.g. '*.jar')
107  * 
108  * @author $author$
109  * @version $Revision$
110  */
111 public class Jalview implements ApplicationSingletonI, JalviewJSApi
112 {
113
114   public static Jalview getInstance()
115   {
116     return (Jalview) ApplicationSingletonProvider
117             .getInstance(Jalview.class);
118   }
119
120   private Jalview()
121   {
122   }
123
124   static
125   {
126     Platform.getURLCommandArguments();
127   }
128
129   private boolean headless;
130
131   public static boolean isHeadlessMode()
132   {
133     return getInstance().headless;
134   }
135
136   private Desktop desktop;
137
138   private AlignFrame currentAlignFrame;
139
140   public boolean isJavaAppletTag;
141
142   public String appletResourcePath;
143
144   JalviewAppLoader appLoader;
145
146   protected JSFunctionExec jsFunctionExec;
147
148   private boolean noCalculation, noMenuBar, noStatus;
149
150   private boolean noAnnotation;
151
152   public static final String TERMINATOR_LINE = "Jalview argument parsing complete.";
153
154   public boolean getStartCalculations()
155   {
156     return !noCalculation;
157   }
158
159   public boolean getAllowMenuBar()
160   {
161     return !noMenuBar;
162   }
163
164   public boolean getShowStatus()
165   {
166     return !noStatus;
167   }
168
169   public boolean getShowAnnotation()
170   {
171     return !noAnnotation;
172   }
173
174   public static AlignFrame getCurrentAlignFrame()
175   {
176     return getInstance().currentAlignFrame;
177   }
178
179   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
180   {
181     getInstance().currentAlignFrame = currentAlignFrame;
182   }
183
184   static
185   {
186     if (!Platform.isJS())
187     /**
188      * Java only
189      * 
190      * @j2sIgnore
191      */
192     {
193       // grab all the rights we can for the JVM
194       Policy.setPolicy(new Policy()
195       {
196         @Override
197         public PermissionCollection getPermissions(CodeSource codesource)
198         {
199           Permissions perms = new Permissions();
200           perms.add(new AllPermission());
201           return (perms);
202         }
203
204         @Override
205         public void refresh()
206         {
207         }
208       });
209     }
210   }
211
212   /**
213    * keep track of feature fetching tasks.
214    * 
215    * @author JimP
216    * 
217    */
218   class FeatureFetcher
219   {
220     /*
221      * TODO: generalise to track all jalview events to orchestrate batch
222      * processing events.
223      */
224
225     private int queued = 0;
226
227     private int running = 0;
228
229     public FeatureFetcher()
230     {
231
232     }
233
234     public void addFetcher(final AlignFrame af,
235             final Vector<String> dasSources)
236     {
237       final long id = System.currentTimeMillis();
238       queued++;
239       final FeatureFetcher us = this;
240       new Thread(new Runnable()
241       {
242
243         @Override
244         public void run()
245         {
246           synchronized (us)
247           {
248             queued--;
249             running++;
250           }
251
252           af.setProgressBar(MessageManager
253                   .getString("status.das_features_being_retrived"), id);
254           af.featureSettings_actionPerformed(null);
255           af.setProgressBar(null, id);
256           synchronized (us)
257           {
258             running--;
259           }
260         }
261       }).start();
262     }
263
264     public synchronized boolean allFinished()
265     {
266       return queued == 0 && running == 0;
267     }
268
269   }
270
271   /**
272    * main class for Jalview application
273    * 
274    * @param args
275    *          open <em>filename</em>
276    */
277   public static void main(String[] args)
278   {
279     // Platform.startJavaLogging();
280     getInstance().doMain(args);
281   }
282
283
284   @SuppressWarnings("unused")
285   /**
286    * @param args
287    */
288   void doMain(String[] args)
289   {
290
291     boolean isJS = Platform.isJS();
292     if (isJS)
293     {
294       Platform.setAppClass(this);
295     }
296     else
297     {
298       System.setSecurityManager(null);
299     }
300
301     System.out
302             .println("Java version: " + System.getProperty("java.version"));
303     System.out.println(System.getProperty("os.arch") + " "
304             + System.getProperty("os.name") + " "
305             + System.getProperty("os.version"));
306
307     ArgsParser aparser = new ArgsParser(args);
308
309     String usrPropsFile = aparser.getValue(ArgsParser.PROPS);
310     Cache.loadProperties(usrPropsFile);
311
312     if (aparser.contains(ArgsParser.NODISPLAY)
313             || aparser.contains(ArgsParser.NOGUI)
314             || aparser.contains(ArgsParser.HEADLESS)
315             || "true".equals(System.getProperty("java.awt.headless")))
316     {
317       headless = true;
318       setSynchronous(true);
319     }
320
321     if (isJS)
322     {
323       isJavaAppletTag = aparser.isApplet();
324       if (isJavaAppletTag)
325       {
326         Preferences.setAppletDefaults();
327         Cache.loadProperties(usrPropsFile); // again, because we
328         // might be changing defaults here?
329       }
330       System.out.println(
331               "<Applet> found: " + aparser.getValue("Info.j2sAppletID"));
332       appletResourcePath = aparser.getValue("Info.resourcePath");
333     }
334     else
335     /**
336      * Java only
337      * 
338      * @j2sIgnore
339      */
340     {
341       if (usrPropsFile != null)
342       {
343         System.out.println(
344                 "CMD [-props " + usrPropsFile + "] executed successfully!");
345       }
346
347       if (aparser.contains("help") || aparser.contains("h"))
348       {
349         showUsage();
350         System.exit(0);
351       }
352
353       // anything else!
354
355       final String jabawsUrl = aparser.getValue(ArgsParser.JABAWS);
356       if (jabawsUrl != null)
357       {
358         try
359         {
360           Jws2Discoverer.getInstance().setPreferredUrl(jabawsUrl);
361           System.out.println(
362                   "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
363         } catch (MalformedURLException e)
364         {
365           System.err.println(
366                   "Invalid jabaws parameter: " + jabawsUrl + " ignored");
367         }
368       }
369
370     }
371     // check for property setting
372     String defs = aparser.getValue(ArgsParser.SETPROP);
373     while (defs != null)
374     {
375       int p = defs.indexOf('=');
376       if (p == -1)
377       {
378         System.err.println("Ignoring invalid setprop argument : " + defs);
379       }
380       else
381       {
382         System.out.println("Executing setprop argument: " + defs);
383         if (isJS)
384         {
385           Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
386         }
387       }
388       defs = aparser.getValue(ArgsParser.SETPROP);
389     }
390     System.setProperty("http.agent",
391             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
392     try
393     {
394       Cache.initLogger();
395     } catch (NoClassDefFoundError error)
396     {
397       error.printStackTrace();
398       System.out.println("\nEssential logging libraries not found."
399               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
400       System.exit(0);
401     }
402
403     desktop = null;
404
405     try
406     {
407       if (!isJS && Platform.isWin())
408       {
409         UIManager.setLookAndFeel(
410                 headless ? "javax.swing.plaf.metal.MetalLookAndFeel"
411                         : UIManager.getSystemLookAndFeelClassName());
412         // UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
413       }
414     } catch (Exception ex)
415     {
416       System.err.println("Unexpected Look and Feel Exception");
417       ex.printStackTrace();
418     }
419     if (Platform.isAMacAndNotJS())
420     {
421
422       LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
423               .getLookAndFeel();
424       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
425               "Jalview");
426       System.setProperty("apple.laf.useScreenMenuBar", "true");
427       if (lookAndFeel != null)
428       {
429         try
430         {
431           UIManager.setLookAndFeel(lookAndFeel);
432         } catch (Throwable e)
433         {
434           System.err.println(
435                   "Failed to set QuaQua look and feel: " + e.toString());
436         }
437       }
438       if (lookAndFeel == null
439               || !(lookAndFeel.getClass().isAssignableFrom(
440                       UIManager.getLookAndFeel().getClass()))
441               || !UIManager.getLookAndFeel().getClass().toString()
442                       .toLowerCase().contains("quaqua"))
443       {
444         try
445         {
446           System.err.println(
447                   "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
448           UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
449         } catch (Throwable e)
450         {
451           System.err.println(
452                   "Failed to reset look and feel: " + e.toString());
453         }
454       }
455     }
456
457     /*
458      * configure 'full' SO model if preferences say to, 
459      * else use the default (SO Lite)
460      */
461     if (Cache.getDefault(Preferences.USE_FULL_SO, false))
462     {
463       SequenceOntologyFactory.setSequenceOntology(new SequenceOntology());
464     }
465
466     if (headless)
467     {
468       // If this is not tested, then
469
470       if (aparser.contains(ArgsParser.NOUSAGESTATS))
471       {
472         System.err.println("CMD [-nousagestats] executed successfully!");
473       }
474       if (aparser.contains(ArgsParser.NOQUESTIONNAIRE))
475       {
476         System.err.println("CMD [-noquestionnaire] executed successfully!");
477       }
478
479     }
480     else
481     {
482       desktop = Desktop.getInstance();
483       desktop.setInBatchMode(true); // indicate we are starting up
484       desktop.setVisible(true);
485
486       if (!isJS)
487       /**
488        * Java only
489        * 
490        * @j2sIgnore
491        */
492       {
493         desktop.startServiceDiscovery();
494         if (!aparser.contains(ArgsParser.NOUSAGESTATS))
495         {
496           startUsageStats(desktop);
497         }
498         else
499         {
500           System.err.println("CMD [-nousagestats] executed successfully!");
501         }
502
503         if (!aparser.contains(ArgsParser.NOQUESTIONNAIRE))
504         {
505           String url = aparser.getValue(ArgsParser.QUESTIONNAIRE);
506           if (url != null)
507           {
508             // Start the desktop questionnaire prompter with the specified
509             // questionnaire
510             Cache.log.debug("Starting questionnaire url at " + url);
511             desktop.checkForQuestionnaire(url);
512             System.out.println("CMD questionnaire[-" + url
513                     + "] executed successfully!");
514           }
515           else
516           {
517             if (Cache.getProperty(Preferences.NOQUESTIONNAIRES) == null)
518             {
519               // Start the desktop questionnaire prompter with the specified
520               // questionnaire
521               // String defurl =
522               // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
523               // //
524               String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
525               Cache.log.debug(
526                       "Starting questionnaire with default url: " + defurl);
527               desktop.checkForQuestionnaire(defurl);
528             }
529           }
530         }
531         else
532         {
533           System.err
534                   .println("CMD [-noquestionnaire] executed successfully!");
535         }
536
537         if (!aparser.contains(ArgsParser.NONEWS))
538         {
539           desktop.checkForNews();
540         }
541
542         BioJsHTMLOutput.updateBioJS();
543       }
544     }
545
546     parseArguments(aparser, true);
547     System.err.println(TERMINATOR_LINE);
548   }
549
550   /**
551    * Allow an outside entity to initiate the second half of argument parsing
552    * (only).
553    * 
554    * @param args
555    * @return null is good
556    */
557   @Override
558   public Object parseArguments(String[] args)
559   {
560
561     try
562     {
563       ArgsParser aparser = new ArgsParser(args);
564       return parseArguments(aparser, false);
565     } catch (Throwable t)
566     {
567       return t;
568     }
569   }
570
571   /**
572    * 
573    * @param aparser
574    * @param isStartup
575    * @return
576    */
577   private Object parseArguments(ArgsParser aparser, boolean isStartup)
578   {
579     boolean isJS = Platform.isJS();
580
581     Desktop desktop = (headless ? null : Desktop.getInstance());
582     // script to execute after all loading is
583     // completed one way or another
584     // extract groovy argument and execute if necessary
585     String groovyscript = (isJS ? null
586             : aparser.getValue(ArgsParser.GROOVY, true));
587     String file = aparser.getValue(ArgsParser.OPEN, true);
588     // BH this here to allow split frame; not working as of 5/17/2019
589     String file2 = aparser.getValue(ArgsParser.OPEN2, true);
590     String fileFormat = (isJavaAppletTag
591             ? aparser.getAppletValue("format", null)
592             : null);
593     FileFormatI format = null;
594     DataSourceType protocol = null;
595
596     if (file == null && desktop == null)
597     {
598       System.out.println("No files to open!");
599       System.exit(1);
600     }
601     boolean haveImport = false;// checkStartVamas(aparser);
602     // Finally, deal with the remaining input data.
603     long progress = -1;
604     if (file == null && isJavaAppletTag)
605     {
606       // Maybe the sequences are added as parameters
607       StringBuffer data = new StringBuffer("PASTE");
608       int i = 1;
609       while ((file = aparser.getAppletValue("sequence" + i, null)) != null)
610       {
611         data.append(file.toString() + "\n");
612         i++;
613       }
614       if (data.length() > 5)
615       {
616         file = data.toString();
617       }
618     }
619
620     String data;
621
622     if (file != null)
623     {
624
625       if (!headless)
626       {
627         desktop.setProgressBar(
628                 MessageManager
629                         .getString("status.processing_commandline_args"),
630                 progress = System.currentTimeMillis());
631       }
632
633       if (!isJS)
634       /**
635        * ignore in JavaScript -- can't just check file existence - could load
636        * it?
637        * 
638        * @j2sIgnore
639        */
640       {
641         if (!file.startsWith("http://") && !file.startsWith("https://"))
642         // BH 2019 added https check for Java
643         {
644           if (!(new File(file)).exists())
645           {
646             System.out.println("Can't find " + file);
647             if (headless)
648             {
649               System.exit(1);
650             }
651           }
652         }
653       }
654
655       protocol = AppletFormatAdapter.checkProtocol(file);
656
657       try
658       {
659         format = (isJavaAppletTag && fileFormat != null
660                 ? FileFormats.getInstance().forName(fileFormat)
661                 : null);
662         if (format == null)
663         {
664           format = new IdentifyFile().identify(file, protocol);
665         }
666       } catch (FileFormatException e1)
667       {
668         // TODO ?
669       }
670
671       if (aparser.contains(ArgsParser.NOMENUBAR))
672       {
673         noMenuBar = true;
674         System.out.println("CMD [nomenu] executed successfully!");
675       }
676
677       if (aparser.contains(ArgsParser.NOSTATUS))
678       {
679         noStatus = true;
680         System.out.println("CMD [nostatus] executed successfully!");
681       }
682
683       if (aparser.contains(ArgsParser.NOANNOTATION)
684               || aparser.contains(ArgsParser.NOANNOTATION2))
685       {
686         noAnnotation = true;
687         System.out.println("CMD no-annotation executed successfully!");
688       }
689       if (aparser.contains(ArgsParser.NOCALCULATION))
690       {
691         noCalculation = true;
692         System.out.println("CMD [nocalculation] executed successfully!");
693       }
694
695       AlignFrame af = new FileLoader(!headless).LoadFileWaitTillLoaded(file,
696               protocol, format);
697       if (af == null)
698       {
699         System.out.println("error");
700       }
701       else
702       {
703         System.out
704                 .println("CMD [-open " + file + "] executed successfully!");
705         if (file2 != null)
706         {
707           protocol = AppletFormatAdapter.checkProtocol(file2);
708           try
709           {
710             format = new IdentifyFile().identify(file2, protocol);
711           } catch (FileFormatException e1)
712           {
713             // TODO ?
714           }
715           AlignFrame af2 = new FileLoader(!headless)
716                   .LoadFileWaitTillLoaded(file2, protocol, format);
717           if (af2 == null)
718           {
719             System.out.println("error");
720           }
721           else
722           {
723             AlignViewport.openLinkedAlignmentAs(af,
724                     af.getViewport().getAlignment(),
725                     af2.getViewport().getAlignment(), "",
726                     AlignViewport.SPLIT_FRAME);
727             System.out.println(
728                     "CMD [-open2 " + file2 + "] executed successfully!");
729           }
730         }
731
732         setCurrentAlignFrame(af);
733
734         // TODO: file2 How to implement file2 for the applet spit screen?
735
736         data = aparser.getValue(ArgsParser.COLOUR, true);
737         if (data != null)
738         {
739           data.replaceAll("%20", " ");
740
741           ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
742                   af.getViewport(), af.getViewport().getAlignment(), data);
743
744           if (cs != null)
745           {
746             System.out.println(
747                     "CMD [-color " + data + "] executed successfully!");
748           }
749           af.changeColour(cs);
750         }
751
752         // Must maintain ability to use the groups flag
753         data = aparser.getValue(ArgsParser.GROUPS, true);
754         if (data != null)
755         {
756           af.parseFeaturesFile(data,
757                   AppletFormatAdapter.checkProtocol(data));
758           // System.out.println("Added " + data);
759           System.out.println(
760                   "CMD groups[-" + data + "]  executed successfully!");
761         }
762         data = aparser.getValue(ArgsParser.FEATURES, true);
763         if (data != null)
764         {
765           af.parseFeaturesFile(data,
766                   AppletFormatAdapter.checkProtocol(data));
767           // System.out.println("Added " + data);
768           System.out.println(
769                   "CMD [-features " + data + "]  executed successfully!");
770         }
771
772         data = aparser.getValue(ArgsParser.ANNOTATIONS, true);
773         if (data != null)
774         {
775           af.loadJalviewDataFile(data, null, null, null);
776           // System.out.println("Added " + data);
777           System.out.println(
778                   "CMD [-annotations " + data + "] executed successfully!");
779         }
780
781         if (aparser.contains(ArgsParser.SHOWOVERVIEW))
782         {
783           af.overviewMenuItem_actionPerformed(null);
784           System.out.println("CMD [showoverview] executed successfully!");
785         }
786
787         // set or clear the sortbytree flag.
788         if (aparser.contains(ArgsParser.SORTBYTREE))
789         {
790           af.getViewport().setSortByTree(true);
791           if (af.getViewport().getSortByTree())
792           {
793             System.out.println("CMD [-sortbytree] executed successfully!");
794           }
795         }
796
797         boolean doUpdateAnnotation = false;
798
799         /**
800          * we do this earlier in JalviewJS because of a complication with
801          * SHOWOVERVIEW
802          * 
803          * For now, just fixing this in JalviewJS.
804          *
805          * 
806          * @j2sIgnore
807          * 
808          */
809         {
810           if (aparser.contains(ArgsParser.NOANNOTATION)
811                   || aparser.contains(ArgsParser.NOANNOTATION2))
812           {
813             af.getViewport().setShowAnnotation(false);
814             if (!af.getViewport().isShowAnnotation())
815             {
816               doUpdateAnnotation = true;
817               System.out
818                       .println("CMD no-annotation executed successfully!");
819             }
820           }
821         }
822         if (aparser.contains(ArgsParser.NOSORTBYTREE))
823         {
824           af.getViewport().setSortByTree(false);
825           if (!af.getViewport().getSortByTree())
826           {
827             doUpdateAnnotation = true;
828             System.out
829                     .println("CMD [-nosortbytree] executed successfully!");
830           }
831         }
832         if (doUpdateAnnotation)
833         { // BH 2019.07.24
834           af.setMenusForViewport();
835           af.alignPanel.updateLayout();
836         }
837         data = aparser.getValue(ArgsParser.TREE, true);
838         if (data != null)
839         {
840           try
841           {
842             System.out.println(
843                     "CMD [-tree " + data + "] executed successfully!");
844             NewickFile nf = new NewickFile(data,
845                     AppletFormatAdapter.checkProtocol(data));
846             af.getViewport()
847                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
848           } catch (IOException ex)
849           {
850             System.err.println("Couldn't add tree " + data);
851             ex.printStackTrace(System.err);
852           }
853         }
854         // TODO - load PDB structure(s) to alignment JAL-629
855         // (associate with identical sequence in alignment, or a specified
856         // sequence)
857         if (isJavaAppletTag)
858         {
859           loadAppletParams(aparser, af);
860         }
861         else if (!isJS)
862         /**
863          * Java only
864          * 
865          * @j2sIgnore
866          */
867         {
868           if (groovyscript != null)
869           {
870             // Execute the groovy script after we've done all the rendering
871             // stuff
872             // and before any images or figures are generated.
873             System.out.println("Executing script " + groovyscript);
874             executeGroovyScript(groovyscript, af);
875             System.out.println("CMD groovy[" + groovyscript
876                     + "] executed successfully!");
877             groovyscript = null;
878           }
879         }
880         createOutputFiles(aparser, af, format);
881         while (aparser.getSize() > 0)
882         {
883           System.out.println("Unknown arg: " + aparser.nextValue());
884         }
885       }
886     }
887     AlignFrame startUpAlframe = null;
888     // We'll only open the default file if the desktop is visible.
889     // And the user
890     // ////////////////////
891
892     if (!isJS && !headless && file == null && !haveImport
893             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
894     /**
895      * Java only
896      * 
897      * @j2sIgnore
898      */
899     {
900       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
901               jalview.bin.Cache.getDefault("www.jalview.org",
902                       "http://www.jalview.org")
903                       + "/examples/exampleFile_2_7.jar");
904       if (file.equals(
905               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
906       {
907         // hardwire upgrade of the startup file
908         file.replace("_2_3.jar", "_2_7.jar");
909         // and remove the stale setting
910         jalview.bin.Cache.removeProperty("STARTUP_FILE");
911       }
912
913       protocol = DataSourceType.FILE;
914
915       if (file.indexOf("http:") > -1)
916       {
917         protocol = DataSourceType.URL;
918       }
919
920       if (file.endsWith(".jar"))
921       {
922         format = FileFormat.Jalview;
923       }
924       else
925       {
926         try
927         {
928           format = new IdentifyFile().identify(file, protocol);
929         } catch (FileFormatException e)
930         {
931           // TODO what?
932         }
933       }
934
935       startUpAlframe = new FileLoader(!headless)
936               .LoadFileWaitTillLoaded(file, protocol, format);
937       // extract groovy arguments before anything else.
938     }
939
940     // Once all other stuff is done, execute any groovy scripts (in order)
941     if (groovyscript != null)
942     {
943       if (Cache.groovyJarsPresent())
944       {
945         System.out.println("Executing script " + groovyscript);
946         executeGroovyScript(groovyscript, startUpAlframe);
947       }
948       else
949       {
950         System.err.println(
951                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
952                         + groovyscript);
953       }
954     }
955     // and finally, turn off batch mode indicator - if the desktop still exists
956     if (desktop != null)
957     {
958       if (progress != -1)
959       {
960         desktop.setProgressBar(null, progress);
961       }
962       desktop.setInBatchMode(false);
963     }
964
965     return null;
966   }
967
968   /**
969    * Writes an output file for each format (if any) specified in the
970    * command-line arguments. Supported formats are currently
971    * <ul>
972    * <li>png</li>
973    * <li>svg</li>
974    * <li>html</li>
975    * <li>biojsmsa</li>
976    * <li>imgMap</li>
977    * <li>eps</li>
978    * </ul>
979    * A format parameter should be followed by a parameter specifying the output
980    * file name. {@code imgMap} parameters should follow those for the
981    * corresponding alignment image output.
982    * 
983    * @param aparser
984    * @param af
985    * @param format
986    */
987   private void createOutputFiles(ArgsParser aparser, AlignFrame af,
988           FileFormatI format)
989   {
990     String imageName = "unnamed.png";
991     while (aparser.getSize() > 1)
992     {
993       String outputFormat = aparser.nextValue();
994       String file = aparser.nextValue();
995       // System.out.println("format " + outputFormat);
996
997       if (outputFormat.equalsIgnoreCase("png"))
998       {
999         af.createPNG(new File(file));
1000         imageName = (new File(file)).getName();
1001         System.out.println("Creating PNG image: " + file);
1002         continue;
1003       }
1004       else if (outputFormat.equalsIgnoreCase("svg"))
1005       {
1006         File imageFile = new File(file);
1007         imageName = imageFile.getName();
1008         af.createSVG(imageFile);
1009         System.out.println("Creating SVG image: " + file);
1010         continue;
1011       }
1012       else if (outputFormat.equalsIgnoreCase("html"))
1013       {
1014         File imageFile = new File(file);
1015         imageName = imageFile.getName();
1016         HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1017         htmlSVG.exportHTML(file);
1018
1019         System.out.println("Creating HTML image: " + file);
1020         continue;
1021       }
1022       else if (outputFormat.equalsIgnoreCase("biojsmsa"))
1023       {
1024         if (file == null)
1025         {
1026           System.err.println("The output html file must not be null");
1027           return;
1028         }
1029         try
1030         {
1031           BioJsHTMLOutput.refreshVersionInfo(
1032                   BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
1033         } catch (URISyntaxException e)
1034         {
1035           e.printStackTrace();
1036         }
1037         BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
1038         bjs.exportHTML(file);
1039         System.out.println("Creating BioJS MSA Viwer HTML file: " + file);
1040         continue;
1041       }
1042       else if (outputFormat.equalsIgnoreCase("imgMap"))
1043       {
1044         af.createImageMap(new File(file), imageName);
1045         System.out.println("Creating image map: " + file);
1046         continue;
1047       }
1048       else if (outputFormat.equalsIgnoreCase("eps"))
1049       {
1050         File outputFile = new File(file);
1051         System.out.println(
1052                 "Creating EPS file: " + outputFile.getAbsolutePath());
1053         af.createEPS(outputFile);
1054         continue;
1055       }
1056
1057       af.saveAlignment(file, format);
1058       if (af.isSaveAlignmentSuccessful())
1059       {
1060         System.out.println(
1061                 "Written alignment in " + format + " format to " + file);
1062       }
1063       else
1064       {
1065         System.out.println("Error writing file " + file + " in " + format
1066                 + " format!!");
1067       }
1068
1069     }
1070   }
1071
1072   private static void showUsage()
1073   {
1074     System.out.println(
1075             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1076                     + "-nodisplay\tRun Jalview without User Interface.\n"
1077                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1078                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1079                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1080                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1081                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
1082                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1083                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1084                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1085                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1086                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1087                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1088                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1089                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1090                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1091                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
1092                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1093                     + "-html FILE\tCreate HTML file from alignment.\n"
1094                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1095                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1096                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1097                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1098                     + "-noquestionnaire\tTurn off questionnaire check.\n"
1099                     + "-nonews\tTurn off check for Jalview news.\n"
1100                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1101                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1102                     // +
1103                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1104                     // after all other properties files have been read\n\t
1105                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1106                     // passed in correctly)"
1107                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1108                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1109                     // +
1110                     // "-vdoc vamsas-document\tImport vamsas document into new
1111                     // session or join existing session with same URN\n"
1112                     // + "-vses vamsas-session\tJoin session with given URN\n"
1113                     + "-groovy FILE\tExecute groovy script in FILE, after all other arguments have been processed (if FILE is the text 'STDIN' then the file will be read from STDIN)\n"
1114                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1115   }
1116
1117   private static void startUsageStats(final Desktop desktop)
1118   {
1119     /**
1120      * start a User Config prompt asking if we can log usage statistics.
1121      */
1122     PromptUserConfig prompter = new PromptUserConfig(
1123             Desktop.getDesktopPane(), "USAGESTATS",
1124             "Jalview Usage Statistics",
1125             "Do you want to help make Jalview better by enabling "
1126                     + "the collection of usage statistics with Google Analytics ?"
1127                     + "\n\n(you can enable or disable usage tracking in the preferences)",
1128             new Runnable()
1129             {
1130               @Override
1131               public void run()
1132               {
1133                 Cache.log.debug(
1134                         "Initialising googletracker for usage stats.");
1135                 Cache.initGoogleTracker();
1136                 Cache.log.debug("Tracking enabled.");
1137               }
1138             }, new Runnable()
1139             {
1140               @Override
1141               public void run()
1142               {
1143                 Cache.log.debug("Not enabling Google Tracking.");
1144               }
1145             }, null, true);
1146     desktop.addDialogThread(prompter);
1147   }
1148
1149   /**
1150    * Locate the given string as a file and pass it to the groovy interpreter.
1151    * 
1152    * @param groovyscript
1153    *          the script to execute
1154    * @param jalviewContext
1155    *          the Jalview Desktop object passed in to the groovy binding as the
1156    *          'Jalview' object.
1157    */
1158   private void executeGroovyScript(String groovyscript, AlignFrame af)
1159   {
1160     /**
1161      * for scripts contained in files
1162      */
1163     File tfile = null;
1164     /**
1165      * script's URI
1166      */
1167     URL sfile = null;
1168     if (groovyscript.trim().equals("STDIN"))
1169     {
1170       // read from stdin into a tempfile and execute it
1171       try
1172       {
1173         tfile = File.createTempFile("jalview", "groovy");
1174         PrintWriter outfile = new PrintWriter(
1175                 new OutputStreamWriter(new FileOutputStream(tfile)));
1176         BufferedReader br = new BufferedReader(
1177                 new InputStreamReader(System.in));
1178         String line = null;
1179         while ((line = br.readLine()) != null)
1180         {
1181           outfile.write(line + "\n");
1182         }
1183         br.close();
1184         outfile.flush();
1185         outfile.close();
1186
1187       } catch (Exception ex)
1188       {
1189         System.err.println("Failed to read from STDIN into tempfile "
1190                 + ((tfile == null) ? "(tempfile wasn't created)"
1191                         : tfile.toString()));
1192         ex.printStackTrace();
1193         return;
1194       }
1195       try
1196       {
1197         sfile = tfile.toURI().toURL();
1198       } catch (Exception x)
1199       {
1200         System.err.println(
1201                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1202                         + tfile.toURI());
1203         x.printStackTrace();
1204         return;
1205       }
1206     }
1207     else
1208     {
1209       try
1210       {
1211         sfile = new URI(groovyscript).toURL();
1212       } catch (Exception x)
1213       {
1214         tfile = new File(groovyscript);
1215         if (!tfile.exists())
1216         {
1217           System.err.println("File '" + groovyscript + "' does not exist.");
1218           return;
1219         }
1220         if (!tfile.canRead())
1221         {
1222           System.err.println("File '" + groovyscript + "' cannot be read.");
1223           return;
1224         }
1225         if (tfile.length() < 1)
1226         {
1227           System.err.println("File '" + groovyscript + "' is empty.");
1228           return;
1229         }
1230         try
1231         {
1232           sfile = tfile.getAbsoluteFile().toURI().toURL();
1233         } catch (Exception ex)
1234         {
1235           System.err.println("Failed to create a file URL for "
1236                   + tfile.getAbsoluteFile());
1237           return;
1238         }
1239       }
1240     }
1241     try
1242     {
1243       Map<String, Object> vbinding = new HashMap<>();
1244       vbinding.put("Jalview", this);
1245       if (af != null)
1246       {
1247         vbinding.put("currentAlFrame", af);
1248       }
1249       Binding gbinding = new Binding(vbinding);
1250       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1251       gse.run(sfile.toString(), gbinding);
1252       if ("STDIN".equals(groovyscript))
1253       {
1254         // delete temp file that we made -
1255         // only if it was successfully executed
1256         tfile.delete();
1257       }
1258     } catch (Exception e)
1259     {
1260       System.err.println("Exception Whilst trying to execute file " + sfile
1261               + " as a groovy script.");
1262       e.printStackTrace(System.err);
1263
1264     }
1265   }
1266
1267   public AlignFrame[] getAlignFrames()
1268   {
1269     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1270             : Desktop.getAlignFrames();
1271
1272   }
1273
1274   /**
1275    * Quit method delegates to Desktop.quit - unless running in headless mode
1276    * when it just ends the JVM
1277    */
1278   public void quit()
1279   {
1280     if (jsFunctionExec != null)
1281     {
1282       jsFunctionExec.tidyUp();
1283       jsFunctionExec = null;
1284     }
1285
1286     if (desktop != null)
1287     {
1288       desktop.quit();
1289     }
1290     else
1291     {
1292       System.exit(0);
1293     }
1294   }
1295
1296   /**
1297    * Handle all JalviewLite applet parameters
1298    * 
1299    * @param aparser
1300    * @param af
1301    */
1302   private void loadAppletParams(ArgsParser aparser, AlignFrame af)
1303   {
1304     JalviewApp app = new JalviewApp()
1305     {
1306
1307       // TODO BH 2019
1308       //
1309       // These are methods that are in JalviewLite that various classes call
1310       // but are not in JalviewLiteJsApi. Or, even if they are, other classes
1311       // call
1312       // them to JalviewLite directly. Some may not be necessary, but they have
1313       // to
1314       // be at least mentioned here, or the classes calling them should
1315       // reference
1316       // JalviewLite itself.
1317
1318       private boolean alignPDBStructures; // From JalviewLite; not implemented
1319
1320       private Hashtable<String, Hashtable<String, String[]>> jsmessages;
1321
1322       private Hashtable<String, int[]> jshashes;
1323
1324       @Override
1325       public String getParameter(String name)
1326       {
1327         return aparser.getAppletValue(name, null);
1328       }
1329
1330       @Override
1331       public boolean getDefaultParameter(String name, boolean def)
1332       {
1333         String stn;
1334         return ((stn = getParameter(name)) == null ? def
1335                 : "true".equalsIgnoreCase(stn));
1336       }
1337
1338       /**
1339        * Get the applet-like document base even though this is an application.
1340        */
1341       @Override
1342       public URL getDocumentBase()
1343       {
1344         return Platform.getDocumentBase();
1345       }
1346
1347       /**
1348        * Get the applet-like code base even though this is an application.
1349        */
1350       @Override
1351       public URL getCodeBase()
1352       {
1353         return Platform.getCodeBase();
1354       }
1355
1356       @Override
1357       public AlignViewportI getViewport()
1358       {
1359         return af.getViewport();
1360       }
1361
1362       /**
1363        * features
1364        * 
1365        */
1366       @Override
1367       public boolean parseFeaturesFile(String filename,
1368               DataSourceType protocol)
1369       {
1370         return af.parseFeaturesFile(filename, protocol);
1371       }
1372
1373       /**
1374        * scorefile
1375        * 
1376        */
1377       @Override
1378       public boolean loadScoreFile(String sScoreFile) throws IOException
1379       {
1380         af.loadJalviewDataFile(sScoreFile, null, null, null);
1381         return true;
1382       }
1383
1384       /**
1385        * annotations, jpredfile, jnetfile
1386        * 
1387        */
1388       @Override
1389       public void updateForAnnotations()
1390       {
1391         af.updateForAnnotations();
1392       }
1393
1394       @Override
1395       public void loadTree(NewickFile fin, String treeFile)
1396               throws IOException
1397       {
1398         // n/a -- already done by standard Jalview command line processing
1399       }
1400
1401       @Override
1402       public void setAlignPdbStructures(boolean defaultParameter)
1403       {
1404         alignPDBStructures = true;
1405       }
1406
1407       @Override
1408       public void newStructureView(PDBEntry pdb, SequenceI[] seqs,
1409               String[] chains, DataSourceType protocol)
1410       {
1411         StructureViewer.launchStructureViewer(af.alignPanel, pdb, seqs);
1412       }
1413
1414       @Override
1415       public void setFeatureGroupState(String[] groups, boolean state)
1416       {
1417         af.setFeatureGroupState(groups, state);
1418       }
1419
1420       @Override
1421       public void alignedStructureView(PDBEntry[] pdb, SequenceI[][] seqs,
1422               String[][] chains, String[] protocols)
1423       {
1424         System.err.println(
1425                 "Jalview applet interface alignedStructureView not implemented");
1426       }
1427
1428       @Override
1429       public void newFeatureSettings()
1430       {
1431         System.err.println(
1432                 "Jalview applet interface newFeatureSettings not implemented");
1433       }
1434
1435       private Vector<Runnable> jsExecQueue;
1436
1437       @Override
1438       public Vector<Runnable> getJsExecQueue(JSFunctionExec exec)
1439       {
1440         jsFunctionExec = exec;
1441         return (jsExecQueue == null ? (jsExecQueue = new Vector<>())
1442                 : jsExecQueue);
1443       }
1444
1445       @Override
1446       public AppletContext getAppletContext()
1447       {
1448         // TODO Auto-generated method stub
1449         return null;
1450       }
1451
1452       @Override
1453       public boolean isJsfallbackEnabled()
1454       {
1455         // TODO Auto-generated method stub
1456         return false;
1457       }
1458
1459       @Override
1460       public JSObject getJSObject()
1461       {
1462         // TODO Auto-generated method stub
1463         return null;
1464       }
1465
1466       @Override
1467       public StructureSelectionManagerProvider getStructureSelectionManagerProvider()
1468       {
1469         // TODO Q: what exactly is this? BH
1470         return null;
1471       }
1472
1473       @Override
1474       public void updateColoursFromMouseOver(Object source,
1475               MouseOverStructureListener mouseOverStructureListener)
1476       {
1477         // TODO Auto-generated method stub
1478
1479       }
1480
1481       @Override
1482       public Object[] getSelectionForListener(SequenceGroup seqsel,
1483               ColumnSelection colsel, HiddenColumns hidden,
1484               SelectionSource source, Object alignFrame)
1485       {
1486         return appLoader.getSelectionForListener(getCurrentAlignFrame(),
1487                 seqsel, colsel, hidden, source, alignFrame);
1488       }
1489
1490       @Override
1491       public String arrayToSeparatorList(String[] array)
1492       {
1493         return appLoader.arrayToSeparatorList(array);
1494       }
1495
1496       @Override
1497       public Hashtable<String, int[]> getJSHashes()
1498       {
1499         return (jshashes == null ? (jshashes = new Hashtable<>())
1500                 : jshashes);
1501       }
1502
1503       @Override
1504       public Hashtable<String, Hashtable<String, String[]>> getJSMessages()
1505       {
1506         return (jsmessages == null ? (jsmessages = new Hashtable<>())
1507                 : jsmessages);
1508       }
1509
1510       @Override
1511       public Object getFrameForSource(VamsasSource source)
1512       {
1513         if (source != null)
1514         {
1515           AlignFrame af;
1516           if (source instanceof jalview.gui.AlignViewport
1517                   && source == (af = getCurrentAlignFrame()).getViewport())
1518           {
1519             // should be valid if it just generated an event!
1520             return af;
1521           }
1522           // TODO: ensure that if '_af' is specified along with a handler
1523           // function, then only events from that alignFrame are sent to that
1524           // function
1525         }
1526         return null;
1527       }
1528
1529       @Override
1530       public FeatureRenderer getNewFeatureRenderer(AlignViewportI vp)
1531       {
1532         return new jalview.gui.FeatureRenderer((AlignmentPanel) vp);
1533       }
1534
1535     };
1536
1537     appLoader = new JalviewAppLoader(true);
1538     appLoader.load(app);
1539   }
1540
1541   /**
1542    * 
1543    * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences()
1544    */
1545   @Override
1546   public String getSelectedSequences()
1547   {
1548     return getSelectedSequencesFrom(getCurrentAlignFrame());
1549   }
1550
1551   /**
1552    * 
1553    * @see jalview.bin.JalviewLiteJsApi#getSelectedSequences(java.lang.String)
1554    */
1555   @Override
1556   public String getSelectedSequences(String sep)
1557   {
1558     return getSelectedSequencesFrom(getCurrentAlignFrame(), sep);
1559   }
1560
1561   /**
1562    * 
1563    * @see jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
1564    *      .AlignFrame)
1565    */
1566   @Override
1567   public String getSelectedSequencesFrom(AlignFrameI alf)
1568   {
1569     if (alf == null)
1570     {
1571       alf = getCurrentAlignFrame();
1572     }
1573     return getSelectedSequencesFrom(alf, null);
1574   }
1575
1576   /**
1577    * 
1578    * @see jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
1579    *      .AlignFrame, java.lang.String)
1580    */
1581   @Override
1582   public String getSelectedSequencesFrom(AlignFrameI alf, String sep)
1583   {
1584     if (alf == null)
1585     {
1586       alf = getCurrentAlignFrame();
1587     }
1588     return appLoader.getSelectedSequencesFrom(alf, sep);
1589   }
1590
1591   /**
1592    * 
1593    * @see jalview.bin.JalviewLiteJsApi#getSelectedSequencesFrom(jalview.appletgui
1594    *      .AlignFrame, java.lang.String)
1595    */
1596   @Override
1597   public void highlight(String sequenceId, String position,
1598           String alignedPosition)
1599   {
1600     highlightIn(null, sequenceId, position,
1601             alignedPosition);
1602   }
1603
1604   @Override
1605   public void highlightIn(AlignFrameI alf, String sequenceId,
1606           String position, String alignedPosition)
1607   {
1608     if (alf == null)
1609     {
1610       alf = getCurrentAlignFrame();
1611     }
1612     appLoader.highlightIn(alf, sequenceId, position, alignedPosition);
1613   }
1614
1615   @Override
1616   public void select(String sequenceIds, String columns)
1617   {
1618     selectIn(getCurrentAlignFrame(), sequenceIds, columns, null);
1619   }
1620
1621   @Override
1622   public void select(String sequenceIds, String columns, String sep)
1623   {
1624     selectIn(null, sequenceIds, columns, sep);
1625   }
1626
1627   @Override
1628   public void selectIn(AlignFrameI alf, String sequenceIds, String columns)
1629   {
1630     selectIn(alf, sequenceIds, columns, null);
1631   }
1632
1633   @Override
1634   public void selectIn(AlignFrameI alf, String sequenceIds, String columns,
1635           String sep)
1636   {
1637     if (alf == null)
1638     {
1639       alf = getCurrentAlignFrame();
1640     }
1641     appLoader.selectIn(alf, sequenceIds, columns, sep);
1642   }
1643
1644   @Override
1645   public String getSelectedSequencesAsAlignment(String format,
1646           String suffix)
1647   {
1648     return getSelectedSequencesAsAlignmentFrom(null,
1649             format, suffix);
1650   }
1651
1652   @Override
1653   public String getSelectedSequencesAsAlignmentFrom(AlignFrameI alf,
1654           String format, String sep)
1655   {
1656     if (alf == null)
1657     {
1658       alf = getCurrentAlignFrame();
1659     }
1660     return appLoader.getSelectedSequencesAsAlignmentFrom(alf, format, sep);
1661   }
1662
1663   @Override
1664   public String getAlignmentOrder()
1665   {
1666     return getAlignmentFrom(getCurrentAlignFrame(), null);
1667   }
1668
1669   @Override
1670   public String getAlignmentOrderFrom(AlignFrameI alf)
1671   {
1672     return getAlignmentFrom(alf, null);
1673   }
1674
1675   @Override
1676   public String getAlignmentOrderFrom(AlignFrameI alf, String sep)
1677   {
1678     if (alf == null)
1679     {
1680       alf = getCurrentAlignFrame();
1681     }
1682     return appLoader.getAlignmentOrderFrom(alf, sep);
1683   }
1684
1685   @Override
1686   public String orderBy(String order, String undoName)
1687   {
1688     return orderBy(order, undoName, null);
1689   }
1690
1691   @Override
1692   public String orderBy(String order, String undoName, String sep)
1693   {
1694     return orderAlignmentBy(getCurrentAlignFrame(), order, undoName, sep);
1695   }
1696
1697   @Override
1698   public String orderAlignmentBy(AlignFrameI alf, String order,
1699           String undoName, String sep)
1700   {
1701     if (alf == null)
1702     {
1703       alf = getCurrentAlignFrame();
1704     }
1705     return appLoader.orderAlignmentBy(alf, order, undoName, sep);
1706   }
1707
1708   @Override
1709   public String getAlignment(String format)
1710   {
1711     return getAlignmentFrom(null, format, null);
1712   }
1713
1714   @Override
1715   public String getAlignmentFrom(AlignFrameI alf, String format)
1716   {
1717     return getAlignmentFrom(alf, format, null);
1718   }
1719
1720   @Override
1721   public String getAlignment(String format, String suffix)
1722   {
1723     return getAlignmentFrom(getCurrentAlignFrame(), format, suffix);
1724   }
1725
1726   @Override
1727   public String getAlignmentFrom(AlignFrameI alf, String format,
1728           String suffix)
1729   {
1730     return appLoader.getAlignmentFrom(alf, format, suffix);
1731   }
1732
1733   @Override
1734   public void loadAnnotation(String annotation)
1735   {
1736     loadAnnotationFrom(getCurrentAlignFrame(), annotation);
1737   }
1738
1739   @Override
1740   public void loadAnnotationFrom(AlignFrameI alf, String annotation)
1741   {
1742     if (alf == null)
1743     {
1744       alf = getCurrentAlignFrame();
1745     }
1746     appLoader.loadAnnotationFrom(alf, annotation);
1747   }
1748
1749   @Override
1750   public void loadFeatures(String features, boolean autoenabledisplay)
1751   {
1752     loadFeaturesFrom(currentAlignFrame, features, autoenabledisplay);
1753   }
1754
1755   @Override
1756   public boolean loadFeaturesFrom(AlignFrameI alf, String features,
1757           boolean autoenabledisplay)
1758   {
1759     if (alf == null)
1760     {
1761       alf = getCurrentAlignFrame();
1762     }
1763     return appLoader.loadFeaturesFrom(alf, features, autoenabledisplay);
1764   }
1765
1766   @Override
1767   public String getFeatures(String format)
1768   {
1769     return getFeaturesFrom(null, format);
1770   }
1771
1772   @Override
1773   public String getFeaturesFrom(AlignFrameI alf, String format)
1774   {
1775     if (alf == null)
1776     {
1777       alf = getCurrentAlignFrame();
1778     }
1779     return appLoader.getFeaturesFrom(alf, format, true, false);
1780   }
1781
1782   @Override
1783   public String getAnnotation()
1784   {
1785     return getAnnotationFrom(null);
1786   }
1787
1788   @Override
1789   public String getAnnotationFrom(AlignFrameI alf)
1790   {
1791     if (alf == null)
1792     {
1793       alf = getCurrentAlignFrame();
1794     }
1795     return appLoader.getAnnotationFrom(alf);
1796   }
1797
1798   @Override
1799   public AlignFrameI newView()
1800   {
1801     return newViewFrom(null, null);
1802   }
1803
1804   @Override
1805   public AlignFrameI newView(String name)
1806   {
1807     return newViewFrom(null, name);
1808   }
1809
1810   @Override
1811   public AlignFrameI newViewFrom(AlignFrameI alf)
1812   {
1813     return newViewFrom(alf, null);
1814   }
1815
1816   @Override
1817   public AlignFrameI newViewFrom(AlignFrameI alf, String name)
1818   {
1819     if (alf == null)
1820     {
1821       alf = getCurrentAlignFrame();
1822     }
1823     return appLoader.newViewFrom(alf, name);
1824   }
1825
1826   @Override
1827   public AlignFrameI loadAlignment(String text, String title)
1828   {
1829     return appLoader.loadAlignment(text, AlignFrame.DEFAULT_WIDTH,
1830             AlignFrame.DEFAULT_HEIGHT, title);
1831   }
1832
1833   @Override
1834   public boolean addPdbFile(AlignFrameI alFrame, String sequenceId,
1835           String pdbEntryString, String pdbFile)
1836   {
1837     if (alFrame == null)
1838     {
1839       alFrame = getCurrentAlignFrame();
1840     }
1841     return appLoader.addPdbFile(alFrame, sequenceId, pdbEntryString,
1842             pdbFile);
1843   }
1844
1845   @Override
1846   public void scrollViewToIn(AlignFrameI alf, String topRow,
1847           String leftHandColumn)
1848   {
1849     if (alf == null)
1850     {
1851       alf = getCurrentAlignFrame();
1852     }
1853     appLoader.scrollViewToIn(alf, topRow, leftHandColumn);
1854   }
1855
1856   @Override
1857   public void scrollViewToRowIn(AlignFrameI alf, String topRow)
1858   {
1859     if (alf == null)
1860     {
1861       alf = getCurrentAlignFrame();
1862     }
1863     appLoader.scrollViewToRowIn(alf, topRow);
1864   }
1865
1866   @Override
1867   public void scrollViewToColumnIn(AlignFrameI alf, String leftHandColumn)
1868   {
1869     if (alf == null)
1870     {
1871       alf = getCurrentAlignFrame();
1872     }
1873     appLoader.scrollViewToColumnIn(alf, leftHandColumn);
1874   }
1875
1876   @Override
1877   public String getFeatureGroups()
1878   {
1879     return getFeatureGroupsOn(null);
1880   }
1881
1882   @Override
1883   public String getFeatureGroupsOn(AlignFrameI alf)
1884   {
1885     if (alf == null)
1886     {
1887       alf = getCurrentAlignFrame();
1888     }
1889     return appLoader.getFeatureGroupsOn(alf);
1890   }
1891
1892   @Override
1893   public String getFeatureGroupsOfState(boolean visible)
1894   {
1895     return getFeatureGroupsOfStateOn(null, visible);
1896   }
1897
1898   @Override
1899   public String getFeatureGroupsOfStateOn(AlignFrameI alf, boolean visible)
1900   {
1901     if (alf == null)
1902     {
1903       alf = getCurrentAlignFrame();
1904     }
1905     return appLoader.getFeatureGroupsOfStateOn(alf, visible);
1906   }
1907
1908   @Override
1909   public void setFeatureGroupState(String groups, boolean state)
1910   { // JalviewLite API
1911     setFeatureGroupStateOn(null, groups, state);
1912   }
1913
1914   @Override
1915   public void setFeatureGroupStateOn(AlignFrameI alf, String groups,
1916           boolean state)
1917   {
1918     if (alf == null)
1919     {
1920       alf = getCurrentAlignFrame();
1921     }
1922     appLoader.setFeatureGroupStateOn(alf, groups, state);
1923   }
1924
1925   @Override
1926   public String getSeparator()
1927   {
1928     return appLoader.getSeparator();
1929   }
1930
1931   @Override
1932   public void setSeparator(String separator)
1933   {
1934     appLoader.setSeparator(separator);
1935   }
1936
1937   @Override
1938   public String getJsMessage(String messageclass, String viewId)
1939   {
1940     // see http://www.jalview.org/examples/jalviewLiteJs.html
1941     return null;
1942   }
1943
1944   /**
1945    * Open a new Tree panel on the desktop statically. Params are standard (not
1946    * set by Groovy). No dialog is opened.
1947    * 
1948    * @param af
1949    * @param treeType
1950    * @param modelName
1951    * @return null, or the string "label.you_need_at_least_n_sequences" if number
1952    *         of sequences selected is inappropriate
1953    */
1954   @Override
1955   public Object openTreePanel(AlignFrame af, String treeType,
1956           String modelName)
1957   { // JalviewJS api
1958     if (af == null)
1959     {
1960       af = getCurrentAlignFrame();
1961     }
1962     return CalculationChooser.openTreePanel(af, treeType, modelName, null);
1963   }
1964
1965   /**
1966    * public static method for JalviewJS API to open a PCAPanel without
1967    * necessarily using a dialog.
1968    * 
1969    * @param af
1970    * @param modelName
1971    * @return the PCAPanel, or the string "label.you_need_at_least_n_sequences"
1972    *         if number of sequences selected is inappropriate
1973    */
1974   @Override
1975   public Object openPcaPanel(AlignFrame af, String modelName)
1976   {
1977     if (af == null)
1978     {
1979       af = getCurrentAlignFrame();
1980     }
1981     return CalculationChooser.openPcaPanel(af, modelName, null);
1982   }
1983
1984   @Override
1985   public String getSelectedSequencesAsAlignment(String format,
1986           boolean suffix)
1987   {
1988     return getSelectedSequencesAsAlignmentFrom(null,
1989             format, suffix);
1990   }
1991
1992   @Override
1993   public String getSelectedSequencesAsAlignmentFrom(AlignFrameI alf,
1994           String format, boolean suffix)
1995   {
1996     if (alf == null)
1997     {
1998       alf = getCurrentAlignFrame();
1999     }
2000     return appLoader.getSelectedSequencesAsAlignmentFrom(alf, format,
2001             "" + suffix);
2002   }
2003
2004   @Override
2005   public String arrayToSeparatorList(String[] array)
2006   {
2007     return appLoader.arrayToSeparatorList(array);
2008   }
2009
2010   @Override
2011   public String[] separatorListToArray(String list)
2012   {
2013     return appLoader.separatorListToArray(list);
2014   }
2015
2016   //// probably not needed in JalviewJS -- From when Jmol and Jalview did not
2017   //// have a direct connection?
2018
2019   @Override
2020   public void setMouseoverListener(String listener)
2021   {
2022     // TODO Auto-generated method stub
2023
2024   }
2025
2026   @Override
2027   public void setMouseoverListener(AlignFrameI af, String listener)
2028   {
2029     // TODO Auto-generated method stub
2030
2031   }
2032
2033   @Override
2034   public void setSelectionListener(String listener)
2035   {
2036     // TODO Auto-generated method stub
2037
2038   }
2039
2040   @Override
2041   public void setSelectionListener(AlignFrameI af, String listener)
2042   {
2043     // TODO Auto-generated method stub
2044
2045   }
2046
2047   @Override
2048   public void setStructureListener(String listener, String modelSet)
2049   {
2050     // TODO Auto-generated method stub
2051
2052   }
2053
2054   @Override
2055   public void removeJavascriptListener(AlignFrameI af, String listener)
2056   {
2057     // TODO Auto-generated method stub
2058
2059   }
2060
2061   @Override
2062   public void mouseOverStructure(String pdbResNum, String chain,
2063           String pdbfile)
2064   {
2065     // TODO Auto-generated method stub
2066
2067   }
2068
2069   @Override
2070   public void showOverview()
2071   {
2072     currentAlignFrame.overviewMenuItem_actionPerformed(null);
2073   }
2074
2075   public void notifyWorker(AlignCalcWorkerI worker, String status)
2076   {
2077     // System.out.println("Jalview worker " + worker.getClass().getSimpleName()
2078     // + " " + status);
2079   }
2080
2081   /**
2082    * flag to allow selected Runnable and Thread processes to run synchronously
2083    * 
2084    * JAL-3563
2085    * 
2086    */
2087   private static boolean isSynchronous = false;
2088
2089   /**
2090    * Set Jalview to run selected processes synchronously in test and headless
2091    * environments.
2092    * 
2093    * JAL-3563
2094    * 
2095    * @param b
2096    * @author Bob Hanson
2097    */
2098   public static void setSynchronous(boolean b)
2099   {
2100     isSynchronous = b;
2101   }
2102
2103   /**
2104    * Allows optional synchronous running of a Runnable that would otherwise use
2105    * SwingUtilities.invokeLater.
2106    * 
2107    * JAL-3563
2108    * 
2109    * @param t
2110    * @author Bob Hanson
2111    */
2112   public static boolean isSynchronous()
2113   {
2114     return isSynchronous;
2115   }
2116
2117   /**
2118    * Allows optional synchronous running of a Runnable that would otherwise use
2119    * SwingUtilities.invokeLater.
2120    * 
2121    * JAL-3563
2122    * 
2123    * @param t
2124    * @author Bob Hanson
2125    */
2126   public static void execRunnable(Runnable r)
2127   {
2128     if (isSynchronous())
2129     {
2130       r.run();
2131     }
2132     else
2133     {
2134       SwingUtilities.invokeLater(r);
2135     }
2136   }
2137
2138   /**
2139    * Allows optional synchronous running of a thread that would otherwise be run
2140    * using start().
2141    * 
2142    * JAL-3563
2143    * 
2144    * @param t
2145    * @author Bob Hanson
2146    */
2147   public static void execThread(Thread t)
2148   {
2149     if (isSynchronous())
2150     {
2151       t.run();
2152     }
2153     else
2154     {
2155       t.start();
2156     }
2157   }
2158
2159   /**
2160    * Get the SwingJS applet ID and combine that with the frameType
2161    * 
2162    * @param frameType
2163    *          "alignment", "desktop", etc., or null
2164    * @return
2165    */
2166   public static String getAppID(String frameType)
2167   {
2168     String id = Cache.getProperty("Info.j2sAppletID");
2169     if (id == null)
2170     {
2171       id = "jalview";
2172     }
2173     return id + (frameType == null ? "" : "-" + frameType);
2174   }
2175
2176 }