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