summaryrefslogtreecommitdiffstats
path: root/depends/launcher/org/simplericity/macify/eawt/DefaultApplication.java
blob: 5752a3505f989402049804ae1dc5272193f28f92 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package org.simplericity.macify.eawt;

/*
 * Copyright 2007 Eirik Bjorsnos.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.*;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.MalformedURLException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


/**
 * Implements Application by calling the Mac OS X API through reflection.
 * If this class is used on a non-OS X platform the operations will have no effect or they will simulate
 * what the Apple API would do for those who manipulate state. ({@link #setEnabledAboutMenu(boolean)} etc.)
 */
@SuppressWarnings("unchecked")
public class DefaultApplication implements Application {

    private Object application;
    private Class applicationListenerClass;

    Map listenerMap = Collections.synchronizedMap(new HashMap<Object, Object>());
    private boolean enabledAboutMenu = true;
    private boolean enabledPreferencesMenu;
    private boolean aboutMenuItemPresent = true;
    private boolean preferencesMenuItemPresent;
    private ClassLoader classLoader;

    public DefaultApplication() {
        try {
            final File file = new File("/System/Library/Java");
            if (file.exists()) {
                ClassLoader scl = ClassLoader.getSystemClassLoader();
                Class clc = scl.getClass();
                if (URLClassLoader.class.isAssignableFrom(clc)) {
                    Method addUrl = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
                    addUrl.setAccessible(true);
                    addUrl.invoke(scl, new Object[]{file.toURI().toURL()});
                }
            }

            Class appClass = Class.forName("com.apple.eawt.Application");
            application = appClass.getMethod("getApplication", new Class[0]).invoke(null, new Object[0]);
            applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener");
        } catch (ClassNotFoundException e) {
            application = null;
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }

    }

    public boolean isMac() {
        return application != null;
    }

    public void addAboutMenuItem() {
        if (isMac()) {
            callMethod(application, "addAboutMenuItem");
        } else {
            this.aboutMenuItemPresent = true;
        }
    }

    public void addApplicationListener(ApplicationListener applicationListener) {

        if (!Modifier.isPublic(applicationListener.getClass().getModifiers())) {
            throw new IllegalArgumentException("ApplicationListener must be a public class");
        }
        if (isMac()) {
            Object listener = Proxy.newProxyInstance(getClass().getClassLoader(),
                    new Class[]{applicationListenerClass},
                    new ApplicationListenerInvocationHandler(applicationListener));

            callMethod(application, "addApplicationListener", new Class[]{applicationListenerClass}, new Object[]{listener});
            listenerMap.put(applicationListener, listener);
        } else {
            listenerMap.put(applicationListener, applicationListener);
        }
    }

    public void addPreferencesMenuItem() {
        if (isMac()) {
            callMethod("addPreferencesMenuItem");
        } else {
            this.preferencesMenuItemPresent = true;
        }
    }

    public boolean getEnabledAboutMenu() {
        if (isMac()) {
            return callMethod("getEnabledAboutMenu").equals(Boolean.TRUE);
        } else {
            return enabledAboutMenu;
        }
    }

    public boolean getEnabledPreferencesMenu() {
        if (isMac()) {
            Object result = callMethod("getEnabledPreferencesMenu");
            return result.equals(Boolean.TRUE);
        } else {
            return enabledPreferencesMenu;
        }
    }

