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