2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
24 import java.io.IOException;
25 import java.lang.reflect.Constructor;
26 import java.lang.reflect.Field;
27 import java.lang.reflect.InvocationTargetException;
28 import java.lang.reflect.Method;
31 * BrowserLauncher is a class that provides two static methods:
33 * openURL(String url), which opens the default web browser for the current user
34 * of the system to the given URL, and
36 * resetBrowser(), which allows switching browsers in Java.
38 * openURL may support other protocols depending on the system -- mailto, ftp,
39 * etc. -- but that has not been rigorously tested and is not guaranteed to
42 * Yes, this is platform-specific code, and yes, it may rely on classes on
43 * certain platforms that are not part of the standard JDK. What we're trying to
44 * do, though, is to take something that's frequently desirable but inherently
45 * platform-specific -- opening a default browser -- and allow programmers (you,
46 * for example) to do so without worrying about dropping into native code or
47 * doing anything else similarly evil.
49 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
50 * systems without modification or a need for additional libraries. All classes
51 * that are required on certain platforms to allow this to run are dynamically
52 * loaded at runtime via reflection and, if not found, will not cause this to do
53 * anything other than returning an error when opening the browser.
55 * There are certain system requirements for this class, as it's running through
56 * Runtime.exec(), which is Java's way of making a native system call.
57 * Currently, this requires that a Macintosh have a Finder which supports the
58 * GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
59 * Internet Scripting AppleScript dictionary installed in the Scripting
60 * Additions folder in the Extensions folder (which is installed by default as
61 * far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
62 * systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
63 * 4.0, as well as later versions of all). On other systems, this drops back
64 * from the inherently platform-sensitive concept of a default browser and
65 * simply attempts to launch Netscape via a shell command.
67 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu)
68 * and may be redistributed or modified in any form without restrictions as long
69 * as the portion of this comment from this paragraph through the end of the
70 * comment is not removed. The author requests that he be notified of any
71 * application, applet, or other binary that makes use of this code, but that's
72 * more out of curiosity than anything and is not required. This software
73 * includes no warranty. The author is not repsonsible for any loss of data or
74 * functionality or any adverse or unexpected effects of using this software.
77 * Steven Spencer, JavaWorld magazine
78 * (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java
80 * Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
81 * Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
83 * @author Eric Albert (<a href=
84 * "mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
85 * @version 1.4b1 (Released June 20, 2001)
89 * SwingJS note: Do not use methods in this class directly. Use
91 * Platform.openURL(String url) only.
93 * JavaScript does not see this class.
95 public class BrowserLauncher
98 * The Java virtual machine that we are running on. Actually, in most cases we
99 * only care about the operating system, but some operating systems require us
100 * to switch on the VM.
102 private static int jvm;
104 /** The browser for the system */
105 private static Object browser;
108 * Caches whether any classes, methods, and fields that are not part of the
109 * JDK and need to be dynamically loaded at runtime loaded successfully.
111 * Note that if this is <code>false</code>, <code>openURL()</code> will always
112 * return an IOException.
114 private static boolean loadedWithoutErrors;
116 /** The com.apple.mrj.MRJFileUtils class */
117 private static Class<?> mrjFileUtilsClass;
119 /** The com.apple.mrj.MRJOSType class */
120 private static Class<?> mrjOSTypeClass;
122 /** The com.apple.MacOS.AEDesc class */
123 private static Class<?> aeDescClass;
125 /** The <init>(int) method of com.apple.MacOS.AETarget */
126 private static Constructor<?> aeTargetConstructor;
128 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
129 private static Constructor<?> appleEventConstructor;
131 /** The <init>(String) method of com.apple.MacOS.AEDesc */
132 private static Constructor<?> aeDescConstructor;
134 /** The findFolder method of com.apple.mrj.MRJFileUtils */
135 private static Method findFolder;
137 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
138 private static Method getFileCreator;
140 /** The getFileType method of com.apple.mrj.MRJFileUtils */
141 private static Method getFileType;
143 /** The openURL method of com.apple.mrj.MRJFileUtils */
144 private static Method openURL;
146 /** The makeOSType method of com.apple.MacOS.OSUtils */
147 private static Method makeOSType;
149 /** The putParameter method of com.apple.MacOS.AppleEvent */
150 private static Method putParameter;
152 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
153 private static Method sendNoReply;
155 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
156 private static Object kSystemFolderType;
158 /** The keyDirectObject AppleEvent parameter type */
159 private static Integer keyDirectObject;
161 /** The kAutoGenerateReturnID AppleEvent code */
162 private static Integer kAutoGenerateReturnID;
164 /** The kAnyTransactionID AppleEvent code */
165 private static Integer kAnyTransactionID;
167 /** The linkage object required for JDirect 3 on Mac OS X. */
168 private static Object linkage;
170 /** The framework to reference on Mac OS X */
171 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
173 /** JVM constant for MRJ 2.0 */
174 private static final int MRJ_2_0 = 0;
176 /** JVM constant for MRJ 2.1 or later */
177 private static final int MRJ_2_1 = 1;
179 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
180 private static final int MRJ_3_0 = 3;
182 /** JVM constant for MRJ 3.1 */
183 private static final int MRJ_3_1 = 4;
185 /** JVM constant for any Windows NT JVM */
186 private static final int WINDOWS_NT = 5;
188 /** JVM constant for any Windows 9x JVM */
189 private static final int WINDOWS_9x = 6;
191 /** JVM constant for any other platform */
192 private static final int OTHER = -1;
195 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep
196 * non-U.S. English systems from working properly.
198 private static final String FINDER_TYPE = "FNDR";
201 * The creator code of the Finder on a Macintosh, which is needed to send
202 * AppleEvents to the application.
204 private static final String FINDER_CREATOR = "MACS";
206 /** The name for the AppleEvent type corresponding to a GetURL event. */
207 private static final String GURL_EVENT = "GURL";
210 * The first parameter that needs to be passed into Runtime.exec() to open the
211 * default web browser on Windows.
213 private static final String FIRST_WINDOWS_PARAMETER = "/c";
215 /** The second parameter for Runtime.exec() on Windows. */
216 private static final String SECOND_WINDOWS_PARAMETER = "start";
219 * The third parameter for Runtime.exec() on Windows. This is a "title"
220 * parameter that the command line expects. Setting this parameter allows URLs
221 * containing spaces to work.
223 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
226 * The shell parameters for Netscape that opens a given URL in an already-open
227 * copy of Netscape on many command-line systems.
229 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
231 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
233 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
235 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
238 * The message from any exception thrown throughout the initialization
241 private static String errorMessage;
244 * An initialization block that determines the operating system and loads the
245 * necessary runtime data.
250 loadedWithoutErrors = true;
252 String osName = System.getProperty("os.name");
254 if (osName.startsWith("Mac OS"))
256 String mrjVersion = System.getProperty("mrj.version");
257 String majorMRJVersion;
258 if (mrjVersion == null)
260 // must be on some later build with mrj support
261 majorMRJVersion = "3.1";
265 majorMRJVersion = mrjVersion.substring(0, 3);
270 double version = Double.valueOf(majorMRJVersion).doubleValue();
276 else if ((version >= 2.1) && (version < 3))
278 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
279 // works via Runtime.exec() and 2.2 supports that but has an openURL()
281 // as well that we currently ignore.
284 else if (version == 3.0)
288 else if (version >= 3.1)
290 // Assume that all 3.1 and later versions of MRJ work the same.
295 loadedWithoutErrors = false;
296 errorMessage = "Unsupported MRJ version: " + version;
298 } catch (NumberFormatException nfe)
300 loadedWithoutErrors = false;
301 errorMessage = "Invalid MRJ version: " + mrjVersion;
304 else if (osName.startsWith("Windows"))
306 if (osName.indexOf("9") != -1)
320 if (loadedWithoutErrors)
321 { // if we haven't hit any errors yet
322 loadedWithoutErrors = loadClasses();
327 * This class should be never be instantiated; this just ensures so.
329 private BrowserLauncher()
334 * Called by a static initializer to load any classes, fields, and methods
335 * required at runtime to locate the user's web browser.
337 * @return <code>true</code> if all intialization succeeded <code>false</code>
338 * if any portion of the initialization failed
340 private static boolean loadClasses()
349 Class<?> aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
350 Class<?> osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
351 Class<?> appleEventClass = Class
352 .forName("com.apple.MacOS.AppleEvent");
353 Class<?> aeClass = Class.forName("com.apple.MacOS.ae");
354 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
356 aeTargetConstructor = aeTargetClass
357 .getDeclaredConstructor(new Class[]
359 appleEventConstructor = appleEventClass
360 .getDeclaredConstructor(new Class[]
361 { int.class, int.class, aeTargetClass, int.class,
363 aeDescConstructor = aeDescClass
364 .getDeclaredConstructor(new Class[]
367 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
370 putParameter = appleEventClass.getDeclaredMethod("putParameter",
372 { int.class, aeDescClass });
373 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
376 Field keyDirectObjectField = aeClass
377 .getDeclaredField("keyDirectObject");
378 keyDirectObject = (Integer) keyDirectObjectField.get(null);
380 Field autoGenerateReturnIDField = appleEventClass
381 .getDeclaredField("kAutoGenerateReturnID");
382 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
385 Field anyTransactionIDField = appleEventClass
386 .getDeclaredField("kAnyTransactionID");
387 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
388 } catch (ClassNotFoundException cnfe)
390 errorMessage = cnfe.getMessage();
393 } catch (NoSuchMethodException nsme)
395 errorMessage = nsme.getMessage();
398 } catch (NoSuchFieldException nsfe)
400 errorMessage = nsfe.getMessage();
403 } catch (IllegalAccessException iae)
405 errorMessage = iae.getMessage();
416 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
417 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
419 Field systemFolderField = mrjFileUtilsClass
420 .getDeclaredField("kSystemFolderType");
421 kSystemFolderType = systemFolderField.get(null);
422 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
425 getFileCreator = mrjFileUtilsClass
426 .getDeclaredMethod("getFileCreator", new Class[]
428 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
431 } catch (ClassNotFoundException cnfe)
433 errorMessage = cnfe.getMessage();
436 } catch (NoSuchFieldException nsfe)
438 errorMessage = nsfe.getMessage();
441 } catch (NoSuchMethodException nsme)
443 errorMessage = nsme.getMessage();
446 } catch (SecurityException se)
448 errorMessage = se.getMessage();
451 } catch (IllegalAccessException iae)
453 errorMessage = iae.getMessage();
464 Class<?> linker = Class.forName("com.apple.mrj.jdirect.Linker");
465 Constructor<?> constructor = linker
466 .getConstructor(new Class[]
468 linkage = constructor
469 .newInstance(new Object[]
470 { BrowserLauncher.class });
471 } catch (ClassNotFoundException cnfe)
473 errorMessage = cnfe.getMessage();
476 } catch (NoSuchMethodException nsme)
478 errorMessage = nsme.getMessage();
481 } catch (InvocationTargetException ite)
483 errorMessage = ite.getMessage();
486 } catch (InstantiationException ie)
488 errorMessage = ie.getMessage();
491 } catch (IllegalAccessException iae)
493 errorMessage = iae.getMessage();
504 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
505 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
508 } catch (ClassNotFoundException cnfe)
510 errorMessage = cnfe.getMessage();
513 } catch (NoSuchMethodException nsme)
515 errorMessage = nsme.getMessage();
530 * Attempts to locate the default web browser on the local system. s results
531 * so it only locates the browser once for each use of this class per JVM
534 * @return The browser for the system. Note that this may not be what you
535 * would consider to be a standard web browser; instead, it's the
536 * application that gets called to open the default web browser. In
537 * some cases, this will be a non-String object that provides the
538 * means of calling the default browser.
540 private static Object locateBrowser()
553 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
556 Object aeTarget = aeTargetConstructor
557 .newInstance(new Object[]
558 { finderCreatorCode });
559 Integer gurlType = (Integer) makeOSType.invoke(null,
562 Object appleEvent = appleEventConstructor
563 .newInstance(new Object[]
564 { gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
565 kAnyTransactionID });
567 // Don't set browser = appleEvent because then the next time we call
568 // locateBrowser(), we'll get the same AppleEvent, to which we'll
570 // added the relevant parameter. Instead, regenerate the AppleEvent
572 // There's probably a way to do this better; if any has any ideas,
576 } catch (IllegalAccessException iae)
579 errorMessage = iae.getMessage();
582 } catch (InstantiationException ie)
585 errorMessage = ie.getMessage();
588 } catch (InvocationTargetException ite)
591 errorMessage = ite.getMessage();
602 systemFolder = (File) findFolder.invoke(null,
604 { kSystemFolderType });
605 } catch (IllegalArgumentException iare)
608 errorMessage = iare.getMessage();
611 } catch (IllegalAccessException iae)
614 errorMessage = iae.getMessage();
617 } catch (InvocationTargetException ite)
620 errorMessage = ite.getTargetException().getClass() + ": "
621 + ite.getTargetException().getMessage();
626 String[] systemFolderFiles = systemFolder.list();
628 // Avoid a FilenameFilter because that can't be stopped mid-list
629 for (int i = 0; i < systemFolderFiles.length; i++)
633 File file = new File(systemFolder, systemFolderFiles[i]);
640 // We're looking for a file with a creator code of 'MACS' and
641 // a type of 'FNDR'. Only requiring the type results in non-Finder
642 // applications being picked up on certain Mac OS 9 systems,
643 // especially German ones, and sending a GURL event to those
644 // applications results in a logout under Multiple Users.
645 Object fileType = getFileType.invoke(null, new Object[] { file });
647 if (FINDER_TYPE.equals(fileType.toString()))
649 Object fileCreator = getFileCreator.invoke(null,
653 if (FINDER_CREATOR.equals(fileCreator.toString()))
655 browser = file.toString(); // Actually the Finder, but that's OK
660 } catch (IllegalArgumentException iare)
662 errorMessage = iare.getMessage();
665 } catch (IllegalAccessException iae)
668 errorMessage = iae.getMessage();
671 } catch (InvocationTargetException ite)
674 errorMessage = ite.getTargetException().getClass() + ": "
675 + ite.getTargetException().getMessage();
687 browser = ""; // Return something non-null
697 browser = "command.com";
703 browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox");
711 * used to ensure that browser is up-to-date after a configuration change
712 * (Unix DEFAULT_BROWSER property change).
714 public static void resetBrowser()
720 * Attempts to open the default web browser to the given URL.
724 * @throws IOException
725 * If the web browser could not be located or does not run
727 public static void openURL(String url) throws IOException
731 Platform.openURL(url);
734 if (!loadedWithoutErrors)
736 throw new IOException(MessageManager
737 .formatMessage("exception.browser_not_found", new String[]
741 Object browser = locateBrowser();
745 throw new IOException(MessageManager.formatMessage(
746 "exception.browser_unable_to_locate", new String[]
754 Object aeDesc = null;
758 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
759 putParameter.invoke(browser,
761 { keyDirectObject, aeDesc });
762 sendNoReply.invoke(browser, new Object[] {});
763 } catch (InvocationTargetException ite)
765 throw new IOException(MessageManager.formatMessage(
766 "exception.invocation_target_exception_creating_aedesc",
768 { ite.getMessage() }));
769 } catch (IllegalAccessException iae)
771 throw new IOException(MessageManager.formatMessage(
772 "exception.illegal_access_building_apple_evt", new String[]
773 { iae.getMessage() }));
774 } catch (InstantiationException ie)
776 throw new IOException(MessageManager.formatMessage(
777 "exception.illegal_access_building_apple_evt", new String[]
778 { ie.getMessage() }));
781 aeDesc = null; // Encourage it to get disposed if it was created
782 browser = null; // Ditto
788 Runtime.getRuntime().exec(new String[] { (String) browser, url });
794 int[] instance = new int[1];
795 int result = ICStart(instance, 0);
799 int[] selectionStart = new int[] { 0 };
800 byte[] urlBytes = url.getBytes();
801 int[] selectionEnd = new int[] { urlBytes.length };
802 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
803 urlBytes.length, selectionStart, selectionEnd);
807 // Ignore the return value; the URL was launched successfully
808 // regardless of what happens here.
813 throw new IOException(MessageManager.formatMessage(
814 "exception.unable_to_launch_url", new String[]
815 { Integer.valueOf(result).toString() }));
820 throw new IOException(MessageManager.formatMessage(
821 "exception.unable_to_create_internet_config", new String[]
822 { Integer.valueOf(result).toString() }));
831 openURL.invoke(null, new Object[] { url });
832 } catch (InvocationTargetException ite)
834 throw new IOException(MessageManager.formatMessage(
835 "exception.invocation_target_calling_url", new String[]
836 { ite.getMessage() }));
837 } catch (IllegalAccessException iae)
839 throw new IOException(MessageManager.formatMessage(
840 "exception.illegal_access_calling_url", new String[]
841 { iae.getMessage() }));
849 // Add quotes around the URL to allow ampersands and other special
850 // characters to work.
851 Process process = Runtime.getRuntime()
853 { (String) browser, FIRST_WINDOWS_PARAMETER,
854 SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
857 // This avoids a memory leak on some versions of Java on Windows.
858 // That's hinted at in
859 // <http://developer.java.sun.com/developer/qow/archive/68/>.
864 } catch (InterruptedException ie)
866 throw new IOException(MessageManager.formatMessage(
867 "exception.interrupted_launching_browser", new String[]
868 { ie.getMessage() }));
875 // Assume that we're on Unix and that Netscape (actually Firefox) is
877 // First, attempt to open the URL in a currently running session of
882 * System.out.println("Executing : "+browser+" "+
883 * NETSCAPE_REMOTE_PARAMETER+" "+ NETSCAPE_OPEN_PARAMETER_START + url +
884 * NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END);
886 process = Runtime.getRuntime()
888 { (String) browser, NETSCAPE_REMOTE_PARAMETER,
890 NETSCAPE_OPEN_PARAMETER_START + url
891 + NETSCAPE_OPEN_NEW_WINDOW
892 + NETSCAPE_OPEN_PARAMETER_END });
896 int exitCode = process.waitFor();
899 { // if Netscape was not open
900 Runtime.getRuntime().exec(new String[] { (String) browser, url });
902 } catch (InterruptedException ie)
904 throw new IOException(MessageManager.formatMessage(
905 "exception.interrupted_launching_browser", new String[]
906 { ie.getMessage() }));
912 // This should never occur, but if it does, we'll try the simplest thing
914 Runtime.getRuntime().exec(new String[] { (String) browser, url });
921 * Methods required for Mac OS X. The presence of native methods does not
922 * cause any problems on other platforms.
924 private native static int ICStart(int[] instance, int signature);
926 private native static int ICStop(int[] instance);
928 private native static int ICLaunchURL(int instance, byte[] hint,
929 byte[] data, int len, int[] selectionStart, int[] selectionEnd);