2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
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.
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.
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.
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;
44 import java.awt.event.ActionEvent;
45 import java.awt.event.ActionListener;
46 import java.io.BufferedReader;
48 import java.io.FileOutputStream;
49 import java.io.IOException;
50 import java.io.InputStreamReader;
51 import java.io.OutputStreamWriter;
52 import java.io.PrintWriter;
53 import java.net.MalformedURLException;
55 import java.net.URISyntaxException;
57 import java.security.AllPermission;
58 import java.security.CodeSource;
59 import java.security.PermissionCollection;
60 import java.security.Permissions;
61 import java.security.Policy;
62 import java.util.HashMap;
64 import java.util.Vector;
65 import java.util.logging.ConsoleHandler;
66 import java.util.logging.Level;
67 import java.util.logging.Logger;
69 import javax.swing.LookAndFeel;
70 import javax.swing.Timer;
71 import javax.swing.UIManager;
73 import groovy.lang.Binding;
74 import groovy.util.GroovyScriptEngine;
77 * Main class for Jalview Application <br>
79 * start with: java -classpath "$PATH_TO_LIB$/*:$PATH_TO_CLASSES$" \
82 * or on Windows: java -classpath "$PATH_TO_LIB$/*;$PATH_TO_CLASSES$" \
83 * jalview.bin.Jalview jalview.bin.Jalview
85 * (ensure -classpath arg is quoted to avoid shell expansion of '*' and do not
86 * embellish '*' to e.g. '*.jar')
96 * // find first query parameter (if any) that doesn't start with j2s
97 * // and set as space-delimited arguments to Jalview main
98 * hr = decodeURI(document.location.href);
99 * pos = hr.indexOf("?");
102 * q = hr.substring(pos+1);
103 * args = q.split("&");
104 * for (i = 0 ; i < args.length; i++)
107 * if (!arg1.startsWith("j2s"))
109 * thisApplet.__Info.args = arg1.split(" ");
117 * singleton instance of this class
119 private static Jalview instance;
121 private Desktop desktop;
123 public static AlignFrame currentAlignFrame;
127 if (!Platform.isJS())
129 // grab all the rights we can for the JVM
130 Policy.setPolicy(new Policy()
133 public PermissionCollection getPermissions(CodeSource codesource)
135 Permissions perms = new Permissions();
136 perms.add(new AllPermission());
141 public void refresh()
149 * keep track of feature fetching tasks.
157 * TODO: generalise to track all jalview events to orchestrate batch
161 private int queued = 0;
163 private int running = 0;
165 public FeatureFetcher()
170 public void addFetcher(final AlignFrame af,
171 final Vector<String> dasSources)
173 final long id = System.currentTimeMillis();
175 final FeatureFetcher us = this;
176 new Thread(new Runnable()
188 af.setProgressBar(MessageManager
189 .getString("status.das_features_being_retrived"), id);
190 af.featureSettings_actionPerformed(null);
191 af.setProgressBar(null, id);
200 public synchronized boolean allFinished()
202 return queued == 0 && running == 0;
207 public static Jalview getInstance()
213 * main class for Jalview application
216 * open <em>filename</em>
218 public static void main(String[] args)
220 // setLogging(); // BH - for event debugging in JavaScript
221 instance = new Jalview();
222 instance.doMain(args);
225 private static void logClass(String name)
227 // BH - for event debugging in JavaScript
228 ConsoleHandler consoleHandler = new ConsoleHandler();
229 consoleHandler.setLevel(Level.ALL);
230 Logger logger = Logger.getLogger(name);
231 logger.setLevel(Level.ALL);
232 logger.addHandler(consoleHandler);
235 @SuppressWarnings("unused")
236 private static void setLogging()
238 // BH - for event debugging in JavaScript (Java mode only)
239 if (!(/** @j2sNative true ||*/false))
241 Logger.getLogger("").setLevel(Level.ALL);
242 logClass("java.awt.EventDispatchThread");
243 logClass("java.awt.EventQueue");
244 logClass("java.awt.Component");
245 logClass("java.awt.focus.Component");
246 logClass("java.awt.focus.DefaultKeyboardFocusManager");
257 void doMain(String[] args)
260 if (!Platform.isJS())
262 System.setSecurityManager(null);
266 .println("Java version: " + System.getProperty("java.version"));
267 System.out.println(System.getProperty("os.arch") + " "
268 + System.getProperty("os.name") + " "
269 + System.getProperty("os.version"));
271 ArgsParser aparser = new ArgsParser(args);
272 boolean headless = false;
274 String usrPropsFile = aparser.getValue("props");
275 Cache.loadProperties(usrPropsFile); // must do this before
276 if (usrPropsFile != null)
279 "CMD [-props " + usrPropsFile + "] executed successfully!");
283 * BH 2018 ignoring this section for JS
288 if (aparser.contains("help") || aparser.contains("h"))
293 if (aparser.contains("nodisplay") || aparser.contains("nogui")
294 || aparser.contains("headless"))
296 System.setProperty("java.awt.headless", "true");
301 final String jabawsUrl = aparser.getValue("jabaws");
302 if (jabawsUrl != null)
306 Jws2Discoverer.getDiscoverer().setPreferredUrl(jabawsUrl);
308 "CMD [-jabaws " + jabawsUrl + "] executed successfully!");
309 } catch (MalformedURLException e)
312 "Invalid jabaws parameter: " + jabawsUrl + " ignored");
317 String defs = aparser.getValue("setprop");
320 int p = defs.indexOf('=');
323 System.err.println("Ignoring invalid setprop argument : " + defs);
327 System.out.println("Executing setprop argument: " + defs);
330 Cache.setProperty(defs.substring(0,p), defs.substring(p+1));
333 defs = aparser.getValue("setprop");
335 if (System.getProperty("java.awt.headless") != null
336 && System.getProperty("java.awt.headless").equals("true"))
340 System.setProperty("http.agent",
341 "Jalview Desktop/" + Cache.getDefault("VERSION", "Unknown"));
345 } catch (NoClassDefFoundError error)
347 error.printStackTrace();
348 System.out.println("\nEssential logging libraries not found."
349 + "\nUse: java -classpath \"$PATH_TO_LIB$/*:$PATH_TO_CLASSES$\" jalview.bin.Jalview");
357 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
358 } catch (Exception ex)
360 System.err.println("Unexpected Look and Feel Exception");
361 ex.printStackTrace();
363 if (Platform.isAMacAndNotJS())
366 LookAndFeel lookAndFeel = ch.randelshofer.quaqua.QuaquaManager
368 System.setProperty("com.apple.mrj.application.apple.menu.about.name",
370 System.setProperty("apple.laf.useScreenMenuBar", "true");
371 if (lookAndFeel != null)
375 UIManager.setLookAndFeel(lookAndFeel);
376 } catch (Throwable e)
379 "Failed to set QuaQua look and feel: " + e.toString());
382 if (lookAndFeel == null || !(lookAndFeel.getClass()
383 .isAssignableFrom(UIManager.getLookAndFeel().getClass()))
384 || !UIManager.getLookAndFeel().getClass().toString()
385 .toLowerCase().contains("quaqua"))
390 "Quaqua LaF not available on this plaform. Using VAqua(4).\nSee https://issues.jalview.org/browse/JAL-2976");
391 UIManager.setLookAndFeel("org.violetlib.aqua.AquaLookAndFeel");
392 } catch (Throwable e)
395 "Failed to reset look and feel: " + e.toString());
401 * configure 'full' SO model if preferences say to,
402 * else use the default (SO Lite)
404 if (Cache.getDefault("USE_FULL_SO", false))
406 SequenceOntologyFactory.setInstance(new SequenceOntology());
411 desktop = new Desktop()
415 // protected void processEvent(AWTEvent e) {
416 // System.out.println("Jalview.java " + e);
417 // super.processEvent(e);
421 desktop.setInBatchMode(true); // indicate we are starting up
422 desktop.setVisible(true);
425 * BH 2018 JS bypass this section
431 desktop.startServiceDiscovery();
432 if (!aparser.contains("nousagestats"))
434 startUsageStats(desktop);
438 System.err.println("CMD [-nousagestats] executed successfully!");
441 if (!aparser.contains("noquestionnaire"))
443 String url = aparser.getValue("questionnaire");
446 // Start the desktop questionnaire prompter with the specified
448 Cache.log.debug("Starting questionnaire url at " + url);
449 desktop.checkForQuestionnaire(url);
450 System.out.println("CMD questionnaire[-" + url
451 + "] executed successfully!");
455 if (Cache.getProperty("NOQUESTIONNAIRES") == null)
457 // Start the desktop questionnaire prompter with the specified
460 // "http://anaplog.compbio.dundee.ac.uk/cgi-bin/questionnaire.pl";
462 String defurl = "http://www.jalview.org/cgi-bin/questionnaire.pl";
464 "Starting questionnaire with default url: " + defurl);
465 desktop.checkForQuestionnaire(defurl);
472 .println("CMD [-noquestionnaire] executed successfully!");
475 if (!aparser.contains("nonews"))
477 desktop.checkForNews();
480 BioJsHTMLOutput.updateBioJS();
484 String file = null, data = null;
485 FileFormatI format = null;
486 DataSourceType protocol = null;
487 FileLoader fileLoader = new FileLoader(!headless);
488 Vector<String> getFeatures = null; // vector of das source nicknames to
492 String groovyscript = null; // script to execute after all loading is
493 // completed one way or another
494 // extract groovy argument and execute if necessary
495 groovyscript = aparser.getValue("groovy", true);
496 file = aparser.getValue("open", true);
498 if (file == null && desktop == null)
500 System.out.println("No files to open!");
503 String vamsasImport = aparser.getValue("vdoc");
504 String vamsasSession = aparser.getValue("vsess");
505 if (vamsasImport != null || vamsasSession != null)
507 if (desktop == null || headless)
510 "Headless vamsas sessions not yet supported. Sorry.");
513 // if we have a file, start a new session and import it.
514 boolean inSession = false;
515 if (vamsasImport != null)
519 DataSourceType viprotocol = AppletFormatAdapter
520 .checkProtocol(vamsasImport);
521 if (viprotocol == DataSourceType.FILE)
523 inSession = desktop.vamsasImport(new File(vamsasImport));
525 else if (viprotocol == DataSourceType.URL)
527 inSession = desktop.vamsasImport(new URL(vamsasImport));
530 } catch (Exception e)
532 System.err.println("Exeption when importing " + vamsasImport
533 + " as a vamsas document.");
538 System.err.println("Failed to import " + vamsasImport
539 + " as a vamsas document.");
543 System.out.println("Imported Successfully into new session "
544 + desktop.getVamsasApplication().getCurrentSession());
547 if (vamsasSession != null)
549 if (vamsasImport != null)
551 // close the newly imported session and import the Jalview specific
552 // remnants into the new session later on.
553 desktop.vamsasStop_actionPerformed(null);
555 // now join the new session
558 if (desktop.joinVamsasSession(vamsasSession))
561 "Successfully joined vamsas session " + vamsasSession);
565 System.err.println("WARNING: Failed to join vamsas session "
568 } catch (Exception e)
571 "ERROR: Failed to join vamsas session " + vamsasSession);
574 if (vamsasImport != null)
576 // the Jalview specific remnants can now be imported into the new
577 // session at the user's leisure.
579 "Skipping Push for import of data into existing vamsas session."); // TODO:
584 // desktop.getVamsasApplication().push_update();
589 // Finally, deal with the remaining input data.
594 desktop.setProgressBar(
596 .getString("status.processing_commandline_args"),
597 progress = System.currentTimeMillis());
599 System.out.println("CMD [-open " + file + "] executed successfully!");
601 if (!Platform.isJS() && !file.startsWith("http://"))
603 if (!(new File(file)).exists())
605 System.out.println("Can't find " + file);
613 protocol = AppletFormatAdapter.checkProtocol(file);
617 format = new IdentifyFile().identify(file, protocol);
618 } catch (FileFormatException e1)
623 AlignFrame af = fileLoader.LoadFileWaitTillLoaded(file, protocol,
627 System.out.println("error");
631 setCurrentAlignFrame(af);
632 data = aparser.getValue("colour", true);
635 data.replaceAll("%20", " ");
637 ColourSchemeI cs = ColourSchemeProperty
638 .getColourScheme(af.getViewport().getAlignment(), data);
643 "CMD [-color " + data + "] executed successfully!");
648 // Must maintain ability to use the groups flag
649 data = aparser.getValue("groups", true);
652 af.parseFeaturesFile(data,
653 AppletFormatAdapter.checkProtocol(data));
654 // System.out.println("Added " + data);
656 "CMD groups[-" + data + "] executed successfully!");
658 data = aparser.getValue("features", true);
661 af.parseFeaturesFile(data,
662 AppletFormatAdapter.checkProtocol(data));
663 // System.out.println("Added " + data);
665 "CMD [-features " + data + "] executed successfully!");
668 data = aparser.getValue("annotations", true);
671 af.loadJalviewDataFile(data, null, null, null);
672 // System.out.println("Added " + data);
674 "CMD [-annotations " + data + "] executed successfully!");
676 // set or clear the sortbytree flag.
677 if (aparser.contains("sortbytree"))
679 af.getViewport().setSortByTree(true);
680 if (af.getViewport().getSortByTree())
682 System.out.println("CMD [-sortbytree] executed successfully!");
685 if (aparser.contains("no-annotation"))
687 af.getViewport().setShowAnnotation(false);
688 if (!af.getViewport().isShowAnnotation())
690 System.out.println("CMD no-annotation executed successfully!");
693 if (aparser.contains("nosortbytree"))
695 af.getViewport().setSortByTree(false);
696 if (!af.getViewport().getSortByTree())
699 .println("CMD [-nosortbytree] executed successfully!");
702 data = aparser.getValue("tree", true);
708 "CMD [-tree " + data + "] executed successfully!");
709 NewickFile nf = new NewickFile(data,
710 AppletFormatAdapter.checkProtocol(data));
712 .setCurrentTree(af.showNewickTree(nf, data).getTree());
713 } catch (IOException ex)
715 System.err.println("Couldn't add tree " + data);
716 ex.printStackTrace(System.err);
719 // TODO - load PDB structure(s) to alignment JAL-629
720 // (associate with identical sequence in alignment, or a specified
723 getFeatures = checkDasArguments(aparser);
724 if (af != null && getFeatures != null)
726 FeatureFetcher ff = startFeatureFetching(getFeatures);
729 while (!ff.allFinished() || af.operationInProgress())
731 // wait around until fetching is finished.
735 } catch (Exception e)
741 getFeatures = null; // have retrieved features - forget them now.
743 if (groovyscript != null)
745 // Execute the groovy script after we've done all the rendering stuff
746 // and before any images or figures are generated.
747 System.out.println("Executing script " + groovyscript);
748 executeGroovyScript(groovyscript, af);
749 System.out.println("CMD groovy[" + groovyscript
750 + "] executed successfully!");
753 String imageName = "unnamed.png";
754 while (aparser.getSize() > 1)
756 String outputFormat = aparser.nextValue();
757 file = aparser.nextValue();
759 if (outputFormat.equalsIgnoreCase("png"))
761 af.createPNG(new File(file));
762 imageName = (new File(file)).getName();
763 System.out.println("Creating PNG image: " + file);
766 else if (outputFormat.equalsIgnoreCase("svg"))
768 File imageFile = new File(file);
769 imageName = imageFile.getName();
770 af.createSVG(imageFile);
771 System.out.println("Creating SVG image: " + file);
774 else if (outputFormat.equalsIgnoreCase("html"))
776 File imageFile = new File(file);
777 imageName = imageFile.getName();
778 HtmlSvgOutput htmlSVG = new HtmlSvgOutput(af.alignPanel);
779 htmlSVG.exportHTML(file);
781 System.out.println("Creating HTML image: " + file);
784 else if (outputFormat.equalsIgnoreCase("biojsmsa"))
788 System.err.println("The output html file must not be null");
793 BioJsHTMLOutput.refreshVersionInfo(
794 BioJsHTMLOutput.BJS_TEMPLATES_LOCAL_DIRECTORY);
795 } catch (URISyntaxException e)
799 BioJsHTMLOutput bjs = new BioJsHTMLOutput(af.alignPanel);
800 bjs.exportHTML(file);
802 .println("Creating BioJS MSA Viwer HTML file: " + file);
805 else if (outputFormat.equalsIgnoreCase("imgMap"))
807 af.createImageMap(new File(file), imageName);
808 System.out.println("Creating image map: " + file);
811 else if (outputFormat.equalsIgnoreCase("eps"))
813 File outputFile = new File(file);
815 "Creating EPS file: " + outputFile.getAbsolutePath());
816 af.createEPS(outputFile);
820 af.saveAlignment(file, format);
821 if (af.isSaveAlignmentSuccessful())
823 System.out.println("Written alignment in " + format
824 + " format to " + file);
828 System.out.println("Error writing file " + file + " in "
829 + format + " format!!");
834 while (aparser.getSize() > 0)
836 System.out.println("Unknown arg: " + aparser.nextValue());
840 AlignFrame startUpAlframe = null;
841 // We'll only open the default file if the desktop is visible.
843 // ////////////////////
845 if (/** @j2sNative false && */ // BH 2018
846 !headless && file == null && vamsasImport == null
847 && jalview.bin.Cache.getDefault("SHOW_STARTUP_FILE", true))
849 file = jalview.bin.Cache.getDefault("STARTUP_FILE",
850 jalview.bin.Cache.getDefault("www.jalview.org",
851 "http://www.jalview.org")
852 + "/examples/exampleFile_2_7.jar");
854 "http://www.jalview.org/examples/exampleFile_2_3.jar"))
856 // hardwire upgrade of the startup file
857 file.replace("_2_3.jar", "_2_7.jar");
858 // and remove the stale setting
859 jalview.bin.Cache.removeProperty("STARTUP_FILE");
862 protocol = DataSourceType.FILE;
864 if (file.indexOf("http:") > -1)
866 protocol = DataSourceType.URL;
869 if (file.endsWith(".jar"))
871 format = FileFormat.Jalview;
877 format = new IdentifyFile().identify(file, protocol);
878 } catch (FileFormatException e)
884 startUpAlframe = fileLoader.LoadFileWaitTillLoaded(file, protocol,
886 getFeatures = checkDasArguments(aparser);
887 // extract groovy arguments before anything else.
889 // If the user has specified features to be retrieved,
890 // or a groovy script to be executed, do them if they
891 // haven't been done already
892 // fetch features for the default alignment
893 if (getFeatures != null)
895 if (startUpAlframe != null)
897 startFeatureFetching(getFeatures);
900 // Once all other stuff is done, execute any groovy scripts (in order)
901 if (groovyscript != null)
903 if (Cache.groovyJarsPresent())
905 System.out.println("Executing script " + groovyscript);
906 executeGroovyScript(groovyscript, startUpAlframe);
911 "Sorry. Groovy Support is not available, so ignoring the provided groovy script "
915 // and finally, turn off batch mode indicator - if the desktop still exists
920 desktop.setProgressBar(null, progress);
922 desktop.setInBatchMode(false);
926 private static void showUsage()
929 "Usage: jalview -open [FILE] [OUTPUT_FORMAT] [OUTPUT_FILE]\n\n"
930 + "-nodisplay\tRun Jalview without User Interface.\n"
931 + "-props FILE\tUse the given Jalview properties file instead of users default.\n"
932 + "-colour COLOURSCHEME\tThe colourscheme to be applied to the alignment\n"
933 + "-annotations FILE\tAdd precalculated annotations to the alignment.\n"
934 + "-tree FILE\tLoad the given newick format tree file onto the alignment\n"
935 + "-features FILE\tUse the given file to mark features on the alignment.\n"
936 + "-fasta FILE\tCreate alignment file FILE in Fasta format.\n"
937 + "-clustal FILE\tCreate alignment file FILE in Clustal format.\n"
938 + "-pfam FILE\tCreate alignment file FILE in PFAM format.\n"
939 + "-msf FILE\tCreate alignment file FILE in MSF format.\n"
940 + "-pileup FILE\tCreate alignment file FILE in Pileup format\n"
941 + "-pir FILE\tCreate alignment file FILE in PIR format.\n"
942 + "-blc FILE\tCreate alignment file FILE in BLC format.\n"
943 + "-json FILE\tCreate alignment file FILE in JSON format.\n"
944 + "-jalview FILE\tCreate alignment file FILE in Jalview format.\n"
945 + "-png FILE\tCreate PNG image FILE from alignment.\n"
946 + "-svg FILE\tCreate SVG image FILE from alignment.\n"
947 + "-html FILE\tCreate HTML file from alignment.\n"
948 + "-biojsMSA FILE\tCreate BioJS MSA Viewer HTML file from alignment.\n"
949 + "-imgMap FILE\tCreate HTML file FILE with image map of PNG image.\n"
950 + "-eps FILE\tCreate EPS file FILE from alignment.\n"
951 + "-questionnaire URL\tQueries the given URL for information about any Jalview user questionnaires.\n"
952 + "-noquestionnaire\tTurn off questionnaire check.\n"
953 + "-nonews\tTurn off check for Jalview news.\n"
954 + "-nousagestats\tTurn off google analytics tracking for this session.\n"
955 + "-sortbytree OR -nosortbytree\tEnable or disable sorting of the given alignment by the given tree\n"
957 // "-setprop PROPERTY=VALUE\tSet the given Jalview property,
958 // after all other properties files have been read\n\t
959 // (quote the 'PROPERTY=VALUE' pair to ensure spaces are
960 // passed in correctly)"
961 + "-jabaws URL\tSpecify URL for Jabaws services (e.g. for a local installation).\n"
962 + "-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"
963 + "\t\t\tSources that also support the sequence command may be specified by prepending the URL with sequence:\n"
964 + "\t\t\t e.g. sequence:http://localdas.somewhere.org/das/source)\n"
965 + "-fetchfrom nickname\tQuery nickname for features for the alignments and display them.\n"
967 // "-vdoc vamsas-document\tImport vamsas document into new
968 // session or join existing session with same URN\n"
969 // + "-vses vamsas-session\tJoin session with given URN\n"
970 + "-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"
971 + "\n~Read documentation in Application or visit http://www.jalview.org for description of Features and Annotations file~\n\n");
974 private static void startUsageStats(final Desktop desktop)
977 * start a User Config prompt asking if we can log usage statistics.
979 PromptUserConfig prompter = new PromptUserConfig(Desktop.desktop,
980 "USAGESTATS", "Jalview Usage Statistics",
981 "Do you want to help make Jalview better by enabling "
982 + "the collection of usage statistics with Google Analytics ?"
983 + "\n\n(you can enable or disable usage tracking in the preferences)",
990 "Initialising googletracker for usage stats.");
991 Cache.initGoogleTracker();
992 Cache.log.debug("Tracking enabled.");
999 Cache.log.debug("Not enabling Google Tracking.");
1002 desktop.addDialogThread(prompter);
1006 * Locate the given string as a file and pass it to the groovy interpreter.
1008 * @param groovyscript
1009 * the script to execute
1010 * @param jalviewContext
1011 * the Jalview Desktop object passed in to the groovy binding as the
1014 private void executeGroovyScript(String groovyscript, AlignFrame af)
1017 * for scripts contained in files
1024 if (groovyscript.trim().equals("STDIN"))
1026 // read from stdin into a tempfile and execute it
1029 tfile = File.createTempFile("jalview", "groovy");
1030 PrintWriter outfile = new PrintWriter(
1031 new OutputStreamWriter(new FileOutputStream(tfile)));
1032 BufferedReader br = new BufferedReader(
1033 new InputStreamReader(System.in));
1035 while ((line = br.readLine()) != null)
1037 outfile.write(line + "\n");
1043 } catch (Exception ex)
1045 System.err.println("Failed to read from STDIN into tempfile "
1046 + ((tfile == null) ? "(tempfile wasn't created)"
1047 : tfile.toString()));
1048 ex.printStackTrace();
1053 sfile = tfile.toURI().toURL();
1054 } catch (Exception x)
1057 "Unexpected Malformed URL Exception for temporary file created from STDIN: "
1059 x.printStackTrace();
1067 sfile = new URI(groovyscript).toURL();
1068 } catch (Exception x)
1070 tfile = new File(groovyscript);
1071 if (!tfile.exists())
1073 System.err.println("File '" + groovyscript + "' does not exist.");
1076 if (!tfile.canRead())
1078 System.err.println("File '" + groovyscript + "' cannot be read.");
1081 if (tfile.length() < 1)
1083 System.err.println("File '" + groovyscript + "' is empty.");
1088 sfile = tfile.getAbsoluteFile().toURI().toURL();
1089 } catch (Exception ex)
1091 System.err.println("Failed to create a file URL for "
1092 + tfile.getAbsoluteFile());
1099 Map<String, Object> vbinding = new HashMap<>();
1100 vbinding.put("Jalview", this);
1103 vbinding.put("currentAlFrame", af);
1105 Binding gbinding = new Binding(vbinding);
1106 GroovyScriptEngine gse = new GroovyScriptEngine(new URL[] { sfile });
1107 gse.run(sfile.toString(), gbinding);
1108 if ("STDIN".equals(groovyscript))
1110 // delete temp file that we made -
1111 // only if it was successfully executed
1114 } catch (Exception e)
1116 System.err.println("Exception Whilst trying to execute file " + sfile
1117 + " as a groovy script.");
1118 e.printStackTrace(System.err);
1124 * Check commandline for any das server definitions or any fetchfrom switches
1126 * @return vector of DAS source nicknames to retrieve from
1128 private static Vector<String> checkDasArguments(ArgsParser aparser)
1130 Vector<String> source = null;
1132 String locsources = Cache.getProperty(Cache.DAS_LOCAL_SOURCE);
1133 while ((data = aparser.getValue("dasserver", true)) != null)
1135 String nickname = null;
1137 int pos = data.indexOf('=');
1138 // determine capabilities
1141 nickname = data.substring(0, pos);
1143 url = data.substring(pos + 1);
1144 if (url != null && (url.startsWith("http:")
1145 || url.startsWith("sequence:http:")))
1147 if (nickname == null)
1151 if (locsources == null)
1159 locsources = locsources + nickname + "|" + url;
1161 "NOTE! dasserver parameter not yet really supported (got args of "
1162 + nickname + "|" + url);
1165 source = new Vector<>();
1167 source.addElement(nickname);
1170 "CMD [-dasserver " + data + "] executed successfully!");
1171 } // loop until no more server entries are found.
1172 if (locsources != null && locsources.indexOf('|') > -1)
1174 Cache.log.debug("Setting local source list in properties file to:\n"
1176 Cache.setProperty(Cache.DAS_LOCAL_SOURCE, locsources);
1178 while ((data = aparser.getValue("fetchfrom", true)) != null)
1180 System.out.println("adding source '" + data + "'");
1183 source = new Vector<>();
1185 source.addElement(data);
1191 * start a feature fetcher for every alignment frame
1195 private FeatureFetcher startFeatureFetching(
1196 final Vector<String> dasSources)
1198 FeatureFetcher ff = new FeatureFetcher();
1199 AlignFrame afs[] = Desktop.getAlignFrames();
1200 if (afs == null || afs.length == 0)
1204 for (int i = 0; i < afs.length; i++)
1206 ff.addFetcher(afs[i], dasSources);
1211 public static boolean isHeadlessMode()
1213 String isheadless = System.getProperty("java.awt.headless");
1214 if (isheadless != null && isheadless.equalsIgnoreCase("true"))
1221 public AlignFrame[] getAlignFrames()
1223 return desktop == null ? new AlignFrame[] { getCurrentAlignFrame() }
1224 : Desktop.getAlignFrames();
1229 * Quit method delegates to Desktop.quit - unless running in headless mode
1230 * when it just ends the JVM
1234 if (desktop != null)
1244 public static AlignFrame getCurrentAlignFrame()
1246 return Jalview.currentAlignFrame;
1249 public static void setCurrentAlignFrame(AlignFrame currentAlignFrame)
1251 Jalview.currentAlignFrame = currentAlignFrame;