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
19 package jalview.util;
\r
21 import java.io.File;
\r
22 import java.io.IOException;
\r
24 import java.lang.reflect.Constructor;
\r
25 import java.lang.reflect.Field;
\r
26 import java.lang.reflect.InvocationTargetException;
\r
27 import java.lang.reflect.Method;
\r
31 * BrowserLauncher is a class that provides one static method, openURL, which opens the default
32 * web browser for the current user of the system to the given URL. It may support other
33 * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
34 * tested and is not guaranteed to work.
36 * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
37 * that are not part of the standard JDK. What we're trying to do, though, is to take something
38 * that's frequently desirable but inherently platform-specific -- opening a default browser --
39 * and allow programmers (you, for example) to do so without worrying about dropping into native
40 * code or doing anything else similarly evil.
42 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
43 * modification or a need for additional libraries. All classes that are required on certain
44 * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
45 * found, will not cause this to do anything other than returning an error when opening the
48 * There are certain system requirements for this class, as it's running through Runtime.exec(),
49 * which is Java's way of making a native system call. Currently, this requires that a Macintosh
50 * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
51 * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
52 * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
53 * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
54 * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
55 * back from the inherently platform-sensitive concept of a default browser and simply attempts
56 * to launch Netscape via a shell command.
58 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu) and may be
59 * redistributed or modified in any form without restrictions as long as the portion of this
60 * comment from this paragraph through the end of the comment is not removed. The author
61 * requests that he be notified of any application, applet, or other binary that makes use of
62 * this code, but that's more out of curiosity than anything and is not required. This software
63 * includes no warranty. The author is not repsonsible for any loss of data or functionality
64 * or any adverse or unexpected effects of using this software.
67 * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
68 * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
69 * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
71 * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
72 * @version 1.4b1 (Released June 20, 2001)
74 public class BrowserLauncher {
\r
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. */
\r
78 private static int jvm;
\r
80 /** The browser for the system */
\r
81 private static Object browser;
\r
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;
\r
92 /** The com.apple.mrj.MRJFileUtils class */
\r
93 private static Class mrjFileUtilsClass;
\r
95 /** The com.apple.mrj.MRJOSType class */
\r
96 private static Class mrjOSTypeClass;
\r
98 /** The com.apple.MacOS.AEDesc class */
\r
99 private static Class aeDescClass;
\r
101 /** The <init>(int) method of com.apple.MacOS.AETarget */
\r
102 private static Constructor aeTargetConstructor;
\r
104 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
\r
105 private static Constructor appleEventConstructor;
\r
107 /** The <init>(String) method of com.apple.MacOS.AEDesc */
\r
108 private static Constructor aeDescConstructor;
\r
110 /** The findFolder method of com.apple.mrj.MRJFileUtils */
\r
111 private static Method findFolder;
\r
113 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
\r
114 private static Method getFileCreator;
\r
116 /** The getFileType method of com.apple.mrj.MRJFileUtils */
\r
117 private static Method getFileType;
\r
119 /** The openURL method of com.apple.mrj.MRJFileUtils */
\r
120 private static Method openURL;
\r
122 /** The makeOSType method of com.apple.MacOS.OSUtils */
\r
123 private static Method makeOSType;
\r
125 /** The putParameter method of com.apple.MacOS.AppleEvent */
\r
126 private static Method putParameter;
\r
128 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
\r
129 private static Method sendNoReply;
\r
131 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
\r
132 private static Object kSystemFolderType;
\r
134 /** The keyDirectObject AppleEvent parameter type */
\r
135 private static Integer keyDirectObject;
\r
137 /** The kAutoGenerateReturnID AppleEvent code */
\r
138 private static Integer kAutoGenerateReturnID;
\r
140 /** The kAnyTransactionID AppleEvent code */
\r
141 private static Integer kAnyTransactionID;
\r
143 /** The linkage object required for JDirect 3 on Mac OS X. */
\r
144 private static Object linkage;
\r
146 /** The framework to reference on Mac OS X */
\r
147 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
\r
149 /** JVM constant for MRJ 2.0 */
\r
150 private static final int MRJ_2_0 = 0;
\r
152 /** JVM constant for MRJ 2.1 or later */
\r
153 private static final int MRJ_2_1 = 1;
\r
155 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
\r
156 private static final int MRJ_3_0 = 3;
\r
158 /** JVM constant for MRJ 3.1 */
\r
159 private static final int MRJ_3_1 = 4;
\r
161 /** JVM constant for any Windows NT JVM */
\r
162 private static final int WINDOWS_NT = 5;
\r
164 /** JVM constant for any Windows 9x JVM */
\r
165 private static final int WINDOWS_9x = 6;
\r
167 /** JVM constant for any other platform */
\r
168 private static final int OTHER = -1;
\r
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";
\r
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";
\r
182 /** The name for the AppleEvent type corresponding to a GetURL event. */
\r
183 private static final String GURL_EVENT = "GURL";
\r
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";
\r
191 /** The second parameter for Runtime.exec() on Windows. */
\r
192 private static final String SECOND_WINDOWS_PARAMETER = "start";
\r
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 = "\"\"";
\r
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";
\r
206 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
\r
207 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
\r
208 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
\r
211 * The message from any exception thrown throughout the initialization process.
213 private static String errorMessage;
\r
216 * An initialization block that determines the operating system and loads the necessary
220 loadedWithoutErrors = true;
\r
222 String osName = System.getProperty("os.name");
\r
224 if (osName.startsWith("Mac OS")) {
\r
225 String mrjVersion = System.getProperty("mrj.version");
\r
226 String majorMRJVersion = mrjVersion.substring(0, 3);
\r
229 double version = Double.valueOf(majorMRJVersion).doubleValue();
\r
231 if (version == 2) {
\r
233 } else if ((version >= 2.1) && (version < 3)) {
\r
234 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
\r
235 // works via Runtime.exec() and 2.2 supports that but has an openURL() method
\r
236 // as well that we currently ignore.
\r
238 } else if (version == 3.0) {
\r
240 } else if (version >= 3.1) {
\r
241 // Assume that all 3.1 and later versions of MRJ work the same.
\r
244 loadedWithoutErrors = false;
\r
245 errorMessage = "Unsupported MRJ version: " + version;
\r
247 } catch (NumberFormatException nfe) {
\r
248 loadedWithoutErrors = false;
\r
249 errorMessage = "Invalid MRJ version: " + mrjVersion;
\r
251 } else if (osName.startsWith("Windows")) {
\r
252 if (osName.indexOf("9") != -1) {
\r
261 if (loadedWithoutErrors) { // if we haven't hit any errors yet
\r
262 loadedWithoutErrors = loadClasses();
\r
267 * This class should be never be instantiated; this just ensures so.
269 private BrowserLauncher() {
\r
273 * Called by a static initializer to load any classes, fields, and methods required at runtime
274 * to locate the user's web browser.
275 * @return <code>true</code> if all intialization succeeded
276 * <code>false</code> if any portion of the initialization failed
278 private static boolean loadClasses() {
\r
283 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
\r
284 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
\r
285 Class appleEventClass = Class.forName(
\r
286 "com.apple.MacOS.AppleEvent");
\r
287 Class aeClass = Class.forName("com.apple.MacOS.ae");
\r
288 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
\r
290 aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[] {
\r
293 appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] {
\r
294 int.class, int.class, aeTargetClass, int.class,
\r
297 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] {
\r
301 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
\r
302 new Class[] { String.class });
\r
303 putParameter = appleEventClass.getDeclaredMethod("putParameter",
\r
304 new Class[] { int.class, aeDescClass });
\r
305 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
\r
308 Field keyDirectObjectField = aeClass.getDeclaredField(
\r
309 "keyDirectObject");
\r
310 keyDirectObject = (Integer) keyDirectObjectField.get(null);
\r
312 Field autoGenerateReturnIDField = appleEventClass.getDeclaredField(
\r
313 "kAutoGenerateReturnID");
\r
314 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
\r
316 Field anyTransactionIDField = appleEventClass.getDeclaredField(
\r
317 "kAnyTransactionID");
\r
318 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
\r
319 } catch (ClassNotFoundException cnfe) {
\r
320 errorMessage = cnfe.getMessage();
\r
323 } catch (NoSuchMethodException nsme) {
\r
324 errorMessage = nsme.getMessage();
\r
327 } catch (NoSuchFieldException nsfe) {
\r
328 errorMessage = nsfe.getMessage();
\r
331 } catch (IllegalAccessException iae) {
\r
332 errorMessage = iae.getMessage();
\r
342 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
\r
343 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
\r
345 Field systemFolderField = mrjFileUtilsClass.getDeclaredField(
\r
346 "kSystemFolderType");
\r
347 kSystemFolderType = systemFolderField.get(null);
\r
348 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
\r
349 new Class[] { mrjOSTypeClass });
\r
350 getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator",
\r
351 new Class[] { File.class });
\r
352 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
\r
353 new Class[] { File.class });
\r
354 } catch (ClassNotFoundException cnfe) {
\r
355 errorMessage = cnfe.getMessage();
\r
358 } catch (NoSuchFieldException nsfe) {
\r
359 errorMessage = nsfe.getMessage();
\r
362 } catch (NoSuchMethodException nsme) {
\r
363 errorMessage = nsme.getMessage();
\r
366 } catch (SecurityException se) {
\r
367 errorMessage = se.getMessage();
\r
370 } catch (IllegalAccessException iae) {
\r
371 errorMessage = iae.getMessage();
\r
381 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
\r
382 Constructor constructor = linker.getConstructor(new Class[] {
\r
385 linkage = constructor.newInstance(new Object[] {
\r
386 BrowserLauncher.class
\r
388 } catch (ClassNotFoundException cnfe) {
\r
389 errorMessage = cnfe.getMessage();
\r
392 } catch (NoSuchMethodException nsme) {
\r
393 errorMessage = nsme.getMessage();
\r
396 } catch (InvocationTargetException ite) {
\r
397 errorMessage = ite.getMessage();
\r
400 } catch (InstantiationException ie) {
\r
401 errorMessage = ie.getMessage();
\r
404 } catch (IllegalAccessException iae) {
\r
405 errorMessage = iae.getMessage();
\r
415 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
\r
416 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
\r
417 new Class[] { String.class });
\r
418 } catch (ClassNotFoundException cnfe) {
\r
419 errorMessage = cnfe.getMessage();
\r
422 } catch (NoSuchMethodException nsme) {
\r
423 errorMessage = nsme.getMessage();
\r
438 * Attempts to locate the default web browser on the local system. Caches results so it
439 * only locates the browser once for each use of this class per JVM instance.
440 * @return The browser for the system. Note that this may not be what you would consider
441 * to be a standard web browser; instead, it's the application that gets called to
442 * open the default web browser. In some cases, this will be a non-String object
443 * that provides the means of calling the default browser.
445 private static Object locateBrowser() {
\r
446 if (browser != null) {
\r
454 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
\r
455 new Object[] { FINDER_CREATOR });
\r
456 Object aeTarget = aeTargetConstructor.newInstance(new Object[] {
\r
459 Integer gurlType = (Integer) makeOSType.invoke(null,
\r
460 new Object[] { GURL_EVENT });
\r
461 Object appleEvent = appleEventConstructor.newInstance(new Object[] {
\r
462 gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
\r
466 // Don't set browser = appleEvent because then the next time we call
\r
467 // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
\r
468 // added the relevant parameter. Instead, regenerate the AppleEvent every time.
\r
469 // There's probably a way to do this better; if any has any ideas, please let
\r
472 } catch (IllegalAccessException iae) {
\r
474 errorMessage = iae.getMessage();
\r
477 } catch (InstantiationException ie) {
\r
479 errorMessage = ie.getMessage();
\r
482 } catch (InvocationTargetException ite) {
\r
484 errorMessage = ite.getMessage();
\r
494 systemFolder = (File) findFolder.invoke(null,
\r
495 new Object[] { kSystemFolderType });
\r
496 } catch (IllegalArgumentException iare) {
\r
498 errorMessage = iare.getMessage();
\r
501 } catch (IllegalAccessException iae) {
\r
503 errorMessage = iae.getMessage();
\r
506 } catch (InvocationTargetException ite) {
\r
508 errorMessage = ite.getTargetException().getClass() + ": " +
\r
509 ite.getTargetException().getMessage();
\r
514 String[] systemFolderFiles = systemFolder.list();
\r
516 // Avoid a FilenameFilter because that can't be stopped mid-list
\r
517 for (int i = 0; i < systemFolderFiles.length; i++) {
\r
519 File file = new File(systemFolder, systemFolderFiles[i]);
\r
521 if (!file.isFile()) {
\r
525 // We're looking for a file with a creator code of 'MACS' and
\r
526 // a type of 'FNDR'. Only requiring the type results in non-Finder
\r
527 // applications being picked up on certain Mac OS 9 systems,
\r
528 // especially German ones, and sending a GURL event to those
\r
529 // applications results in a logout under Multiple Users.
\r
530 Object fileType = getFileType.invoke(null,
\r
531 new Object[] { file });
\r
533 if (FINDER_TYPE.equals(fileType.toString())) {
\r
534 Object fileCreator = getFileCreator.invoke(null,
\r
535 new Object[] { file });
\r
537 if (FINDER_CREATOR.equals(fileCreator.toString())) {
\r
538 browser = file.toString(); // Actually the Finder, but that's OK
\r
543 } catch (IllegalArgumentException iare) {
\r
545 errorMessage = iare.getMessage();
\r
548 } catch (IllegalAccessException iae) {
\r
550 errorMessage = iae.getMessage();
\r
553 } catch (InvocationTargetException ite) {
\r
555 errorMessage = ite.getTargetException().getClass() + ": " +
\r
556 ite.getTargetException().getMessage();
\r
568 browser = ""; // Return something non-null
\r
573 browser = "cmd.exe";
\r
578 browser = "command.com";
\r
582 case OTHER:default:
\r
583 browser = jalview.bin.Cache.applicationProperties.getProperty(
\r
584 "jalview.browser");
\r
586 if (browser == null) {
\r
587 // hope firefox exists :-/
\r
588 browser = "firefox";
\r
598 * Attempts to open the default web browser to the given URL.
599 * @param url The URL to open
600 * @throws IOException If the web browser could not be located or does not run
602 public static void openURL(String url) throws IOException {
\r
603 if (!loadedWithoutErrors) {
\r
604 throw new IOException("Exception in finding browser: " +
\r
608 Object browser = locateBrowser();
\r
610 if (browser == null) {
\r
611 throw new IOException("Unable to locate browser: " + errorMessage);
\r
617 Object aeDesc = null;
\r
620 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
\r
621 putParameter.invoke(browser,
\r
622 new Object[] { keyDirectObject, aeDesc });
\r
623 sendNoReply.invoke(browser, new Object[] { });
\r
624 } catch (InvocationTargetException ite) {
\r
625 throw new IOException(
\r
626 "InvocationTargetException while creating AEDesc: " +
\r
628 } catch (IllegalAccessException iae) {
\r
629 throw new IOException(
\r
630 "IllegalAccessException while building AppleEvent: " +
\r
632 } catch (InstantiationException ie) {
\r
633 throw new IOException(
\r
634 "InstantiationException while creating AEDesc: " +
\r
637 aeDesc = null; // Encourage it to get disposed if it was created
\r
638 browser = null; // Ditto
\r
644 Runtime.getRuntime().exec(new String[] { (String) browser, url });
\r
650 int[] instance = new int[1];
\r
651 int result = ICStart(instance, 0);
\r
654 int[] selectionStart = new int[] { 0 };
\r
655 byte[] urlBytes = url.getBytes();
\r
656 int[] selectionEnd = new int[] { urlBytes.length };
\r
657 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
\r
658 urlBytes.length, selectionStart, selectionEnd);
\r
661 // Ignore the return value; the URL was launched successfully
\r
662 // regardless of what happens here.
\r
665 throw new IOException("Unable to launch URL: " + result);
\r
668 throw new IOException(
\r
669 "Unable to create an Internet Config instance: " + result);
\r
677 openURL.invoke(null, new Object[] { url });
\r
678 } catch (InvocationTargetException ite) {
\r
679 throw new IOException(
\r
680 "InvocationTargetException while calling openURL: " +
\r
682 } catch (IllegalAccessException iae) {
\r
683 throw new IOException(
\r
684 "IllegalAccessException while calling openURL: " +
\r
693 // Add quotes around the URL to allow ampersands and other special
\r
694 // characters to work.
\r
695 Process process = Runtime.getRuntime().exec(new String[] {
\r
696 (String) browser, FIRST_WINDOWS_PARAMETER,
\r
697 SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
\r
701 // This avoids a memory leak on some versions of Java on Windows.
\r
702 // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
\r
705 process.exitValue();
\r
706 } catch (InterruptedException ie) {
\r
707 throw new IOException(
\r
708 "InterruptedException while launching browser: " +
\r
716 // Assume that we're on Unix and that Netscape (actually Firefox) is installed
\r
717 // First, attempt to open the URL in a currently running session of Netscape
\r
718 // JBPNote log debug
\r
720 /* System.out.println("Executing : "+browser+" "+
721 NETSCAPE_REMOTE_PARAMETER+" "+
722 NETSCAPE_OPEN_PARAMETER_START +
724 NETSCAPE_OPEN_NEW_WINDOW +
725 NETSCAPE_OPEN_PARAMETER_END);
727 process = Runtime.getRuntime().exec(new String[] {
\r
728 (String) browser, NETSCAPE_REMOTE_PARAMETER,
\r
730 NETSCAPE_OPEN_PARAMETER_START + url +
\r
731 NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END
\r
735 int exitCode = process.waitFor();
\r
737 if (exitCode != 0) { // if Netscape was not open
\r
738 Runtime.getRuntime().exec(new String[] { (String) browser, url });
\r
740 } catch (InterruptedException ie) {
\r
741 throw new IOException(
\r
742 "InterruptedException while launching browser: " +
\r
750 // This should never occur, but if it does, we'll try the simplest thing possible
\r
751 Runtime.getRuntime().exec(new String[] { (String) browser, url });
\r
758 * Methods required for Mac OS X. The presence of native methods does not cause
759 * any problems on other platforms.
761 private native static int ICStart(int[] instance, int signature);
\r
763 private native static int ICStop(int[] instance);
\r
765 private native static int ICLaunchURL(int instance, byte[] hint,
\r
766 byte[] data, int len, int[] selectionStart, int[] selectionEnd);
\r