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