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