2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 import java.io.IOException;
24 import java.lang.reflect.Constructor;
25 import java.lang.reflect.Field;
26 import java.lang.reflect.InvocationTargetException;
27 import java.lang.reflect.Method;
30 * BrowserLauncher is a class that provides one static method, openURL, which opens the default
31 * web browser for the current user of the system to the given URL. It may support other
32 * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
33 * tested and is not guaranteed to work.
35 * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
36 * that are not part of the standard JDK. What we're trying to do, though, is to take something
37 * that's frequently desirable but inherently platform-specific -- opening a default browser --
38 * and allow programmers (you, for example) to do so without worrying about dropping into native
39 * code or doing anything else similarly evil.
41 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
42 * modification or a need for additional libraries. All classes that are required on certain
43 * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
44 * found, will not cause this to do anything other than returning an error when opening the
47 * There are certain system requirements for this class, as it's running through Runtime.exec(),
48 * which is Java's way of making a native system call. Currently, this requires that a Macintosh
49 * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
50 * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
51 * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
52 * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
53 * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
54 * back from the inherently platform-sensitive concept of a default browser and simply attempts
55 * to launch Netscape via a shell command.
57 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu) and may be
58 * redistributed or modified in any form without restrictions as long as the portion of this
59 * comment from this paragraph through the end of the comment is not removed. The author
60 * requests that he be notified of any application, applet, or other binary that makes use of
61 * this code, but that's more out of curiosity than anything and is not required. This software
62 * includes no warranty. The author is not repsonsible for any loss of data or functionality
63 * or any adverse or unexpected effects of using this software.
66 * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
67 * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
68 * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
70 * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
71 * @version 1.4b1 (Released June 20, 2001)
73 public class BrowserLauncher {
76 * The Java virtual machine that we are running on. Actually, in most cases we only care
77 * about the operating system, but some operating systems require us to switch on the VM. */
78 private static int jvm;
80 /** The browser for the system */
81 private static Object browser;
84 * Caches whether any classes, methods, and fields that are not part of the JDK and need to
85 * be dynamically loaded at runtime loaded successfully.
87 * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
90 private static boolean loadedWithoutErrors;
92 /** The com.apple.mrj.MRJFileUtils class */
93 private static Class mrjFileUtilsClass;
95 /** The com.apple.mrj.MRJOSType class */
96 private static Class mrjOSTypeClass;
98 /** The com.apple.MacOS.AEDesc class */
99 private static Class aeDescClass;
101 /** The <init>(int) method of com.apple.MacOS.AETarget */
102 private static Constructor aeTargetConstructor;
104 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
105 private static Constructor appleEventConstructor;
107 /** The <init>(String) method of com.apple.MacOS.AEDesc */
108 private static Constructor aeDescConstructor;
110 /** The findFolder method of com.apple.mrj.MRJFileUtils */
111 private static Method findFolder;
113 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
114 private static Method getFileCreator;
116 /** The getFileType method of com.apple.mrj.MRJFileUtils */
117 private static Method getFileType;
119 /** The openURL method of com.apple.mrj.MRJFileUtils */
120 private static Method openURL;
122 /** The makeOSType method of com.apple.MacOS.OSUtils */
123 private static Method makeOSType;
125 /** The putParameter method of com.apple.MacOS.AppleEvent */
126 private static Method putParameter;
128 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
129 private static Method sendNoReply;
131 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
132 private static Object kSystemFolderType;
134 /** The keyDirectObject AppleEvent parameter type */
135 private static Integer keyDirectObject;
137 /** The kAutoGenerateReturnID AppleEvent code */
138 private static Integer kAutoGenerateReturnID;
140 /** The kAnyTransactionID AppleEvent code */
141 private static Integer kAnyTransactionID;
143 /** The linkage object required for JDirect 3 on Mac OS X. */
144 private static Object linkage;
146 /** The framework to reference on Mac OS X */
147 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
149 /** JVM constant for MRJ 2.0 */
150 private static final int MRJ_2_0 = 0;
152 /** JVM constant for MRJ 2.1 or later */
153 private static final int MRJ_2_1 = 1;
155 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
156 private static final int MRJ_3_0 = 3;
158 /** JVM constant for MRJ 3.1 */
159 private static final int MRJ_3_1 = 4;
161 /** JVM constant for any Windows NT JVM */
162 private static final int WINDOWS_NT = 5;
164 /** JVM constant for any Windows 9x JVM */
165 private static final int WINDOWS_9x = 6;
167 /** JVM constant for any other platform */
168 private static final int OTHER = -1;
171 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
172 * systems from working properly.
174 private static final String FINDER_TYPE = "FNDR";
177 * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
180 private static final String FINDER_CREATOR = "MACS";
182 /** The name for the AppleEvent type corresponding to a GetURL event. */
183 private static final String GURL_EVENT = "GURL";
186 * The first parameter that needs to be passed into Runtime.exec() to open the default web
187 * browser on Windows.
189 private static final String FIRST_WINDOWS_PARAMETER = "/c";
191 /** The second parameter for Runtime.exec() on Windows. */
192 private static final String SECOND_WINDOWS_PARAMETER = "start";
195 * The third parameter for Runtime.exec() on Windows. This is a "title"
196 * parameter that the command line expects. Setting this parameter allows
197 * URLs containing spaces to work.
199 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
202 * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
203 * on many command-line systems.
205 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
206 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
207 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
208 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
211 * The message from any exception thrown throughout the initialization process.
213 private static String errorMessage;
216 * An initialization block that determines the operating system and loads the necessary
220 loadedWithoutErrors = true;
221 String osName = System.getProperty("os.name");
222 if (osName.startsWith("Mac OS")) {
223 String mrjVersion = System.getProperty("mrj.version");
224 String majorMRJVersion = mrjVersion.substring(0, 3);
226 double version = Double.valueOf(majorMRJVersion).doubleValue();
229 } else if (version >= 2.1 && version < 3) {
230 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
231 // works via Runtime.exec() and 2.2 supports that but has an openURL() method
232 // as well that we currently ignore.
234 } else if (version == 3.0) {
236 } else if (version >= 3.1) {
237 // Assume that all 3.1 and later versions of MRJ work the same.
240 loadedWithoutErrors = false;
241 errorMessage = "Unsupported MRJ version: " + version;
243 } catch (NumberFormatException nfe) {
244 loadedWithoutErrors = false;
245 errorMessage = "Invalid MRJ version: " + mrjVersion;
247 } else if (osName.startsWith("Windows")) {
248 if (osName.indexOf("9") != -1) {
257 if (loadedWithoutErrors) { // if we haven't hit any errors yet
258 loadedWithoutErrors = loadClasses();
263 * This class should be never be instantiated; this just ensures so.
265 private BrowserLauncher() { }
268 * Called by a static initializer to load any classes, fields, and methods required at runtime
269 * to locate the user's web browser.
270 * @return <code>true</code> if all intialization succeeded
271 * <code>false</code> if any portion of the initialization failed
273 private static boolean loadClasses() {
277 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
278 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
279 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
280 Class aeClass = Class.forName("com.apple.MacOS.ae");
281 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
283 aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class });
284 appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
285 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });
287 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class });
288 putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass });
289 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { });
291 Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
292 keyDirectObject = (Integer) keyDirectObjectField.get(null);
293 Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
294 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
295 Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
296 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
297 } catch (ClassNotFoundException cnfe) {
298 errorMessage = cnfe.getMessage();
300 } catch (NoSuchMethodException nsme) {
301 errorMessage = nsme.getMessage();
303 } catch (NoSuchFieldException nsfe) {
304 errorMessage = nsfe.getMessage();
306 } catch (IllegalAccessException iae) {
307 errorMessage = iae.getMessage();
313 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
314 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
315 Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
316 kSystemFolderType = systemFolderField.get(null);
317 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
318 getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
319 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
320 } catch (ClassNotFoundException cnfe) {
321 errorMessage = cnfe.getMessage();
323 } catch (NoSuchFieldException nsfe) {
324 errorMessage = nsfe.getMessage();
326 } catch (NoSuchMethodException nsme) {
327 errorMessage = nsme.getMessage();
329 } catch (SecurityException se) {
330 errorMessage = se.getMessage();
332 } catch (IllegalAccessException iae) {
333 errorMessage = iae.getMessage();
339 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
340 Constructor constructor = linker.getConstructor(new Class[]{ Class.class });
341 linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
342 } catch (ClassNotFoundException cnfe) {
343 errorMessage = cnfe.getMessage();
345 } catch (NoSuchMethodException nsme) {
346 errorMessage = nsme.getMessage();
348 } catch (InvocationTargetException ite) {
349 errorMessage = ite.getMessage();
351 } catch (InstantiationException ie) {
352 errorMessage = ie.getMessage();
354 } catch (IllegalAccessException iae) {
355 errorMessage = iae.getMessage();
361 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
362 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
363 } catch (ClassNotFoundException cnfe) {
364 errorMessage = cnfe.getMessage();
366 } catch (NoSuchMethodException nsme) {
367 errorMessage = nsme.getMessage();
378 * Attempts to locate the default web browser on the local system. Caches results so it
379 * only locates the browser once for each use of this class per JVM instance.
380 * @return The browser for the system. Note that this may not be what you would consider
381 * to be a standard web browser; instead, it's the application that gets called to
382 * open the default web browser. In some cases, this will be a non-String object
383 * that provides the means of calling the default browser.
385 private static Object locateBrowser() {
386 if (browser != null) {
392 Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
393 Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
394 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
395 Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
396 // Don't set browser = appleEvent because then the next time we call
397 // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
398 // added the relevant parameter. Instead, regenerate the AppleEvent every time.
399 // There's probably a way to do this better; if any has any ideas, please let
402 } catch (IllegalAccessException iae) {
404 errorMessage = iae.getMessage();
406 } catch (InstantiationException ie) {
408 errorMessage = ie.getMessage();
410 } catch (InvocationTargetException ite) {
412 errorMessage = ite.getMessage();
418 systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
419 } catch (IllegalArgumentException iare) {
421 errorMessage = iare.getMessage();
423 } catch (IllegalAccessException iae) {
425 errorMessage = iae.getMessage();
427 } catch (InvocationTargetException ite) {
429 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
432 String[] systemFolderFiles = systemFolder.list();
433 // Avoid a FilenameFilter because that can't be stopped mid-list
434 for(int i = 0; i < systemFolderFiles.length; i++) {
436 File file = new File(systemFolder, systemFolderFiles[i]);
437 if (!file.isFile()) {
440 // We're looking for a file with a creator code of 'MACS' and
441 // a type of 'FNDR'. Only requiring the type results in non-Finder
442 // applications being picked up on certain Mac OS 9 systems,
443 // especially German ones, and sending a GURL event to those
444 // applications results in a logout under Multiple Users.
445 Object fileType = getFileType.invoke(null, new Object[] { file });
446 if (FINDER_TYPE.equals(fileType.toString())) {
447 Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
448 if (FINDER_CREATOR.equals(fileCreator.toString())) {
449 browser = file.toString(); // Actually the Finder, but that's OK
453 } catch (IllegalArgumentException iare) {
455 errorMessage = iare.getMessage();
457 } catch (IllegalAccessException iae) {
459 errorMessage = iae.getMessage();
461 } catch (InvocationTargetException ite) {
463 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
471 browser = ""; // Return something non-null
477 browser = "command.com";
481 browser = jalview.bin.Cache.applicationProperties.getProperty("jalview.browser");
483 // hope firefox exists :-/
492 * Attempts to open the default web browser to the given URL.
493 * @param url The URL to open
494 * @throws IOException If the web browser could not be located or does not run
496 public static void openURL(String url) throws IOException {
497 if (!loadedWithoutErrors) {
498 throw new IOException("Exception in finding browser: " + errorMessage);
500 Object browser = locateBrowser();
501 if (browser == null) {
502 throw new IOException("Unable to locate browser: " + errorMessage);
507 Object aeDesc = null;
509 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
510 putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
511 sendNoReply.invoke(browser, new Object[] { });
512 } catch (InvocationTargetException ite) {
513 throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
514 } catch (IllegalAccessException iae) {
515 throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
516 } catch (InstantiationException ie) {
517 throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
519 aeDesc = null; // Encourage it to get disposed if it was created
520 browser = null; // Ditto
524 Runtime.getRuntime().exec(new String[] { (String) browser, url } );
527 int[] instance = new int[1];
528 int result = ICStart(instance, 0);
530 int[] selectionStart = new int[] { 0 };
531 byte[] urlBytes = url.getBytes();
532 int[] selectionEnd = new int[] { urlBytes.length };
533 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
534 urlBytes.length, selectionStart,
537 // Ignore the return value; the URL was launched successfully
538 // regardless of what happens here.
541 throw new IOException("Unable to launch URL: " + result);
544 throw new IOException("Unable to create an Internet Config instance: " + result);
549 openURL.invoke(null, new Object[] { url });
550 } catch (InvocationTargetException ite) {
551 throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
552 } catch (IllegalAccessException iae) {
553 throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
558 // Add quotes around the URL to allow ampersands and other special
559 // characters to work.
560 Process process = Runtime.getRuntime().exec(new String[] { (String) browser,
561 FIRST_WINDOWS_PARAMETER,
562 SECOND_WINDOWS_PARAMETER,
563 THIRD_WINDOWS_PARAMETER,
565 // This avoids a memory leak on some versions of Java on Windows.
566 // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
570 } catch (InterruptedException ie) {
571 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
575 // Assume that we're on Unix and that Netscape (actually Firefox) is installed
577 // First, attempt to open the URL in a currently running session of Netscape
580 /* System.out.println("Executing : "+browser+" "+
581 NETSCAPE_REMOTE_PARAMETER+" "+
582 NETSCAPE_OPEN_PARAMETER_START +
584 NETSCAPE_OPEN_NEW_WINDOW +
585 NETSCAPE_OPEN_PARAMETER_END);
587 process = Runtime.getRuntime().exec(new String[] { (String) browser,
588 NETSCAPE_REMOTE_PARAMETER,
589 NETSCAPE_OPEN_PARAMETER_START +
591 NETSCAPE_OPEN_NEW_WINDOW +
592 NETSCAPE_OPEN_PARAMETER_END });
594 int exitCode = process.waitFor();
595 if (exitCode != 0) { // if Netscape was not open
597 // System.out.println("Executing : "+browser+" "+url+"\n");
598 Runtime.getRuntime().exec(new String[] { (String) browser, url });
600 } catch (InterruptedException ie) {
601 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
605 // This should never occur, but if it does, we'll try the simplest thing possible
606 Runtime.getRuntime().exec(new String[] { (String) browser, url });
612 * Methods required for Mac OS X. The presence of native methods does not cause
613 * any problems on other platforms.
615 private native static int ICStart(int[] instance, int signature);
616 private native static int ICStop(int[] instance);
617 private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
618 int[] selectionStart, int[] selectionEnd);