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