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