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.lang.reflect.*;
27 * BrowserLauncher is a class that provides one static method, openURL, which
28 * opens the default web browser for the current user of the system to the given
29 * URL. It may support other protocols depending on the system -- mailto, ftp,
30 * etc. -- but that has not been rigorously tested and is not guaranteed to
33 * Yes, this is platform-specific code, and yes, it may rely on classes on
34 * certain platforms that are not part of the standard JDK. What we're trying to
35 * do, though, is to take something that's frequently desirable but inherently
36 * platform-specific -- opening a default browser -- and allow programmers (you,
37 * for example) to do so without worrying about dropping into native code or
38 * doing anything else similarly evil.
40 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
41 * systems without modification or a need for additional libraries. All classes
42 * that are required on certain platforms to allow this to run are dynamically
43 * loaded at runtime via reflection and, if not found, will not cause this to do
44 * anything other than returning an error when opening the browser.
46 * There are certain system requirements for this class, as it's running through
47 * Runtime.exec(), which is Java's way of making a native system call.
48 * Currently, this requires that a Macintosh have a Finder which supports the
49 * GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
50 * Internet Scripting AppleScript dictionary installed in the Scripting
51 * Additions folder in the Extensions folder (which is installed by default as
52 * far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
53 * systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
54 * 4.0, as well as later versions of all). On other systems, this drops back
55 * from the inherently platform-sensitive concept of a default browser and
56 * simply attempts to launch Netscape via a shell command.
58 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu)
59 * and may be redistributed or modified in any form without restrictions as long
60 * as the portion of this comment from this paragraph through the end of the
61 * comment is not removed. The author requests that he be notified of any
62 * application, applet, or other binary that makes use of this code, but that's
63 * more out of curiosity than anything and is not required. This software
64 * includes no warranty. The author is not repsonsible for any loss of data or
65 * functionality or any adverse or unexpected effects of using this software.
68 * Steven Spencer, JavaWorld magazine (<a
69 * href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip
71 * Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
72 * Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
74 * @author Eric Albert (<a
75 * href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
76 * @version 1.4b1 (Released June 20, 2001)
78 public class BrowserLauncher
81 * The Java virtual machine that we are running on. Actually, in most cases we
82 * only care about the operating system, but some operating systems require us
83 * to switch on the VM.
85 private static int jvm;
87 /** The browser for the system */
88 private static Object browser;
91 * Caches whether any classes, methods, and fields that are not part of the
92 * JDK and need to be dynamically loaded at runtime loaded successfully.
94 * Note that if this is <code>false</code>, <code>openURL()</code> will always
95 * return an IOException.
97 private static boolean loadedWithoutErrors;
99 /** The com.apple.mrj.MRJFileUtils class */
100 private static Class mrjFileUtilsClass;
102 /** The com.apple.mrj.MRJOSType class */
103 private static Class mrjOSTypeClass;
105 /** The com.apple.MacOS.AEDesc class */
106 private static Class aeDescClass;
108 /** The <init>(int) method of com.apple.MacOS.AETarget */
109 private static Constructor aeTargetConstructor;
111 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
112 private static Constructor appleEventConstructor;
114 /** The <init>(String) method of com.apple.MacOS.AEDesc */
115 private static Constructor aeDescConstructor;
117 /** The findFolder method of com.apple.mrj.MRJFileUtils */
118 private static Method findFolder;
120 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
121 private static Method getFileCreator;
123 /** The getFileType method of com.apple.mrj.MRJFileUtils */
124 private static Method getFileType;
126 /** The openURL method of com.apple.mrj.MRJFileUtils */
127 private static Method openURL;
129 /** The makeOSType method of com.apple.MacOS.OSUtils */
130 private static Method makeOSType;
132 /** The putParameter method of com.apple.MacOS.AppleEvent */
133 private static Method putParameter;
135 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
136 private static Method sendNoReply;
138 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
139 private static Object kSystemFolderType;
141 /** The keyDirectObject AppleEvent parameter type */
142 private static Integer keyDirectObject;
144 /** The kAutoGenerateReturnID AppleEvent code */
145 private static Integer kAutoGenerateReturnID;
147 /** The kAnyTransactionID AppleEvent code */
148 private static Integer kAnyTransactionID;
150 /** The linkage object required for JDirect 3 on Mac OS X. */
151 private static Object linkage;
153 /** The framework to reference on Mac OS X */
154 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
156 /** JVM constant for MRJ 2.0 */
157 private static final int MRJ_2_0 = 0;
159 /** JVM constant for MRJ 2.1 or later */
160 private static final int MRJ_2_1 = 1;
162 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
163 private static final int MRJ_3_0 = 3;
165 /** JVM constant for MRJ 3.1 */
166 private static final int MRJ_3_1 = 4;
168 /** JVM constant for any Windows NT JVM */
169 private static final int WINDOWS_NT = 5;
171 /** JVM constant for any Windows 9x JVM */
172 private static final int WINDOWS_9x = 6;
174 /** JVM constant for any other platform */
175 private static final int OTHER = -1;
178 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep
179 * non-U.S. English systems from working properly.
181 private static final String FINDER_TYPE = "FNDR";
184 * The creator code of the Finder on a Macintosh, which is needed to send
185 * AppleEvents to the application.
187 private static final String FINDER_CREATOR = "MACS";
189 /** The name for the AppleEvent type corresponding to a GetURL event. */
190 private static final String GURL_EVENT = "GURL";
193 * The first parameter that needs to be passed into Runtime.exec() to open the
194 * default web browser on Windows.
196 private static final String FIRST_WINDOWS_PARAMETER = "/c";
198 /** The second parameter for Runtime.exec() on Windows. */
199 private static final String SECOND_WINDOWS_PARAMETER = "start";
202 * The third parameter for Runtime.exec() on Windows. This is a "title"
203 * parameter that the command line expects. Setting this parameter allows URLs
204 * containing spaces to work.
206 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
209 * The shell parameters for Netscape that opens a given URL in an already-open
210 * copy of Netscape on many command-line systems.
212 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
214 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
216 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
218 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
221 * The message from any exception thrown throughout the initialization
224 private static String errorMessage;
227 * An initialization block that determines the operating system and loads the
228 * necessary runtime data.
232 loadedWithoutErrors = true;
234 String osName = System.getProperty("os.name");
236 if (osName.startsWith("Mac OS"))
238 String mrjVersion = System.getProperty("mrj.version");
239 String majorMRJVersion;
240 if (mrjVersion == null)
242 // must be on some later build with mrj support
243 majorMRJVersion = "3.1";
247 majorMRJVersion = mrjVersion.substring(0, 3);
252 double version = Double.valueOf(majorMRJVersion).doubleValue();
258 else if ((version >= 2.1) && (version < 3))
260 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
261 // works via Runtime.exec() and 2.2 supports that but has an openURL()
263 // as well that we currently ignore.
266 else if (version == 3.0)
270 else if (version >= 3.1)
272 // Assume that all 3.1 and later versions of MRJ work the same.
277 loadedWithoutErrors = false;
278 errorMessage = "Unsupported MRJ version: " + version;
280 } catch (NumberFormatException nfe)
282 loadedWithoutErrors = false;
283 errorMessage = "Invalid MRJ version: " + mrjVersion;
286 else if (osName.startsWith("Windows"))
288 if (osName.indexOf("9") != -1)
302 if (loadedWithoutErrors)
303 { // if we haven't hit any errors yet
304 loadedWithoutErrors = loadClasses();
309 * This class should be never be instantiated; this just ensures so.
311 private BrowserLauncher()
316 * Called by a static initializer to load any classes, fields, and methods
317 * required at runtime to locate the user's web browser.
319 * @return <code>true</code> if all intialization succeeded <code>false</code>
320 * if any portion of the initialization failed
322 private static boolean loadClasses()
330 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
331 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
332 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
333 Class aeClass = Class.forName("com.apple.MacOS.ae");
334 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
336 aeTargetConstructor = aeTargetClass
337 .getDeclaredConstructor(new Class[]
339 appleEventConstructor = appleEventClass
340 .getDeclaredConstructor(new Class[]
341 { int.class, int.class, aeTargetClass, int.class, int.class });
342 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[]
345 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
348 putParameter = appleEventClass.getDeclaredMethod("putParameter",
350 { int.class, aeDescClass });
351 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
355 Field keyDirectObjectField = aeClass
356 .getDeclaredField("keyDirectObject");
357 keyDirectObject = (Integer) keyDirectObjectField.get(null);
359 Field autoGenerateReturnIDField = appleEventClass
360 .getDeclaredField("kAutoGenerateReturnID");
361 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
364 Field anyTransactionIDField = appleEventClass
365 .getDeclaredField("kAnyTransactionID");
366 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
367 } catch (ClassNotFoundException cnfe)
369 errorMessage = cnfe.getMessage();
372 } catch (NoSuchMethodException nsme)
374 errorMessage = nsme.getMessage();
377 } catch (NoSuchFieldException nsfe)
379 errorMessage = nsfe.getMessage();
382 } catch (IllegalAccessException iae)
384 errorMessage = iae.getMessage();
395 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
396 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
398 Field systemFolderField = mrjFileUtilsClass
399 .getDeclaredField("kSystemFolderType");
400 kSystemFolderType = systemFolderField.get(null);
401 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
404 getFileCreator = mrjFileUtilsClass.getDeclaredMethod(
405 "getFileCreator", new Class[]
407 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
410 } catch (ClassNotFoundException cnfe)
412 errorMessage = cnfe.getMessage();
415 } catch (NoSuchFieldException nsfe)
417 errorMessage = nsfe.getMessage();
420 } catch (NoSuchMethodException nsme)
422 errorMessage = nsme.getMessage();
425 } catch (SecurityException se)
427 errorMessage = se.getMessage();
430 } catch (IllegalAccessException iae)
432 errorMessage = iae.getMessage();
443 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
444 Constructor constructor = linker.getConstructor(new Class[]
446 linkage = constructor.newInstance(new Object[]
447 { BrowserLauncher.class });
448 } catch (ClassNotFoundException cnfe)
450 errorMessage = cnfe.getMessage();
453 } catch (NoSuchMethodException nsme)
455 errorMessage = nsme.getMessage();
458 } catch (InvocationTargetException ite)
460 errorMessage = ite.getMessage();
463 } catch (InstantiationException ie)
465 errorMessage = ie.getMessage();
468 } catch (IllegalAccessException iae)
470 errorMessage = iae.getMessage();
481 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
482 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
485 } catch (ClassNotFoundException cnfe)
487 errorMessage = cnfe.getMessage();
490 } catch (NoSuchMethodException nsme)
492 errorMessage = nsme.getMessage();
507 * Attempts to locate the default web browser on the local system. s results
508 * so it only locates the browser once for each use of this class per JVM
511 * @return The browser for the system. Note that this may not be what you
512 * would consider to be a standard web browser; instead, it's the
513 * application that gets called to open the default web browser. In
514 * some cases, this will be a non-String object that provides the
515 * means of calling the default browser.
517 private static Object locateBrowser()
530 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
533 Object aeTarget = aeTargetConstructor.newInstance(new Object[]
534 { finderCreatorCode });
535 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[]
537 Object appleEvent = appleEventConstructor.newInstance(new Object[]
538 { gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
539 kAnyTransactionID });
541 // Don't set browser = appleEvent because then the next time we call
542 // locateBrowser(), we'll get the same AppleEvent, to which we'll
544 // added the relevant parameter. Instead, regenerate the AppleEvent
546 // There's probably a way to do this better; if any has any ideas,
550 } catch (IllegalAccessException iae)
553 errorMessage = iae.getMessage();
556 } catch (InstantiationException ie)
559 errorMessage = ie.getMessage();
562 } catch (InvocationTargetException ite)
565 errorMessage = ite.getMessage();
576 systemFolder = (File) findFolder.invoke(null, new Object[]
577 { kSystemFolderType });
578 } catch (IllegalArgumentException iare)
581 errorMessage = iare.getMessage();
584 } catch (IllegalAccessException iae)
587 errorMessage = iae.getMessage();
590 } catch (InvocationTargetException ite)
593 errorMessage = ite.getTargetException().getClass() + ": "
594 + ite.getTargetException().getMessage();
599 String[] systemFolderFiles = systemFolder.list();
601 // Avoid a FilenameFilter because that can't be stopped mid-list
602 for (int i = 0; i < systemFolderFiles.length; i++)
606 File file = new File(systemFolder, systemFolderFiles[i]);
613 // We're looking for a file with a creator code of 'MACS' and
614 // a type of 'FNDR'. Only requiring the type results in non-Finder
615 // applications being picked up on certain Mac OS 9 systems,
616 // especially German ones, and sending a GURL event to those
617 // applications results in a logout under Multiple Users.
618 Object fileType = getFileType.invoke(null, new Object[]
621 if (FINDER_TYPE.equals(fileType.toString()))
623 Object fileCreator = getFileCreator.invoke(null, new Object[]
626 if (FINDER_CREATOR.equals(fileCreator.toString()))
628 browser = file.toString(); // Actually the Finder, but that's OK
633 } catch (IllegalArgumentException iare)
635 errorMessage = iare.getMessage();
638 } catch (IllegalAccessException iae)
641 errorMessage = iae.getMessage();
644 } catch (InvocationTargetException ite)
647 errorMessage = ite.getTargetException().getClass() + ": "
648 + ite.getTargetException().getMessage();
660 browser = ""; // Return something non-null
670 browser = "command.com";
676 browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox");
685 * used to ensure that browser is up-to-date after a configuration change
686 * (Unix DEFAULT_BROWSER property change).
688 public static void resetBrowser()
694 * Attempts to open the default web browser to the given URL.
698 * @throws IOException
699 * If the web browser could not be located or does not run
701 public static void openURL(String url) throws IOException
703 if (!loadedWithoutErrors)
705 throw new IOException(MessageManager.formatMessage("exception.browser_not_found", new String[]{errorMessage}));
708 Object browser = locateBrowser();
712 throw new IOException(MessageManager.formatMessage("exception.browser_unable_to_locate", new String[]{errorMessage}));
719 Object aeDesc = null;
723 aeDesc = aeDescConstructor.newInstance(new Object[]
725 putParameter.invoke(browser, new Object[]
726 { keyDirectObject, aeDesc });
727 sendNoReply.invoke(browser, new Object[]
729 } catch (InvocationTargetException ite)
731 throw new IOException(MessageManager.formatMessage("exception.invocation_target_exception_creating_aedesc", new String[]{ite.getMessage()}));
732 } catch (IllegalAccessException iae)
734 throw new IOException(MessageManager.formatMessage("exception.illegal_access_building_apple_evt", new String[]{iae.getMessage()}));
735 } catch (InstantiationException ie)
737 throw new IOException(MessageManager.formatMessage("exception.illegal_access_building_apple_evt", new String[]{ie.getMessage()}));
740 aeDesc = null; // Encourage it to get disposed if it was created
741 browser = null; // Ditto
747 Runtime.getRuntime().exec(new String[]
748 { (String) browser, url });
754 int[] instance = new int[1];
755 int result = ICStart(instance, 0);
759 int[] selectionStart = new int[]
761 byte[] urlBytes = url.getBytes();
762 int[] selectionEnd = new int[]
764 result = ICLaunchURL(instance[0], new byte[]
765 { 0 }, urlBytes, urlBytes.length, selectionStart, selectionEnd);
769 // Ignore the return value; the URL was launched successfully
770 // regardless of what happens here.
775 throw new IOException(MessageManager.formatMessage("exception.unable_to_launch_url", new String[]{Integer.valueOf(result).toString()}));
780 throw new IOException(MessageManager.formatMessage("exception.unable_to_create_internet_config", new String[]{Integer.valueOf(result).toString()}));
789 openURL.invoke(null, new Object[]
791 } catch (InvocationTargetException ite)
793 throw new IOException(MessageManager.formatMessage("exception.invocation_target_calling_url", new String[]{ite.getMessage()}));
794 } catch (IllegalAccessException iae)
796 throw new IOException(MessageManager.formatMessage("exception.illegal_access_calling_url", new String[]{iae.getMessage()}));
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(MessageManager.formatMessage("exception.interrupted_launching_browser", new String[]{ie.getMessage()}));
828 // Assume that we're on Unix and that Netscape (actually Firefox) is
830 // First, attempt to open the URL in a currently running session of
835 * System.out.println("Executing : "+browser+" "+
836 * NETSCAPE_REMOTE_PARAMETER+" "+ NETSCAPE_OPEN_PARAMETER_START + url +
837 * NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END);
839 process = Runtime.getRuntime().exec(
843 NETSCAPE_REMOTE_PARAMETER,
845 NETSCAPE_OPEN_PARAMETER_START + url
846 + NETSCAPE_OPEN_NEW_WINDOW
847 + NETSCAPE_OPEN_PARAMETER_END });
851 int exitCode = process.waitFor();
854 { // if Netscape was not open
855 Runtime.getRuntime().exec(new String[]
856 { (String) browser, url });
858 } catch (InterruptedException ie)
860 throw new IOException(MessageManager.formatMessage("exception.interrupted_launching_browser", new String[]{ie.getMessage()}));
867 // This should never occur, but if it does, we'll try the simplest thing
869 Runtime.getRuntime().exec(new String[]
870 { (String) browser, url });
877 * Methods required for Mac OS X. The presence of native methods does not
878 * cause any problems on other platforms.
880 private native static int ICStart(int[] instance, int signature);
882 private native static int ICStop(int[] instance);
884 private native static int ICLaunchURL(int instance, byte[] hint,
885 byte[] data, int len, int[] selectionStart, int[] selectionEnd);