2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3 * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
21 import java.lang.reflect.*;
24 * BrowserLauncher is a class that provides one static method, openURL, which
25 * opens the default web browser for the current user of the system to the given
26 * URL. It may support other protocols depending on the system -- mailto, ftp,
27 * etc. -- but that has not been rigorously tested and is not guaranteed to
30 * Yes, this is platform-specific code, and yes, it may rely on classes on
31 * certain platforms that are not part of the standard JDK. What we're trying to
32 * do, though, is to take something that's frequently desirable but inherently
33 * platform-specific -- opening a default browser -- and allow programmers (you,
34 * for example) to do so without worrying about dropping into native code or
35 * doing anything else similarly evil.
37 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
38 * systems without modification or a need for additional libraries. All classes
39 * that are required on certain platforms to allow this to run are dynamically
40 * loaded at runtime via reflection and, if not found, will not cause this to do
41 * anything other than returning an error when opening the browser.
43 * There are certain system requirements for this class, as it's running through
44 * Runtime.exec(), which is Java's way of making a native system call.
45 * Currently, this requires that a Macintosh have a Finder which supports the
46 * GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
47 * Internet Scripting AppleScript dictionary installed in the Scripting
48 * Additions folder in the Extensions folder (which is installed by default as
49 * far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
50 * systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
51 * 4.0, as well as later versions of all). On other systems, this drops back
52 * from the inherently platform-sensitive concept of a default browser and
53 * simply attempts to launch Netscape via a shell command.
55 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu)
56 * and may be redistributed or modified in any form without restrictions as long
57 * as the portion of this comment from this paragraph through the end of the
58 * comment is not removed. The author requests that he be notified of any
59 * application, applet, or other binary that makes use of this code, but that's
60 * more out of curiosity than anything and is not required. This software
61 * includes no warranty. The author is not repsonsible for any loss of data or
62 * functionality or any adverse or unexpected effects of using this software.
65 * Steven Spencer, JavaWorld magazine (<a
66 * href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip
68 * Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
69 * Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
71 * @author Eric Albert (<a
72 * href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
73 * @version 1.4b1 (Released June 20, 2001)
75 public class BrowserLauncher
78 * The Java virtual machine that we are running on. Actually, in most cases we
79 * only care about the operating system, but some operating systems require us
80 * to switch on the VM.
82 private static int jvm;
84 /** The browser for the system */
85 private static Object browser;
88 * Caches whether any classes, methods, and fields that are not part of the
89 * JDK and need to be dynamically loaded at runtime loaded successfully.
91 * Note that if this is <code>false</code>, <code>openURL()</code> will always
92 * return an IOException.
94 private static boolean loadedWithoutErrors;
96 /** The com.apple.mrj.MRJFileUtils class */
97 private static Class mrjFileUtilsClass;
99 /** The com.apple.mrj.MRJOSType class */
100 private static Class mrjOSTypeClass;
102 /** The com.apple.MacOS.AEDesc class */
103 private static Class aeDescClass;
105 /** The <init>(int) method of com.apple.MacOS.AETarget */
106 private static Constructor aeTargetConstructor;
108 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
109 private static Constructor appleEventConstructor;
111 /** The <init>(String) method of com.apple.MacOS.AEDesc */
112 private static Constructor aeDescConstructor;
114 /** The findFolder method of com.apple.mrj.MRJFileUtils */
115 private static Method findFolder;
117 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
118 private static Method getFileCreator;
120 /** The getFileType method of com.apple.mrj.MRJFileUtils */
121 private static Method getFileType;
123 /** The openURL method of com.apple.mrj.MRJFileUtils */
124 private static Method openURL;
126 /** The makeOSType method of com.apple.MacOS.OSUtils */
127 private static Method makeOSType;
129 /** The putParameter method of com.apple.MacOS.AppleEvent */
130 private static Method putParameter;
132 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
133 private static Method sendNoReply;
135 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
136 private static Object kSystemFolderType;
138 /** The keyDirectObject AppleEvent parameter type */
139 private static Integer keyDirectObject;
141 /** The kAutoGenerateReturnID AppleEvent code */
142 private static Integer kAutoGenerateReturnID;
144 /** The kAnyTransactionID AppleEvent code */
145 private static Integer kAnyTransactionID;
147 /** The linkage object required for JDirect 3 on Mac OS X. */
148 private static Object linkage;
150 /** The framework to reference on Mac OS X */
151 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
153 /** JVM constant for MRJ 2.0 */
154 private static final int MRJ_2_0 = 0;
156 /** JVM constant for MRJ 2.1 or later */
157 private static final int MRJ_2_1 = 1;
159 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
160 private static final int MRJ_3_0 = 3;
162 /** JVM constant for MRJ 3.1 */
163 private static final int MRJ_3_1 = 4;
165 /** JVM constant for any Windows NT JVM */
166 private static final int WINDOWS_NT = 5;
168 /** JVM constant for any Windows 9x JVM */
169 private static final int WINDOWS_9x = 6;
171 /** JVM constant for any other platform */
172 private static final int OTHER = -1;
175 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep
176 * non-U.S. English systems from working properly.
178 private static final String FINDER_TYPE = "FNDR";
181 * The creator code of the Finder on a Macintosh, which is needed to send
182 * AppleEvents to the application.
184 private static final String FINDER_CREATOR = "MACS";
186 /** The name for the AppleEvent type corresponding to a GetURL event. */
187 private static final String GURL_EVENT = "GURL";
190 * The first parameter that needs to be passed into Runtime.exec() to open the
191 * default web browser on Windows.
193 private static final String FIRST_WINDOWS_PARAMETER = "/c";
195 /** The second parameter for Runtime.exec() on Windows. */
196 private static final String SECOND_WINDOWS_PARAMETER = "start";
199 * The third parameter for Runtime.exec() on Windows. This is a "title"
200 * parameter that the command line expects. Setting this parameter allows URLs
201 * containing spaces to work.
203 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
206 * The shell parameters for Netscape that opens a given URL in an already-open
207 * copy of Netscape on many command-line systems.
209 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
211 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
213 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
215 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
218 * The message from any exception thrown throughout the initialization
221 private static String errorMessage;
224 * An initialization block that determines the operating system and loads the
225 * necessary runtime data.
229 loadedWithoutErrors = true;
231 String osName = System.getProperty("os.name");
233 if (osName.startsWith("Mac OS"))
235 String mrjVersion = System.getProperty("mrj.version");
236 String majorMRJVersion = mrjVersion.substring(0, 3);
240 double version = Double.valueOf(majorMRJVersion).doubleValue();
246 else if ((version >= 2.1) && (version < 3))
248 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
249 // works via Runtime.exec() and 2.2 supports that but has an openURL()
251 // as well that we currently ignore.
254 else if (version == 3.0)
258 else if (version >= 3.1)
260 // Assume that all 3.1 and later versions of MRJ work the same.
265 loadedWithoutErrors = false;
266 errorMessage = "Unsupported MRJ version: " + version;
268 } catch (NumberFormatException nfe)
270 loadedWithoutErrors = false;
271 errorMessage = "Invalid MRJ version: " + mrjVersion;
274 else if (osName.startsWith("Windows"))
276 if (osName.indexOf("9") != -1)
290 if (loadedWithoutErrors)
291 { // if we haven't hit any errors yet
292 loadedWithoutErrors = loadClasses();
297 * This class should be never be instantiated; this just ensures so.
299 private BrowserLauncher()
304 * Called by a static initializer to load any classes, fields, and methods
305 * required at runtime to locate the user's web browser.
307 * @return <code>true</code> if all intialization succeeded <code>false</code>
308 * if any portion of the initialization failed
310 private static boolean loadClasses()
318 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
319 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
320 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
321 Class aeClass = Class.forName("com.apple.MacOS.ae");
322 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
324 aeTargetConstructor = aeTargetClass
325 .getDeclaredConstructor(new Class[]
327 appleEventConstructor = appleEventClass
328 .getDeclaredConstructor(new Class[]
329 { int.class, int.class, aeTargetClass, int.class, int.class });
330 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[]
333 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
336 putParameter = appleEventClass.getDeclaredMethod("putParameter",
338 { int.class, aeDescClass });
339 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
343 Field keyDirectObjectField = aeClass
344 .getDeclaredField("keyDirectObject");
345 keyDirectObject = (Integer) keyDirectObjectField.get(null);
347 Field autoGenerateReturnIDField = appleEventClass
348 .getDeclaredField("kAutoGenerateReturnID");
349 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
352 Field anyTransactionIDField = appleEventClass
353 .getDeclaredField("kAnyTransactionID");
354 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
355 } catch (ClassNotFoundException cnfe)
357 errorMessage = cnfe.getMessage();
360 } catch (NoSuchMethodException nsme)
362 errorMessage = nsme.getMessage();
365 } catch (NoSuchFieldException nsfe)
367 errorMessage = nsfe.getMessage();
370 } catch (IllegalAccessException iae)
372 errorMessage = iae.getMessage();
383 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
384 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
386 Field systemFolderField = mrjFileUtilsClass
387 .getDeclaredField("kSystemFolderType");
388 kSystemFolderType = systemFolderField.get(null);
389 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
392 getFileCreator = mrjFileUtilsClass.getDeclaredMethod(
393 "getFileCreator", new Class[]
395 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
398 } catch (ClassNotFoundException cnfe)
400 errorMessage = cnfe.getMessage();
403 } catch (NoSuchFieldException nsfe)
405 errorMessage = nsfe.getMessage();
408 } catch (NoSuchMethodException nsme)
410 errorMessage = nsme.getMessage();
413 } catch (SecurityException se)
415 errorMessage = se.getMessage();
418 } catch (IllegalAccessException iae)
420 errorMessage = iae.getMessage();
431 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
432 Constructor constructor = linker.getConstructor(new Class[]
434 linkage = constructor.newInstance(new Object[]
435 { BrowserLauncher.class });
436 } catch (ClassNotFoundException cnfe)
438 errorMessage = cnfe.getMessage();
441 } catch (NoSuchMethodException nsme)
443 errorMessage = nsme.getMessage();
446 } catch (InvocationTargetException ite)
448 errorMessage = ite.getMessage();
451 } catch (InstantiationException ie)
453 errorMessage = ie.getMessage();
456 } catch (IllegalAccessException iae)
458 errorMessage = iae.getMessage();
469 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
470 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
473 } catch (ClassNotFoundException cnfe)
475 errorMessage = cnfe.getMessage();
478 } catch (NoSuchMethodException nsme)
480 errorMessage = nsme.getMessage();
495 * Attempts to locate the default web browser on the local system. s results
496 * so it only locates the browser once for each use of this class per JVM
499 * @return The browser for the system. Note that this may not be what you
500 * would consider to be a standard web browser; instead, it's the
501 * application that gets called to open the default web browser. In
502 * some cases, this will be a non-String object that provides the
503 * means of calling the default browser.
505 private static Object locateBrowser()
518 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
521 Object aeTarget = aeTargetConstructor.newInstance(new Object[]
522 { finderCreatorCode });
523 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[]
525 Object appleEvent = appleEventConstructor.newInstance(new Object[]
526 { gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
527 kAnyTransactionID });
529 // Don't set browser = appleEvent because then the next time we call
530 // locateBrowser(), we'll get the same AppleEvent, to which we'll
532 // added the relevant parameter. Instead, regenerate the AppleEvent
534 // There's probably a way to do this better; if any has any ideas,
538 } catch (IllegalAccessException iae)
541 errorMessage = iae.getMessage();
544 } catch (InstantiationException ie)
547 errorMessage = ie.getMessage();
550 } catch (InvocationTargetException ite)
553 errorMessage = ite.getMessage();
564 systemFolder = (File) findFolder.invoke(null, new Object[]
565 { kSystemFolderType });
566 } catch (IllegalArgumentException iare)
569 errorMessage = iare.getMessage();
572 } catch (IllegalAccessException iae)
575 errorMessage = iae.getMessage();
578 } catch (InvocationTargetException ite)
581 errorMessage = ite.getTargetException().getClass() + ": "
582 + ite.getTargetException().getMessage();
587 String[] systemFolderFiles = systemFolder.list();
589 // Avoid a FilenameFilter because that can't be stopped mid-list
590 for (int i = 0; i < systemFolderFiles.length; i++)
594 File file = new File(systemFolder, systemFolderFiles[i]);
601 // We're looking for a file with a creator code of 'MACS' and
602 // a type of 'FNDR'. Only requiring the type results in non-Finder
603 // applications being picked up on certain Mac OS 9 systems,
604 // especially German ones, and sending a GURL event to those
605 // applications results in a logout under Multiple Users.
606 Object fileType = getFileType.invoke(null, new Object[]
609 if (FINDER_TYPE.equals(fileType.toString()))
611 Object fileCreator = getFileCreator.invoke(null, new Object[]
614 if (FINDER_CREATOR.equals(fileCreator.toString()))
616 browser = file.toString(); // Actually the Finder, but that's OK
621 } catch (IllegalArgumentException iare)
623 errorMessage = iare.getMessage();
626 } catch (IllegalAccessException iae)
629 errorMessage = iae.getMessage();
632 } catch (InvocationTargetException ite)
635 errorMessage = ite.getTargetException().getClass() + ": "
636 + ite.getTargetException().getMessage();
648 browser = ""; // Return something non-null
658 browser = "command.com";
664 browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox");
673 * used to ensure that browser is up-to-date after a configuration change
674 * (Unix DEFAULT_BROWSER property change).
676 public static void resetBrowser()
682 * Attempts to open the default web browser to the given URL.
686 * @throws IOException
687 * If the web browser could not be located or does not run
689 public static void openURL(String url) throws IOException
691 if (!loadedWithoutErrors)
693 throw new IOException("Exception in finding browser: " + errorMessage);
696 Object browser = locateBrowser();
700 throw new IOException("Unable to locate browser: " + errorMessage);
707 Object aeDesc = null;
711 aeDesc = aeDescConstructor.newInstance(new Object[]
713 putParameter.invoke(browser, new Object[]
714 { keyDirectObject, aeDesc });
715 sendNoReply.invoke(browser, new Object[]
717 } catch (InvocationTargetException ite)
719 throw new IOException(
720 "InvocationTargetException while creating AEDesc: "
722 } catch (IllegalAccessException iae)
724 throw new IOException(
725 "IllegalAccessException while building AppleEvent: "
727 } catch (InstantiationException ie)
729 throw new IOException(
730 "InstantiationException while creating AEDesc: "
734 aeDesc = null; // Encourage it to get disposed if it was created
735 browser = null; // Ditto
741 Runtime.getRuntime().exec(new String[]
742 { (String) browser, url });
748 int[] instance = new int[1];
749 int result = ICStart(instance, 0);
753 int[] selectionStart = new int[]
755 byte[] urlBytes = url.getBytes();
756 int[] selectionEnd = new int[]
758 result = ICLaunchURL(instance[0], new byte[]
759 { 0 }, urlBytes, urlBytes.length, selectionStart, selectionEnd);
763 // Ignore the return value; the URL was launched successfully
764 // regardless of what happens here.
769 throw new IOException("Unable to launch URL: " + result);
774 throw new IOException(
775 "Unable to create an Internet Config instance: " + result);
784 openURL.invoke(null, new Object[]
786 } catch (InvocationTargetException ite)
788 throw new IOException(
789 "InvocationTargetException while calling openURL: "
791 } catch (IllegalAccessException iae)
793 throw new IOException(
794 "IllegalAccessException while calling openURL: "
803 // Add quotes around the URL to allow ampersands and other special
804 // characters to work.
805 Process process = Runtime.getRuntime().exec(
807 { (String) browser, FIRST_WINDOWS_PARAMETER,
808 SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
811 // This avoids a memory leak on some versions of Java on Windows.
812 // That's hinted at in
813 // <http://developer.java.sun.com/developer/qow/archive/68/>.
818 } catch (InterruptedException ie)
820 throw new IOException(
821 "InterruptedException while launching browser: "
829 // Assume that we're on Unix and that Netscape (actually Firefox) is
831 // First, attempt to open the URL in a currently running session of
836 * System.out.println("Executing : "+browser+" "+
837 * NETSCAPE_REMOTE_PARAMETER+" "+ NETSCAPE_OPEN_PARAMETER_START + url +
838 * NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END);
840 process = Runtime.getRuntime().exec(
844 NETSCAPE_REMOTE_PARAMETER,
846 NETSCAPE_OPEN_PARAMETER_START + url
847 + NETSCAPE_OPEN_NEW_WINDOW
848 + NETSCAPE_OPEN_PARAMETER_END });
852 int exitCode = process.waitFor();
855 { // if Netscape was not open
856 Runtime.getRuntime().exec(new String[]
857 { (String) browser, url });
859 } catch (InterruptedException ie)
861 throw new IOException(
862 "InterruptedException while launching browser: "
870 // This should never occur, but if it does, we'll try the simplest thing
872 Runtime.getRuntime().exec(new String[]
873 { (String) browser, url });
880 * Methods required for Mac OS X. The presence of native methods does not
881 * cause any problems on other platforms.
883 private native static int ICStart(int[] instance, int signature);
885 private native static int ICStop(int[] instance);
887 private native static int ICLaunchURL(int instance, byte[] hint,
888 byte[] data, int len, int[] selectionStart, int[] selectionEnd);