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