2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 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 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
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 always
93 * 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;
238 if (mrjVersion == null)
240 // must be on some later build with mrj support
241 majorMRJVersion = "3.1";
245 majorMRJVersion = mrjVersion.substring(0, 3);
250 double version = Double.valueOf(majorMRJVersion).doubleValue();
256 else if ((version >= 2.1) && (version < 3))
258 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
259 // works via Runtime.exec() and 2.2 supports that but has an openURL()
261 // as well that we currently ignore.
264 else if (version == 3.0)
268 else if (version >= 3.1)
270 // Assume that all 3.1 and later versions of MRJ work the same.
275 loadedWithoutErrors = false;
276 errorMessage = "Unsupported MRJ version: " + version;
278 } catch (NumberFormatException nfe)
280 loadedWithoutErrors = false;
281 errorMessage = "Invalid MRJ version: " + mrjVersion;
284 else if (osName.startsWith("Windows"))
286 if (osName.indexOf("9") != -1)
300 if (loadedWithoutErrors)
301 { // if we haven't hit any errors yet
302 loadedWithoutErrors = loadClasses();
307 * This class should be never be instantiated; this just ensures so.
309 private BrowserLauncher()
314 * Called by a static initializer to load any classes, fields, and methods
315 * required at runtime to locate the user's web browser.
317 * @return <code>true</code> if all intialization succeeded <code>false</code>
318 * if any portion of the initialization failed
320 private static boolean loadClasses()
328 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
329 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
330 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
331 Class aeClass = Class.forName("com.apple.MacOS.ae");
332 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
334 aeTargetConstructor = aeTargetClass
335 .getDeclaredConstructor(new Class[]
337 appleEventConstructor = appleEventClass
338 .getDeclaredConstructor(new Class[]
339 { int.class, int.class, aeTargetClass, int.class, int.class });
340 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[]
343 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
346 putParameter = appleEventClass.getDeclaredMethod("putParameter",
348 { int.class, aeDescClass });
349 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
353 Field keyDirectObjectField = aeClass
354 .getDeclaredField("keyDirectObject");
355 keyDirectObject = (Integer) keyDirectObjectField.get(null);
357 Field autoGenerateReturnIDField = appleEventClass
358 .getDeclaredField("kAutoGenerateReturnID");
359 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
362 Field anyTransactionIDField = appleEventClass
363 .getDeclaredField("kAnyTransactionID");
364 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
365 } catch (ClassNotFoundException cnfe)
367 errorMessage = cnfe.getMessage();
370 } catch (NoSuchMethodException nsme)
372 errorMessage = nsme.getMessage();
375 } catch (NoSuchFieldException nsfe)
377 errorMessage = nsfe.getMessage();
380 } catch (IllegalAccessException iae)
382 errorMessage = iae.getMessage();
393 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
394 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
396 Field systemFolderField = mrjFileUtilsClass
397 .getDeclaredField("kSystemFolderType");
398 kSystemFolderType = systemFolderField.get(null);
399 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
402 getFileCreator = mrjFileUtilsClass.getDeclaredMethod(
403 "getFileCreator", new Class[]
405 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
408 } catch (ClassNotFoundException cnfe)
410 errorMessage = cnfe.getMessage();
413 } catch (NoSuchFieldException nsfe)
415 errorMessage = nsfe.getMessage();
418 } catch (NoSuchMethodException nsme)
420 errorMessage = nsme.getMessage();
423 } catch (SecurityException se)
425 errorMessage = se.getMessage();
428 } catch (IllegalAccessException iae)
430 errorMessage = iae.getMessage();
441 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
442 Constructor constructor = linker.getConstructor(new Class[]
444 linkage = constructor.newInstance(new Object[]
445 { BrowserLauncher.class });
446 } catch (ClassNotFoundException cnfe)
448 errorMessage = cnfe.getMessage();
451 } catch (NoSuchMethodException nsme)
453 errorMessage = nsme.getMessage();
456 } catch (InvocationTargetException ite)
458 errorMessage = ite.getMessage();
461 } catch (InstantiationException ie)
463 errorMessage = ie.getMessage();
466 } catch (IllegalAccessException iae)
468 errorMessage = iae.getMessage();
479 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
480 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
483 } catch (ClassNotFoundException cnfe)
485 errorMessage = cnfe.getMessage();
488 } catch (NoSuchMethodException nsme)
490 errorMessage = nsme.getMessage();
505 * Attempts to locate the default web browser on the local system. s results
506 * so it only locates the browser once for each use of this class per JVM
509 * @return The browser for the system. Note that this may not be what you
510 * would consider to be a standard web browser; instead, it's the
511 * application that gets called to open the default web browser. In
512 * some cases, this will be a non-String object that provides the
513 * means of calling the default browser.
515 private static Object locateBrowser()
528 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
531 Object aeTarget = aeTargetConstructor.newInstance(new Object[]
532 { finderCreatorCode });
533 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[]
535 Object appleEvent = appleEventConstructor.newInstance(new Object[]
536 { gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
537 kAnyTransactionID });
539 // Don't set browser = appleEvent because then the next time we call
540 // locateBrowser(), we'll get the same AppleEvent, to which we'll
542 // added the relevant parameter. Instead, regenerate the AppleEvent
544 // There's probably a way to do this better; if any has any ideas,
548 } catch (IllegalAccessException iae)
551 errorMessage = iae.getMessage();
554 } catch (InstantiationException ie)
557 errorMessage = ie.getMessage();
560 } catch (InvocationTargetException ite)
563 errorMessage = ite.getMessage();
574 systemFolder = (File) findFolder.invoke(null, new Object[]
575 { kSystemFolderType });
576 } catch (IllegalArgumentException iare)
579 errorMessage = iare.getMessage();
582 } catch (IllegalAccessException iae)
585 errorMessage = iae.getMessage();
588 } catch (InvocationTargetException ite)
591 errorMessage = ite.getTargetException().getClass() + ": "
592 + ite.getTargetException().getMessage();
597 String[] systemFolderFiles = systemFolder.list();
599 // Avoid a FilenameFilter because that can't be stopped mid-list
600 for (int i = 0; i < systemFolderFiles.length; i++)
604 File file = new File(systemFolder, systemFolderFiles[i]);
611 // We're looking for a file with a creator code of 'MACS' and
612 // a type of 'FNDR'. Only requiring the type results in non-Finder
613 // applications being picked up on certain Mac OS 9 systems,
614 // especially German ones, and sending a GURL event to those
615 // applications results in a logout under Multiple Users.
616 Object fileType = getFileType.invoke(null, new Object[]
619 if (FINDER_TYPE.equals(fileType.toString()))
621 Object fileCreator = getFileCreator.invoke(null, new Object[]
624 if (FINDER_CREATOR.equals(fileCreator.toString()))
626 browser = file.toString(); // Actually the Finder, but that's OK
631 } catch (IllegalArgumentException iare)
633 errorMessage = iare.getMessage();
636 } catch (IllegalAccessException iae)
639 errorMessage = iae.getMessage();
642 } catch (InvocationTargetException ite)
645 errorMessage = ite.getTargetException().getClass() + ": "
646 + ite.getTargetException().getMessage();
658 browser = ""; // Return something non-null
668 browser = "command.com";
674 browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox");
683 * used to ensure that browser is up-to-date after a configuration change
684 * (Unix DEFAULT_BROWSER property change).
686 public static void resetBrowser()
692 * Attempts to open the default web browser to the given URL.
696 * @throws IOException
697 * If the web browser could not be located or does not run
699 public static void openURL(String url) throws IOException
701 if (!loadedWithoutErrors)
703 throw new IOException("Exception in finding browser: " + errorMessage);
706 Object browser = locateBrowser();
710 throw new IOException("Unable to locate browser: " + errorMessage);
717 Object aeDesc = null;
721 aeDesc = aeDescConstructor.newInstance(new Object[]
723 putParameter.invoke(browser, new Object[]
724 { keyDirectObject, aeDesc });
725 sendNoReply.invoke(browser, new Object[]
727 } catch (InvocationTargetException ite)
729 throw new IOException(
730 "InvocationTargetException while creating AEDesc: "
732 } catch (IllegalAccessException iae)
734 throw new IOException(
735 "IllegalAccessException while building AppleEvent: "
737 } catch (InstantiationException ie)
739 throw new IOException(
740 "InstantiationException while creating AEDesc: "
744 aeDesc = null; // Encourage it to get disposed if it was created
745 browser = null; // Ditto
751 Runtime.getRuntime().exec(new String[]
752 { (String) browser, url });
758 int[] instance = new int[1];
759 int result = ICStart(instance, 0);
763 int[] selectionStart = new int[]
765 byte[] urlBytes = url.getBytes();
766 int[] selectionEnd = new int[]
768 result = ICLaunchURL(instance[0], new byte[]
769 { 0 }, urlBytes, urlBytes.length, selectionStart, selectionEnd);
773 // Ignore the return value; the URL was launched successfully
774 // regardless of what happens here.
779 throw new IOException("Unable to launch URL: " + result);
784 throw new IOException(
785 "Unable to create an Internet Config instance: " + result);
794 openURL.invoke(null, new Object[]
796 } catch (InvocationTargetException ite)
798 throw new IOException(
799 "InvocationTargetException while calling openURL: "
801 } catch (IllegalAccessException iae)
803 throw new IOException(
804 "IllegalAccessException while calling openURL: "
813 // Add quotes around the URL to allow ampersands and other special
814 // characters to work.
815 Process process = Runtime.getRuntime().exec(
817 { (String) browser, FIRST_WINDOWS_PARAMETER,
818 SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
821 // This avoids a memory leak on some versions of Java on Windows.
822 // That's hinted at in
823 // <http://developer.java.sun.com/developer/qow/archive/68/>.
828 } catch (InterruptedException ie)
830 throw new IOException(
831 "InterruptedException while launching browser: "
839 // Assume that we're on Unix and that Netscape (actually Firefox) is
841 // First, attempt to open the URL in a currently running session of
846 * System.out.println("Executing : "+browser+" "+
847 * NETSCAPE_REMOTE_PARAMETER+" "+ NETSCAPE_OPEN_PARAMETER_START + url +
848 * NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END);
850 process = Runtime.getRuntime().exec(
854 NETSCAPE_REMOTE_PARAMETER,
856 NETSCAPE_OPEN_PARAMETER_START + url
857 + NETSCAPE_OPEN_NEW_WINDOW
858 + NETSCAPE_OPEN_PARAMETER_END });
862 int exitCode = process.waitFor();
865 { // if Netscape was not open
866 Runtime.getRuntime().exec(new String[]
867 { (String) browser, url });
869 } catch (InterruptedException ie)
871 throw new IOException(
872 "InterruptedException while launching browser: "
880 // This should never occur, but if it does, we'll try the simplest thing
882 Runtime.getRuntime().exec(new String[]
883 { (String) browser, url });
890 * Methods required for Mac OS X. The presence of native methods does not
891 * cause any problems on other platforms.
893 private native static int ICStart(int[] instance, int signature);
895 private native static int ICStop(int[] instance);
897 private native static int ICLaunchURL(int instance, byte[] hint,
898 byte[] data, int len, int[] selectionStart, int[] selectionEnd);