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