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 one static method, openURL, which
32 * opens the default web browser for the current user of the system to the given
33 * URL. It may support other protocols depending on the system -- mailto, ftp,
34 * etc. -- but that has not been rigorously tested and is not guaranteed to
37 * Yes, this is platform-specific code, and yes, it may rely on classes on
38 * certain platforms that are not part of the standard JDK. What we're trying to
39 * do, though, is to take something that's frequently desirable but inherently
40 * platform-specific -- opening a default browser -- and allow programmers (you,
41 * for example) to do so without worrying about dropping into native code or
42 * doing anything else similarly evil.
44 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
45 * systems without modification or a need for additional libraries. All classes
46 * that are required on certain platforms to allow this to run are dynamically
47 * loaded at runtime via reflection and, if not found, will not cause this to do
48 * anything other than returning an error when opening the browser.
50 * There are certain system requirements for this class, as it's running through
51 * Runtime.exec(), which is Java's way of making a native system call.
52 * Currently, this requires that a Macintosh have a Finder which supports the
53 * GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
54 * Internet Scripting AppleScript dictionary installed in the Scripting
55 * Additions folder in the Extensions folder (which is installed by default as
56 * far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
57 * systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
58 * 4.0, as well as later versions of all). On other systems, this drops back
59 * from the inherently platform-sensitive concept of a default browser and
60 * simply attempts to launch Netscape via a shell command.
62 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu)
63 * and may be redistributed or modified in any form without restrictions as long
64 * as the portion of this comment from this paragraph through the end of the
65 * comment is not removed. The author requests that he be notified of any
66 * application, applet, or other binary that makes use of this code, but that's
67 * more out of curiosity than anything and is not required. This software
68 * includes no warranty. The author is not repsonsible for any loss of data or
69 * functionality or any adverse or unexpected effects of using this software.
72 * Steven Spencer, JavaWorld magazine
73 * (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java
75 * Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
76 * Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
78 * @author Eric Albert (<a href=
79 * "mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
80 * @version 1.4b1 (Released June 20, 2001)
82 public class BrowserLauncher
85 * The Java virtual machine that we are running on. Actually, in most cases we
86 * only care about the operating system, but some operating systems require us
87 * to switch on the VM.
89 private static int jvm;
91 /** The browser for the system */
92 private static Object browser;
95 * Caches whether any classes, methods, and fields that are not part of the
96 * JDK and need to be dynamically loaded at runtime loaded successfully.
98 * Note that if this is <code>false</code>, <code>openURL()</code> will always
99 * return an IOException.
101 private static boolean loadedWithoutErrors;
103 /** The com.apple.mrj.MRJFileUtils class */
104 private static Class mrjFileUtilsClass;
106 /** The com.apple.mrj.MRJOSType class */
107 private static Class mrjOSTypeClass;
109 /** The com.apple.MacOS.AEDesc class */
110 private static Class aeDescClass;
112 /** The <init>(int) method of com.apple.MacOS.AETarget */
113 private static Constructor aeTargetConstructor;
115 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
116 private static Constructor appleEventConstructor;
118 /** The <init>(String) method of com.apple.MacOS.AEDesc */
119 private static Constructor aeDescConstructor;
121 /** The findFolder method of com.apple.mrj.MRJFileUtils */
122 private static Method findFolder;
124 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
125 private static Method getFileCreator;
127 /** The getFileType method of com.apple.mrj.MRJFileUtils */
128 private static Method getFileType;
130 /** The openURL method of com.apple.mrj.MRJFileUtils */
131 private static Method openURL;
133 /** The makeOSType method of com.apple.MacOS.OSUtils */
134 private static Method makeOSType;
136 /** The putParameter method of com.apple.MacOS.AppleEvent */
137 private static Method putParameter;
139 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
140 private static Method sendNoReply;
142 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
143 private static Object kSystemFolderType;
145 /** The keyDirectObject AppleEvent parameter type */
146 private static Integer keyDirectObject;
148 /** The kAutoGenerateReturnID AppleEvent code */
149 private static Integer kAutoGenerateReturnID;
151 /** The kAnyTransactionID AppleEvent code */
152 private static Integer kAnyTransactionID;
154 /** The linkage object required for JDirect 3 on Mac OS X. */
155 private static Object linkage;
157 /** The framework to reference on Mac OS X */
158 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
160 /** JVM constant for MRJ 2.0 */
161 private static final int MRJ_2_0 = 0;
163 /** JVM constant for MRJ 2.1 or later */
164 private static final int MRJ_2_1 = 1;
166 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
167 private static final int MRJ_3_0 = 3;
169 /** JVM constant for MRJ 3.1 */
170 private static final int MRJ_3_1 = 4;
172 /** JVM constant for any Windows NT JVM */
173 private static final int WINDOWS_NT = 5;
175 /** JVM constant for any Windows 9x JVM */
176 private static final int WINDOWS_9x = 6;
178 /** JVM constant for any other platform */
179 private static final int OTHER = -1;
182 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep
183 * non-U.S. English systems from working properly.
185 private static final String FINDER_TYPE = "FNDR";
188 * The creator code of the Finder on a Macintosh, which is needed to send
189 * AppleEvents to the application.
191 private static final String FINDER_CREATOR = "MACS";
193 /** The name for the AppleEvent type corresponding to a GetURL event. */
194 private static final String GURL_EVENT = "GURL";
197 * The first parameter that needs to be passed into Runtime.exec() to open the
198 * default web browser on Windows.
200 private static final String FIRST_WINDOWS_PARAMETER = "/c";
202 /** The second parameter for Runtime.exec() on Windows. */
203 private static final String SECOND_WINDOWS_PARAMETER = "start";
206 * The third parameter for Runtime.exec() on Windows. This is a "title"
207 * parameter that the command line expects. Setting this parameter allows URLs
208 * containing spaces to work.
210 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
213 * The shell parameters for Netscape that opens a given URL in an already-open
214 * copy of Netscape on many command-line systems.
216 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
218 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
220 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
222 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
225 * The message from any exception thrown throughout the initialization
228 private static String errorMessage;
231 * An initialization block that determines the operating system and loads the
232 * necessary runtime data.
236 loadedWithoutErrors = true;
238 String osName = System.getProperty("os.name");
240 if (osName.startsWith("Mac OS"))
242 String mrjVersion = System.getProperty("mrj.version");
243 String majorMRJVersion;
244 if (mrjVersion == null)
246 // must be on some later build with mrj support
247 majorMRJVersion = "3.1";
251 majorMRJVersion = mrjVersion.substring(0, 3);
256 double version = Double.valueOf(majorMRJVersion).doubleValue();
262 else if ((version >= 2.1) && (version < 3))
264 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
265 // works via Runtime.exec() and 2.2 supports that but has an openURL()
267 // as well that we currently ignore.
270 else if (version == 3.0)
274 else if (version >= 3.1)
276 // Assume that all 3.1 and later versions of MRJ work the same.
281 loadedWithoutErrors = false;
282 errorMessage = "Unsupported MRJ version: " + version;
284 } catch (NumberFormatException nfe)
286 loadedWithoutErrors = false;
287 errorMessage = "Invalid MRJ version: " + mrjVersion;
290 else if (osName.startsWith("Windows"))
292 if (osName.indexOf("9") != -1)
306 if (loadedWithoutErrors)
307 { // if we haven't hit any errors yet
308 loadedWithoutErrors = loadClasses();
313 * This class should be never be instantiated; this just ensures so.
315 private BrowserLauncher()
320 * Called by a static initializer to load any classes, fields, and methods
321 * required at runtime to locate the user's web browser.
323 * @return <code>true</code> if all intialization succeeded <code>false</code>
324 * if any portion of the initialization failed
326 private static boolean loadClasses()
334 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
335 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
336 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
337 Class aeClass = Class.forName("com.apple.MacOS.ae");
338 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
340 aeTargetConstructor = aeTargetClass
341 .getDeclaredConstructor(new Class[]
343 appleEventConstructor = appleEventClass
344 .getDeclaredConstructor(new Class[]
345 { int.class, int.class, aeTargetClass, int.class,
347 aeDescConstructor = aeDescClass
348 .getDeclaredConstructor(new Class[]
351 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
354 putParameter = appleEventClass.getDeclaredMethod("putParameter",
356 { int.class, aeDescClass });
357 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
360 Field keyDirectObjectField = aeClass
361 .getDeclaredField("keyDirectObject");
362 keyDirectObject = (Integer) keyDirectObjectField.get(null);
364 Field autoGenerateReturnIDField = appleEventClass
365 .getDeclaredField("kAutoGenerateReturnID");
366 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
369 Field anyTransactionIDField = appleEventClass
370 .getDeclaredField("kAnyTransactionID");
371 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
372 } catch (ClassNotFoundException cnfe)
374 errorMessage = cnfe.getMessage();
377 } catch (NoSuchMethodException nsme)
379 errorMessage = nsme.getMessage();
382 } catch (NoSuchFieldException nsfe)
384 errorMessage = nsfe.getMessage();
387 } catch (IllegalAccessException iae)
389 errorMessage = iae.getMessage();
400 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
401 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
403 Field systemFolderField = mrjFileUtilsClass
404 .getDeclaredField("kSystemFolderType");
405 kSystemFolderType = systemFolderField.get(null);
406 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
409 getFileCreator = mrjFileUtilsClass
410 .getDeclaredMethod("getFileCreator", new Class[]
412 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
415 } catch (ClassNotFoundException cnfe)
417 errorMessage = cnfe.getMessage();
420 } catch (NoSuchFieldException nsfe)
422 errorMessage = nsfe.getMessage();
425 } catch (NoSuchMethodException nsme)
427 errorMessage = nsme.getMessage();
430 } catch (SecurityException se)
432 errorMessage = se.getMessage();
435 } catch (IllegalAccessException iae)
437 errorMessage = iae.getMessage();
448 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
449 Constructor constructor = linker
450 .getConstructor(new Class[]
452 linkage = constructor
453 .newInstance(new Object[]
454 { BrowserLauncher.class });
455 } catch (ClassNotFoundException cnfe)
457 errorMessage = cnfe.getMessage();
460 } catch (NoSuchMethodException nsme)
462 errorMessage = nsme.getMessage();
465 } catch (InvocationTargetException ite)
467 errorMessage = ite.getMessage();
470 } catch (InstantiationException ie)
472 errorMessage = ie.getMessage();
475 } catch (IllegalAccessException iae)
477 errorMessage = iae.getMessage();
488 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
489 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
492 } catch (ClassNotFoundException cnfe)
494 errorMessage = cnfe.getMessage();
497 } catch (NoSuchMethodException nsme)
499 errorMessage = nsme.getMessage();
514 * Attempts to locate the default web browser on the local system. s results
515 * so it only locates the browser once for each use of this class per JVM
518 * @return The browser for the system. Note that this may not be what you
519 * would consider to be a standard web browser; instead, it's the
520 * application that gets called to open the default web browser. In
521 * some cases, this will be a non-String object that provides the
522 * means of calling the default browser.
524 private static Object locateBrowser()
528 return "/Volumes/Macintosh HD/Applications/Firefox.app/Contents/MacOS/firefox";
541 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
544 Object aeTarget = aeTargetConstructor
545 .newInstance(new Object[]
546 { finderCreatorCode });
547 Integer gurlType = (Integer) makeOSType.invoke(null,
550 Object appleEvent = appleEventConstructor
551 .newInstance(new Object[]
552 { gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
553 kAnyTransactionID });
555 // Don't set browser = appleEvent because then the next time we call
556 // locateBrowser(), we'll get the same AppleEvent, to which we'll
558 // added the relevant parameter. Instead, regenerate the AppleEvent
560 // There's probably a way to do this better; if any has any ideas,
564 } catch (IllegalAccessException iae)
567 errorMessage = iae.getMessage();
570 } catch (InstantiationException ie)
573 errorMessage = ie.getMessage();
576 } catch (InvocationTargetException ite)
579 errorMessage = ite.getMessage();
590 systemFolder = (File) findFolder.invoke(null,
592 { kSystemFolderType });
593 } catch (IllegalArgumentException iare)
596 errorMessage = iare.getMessage();
599 } catch (IllegalAccessException iae)
602 errorMessage = iae.getMessage();
605 } catch (InvocationTargetException ite)
608 errorMessage = ite.getTargetException().getClass() + ": "
609 + ite.getTargetException().getMessage();
614 String[] systemFolderFiles = systemFolder.list();
616 // Avoid a FilenameFilter because that can't be stopped mid-list
617 for (int i = 0; i < systemFolderFiles.length; i++)
621 File file = new File(systemFolder, systemFolderFiles[i]);
628 // We're looking for a file with a creator code of 'MACS' and
629 // a type of 'FNDR'. Only requiring the type results in non-Finder
630 // applications being picked up on certain Mac OS 9 systems,
631 // especially German ones, and sending a GURL event to those
632 // applications results in a logout under Multiple Users.
633 Object fileType = getFileType.invoke(null, new Object[] { file });
635 if (FINDER_TYPE.equals(fileType.toString()))
637 Object fileCreator = getFileCreator.invoke(null,
641 if (FINDER_CREATOR.equals(fileCreator.toString()))
643 browser = file.toString(); // Actually the Finder, but that's OK
648 } catch (IllegalArgumentException iare)
650 errorMessage = iare.getMessage();
653 } catch (IllegalAccessException iae)
656 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");
700 * used to ensure that browser is up-to-date after a configuration change
701 * (Unix DEFAULT_BROWSER property change).
703 public static void resetBrowser()
709 * Attempts to open the default web browser to the given URL.
713 * @throws IOException
714 * If the web browser could not be located or does not run
716 public static void openURL(String url) throws IOException
718 if (false && !loadedWithoutErrors)
720 throw new IOException(MessageManager
721 .formatMessage("exception.browser_not_found", new String[]
725 Object browser = locateBrowser();
729 throw new IOException(MessageManager.formatMessage(
730 "exception.browser_unable_to_locate", new String[]
738 Object aeDesc = null;
742 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
743 putParameter.invoke(browser,
745 { keyDirectObject, aeDesc });
746 sendNoReply.invoke(browser, new Object[] {});
747 } catch (InvocationTargetException ite)
749 throw new IOException(MessageManager.formatMessage(
750 "exception.invocation_target_exception_creating_aedesc",
752 { ite.getMessage() }));
753 } catch (IllegalAccessException iae)
755 throw new IOException(MessageManager.formatMessage(
756 "exception.illegal_access_building_apple_evt", new String[]
757 { iae.getMessage() }));
758 } catch (InstantiationException ie)
760 throw new IOException(MessageManager.formatMessage(
761 "exception.illegal_access_building_apple_evt", new String[]
762 { ie.getMessage() }));
765 aeDesc = null; // Encourage it to get disposed if it was created
766 browser = null; // Ditto
772 Runtime.getRuntime().exec(new String[] { (String) browser, url });
778 int[] instance = new int[1];
779 int result = ICStart(instance, 0);
783 int[] selectionStart = new int[] { 0 };
784 byte[] urlBytes = url.getBytes();
785 int[] selectionEnd = new int[] { urlBytes.length };
786 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
787 urlBytes.length, selectionStart, selectionEnd);
791 // Ignore the return value; the URL was launched successfully
792 // regardless of what happens here.
797 throw new IOException(MessageManager.formatMessage(
798 "exception.unable_to_launch_url", new String[]
799 { Integer.valueOf(result).toString() }));
804 throw new IOException(MessageManager.formatMessage(
805 "exception.unable_to_create_internet_config", new String[]
806 { Integer.valueOf(result).toString() }));
815 openURL.invoke(null, new Object[] { url });
816 } catch (InvocationTargetException ite)
818 throw new IOException(MessageManager.formatMessage(
819 "exception.invocation_target_calling_url", new String[]
820 { ite.getMessage() }));
821 } catch (IllegalAccessException iae)
823 throw new IOException(MessageManager.formatMessage(
824 "exception.illegal_access_calling_url", new String[]
825 { iae.getMessage() }));
833 // Add quotes around the URL to allow ampersands and other special
834 // characters to work.
835 Process process = Runtime.getRuntime()
837 { (String) browser, FIRST_WINDOWS_PARAMETER,
838 SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
841 // This avoids a memory leak on some versions of Java on Windows.
842 // That's hinted at in
843 // <http://developer.java.sun.com/developer/qow/archive/68/>.
848 } catch (InterruptedException ie)
850 throw new IOException(MessageManager.formatMessage(
851 "exception.interrupted_launching_browser", new String[]
852 { ie.getMessage() }));
859 // Assume that we're on Unix and that Netscape (actually Firefox) is
861 // First, attempt to open the URL in a currently running session of
866 * System.out.println("Executing : "+browser+" "+
867 * NETSCAPE_REMOTE_PARAMETER+" "+ NETSCAPE_OPEN_PARAMETER_START + url +
868 * NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END);
870 process = Runtime.getRuntime()
872 { (String) browser, NETSCAPE_REMOTE_PARAMETER,
874 NETSCAPE_OPEN_PARAMETER_START + url
875 + NETSCAPE_OPEN_NEW_WINDOW
876 + NETSCAPE_OPEN_PARAMETER_END });
880 int exitCode = process.waitFor();
883 { // if Netscape was not open
884 Runtime.getRuntime().exec(new String[] { (String) browser, url });
886 } catch (InterruptedException ie)
888 throw new IOException(MessageManager.formatMessage(
889 "exception.interrupted_launching_browser", new String[]
890 { ie.getMessage() }));
897 // This should never occur, but if it does, we'll try the simplest thing
899 Runtime.getRuntime().exec(new String[] { (String) browser, url });
906 * Methods required for Mac OS X. The presence of native methods does not
907 * cause any problems on other platforms.
909 private native static int ICStart(int[] instance, int signature);
911 private native static int ICStop(int[] instance);
913 private native static int ICLaunchURL(int instance, byte[] hint,
914 byte[] data, int len, int[] selectionStart, int[] selectionEnd);