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