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