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