cc3a4a28e0b8716cbf798604ecafd3635917be71
[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.isLinux() && ! Platform.isJS()) {
419         setMetalLookAndFeel();
420       }
421       if (Platform.isAMacAndNotJS())
422       {
423         setMacLookAndFeel();
424       }
425     }
426
427     /*
428      * configure 'full' SO model if preferences say to, else use the default (full SO)
429      * - as JS currently doesn't have OBO parsing, it must use 'Lite' version
430      */
431     boolean soDefault = !Platform.isJS();
432     if (Cache.getDefault("USE_FULL_SO", soDefault))
433     {
434       SequenceOntologyFactory.setInstance(new SequenceOntology());
435     }
436
437     if (!headless)
438     {
439       desktop = new Desktop();
440       desktop.setInBatchMode(true); // indicate we are starting up
441
442       try
443       {
444         JalviewTaskbar.setTaskbar(this);
445       } catch (Throwable t)
446       {
447         System.out.println("Error setting Taskbar: " + t.getMessage());
448       }
449
450       desktop.setVisible(true);
451
452       if (!Platform.isJS())
453       /**
454        * Java only
455        * 
456        * @j2sIgnore
457        */
458       {
459         desktop.startServiceDiscovery();
460         if (!aparser.contains("nousagestats"))
461         {
462           startUsageStats(desktop);
463         }
464         else
465         {
466           System.err.println("CMD [-nousagestats] executed successfully!");
467         }
468
469         if (!aparser.contains("noquestionnaire"))
470         {
471           String url = aparser.getValue("questionnaire");
472           if (url != null)
473           {
474             // Start the desktop questionnaire prompter with the specified
475             // questionnaire
476             Cache.log.debug("Starting questionnaire url at " + url);
477             desktop.checkForQuestionnaire(url);
478             System.out.println("CMD questionnaire[-" + url
479                     + "] executed successfully!");
480           }
481           else
482           {
483             if (Cache.getProperty("NOQUESTIONNAIRES") == null)
484             {
485               // Start the desktop questionnaire prompter with the specified
486               // questionnaire
487               // String defurl =
488               // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
489               // //
490               String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
491               Cache.log.debug(
492                       "Starting questionnaire with default url: " + defurl);
493               desktop.checkForQuestionnaire(defurl);
494             }
495           }
496         }
497         else
498         {
499           System.err
500                   .println("CMD [-noquestionnaire] executed successfully!");
501         }
502
503         if (!aparser.contains("nonews"))
504         {
505           desktop.checkForNews();
506         }
507
508         BioJsHTMLOutput.updateBioJS();
509       }
510     }
511
512     // Move any new getdown-launcher-new.jar into place over old
513     // getdown-launcher.jar
514     String appdirString = System.getProperty("getdownappdir");
515     if (appdirString != null && appdirString.length() > 0)
516     {
517       final File appdir = new File(appdirString);
518       new Thread()
519       {
520         @Override
521         public void run()
522         {
523           LaunchUtil.upgradeGetdown(
524                   new File(appdir, "getdown-launcher-old.jar"),
525                   new File(appdir, "getdown-launcher.jar"),
526                   new File(appdir, "getdown-launcher-new.jar"));
527         }
528       }.start();
529     }
530
531     String file = null, data = null;
532     FileFormatI format = null;
533     DataSourceType protocol = null;
534     FileLoader fileLoader = new FileLoader(!headless);
535
536     String groovyscript = null; // script to execute after all loading is
537     // completed one way or another
538     // extract groovy argument and execute if necessary
539     groovyscript = aparser.getValue("groovy", true);
540     file = aparser.getValue("open", true);
541
542     if (file == null && desktop == null)
543     {
544       System.out.println("No files to open!");
545       System.exit(1);
546     }
547     long progress = -1;
548     // Finally, deal with the remaining input data.
549     if (file != null)
550     {
551       if (!headless)
552       {
553         desktop.setProgressBar(
554                 MessageManager
555                         .getString("status.processing_commandline_args"),
556                 progress = System.currentTimeMillis());
557       }
558       System.out.println("CMD [-open " + file + "] executed successfully!");
559
560       if (!Platform.isJS())
561       /**
562        * ignore in JavaScript -- can't just file existence - could load it?
563        * 
564        * @j2sIgnore
565        */
566       {
567         if (!file.startsWith("http://") && !file.startsWith("https://"))
568         // BH 2019 added https check for Java
569         {
570           if (!(new File(file)).exists())
571           {
572             System.out.println("Can't find " + file);
573             if (headless)
574             {
575               System.exit(1);
576             }
577           }
578         }
579       }
580
581       protocol = AppletFormatAdapter.checkProtocol(file);
582
583       try
584       {
585         format = new IdentifyFile().identify(file, protocol);
586       } catch (FileFormatException e1)
587       {
588         // TODO ?
589       }
590
591       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
592               format);
593       if (af == null)
594       {
595         System.out.println("error");
596       }
597       else
598       {
599         setCurrentAlignFrame(af);
600         data = aparser.getValue("colour", true);
601         if (data != null)
602         {
603           data.replaceAll("%20", " ");
604
605           ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
606                   af.getViewport(), af.getViewport().getAlignment(), data);
607
608           if (cs != null)
609           {
610             System.out.println(
611                     "CMD [-color " + data + "] executed successfully!");
612           }
613           af.changeColour(cs);
614         }
615
616         // Must maintain ability to use the groups flag
617         data = aparser.getValue("groups", true);
618         if (data != null)
619         {
620           af.parseFeaturesFile(data,
621                   AppletFormatAdapter.checkProtocol(data));
622           // System.out.println("Added " + data);
623           System.out.println(
624                   "CMD groups[-" + data + "]  executed successfully!");
625         }
626         data = aparser.getValue("features", true);
627         if (data != null)
628         {
629           af.parseFeaturesFile(data,
630                   AppletFormatAdapter.checkProtocol(data));
631           // System.out.println("Added " + data);
632           System.out.println(
633                   "CMD [-features " + data + "]  executed successfully!");
634         }
635
636         data = aparser.getValue("annotations", true);
637         if (data != null)
638         {
639           af.loadJalviewDataFile(data, null, null, null);
640           // System.out.println("Added " + data);
641           System.out.println(
642                   "CMD [-annotations " + data + "] executed successfully!");
643         }
644         // set or clear the sortbytree flag.
645         if (aparser.contains("sortbytree"))
646         {
647           af.getViewport().setSortByTree(true);
648           if (af.getViewport().getSortByTree())
649           {
650             System.out.println("CMD [-sortbytree] executed successfully!");
651           }
652         }
653         if (aparser.contains("no-annotation"))
654         {
655           af.getViewport().setShowAnnotation(false);
656           if (!af.getViewport().isShowAnnotation())
657           {
658             System.out.println("CMD no-annotation executed successfully!");
659           }
660         }
661         if (aparser.contains("nosortbytree"))
662         {
663           af.getViewport().setSortByTree(false);
664           if (!af.getViewport().getSortByTree())
665           {
666             System.out
667                     .println("CMD [-nosortbytree] executed successfully!");
668           }
669         }
670         data = aparser.getValue("tree", true);
671         if (data != null)
672         {
673           try
674           {
675             System.out.println(
676                     "CMD [-tree " + data + "] executed successfully!");
677             NewickFile nf = new NewickFile(data,
678                     AppletFormatAdapter.checkProtocol(data));
679             af.getViewport()
680                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
681           } catch (IOException ex)
682           {
683             System.err.println("Couldn't add tree " + data);
684             ex.printStackTrace(System.err);
685           }
686         }
687         // TODO - load PDB structure(s) to alignment JAL-629
688         // (associate with identical sequence in alignment, or a specified
689         // sequence)
690         if (groovyscript != null)
691         {
692           // Execute the groovy script after we've done all the rendering stuff
693           // and before any images or figures are generated.
694           System.out.println("Executing script " + groovyscript);
695           executeGroovyScript(groovyscript, af);
696           System.out.println("CMD groovy[" + groovyscript
697                   + "] executed successfully!");
698           groovyscript = null;
699         }
700         String imageName = "unnamed.png";
701         while (aparser.getSize() > 1)
702         {
703           String outputFormat = aparser.nextValue();
704           file = aparser.nextValue();
705
706           if (outputFormat.equalsIgnoreCase("png"))
707           {
708             af.createPNG(new File(file));
709             imageName = (new File(file)).getName();
710             System.out.println("Creating PNG image: " + file);
711             continue;
712           }
713           else if (outputFormat.equalsIgnoreCase("svg"))
714           {
715             File imageFile = new File(file);
716             imageName = imageFile.getName();
717             af.createSVG(imageFile);
718             System.out.println("Creating SVG image: " + file);
719             continue;
720           }
721           else if (outputFormat.equalsIgnoreCase("html"))
722           {
723             File imageFile = new File(file);
724             imageName = imageFile.getName();
725             HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
726             htmlSVG.exportHTML(file);
727
728             System.out.println("Creating HTML image: " + file);
729             continue;
730           }
731           else if (outputFormat.equalsIgnoreCase("biojsmsa"))
732           {
733             if (file == null)
734             {
735               System.err.println("The output html file must not be null");
736               return;
737             }
738             try
739             {
740               BioJsHTMLOutput.refreshVersionInfo(
741                       BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
742             } catch (URISyntaxException e)
743             {
744               e.printStackTrace();
745             }
746             BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
747             bjs.exportHTML(file);
748             System.out
749                     .println("Creating BioJS MSA Viwer HTML file: " + file);
750             continue;
751           }
752           else if (outputFormat.equalsIgnoreCase("imgMap"))
753           {
754             af.createImageMap(new File(file), imageName);
755             System.out.println("Creating image map: " + file);
756             continue;
757           }
758           else if (outputFormat.equalsIgnoreCase("eps"))
759           {
760             File outputFile = new File(file);
761             System.out.println(
762                     "Creating EPS file: " + outputFile.getAbsolutePath());
763             af.createEPS(outputFile);
764             continue;
765           }
766
767           af.saveAlignment(file, format);
768           if (af.isSaveAlignmentSuccessful())
769           {
770             System.out.println("Written alignment in " + format
771                     + " format to " + file);
772           }
773           else
774           {
775             System.out.println("Error writing file " + file + " in "
776                     + format + " format!!");
777           }
778
779         }
780
781         while (aparser.getSize() > 0)
782         {
783           System.out.println("Unknown arg: " + aparser.nextValue());
784         }
785       }
786     }
787     AlignFrame startUpAlframe = null;
788     // We'll only open the default file if the desktop is visible.
789     // And the user
790     // ////////////////////
791
792     if (!Platform.isJS() && !headless && file == null
793             && Cache.getDefault("SHOW_STARTUP_FILE", true))
794     /**
795      * Java only
796      * 
797      * @j2sIgnore
798      */
799     {
800       file = Cache.getDefault("STARTUP_FILE",
801               Cache.getDefault("www.jalview.org", "http://www.jalview.org")
802                       + "/examples/exampleFile_2_7.jar");
803       if (file.equals(
804               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
805       {
806         // hardwire upgrade of the startup file
807         file.replace("_2_3.jar", "_2_7.jar");
808         // and remove the stale setting
809         Cache.removeProperty("STARTUP_FILE");
810       }
811
812       protocol = DataSourceType.FILE;
813
814       if (file.indexOf("http:") > -1)
815       {
816         protocol = DataSourceType.URL;
817       }
818
819       if (file.endsWith(".jar"))
820       {
821         format = FileFormat.Jalview;
822       }
823       else
824       {
825         try
826         {
827           format = new IdentifyFile().identify(file, protocol);
828         } catch (FileFormatException e)
829         {
830           // TODO what?
831         }
832       }
833
834       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
835               format);
836       // extract groovy arguments before anything else.
837     }
838
839     // Once all other stuff is done, execute any groovy scripts (in order)
840     if (groovyscript != null)
841     {
842       if (Cache.groovyJarsPresent())
843       {
844         System.out.println("Executing script " + groovyscript);
845         executeGroovyScript(groovyscript, startUpAlframe);
846       }
847       else
848       {
849         System.err.println(
850                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
851                         + groovyscript);
852       }
853     }
854     // and finally, turn off batch mode indicator - if the desktop still exists
855     if (desktop != null)
856     {
857       if (progress != -1)
858       {
859         desktop.setProgressBar(null, progress);
860       }
861       desktop.setInBatchMode(false);
862     }
863   }
864
865   private static boolean setCrossPlatformLookAndFeel()
866   {
867     boolean set = false;
868     try
869     {
870       UIManager.setLookAndFeel(
871               UIManager.getCrossPlatformLookAndFeelClassName());
872       set = true;
873     } catch (Exception ex)
874     {
875       System.err.println("Unexpected Look and Feel Exception");
876       ex.printStackTrace();
877     }
878     return set;
879   }
880
881   private static boolean setSystemLookAndFeel()
882   {
883     boolean set = false;
884     try
885     {
886       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
887       set = true;
888     } catch (Exception ex)
889     {
890       System.err.println("Unexpected Look and Feel Exception");
891       ex.printStackTrace();
892     }
893     return set;
894   }
895
896   private static boolean setGtkLookAndFeel()
897   {
898     boolean set = false;
899     String laf = "com.sun.java.swing.plaf.gtk.GTKLookAndFeel";
900     try
901     {
902       UIManager.setLookAndFeel(laf);
903       set = true;
904     } catch (Exception ex)
905     {
906       System.err.println("Unexpected Look and Feel Exception");
907       ex.printStackTrace();
908     }
909     return set;
910   }
911
912   private static boolean setMetalLookAndFeel()
913   {
914     boolean set = false;
915     String laf = "javax.swing.plaf.metal.MetalLookAndFeel";
916     try
917     {
918       UIManager.setLookAndFeel(laf);
919       set = true;
920     } catch (Exception ex)
921     {
922       System.err.println("Unexpected Look and Feel Exception");
923       ex.printStackTrace();
924     }
925     return set;
926   }
927
928   private static boolean setMacLookAndFeel()
929   {
930     boolean set = false;
931     LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
932             .getLookAndFeel();
933     System.setProperty("com.apple.mrj.application.apple.menu.about.name",
934             "Jalview");
935     System.setProperty("apple.laf.useScreenMenuBar", "true");
936     if (lookAndFeel != null)
937     {
938       try
939       {
940         UIManager.setLookAndFeel(lookAndFeel);
941         set = true;
942       } catch (Throwable e)
943       {
944         System.err.println(
945                 "Failed to set QuaQua look and feel: " + e.toString());
946       }
947     }
948     if (lookAndFeel == null
949             || !(lookAndFeel.getClass().isAssignableFrom(
950                     UIManager.getLookAndFeel().getClass()))
951             || !UIManager.getLookAndFeel().getClass().toString()
952                     .toLowerCase().contains("quaqua"))
953     {
954       try
955       {
956         System.err.println(
957                 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
958         UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
959         set = true;
960       } catch (Throwable e)
961       {
962         System.err
963                 .println("Failed to reset look and feel: " + e.toString());
964       }
965     }
966     return set;
967   }
968
969   private static void showUsage()
970   {
971     System.out.println(
972             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
973                     + "-nodisplay\tRun Jalview without User Interface.\n"
974                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
975                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
976                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
977                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
978                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
979                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
980                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
981                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
982                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
983                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
984                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
985                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
986                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
987                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
988                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
989                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
990                     + "-html FILE\tCreate HTML file from alignment.\n"
991                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
992                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
993                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
994                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
995                     + "-noquestionnaire\tTurn off questionnaire check.\n"
996                     + "-nonews\tTurn off check for Jalview news.\n"
997                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
998                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
999                     // +
1000                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1001                     // after all other properties files have been read\n\t
1002                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1003                     // passed in correctly)"
1004                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1005                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1006                     + "-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"
1007                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1008   }
1009
1010   private static void startUsageStats(final Desktop desktop)
1011   {
1012     /**
1013      * start a User Config prompt asking if we can log usage statistics.
1014      */
1015     PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
1016             "USAGESTATS", "Jalview Usage Statistics",
1017             "Do you want to help make Jalview better by enabling "
1018                     + "the collection of usage statistics with Google Analytics ?"
1019                     + "\n\n(you can enable or disable usage tracking in the preferences)",
1020             new Runnable()
1021             {
1022               @Override
1023               public void run()
1024               {
1025                 Cache.log.debug(
1026                         "Initialising googletracker for usage stats.");
1027                 Cache.initGoogleTracker();
1028                 Cache.log.debug("Tracking enabled.");
1029               }
1030             }, new Runnable()
1031             {
1032               @Override
1033               public void run()
1034               {
1035                 Cache.log.debug("Not enabling Google Tracking.");
1036               }
1037             }, null, true);
1038     desktop.addDialogThread(prompter);
1039   }
1040
1041   /**
1042    * Locate the given string as a file and pass it to the groovy interpreter.
1043    * 
1044    * @param groovyscript
1045    *          the script to execute
1046    * @param jalviewContext
1047    *          the Jalview Desktop object passed in to the groovy binding as the
1048    *          'Jalview' object.
1049    */
1050   private void executeGroovyScript(String groovyscript, AlignFrame af)
1051   {
1052     /**
1053      * for scripts contained in files
1054      */
1055     File tfile = null;
1056     /**
1057      * script's URI
1058      */
1059     URL sfile = null;
1060     if (groovyscript.trim().equals("STDIN"))
1061     {
1062       // read from stdin into a tempfile and execute it
1063       try
1064       {
1065         tfile = File.createTempFile("jalview", "groovy");
1066         PrintWriter outfile = new PrintWriter(
1067                 new OutputStreamWriter(new FileOutputStream(tfile)));
1068         BufferedReader br = new BufferedReader(
1069                 new InputStreamReader(System.in));
1070         String line = null;
1071         while ((line = br.readLine()) != null)
1072         {
1073           outfile.write(line + "\n");
1074         }
1075         br.close();
1076         outfile.flush();
1077         outfile.close();
1078
1079       } catch (Exception ex)
1080       {
1081         System.err.println("Failed to read from STDIN into tempfile "
1082                 + ((tfile == null) ? "(tempfile wasn't created)"
1083                         : tfile.toString()));
1084         ex.printStackTrace();
1085         return;
1086       }
1087       try
1088       {
1089         sfile = tfile.toURI().toURL();
1090       } catch (Exception x)
1091       {
1092         System.err.println(
1093                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1094                         + tfile.toURI());
1095         x.printStackTrace();
1096         return;
1097       }
1098     }
1099     else
1100     {
1101       try
1102       {
1103         sfile = new URI(groovyscript).toURL();
1104       } catch (Exception x)
1105       {
1106         tfile = new File(groovyscript);
1107         if (!tfile.exists())
1108         {
1109           System.err.println("File '" + groovyscript + "' does not exist.");
1110           return;
1111         }
1112         if (!tfile.canRead())
1113         {
1114           System.err.println("File '" + groovyscript + "' cannot be read.");
1115           return;
1116         }
1117         if (tfile.length() < 1)
1118         {
1119           System.err.println("File '" + groovyscript + "' is empty.");
1120           return;
1121         }
1122         try
1123         {
1124           sfile = tfile.getAbsoluteFile().toURI().toURL();
1125         } catch (Exception ex)
1126         {
1127           System.err.println("Failed to create a file URL for "
1128                   + tfile.getAbsoluteFile());
1129           return;
1130         }
1131       }
1132     }
1133     try
1134     {
1135       Map<String, java.lang.Object> vbinding = new HashMap<>();
1136       vbinding.put("Jalview", this);
1137       if (af != null)
1138       {
1139         vbinding.put("currentAlFrame", af);
1140       }
1141       Binding gbinding = new Binding(vbinding);
1142       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1143       gse.run(sfile.toString(), gbinding);
1144       if ("STDIN".equals(groovyscript))
1145       {
1146         // delete temp file that we made -
1147         // only if it was successfully executed
1148         tfile.delete();
1149       }
1150     } catch (Exception e)
1151     {
1152       System.err.println("Exception Whilst trying to execute file " + sfile
1153               + " as a groovy script.");
1154       e.printStackTrace(System.err);
1155
1156     }
1157   }
1158
1159   public static boolean isHeadlessMode()
1160   {
1161     String isheadless = System.getProperty("java.awt.headless");
1162     if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1163     {
1164       return true;
1165     }
1166     return false;
1167   }
1168
1169   public AlignFrame[] getAlignFrames()
1170   {
1171     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1172             : Desktop.getAlignFrames();
1173
1174   }
1175
1176   /**
1177    * Quit method delegates to Desktop.quit - unless running in headless mode
1178    * when it just ends the JVM
1179    */
1180   public void quit()
1181   {
1182     if (desktop != null)
1183     {
1184       desktop.quit();
1185     }
1186     else
1187     {
1188       System.exit(0);
1189     }
1190   }
1191
1192   public static AlignFrame getCurrentAlignFrame()
1193   {
1194     return Jalview.currentAlignFrame;
1195   }
1196
1197   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1198   {
1199     Jalview.currentAlignFrame = currentAlignFrame;
1200   }
1201 }