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