Bump java library versions
[fw/altos] / altosuilib / OSXAdapter.java
1 /*
2
3 File: OSXAdapter.java
4
5 Abstract: Hooks existing preferences/about/quit functionality from an
6     existing Java app into handlers for the Mac OS X application menu.
7     Uses a Proxy object to dynamically implement the
8     com.apple.eawt.ApplicationListener interface and register it with the
9     com.apple.eawt.Application object.  This allows the complete project
10     to be both built and run on any platform without any stubs or
11     placeholders. Useful for developers looking to implement Mac OS X
12     features while supporting multiple platforms with minimal impact.
13
14 Version: 2.0
15
16 Disclaimer: IMPORTANT:  This Apple software is supplied to you by
17 Apple Inc. ("Apple") in consideration of your agreement to the
18 following terms, and your use, installation, modification or
19 redistribution of this Apple software constitutes acceptance of these
20 terms.  If you do not agree with these terms, please do not use,
21 install, modify or redistribute this Apple software.
22
23 In consideration of your agreement to abide by the following terms, and
24 subject to these terms, Apple grants you a personal, non-exclusive
25 license, under Apple's copyrights in this original Apple software (the
26 "Apple Software"), to use, reproduce, modify and redistribute the Apple
27 Software, with or without modifications, in source and/or binary forms;
28 provided that if you redistribute the Apple Software in its entirety and
29 without modifications, you must retain this notice and the following
30 text and disclaimers in all such redistributions of the Apple Software.
31 Neither the name, trademarks, service marks or logos of Apple Inc.
32 may be used to endorse or promote products derived from the Apple
33 Software without specific prior written permission from Apple.  Except
34 as expressly stated in this notice, no other rights or licenses, express
35 or implied, are granted by Apple herein, including but not limited to
36 any patent rights that may be infringed by your derivative works or by
37 other works in which the Apple Software may be incorporated.
38
39 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
40 MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
41 THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
42 FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
43 OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
44
45 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
46 OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
47 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
48 INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
49 MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
50 AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
51 STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
52 POSSIBILITY OF SUCH DAMAGE.
53
54 Copyright © 2003-2007 Apple, Inc., All Rights Reserved
55
56 */
57
58 package org.altusmetrum.altosuilib_6;
59
60 import java.lang.reflect.*;
61 import java.util.HashMap;
62
63
64 public class OSXAdapter implements InvocationHandler {
65
66     protected Object targetObject;
67     protected Method targetMethod;
68     protected String proxySignature;
69
70     static Object macOSXApplication;
71
72     // Pass this method an Object and Method equipped to perform application shutdown logic
73     // The method passed should return a boolean stating whether or not the quit should occur
74     public static void setQuitHandler(Object target, Method quitHandler) {
75         setHandler(new OSXAdapter("handleQuit", target, quitHandler));
76     }
77
78     // Pass this method an Object and Method equipped to display application info
79     // They will be called when the About menu item is selected from the application menu
80     public static void setAboutHandler(Object target, Method aboutHandler) {
81         boolean enableAboutMenu = (target != null && aboutHandler != null);
82         if (enableAboutMenu) {
83             setHandler(new OSXAdapter("handleAbout", target, aboutHandler));
84         }
85         // If we're setting a handler, enable the About menu item by calling
86         // com.apple.eawt.Application reflectively
87         try {
88             Method enableAboutMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledAboutMenu", new Class[] { boolean.class });
89             enableAboutMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enableAboutMenu) });
90         } catch (Exception ex) {
91             System.err.println("OSXAdapter could not access the About Menu");
92             ex.printStackTrace();
93         }
94     }
95
96     // Pass this method an Object and a Method equipped to display application options
97     // They will be called when the Preferences menu item is selected from the application menu
98     public static void setPreferencesHandler(Object target, Method prefsHandler) {
99         boolean enablePrefsMenu = (target != null && prefsHandler != null);
100         if (enablePrefsMenu) {
101             setHandler(new OSXAdapter("handlePreferences", target, prefsHandler));
102         }
103         // If we're setting a handler, enable the Preferences menu item by calling
104         // com.apple.eawt.Application reflectively
105         try {
106             Method enablePrefsMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledPreferencesMenu", new Class[] { boolean.class });
107             enablePrefsMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enablePrefsMenu) });
108         } catch (Exception ex) {
109             System.err.println("OSXAdapter could not access the About Menu");
110             ex.printStackTrace();
111         }
112     }
113
114     // Pass this method an Object and a Method equipped to handle document events from the Finder
115     // Documents are registered with the Finder via the CFBundleDocumentTypes dictionary in the
116     // application bundle's Info.plist
117     public static void setFileHandler(Object target, Method fileHandler) {
118         setHandler(new OSXAdapter("handleOpenFile", target, fileHandler) {
119             // Override OSXAdapter.callTarget to send information on the
120             // file to be opened
121             public boolean callTarget(Object appleEvent) {
122                 if (appleEvent != null) {
123                     try {
124                         Method getFilenameMethod = appleEvent.getClass().getDeclaredMethod("getFilename", (Class[])null);
125                         String filename = (String) getFilenameMethod.invoke(appleEvent, (Object[])null);
126                         this.targetMethod.invoke(this.targetObject, new Object[] { filename });
127                     } catch (Exception ex) {
128
129                     }
130                 }
131                 return true;
132             }
133         });
134     }
135
136     // setHandler creates a Proxy object from the passed OSXAdapter and adds it as an ApplicationListener
137     public static void setHandler(OSXAdapter adapter) {
138         try {
139             Class applicationClass = Class.forName("com.apple.eawt.Application");
140             if (macOSXApplication == null) {
141                 macOSXApplication = applicationClass.getConstructor((Class[])null).newInstance((Object[])null);
142             }
143             Class applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener");
144             Method addListenerMethod = applicationClass.getDeclaredMethod("addApplicationListener", new Class[] { applicationListenerClass });
145             // Create a proxy object around this handler that can be reflectively added as an Apple ApplicationListener
146             Object osxAdapterProxy = Proxy.newProxyInstance(OSXAdapter.class.getClassLoader(), new Class[] { applicationListenerClass }, adapter);
147             addListenerMethod.invoke(macOSXApplication, new Object[] { osxAdapterProxy });
148         } catch (ClassNotFoundException cnfe) {
149             System.err.println("This version of Mac OS X does not support the Apple EAWT.  ApplicationEvent handling has been disabled (" + cnfe + ")");
150         } catch (Exception ex) {  // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking eawt.Application methods
151             System.err.println("Mac OS X Adapter could not talk to EAWT:");
152             ex.printStackTrace();
153         }
154     }
155
156     // Each OSXAdapter has the name of the EAWT method it intends to listen for (handleAbout, for example),
157     // the Object that will ultimately perform the task, and the Method to be called on that Object
158     protected OSXAdapter(String proxySignature, Object target, Method handler) {
159         this.proxySignature = proxySignature;
160         this.targetObject = target;
161         this.targetMethod = handler;
162     }
163
164     // Override this method to perform any operations on the event
165     // that comes with the various callbacks
166     // See setFileHandler above for an example
167     public boolean callTarget(Object appleEvent) throws InvocationTargetException, IllegalAccessException {
168         Object result = targetMethod.invoke(targetObject, (Object[])null);
169         if (result == null) {
170             return true;
171         }
172         return Boolean.valueOf(result.toString()).booleanValue();
173     }
174
175     // InvocationHandler implementation
176     // This is the entry point for our proxy object; it is called every time an ApplicationListener method is invoked
177     public Object invoke (Object proxy, Method method, Object[] args) throws Throwable {
178         if (isCorrectMethod(method, args)) {
179             boolean handled = callTarget(args[0]);
180             setApplicationEventHandled(args[0], handled);
181         }
182         // All of the ApplicationListener methods are void; return null regardless of what happens
183         return null;
184     }
185
186     // Compare the method that was called to the intended method when the OSXAdapter instance was created
187     // (e.g. handleAbout, handleQuit, handleOpenFile, etc.)
188     protected boolean isCorrectMethod(Method method, Object[] args) {
189         return (targetMethod != null && proxySignature.equals(method.getName()) && args.length == 1);
190     }
191
192     // It is important to mark the ApplicationEvent as handled and cancel the default behavior
193     // This method checks for a boolean result from the proxy method and sets the event accordingly
194     protected void setApplicationEventHandled(Object event, boolean handled) {
195         if (event != null) {
196             try {
197                 Method setHandledMethod = event.getClass().getDeclaredMethod("setHandled", new Class[] { boolean.class });
198                 // If the target method returns a boolean, use that as a hint
199                 setHandledMethod.invoke(event, new Object[] { Boolean.valueOf(handled) });
200             } catch (Exception ex) {
201                 System.err.println("OSXAdapter was unable to handle an ApplicationEvent: " + event);
202                 ex.printStackTrace();
203             }
204         }
205     }
206 }