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