Jalview-JS/JAL-3253 applet param PDBFILE
[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.api.AlignViewportI;
24 import jalview.api.JalviewApp;
25 import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
26 import jalview.datamodel.PDBEntry;
27 import jalview.datamodel.SequenceI;
28 import jalview.ext.so.SequenceOntology;
29 import jalview.gui.AlignFrame;
30 import jalview.gui.Desktop;
31 import jalview.gui.Preferences;
32 import jalview.gui.PromptUserConfig;
33 import jalview.gui.StructureViewer;
34 import jalview.io.AppletFormatAdapter;
35 import jalview.io.BioJsHTMLOutput;
36 import jalview.io.DataSourceType;
37 import jalview.io.FileFormat;
38 import jalview.io.FileFormatException;
39 import jalview.io.FileFormatI;
40 import jalview.io.FileFormats;
41 import jalview.io.FileLoader;
42 import jalview.io.HtmlSvgOutput;
43 import jalview.io.IdentifyFile;
44 import jalview.io.NewickFile;
45 import jalview.io.gff.SequenceOntologyFactory;
46 import jalview.schemes.ColourSchemeI;
47 import jalview.schemes.ColourSchemeProperty;
48 import jalview.util.MessageManager;
49 import jalview.util.Platform;
50 import jalview.ws.jws2.Jws2Discoverer;
51
52 import java.io.BufferedReader;
53 import java.io.File;
54 import java.io.FileOutputStream;
55 import java.io.IOException;
56 import java.io.InputStreamReader;
57 import java.io.OutputStreamWriter;
58 import java.io.PrintWriter;
59 import java.net.MalformedURLException;
60 import java.net.URI;
61 import java.net.URISyntaxException;
62 import java.net.URL;
63 import java.security.AllPermission;
64 import java.security.CodeSource;
65 import java.security.PermissionCollection;
66 import java.security.Permissions;
67 import java.security.Policy;
68 import java.util.HashMap;
69 import java.util.Map;
70 import java.util.Vector;
71 import java.util.logging.ConsoleHandler;
72 import java.util.logging.Level;
73 import java.util.logging.Logger;
74
75 import javax.swing.LookAndFeel;
76 import javax.swing.UIManager;
77
78 import groovy.lang.Binding;
79 import groovy.util.GroovyScriptEngine;
80
81 /**
82  * Main class for Jalview Application <br>
83  * <br>
84  * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
85  * jalview.bin.Jalview
86  * 
87  * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
88  * jalview.bin.Jalview jalview.bin.Jalview
89  * 
90  * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
91  * embellish '*' to e.g. '*.jar')
92  * 
93  * @author $author$
94  * @version $Revision$
95  */
96 public class Jalview implements ApplicationSingletonI
97 {
98
99   public static Jalview getInstance()
100   {
101     return (Jalview) ApplicationSingletonProvider
102             .getInstance(Jalview.class);
103   }
104
105   private Jalview()
106   {
107   }
108
109   static
110   {
111     Platform.getURLCommandArguments();
112   }
113
114   private boolean headless;
115
116   public static boolean isHeadlessMode()
117   {
118     return getInstance().headless;
119   }
120
121   private Desktop desktop;
122
123   private AlignFrame currentAlignFrame;
124
125   public boolean isJavaAppletTag;
126
127   public String appletResourcePath;
128
129   public static AlignFrame getCurrentAlignFrame()
130   {
131     return getInstance().currentAlignFrame;
132   }
133
134   public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
135   {
136     getInstance().currentAlignFrame = currentAlignFrame;
137   }
138
139   static
140   {
141     if (!Platform.isJS())
142     /**
143      * Java only
144      * 
145      * @j2sIgnore
146      */
147     {
148       // grab all the rights we can for the JVM
149       Policy.setPolicy(new Policy()
150       {
151         @Override
152         public PermissionCollection getPermissions(CodeSource codesource)
153         {
154           Permissions perms = new Permissions();
155           perms.add(new AllPermission());
156           return (perms);
157         }
158
159         @Override
160         public void refresh()
161         {
162         }
163       });
164     }
165   }
166
167   /**
168    * keep track of feature fetching tasks.
169    * 
170    * @author JimP
171    * 
172    */
173   class FeatureFetcher
174   {
175     /*
176      * TODO: generalise to track all jalview events to orchestrate batch
177      * processing events.
178      */
179
180     private int queued = 0;
181
182     private int running = 0;
183
184     public FeatureFetcher()
185     {
186
187     }
188
189     public void addFetcher(final AlignFrame af,
190             final Vector<String> dasSources)
191     {
192       final long id = System.currentTimeMillis();
193       queued++;
194       final FeatureFetcher us = this;
195       new Thread(new Runnable()
196       {
197
198         @Override
199         public void run()
200         {
201           synchronized (us)
202           {
203             queued--;
204             running++;
205           }
206
207           af.setProgressBar(MessageManager
208                   .getString("status.das_features_being_retrived"), id);
209           af.featureSettings_actionPerformed(null);
210           af.setProgressBar(null, id);
211           synchronized (us)
212           {
213             running--;
214           }
215         }
216       }).start();
217     }
218
219     public synchronized boolean allFinished()
220     {
221       return queued == 0 && running == 0;
222     }
223
224   }
225
226   /**
227    * main class for Jalview application
228    * 
229    * @param args
230    *          open <em>filename</em>
231    */
232   public static void main(String[] args)
233   {
234     // setLogging(); // BH - for event debugging in JavaScript
235     getInstance().doMain(args);
236   }
237
238   private static void logClass(String name)
239   {
240     // BH - for event debugging in JavaScript
241     ConsoleHandler consoleHandler = new ConsoleHandler();
242     consoleHandler.setLevel(Level.ALL);
243     Logger logger = Logger.getLogger(name);
244     logger.setLevel(Level.ALL);
245     logger.addHandler(consoleHandler);
246   }
247
248   @SuppressWarnings("unused")
249   private static void setLogging()
250   {
251
252     /**
253      * @j2sIgnore
254      * 
255      */
256     {
257       System.out.println("not in js");
258     }
259
260     // BH - for event debugging in JavaScript (Java mode only)
261     if (!Platform.isJS())
262     /**
263      * Java only
264      * 
265      * @j2sIgnore
266      */
267     {
268       Logger.getLogger("").setLevel(Level.ALL);
269       logClass("java.awt.EventDispatchThread");
270       logClass("java.awt.EventQueue");
271       logClass("java.awt.Component");
272       logClass("java.awt.focus.Component");
273       logClass("java.awt.focus.DefaultKeyboardFocusManager");
274     }
275
276   }
277
278   /**
279    * @param args
280    */
281   void doMain(String[] args)
282   {
283
284     boolean isJS = Platform.isJS();
285     if (!isJS)
286     {
287       System.setSecurityManager(null);
288     }
289
290     System.out
291             .println("Java version: " + System.getProperty("java.version"));
292     System.out.println(System.getProperty("os.arch") + " "
293             + System.getProperty("os.name") + " "
294             + System.getProperty("os.version"));
295
296     ArgsParser aparser = new ArgsParser(args);
297
298     String usrPropsFile = aparser.getValue(ArgsParser.PROPS);
299     Cache.loadProperties(usrPropsFile);
300     if (isJS)
301     {
302       isJavaAppletTag = aparser.isApplet();
303       if (isJavaAppletTag)
304       {
305         Preferences.setAppletDefaults();
306         Cache.loadProperties(usrPropsFile); // again, because we
307         // might be changing defaults here?
308       }
309       System.out.println(
310               "<Applet> found: " + aparser.getValue("Info.j2sAppletID"));
311       appletResourcePath = aparser.getValue("Info.resourcePath");
312     }
313     else
314     /**
315      * Java only
316      * 
317      * @j2sIgnore
318      */
319     {
320       if (usrPropsFile != null)
321       {
322         System.out.println(
323                 "CMD [-props " + usrPropsFile + "] executed successfully!");
324       }
325
326       if (aparser.contains("help") || aparser.contains("h"))
327       {
328         showUsage();
329         System.exit(0);
330       }
331       if (aparser.contains(ArgsParser.NODISPLAY)
332               || aparser.contains(ArgsParser.NOGUI)
333               || aparser.contains(ArgsParser.HEADLESS)
334               || "true".equals(System.getProperty("java.awt.headless")))
335       {
336         headless = true;
337       }
338
339       // anything else!
340
341       final String jabawsUrl = aparser.getValue(ArgsParser.JABAWS);
342       if (jabawsUrl != null)
343       {
344         try
345         {
346           Jws2Discoverer.getInstance().setPreferredUrl(jabawsUrl);
347           System.out.println(
348                   "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
349         } catch (MalformedURLException e)
350         {
351           System.err.println(
352                   "Invalid jabaws parameter: " + jabawsUrl + " ignored");
353         }
354       }
355
356     }
357     // check for property setting
358     String defs = aparser.getValue(ArgsParser.SETPROP);
359     while (defs != null)
360     {
361       int p = defs.indexOf('=');
362       if (p == -1)
363       {
364         System.err.println("Ignoring invalid setprop argument : " + defs);
365       }
366       else
367       {
368         System.out.println("Executing setprop argument: " + defs);
369         if (isJS)
370         {
371           Cache.setProperty(defs.substring(0, p), defs.substring(p + 1));
372         }
373       }
374       defs = aparser.getValue(ArgsParser.SETPROP);
375     }
376     System.setProperty("http.agent",
377             "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
378     try
379     {
380       Cache.initLogger();
381     } catch (NoClassDefFoundError error)
382     {
383       error.printStackTrace();
384       System.out.println("\nEssential logging libraries not found."
385               + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
386       System.exit(0);
387     }
388
389     desktop = null;
390
391     try
392     {
393       UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
394     } catch (Exception ex)
395     {
396       System.err.println("Unexpected Look and Feel Exception");
397       ex.printStackTrace();
398     }
399     if (Platform.isAMacAndNotJS())
400     {
401
402       LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
403               .getLookAndFeel();
404       System.setProperty("com.apple.mrj.application.apple.menu.about.name",
405               "Jalview");
406       System.setProperty("apple.laf.useScreenMenuBar", "true");
407       if (lookAndFeel != null)
408       {
409         try
410         {
411           UIManager.setLookAndFeel(lookAndFeel);
412         } catch (Throwable e)
413         {
414           System.err.println(
415                   "Failed to set QuaQua look and feel: " + e.toString());
416         }
417       }
418       if (lookAndFeel == null
419               || !(lookAndFeel.getClass().isAssignableFrom(
420                       UIManager.getLookAndFeel().getClass()))
421               || !UIManager.getLookAndFeel().getClass().toString()
422                       .toLowerCase().contains("quaqua"))
423       {
424         try
425         {
426           System.err.println(
427                   "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
428           UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
429         } catch (Throwable e)
430         {
431           System.err.println(
432                   "Failed to reset look and feel: " + e.toString());
433         }
434       }
435     }
436
437     /*
438      * configure 'full' SO model if preferences say to, 
439      * else use the default (SO Lite)
440      */
441     if (Cache.getDefault("USE_FULL_SO", false))
442     {
443       SequenceOntologyFactory.setSequenceOntology(new SequenceOntology());
444     }
445
446     if (!headless)
447     {
448       desktop = Desktop.getInstance();
449       desktop.setInBatchMode(true); // indicate we are starting up
450       desktop.setVisible(true);
451
452       if (!isJS)
453       /**
454        * Java only
455        * 
456        * @j2sIgnore
457        */
458       {
459         desktop.startServiceDiscovery();
460         if (!aparser.contains(ArgsParser.NOUSAGESTATS))
461         {
462           startUsageStats(desktop);
463         }
464         else
465         {
466           System.err.println("CMD [-nousagestats] executed successfully!");
467         }
468
469         if (!aparser.contains(ArgsParser.NOQUESTIONNAIRE))
470         {
471           String url = aparser.getValue(ArgsParser.QUESTIONNAIRE);
472           if (url != null)
473           {
474             // Start the desktop questionnaire prompter with the specified
475             // questionnaire
476             Cache.log.debug("Starting questionnaire url at " + url);
477             desktop.checkForQuestionnaire(url);
478             System.out.println("CMD questionnaire[-" + url
479                     + "] executed successfully!");
480           }
481           else
482           {
483             if (Cache.getProperty("NOQUESTIONNAIRES") == null)
484             {
485               // Start the desktop questionnaire prompter with the specified
486               // questionnaire
487               // String defurl =
488               // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
489               // //
490               String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
491               Cache.log.debug(
492                       "Starting questionnaire with default url: " + defurl);
493               desktop.checkForQuestionnaire(defurl);
494             }
495           }
496         }
497         else
498         {
499           System.err
500                   .println("CMD [-noquestionnaire] executed successfully!");
501         }
502
503         if (!aparser.contains(ArgsParser.NONEWS))
504         {
505           desktop.checkForNews();
506         }
507
508         BioJsHTMLOutput.updateBioJS();
509       }
510     }
511
512     String data = null;
513     FileLoader fileLoader = new FileLoader(!headless);
514
515     // script to execute after all loading is
516     // completed one way or another
517     // extract groovy argument and execute if necessary
518     String groovyscript = (isJS ? null
519             : aparser.getValue(ArgsParser.GROOVY, true));
520     String file = aparser.getValue(ArgsParser.OPEN, true);
521     String file2 = (isJavaAppletTag ? aparser.getAppletValue("file2", null)
522             : null);
523     String fileFormat = (isJavaAppletTag
524             ? aparser.getAppletValue("format", null)
525             : null);
526     FileFormatI format = null;
527     DataSourceType protocol = null;
528
529     if (file == null && desktop == null)
530     {
531       System.out.println("No files to open!");
532       System.exit(1);
533     }
534     boolean haveImport = checkStartVamas(aparser);
535     // Finally, deal with the remaining input data.
536     long progress = -1;
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)
549       /**
550        * ignore in JavaScript -- can't just check file existence - could load
551        * it?
552        * 
553        * @j2sIgnore
554        */
555       {
556         if (!file.startsWith("http://") && !file.startsWith("https://"))
557         // BH 2019 added https check for Java
558         {
559           if (!(new File(file)).exists())
560           {
561             System.out.println("Can't find " + file);
562             if (headless)
563             {
564               System.exit(1);
565             }
566           }
567         }
568       }
569
570       protocol = AppletFormatAdapter.checkProtocol(file);
571
572       try
573       {
574         format = (isJavaAppletTag && fileFormat != null
575                 ? FileFormats.getInstance().forName(fileFormat)
576                 : null);
577         if (format == null)
578         {
579           format = new IdentifyFile().identify(file, protocol);
580         }
581       } catch (FileFormatException e1)
582       {
583         // TODO ?
584       }
585
586       AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
587               format);
588       if (af == null)
589       {
590         System.out.println("error");
591       }
592       else
593       {
594         setCurrentAlignFrame(af);
595
596         // TODO: file2 How to implement file2 for the applet spit screen?
597
598         data = aparser.getValue(ArgsParser.COLOUR, true);
599         if (data != null)
600         {
601           data.replaceAll("%20", " ");
602
603           ColourSchemeI cs = ColourSchemeProperty.getColourScheme(
604                   af.getViewport(), af.getViewport().getAlignment(), data);
605
606           if (cs != null)
607           {
608             System.out.println(
609                     "CMD [-color " + data + "] executed successfully!");
610           }
611           af.changeColour(cs);
612         }
613
614         // Must maintain ability to use the groups flag
615         data = aparser.getValue(ArgsParser.GROUPS, true);
616         if (data != null)
617         {
618           af.parseFeaturesFile(data,
619                   AppletFormatAdapter.checkProtocol(data));
620           // System.out.println("Added " + data);
621           System.out.println(
622                   "CMD groups[-" + data + "]  executed successfully!");
623         }
624         data = aparser.getValue(ArgsParser.FEATURES, true);
625         if (data != null)
626         {
627           af.parseFeaturesFile(data,
628                   AppletFormatAdapter.checkProtocol(data));
629           // System.out.println("Added " + data);
630           System.out.println(
631                   "CMD [-features " + data + "]  executed successfully!");
632         }
633
634         data = aparser.getValue(ArgsParser.ANNOTATIONS, true);
635         if (data != null)
636         {
637           af.loadJalviewDataFile(data, null, null, null);
638           // System.out.println("Added " + data);
639           System.out.println(
640                   "CMD [-annotations " + data + "] executed successfully!");
641         }
642         // set or clear the sortbytree flag.
643         if (aparser.contains(ArgsParser.SORTBYTREE))
644         {
645           af.getViewport().setSortByTree(true);
646           if (af.getViewport().getSortByTree())
647           {
648             System.out.println("CMD [-sortbytree] executed successfully!");
649           }
650         }
651         if (aparser.contains(ArgsParser.NOANNOTATION)
652                 || aparser.contains(ArgsParser.NOANNOTATION2))
653         {
654           af.getViewport().setShowAnnotation(false);
655           if (!af.getViewport().isShowAnnotation())
656           {
657             System.out.println("CMD no-annotation executed successfully!");
658           }
659         }
660         if (aparser.contains(ArgsParser.NOSORTBYTREE))
661         {
662           af.getViewport().setSortByTree(false);
663           if (!af.getViewport().getSortByTree())
664           {
665             System.out
666                     .println("CMD [-nosortbytree] executed successfully!");
667           }
668         }
669         data = aparser.getValue(ArgsParser.TREE, true);
670         if (data != null)
671         {
672           try
673           {
674             System.out.println(
675                     "CMD [-tree " + data + "] executed successfully!");
676             NewickFile nf = new NewickFile(data,
677                     AppletFormatAdapter.checkProtocol(data));
678             af.getViewport()
679                     .setCurrentTree(af.showNewickTree(nf, data).getTree());
680           } catch (IOException ex)
681           {
682             System.err.println("Couldn't add tree " + data);
683             ex.printStackTrace(System.err);
684           }
685         }
686         // TODO - load PDB structure(s) to alignment JAL-629
687         // (associate with identical sequence in alignment, or a specified
688         // sequence)
689         if (isJavaAppletTag)
690         {
691           loadAppletParams(aparser, af);
692         }
693         else if (!isJS)
694           /**
695            * Java only
696            * 
697            * @j2sIgnore
698            */
699         {
700           if (groovyscript != null)
701           {
702             // Execute the groovy script after we've done all the rendering stuff
703             // and before any images or figures are generated.
704             System.out.println("Executing script " + groovyscript);
705             executeGroovyScript(groovyscript, af);
706             System.out.println("CMD groovy[" + groovyscript
707                     + "] executed successfully!");
708             groovyscript = null;
709           }
710           checkOutputFile(aparser, af, format);
711           while (aparser.getSize() > 0)
712           {
713             System.out.println("Unknown arg: " + aparser.nextValue());
714           }
715         }
716       }
717     }
718     AlignFrame startUpAlframe = null;
719     // We'll only open the default file if the desktop is visible.
720     // And the user
721     // ////////////////////
722
723     if (!isJS && !headless && file == null && !haveImport
724             && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
725     /**
726      * Java only
727      * 
728      * @j2sIgnore
729      */
730     {
731       file = jalview.bin.Cache.getDefault("STARTUP_FILE",
732               jalview.bin.Cache.getDefault("www.jalview.org",
733                       "http://www.jalview.org")
734                       + "/examples/exampleFile_2_7.jar");
735       if (file.equals(
736               "http://www.jalview.org/examples/exampleFile_2_3.jar"))
737       {
738         // hardwire upgrade of the startup file
739         file.replace("_2_3.jar", "_2_7.jar");
740         // and remove the stale setting
741         jalview.bin.Cache.removeProperty("STARTUP_FILE");
742       }
743
744       protocol = DataSourceType.FILE;
745
746       if (file.indexOf("http:") > -1)
747       {
748         protocol = DataSourceType.URL;
749       }
750
751       if (file.endsWith(".jar"))
752       {
753         format = FileFormat.Jalview;
754       }
755       else
756       {
757         try
758         {
759           format = new IdentifyFile().identify(file, protocol);
760         } catch (FileFormatException e)
761         {
762           // TODO what?
763         }
764       }
765
766       startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
767               format);
768       // extract groovy arguments before anything else.
769     }
770
771     // Once all other stuff is done, execute any groovy scripts (in order)
772     if (groovyscript != null)
773     {
774       if (Cache.groovyJarsPresent())
775       {
776         System.out.println("Executing script " + groovyscript);
777         executeGroovyScript(groovyscript, startUpAlframe);
778       }
779       else
780       {
781         System.err.println(
782                 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
783                         + groovyscript);
784       }
785     }
786     // and finally, turn off batch mode indicator - if the desktop still exists
787     if (desktop != null)
788     {
789       if (progress != -1)
790       {
791         desktop.setProgressBar(null, progress);
792       }
793       desktop.setInBatchMode(false);
794     }
795   }
796
797   private boolean checkStartVamas(ArgsParser aparser)
798   {
799     String vamsasImport = aparser.getValue(ArgsParser.VDOC);
800     String vamsasSession = aparser.getValue(ArgsParser.VSESS);
801     if (vamsasImport == null && vamsasSession == null)
802     {
803       return false;
804     }
805     if (desktop == null || headless)
806     {
807       System.out.println(
808               "Headless vamsas sessions not yet supported. Sorry.");
809       System.exit(1);
810     }
811     boolean haveImport = (vamsasImport != null);
812     if (haveImport)
813     {
814       // if we have a file, start a new session and import it.
815       boolean inSession = false;
816       try
817       {
818         DataSourceType viprotocol = AppletFormatAdapter
819                 .checkProtocol(vamsasImport);
820         if (viprotocol == DataSourceType.FILE)
821         {
822           inSession = desktop.vamsasImport(new File(vamsasImport));
823         }
824         else if (viprotocol == DataSourceType.URL)
825         {
826           inSession = desktop.vamsasImport(new URL(vamsasImport));
827         }
828
829       } catch (Exception e)
830       {
831         System.err.println("Exeption when importing " + vamsasImport
832                 + " as a vamsas document.");
833         e.printStackTrace();
834       }
835       if (!inSession)
836       {
837         System.err.println("Failed to import " + vamsasImport
838                 + " as a vamsas document.");
839       }
840       else
841       {
842         System.out.println("Imported Successfully into new session "
843                 + desktop.getVamsasApplication().getCurrentSession());
844       }
845     }
846     if (vamsasSession != null)
847     {
848       if (vamsasImport != null)
849       {
850         // close the newly imported session and import the Jalview specific
851         // remnants into the new session later on.
852         desktop.vamsasStop_actionPerformed(null);
853       }
854       // now join the new session
855       try
856       {
857         if (desktop.joinVamsasSession(vamsasSession))
858         {
859           System.out.println(
860                   "Successfully joined vamsas session " + vamsasSession);
861         }
862         else
863         {
864           System.err.println("WARNING: Failed to join vamsas session "
865                   + vamsasSession);
866         }
867       } catch (Exception e)
868       {
869         System.err.println(
870                 "ERROR: Failed to join vamsas session " + vamsasSession);
871         e.printStackTrace();
872       }
873       if (vamsasImport != null)
874       {
875         // the Jalview specific remnants can now be imported into the new
876         // session at the user's leisure.
877         Cache.log.info(
878                 "Skipping Push for import of data into existing vamsas session."); // TODO:
879         // enable
880         // this
881         // when
882         // debugged
883         // desktop.getVamsasApplication().push_update();
884       }
885     }
886     return haveImport;
887   }
888
889   private void checkOutputFile(ArgsParser aparser, AlignFrame af,
890           FileFormatI format)
891   {
892     String imageName = "unnamed.png";
893     while (aparser.getSize() > 1)
894     {
895       // PNG filename
896       // SVG filename
897       // HTML filename
898       // biojsmsa filename
899       String outputFormat = aparser.nextValue();
900       String file = aparser.nextValue();
901       if (outputFormat.equalsIgnoreCase("png"))
902       {
903         af.createPNG(new File(file));
904         imageName = (new File(file)).getName();
905         System.out.println("Creating PNG image: " + file);
906         continue;
907       }
908       else if (outputFormat.equalsIgnoreCase("svg"))
909       {
910         File imageFile = new File(file);
911         imageName = imageFile.getName();
912         af.createSVG(imageFile);
913         System.out.println("Creating SVG image: " + file);
914         continue;
915       }
916       else if (outputFormat.equalsIgnoreCase("html"))
917       {
918         File imageFile = new File(file);
919         imageName = imageFile.getName();
920         HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
921         htmlSVG.exportHTML(file);
922
923         System.out.println("Creating HTML image: " + file);
924         continue;
925       }
926       else if (outputFormat.equalsIgnoreCase("biojsmsa"))
927       {
928         if (file == null)
929         {
930           System.err.println("The output html file must not be null");
931           return;
932         }
933         try
934         {
935           BioJsHTMLOutput.refreshVersionInfo(
936                   BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
937         } catch (URISyntaxException e)
938         {
939           e.printStackTrace();
940         }
941         BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
942         bjs.exportHTML(file);
943         System.out.println("Creating BioJS MSA Viwer HTML file: " + file);
944         continue;
945       }
946       else if (outputFormat.equalsIgnoreCase("imgMap"))
947       {
948         af.createImageMap(new File(file), imageName);
949         System.out.println("Creating image map: " + file);
950         continue;
951       }
952       else if (outputFormat.equalsIgnoreCase("eps"))
953       {
954         File outputFile = new File(file);
955         System.out.println(
956                 "Creating EPS file: " + outputFile.getAbsolutePath());
957         af.createEPS(outputFile);
958         continue;
959       }
960
961       af.saveAlignment(file, format);
962       if (af.isSaveAlignmentSuccessful())
963       {
964         System.out.println(
965                 "Written alignment in " + format + " format to " + file);
966       }
967       else
968       {
969         System.out.println("Error writing file " + file + " in " + format
970                 + " format!!");
971       }
972
973     }
974   }
975
976   private static void showUsage()
977   {
978     System.out.println(
979             "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
980                     + "-nodisplay\tRun Jalview without User Interface.\n"
981                     + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
982                     + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
983                     + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
984                     + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
985                     + "-features FILE\tUse the given file to mark features on the alignment.\n"
986                     + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
987                     + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
988                     + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
989                     + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
990                     + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
991                     + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
992                     + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
993                     + "-json FILE\tCreate alignment file FILE in JSON format.\n"
994                     + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
995                     + "-png FILE\tCreate PNG image FILE from alignment.\n"
996                     + "-svg FILE\tCreate SVG image FILE from alignment.\n"
997                     + "-html FILE\tCreate HTML file from alignment.\n"
998                     + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
999                     + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
1000                     + "-eps FILE\tCreate EPS file FILE from alignment.\n"
1001                     + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
1002                     + "-noquestionnaire\tTurn off questionnaire check.\n"
1003                     + "-nonews\tTurn off check for Jalview news.\n"
1004                     + "-nousagestats\tTurn off google analytics tracking for this session.\n"
1005                     + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
1006                     // +
1007                     // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
1008                     // after all other properties files have been read\n\t
1009                     // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
1010                     // passed in correctly)"
1011                     + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
1012                     + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
1013                     // +
1014                     // "-vdoc vamsas-document\tImport vamsas document into new
1015                     // session or join existing session with same URN\n"
1016                     // + "-vses vamsas-session\tJoin session with given URN\n"
1017                     + "-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"
1018                     + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
1019   }
1020
1021   private static void startUsageStats(final Desktop desktop)
1022   {
1023     /**
1024      * start a User Config prompt asking if we can log usage statistics.
1025      */
1026     PromptUserConfig prompter = new PromptUserConfig(
1027             Desktop.getDesktopPane(), "USAGESTATS",
1028             "Jalview Usage Statistics",
1029             "Do you want to help make Jalview better by enabling "
1030                     + "the collection of usage statistics with Google Analytics ?"
1031                     + "\n\n(you can enable or disable usage tracking in the preferences)",
1032             new Runnable()
1033             {
1034               @Override
1035               public void run()
1036               {
1037                 Cache.log.debug(
1038                         "Initialising googletracker for usage stats.");
1039                 Cache.initGoogleTracker();
1040                 Cache.log.debug("Tracking enabled.");
1041               }
1042             }, new Runnable()
1043             {
1044               @Override
1045               public void run()
1046               {
1047                 Cache.log.debug("Not enabling Google Tracking.");
1048               }
1049             }, null, true);
1050     desktop.addDialogThread(prompter);
1051   }
1052
1053   /**
1054    * Locate the given string as a file and pass it to the groovy interpreter.
1055    * 
1056    * @param groovyscript
1057    *          the script to execute
1058    * @param jalviewContext
1059    *          the Jalview Desktop object passed in to the groovy binding as the
1060    *          'Jalview' object.
1061    */
1062   private void executeGroovyScript(String groovyscript, AlignFrame af)
1063   {
1064     /**
1065      * for scripts contained in files
1066      */
1067     File tfile = null;
1068     /**
1069      * script's URI
1070      */
1071     URL sfile = null;
1072     if (groovyscript.trim().equals("STDIN"))
1073     {
1074       // read from stdin into a tempfile and execute it
1075       try
1076       {
1077         tfile = File.createTempFile("jalview", "groovy");
1078         PrintWriter outfile = new PrintWriter(
1079                 new OutputStreamWriter(new FileOutputStream(tfile)));
1080         BufferedReader br = new BufferedReader(
1081                 new InputStreamReader(System.in));
1082         String line = null;
1083         while ((line = br.readLine()) != null)
1084         {
1085           outfile.write(line + "\n");
1086         }
1087         br.close();
1088         outfile.flush();
1089         outfile.close();
1090
1091       } catch (Exception ex)
1092       {
1093         System.err.println("Failed to read from STDIN into tempfile "
1094                 + ((tfile == null) ? "(tempfile wasn't created)"
1095                         : tfile.toString()));
1096         ex.printStackTrace();
1097         return;
1098       }
1099       try
1100       {
1101         sfile = tfile.toURI().toURL();
1102       } catch (Exception x)
1103       {
1104         System.err.println(
1105                 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1106                         + tfile.toURI());
1107         x.printStackTrace();
1108         return;
1109       }
1110     }
1111     else
1112     {
1113       try
1114       {
1115         sfile = new URI(groovyscript).toURL();
1116       } catch (Exception x)
1117       {
1118         tfile = new File(groovyscript);
1119         if (!tfile.exists())
1120         {
1121           System.err.println("File '" + groovyscript + "' does not exist.");
1122           return;
1123         }
1124         if (!tfile.canRead())
1125         {
1126           System.err.println("File '" + groovyscript + "' cannot be read.");
1127           return;
1128         }
1129         if (tfile.length() < 1)
1130         {
1131           System.err.println("File '" + groovyscript + "' is empty.");
1132           return;
1133         }
1134         try
1135         {
1136           sfile = tfile.getAbsoluteFile().toURI().toURL();
1137         } catch (Exception ex)
1138         {
1139           System.err.println("Failed to create a file URL for "
1140                   + tfile.getAbsoluteFile());
1141           return;
1142         }
1143       }
1144     }
1145     try
1146     {
1147       Map<String, Object> vbinding = new HashMap<>();
1148       vbinding.put("Jalview", this);
1149       if (af != null)
1150       {
1151         vbinding.put("currentAlFrame", af);
1152       }
1153       Binding gbinding = new Binding(vbinding);
1154       GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1155       gse.run(sfile.toString(), gbinding);
1156       if ("STDIN".equals(groovyscript))
1157       {
1158         // delete temp file that we made -
1159         // only if it was successfully executed
1160         tfile.delete();
1161       }
1162     } catch (Exception e)
1163     {
1164       System.err.println("Exception Whilst trying to execute file " + sfile
1165               + " as a groovy script.");
1166       e.printStackTrace(System.err);
1167
1168     }
1169   }
1170
1171   public AlignFrame[] getAlignFrames()
1172   {
1173     return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1174             : Desktop.getAlignFrames();
1175
1176   }
1177
1178   /**
1179    * Quit method delegates to Desktop.quit - unless running in headless mode
1180    * when it just ends the JVM
1181    */
1182   public void quit()
1183   {
1184     if (desktop != null)
1185     {
1186       desktop.quit();
1187     }
1188     else
1189     {
1190       System.exit(0);
1191     }
1192   }
1193
1194   /**
1195    * Get the SwingJS applet ID and combine that with the frameType
1196    * 
1197    * @param frameType
1198    *          "alignment", "desktop", etc., or null
1199    * @return
1200    */
1201   public static String getAppID(String frameType)
1202   {
1203     String id = Cache.getProperty("Info.j2sAppletID");
1204     if (id == null)
1205     {
1206       id = "jalview";
1207     }
1208     return id + (frameType == null ? "" : "-" + frameType);
1209   }
1210
1211   /**
1212    * Handle all JalviewLite applet parameters
1213    * 
1214    * @param aparser
1215    * @param af
1216    */
1217   private void loadAppletParams(ArgsParser aparser, AlignFrame af)
1218   {
1219     JalviewApp app = new JalviewApp()
1220     {
1221
1222       private boolean alignPDBStructures; // From JalviewLite; not implemented
1223
1224       @Override
1225       public String getParameter(String name)
1226       {
1227         return aparser.getAppletValue(name, null);
1228       }
1229
1230       @Override
1231       public boolean getDefaultParameter(String name, boolean def)
1232       {
1233         String stn;
1234         return ((stn = getParameter(name)) == null ? def
1235                 : "true".equalsIgnoreCase(stn));
1236       }
1237
1238       /**
1239        * Get the applet-like document base even though this is an application.
1240        */
1241       @Override
1242       public URL getDocumentBase()
1243       {
1244         return Platform.getDocumentBase();
1245       }
1246
1247       /**
1248        * Get the applet-like code base even though this is an application.
1249        */
1250       @Override
1251       public URL getCodeBase()
1252       {
1253         return Platform.getCodeBase();
1254       }
1255
1256       @Override
1257       public AlignViewportI getViewport()
1258       {
1259         return af.getViewport();
1260       }
1261
1262       /**
1263        * features
1264        * 
1265        */
1266       @Override
1267       public boolean parseFeaturesFile(String filename,
1268               DataSourceType protocol)
1269       {
1270         return af.parseFeaturesFile(filename, protocol);
1271       }
1272
1273       /**
1274        * scorefile
1275        * 
1276        */
1277       @Override
1278       public boolean loadScoreFile(String sScoreFile) throws IOException
1279       {
1280         af.loadJalviewDataFile(sScoreFile, null,
1281                 null, null);
1282         return true;
1283       }
1284
1285       /**
1286        * annotations, jpredfile, jnetfile
1287        * 
1288        */
1289       @Override
1290       public void updateForAnnotations()
1291       {
1292         af.updateForAnnotations();
1293       }
1294
1295       @Override
1296       public void loadTree(NewickFile fin, String treeFile)
1297               throws IOException
1298       {
1299         // n/a -- already done by standard Jalview command line processing
1300       }
1301
1302       @Override
1303       public void setAlignPdbStructures(boolean defaultParameter)
1304       {
1305         alignPDBStructures = true;
1306       }
1307
1308       @Override
1309       public void newStructureView(PDBEntry pdb, SequenceI[] seqs,
1310               String[] chains, DataSourceType protocol)
1311       {
1312         StructureViewer.launchStructureViewer(af.alignPanel, pdb, seqs);
1313       }
1314
1315       @Override
1316       public void setFeatureGroupState(String[] groups, boolean state)
1317       {
1318         af.setFeatureGroupState(groups, state);
1319       }
1320
1321       @Override
1322       public void alignedStructureView(PDBEntry[] pdb, SequenceI[][] seqs,
1323               String[][] chains, String[] protocols)
1324       {
1325         System.err.println(
1326                 "Jalview applet interface alignedStructureView not implemented");
1327       }
1328
1329       @Override
1330       public void newFeatureSettings()
1331       {
1332         System.err.println(
1333                 "Jalview applet interface newFeatureSettings not implemented");
1334       }
1335
1336     };
1337
1338     new JalviewAppLoader(true).load(app);
1339
1340   }
1341
1342 }