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