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