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