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