2 * Jalview - A Sequence Alignment Editor and Viewer
3 * Copyright (C) 2006 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
22 import java.lang.reflect.*;
25 * BrowserLauncher is a class that provides one static method, openURL, which opens the default
26 * web browser for the current user of the system to the given URL. It may support other
27 * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
28 * tested and is not guaranteed to work.
30 * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
31 * that are not part of the standard JDK. What we're trying to do, though, is to take something
32 * that's frequently desirable but inherently platform-specific -- opening a default browser --
33 * and allow programmers (you, for example) to do so without worrying about dropping into native
34 * code or doing anything else similarly evil.
36 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
37 * modification or a need for additional libraries. All classes that are required on certain
38 * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
39 * found, will not cause this to do anything other than returning an error when opening the
42 * There are certain system requirements for this class, as it's running through Runtime.exec(),
43 * which is Java's way of making a native system call. Currently, this requires that a Macintosh
44 * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
45 * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
46 * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
47 * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
48 * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
49 * back from the inherently platform-sensitive concept of a default browser and simply attempts
50 * to launch Netscape via a shell command.
52 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu) and may be
53 * redistributed or modified in any form without restrictions as long as the portion of this
54 * comment from this paragraph through the end of the comment is not removed. The author
55 * requests that he be notified of any application, applet, or other binary that makes use of
56 * this code, but that's more out of curiosity than anything and is not required. This software
57 * includes no warranty. The author is not repsonsible for any loss of data or functionality
58 * or any adverse or unexpected effects of using this software.
61 * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
62 * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
63 * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
65 * @author Eric Albert (<a href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
66 * @version 1.4b1 (Released June 20, 2001)
68 public class BrowserLauncher
71 * The Java virtual machine that we are running on. Actually, in most cases we only care
72 * about the operating system, but some operating systems require us to switch on the VM. */
73 private static int jvm;
75 /** The browser for the system */
76 private static Object browser;
79 * Caches whether any classes, methods, and fields that are not part of the JDK and need to
80 * be dynamically loaded at runtime loaded successfully.
82 * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
85 private static boolean loadedWithoutErrors;
87 /** The com.apple.mrj.MRJFileUtils class */
88 private static Class mrjFileUtilsClass;
90 /** The com.apple.mrj.MRJOSType class */
91 private static Class mrjOSTypeClass;
93 /** The com.apple.MacOS.AEDesc class */
94 private static Class aeDescClass;
96 /** The <init>(int) method of com.apple.MacOS.AETarget */
97 private static Constructor aeTargetConstructor;
99 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
100 private static Constructor appleEventConstructor;
102 /** The <init>(String) method of com.apple.MacOS.AEDesc */
103 private static Constructor aeDescConstructor;
105 /** The findFolder method of com.apple.mrj.MRJFileUtils */
106 private static Method findFolder;
108 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
109 private static Method getFileCreator;
111 /** The getFileType method of com.apple.mrj.MRJFileUtils */
112 private static Method getFileType;
114 /** The openURL method of com.apple.mrj.MRJFileUtils */
115 private static Method openURL;
117 /** The makeOSType method of com.apple.MacOS.OSUtils */
118 private static Method makeOSType;
120 /** The putParameter method of com.apple.MacOS.AppleEvent */
121 private static Method putParameter;
123 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
124 private static Method sendNoReply;
126 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
127 private static Object kSystemFolderType;
129 /** The keyDirectObject AppleEvent parameter type */
130 private static Integer keyDirectObject;
132 /** The kAutoGenerateReturnID AppleEvent code */
133 private static Integer kAutoGenerateReturnID;
135 /** The kAnyTransactionID AppleEvent code */
136 private static Integer kAnyTransactionID;
138 /** The linkage object required for JDirect 3 on Mac OS X. */
139 private static Object linkage;
141 /** The framework to reference on Mac OS X */
142 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
144 /** JVM constant for MRJ 2.0 */
145 private static final int MRJ_2_0 = 0;
147 /** JVM constant for MRJ 2.1 or later */
148 private static final int MRJ_2_1 = 1;
150 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
151 private static final int MRJ_3_0 = 3;
153 /** JVM constant for MRJ 3.1 */
154 private static final int MRJ_3_1 = 4;
156 /** JVM constant for any Windows NT JVM */
157 private static final int WINDOWS_NT = 5;
159 /** JVM constant for any Windows 9x JVM */
160 private static final int WINDOWS_9x = 6;
162 /** JVM constant for any other platform */
163 private static final int OTHER = -1;
166 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
167 * systems from working properly.
169 private static final String FINDER_TYPE = "FNDR";
172 * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
175 private static final String FINDER_CREATOR = "MACS";
177 /** The name for the AppleEvent type corresponding to a GetURL event. */
178 private static final String GURL_EVENT = "GURL";
181 * The first parameter that needs to be passed into Runtime.exec() to open the default web
182 * browser on Windows.
184 private static final String FIRST_WINDOWS_PARAMETER = "/c";
186 /** The second parameter for Runtime.exec() on Windows. */
187 private static final String SECOND_WINDOWS_PARAMETER = "start";
190 * The third parameter for Runtime.exec() on Windows. This is a "title"
191 * parameter that the command line expects. Setting this parameter allows
192 * URLs containing spaces to work.
194 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
197 * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
198 * on many command-line systems.
200 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
201 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
202 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
203 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
206 * The message from any exception thrown throughout the initialization process.
208 private static String errorMessage;
211 * An initialization block that determines the operating system and loads the necessary
216 loadedWithoutErrors = true;
218 String osName = System.getProperty("os.name");
220 if (osName.startsWith("Mac OS"))
222 String mrjVersion = System.getProperty("mrj.version");
223 String majorMRJVersion = mrjVersion.substring(0, 3);
227 double version = Double.valueOf(majorMRJVersion).doubleValue();
233 else if ( (version >= 2.1) && (version < 3))
235 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
236 // works via Runtime.exec() and 2.2 supports that but has an openURL() method
237 // as well that we currently ignore.
240 else if (version == 3.0)
244 else if (version >= 3.1)
246 // Assume that all 3.1 and later versions of MRJ work the same.
251 loadedWithoutErrors = false;
252 errorMessage = "Unsupported MRJ version: " + version;
255 catch (NumberFormatException nfe)
257 loadedWithoutErrors = false;
258 errorMessage = "Invalid MRJ version: " + mrjVersion;
261 else if (osName.startsWith("Windows"))
263 if (osName.indexOf("9") != -1)
277 if (loadedWithoutErrors)
278 { // if we haven't hit any errors yet
279 loadedWithoutErrors = loadClasses();
284 * This class should be never be instantiated; this just ensures so.
286 private BrowserLauncher()
291 * Called by a static initializer to load any classes, fields, and methods required at runtime
292 * to locate the user's web browser.
293 * @return <code>true</code> if all intialization succeeded
294 * <code>false</code> if any portion of the initialization failed
296 private static boolean loadClasses()
304 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
305 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
306 Class appleEventClass = Class.forName(
307 "com.apple.MacOS.AppleEvent");
308 Class aeClass = Class.forName("com.apple.MacOS.ae");
309 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
311 aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class[]
315 appleEventConstructor = appleEventClass.getDeclaredConstructor(new
318 int.class, int.class, aeTargetClass, int.class,
321 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[]
326 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
329 putParameter = appleEventClass.getDeclaredMethod("putParameter",
331 {int.class, aeDescClass});
332 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
336 Field keyDirectObjectField = aeClass.getDeclaredField(
338 keyDirectObject = (Integer) keyDirectObjectField.get(null);
340 Field autoGenerateReturnIDField = appleEventClass.getDeclaredField(
341 "kAutoGenerateReturnID");
342 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
344 Field anyTransactionIDField = appleEventClass.getDeclaredField(
345 "kAnyTransactionID");
346 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
348 catch (ClassNotFoundException cnfe)
350 errorMessage = cnfe.getMessage();
354 catch (NoSuchMethodException nsme)
356 errorMessage = nsme.getMessage();
360 catch (NoSuchFieldException nsfe)
362 errorMessage = nsfe.getMessage();
366 catch (IllegalAccessException iae)
368 errorMessage = iae.getMessage();
380 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
381 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
383 Field systemFolderField = mrjFileUtilsClass.getDeclaredField(
384 "kSystemFolderType");
385 kSystemFolderType = systemFolderField.get(null);
386 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
389 getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator",
392 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
396 catch (ClassNotFoundException cnfe)
398 errorMessage = cnfe.getMessage();
402 catch (NoSuchFieldException nsfe)
404 errorMessage = nsfe.getMessage();
408 catch (NoSuchMethodException nsme)
410 errorMessage = nsme.getMessage();
414 catch (SecurityException se)
416 errorMessage = se.getMessage();
420 catch (IllegalAccessException iae)
422 errorMessage = iae.getMessage();
434 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
435 Constructor constructor = linker.getConstructor(new Class[]
439 linkage = constructor.newInstance(new Object[]
441 BrowserLauncher.class
444 catch (ClassNotFoundException cnfe)
446 errorMessage = cnfe.getMessage();
450 catch (NoSuchMethodException nsme)
452 errorMessage = nsme.getMessage();
456 catch (InvocationTargetException ite)
458 errorMessage = ite.getMessage();
462 catch (InstantiationException ie)
464 errorMessage = ie.getMessage();
468 catch (IllegalAccessException iae)
470 errorMessage = iae.getMessage();
482 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
483 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
487 catch (ClassNotFoundException cnfe)
489 errorMessage = cnfe.getMessage();
493 catch (NoSuchMethodException nsme)
495 errorMessage = nsme.getMessage();
511 * Attempts to locate the default web browser on the local system. s results so it
512 * only locates the browser once for each use of this class per JVM instance.
513 * @return The browser for the system. Note that this may not be what you would consider
514 * to be a standard web browser; instead, it's the application that gets called to
515 * open the default web browser. In some cases, this will be a non-String object
516 * that provides the means of calling the default browser.
518 private static Object locateBrowser()
531 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
534 Object aeTarget = aeTargetConstructor.newInstance(new Object[]
538 Integer gurlType = (Integer) makeOSType.invoke(null,
541 Object appleEvent = appleEventConstructor.newInstance(new Object[]
543 gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
547 // Don't set browser = appleEvent because then the next time we call
548 // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
549 // added the relevant parameter. Instead, regenerate the AppleEvent every time.
550 // There's probably a way to do this better; if any has any ideas, please let
554 catch (IllegalAccessException iae)
557 errorMessage = iae.getMessage();
561 catch (InstantiationException ie)
564 errorMessage = ie.getMessage();
568 catch (InvocationTargetException ite)
571 errorMessage = ite.getMessage();
582 systemFolder = (File) findFolder.invoke(null,
584 {kSystemFolderType});
586 catch (IllegalArgumentException iare)
589 errorMessage = iare.getMessage();
593 catch (IllegalAccessException iae)
596 errorMessage = iae.getMessage();
600 catch (InvocationTargetException ite)
603 errorMessage = ite.getTargetException().getClass() + ": " +
604 ite.getTargetException().getMessage();
609 String[] systemFolderFiles = systemFolder.list();
611 // Avoid a FilenameFilter because that can't be stopped mid-list
612 for (int i = 0; i < systemFolderFiles.length; i++)
616 File file = new File(systemFolder, systemFolderFiles[i]);
623 // We're looking for a file with a creator code of 'MACS' and
624 // a type of 'FNDR'. Only requiring the type results in non-Finder
625 // applications being picked up on certain Mac OS 9 systems,
626 // especially German ones, and sending a GURL event to those
627 // applications results in a logout under Multiple Users.
628 Object fileType = getFileType.invoke(null,
632 if (FINDER_TYPE.equals(fileType.toString()))
634 Object fileCreator = getFileCreator.invoke(null,
638 if (FINDER_CREATOR.equals(fileCreator.toString()))
640 browser = file.toString(); // Actually the Finder, but that's OK
646 catch (IllegalArgumentException iare)
648 errorMessage = iare.getMessage();
652 catch (IllegalAccessException iae)
655 errorMessage = iae.getMessage();
659 catch (InvocationTargetException ite)
662 errorMessage = ite.getTargetException().getClass() + ": " +
663 ite.getTargetException().getMessage();
675 browser = ""; // Return something non-null
685 browser = "command.com";
691 browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox");
699 * used to ensure that browser is up-to-date after a configuration
700 * change (Unix DEFAULT_BROWSER property change).
702 public static void resetBrowser() {
706 * Attempts to open the default web browser to the given URL.
707 * @param url The URL to open
708 * @throws IOException If the web browser could not be located or does not run
710 public static void openURL(String url)
713 if (!loadedWithoutErrors)
715 throw new IOException("Exception in finding browser: " +
719 Object browser = locateBrowser();
723 throw new IOException("Unable to locate browser: " + errorMessage);
730 Object aeDesc = null;
734 aeDesc = aeDescConstructor.newInstance(new Object[]
736 putParameter.invoke(browser,
738 {keyDirectObject, aeDesc});
739 sendNoReply.invoke(browser, new Object[]
742 catch (InvocationTargetException ite)
744 throw new IOException(
745 "InvocationTargetException while creating AEDesc: " +
748 catch (IllegalAccessException iae)
750 throw new IOException(
751 "IllegalAccessException while building AppleEvent: " +
754 catch (InstantiationException ie)
756 throw new IOException(
757 "InstantiationException while creating AEDesc: " +
762 aeDesc = null; // Encourage it to get disposed if it was created
763 browser = null; // Ditto
769 Runtime.getRuntime().exec(new String[]
770 { (String) browser, url});
776 int[] instance = new int[1];
777 int result = ICStart(instance, 0);
781 int[] selectionStart = new int[]
784 byte[] urlBytes = url.getBytes();
785 int[] selectionEnd = new int[]
788 result = ICLaunchURL(instance[0], new byte[]
790 urlBytes.length, selectionStart, selectionEnd);
794 // Ignore the return value; the URL was launched successfully
795 // regardless of what happens here.
800 throw new IOException("Unable to launch URL: " + result);
805 throw new IOException(
806 "Unable to create an Internet Config instance: " + result);
815 openURL.invoke(null, new Object[]
818 catch (InvocationTargetException ite)
820 throw new IOException(
821 "InvocationTargetException while calling openURL: " +
824 catch (IllegalAccessException iae)
826 throw new IOException(
827 "IllegalAccessException while calling openURL: " +
837 // Add quotes around the URL to allow ampersands and other special
838 // characters to work.
839 Process process = Runtime.getRuntime().exec(new String[]
841 (String) browser, FIRST_WINDOWS_PARAMETER,
842 SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
846 // This avoids a memory leak on some versions of Java on Windows.
847 // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
853 catch (InterruptedException ie)
855 throw new IOException(
856 "InterruptedException while launching browser: " +
865 // Assume that we're on Unix and that Netscape (actually Firefox) is installed
866 // First, attempt to open the URL in a currently running session of Netscape
869 /* System.out.println("Executing : "+browser+" "+
870 NETSCAPE_REMOTE_PARAMETER+" "+
871 NETSCAPE_OPEN_PARAMETER_START +
873 NETSCAPE_OPEN_NEW_WINDOW +
874 NETSCAPE_OPEN_PARAMETER_END);
876 process = Runtime.getRuntime().exec(new String[]
879 NETSCAPE_REMOTE_PARAMETER,
881 NETSCAPE_OPEN_PARAMETER_START + url +
882 NETSCAPE_OPEN_NEW_WINDOW +
883 NETSCAPE_OPEN_PARAMETER_END
888 int exitCode = process.waitFor();
891 { // if Netscape was not open
892 Runtime.getRuntime().exec(new String[]
893 { (String) browser, url});
896 catch (InterruptedException ie)
898 throw new IOException(
899 "InterruptedException while launching browser: " +
908 // This should never occur, but if it does, we'll try the simplest thing possible
909 Runtime.getRuntime().exec(new String[]
910 { (String) browser, url});
917 * Methods required for Mac OS X. The presence of native methods does not cause
918 * any problems on other platforms.
920 private native static int ICStart(int[] instance, int signature);
922 private native static int ICStop(int[] instance);
924 private native static int ICLaunchURL(int instance, byte[] hint,
925 byte[] data, int len,
926 int[] selectionStart,