    public Point getMouseLocationOnScreen() {
        if (isMac()) {
            try {
                Method method = application.getClass().getMethod("getMouseLocationOnScreen", new Class[0]);
                return (Point) method.invoke(null, new Object[0]);
            } catch (NoSuchMethodException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            } catch (InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        } else {
            return new Point(0, 0);
        }
    }

    public boolean isAboutMenuItemPresent() {
        if (isMac()) {
            return callMethod("isAboutMenuItemPresent").equals(Boolean.TRUE);
        } else {
            return aboutMenuItemPresent;
        }
    }

    public boolean isPreferencesMenuItemPresent() {
        if (isMac()) {
            return callMethod("isPreferencesMenuItemPresent").equals(Boolean.TRUE);
        } else {
            return this.preferencesMenuItemPresent;
        }
    }

    public void removeAboutMenuItem() {
        if (isMac()) {
            callMethod("removeAboutMenuItem");
        } else {
            this.aboutMenuItemPresent = false;
        }
    }

    public synchronized void removeApplicationListener(ApplicationListener applicationListener) {
        if (isMac()) {
            Object listener = listenerMap.get(applicationListener);
            callMethod(application, "removeApplicationListener", new Class[]{applicationListenerClass}, new Object[]{listener});

        }
        listenerMap.remove(applicationListener);
    }

    public void removePreferencesMenuItem() {
        if (isMac()) {
            callMethod("removeAboutMenuItem");
        } else {
            this.preferencesMenuItemPresent = false;
        }
    }

    public void setEnabledAboutMenu(boolean enabled) {
        if (isMac()) {
            callMethod(application, "setEnabledAboutMenu", new Class[]{Boolean.TYPE}, new Object[]{Boolean.valueOf(enabled)});
        } else {
            this.enabledAboutMenu = enabled;
        }
    }

    public void setEnabledPreferencesMenu(boolean enabled) {
        if (isMac()) {
            callMethod(application, "setEnabledPreferencesMenu", new Class[]{Boolean.TYPE}, new Object[]{Boolean.valueOf(enabled)});
        } else {
            this.enabledPreferencesMenu = enabled;
        }

    }

    public int requestUserAttention(int type) {
        if (type != REQUEST_USER_ATTENTION_TYPE_CRITICAL && type != REQUEST_USER_ATTENTION_TYPE_INFORMATIONAL) {
            throw new IllegalArgumentException("Requested user attention type is not allowed: " + type);
        }
        try {
            Object application = getNSApplication();
            Field critical = application.getClass().getField("UserAttentionRequestCritical");
            Field informational = application.getClass().getField("UserAttentionRequestInformational");
            Field actual = type == REQUEST_USER_ATTENTION_TYPE_CRITICAL ? critical : informational;

            return ((Integer) application.getClass().getMethod("requestUserAttention", new Class[]{Integer.TYPE}).invoke(application, new Object[]{actual.get(null)})).intValue();

        } catch (ClassNotFoundException e) {
            return -1;
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        }
    }

    public void cancelUserAttentionRequest(int request) {
        try {
            Object application = getNSApplication();
            application.getClass().getMethod("cancelUserAttentionRequest", new Class[]{Integer.TYPE}).invoke(application, new Object[]{new Integer(request)});
        } catch (ClassNotFoundException e) {
            // Nada
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    private Object getNSApplication() throws ClassNotFoundException {
        try {
            Class applicationClass = Class.forName("com.apple.cocoa.application.NSApplication");
            return applicationClass.getMethod("sharedApplication", new Class[0]).invoke(null, new Object[0]);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }

    public void setApplicationIconImage(BufferedImage image) {
        if (isMac()) {
            try {
                Method setDockIconImage = application.getClass().getMethod("setDockIconImage", Image.class);

                try {
                    setDockIconImage.invoke(application, image);
                } catch (IllegalAccessException e) {

                } catch (InvocationTargetException e) {

                }
            } catch (NoSuchMethodException mnfe) {


                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                try {
                    ImageIO.write(image, "png", stream);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }

                try {
                    Class nsDataClass = Class.forName("com.apple.cocoa.foundation.NSData");
                    Constructor constructor = nsDataClass.getConstructor(new Class[]{new byte[0].getClass()});

                    Object nsData = constructor.newInstance(new Object[]{stream.toByteArray()});

                    Class nsImageClass = Class.forName("com.apple.cocoa.application.NSImage");
                    Object nsImage = nsImageClass.getConstructor(new Class[]{nsDataClass}).newInstance(new Object[]{nsData});

                    Object application = getNSApplication();

                    application.getClass().getMethod("setApplicationIconImage", new Class[]{nsImageClass}).invoke(application, new Object[]{nsImage});

                } catch (ClassNotFoundException e) {

                } catch (NoSuchMethodException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                } catch (InstantiationException e) {
                    throw new RuntimeException(e);
                }

            }

        }
    }

    public BufferedImage getApplicationIconImage() {
        if (isMac()) {

            try {
                Method getDockIconImage = application.getClass().getMethod("getDockIconImage");
                try {
                    return (BufferedImage) getDockIconImage.invoke(application);
                } catch (IllegalAccessException e) {

                } catch (InvocationTargetException e) {

                }
            } catch (NoSuchMethodException nsme) {

                try {
                    Class nsDataClass = Class.forName("com.apple.cocoa.foundation.NSData");
                    Class nsImageClass = Class.forName("com.apple.cocoa.application.NSImage");
                    Object application = getNSApplication();
                    Object nsImage = application.getClass().getMethod("applicationIconImage", new Class[0]).invoke(application, new Object[0]);

                    Object nsData = nsImageClass.getMethod("TIFFRepresentation", new Class[0]).invoke(nsImage, new Object[0]);

                    Integer length = (Integer) nsDataClass.getMethod("length", new Class[0]).invoke(nsData, new Object[0]);
                    byte[] bytes = (byte[]) nsDataClass.getMethod("bytes", new Class[]{Integer.TYPE, Integer.TYPE}).invoke(nsData, new Object[]{Integer.valueOf(0), length});

                    BufferedImage image = ImageIO.read(new ByteArrayInputStream(bytes));
                    return image;

                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    throw new RuntimeException(e);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }

        return null;
    }

    private Object callMethod(String methodname) {
        return callMethod(application, methodname, new Class[0], new Object[0]);
    }

    private Object callMethod(Object object, String methodname) {
        return callMethod(object, methodname, new Class[0], new Object[0]);
    }

    private Object callMethod(Object object, String methodname, Class[] classes, Object[] arguments) {
        try {
            if (classes == null) {
                classes = new Class[arguments.length];
                for (int i = 0; i < classes.length; i++) {
                    classes[i] = arguments[i].getClass();

                }
            }
            Method addListnerMethod = object.getClass().getMethod(methodname, classes);
            return addListnerMethod.invoke(object, arguments);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }

    class ApplicationListenerInvocationHandler implements InvocationHandler {
        private ApplicationListener applicationListener;

        ApplicationListenerInvocationHandler(ApplicationListener applicationListener) {
            this.applicationListener = applicationListener;
        }

        public Object invoke(Object object, Method appleMethod, Object[] objects) throws Throwable {

            ApplicationEvent event = createApplicationEvent(objects[0]);
            try {
                Method method = applicationListener.getClass().getMethod(appleMethod.getName(), new Class[]{ApplicationEvent.class});
                return method.invoke(applicationListener, new Object[]{event});
            } catch (NoSuchMethodException e) {
                if (appleMethod.getName().equals("equals") && objects.length == 1) {
                    return Boolean.valueOf(object == objects[0]);
                }
                return null;
            }
        }
    }

    private ApplicationEvent createApplicationEvent(final Object appleApplicationEvent) {
        return (ApplicationEvent) Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{ApplicationEvent.class}, new InvocationHandler() {
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                return appleApplicationEvent.getClass().getMethod(method.getName(), method.getParameterTypes()).invoke(appleApplicationEvent, objects);
            }
        });
    }
}