2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.4)
3 * Copyright (C) 2008 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
26 * opens the default web browser for the current user of the system to the given
27 * URL. It may support other protocols depending on the system -- mailto, ftp,
28 * etc. -- but that has not been rigorously tested and is not guaranteed to
31 * Yes, this is platform-specific code, and yes, it may rely on classes on
32 * certain platforms that are not part of the standard JDK. What we're trying to
33 * do, though, is to take something that's frequently desirable but inherently
34 * platform-specific -- opening a default browser -- and allow programmers (you,
35 * for example) to do so without worrying about dropping into native code or
36 * doing anything else similarly evil.
38 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
39 * systems without modification or a need for additional libraries. All classes
40 * that are required on certain platforms to allow this to run are dynamically
41 * loaded at runtime via reflection and, if not found, will not cause this to do
42 * anything other than returning an error when opening the browser.
44 * There are certain system requirements for this class, as it's running through
45 * Runtime.exec(), which is Java's way of making a native system call.
46 * Currently, this requires that a Macintosh have a Finder which supports the
47 * GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
48 * Internet Scripting AppleScript dictionary installed in the Scripting
49 * Additions folder in the Extensions folder (which is installed by default as
50 * far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
51 * systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
52 * 4.0, as well as later versions of all). On other systems, this drops back
53 * from the inherently platform-sensitive concept of a default browser and
54 * simply attempts to launch Netscape via a shell command.
56 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu)
57 * and may be redistributed or modified in any form without restrictions as long
58 * as the portion of this comment from this paragraph through the end of the
59 * comment is not removed. The author requests that he be notified of any
60 * application, applet, or other binary that makes use of this code, but that's
61 * 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
63 * functionality or any adverse or unexpected effects of using this software.
66 * Steven Spencer, JavaWorld magazine (<a
67 * href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip
69 * Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
70 * Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
72 * @author Eric Albert (<a
73 * href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
74 * @version 1.4b1 (Released June 20, 2001)
76 public class BrowserLauncher
79 * The Java virtual machine that we are running on. Actually, in most cases we
80 * only care about the operating system, but some operating systems require us
81 * to switch on the VM.
83 private static int jvm;
85 /** The browser for the system */
86 private static Object browser;
89 * Caches whether any classes, methods, and fields that are not part of the
90 * JDK and need to be dynamically loaded at runtime loaded successfully.
92 * Note that if this is <code>false</code>, <code>openURL()</code> will
93 * always return an IOException.
95 private static boolean loadedWithoutErrors;
97 /** The com.apple.mrj.MRJFileUtils class */
98 private static Class mrjFileUtilsClass;
100 /** The com.apple.mrj.MRJOSType class */
101 private static Class mrjOSTypeClass;
103 /** The com.apple.MacOS.AEDesc class */
104 private static Class aeDescClass;
106 /** The <init>(int) method of com.apple.MacOS.AETarget */
107 private static Constructor aeTargetConstructor;
109 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
110 private static Constructor appleEventConstructor;
112 /** The <init>(String) method of com.apple.MacOS.AEDesc */
113 private static Constructor aeDescConstructor;
115 /** The findFolder method of com.apple.mrj.MRJFileUtils */
116 private static Method findFolder;
118 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
119 private static Method getFileCreator;
121 /** The getFileType method of com.apple.mrj.MRJFileUtils */
122 private static Method getFileType;
124 /** The openURL method of com.apple.mrj.MRJFileUtils */
125 private static Method openURL;
127 /** The makeOSType method of com.apple.MacOS.OSUtils */
128 private static Method makeOSType;
130 /** The putParameter method of com.apple.MacOS.AppleEvent */
131 private static Method putParameter;
133 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
134 private static Method sendNoReply;
136 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
137 private static Object kSystemFolderType;
139 /** The keyDirectObject AppleEvent parameter type */
140 private static Integer keyDirectObject;
142 /** The kAutoGenerateReturnID AppleEvent code */
143 private static Integer kAutoGenerateReturnID;
145 /** The kAnyTransactionID AppleEvent code */
146 private static Integer kAnyTransactionID;
148 /** The linkage object required for JDirect 3 on Mac OS X. */
149 private static Object linkage;
151 /** The framework to reference on Mac OS X */
152 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
154 /** JVM constant for MRJ 2.0 */
155 private static final int MRJ_2_0 = 0;
157 /** JVM constant for MRJ 2.1 or later */
158 private static final int MRJ_2_1 = 1;
160 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
161 private static final int MRJ_3_0 = 3;
163 /** JVM constant for MRJ 3.1 */
164 private static final int MRJ_3_1 = 4;
166 /** JVM constant for any Windows NT JVM */
167 private static final int WINDOWS_NT = 5;
169 /** JVM constant for any Windows 9x JVM */
170 private static final int WINDOWS_9x = 6;
172 /** JVM constant for any other platform */
173 private static final int OTHER = -1;
176 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep
177 * non-U.S. English systems from working properly.
179 private static final String FINDER_TYPE = "FNDR";
182 * The creator code of the Finder on a Macintosh, which is needed to send
183 * AppleEvents to the application.
185 private static final String FINDER_CREATOR = "MACS";
187 /** The name for the AppleEvent type corresponding to a GetURL event. */
188 private static final String GURL_EVENT = "GURL";
191 * The first parameter that needs to be passed into Runtime.exec() to open the
192 * default web browser on Windows.
194 private static final String FIRST_WINDOWS_PARAMETER = "/c";
196 /** The second parameter for Runtime.exec() on Windows. */
197 private static final String SECOND_WINDOWS_PARAMETER = "start";
200 * The third parameter for Runtime.exec() on Windows. This is a "title"
201 * parameter that the command line expects. Setting this parameter allows URLs
202 * containing spaces to work.
204 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
207 * The shell parameters for Netscape that opens a given URL in an already-open
208 * copy of Netscape on many command-line systems.
210 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
212 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
214 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
216 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
219 * The message from any exception thrown throughout the initialization
222 private static String errorMessage;
225 * An initialization block that determines the operating system and loads the
226 * necessary runtime data.
230 loadedWithoutErrors = true;
232 String osName = System.getProperty("os.name");
234 if (osName.startsWith("Mac OS"))
236 String mrjVersion = System.getProperty("mrj.version");
237 String majorMRJVersion = mrjVersion.substring(0, 3);
241 double version = Double.valueOf(majorMRJVersion).doubleValue();
247 else if ((version >= 2.1) && (version < 3))
249 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
250 // works via Runtime.exec() and 2.2 supports that but has an openURL()
252 // as well that we currently ignore.
255 else if (version == 3.0)
259 else if (version >= 3.1)
261 // Assume that all 3.1 and later versions of MRJ work the same.
266 loadedWithoutErrors = false;
267 errorMessage = "Unsupported MRJ version: " + version;
269 } catch (NumberFormatException nfe)
271 loadedWithoutErrors = false;
272 errorMessage = "Invalid MRJ version: " + mrjVersion;
275 else if (osName.startsWith("Windows"))
277 if (osName.indexOf("9") != -1)
291 if (loadedWithoutErrors)
292 { // if we haven't hit any errors yet
293 loadedWithoutErrors = loadClasses();
298 * This class should be never be instantiated; this just ensures so.
300 private BrowserLauncher()
305 * Called by a static initializer to load any classes, fields, and methods
306 * required at runtime to locate the user's web browser.
308 * @return <code>true</code> if all intialization succeeded
309 * <code>false</code> if any portion of the initialization failed
311 private static boolean loadClasses()
319 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
320 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
321 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
322 Class aeClass = Class.forName("com.apple.MacOS.ae");
323 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
325 aeTargetConstructor = aeTargetClass
326 .getDeclaredConstructor(new Class[]
328 appleEventConstructor = appleEventClass
329 .getDeclaredConstructor(new Class[]
330 { int.class, int.class, aeTargetClass, int.class, int.class });
331 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[]
334 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
337 putParameter = appleEventClass.getDeclaredMethod("putParameter",
339 { int.class, aeDescClass });
340 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
344 Field keyDirectObjectField = aeClass
345 .getDeclaredField("keyDirectObject");
346 keyDirectObject = (Integer) keyDirectObjectField.get(null);
348 Field autoGenerateReturnIDField = appleEventClass
349 .getDeclaredField("kAutoGenerateReturnID");
350 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
353 Field anyTransactionIDField = appleEventClass
354 .getDeclaredField("kAnyTransactionID");
355 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
356 } catch (ClassNotFoundException cnfe)
358 errorMessage = cnfe.getMessage();
361 } catch (NoSuchMethodException nsme)
363 errorMessage = nsme.getMessage();
366 } catch (NoSuchFieldException nsfe)
368 errorMessage = nsfe.getMessage();
371 } catch (IllegalAccessException iae)
373 errorMessage = iae.getMessage();
384 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
385 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
387 Field systemFolderField = mrjFileUtilsClass
388 .getDeclaredField("kSystemFolderType");
389 kSystemFolderType = systemFolderField.get(null);
390 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
393 getFileCreator = mrjFileUtilsClass.getDeclaredMethod(
394 "getFileCreator", new Class[]
396 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
399 } catch (ClassNotFoundException cnfe)
401 errorMessage = cnfe.getMessage();
404 } catch (NoSuchFieldException nsfe)
406 errorMessage = nsfe.getMessage();
409 } catch (NoSuchMethodException nsme)
411 errorMessage = nsme.getMessage();
414 } catch (SecurityException se)
416 errorMessage = se.getMessage();
419 } catch (IllegalAccessException iae)
421 errorMessage = iae.getMessage();
432 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
433 Constructor constructor = linker.getConstructor(new Class[]
435 linkage = constructor.newInstance(new Object[]
436 { BrowserLauncher.class });
437 } catch (ClassNotFoundException cnfe)
439 errorMessage = cnfe.getMessage();
442 } catch (NoSuchMethodException nsme)
444 errorMessage = nsme.getMessage();
447 } catch (InvocationTargetException ite)
449 errorMessage = ite.getMessage();
452 } catch (InstantiationException ie)
454 errorMessage = ie.getMessage();
457 } catch (IllegalAccessException iae)
459 errorMessage = iae.getMessage();
470 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
471 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
474 } catch (ClassNotFoundException cnfe)
476 errorMessage = cnfe.getMessage();
479 } catch (NoSuchMethodException nsme)
481 errorMessage = nsme.getMessage();
496 * Attempts to locate the default web browser on the local system. s results
497 * so it only locates the browser once for each use of this class per JVM
500 * @return The browser for the system. Note that this may not be what you
501 * would consider to be a standard web browser; instead, it's the
502 * application that gets called to open the default web browser. In
503 * some cases, this will be a non-String object that provides the
504 * means of calling the default browser.
506 private static Object locateBrowser()
519 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
522 Object aeTarget = aeTargetConstructor.newInstance(new Object[]
523 { finderCreatorCode });
524 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[]
526 Object appleEvent = appleEventConstructor.newInstance(new Object[]
527 { gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
528 kAnyTransactionID });
530 // Don't set browser = appleEvent because then the next time we call
531 // locateBrowser(), we'll get the same AppleEvent, to which we'll
533 // added the relevant parameter. Instead, regenerate the AppleEvent
535 // There's probably a way to do this better; if any has any ideas,
539 } catch (IllegalAccessException iae)
542 errorMessage = iae.getMessage();
545 } catch (InstantiationException ie)
548 errorMessage = ie.getMessage();
551 } catch (InvocationTargetException ite)
554 errorMessage = ite.getMessage();
565 systemFolder = (File) findFolder.invoke(null, new Object[]
566 { kSystemFolderType });
567 } catch (IllegalArgumentException iare)
570 errorMessage = iare.getMessage();
573 } catch (IllegalAccessException iae)
576 errorMessage = iae.getMessage();
579 } catch (InvocationTargetException ite)
582 errorMessage = ite.getTargetException().getClass() + ": "
583 + ite.getTargetException().getMessage();
588 String[] systemFolderFiles = systemFolder.list();
590 // Avoid a FilenameFilter because that can't be stopped mid-list
591 for (int i = 0; i < systemFolderFiles.length; i++)
595 File file = new File(systemFolder, systemFolderFiles[i]);
602 // We're looking for a file with a creator code of 'MACS' and
603 // a type of 'FNDR'. Only requiring the type results in non-Finder
604 // applications being picked up on certain Mac OS 9 systems,
605 // especially German ones, and sending a GURL event to those
606 // applications results in a logout under Multiple Users.
607 Object fileType = getFileType.invoke(null, new Object[]
610 if (FINDER_TYPE.equals(fileType.toString()))
612 Object fileCreator = getFileCreator.invoke(null, new Object[]
615 if (FINDER_CREATOR.equals(fileCreator.toString()))
617 browser = file.toString(); // Actually the Finder, but that's OK
622 } catch (IllegalArgumentException iare)
624 errorMessage = iare.getMessage();
627 } catch (IllegalAccessException iae)
630 errorMessage = iae.getMessage();
633 } catch (InvocationTargetException ite)
636 errorMessage = ite.getTargetException().getClass() + ": "
637 + ite.getTargetException().getMessage();
649 browser = ""; // Return something non-null
659 browser = "command.com";
665 browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox");
674 * used to ensure that browser is up-to-date after a configuration change
675 * (Unix DEFAULT_BROWSER property change).
677 public static void resetBrowser()
683 * Attempts to open the default web browser to the given URL.
687 * @throws IOException
688 * If the web browser could not be located or does not run
690 public static void openURL(String url) throws IOException
692 if (!loadedWithoutErrors)
694 throw new IOException("Exception in finding browser: " + errorMessage);
697 Object browser = locateBrowser();
701 throw new IOException("Unable to locate browser: " + errorMessage);
708 Object aeDesc = null;
712 aeDesc = aeDescConstructor.newInstance(new Object[]
714 putParameter.invoke(browser, new Object[]
715 { keyDirectObject, aeDesc });
716 sendNoReply.invoke(browser, new Object[]
718 } catch (InvocationTargetException ite)
720 throw new IOException(
721 "InvocationTargetException while creating AEDesc: "
723 } catch (IllegalAccessException iae)
725 throw new IOException(
726 "IllegalAccessException while building AppleEvent: "
728 } catch (InstantiationException ie)
730 throw new IOException(
731 "InstantiationException while creating AEDesc: "
735 aeDesc = null; // Encourage it to get disposed if it was created
736 browser = null; // Ditto
742 Runtime.getRuntime().exec(new String[]
743 { (String) browser, url });
749 int[] instance = new int[1];
750 int result = ICStart(instance, 0);
754 int[] selectionStart = new int[]
756 byte[] urlBytes = url.getBytes();
757 int[] selectionEnd = new int[]
759 result = ICLaunchURL(instance[0], new byte[]
760 { 0 }, urlBytes, urlBytes.length, selectionStart, selectionEnd);
764 // Ignore the return value; the URL was launched successfully
765 // regardless of what happens here.
770 throw new IOException("Unable to launch URL: " + result);
775 throw new IOException(
776 "Unable to create an Internet Config instance: " + result);
785 openURL.invoke(null, new Object[]
787 } catch (InvocationTargetException ite)
789 throw new IOException(
790 "InvocationTargetException while calling openURL: "
792 } catch (IllegalAccessException iae)
794 throw new IOException(
795 "IllegalAccessException while calling openURL: "
804 // Add quotes around the URL to allow ampersands and other special
805 // characters to work.
806 Process process = Runtime.getRuntime().exec(
808 { (String) browser, FIRST_WINDOWS_PARAMETER,
809 SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
812 // This avoids a memory leak on some versions of Java on Windows.
813 // That's hinted at in
814 // <http://developer.java.sun.com/developer/qow/archive/68/>.
819 } catch (InterruptedException ie)
821 throw new IOException(
822 "InterruptedException while launching browser: "
830 // Assume that we're on Unix and that Netscape (actually Firefox) is
832 // First, attempt to open the URL in a currently running session of
837 * System.out.println("Executing : "+browser+" "+
838 * NETSCAPE_REMOTE_PARAMETER+" "+ NETSCAPE_OPEN_PARAMETER_START + url +
839 * NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END);
841 process = Runtime.getRuntime().exec(
845 NETSCAPE_REMOTE_PARAMETER,
847 NETSCAPE_OPEN_PARAMETER_START + url
848 + NETSCAPE_OPEN_NEW_WINDOW
849 + NETSCAPE_OPEN_PARAMETER_END });
853 int exitCode = process.waitFor();
856 { // if Netscape was not open
857 Runtime.getRuntime().exec(new String[]
858 { (String) browser, url });
860 } catch (InterruptedException ie)
862 throw new IOException(
863 "InterruptedException while launching browser: "
871 // This should never occur, but if it does, we'll try the simplest thing
873 Runtime.getRuntime().exec(new String[]
874 { (String) browser, url });
881 * Methods required for Mac OS X. The presence of native methods does not
882 * cause any problems on other platforms.
884 private native static int ICStart(int[] instance, int signature);
886 private native static int ICStop(int[] instance);
888 private native static int ICLaunchURL(int instance, byte[] hint,
889 byte[] data, int len, int[] selectionStart, int[] selectionEnd);