Debian Codegraph @

src/java/org/astrogrid/samp/gui/BrowserLauncher.java

raw
1 // package edu.stanford.ejalbert;
2 //
3 // This class taken from http://browserlauncher.sourceforge.net/
4 // and renamed with a couple of tweaks for convenience.
5 // Original version is BrowserLauncher 1.4b1.
6
7 package org.astrogrid.samp.gui;
8
9 import java.io.File;
10 import java.io.FileNotFoundException;
11 import java.io.IOException;
12 import java.lang.reflect.Constructor;
13 import java.lang.reflect.Field;
14 import java.lang.reflect.InvocationTargetException;
15 import java.lang.reflect.Method;
16
17 /**
18 * BrowserLauncher is a class that provides one static method, openURL, which opens the default
19 * web browser for the current user of the system to the given URL. It may support other
20 * protocols depending on the system -- mailto, ftp, etc. -- but that has not been rigorously
21 * tested and is not guaranteed to work.
22 * <p>
23 * Yes, this is platform-specific code, and yes, it may rely on classes on certain platforms
24 * that are not part of the standard JDK. What we're trying to do, though, is to take something
25 * that's frequently desirable but inherently platform-specific -- opening a default browser --
26 * and allow programmers (you, for example) to do so without worrying about dropping into native
27 * code or doing anything else similarly evil.
28 * <p>
29 * Anyway, this code is completely in Java and will run on all JDK 1.1-compliant systems without
30 * modification or a need for additional libraries. All classes that are required on certain
31 * platforms to allow this to run are dynamically loaded at runtime via reflection and, if not
32 * found, will not cause this to do anything other than returning an error when opening the
33 * browser.
34 * <p>
35 * There are certain system requirements for this class, as it's running through Runtime.exec(),
36 * which is Java's way of making a native system call. Currently, this requires that a Macintosh
37 * have a Finder which supports the GURL event, which is true for Mac OS 8.0 and 8.1 systems that
38 * have the Internet Scripting AppleScript dictionary installed in the Scripting Additions folder
39 * in the Extensions folder (which is installed by default as far as I know under Mac OS 8.0 and
40 * 8.1), and for all Mac OS 8.5 and later systems. On Windows, it only runs under Win32 systems
41 * (Windows 95, 98, and NT 4.0, as well as later versions of all). On other systems, this drops
42 * back from the inherently platform-sensitive concept of a default browser and simply attempts
43 * to launch Netscape via a shell command.
44 * <p>
45 * This code is Copyright 1999-2001 by Eric Albert ([email protected]) and may be
46 * redistributed or modified in any form without restrictions as long as the portion of this
47 * comment from this paragraph through the end of the comment is not removed. The author
48 * requests that he be notified of any application, applet, or other binary that makes use of
49 * this code, but that's more out of curiosity than anything and is not required. This software
50 * includes no warranty. The author is not repsonsible for any loss of data or functionality
51 * or any adverse or unexpected effects of using this software.
52 * <p>
53 * Credits:
54 * <br>Steven Spencer, JavaWorld magazine (<a href="http://www.javaworld.com/javaworld/javatips/jw-javatip66.html">Java Tip 66</a>)
55 * <br>Thanks also to Ron B. Yeh, Eric Shapiro, Ben Engber, Paul Teitlebaum, Andrea Cantatore,
56 * Larry Barowski, Trevor Bedzek, Frank Miedrich, and Ron Rabakukk
57 *
58 * @author Eric Albert (<a href="mailto:[email protected]">[email protected]</a>)
59 * @version 1.4b1 (Released June 20, 2001)
60 */
61 class BrowserLauncher {
62
63 /**
64 * The Java virtual machine that we are running on. Actually, in most cases we only care
65 * about the operating system, but some operating systems require us to switch on the VM. */
66 private static int jvm;
67
68 /** The browser for the system */
69 private static Object browser;
70
71 /**
72 * Caches whether any classes, methods, and fields that are not part of the JDK and need to
73 * be dynamically loaded at runtime loaded successfully.
74 * <p>
75 * Note that if this is <code>false</code>, <code>openURL()</code> will always return an
76 * IOException.
77 */
78 private static boolean loadedWithoutErrors;
79
80 /** The com.apple.mrj.MRJFileUtils class */
81 private static Class mrjFileUtilsClass;
82
83 /** The com.apple.mrj.MRJOSType class */
84 private static Class mrjOSTypeClass;
85
86 /** The com.apple.MacOS.AEDesc class */
87 private static Class aeDescClass;
88
89 /** The <init>(int) method of com.apple.MacOS.AETarget */
90 private static Constructor aeTargetConstructor;
91
92 /** The <init>(int, int, int) method of com.apple.MacOS.AppleEvent */
93 private static Constructor appleEventConstructor;
94
95 /** The <init>(String) method of com.apple.MacOS.AEDesc */
96 private static Constructor aeDescConstructor;
97
98 /** The findFolder method of com.apple.mrj.MRJFileUtils */
99 private static Method findFolder;
100
101 /** The getFileCreator method of com.apple.mrj.MRJFileUtils */
102 private static Method getFileCreator;
103
104 /** The getFileType method of com.apple.mrj.MRJFileUtils */
105 private static Method getFileType;
106
107 /** The openURL method of com.apple.mrj.MRJFileUtils */
108 private static Method openURL;
109
110 /** The makeOSType method of com.apple.MacOS.OSUtils */
111 private static Method makeOSType;
112
113 /** The putParameter method of com.apple.MacOS.AppleEvent */
114 private static Method putParameter;
115
116 /** The sendNoReply method of com.apple.MacOS.AppleEvent */
117 private static Method sendNoReply;
118
119 /** Actually an MRJOSType pointing to the System Folder on a Macintosh */
120 private static Object kSystemFolderType;
121
122 /** The keyDirectObject AppleEvent parameter type */
123 private static Integer keyDirectObject;
124
125 /** The kAutoGenerateReturnID AppleEvent code */
126 private static Integer kAutoGenerateReturnID;
127
128 /** The kAnyTransactionID AppleEvent code */
129 private static Integer kAnyTransactionID;
130
131 /** The linkage object required for JDirect 3 on Mac OS X. */
132 private static Object linkage;
133
134 /** The framework to reference on Mac OS X */
135 private static final String JDirect_MacOSX = "/System/Library/Frameworks/Carbon.framework/Frameworks/HIToolbox.framework/HIToolbox";
136
137 /** JVM constant for MRJ 2.0 */
138 private static final int MRJ_2_0 = 0;
139
140 /** JVM constant for MRJ 2.1 or later */
141 private static final int MRJ_2_1 = 1;
142
143 /** JVM constant for Java on Mac OS X 10.0 (MRJ 3.0) */
144 private static final int MRJ_3_0 = 3;
145
146 /** JVM constant for MRJ 3.1 */
147 private static final int MRJ_3_1 = 4;
148
149 /** JVM constant for any Windows NT JVM */
150 private static final int WINDOWS_NT = 5;
151
152 /** JVM constant for any Windows 9x JVM */
153 private static final int WINDOWS_9x = 6;
154
155 /** JVM constant for any other platform */
156 private static final int OTHER = -1;
157
158 /**
159 * The file type of the Finder on a Macintosh. Hardcoding "Finder" would keep non-U.S. English
160 * systems from working properly.
161 */
162 private static final String FINDER_TYPE = "FNDR";
163
164 /**
165 * The creator code of the Finder on a Macintosh, which is needed to send AppleEvents to the
166 * application.
167 */
168 private static final String FINDER_CREATOR = "MACS";
169
170 /** The name for the AppleEvent type corresponding to a GetURL event. */
171 private static final String GURL_EVENT = "GURL";
172
173 /**
174 * The first parameter that needs to be passed into Runtime.exec() to open the default web
175 * browser on Windows.
176 */
177 private static final String FIRST_WINDOWS_PARAMETER = "/c";
178
179 /** The second parameter for Runtime.exec() on Windows. */
180 private static final String SECOND_WINDOWS_PARAMETER = "start";
181
182 /**
183 * The third parameter for Runtime.exec() on Windows. This is a "title"
184 * parameter that the command line expects. Setting this parameter allows
185 * URLs containing spaces to work.
186 */
187 private static final String THIRD_WINDOWS_PARAMETER = "\"\"";
188
189 /**
190 * The shell parameters for Netscape that opens a given URL in an already-open copy of Netscape
191 * on many command-line systems.
192 */
193 private static final String NETSCAPE_REMOTE_PARAMETER = "-remote";
194 private static final String NETSCAPE_OPEN_PARAMETER_START = "'openURL(";
195 private static final String NETSCAPE_OPEN_PARAMETER_END = ")'";
196
197 /**
198 * The message from any exception thrown throughout the initialization process.
199 */
200 private static String errorMessage;
201
202 /**
203 * An initialization block that determines the operating system and loads the necessary
204 * runtime data.
205 */
206 static {
207 loadedWithoutErrors = true;
208 String osName = java.lang.System.getProperty("os.name");
209 if (osName.startsWith("Mac OS")) {
210 String mrjVersion = java.lang.System.getProperty("mrj.version");
211 String majorMRJVersion = mrjVersion.substring(0, 3);
212 try {
213 double version = Double.valueOf(majorMRJVersion).doubleValue();
214 if (version == 2) {
215 jvm = MRJ_2_0;
216 } else if (version >= 2.1 && version < 3) {
217 // Assume that all 2.x versions of MRJ work the same. MRJ 2.1 actually
218 // works via Runtime.exec() and 2.2 supports that but has an openURL() method
219 // as well that we currently ignore.
220 jvm = MRJ_2_1;
221 } else if (version == 3.0) {
222 jvm = MRJ_3_0;
223 } else if (version >= 3.1) {
224 // Assume that all 3.1 and later versions of MRJ work the same.
225 jvm = MRJ_3_1;
226 } else {
227 loadedWithoutErrors = false;
228 errorMessage = "Unsupported MRJ version: " + version;
229 }
230 } catch (NumberFormatException nfe) {
231 loadedWithoutErrors = false;
232 errorMessage = "Invalid MRJ version: " + mrjVersion;
233 }
234 } else if (osName.startsWith("Windows")) {
235 if (osName.indexOf("9") != -1) {
236 jvm = WINDOWS_9x;
237 } else {
238 jvm = WINDOWS_NT;
239 }
240 } else {
241 jvm = OTHER;
242 }
243
244 if (loadedWithoutErrors) { // if we haven't hit any errors yet
245 loadedWithoutErrors = loadClasses();
246 }
247 }
248
249 /**
250 * This class should be never be instantiated; this just ensures so.
251 */
252 private BrowserLauncher() { }
253
254 /**
255 * Called by a static initializer to load any classes, fields, and methods required at runtime
256 * to locate the user's web browser.
257 * @return <code>true</code> if all intialization succeeded
258 * <code>false</code> if any portion of the initialization failed
259 */
260 private static boolean loadClasses() {
261 switch (jvm) {
262 case MRJ_2_0:
263 try {
264 Class aeTargetClass = Class.forName("com.apple.MacOS.AETarget");
265 Class osUtilsClass = Class.forName("com.apple.MacOS.OSUtils");
266 Class appleEventClass = Class.forName("com.apple.MacOS.AppleEvent");
267 Class aeClass = Class.forName("com.apple.MacOS.ae");
268 aeDescClass = Class.forName("com.apple.MacOS.AEDesc");
269
270 aeTargetConstructor = aeTargetClass.getDeclaredConstructor(new Class [] { int.class });
271 appleEventConstructor = appleEventClass.getDeclaredConstructor(new Class[] { int.class, int.class, aeTargetClass, int.class, int.class });
272 aeDescConstructor = aeDescClass.getDeclaredConstructor(new Class[] { String.class });
273
274 makeOSType = osUtilsClass.getDeclaredMethod("makeOSType", new Class [] { String.class });
275 putParameter = appleEventClass.getDeclaredMethod("putParameter", new Class[] { int.class, aeDescClass });
276 sendNoReply = appleEventClass.getDeclaredMethod("sendNoReply", new Class[] { });
277
278 Field keyDirectObjectField = aeClass.getDeclaredField("keyDirectObject");
279 keyDirectObject = (Integer) keyDirectObjectField.get(null);
280 Field autoGenerateReturnIDField = appleEventClass.getDeclaredField("kAutoGenerateReturnID");
281 kAutoGenerateReturnID = (Integer) autoGenerateReturnIDField.get(null);
282 Field anyTransactionIDField = appleEventClass.getDeclaredField("kAnyTransactionID");
283 kAnyTransactionID = (Integer) anyTransactionIDField.get(null);
284 } catch (ClassNotFoundException cnfe) {
285 errorMessage = cnfe.getMessage();
286 return false;
287 } catch (NoSuchMethodException nsme) {
288 errorMessage = nsme.getMessage();
289 return false;
290 } catch (NoSuchFieldException nsfe) {
291 errorMessage = nsfe.getMessage();
292 return false;
293 } catch (IllegalAccessException iae) {
294 errorMessage = iae.getMessage();
295 return false;
296 }
297 break;
298 case MRJ_2_1:
299 try {
300 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
301 mrjOSTypeClass = Class.forName("com.apple.mrj.MRJOSType");
302 Field systemFolderField = mrjFileUtilsClass.getDeclaredField("kSystemFolderType");
303 kSystemFolderType = systemFolderField.get(null);
304 findFolder = mrjFileUtilsClass.getDeclaredMethod("findFolder", new Class[] { mrjOSTypeClass });
305 getFileCreator = mrjFileUtilsClass.getDeclaredMethod("getFileCreator", new Class[] { File.class });
306 getFileType = mrjFileUtilsClass.getDeclaredMethod("getFileType", new Class[] { File.class });
307 } catch (ClassNotFoundException cnfe) {
308 errorMessage = cnfe.getMessage();
309 return false;
310 } catch (NoSuchFieldException nsfe) {
311 errorMessage = nsfe.getMessage();
312 return false;
313 } catch (NoSuchMethodException nsme) {
314 errorMessage = nsme.getMessage();
315 return false;
316 } catch (SecurityException se) {
317 errorMessage = se.getMessage();
318 return false;
319 } catch (IllegalAccessException iae) {
320 errorMessage = iae.getMessage();
321 return false;
322 }
323 break;
324 case MRJ_3_0:
325 try {
326 Class linker = Class.forName("com.apple.mrj.jdirect.Linker");
327 Constructor constructor = linker.getConstructor(new Class[]{ Class.class });
328 linkage = constructor.newInstance(new Object[] { BrowserLauncher.class });
329 } catch (ClassNotFoundException cnfe) {
330 errorMessage = cnfe.getMessage();
331 return false;
332 } catch (NoSuchMethodException nsme) {
333 errorMessage = nsme.getMessage();
334 return false;
335 } catch (InvocationTargetException ite) {
336 errorMessage = ite.getMessage();
337 return false;
338 } catch (InstantiationException ie) {
339 errorMessage = ie.getMessage();
340 return false;
341 } catch (IllegalAccessException iae) {
342 errorMessage = iae.getMessage();
343 return false;
344 }
345 break;
346 case MRJ_3_1:
347 try {
348 mrjFileUtilsClass = Class.forName("com.apple.mrj.MRJFileUtils");
349 openURL = mrjFileUtilsClass.getDeclaredMethod("openURL", new Class[] { String.class });
350 } catch (ClassNotFoundException cnfe) {
351 errorMessage = cnfe.getMessage();
352 return false;
353 } catch (NoSuchMethodException nsme) {
354 errorMessage = nsme.getMessage();
355 return false;
356 }
357 break;
358 default:
359 break;
360 }
361 return true;
362 }
363
364 /**
365 * Attempts to locate the default web browser on the local system. Caches results so it
366 * only locates the browser once for each use of this class per JVM instance.
367 * @return The browser for the system. Note that this may not be what you would consider
368 * to be a standard web browser; instead, it's the application that gets called to
369 * open the default web browser. In some cases, this will be a non-String object
370 * that provides the means of calling the default browser.
371 */
372 private static Object locateBrowser() {
373 if (browser != null) {
374 return browser;
375 }
376 switch (jvm) {
377 case MRJ_2_0:
378 try {
379 Integer finderCreatorCode = (Integer) makeOSType.invoke(null, new Object[] { FINDER_CREATOR });
380 Object aeTarget = aeTargetConstructor.newInstance(new Object[] { finderCreatorCode });
381 Integer gurlType = (Integer) makeOSType.invoke(null, new Object[] { GURL_EVENT });
382 Object appleEvent = appleEventConstructor.newInstance(new Object[] { gurlType, gurlType, aeTarget, kAutoGenerateReturnID, kAnyTransactionID });
383 // Don't set browser = appleEvent because then the next time we call
384 // locateBrowser(), we'll get the same AppleEvent, to which we'll already have
385 // added the relevant parameter. Instead, regenerate the AppleEvent every time.
386 // There's probably a way to do this better; if any has any ideas, please let
387 // me know.
388 return appleEvent;
389 } catch (IllegalAccessException iae) {
390 browser = null;
391 errorMessage = iae.getMessage();
392 return browser;
393 } catch (InstantiationException ie) {
394 browser = null;
395 errorMessage = ie.getMessage();
396 return browser;
397 } catch (InvocationTargetException ite) {
398 browser = null;
399 errorMessage = ite.getMessage();
400 return browser;
401 }
402 case MRJ_2_1:
403 File systemFolder;
404 try {
405 systemFolder = (File) findFolder.invoke(null, new Object[] { kSystemFolderType });
406 } catch (IllegalArgumentException iare) {
407 browser = null;
408 errorMessage = iare.getMessage();
409 return browser;
410 } catch (IllegalAccessException iae) {
411 browser = null;
412 errorMessage = iae.getMessage();
413 return browser;
414 } catch (InvocationTargetException ite) {
415 browser = null;
416 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
417 return browser;
418 }
419 String[] systemFolderFiles = systemFolder.list();
420 // Avoid a FilenameFilter because that can't be stopped mid-list
421 for(int i = 0; i < systemFolderFiles.length; i++) {
422 try {
423 File file = new File(systemFolder, systemFolderFiles[i]);
424 if (!file.isFile()) {
425 continue;
426 }
427 // We're looking for a file with a creator code of 'MACS' and
428 // a type of 'FNDR'. Only requiring the type results in non-Finder
429 // applications being picked up on certain Mac OS 9 systems,
430 // especially German ones, and sending a GURL event to those
431 // applications results in a logout under Multiple Users.
432 Object fileType = getFileType.invoke(null, new Object[] { file });
433 if (FINDER_TYPE.equals(fileType.toString())) {
434 Object fileCreator = getFileCreator.invoke(null, new Object[] { file });
435 if (FINDER_CREATOR.equals(fileCreator.toString())) {
436 browser = file.toString(); // Actually the Finder, but that's OK
437 return browser;
438 }
439 }
440 } catch (IllegalArgumentException iare) {
441 browser = browser;
442 errorMessage = iare.getMessage();
443 return null;
444 } catch (IllegalAccessException iae) {
445 browser = null;
446 errorMessage = iae.getMessage();
447 return browser;
448 } catch (InvocationTargetException ite) {
449 browser = null;
450 errorMessage = ite.getTargetException().getClass() + ": " + ite.getTargetException().getMessage();
451 return browser;
452 }
453 }
454 browser = null;
455 break;
456 case MRJ_3_0:
457 case MRJ_3_1:
458 browser = ""; // Return something non-null
459 break;
460 case WINDOWS_NT:
461 browser = "cmd.exe";
462 break;
463 case WINDOWS_9x:
464 browser = "command.com";
465 break;
466 case OTHER:
467 default:
468 browser = "firefox";
469 break;
470 }
471 return browser;
472 }
473
474 /**
475 * Attempts to open the default web browser to the given URL.
476 * @param url The URL to open
477 * @throws IOException If the web browser could not be located or does not run
478 */
479 public static void openURL(String url) throws IOException {
480 if (!loadedWithoutErrors) {
481 throw new IOException("Exception in finding browser: " + errorMessage);
482 }
483 Object browser = locateBrowser();
484 if (browser == null) {
485 throw new IOException("Unable to locate browser: " + errorMessage);
486 }
487
488 switch (jvm) {
489 case MRJ_2_0:
490 Object aeDesc = null;
491 try {
492 aeDesc = aeDescConstructor.newInstance(new Object[] { url });
493 putParameter.invoke(browser, new Object[] { keyDirectObject, aeDesc });
494 sendNoReply.invoke(browser, new Object[] { });
495 } catch (InvocationTargetException ite) {
496 throw new IOException("InvocationTargetException while creating AEDesc: " + ite.getMessage());
497 } catch (IllegalAccessException iae) {
498 throw new IOException("IllegalAccessException while building AppleEvent: " + iae.getMessage());
499 } catch (InstantiationException ie) {
500 throw new IOException("InstantiationException while creating AEDesc: " + ie.getMessage());
501 } finally {
502 aeDesc = null; // Encourage it to get disposed if it was created
503 browser = null; // Ditto
504 }
505 break;
506 case MRJ_2_1:
507 Runtime.getRuntime().exec(new String[] { (String) browser, url } );
508 break;
509 case MRJ_3_0:
510 int[] instance = new int[1];
511 int result = ICStart(instance, 0);
512 if (result == 0) {
513 int[] selectionStart = new int[] { 0 };
514 byte[] urlBytes = url.getBytes();
515 int[] selectionEnd = new int[] { urlBytes.length };
516 result = ICLaunchURL(instance[0], new byte[] { 0 }, urlBytes,
517 urlBytes.length, selectionStart,
518 selectionEnd);
519 if (result == 0) {
520 // Ignore the return value; the URL was launched successfully
521 // regardless of what happens here.
522 ICStop(instance);
523 } else {
524 throw new IOException("Unable to launch URL: " + result);
525 }
526 } else {
527 throw new IOException("Unable to create an Internet Config instance: " + result);
528 }
529 break;
530 case MRJ_3_1:
531 try {
532 openURL.invoke(null, new Object[] { url });
533 } catch (InvocationTargetException ite) {
534 throw new IOException("InvocationTargetException while calling openURL: " + ite.getMessage());
535 } catch (IllegalAccessException iae) {
536 throw new IOException("IllegalAccessException while calling openURL: " + iae.getMessage());
537 }
538 break;
539 case WINDOWS_NT:
540 case WINDOWS_9x:
541 // Add quotes around the URL to allow ampersands and other special
542 // characters to work.
543 Process process = Runtime.getRuntime().exec(new String[] { (String) browser,
544 FIRST_WINDOWS_PARAMETER,
545 SECOND_WINDOWS_PARAMETER,
546 THIRD_WINDOWS_PARAMETER,
547 '"' + url + '"' });
548 // This avoids a memory leak on some versions of Java on Windows.
549 // That's hinted at in <http://developer.java.sun.com/developer/qow/archive/68/>.
550 try {
551 process.waitFor();
552 process.exitValue();
553 } catch (InterruptedException ie) {
554 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
555 }
556 break;
557 case OTHER:
558 // Assume that we're on Unix and that Netscape is installed
559
560 // First, attempt to open the URL in a currently running session of Netscape
561 process = Runtime.getRuntime().exec(new String[] { (String) browser,
562 NETSCAPE_REMOTE_PARAMETER,
563 NETSCAPE_OPEN_PARAMETER_START +
564 url +
565 NETSCAPE_OPEN_PARAMETER_END });
566 try {
567 int exitCode = process.waitFor();
568 if (exitCode != 0) { // if Netscape was not open
569 Runtime.getRuntime().exec(new String[] { (String) browser, url });
570 }
571 } catch (InterruptedException ie) {
572 throw new IOException("InterruptedException while launching browser: " + ie.getMessage());
573 }
574 break;
575 default:
576 // This should never occur, but if it does, we'll try the simplest thing possible
577 Runtime.getRuntime().exec(new String[] { (String) browser, url });
578 break;
579 }
580 }
581
582 /**
583 * Methods required for Mac OS X. The presence of native methods does not cause
584 * any problems on other platforms.
585 */
586 private native static int ICStart(int[] instance, int signature);
587 private native static int ICStop(int[] instance);
588 private native static int ICLaunchURL(int instance, byte[] hint, byte[] data, int len,
589 int[] selectionStart, int[] selectionEnd);
590 }