1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.log4j.chainsaw.osx;
18
19 import java.lang.reflect.InvocationHandler;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Proxy;
23
24 import org.apache.log4j.Logger;
25 import org.apache.log4j.chainsaw.LogUI;
26
27
28
29
30
31
32
33
34
35
36
37
38
39 public class OSXIntegration {
40 public static final boolean IS_OSX = System.getProperty("os.name").startsWith("Mac OS X");
41 private static final Logger LOG = Logger.getLogger(OSXIntegration.class);
42 private static Object applicationInstance;
43 public static final void init(final LogUI logui) {
44 LOG.info("OSXIntegration.init() called");
45 if(!IS_OSX) {
46 LOG.info("Not OSX, ignoring...");
47 return;
48 }
49 try {
50 Class applicationClazz = Class.forName("com.apple.eawt.Application");
51 Class listenerClass = Class.forName("com.apple.eawt.ApplicationListener");
52 applicationInstance = applicationClazz.newInstance();
53
54
55 Method enablePreferenceMethod = applicationClazz.getMethod("setEnabledPreferencesMenu", new Class[] {boolean.class});
56 enablePreferenceMethod.invoke(applicationInstance, new Object[] {Boolean.TRUE});
57
58
59
60 Method enableAboutMethod = applicationClazz.getMethod("setEnabledAboutMenu", new Class[] {boolean.class});
61 enableAboutMethod.invoke(applicationInstance, new Object[] {Boolean.TRUE});
62
63
64 Object listenerProxy = Proxy.newProxyInstance(OSXIntegration.class.getClassLoader(),
65 new Class[] {listenerClass},
66 new InvocationHandler() {
67
68 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
69 if("handlePreferences".equals(method.getName())){
70 LOG.info("handlePreferences(...) called");
71 logui.showApplicationPreferences();
72 }else if("handleQuit".equals(method.getName())){
73 setHandled(args[0], logui.exit()?Boolean.TRUE:Boolean.FALSE);
74
75 }else if("handleAbout".equals(method.getName())) {
76 logui.showAboutBox();
77 setHandled(args[0], Boolean.TRUE);
78 }
79
80 return null;
81 }
82
83 private void setHandled(Object event, Boolean val) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
84 Method handleMethod = event.getClass().getMethod("setHandled", new Class[] {boolean.class});
85 handleMethod.invoke(event, new Object[] {val});
86 }});
87
88 Method registerListenerMethod = applicationClazz.getMethod("addApplicationListener", new Class[] {listenerClass});
89 registerListenerMethod.invoke(applicationInstance, new Object[] {listenerProxy});
90 } catch (Exception e) {
91 LOG.error("Failed to setup OSXIntegration", e);
92 }
93 }
94 }