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