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