Refactoring of Jalview, JalviewAppLoader, JalviewApp, various
[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.Map;
41 import java.util.Vector;
42
43 import javax.swing.LookAndFeel;
44 import javax.swing.UIManager;
45
46 import com.threerings.getdown.util.LaunchUtil;
47
48 import groovy.lang.Binding;
49 import groovy.util.GroovyScriptEngine;
50 import jalview.api.AlignCalcWorkerI;
51 import jalview.api.JalviewJSApp;
52 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
53 import jalview.ext.so.SequenceOntology;
54 import jalview.gui.AlignFrame;
55 import jalview.gui.AlignViewport;
56 import jalview.gui.Desktop;
57 import jalview.gui.Preferences;
58 import jalview.gui.PromptUserConfig;
59 import jalview.io.AppletFormatAdapter;
60 import jalview.io.BioJsHTMLOutput;
61 import jalview.io.DataSourceType;
62 import jalview.io.FileFormat;
63 import jalview.io.FileFormatException;
64 import jalview.io.FileFormatI;
65 import jalview.io.FileFormats;
66 import jalview.io.FileLoader;
67 import jalview.io.HtmlSvgOutput;
68 import jalview.io.IdentifyFile;
69 import jalview.io.NewickFile;
70 import jalview.io.gff.SequenceOntologyFactory;
71 import jalview.schemes.ColourSchemeI;
72 import jalview.schemes.ColourSchemeProperty;
73 import jalview.util.MessageManager;
74 import jalview.util.Platform;
75 import jalview.ws.jws2.Jws2Discoverer;
76 //import netscape.javascript.JSObject;
77
78 /**
79  * Main class for Jalview Application <br>
80  * <br>
81  * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
82  * jalview.bin.Jalview
83  * 
84  * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
85  * jalview.bin.Jalview jalview.bin.Jalview
86  * 
87  * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
88  * embellish '*' to e.g. '*.jar')
89  * 
90  * @author $author$
91  * @version $Revision$
92  */
93 public class Jalview implements ApplicationSingletonI
94 {
95
96   // for testing those nasty messages you cannot ever find.
97   // static
98   // {
99   // System.setOut(new PrintStream(new ByteArrayOutputStream())
100   // {
101   // @Override
102   // public void println(Object o)
103   // {
104   // if (o != null)
105   // {
106   // System.err.println(o);
107   // }
108   // }
109   //
110   // });
111   // }
112   public static Jalview getInstance()
113   {
114     return (Jalview) ApplicationSingletonProvider
115             .getInstance(Jalview.class);
116   }
117
118   private Jalview()
119   {
120   }
121
122   static
123   {
124     Platform.getURLCommandArguments();
125   }
126
127   private boolean headless;
128
129   private Desktop desktop;
130
131   public AlignFrame currentAlignFrame;
132
133   public String appletResourcePath;
134
135   JalviewJSApp app; // JalviewJS-specific JavaScript interface
136   
137   private boolean noCalculation, noMenuBar, noStatus;
138
139   private boolean noAnnotation;
140
141   public boolean getStartCalculations()
142   {
143     return !noCalculation;
144   }
145
146   public boolean getAllowMenuBar()
147   {
148     return !noMenuBar;
149   }
150
151   public boolean getShowStatus()
152   {
153     return !noStatus;
154   }
155
156   public boolean getShowAnnotation()
157   {
158     return !noAnnotation;
159   }
160
161   static
162   {
163     if (!Platform.isJS())
164     /**
165      * Java only
166      * 
167      * @j2sIgnore
168      */
169     {
170       // grab all the rights we can for the JVM
171       Policy.setPolicy(new Policy()
172       {
173         @Override
174         public PermissionCollection getPermissions(CodeSource codesource)
175         {
176           Permissions perms = new Permissions();
177           perms.add(new AllPermission());
178           return (perms);
179         }
180
181         @Override
182         public void refresh()
183         {
184         }
185       });
186     }
187   }
188
189   /**
190    * keep track of feature fetching tasks.
191    * 
192    * @author JimP
193    * 
194    */
195   class FeatureFetcher
196   {
197     /*
198      * TODO: generalise to track all jalview events to orchestrate batch processing
199      * events.
200      */
201
202     private int queued = 0;
203
204     private int running = 0;
205
206     public FeatureFetcher()
207     {
208
209     }
210
211     public void addFetcher(final AlignFrame af,
212             final Vector<String> dasSources)
213     {
214       final long id = System.currentTimeMillis();
215       queued++;
216       final FeatureFetcher us = this;
217       new Thread(new Runnable()
218       {
219
220         @Override
221         public void run()
222         {
223           synchronized (us)
224           {
225             queued--;
226             running++;
227           }
228
229           af.setProgressBar(MessageManager
230                   .getString("status.das_features_being_retrived"), id);
231           af.featureSettings_actionPerformed(null);
232           af.setProgressBar(null, id);
233           synchronized (us)
234           {
235             running--;
236           }
237         }
238       }).start();
239     }
240
241     public synchronized boolean allFinished()
242     {
243       return queued == 0 && running == 0;
244     }
245
246   }
247
248   private final static boolean doPlatformLogging = false;
249
250   /**
251    * main class for Jalview application
252    * 
253    * @param args
254    *          open <em>filename</em>
255    */
256   public static void main(String[] args)
257   {
258     if (doPlatformLogging)
259     {
260       Platform.startJavaLogging();
261     }
262     getInstance().doMain(args);
263   }
264
265   /**
266    * @param args
267    */
268   void doMain(String[] args)
269   {
270
271     boolean isJS = Platform.isJS();
272     if (!isJS)
273     {
274       System.setSecurityManager(null);
275     }
276
277     System.out
278             .println("Java version: " + System.getProperty("java.version"));
279     System.out.println("Java Home: " + System.getProperty("java.home"));
280     System.out.println(System.getProperty("os.arch") + " "
281             + System.getProperty("os.name") + " "
282             + System.getProperty("os.version"));
283     String val = System.getProperty("sys.install4jVersion");
284     if (val != null)
285     {
286       System.out.println("Install4j version: " + val);
287     }
288     val = System.getProperty("installer_template_version");
289     if (val != null)
290     {
291       System.out.println("Install4j template version: " + val);
292     }
293     val = System.getProperty("launcher_version");
294     if (val != null)
295     {
296       System.out.println("Launcher version: " + val);
297     }
298
299     // report Jalview version
300     Cache.getInstance().loadBuildProperties(true);
301
302     ArgsParser aparser = new ArgsParser(args);
303     headless = false;
304
305     String usrPropsFile = aparser.getValue("props");
306
307     Cache.loadProperties(usrPropsFile); // must do this before
308
309     if (isJS)
310     {
311         app = new JalviewJSApp(aparser);
312         Preferences.setAppletDefaults();
313         Cache.loadProperties(usrPropsFile); // again, because we
314         // might be changing defaults here?
315       appletResourcePath = (String) aparser.getAppletValue("resourcepath", null, true);
316     }
317     else
318     /**
319      * Java only
320      * 
321      * @j2sIgnore
322      */
323     {
324
325       if (usrPropsFile != null)
326       {
327         System.out.println(
328                 "CMD [-props " + usrPropsFile + "] executed successfully!");
329       }
330       if (aparser.contains("help") || aparser.contains("h"))
331       {
332         showUsage();
333         System.exit(0);
334       }
335       // ?>>
336       if (aparser.contains("nodisplay") || aparser.contains("nogui")
337               || aparser.contains("headless"))
338       {
339         System.setProperty("java.awt.headless", "true");
340         headless = true;
341       }
342       // <<?
343
344       // anything else!
345
346       final String jabawsUrl = aparser.getValue(ArgsParser.JABAWS);
347       if (jabawsUrl != null)
348       {
349         try
350         {
351           Jws2Discoverer.getInstance().setPreferredUrl(jabawsUrl);
352           System.out.println(
353                   "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
354         } catch (MalformedURLException e)
355         {
356           System.err.println(
357                   "Invalid jabaws parameter: " + jabawsUrl + " ignored");
358         }
359       }
360
361     }
362     String defs = aparser.getValue(ArgsParser.SETPROP);
363     while (defs != null)
364     {
365       int p = defs.indexOf('=');
366       if (p == -1)
367       {
368         System.err.println("Ignoring invalid setprop argument : " + defs);
369       }
370       else
371       {
372         System.out.println("Executing setprop argument: " + defs);
373         if (isJS)
374         {
375           Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
376         }
377       }
378       defs = aparser.getValue("setprop");
379     }
380     if (System.getProperty("java.awt.headless") != null
381             && System.getProperty("java.awt.headless").equals("true"))
382     {
383       headless = true;
384     }
385     System.setProperty("http.agent",
386             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
387     try
388     {
389       Cache.initLogger();
390     } catch (NoClassDefFoundError error)
391     {
392       error.printStackTrace();
393       System.out.println("\nEssential logging libraries not found."
394               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
395       System.exit(0);
396     }
397
398     desktop = null;
399
400     if (!isJS)
401     /** @j2sIgnore */
402     {
403       try
404       {
405         UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
406       } catch (Exception ex)
407       {
408         System.err.println("Unexpected Look and Feel Exception");
409         ex.printStackTrace();
410       }
411       if (Platform.isMac())
412       {
413
414         LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
415                 .getLookAndFeel();
416         System.setProperty(
417                 "com.apple.mrj.application.apple.menu.about.name",
418                 "Jalview");
419         System.setProperty("apple.laf.useScreenMenuBar", "true");
420         if (lookAndFeel != null)
421         {
422           try
423           {
424             UIManager.setLookAndFeel(lookAndFeel);
425           } catch (Throwable e)
426           {
427             System.err.println(
428                     "Failed to set QuaQua look and feel: " + e.toString());
429           }
430         }
431         if (lookAndFeel == null
432                 || !(lookAndFeel.getClass().isAssignableFrom(
433                         UIManager.getLookAndFeel().getClass()))
434                 || !UIManager.getLookAndFeel().getClass().toString()
435                         .toLowerCase().contains("quaqua"))
436         {
437           try
438           {
439             System.err.println(
440                     "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
441             UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
442           } catch (Throwable e)
443           {
444             System.err.println(
445                     "Failed to reset look and feel: " + e.toString());
446           }
447         }
448       }
449     }
450     /*
451      * configure 'full' SO model if preferences say to, else use the default (full SO)
452      * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
453      */
454     boolean soDefault = !Platform.isJS();
455     if (Cache.getDefault("USE_FULL_SO", soDefault))
456     {
457       SequenceOntologyFactory.setSequenceOntology(new SequenceOntology());
458     }
459
460     if (!headless)
461     {
462       desktop = Desktop.getInstance();
463       desktop.setInBatchMode(true); // indicate we are starting up
464       try
465       {
466         JalviewTaskbar.setTaskbar(this);
467       } catch (Throwable t)
468       {
469         System.out.println("Error setting Taskbar: " + t.getMessage());
470       }
471       desktop.setVisible(true);
472
473       if (!Platform.isJS())
474       /**
475        * Java only
476        * 
477        * @j2sIgnore
478        */
479       {
480         desktop.startServiceDiscovery();
481         if (!aparser.contains("nousagestats"))
482         {
483           startUsageStats(desktop);
484         }
485         else
486         {
487           System.err.println("CMD [-nousagestats] executed successfully!");
488         }
489
490         if (!aparser.contains("noquestionnaire"))
491         {
492           String url = aparser.getValue("questionnaire");
493           if (url != null)
494           {
495             // Start the desktop questionnaire prompter with the specified
496             // questionnaire
497             Cache.log.debug("Starting questionnaire url at " + url);
498             desktop.checkForQuestionnaire(url);
499             System.out.println("CMD questionnaire[-" + url
500                     + "] executed successfully!");
501           }
502           else
503           {
504             if (Cache.getProperty("NOQUESTIONNAIRES") == null)
505             {
506               // Start the desktop questionnaire prompter with the specified
507               // questionnaire
508               // String defurl =
509               // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
510               // //
511               String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
512               Cache.log.debug(
513                       "Starting questionnaire with default url: " + defurl);
514               desktop.checkForQuestionnaire(defurl);
515             }
516           }
517         }
518         else
519         {
520           System.err
521                   .println("CMD [-noquestionnaire] executed successfully!");
522         }
523
524         if (!aparser.contains("nonews"))
525         {
526           desktop.checkForNews();
527         }
528
529         BioJsHTMLOutput.updateBioJS();
530       }
531     }
532
533     parseArguments(aparser, true);
534     
535   }
536
537   /**
538    * 
539    * @param aparser
540    * @param isStartup
541    */
542   public void parseArguments(ArgsParser aparser, boolean isStartup)
543   {
544
545     String groovyscript = null; // script to execute after all loading is
546     boolean isJS = Platform.isJS();
547     if (!isJS)
548     /** @j2sIgnore */
549     {
550       // Move any new getdown-launcher-new.jar into place over old
551       // getdown-launcher.jar
552       String appdirString = System.getProperty("getdownappdir");
553       if (appdirString != null && appdirString.length() > 0)
554       {
555         final File appdir = new File(appdirString);
556         new Thread()
557         {
558           @Override
559           public void run()
560           {
561             LaunchUtil.upgradeGetdown(
562                     new File(appdir, "getdown-launcher-old.jar"),
563                     new File(appdir, "getdown-launcher.jar"),
564                     new File(appdir, "getdown-launcher-new.jar"));
565           }
566         }.start();
567       }
568
569       // completed one way or another
570       // extract groovy argument and execute if necessary
571       groovyscript = aparser.getValue("groovy", true);
572
573     }
574
575     String file = aparser.getValue("open", true);
576
577     if (file == null && desktop == null)
578     {
579       System.out.println("No files to open!");
580       System.exit(1);
581     }
582
583     long progress = -1;
584     DataSourceType protocol = null;
585     FileLoader fileLoader = new FileLoader(!headless);
586     FileFormatI format = null;
587     // Finally, deal with the remaining input data.
588     if (file != null)
589     {
590       if (!headless)
591       {
592         desktop.setProgressBar(
593                 MessageManager
594                         .getString("status.processing_commandline_args"),
595                 progress = System.currentTimeMillis());
596       }
597       System.out.println("CMD [-open " + file + "] executed successfully!");
598
599       if (!Platform.isJS())
600       /**
601        * ignore in JavaScript -- can't just file existence - could load it?
602        * 
603        * @j2sIgnore
604        */
605       {
606         if (!file.startsWith("http://") && !file.startsWith("https://"))
607         // BH 2019 added https check for Java
608         {
609           if (!(new File(file)).exists())
610           {
611             System.out.println("Can't find " + file);
612             if (headless)
613             {
614               System.exit(1);
615             }
616           }
617         }
618       }
619       String fileFormat = (isJS ? (String) aparser.getAppletValue("format", null, true)
620               : null);
621       protocol = AppletFormatAdapter.checkProtocol(file);
622       try
623       {
624         format = (fileFormat != null
625                 ? FileFormats.getInstance().forName(fileFormat)
626                 : null);
627         if (format == null)
628         {
629           format = new IdentifyFile().identify(file, protocol);
630         }
631       } catch (FileFormatException e1)
632       {
633         // TODO ?
634       }
635
636       if (aparser.contains(ArgsParser.NOMENUBAR))
637       {
638         noMenuBar = true;
639         System.out.println("CMD [nomenu] executed successfully!");
640       }
641
642       if (aparser.contains(ArgsParser.NOSTATUS))
643       {
644         noStatus = true;
645         System.out.println("CMD [nostatus] executed successfully!");
646       }
647
648       if (aparser.contains(ArgsParser.NOANNOTATION)
649               || aparser.contains(ArgsParser.NOANNOTATION2))
650       {
651         noAnnotation = true;
652         System.out.println("CMD no-annotation executed successfully!");
653       }
654       if (aparser.contains(ArgsParser.NOCALCULATION))
655       {
656         noCalculation = true;
657         System.out.println("CMD [nocalculation] executed successfully!");
658       }
659
660       AlignFrame af = new FileLoader(!headless).LoadFileWaitTillLoaded(file,
661               protocol, format);
662       if (af == null)
663       {
664         System.out.println("error");
665       }
666       else
667       {
668
669         // JalviewLite interface for JavaScript allows second file open
670         String file2 = aparser.getValue(ArgsParser.OPEN2, true);
671         if (file2 != null)
672         {
673           protocol = AppletFormatAdapter.checkProtocol(file2);
674           try
675           {
676             format = new IdentifyFile().identify(file2, protocol);
677           } catch (FileFormatException e1)
678           {
679             // TODO ?
680           }
681           AlignFrame af2 = new FileLoader(!headless)
682                   .LoadFileWaitTillLoaded(file2, protocol, format);
683           if (af2 == null)
684           {
685             System.out.println("error");
686           }
687           else
688           {
689             AlignViewport.openLinkedAlignmentAs(af,
690                     af.getViewport().getAlignment(),
691                     af2.getViewport().getAlignment(), "",
692                     AlignViewport.SPLIT_FRAME);
693             System.out.println(
694                     "CMD [-open2 " + file2 + "] executed successfully!");
695           }
696         }
697         setCurrentAlignFrame(af);
698
699         String data = aparser.getValue(ArgsParser.COLOUR, true);
700         if (data != null)
701         {
702           data.replaceAll("%20", " ");
703
704           ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
705                   af.getViewport(), af.getViewport().getAlignment(), data);
706
707           if (cs != null)
708           {
709             System.out.println(
710                     "CMD [-color " + data + "] executed successfully!");
711           }
712           af.changeColour(cs);
713         }
714
715         // Must maintain ability to use the groups flag
716         data = aparser.getValue(ArgsParser.GROUPS, true);
717         if (data != null)
718         {
719           af.parseFeaturesFile(data,
720                   AppletFormatAdapter.checkProtocol(data));
721           // System.out.println("Added " + data);
722           System.out.println(
723                   "CMD groups[-" + data + "]  executed successfully!");
724         }
725         data = aparser.getValue(ArgsParser.FEATURES, true);
726         if (data != null)
727         {
728           af.parseFeaturesFile(data,
729                   AppletFormatAdapter.checkProtocol(data));
730           // System.out.println("Added " + data);
731           System.out.println(
732                   "CMD [-features " + data + "]  executed successfully!");
733         }
734         data = aparser.getValue(ArgsParser.ANNOTATIONS, true);
735         if (data != null)
736         {
737           af.loadJalviewDataFile(data, null, null, null);
738           // System.out.println("Added " + data);
739           System.out.println(
740                   "CMD [-annotations " + data + "] executed successfully!");
741         }
742
743         // JavaScript feature
744
745         if (aparser.contains(ArgsParser.SHOWOVERVIEW))
746         {
747           af.overviewMenuItem_actionPerformed(null);
748           System.out.println("CMD [showoverview] executed successfully!");
749         }
750
751         // set or clear the sortbytree flag.
752         if (aparser.contains(ArgsParser.SORTBYTREE))
753         {
754           af.getViewport().setSortByTree(true);
755           if (af.getViewport().getSortByTree())
756           {
757             System.out.println("CMD [-sortbytree] executed successfully!");
758           }
759         }
760
761         boolean doUpdateAnnotation = false;
762         /**
763          * we do this earlier in JalviewJS because of a complication with
764          * SHOWOVERVIEW
765          * 
766          * For now, just fixing this in JalviewJS.
767          *
768          * 
769          * @j2sIgnore
770          * 
771          */
772         {
773           if (aparser.contains(ArgsParser.NOANNOTATION)
774                   || aparser.contains(ArgsParser.NOANNOTATION2))
775           {
776             af.getViewport().setShowAnnotation(false);
777             if (!af.getViewport().isShowAnnotation())
778             {
779               doUpdateAnnotation = true;
780               System.out
781                       .println("CMD no-annotation executed successfully!");
782             }
783           }
784         }
785
786         if (aparser.contains(ArgsParser.NOSORTBYTREE))
787         {
788           af.getViewport().setSortByTree(false);
789           if (!af.getViewport().getSortByTree())
790           {
791             doUpdateAnnotation = true;
792             System.out
793                     .println("CMD [-nosortbytree] executed successfully!");
794           }
795         }
796         if (doUpdateAnnotation)
797         { // BH 2019.07.24
798           af.setMenusForViewport();
799           af.alignPanel.updateLayout();
800         }
801
802         data = aparser.getValue(ArgsParser.TREE, true);
803         if (data != null)
804         {
805           try
806           {
807             NewickFile nf = new NewickFile(data,
808                     AppletFormatAdapter.checkProtocol(data));
809             af.getViewport()
810                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
811             System.out.println(
812                     "CMD [-tree " + data + "] executed successfully!");
813           } catch (IOException ex)
814           {
815             System.err.println("Couldn't add tree " + data);
816             ex.printStackTrace(System.err);
817           }
818         }
819         // TODO - load PDB structure(s) to alignment JAL-629
820         // (associate with identical sequence in alignment, or a specified
821         // sequence)
822         
823         if (isJS)
824         {
825           app.load(af);
826         }
827         else
828         /**
829          * Java only
830          * 
831          * @j2sIgnore
832          */
833         {
834           if (groovyscript != null)
835           {
836             // Execute the groovy script after we've done all the rendering
837             // stuff
838             // and before any images or figures are generated.
839             System.out.println("Executing script " + groovyscript);
840             executeGroovyScript(groovyscript, af);
841             System.out.println("CMD groovy[" + groovyscript
842                     + "] executed successfully!");
843             groovyscript = null;
844           }
845           createOutputFiles(aparser, af, format);
846         }
847       }
848     }
849
850     AlignFrame startUpAlframe = null;
851     // We'll only open the default file if the desktop is visible.
852     // And the user
853     // ////////////////////
854
855     if (!isJS && !headless && file == null
856             && Cache.getDefault("SHOW_STARTUP_FILE", true))
857     /**
858      * Java only
859      * 
860      * @j2sIgnore
861      */
862     {
863       file = Cache.getDefault("STARTUP_FILE",
864               Cache.getDefault("www.jalview.org", "http://www.jalview.org")
865                       + "/examples/exampleFile_2_7.jar");
866       if (file.equals(
867               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
868       {
869         // hardwire upgrade of the startup file
870         file.replace("_2_3.jar", "_2_7.jar");
871         // and remove the stale setting
872         Cache.removeProperty("STARTUP_FILE");
873       }
874
875       protocol = DataSourceType.FILE;
876
877       if (file.indexOf("http:") > -1)
878       {
879         protocol = DataSourceType.URL;
880       }
881
882       if (file.endsWith(".jar"))
883       {
884         format = FileFormat.Jalview;
885       }
886       else
887       {
888         try
889         {
890           format = new IdentifyFile().identify(file, protocol);
891         } catch (FileFormatException e)
892         {
893           // TODO what?
894         }
895       }
896
897       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
898               format);
899
900     }
901
902     // extract groovy arguments before anything else.
903     // Once all other stuff is done, execute any groovy scripts (in order)
904     if (groovyscript != null)
905     {
906       if (Cache.groovyJarsPresent())
907       {
908         System.out.println("Executing script " + groovyscript);
909         executeGroovyScript(groovyscript, startUpAlframe);
910       }
911       else
912       {
913         System.err.println(
914                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
915                         + groovyscript);
916       }
917     }
918
919     // and finally, turn off batch mode indicator - if the desktop still exists
920     if (desktop != null)
921     {
922       if (progress != -1)
923       {
924         desktop.setProgressBar(null, progress);
925       }
926       desktop.setInBatchMode(false);
927     }
928
929     if (isJS && isStartup)
930     {
931       app.callInitCallback();
932     }
933   }
934   
935
936   /**
937    * Writes an output file for each format (if any) specified in the
938    * command-line arguments. Supported formats are currently
939    * <ul>
940    * <li>png</li>
941    * <li>svg</li>
942    * <li>html</li>
943    * <li>biojsmsa</li>
944    * <li>imgMap</li>
945    * <li>eps</li>
946    * </ul>
947    * A format parameter should be followed by a parameter specifying the output
948    * file name. {@code imgMap} parameters should follow those for the
949    * corresponding alignment image output.
950    * 
951    * @param aparser
952    * @param af
953    * @param format
954    */
955   private void createOutputFiles(ArgsParser aparser, AlignFrame af,
956           FileFormatI format)
957   {
958     while (aparser.getSize() >= 2)
959     {
960       String outputFormat = aparser.nextValue();
961       File imageFile;
962       String fname;
963       switch (outputFormat.toLowerCase())
964       {
965       case "png":
966         imageFile = new File(aparser.nextValue());
967         af.createPNG(imageFile);
968         System.out.println(
969                 "Creating PNG image: " + imageFile.getAbsolutePath());
970         continue;
971       case "svg":
972         imageFile = new File(aparser.nextValue());
973         af.createSVG(imageFile);
974         System.out.println(
975                 "Creating SVG image: " + imageFile.getAbsolutePath());
976         continue;
977       case "eps":
978         imageFile = new File(aparser.nextValue());
979         System.out.println(
980                 "Creating EPS file: " + imageFile.getAbsolutePath());
981         af.createEPS(imageFile);
982         continue;
983       case "biojsmsa":
984         fname = new File(aparser.nextValue()).getAbsolutePath();
985         try
986         {
987           BioJsHTMLOutput.refreshVersionInfo(
988                   BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
989         } catch (URISyntaxException e)
990         {
991           e.printStackTrace();
992         }
993         BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
994         bjs.exportHTML(fname);
995         System.out.println("Creating BioJS MSA Viwer HTML file: " + fname);
996         continue;
997       case "html":
998         fname = new File(aparser.nextValue()).getAbsolutePath();
999         HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
1000         htmlSVG.exportHTML(fname);
1001         System.out.println("Creating HTML image: " + fname);
1002         continue;
1003       case "imgmap":
1004         imageFile = new File(aparser.nextValue());
1005         af.alignPanel.makePNGImageMap(imageFile, "unnamed.png");
1006         System.out.println(
1007                 "Creating image map: " + imageFile.getAbsolutePath());
1008         continue;
1009       }
1010       if (!Platform.isJS())
1011       {
1012         // skipping outputFormat?
1013         System.out.println("Unknown arg: " + outputFormat);      
1014         fname = new File(aparser.nextValue()).getAbsolutePath();
1015         af.saveAlignment(fname, format);
1016         if (af.isSaveAlignmentSuccessful())
1017         {
1018           System.out.println(
1019                   "Written alignment in " + format + " format to " + fname);
1020         }
1021         else
1022         {
1023           System.out.println("Error writing file " + fname + " in " + format
1024                   + " format!!");
1025         }
1026       }
1027       while (aparser.getSize() > 0)
1028       {
1029         System.out.println("Unknown arg: " + aparser.nextValue());
1030       }
1031       break;
1032     }
1033
1034   }
1035
1036   private static void showUsage()
1037   {
1038     System.out.println(
1039             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
1040                     + "-nodisplay\tRun Jalview without User Interface.\n"
1041                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
1042                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
1043                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
1044                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
1045                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
1046                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
1047                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
1048                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
1049                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
1050                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
1051                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
1052                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
1053                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
1054                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
1055                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
1056                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
1057                     + "-html FILE\tCreate HTML file from alignment.\n"
1058                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
1059                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1060                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1061                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1062                     + "-noquestionnaire\tTurn off questionnaire check.\n"
1063                     + "-nonews\tTurn off check for Jalview news.\n"
1064                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1065                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1066                     // +
1067                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1068                     // after all other properties files have been read\n\t
1069                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1070                     // passed in correctly)"
1071                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1072                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1073                     + "-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"
1074                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1075   }
1076
1077   private static void startUsageStats(final Desktop desktop)
1078   {
1079     /**
1080      * start a User Config prompt asking if we can log usage statistics.
1081      */
1082     PromptUserConfig prompter = new PromptUserConfig(Desktop.getDesktopPane(),
1083             "USAGESTATS", "Jalview Usage Statistics",
1084             "Do you want to help make Jalview better by enabling "
1085                     + "the collection of usage statistics with Google Analytics ?"
1086                     + "\n\n(you can enable or disable usage tracking in the preferences)",
1087             new Runnable()
1088             {
1089               @Override
1090               public void run()
1091               {
1092                 Cache.log.debug(
1093                         "Initialising googletracker for usage stats.");
1094                 Cache.initGoogleTracker();
1095                 Cache.log.debug("Tracking enabled.");
1096               }
1097             }, new Runnable()
1098             {
1099               @Override
1100               public void run()
1101               {
1102                 Cache.log.debug("Not enabling Google Tracking.");
1103               }
1104             }, null, true);
1105     desktop.addDialogThread(prompter);
1106   }
1107
1108   /**
1109    * Locate the given string as a file and pass it to the groovy interpreter.
1110    * 
1111    * @param groovyscript
1112    *          the script to execute
1113    * @param jalviewContext
1114    *          the Jalview Desktop object passed in to the groovy binding as the
1115    *          'Jalview' object.
1116    */
1117   private void executeGroovyScript(String groovyscript, AlignFrame af)
1118   {
1119     /**
1120      * for scripts contained in files
1121      */
1122     File tfile = null;
1123     /**
1124      * script's URI
1125      */
1126     URL sfile = null;
1127     if (groovyscript.trim().equals("STDIN"))
1128     {
1129       // read from stdin into a tempfile and execute it
1130       try
1131       {
1132         tfile = File.createTempFile("jalview", "groovy");
1133         PrintWriter outfile = new PrintWriter(
1134                 new OutputStreamWriter(new FileOutputStream(tfile)));
1135         BufferedReader br = new BufferedReader(
1136                 new InputStreamReader(System.in));
1137         String line = null;
1138         while ((line = br.readLine()) != null)
1139         {
1140           outfile.write(line + "\n");
1141         }
1142         br.close();
1143         outfile.flush();
1144         outfile.close();
1145
1146       } catch (Exception ex)
1147       {
1148         System.err.println("Failed to read from STDIN into tempfile "
1149                 + ((tfile == null) ? "(tempfile wasn't created)"
1150                         : tfile.toString()));
1151         ex.printStackTrace();
1152         return;
1153       }
1154       try
1155       {
1156         sfile = tfile.toURI().toURL();
1157       } catch (Exception x)
1158       {
1159         System.err.println(
1160                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1161                         + tfile.toURI());
1162         x.printStackTrace();
1163         return;
1164       }
1165     }
1166     else
1167     {
1168       try
1169       {
1170         sfile = new URI(groovyscript).toURL();
1171       } catch (Exception x)
1172       {
1173         tfile = new File(groovyscript);
1174         if (!tfile.exists())
1175         {
1176           System.err.println("File '" + groovyscript + "' does not exist.");
1177           return;
1178         }
1179         if (!tfile.canRead())
1180         {
1181           System.err.println("File '" + groovyscript + "' cannot be read.");
1182           return;
1183         }
1184         if (tfile.length() < 1)
1185         {
1186           System.err.println("File '" + groovyscript + "' is empty.");
1187           return;
1188         }
1189         try
1190         {
1191           sfile = tfile.getAbsoluteFile().toURI().toURL();
1192         } catch (Exception ex)
1193         {
1194           System.err.println("Failed to create a file URL for "
1195                   + tfile.getAbsoluteFile());
1196           return;
1197         }
1198       }
1199     }
1200     try
1201     {
1202       Map<String, java.lang.Object> vbinding = new HashMap<>();
1203       vbinding.put("Jalview", this);
1204       if (af != null)
1205       {
1206         vbinding.put("currentAlFrame", af);
1207       }
1208       Binding gbinding = new Binding(vbinding);
1209       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1210       gse.run(sfile.toString(), gbinding);
1211       if ("STDIN".equals(groovyscript))
1212       {
1213         // delete temp file that we made -
1214         // only if it was successfully executed
1215         tfile.delete();
1216       }
1217     } catch (Exception e)
1218     {
1219       System.err.println("Exception Whilst trying to execute file " + sfile
1220               + " as a groovy script.");
1221       e.printStackTrace(System.err);
1222
1223     }
1224   }
1225
1226   public static boolean isHeadlessMode()
1227   {
1228     String isheadless = System.getProperty("java.awt.headless");
1229     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1230     {
1231       return true;
1232     }
1233     return false;
1234   }
1235
1236   public AlignFrame[] getAlignFrames()
1237   {
1238     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1239             : Desktop.getAlignFrames();
1240
1241   }
1242
1243   /**
1244    * Quit method delegates to Desktop.quit - unless running in headless mode
1245    * when it just ends the JVM
1246    */
1247   public void quit()
1248   {
1249     if (desktop != null)
1250     {
1251       desktop.quit();
1252     }
1253     else
1254     {
1255       System.exit(0);
1256     }
1257   }
1258
1259   public static AlignFrame getCurrentAlignFrame()
1260   {
1261     return Jalview.getInstance().currentAlignFrame;
1262   }
1263
1264   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1265   {
1266     Jalview.getInstance().currentAlignFrame = currentAlignFrame;
1267   }
1268
1269   
1270   /**
1271    * Get the SwingJS applet ID and combine that with the frameType
1272    * 
1273    * @param frameType
1274    *          "alignment", "desktop", etc., or null
1275    * @return
1276    */
1277   public static String getAppID(String frameType)
1278   {
1279     return (Platform.isJS() ? getInstance().app.getAppID(frameType) : null);
1280   }
1281
1282   public String doSendCallback(Object callback, Object[] data) {
1283     return (Platform.isJS() ? app.doSendCallback(callback, data) : null);
1284   }
1285
1286   public void notifyWorker(AlignCalcWorkerI worker, String status)
1287   {
1288     // System.out.println("Jalview worker " + worker.getClass().getSimpleName()
1289     // + " " + status);
1290   }
1291
1292   public Object arrayToSeparatorList(String[] seqs)
1293   {
1294     return (Platform.isJS() ? app.arrayToSeparatorList(seqs) : null);
1295   }
1296  
1297   
1298 }