2 * 2004 Jalview Reengineered
12 import java.io.IOException;
13 import java.lang.reflect.Constructor;
14 import java.lang.reflect.Field;
15 import java.lang.reflect.InvocationTargetException;
16 import java.lang.reflect.Method;
19 * BrowserLauncher is a class that provides one static method, openURL, which opens the default
20 * web browser for the current user of the system to the given URL. It may support other
21 * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
22 * tested and is not guaranteed to work.
24 * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
25 * that are not part of the standard JDK. What we're trying to do, though, is to take something
26 * that's frequently desirable but inherently platform-specific -- opening a default browser --
27 * and allow programmers (you, for example) to do so without worrying about dropping into native
28 * code or doing anything else similarly evil.
30 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
31 * modification or a need for additional libraries. All classes that are required on certain
32 * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
33 * found, will not cause this to do anything other than returning an error when opening the
36 * There are certain system requirements for this class, as it's running through Runtime.exec(),
37 * which is Java's way of making a native system call. Currently, this requires that a Macintosh
38 * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
39 * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
40 * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
41 * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
42 * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
43 * back from the inherently platform-sensitive concept of a default browser and simply attempts
44 * to launch Netscape via a shell command.
46 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu) and may be
47 * redistributed or modified in any form without restrictions as long as the portion of this
48 * comment from this paragraph through the end of the comment is not removed. The author
49 * requests that he be notified of any application, applet, or other binary that makes use of
50 * this code, but that's more out of curiosity than anything and is not required. This software
51 * includes no warranty. The author is not repsonsible for any loss of data or functionality
52 * or any adverse or unexpected effects of using this software.
55 * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
56 * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
57 * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
59 * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
60 * @version 1.4b1 (Released June 20, 2001)
62 public class BrowserLauncher {
65 * The Java virtual machine that we are running on. Actually, in most cases we only care
66 * about the operating system, but some operating systems require us to switch on the VM. */
67 private static int jvm;
69 /** The browser for the system */
70 private static Object browser;
73 * Caches whether any classes, methods, and fields that are not part of the JDK and need to
74 * be dynamically loaded at runtime loaded successfully.
76 * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
79 private static boolean loadedWithoutErrors;
81 /** The com.apple.mrj.MRJFileUtils class */
82 private static Class mrjFileUtilsClass;
84 /** The com.apple.mrj.MRJOSType class */
85 private static Class mrjOSTypeClass;
87 /** The com.apple.MacOS.AEDesc class */
88 private static Class aeDescClass;
90 /** The <init>(int) method of com.apple.MacOS.AETarget */
91 private static Constructor aeTargetConstructor;
93 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
94 private static Constructor appleEventConstructor;
96 /** The <init>(String) method of com.apple.MacOS.AEDesc */
97 private static Constructor aeDescConstructor;
99 /** The findFolder method of com.apple.mrj.MRJFileUtils */
100 private static Method findFolder;
102 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
103 private static Method getFileCreator;
105 /** The getFileType method of com.apple.mrj.MRJFileUtils */
106 private static Method getFileType;
108 /** The openURL method of com.apple.mrj.MRJFileUtils */
109 private static Method openURL;
111 /** The makeOSType method of com.apple.MacOS.OSUtils */
112 private static Method makeOSType;
114 /** The putParameter method of com.apple.MacOS.AppleEvent */
115 private static Method putParameter;
117 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
118 private static Method sendNoReply;
120 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
121 private static Object kSystemFolderType;
123 /** The keyDirectObject AppleEvent parameter type */
124 private static Integer keyDirectObject;
126 /** The kAutoGenerateReturnID AppleEvent code */
127 private static Integer kAutoGenerateReturnID;
129 /** The kAnyTransactionID AppleEvent code */
130 private static Integer kAnyTransactionID;
132 /** The linkage object required for JDirect 3 on Mac OS X. */
133 private static Object linkage;
135 /** The framework to reference on Mac OS X */
136 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
138 /** JVM constant for MRJ 2.0 */
139 private static final int MRJ_2_0 = 0;
141 /** JVM constant for MRJ 2.1 or later */
142 private static final int MRJ_2_1 = 1;
144 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
145 private static final int MRJ_3_0 = 3;
147 /** JVM constant for MRJ 3.1 */
148 private static final int MRJ_3_1 = 4;
150 /** JVM constant for any Windows NT JVM */
151 private static final int WINDOWS_NT = 5;
153 /** JVM constant for any Windows 9x JVM */
154 private static final int WINDOWS_9x = 6;
156 /** JVM constant for any other platform */
157 private static final int OTHER = -1;
160 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
161 * systems from working properly.
163 private static final String FINDER_TYPE = "FNDR";
166 * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
169 private static final String FINDER_CREATOR = "MACS";
171 /** The name for the AppleEvent type corresponding to a GetURL event. */
172 private static final String GURL_EVENT = "GURL";
175 * The first parameter that needs to be passed into Runtime.exec() to open the default web
176 * browser on Windows.
178 private static final String FIRST_WINDOWS_PARAMETER = "/c";
180 /** The second parameter for Runtime.exec() on Windows. */
181 private static final String SECOND_WINDOWS_PARAMETER = "start";
184 * The third parameter for Runtime.exec() on Windows. This is a "title"
185 * parameter that the command line expects. Setting this parameter allows
186 * URLs containing spaces to work.
188 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
191 * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
192 * on many command-line systems.
194 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
195 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
196 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
197 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
200 * The message from any exception thrown throughout the initialization process.
202 private static String errorMessage;
205 * An initialization block that determines the operating system and loads the necessary
209 loadedWithoutErrors = true;
210 String osName = System.getProperty("os.name");
211 if (osName.startsWith("Mac OS")) {
212 String mrjVersion = System.getProperty("mrj.version");
213 String majorMRJVersion = mrjVersion.substring(0, 3);
215 double version = Double.valueOf(majorMRJVersion).doubleValue();
218 } else if (version >= 2.1 && version < 3) {
219 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
220 // works via Runtime.exec() and 2.2 supports that but has an openURL() method
221 // as well that we currently ignore.
223 } else if (version == 3.0) {
225 } else if (version >= 3.1) {
226 // Assume that all 3.1 and later versions of MRJ work the same.
229 loadedWithoutErrors = false;
230 errorMessage = "Unsupported MRJ version: " + version;
232 } catch (NumberFormatException nfe) {
233 loadedWithoutErrors = false;
234 errorMessage = "Invalid MRJ version: " + mrjVersion;
236 } else if (osName.startsWith("Windows")) {
237 if (osName.indexOf("9") != -1) {
246 if (loadedWithoutErrors) { // if we haven't hit any errors yet
247 loadedWithoutErrors = loadClasses();
252 * This class should be never be instantiated; this just ensures so.
254 private BrowserLauncher() { }
257 * Called by a static initializer to load any classes, fields, and methods required at runtime
258 * to locate the user's web browser.
259 * @return <code>true</code> if all intialization succeeded
260 * <code>false</code> if any portion of the initialization failed
262 private static boolean loadClasses() {
266 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
267 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
268 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
269 Class aeClass = Class.forName("com.apple.MacOS.ae");
270 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
272 aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class });
273 appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
274 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });
276 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class });
277 putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass });
278 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { });
280 Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
281 keyDirectObject = (Integer) keyDirectObjectField.get(null);
282 Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
283 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
284 Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
285 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
286 } catch (ClassNotFoundException cnfe) {
287 errorMessage = cnfe.getMessage();
289 } catch (NoSuchMethodException nsme) {
290 errorMessage = nsme.getMessage();
292 } catch (NoSuchFieldException nsfe) {
293 errorMessage = nsfe.getMessage();
295 } catch (IllegalAccessException iae) {
296 errorMessage = iae.getMessage();
302 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
303 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
304 Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
305 kSystemFolderType = systemFolderField.get(null);
306 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
307 getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
308 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
309 } catch (ClassNotFoundException cnfe) {
310 errorMessage = cnfe.getMessage();
312 } catch (NoSuchFieldException nsfe) {
313 errorMessage = nsfe.getMessage();
315 } catch (NoSuchMethodException nsme) {
316 errorMessage = nsme.getMessage();
318 } catch (SecurityException se) {
319 errorMessage = se.getMessage();
321 } catch (IllegalAccessException iae) {
322 errorMessage = iae.getMessage();
328 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
329 Constructor constructor = linker.getConstructor(new Class[]{ Class.class });
330 linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
331 } catch (ClassNotFoundException cnfe) {
332 errorMessage = cnfe.getMessage();
334 } catch (NoSuchMethodException nsme) {
335 errorMessage = nsme.getMessage();
337 } catch (InvocationTargetException ite) {
338 errorMessage = ite.getMessage();
340 } catch (InstantiationException ie) {
341 errorMessage = ie.getMessage();
343 } catch (IllegalAccessException iae) {
344 errorMessage = iae.getMessage();
350 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
351 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
352 } catch (ClassNotFoundException cnfe) {
353 errorMessage = cnfe.getMessage();
355 } catch (NoSuchMethodException nsme) {
356 errorMessage = nsme.getMessage();
367 * Attempts to locate the default web browser on the local system. Caches results so it
368 * only locates the browser once for each use of this class per JVM instance.
369 * @return The browser for the system. Note that this may not be what you would consider
370 * to be a standard web browser; instead, it's the application that gets called to
371 * open the default web browser. In some cases, this will be a non-String object
372 * that provides the means of calling the default browser.
374 private static Object locateBrowser() {
375 if (browser != null) {
381 Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
382 Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
383 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
384 Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
385 // Don't set browser = appleEvent because then the next time we call
386 // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
387 // added the relevant parameter. Instead, regenerate the AppleEvent every time.
388 // There's probably a way to do this better; if any has any ideas, please let
391 } catch (IllegalAccessException iae) {
393 errorMessage = iae.getMessage();
395 } catch (InstantiationException ie) {
397 errorMessage = ie.getMessage();
399 } catch (InvocationTargetException ite) {
401 errorMessage = ite.getMessage();
407 systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
408 } catch (IllegalArgumentException iare) {
410 errorMessage = iare.getMessage();
412 } catch (IllegalAccessException iae) {
414 errorMessage = iae.getMessage();
416 } catch (InvocationTargetException ite) {
418 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
421 String[] systemFolderFiles = systemFolder.list();
422 // Avoid a FilenameFilter because that can't be stopped mid-list
423 for(int i = 0; i < systemFolderFiles.length; i++) {
425 File file = new File(systemFolder, systemFolderFiles[i]);
426 if (!file.isFile()) {
429 // We're looking for a file with a creator code of 'MACS' and
430 // a type of 'FNDR'. Only requiring the type results in non-Finder
431 // applications being picked up on certain Mac OS 9 systems,
432 // especially German ones, and sending a GURL event to those
433 // applications results in a logout under Multiple Users.
434 Object fileType = getFileType.invoke(null, new Object[] { file });
435 if (FINDER_TYPE.equals(fileType.toString())) {
436 Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
437 if (FINDER_CREATOR.equals(fileCreator.toString())) {
438 browser = file.toString(); // Actually the Finder, but that's OK
442 } catch (IllegalArgumentException iare) {
444 errorMessage = iare.getMessage();
446 } catch (IllegalAccessException iae) {
448 errorMessage = iae.getMessage();
450 } catch (InvocationTargetException ite) {
452 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
460 browser = ""; // Return something non-null
466 browser = "command.com";
470 browser = jalview.bin.Cache.applicationProperties.getProperty("jalview.browser");
472 // hope firefox exists :-/
481 * Attempts to open the default web browser to the given URL.
482 * @param url The URL to open
483 * @throws IOException If the web browser could not be located or does not run
485 public static void openURL(String url) throws IOException {
486 if (!loadedWithoutErrors) {
487 throw new IOException("Exception in finding browser: " + errorMessage);
489 Object browser = locateBrowser();
490 if (browser == null) {
491 throw new IOException("Unable to locate browser: " + errorMessage);
496 Object aeDesc = null;
498 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
499 putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
500 sendNoReply.invoke(browser, new Object[] { });
501 } catch (InvocationTargetException ite) {
502 throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
503 } catch (IllegalAccessException iae) {
504 throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
505 } catch (InstantiationException ie) {
506 throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
508 aeDesc = null; // Encourage it to get disposed if it was created
509 browser = null; // Ditto
513 Runtime.getRuntime().exec(new String[] { (String) browser, url } );
516 int[] instance = new int[1];
517 int result = ICStart(instance, 0);
519 int[] selectionStart = new int[] { 0 };
520 byte[] urlBytes = url.getBytes();
521 int[] selectionEnd = new int[] { urlBytes.length };
522 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
523 urlBytes.length, selectionStart,
526 // Ignore the return value; the URL was launched successfully
527 // regardless of what happens here.
530 throw new IOException("Unable to launch URL: " + result);
533 throw new IOException("Unable to create an Internet Config instance: " + result);
538 openURL.invoke(null, new Object[] { url });
539 } catch (InvocationTargetException ite) {
540 throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
541 } catch (IllegalAccessException iae) {
542 throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
547 // Add quotes around the URL to allow ampersands and other special
548 // characters to work.
549 Process process = Runtime.getRuntime().exec(new String[] { (String) browser,
550 FIRST_WINDOWS_PARAMETER,
551 SECOND_WINDOWS_PARAMETER,
552 THIRD_WINDOWS_PARAMETER,
554 // This avoids a memory leak on some versions of Java on Windows.
555 // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
559 } catch (InterruptedException ie) {
560 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
564 // Assume that we're on Unix and that Netscape (actually Firefox) is installed
566 // First, attempt to open the URL in a currently running session of Netscape
567 process = Runtime.getRuntime().exec(new String[] { (String) browser,
568 NETSCAPE_REMOTE_PARAMETER,
569 NETSCAPE_OPEN_PARAMETER_START +
571 NETSCAPE_OPEN_NEW_WINDOW +
572 NETSCAPE_OPEN_PARAMETER_END });
574 int exitCode = process.waitFor();
575 if (exitCode != 0) { // if Netscape was not open
576 Runtime.getRuntime().exec(new String[] { (String) browser, url });
578 } catch (InterruptedException ie) {
579 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
583 // This should never occur, but if it does, we'll try the simplest thing possible
584 Runtime.getRuntime().exec(new String[] { (String) browser, url });
590 * Methods required for Mac OS X. The presence of native methods does not cause
591 * any problems on other platforms.
593 private native static int ICStart(int[] instance, int signature);
594 private native static int ICStop(int[] instance);
595 private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
596 int[] selectionStart, int[] selectionEnd);