2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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/>.
21 import java.lang.reflect.*;
24 * BrowserLauncher is a class that provides one static method, openURL, which
25 * opens the default web browser for the current user of the system to the given
26 * URL. It may support other protocols depending on the system -- mailto, ftp,
27 * etc. -- but that has not been rigorously tested and is not guaranteed to
30 * Yes, this is platform-specific code, and yes, it may rely on classes on
31 * certain platforms that are not part of the standard JDK. What we're trying to
32 * do, though, is to take something that's frequently desirable but inherently
33 * platform-specific -- opening a default browser -- and allow programmers (you,
34 * for example) to do so without worrying about dropping into native code or
35 * doing anything else similarly evil.
37 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant
38 * systems without modification or a need for additional libraries. All classes
39 * that are required on certain platforms to allow this to run are dynamically
40 * loaded at runtime via reflection and, if not found, will not cause this to do
41 * anything other than returning an error when opening the browser.
43 * There are certain system requirements for this class, as it's running through
44 * Runtime.exec(), which is Java's way of making a native system call.
45 * Currently, this requires that a Macintosh have a Finder which supports the
46 * GURL event, which is true for Mac OS 8.0 and 8.1 systems that have the
47 * Internet Scripting AppleScript dictionary installed in the Scripting
48 * Additions folder in the Extensions folder (which is installed by default as
49 * far as I know under Mac OS 8.0 and 8.1), and for all Mac OS 8.5 and later
50 * systems. On Windows, it only runs under Win32 systems (Windows 95, 98, and NT
51 * 4.0, as well as later versions of all). On other systems, this drops back
52 * from the inherently platform-sensitive concept of a default browser and
53 * simply attempts to launch Netscape via a shell command.
55 * This code is Copyright 1999-2001 by Eric Albert (ejalbert\@cs.stanford.edu)
56 * and may be redistributed or modified in any form without restrictions as long
57 * as the portion of this comment from this paragraph through the end of the
58 * comment is not removed. The author requests that he be notified of any
59 * application, applet, or other binary that makes use of this code, but that's
60 * more out of curiosity than anything and is not required. This software
61 * includes no warranty. The author is not repsonsible for any loss of data or
62 * functionality or any adverse or unexpected effects of using this software.
65 * Steven Spencer, JavaWorld magazine (<a
66 * href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip
68 * Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea
69 * Cantatore, Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
71 * @author Eric Albert (<a
72 * href="mailto:ejalbert@cs.stanford.edu">ejalbert@cs.stanford.edu</a>)
73 * @version 1.4b1 (Released June 20, 2001)
75 public class BrowserLauncher
78 * The Java virtual machine that we are running on. Actually, in most cases we
79 * only care about the operating system, but some operating systems require us
80 * to switch on the VM.
82 private static int jvm;
84 /** The browser for the system */
85 private static Object browser;
88 * Caches whether any classes, methods, and fields that are not part of the
89 * JDK and need to be dynamically loaded at runtime loaded successfully.
91 * Note that if this is <code>false</code>, <code>openURL()</code> will always
92 * return an IOException.
94 private static boolean loadedWithoutErrors;
96 /** The com.apple.mrj.MRJFileUtils class */
97 private static Class mrjFileUtilsClass;
99 /** The com.apple.mrj.MRJOSType class */
100 private static Class mrjOSTypeClass;
102 /** The com.apple.MacOS.AEDesc class */
103 private static Class aeDescClass;
105 /** The <init>(int) method of com.apple.MacOS.AETarget */
106 private static Constructor aeTargetConstructor;
108 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
109 private static Constructor appleEventConstructor;
111 /** The <init>(String) method of com.apple.MacOS.AEDesc */
112 private static Constructor aeDescConstructor;
114 /** The findFolder method of com.apple.mrj.MRJFileUtils */
115 private static Method findFolder;
117 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
118 private static Method getFileCreator;
120 /** The getFileType method of com.apple.mrj.MRJFileUtils */
121 private static Method getFileType;
123 /** The openURL method of com.apple.mrj.MRJFileUtils */
124 private static Method openURL;
126 /** The makeOSType method of com.apple.MacOS.OSUtils */
127 private static Method makeOSType;
129 /** The putParameter method of com.apple.MacOS.AppleEvent */
130 private static Method putParameter;
132 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
133 private static Method sendNoReply;
135 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
136 private static Object kSystemFolderType;
138 /** The keyDirectObject AppleEvent parameter type */
139 private static Integer keyDirectObject;
141 /** The kAutoGenerateReturnID AppleEvent code */
142 private static Integer kAutoGenerateReturnID;
144 /** The kAnyTransactionID AppleEvent code */
145 private static Integer kAnyTransactionID;
147 /** The linkage object required for JDirect 3 on Mac OS X. */
148 private static Object linkage;
150 /** The framework to reference on Mac OS X */
151 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
153 /** JVM constant for MRJ 2.0 */
154 private static final int MRJ_2_0 = 0;
156 /** JVM constant for MRJ 2.1 or later */
157 private static final int MRJ_2_1 = 1;
159 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
160 private static final int MRJ_3_0 = 3;
162 /** JVM constant for MRJ 3.1 */
163 private static final int MRJ_3_1 = 4;
165 /** JVM constant for any Windows NT JVM */
166 private static final int WINDOWS_NT = 5;
168 /** JVM constant for any Windows 9x JVM */
169 private static final int WINDOWS_9x = 6;
171 /** JVM constant for any other platform */
172 private static final int OTHER = -1;
175 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep
176 * non-U.S. English systems from working properly.
178 private static final String FINDER_TYPE = "FNDR";
181 * The creator code of the Finder on a Macintosh, which is needed to send
182 * AppleEvents to the application.
184 private static final String FINDER_CREATOR = "MACS";
186 /** The name for the AppleEvent type corresponding to a GetURL event. */
187 private static final String GURL_EVENT = "GURL";
190 * The first parameter that needs to be passed into Runtime.exec() to open the
191 * default web browser on Windows.
193 private static final String FIRST_WINDOWS_PARAMETER = "/c";
195 /** The second parameter for Runtime.exec() on Windows. */
196 private static final String SECOND_WINDOWS_PARAMETER = "start";
199 * The third parameter for Runtime.exec() on Windows. This is a "title"
200 * parameter that the command line expects. Setting this parameter allows URLs
201 * containing spaces to work.
203 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
206 * The shell parameters for Netscape that opens a given URL in an already-open
207 * copy of Netscape on many command-line systems.
209 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
211 private static final String NETSCAPE_OPEN_PARAMETER_START = "openURL(";
213 private static final String NETSCAPE_OPEN_NEW_WINDOW = ", new-window";
215 private static final String NETSCAPE_OPEN_PARAMETER_END = ")";
218 * The message from any exception thrown throughout the initialization
221 private static String errorMessage;
224 * An initialization block that determines the operating system and loads the
225 * necessary runtime data.
229 loadedWithoutErrors = true;
231 String osName = System.getProperty("os.name");
233 if (osName.startsWith("Mac OS"))
235 String mrjVersion = System.getProperty("mrj.version");
236 String majorMRJVersion;
237 if (mrjVersion == null)
239 // must be on some later build with mrj support
240 majorMRJVersion = "3.1";
244 majorMRJVersion = mrjVersion.substring(0, 3);
249 double version = Double.valueOf(majorMRJVersion).doubleValue();
255 else if ((version >= 2.1) && (version < 3))
257 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
258 // works via Runtime.exec() and 2.2 supports that but has an openURL()
260 // as well that we currently ignore.
263 else if (version == 3.0)
267 else if (version >= 3.1)
269 // Assume that all 3.1 and later versions of MRJ work the same.
274 loadedWithoutErrors = false;
275 errorMessage = "Unsupported MRJ version: " + version;
277 } catch (NumberFormatException nfe)
279 loadedWithoutErrors = false;
280 errorMessage = "Invalid MRJ version: " + mrjVersion;
283 else if (osName.startsWith("Windows"))
285 if (osName.indexOf("9") != -1)
299 if (loadedWithoutErrors)
300 { // if we haven't hit any errors yet
301 loadedWithoutErrors = loadClasses();
306 * This class should be never be instantiated; this just ensures so.
308 private BrowserLauncher()
313 * Called by a static initializer to load any classes, fields, and methods
314 * required at runtime to locate the user's web browser.
316 * @return <code>true</code> if all intialization succeeded <code>false</code>
317 * if any portion of the initialization failed
319 private static boolean loadClasses()
327 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
328 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
329 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
330 Class aeClass = Class.forName("com.apple.MacOS.ae");
331 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
333 aeTargetConstructor = aeTargetClass
334 .getDeclaredConstructor(new Class[]
336 appleEventConstructor = appleEventClass
337 .getDeclaredConstructor(new Class[]
338 { int.class, int.class, aeTargetClass, int.class, int.class });
339 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[]
342 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType",
345 putParameter = appleEventClass.getDeclaredMethod("putParameter",
347 { int.class, aeDescClass });
348 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply",
352 Field keyDirectObjectField = aeClass
353 .getDeclaredField("keyDirectObject");
354 keyDirectObject = (Integer) keyDirectObjectField.get(null);
356 Field autoGenerateReturnIDField = appleEventClass
357 .getDeclaredField("kAutoGenerateReturnID");
358 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField
361 Field anyTransactionIDField = appleEventClass
362 .getDeclaredField("kAnyTransactionID");
363 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
364 } catch (ClassNotFoundException cnfe)
366 errorMessage = cnfe.getMessage();
369 } catch (NoSuchMethodException nsme)
371 errorMessage = nsme.getMessage();
374 } catch (NoSuchFieldException nsfe)
376 errorMessage = nsfe.getMessage();
379 } catch (IllegalAccessException iae)
381 errorMessage = iae.getMessage();
392 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
393 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
395 Field systemFolderField = mrjFileUtilsClass
396 .getDeclaredField("kSystemFolderType");
397 kSystemFolderType = systemFolderField.get(null);
398 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder",
401 getFileCreator = mrjFileUtilsClass.getDeclaredMethod(
402 "getFileCreator", new Class[]
404 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType",
407 } catch (ClassNotFoundException cnfe)
409 errorMessage = cnfe.getMessage();
412 } catch (NoSuchFieldException nsfe)
414 errorMessage = nsfe.getMessage();
417 } catch (NoSuchMethodException nsme)
419 errorMessage = nsme.getMessage();
422 } catch (SecurityException se)
424 errorMessage = se.getMessage();
427 } catch (IllegalAccessException iae)
429 errorMessage = iae.getMessage();
440 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
441 Constructor constructor = linker.getConstructor(new Class[]
443 linkage = constructor.newInstance(new Object[]
444 { BrowserLauncher.class });
445 } catch (ClassNotFoundException cnfe)
447 errorMessage = cnfe.getMessage();
450 } catch (NoSuchMethodException nsme)
452 errorMessage = nsme.getMessage();
455 } catch (InvocationTargetException ite)
457 errorMessage = ite.getMessage();
460 } catch (InstantiationException ie)
462 errorMessage = ie.getMessage();
465 } catch (IllegalAccessException iae)
467 errorMessage = iae.getMessage();
478 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
479 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL",
482 } catch (ClassNotFoundException cnfe)
484 errorMessage = cnfe.getMessage();
487 } catch (NoSuchMethodException nsme)
489 errorMessage = nsme.getMessage();
504 * Attempts to locate the default web browser on the local system. s results
505 * so it only locates the browser once for each use of this class per JVM
508 * @return The browser for the system. Note that this may not be what you
509 * would consider to be a standard web browser; instead, it's the
510 * application that gets called to open the default web browser. In
511 * some cases, this will be a non-String object that provides the
512 * means of calling the default browser.
514 private static Object locateBrowser()
527 Integer finderCreatorCode = (Integer) makeOSType.invoke(null,
530 Object aeTarget = aeTargetConstructor.newInstance(new Object[]
531 { finderCreatorCode });
532 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[]
534 Object appleEvent = appleEventConstructor.newInstance(new Object[]
535 { gurlType, gurlType, aeTarget, kAutoGenerateReturnID,
536 kAnyTransactionID });
538 // Don't set browser = appleEvent because then the next time we call
539 // locateBrowser(), we'll get the same AppleEvent, to which we'll
541 // added the relevant parameter. Instead, regenerate the AppleEvent
543 // There's probably a way to do this better; if any has any ideas,
547 } catch (IllegalAccessException iae)
550 errorMessage = iae.getMessage();
553 } catch (InstantiationException ie)
556 errorMessage = ie.getMessage();
559 } catch (InvocationTargetException ite)
562 errorMessage = ite.getMessage();
573 systemFolder = (File) findFolder.invoke(null, new Object[]
574 { kSystemFolderType });
575 } catch (IllegalArgumentException iare)
578 errorMessage = iare.getMessage();
581 } catch (IllegalAccessException iae)
584 errorMessage = iae.getMessage();
587 } catch (InvocationTargetException ite)
590 errorMessage = ite.getTargetException().getClass() + ": "
591 + ite.getTargetException().getMessage();
596 String[] systemFolderFiles = systemFolder.list();
598 // Avoid a FilenameFilter because that can't be stopped mid-list
599 for (int i = 0; i < systemFolderFiles.length; i++)
603 File file = new File(systemFolder, systemFolderFiles[i]);
610 // We're looking for a file with a creator code of 'MACS' and
611 // a type of 'FNDR'. Only requiring the type results in non-Finder
612 // applications being picked up on certain Mac OS 9 systems,
613 // especially German ones, and sending a GURL event to those
614 // applications results in a logout under Multiple Users.
615 Object fileType = getFileType.invoke(null, new Object[]
618 if (FINDER_TYPE.equals(fileType.toString()))
620 Object fileCreator = getFileCreator.invoke(null, new Object[]
623 if (FINDER_CREATOR.equals(fileCreator.toString()))
625 browser = file.toString(); // Actually the Finder, but that's OK
630 } catch (IllegalArgumentException iare)
632 errorMessage = iare.getMessage();
635 } catch (IllegalAccessException iae)
638 errorMessage = iae.getMessage();
641 } catch (InvocationTargetException ite)
644 errorMessage = ite.getTargetException().getClass() + ": "
645 + ite.getTargetException().getMessage();
657 browser = ""; // Return something non-null
667 browser = "command.com";
673 browser = jalview.bin.Cache.getDefault("DEFAULT_BROWSER", "firefox");
682 * used to ensure that browser is up-to-date after a configuration change
683 * (Unix DEFAULT_BROWSER property change).
685 public static void resetBrowser()
691 * Attempts to open the default web browser to the given URL.
695 * @throws IOException
696 * If the web browser could not be located or does not run
698 public static void openURL(String url) throws IOException
700 if (!loadedWithoutErrors)
702 throw new IOException("Exception in finding browser: " + errorMessage);
705 Object browser = locateBrowser();
709 throw new IOException("Unable to locate browser: " + errorMessage);
716 Object aeDesc = null;
720 aeDesc = aeDescConstructor.newInstance(new Object[]
722 putParameter.invoke(browser, new Object[]
723 { keyDirectObject, aeDesc });
724 sendNoReply.invoke(browser, new Object[]
726 } catch (InvocationTargetException ite)
728 throw new IOException(
729 "InvocationTargetException while creating AEDesc: "
731 } catch (IllegalAccessException iae)
733 throw new IOException(
734 "IllegalAccessException while building AppleEvent: "
736 } catch (InstantiationException ie)
738 throw new IOException(
739 "InstantiationException while creating AEDesc: "
743 aeDesc = null; // Encourage it to get disposed if it was created
744 browser = null; // Ditto
750 Runtime.getRuntime().exec(new String[]
751 { (String) browser, url });
757 int[] instance = new int[1];
758 int result = ICStart(instance, 0);
762 int[] selectionStart = new int[]
764 byte[] urlBytes = url.getBytes();
765 int[] selectionEnd = new int[]
767 result = ICLaunchURL(instance[0], new byte[]
768 { 0 }, urlBytes, urlBytes.length, selectionStart, selectionEnd);
772 // Ignore the return value; the URL was launched successfully
773 // regardless of what happens here.
778 throw new IOException("Unable to launch URL: " + result);
783 throw new IOException(
784 "Unable to create an Internet Config instance: " + result);
793 openURL.invoke(null, new Object[]
795 } catch (InvocationTargetException ite)
797 throw new IOException(
798 "InvocationTargetException while calling openURL: "
800 } catch (IllegalAccessException iae)
802 throw new IOException(
803 "IllegalAccessException while calling openURL: "
812 // Add quotes around the URL to allow ampersands and other special
813 // characters to work.
814 Process process = Runtime.getRuntime().exec(
816 { (String) browser, FIRST_WINDOWS_PARAMETER,
817 SECOND_WINDOWS_PARAMETER, THIRD_WINDOWS_PARAMETER,
820 // This avoids a memory leak on some versions of Java on Windows.
821 // That's hinted at in
822 // <http://developer.java.sun.com/developer/qow/archive/68/>.
827 } catch (InterruptedException ie)
829 throw new IOException(
830 "InterruptedException while launching browser: "
838 // Assume that we're on Unix and that Netscape (actually Firefox) is
840 // First, attempt to open the URL in a currently running session of
845 * System.out.println("Executing : "+browser+" "+
846 * NETSCAPE_REMOTE_PARAMETER+" "+ NETSCAPE_OPEN_PARAMETER_START + url +
847 * NETSCAPE_OPEN_NEW_WINDOW + NETSCAPE_OPEN_PARAMETER_END);
849 process = Runtime.getRuntime().exec(
853 NETSCAPE_REMOTE_PARAMETER,
855 NETSCAPE_OPEN_PARAMETER_START + url
856 + NETSCAPE_OPEN_NEW_WINDOW
857 + NETSCAPE_OPEN_PARAMETER_END });
861 int exitCode = process.waitFor();
864 { // if Netscape was not open
865 Runtime.getRuntime().exec(new String[]
866 { (String) browser, url });
868 } catch (InterruptedException ie)
870 throw new IOException(
871 "InterruptedException while launching browser: "
879 // This should never occur, but if it does, we'll try the simplest thing
881 Runtime.getRuntime().exec(new String[]
882 { (String) browser, url });
889 * Methods required for Mac OS X. The presence of native methods does not
890 * cause any problems on other platforms.
892 private native static int ICStart(int[] instance, int signature);
894 private native static int ICStop(int[] instance);
896 private native static int ICLaunchURL(int instance, byte[] hint,
897 byte[] data, int len, int[] selectionStart, int[] selectionEnd);