You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Apple.java 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. * Copyright (c) 2006-2013 DMDirc Developers
  3. *
  4. * Permission is hereby granted, free of charge, to any person obtaining a copy
  5. * of this software and associated documentation files (the "Software"), to deal
  6. * in the Software without restriction, including without limitation the rights
  7. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. * copies of the Software, and to permit persons to whom the Software is
  9. * furnished to do so, subject to the following conditions:
  10. *
  11. * The above copyright notice and this permission notice shall be included in
  12. * all copies or substantial portions of the Software.
  13. *
  14. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. * SOFTWARE.
  21. */
  22. package com.dmdirc.addons.ui_swing;
  23. import com.dmdirc.actions.ActionManager;
  24. import com.dmdirc.actions.CoreActionType;
  25. import com.dmdirc.addons.ui_swing.components.menubar.MenuBar;
  26. import com.dmdirc.commandparser.commands.global.NewServer;
  27. import com.dmdirc.config.ConfigManager;
  28. import com.dmdirc.interfaces.ActionListener;
  29. import com.dmdirc.interfaces.actions.ActionType;
  30. import com.dmdirc.logger.ErrorLevel;
  31. import com.dmdirc.logger.Logger;
  32. import java.awt.Image;
  33. import java.awt.PopupMenu;
  34. import java.awt.event.ActionEvent;
  35. import java.lang.reflect.InvocationHandler;
  36. import java.lang.reflect.InvocationTargetException;
  37. import java.lang.reflect.Method;
  38. import java.lang.reflect.Proxy;
  39. import java.net.URI;
  40. import java.net.URISyntaxException;
  41. import java.util.ArrayList;
  42. import java.util.EventObject;
  43. import java.util.List;
  44. import javax.swing.JMenu;
  45. import javax.swing.JMenuBar;
  46. import javax.swing.JMenuItem;
  47. import javax.swing.UIManager;
  48. /**
  49. * Integrate DMDirc with OS X better.
  50. */
  51. public final class Apple implements InvocationHandler, ActionListener {
  52. /** Store any addresses that are opened before CLIENT_OPENED. */
  53. private final List<URI> addresses = new ArrayList<URI>();
  54. /** Config manager used to read settings. */
  55. private final ConfigManager configManager;
  56. /** The "Application" object used to do stuff on OS X. */
  57. private Object application;
  58. /** Are we listening? */
  59. private boolean isListener = false;
  60. /** The MenuBar for the application. */
  61. private MenuBar menuBar = null;
  62. /** Has the CLIENT_OPENED action been called? */
  63. private boolean clientOpened = false;
  64. /** Our swing controller. */
  65. private final SwingController controller;
  66. /**
  67. * Create the Apple class.
  68. * <p>
  69. * This attempts to:
  70. * </p>
  71. *
  72. * <ul>
  73. * <li>load the JNI library</li>
  74. * <li>register the callback</li>
  75. * <li>register a CLIENT_OPENED listener</li>
  76. * </ul>
  77. *
  78. * @param configManager Config manager
  79. */
  80. public Apple(final ConfigManager configManager, final SwingController controller) {
  81. this.configManager = configManager;
  82. this.controller = controller;
  83. if (isApple()) {
  84. try {
  85. System.loadLibrary("DMDirc-Apple"); // NOPMD
  86. registerOpenURLCallback();
  87. ActionManager.getActionManager().registerListener(this, CoreActionType.CLIENT_OPENED);
  88. } catch (UnsatisfiedLinkError ule) {
  89. Logger.appError(ErrorLevel.MEDIUM, "Unable to load JNI library.", ule);
  90. }
  91. }
  92. }
  93. /**
  94. * Register the getURL Callback.
  95. *
  96. * @return 0 on success, 1 on failure.
  97. */
  98. private synchronized native int registerOpenURLCallback();
  99. /**
  100. * Call a method on the given object.
  101. *
  102. * @param obj Object to call method on.
  103. * @oaram className Name of class that object really is.
  104. * @param methodName Method to call
  105. * @param classes Array of classes to pass when calling getMethod
  106. * @param objects Array of objects to pass when invoking.
  107. * @return Output from method.invoke()
  108. */
  109. private Object reflectMethod(final Object obj, final String className, final String methodName, final Class[] classes, final Object[] objects) {
  110. try {
  111. final Class<?> clazz = className == null ? obj.getClass() : Class.forName(className);
  112. final Method method = clazz.getMethod(methodName, classes == null ? new Class[0] : classes);
  113. return method.invoke(obj, objects == null ? new Object[0] : objects);
  114. } catch (IllegalArgumentException ex) {
  115. Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
  116. } catch (InvocationTargetException ex) {
  117. Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
  118. } catch (final ClassNotFoundException ex) {
  119. Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
  120. } catch (final NoSuchMethodException ex) {
  121. Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
  122. } catch (final IllegalAccessException ex) {
  123. Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
  124. }
  125. return null;
  126. }
  127. /**
  128. * Handle a method call to the apple Application class.
  129. *
  130. * @param methodName Method to call
  131. * @param classes Array of classes to pass when calling getMethod
  132. * @param objects Array of objects to pass when invoking.
  133. * @return Output from method.invoke()
  134. */
  135. private Object doAppleMethod(final String methodName, final Class[] classes, final Object[] objects) {
  136. if (!isApple()) { return null; }
  137. return reflectMethod(getApplication(), null, methodName, classes, objects);
  138. }
  139. /**
  140. * Get the "Application" object.
  141. *
  142. * @return Object that on OSX will be an "Application"
  143. */
  144. public Object getApplication() {
  145. synchronized (Apple.class) {
  146. if (isApple() && application == null) {
  147. application = reflectMethod(null, "com.apple.eawt.Application", "getApplication", null, null);
  148. }
  149. return application;
  150. }
  151. }
  152. /**
  153. * Are we on OS X?
  154. *
  155. * @return true if we are running on OS X
  156. */
  157. public static boolean isApple() {
  158. return (System.getProperty("mrj.version") != null);
  159. }
  160. /**
  161. * Are we using the OS X look and feel?
  162. *
  163. * @return true if we are using the OS X look and feel
  164. */
  165. public static boolean isAppleUI() {
  166. final String name = UIManager.getLookAndFeel().getClass().getName();
  167. return isApple() && (name.equals("apple.laf.AquaLookAndFeel") || name.equals("com.apple.laf.AquaLookAndFeel"));
  168. }
  169. /**
  170. * Set some OS X only UI settings.
  171. */
  172. public void setUISettings() {
  173. if (!isApple()) {
  174. return;
  175. }
  176. // Set some Apple OS X related stuff from http://tinyurl.com/6xwuld
  177. final String aaText = configManager.getOptionBool("ui", "antialias") ? "on" : "off";
  178. System.setProperty("apple.awt.antialiasing", aaText);
  179. System.setProperty("apple.awt.textantialiasing", aaText);
  180. System.setProperty("apple.awt.showGrowBox", "true");
  181. System.setProperty("com.apple.mrj.application.apple.menu.about.name", "DMDirc");
  182. System.setProperty("apple.laf.useScreenMenuBar", "true");
  183. System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
  184. System.setProperty("com.apple.mrj.application.live-resize", "true");
  185. }
  186. /**
  187. * Requests this application to move to the foreground.
  188. *
  189. * @param allWindows if all windows of this application should be moved to
  190. * the foreground, or only the foremost one
  191. */
  192. public void requestForeground(final boolean allWindows) {
  193. doAppleMethod("requestForeground", new Class[]{Boolean.TYPE}, new Object[]{allWindows});
  194. }
  195. /**
  196. * Requests user attention to this application (usually through bouncing
  197. * the Dock icon). Critical requests will continue to bounce the Dock icon
  198. * until the app is activated. An already active application requesting
  199. * attention does nothing.
  200. *
  201. * @param isCritical If this is false, the dock icon only bounces once,
  202. * otherwise it will bounce until clicked on.
  203. */
  204. public void requestUserAttention(final boolean isCritical) {
  205. doAppleMethod("requestUserAttention", new Class[]{Boolean.TYPE}, new Object[]{isCritical});
  206. }
  207. /**
  208. * Attaches the contents of the provided PopupMenu to the application's Dock icon.
  209. *
  210. * @param menu the PopupMenu to attach to this application's Dock icon
  211. */
  212. public void setDockMenu(final PopupMenu menu) {
  213. doAppleMethod("setDockMenu", new Class[]{PopupMenu.class}, new Object[]{menu});
  214. }
  215. /**
  216. * Get the PopupMenu attached to the application's Dock icon.
  217. *
  218. * @return the PopupMenu attached to this application's Dock icon
  219. */
  220. public PopupMenu getDockMenu() {
  221. final Object result = doAppleMethod("getDockMenu", null, null);
  222. return (result instanceof PopupMenu) ? (PopupMenu)result : null;
  223. }
  224. /**
  225. * Changes this application's Dock icon to the provided image.
  226. *
  227. * @param image The image to use
  228. */
  229. public void setDockIconImage(final Image image) {
  230. doAppleMethod("setDockIconImage", new Class[]{Image.class}, new Object[]{image});
  231. }
  232. /**
  233. * Obtains an image of this application's Dock icon.
  234. *
  235. * @return The application's dock icon.
  236. */
  237. public Image getDockIconImage() {
  238. final Object result = doAppleMethod("getDockIconImage", null, null);
  239. return (result instanceof Image) ? (Image)result : null;
  240. }
  241. /**
  242. * Affixes a small system provided badge to this application's Dock icon.
  243. * Usually a number.
  244. *
  245. * @param badge textual label to affix to the Dock icon
  246. */
  247. public void setDockIconBadge(final String badge) {
  248. doAppleMethod("setDockIconBadge", new Class[]{String.class}, new Object[]{badge});
  249. }
  250. /**
  251. * Sets the default menu bar to use when there are no active frames.
  252. * Only used when the system property "apple.laf.useScreenMenuBar" is
  253. * "true", and the Aqua Look and Feel is active.
  254. *
  255. * @param menuBar to use when no other frames are active
  256. */
  257. public void setDefaultMenuBar(final JMenuBar menuBar) {
  258. doAppleMethod("setDefaultMenuBar", new Class[]{JMenuBar.class}, new Object[]{menuBar});
  259. }
  260. /**
  261. * Add this application as a handler for the given event.
  262. *
  263. * @param handlerClass Class used as the handler.
  264. * @param handlerMethod Method used to set the handler.
  265. * @return True if we succeeded.
  266. */
  267. private boolean addHandler(final String handlerClass, final String handlerMethod) {
  268. try {
  269. final Class<?> listenerClass = Class.forName(handlerClass);
  270. final Object listener = Proxy.newProxyInstance(getClass().getClassLoader(), new Class[]{listenerClass}, this);
  271. final Method method = getApplication().getClass().getMethod(handlerMethod, new Class[]{listenerClass});
  272. method.invoke(getApplication(), listener);
  273. return true;
  274. } catch (final ClassNotFoundException ex) {
  275. return false;
  276. } catch (final NoSuchMethodException ex) {
  277. return false;
  278. } catch (final IllegalAccessException ex) {
  279. return false;
  280. } catch (final InvocationTargetException ex) {
  281. return false;
  282. }
  283. }
  284. /**
  285. * Set this up as a listener for the Apple Events.
  286. *
  287. * @return True if the listener was added, else false.
  288. */
  289. public boolean setListener() {
  290. if (!isApple() || isListener) {
  291. return false;
  292. }
  293. addHandler("com.apple.eawt.OpenURIHandler", "setOpenURIHandler");
  294. addHandler("com.apple.eawt.AboutHandler", "setAboutHandler");
  295. addHandler("com.apple.eawt.QuitHandler", "setQuitHandler");
  296. addHandler("com.apple.eawt.PreferencesHandler", "setPreferencesHandler");
  297. isListener = true;
  298. return true;
  299. }
  300. /**
  301. * {@inheritDoc}
  302. *
  303. * @throws Throwable Throws stuff on errors
  304. */
  305. @Override
  306. public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
  307. if (!isApple()) {
  308. return null;
  309. }
  310. try {
  311. final Class[] classes = new Class[args.length];
  312. for (int i = 0; i < args.length; i++) {
  313. if (EventObject.class.isInstance(args[i])) {
  314. classes[i] = EventObject.class;
  315. } else {
  316. final Class c = args[i].getClass();
  317. if (c.getCanonicalName().equals("com.apple.eawt.QuitResponse")) {
  318. classes[i] = Object.class;
  319. } else {
  320. classes[i] = c;
  321. }
  322. }
  323. }
  324. final Method thisMethod = this.getClass().getMethod(method.getName(), classes);
  325. return thisMethod.invoke(this, args);
  326. } catch (final NoSuchMethodException e) {
  327. if (method.getName().equals("equals") && args.length == 1) {
  328. return Boolean.valueOf(proxy == args[0]);
  329. }
  330. }
  331. return null;
  332. }
  333. /**
  334. * Set the MenuBar.
  335. * This will unset all menu mnemonics aswell if on the OSX ui.
  336. *
  337. * @param newMenuBar MenuBar to use to send events to,
  338. */
  339. public void setMenuBar(final MenuBar newMenuBar) {
  340. menuBar = newMenuBar;
  341. if (!isAppleUI()) {
  342. return;
  343. }
  344. for (int i = 0; i < menuBar.getMenuCount(); i++) {
  345. final JMenu menu = menuBar.getMenu(i);
  346. if (menu == null) {
  347. continue;
  348. }
  349. menu.setMnemonic(0);
  350. for (int j = 0; j < menu.getItemCount(); j++) {
  351. final JMenuItem menuItem = menu.getItem(j);
  352. if (menuItem != null) {
  353. menuItem.setMnemonic(0);
  354. }
  355. }
  356. }
  357. }
  358. /**
  359. * Handle an event using the menuBar.
  360. *
  361. * @param name The name of the event according to the menubar
  362. */
  363. public void handleMenuBarEvent(final String name) {
  364. if (!isApple() || menuBar == null) {
  365. return;
  366. }
  367. final ActionEvent actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, name);
  368. for (int i = 0; i < menuBar.getMenuCount(); i++) {
  369. final JMenu menu = menuBar.getMenu(i);
  370. if (menu instanceof java.awt.event.ActionListener) {
  371. ((java.awt.event.ActionListener)menu).actionPerformed(actionEvent);
  372. }
  373. }
  374. }
  375. /**
  376. * This is called when About is selected from the Application menu.
  377. *
  378. * @param event an ApplicationEvent object
  379. */
  380. public void handleAbout(final EventObject event) {
  381. handleMenuBarEvent("About");
  382. }
  383. /**
  384. * This is called when Preferences is selected from the Application menu.
  385. *
  386. * @param event an ApplicationEvent object
  387. */
  388. public void handlePreferences(final EventObject event) {
  389. handleMenuBarEvent("Preferences");
  390. }
  391. /** {@inheritDoc} */
  392. @Override
  393. public void processEvent(final ActionType type, final StringBuffer format, final Object... arguments) {
  394. if (type == CoreActionType.CLIENT_OPENED) {
  395. synchronized (addresses) {
  396. clientOpened = true;
  397. for (final URI addr : addresses) {
  398. controller.getMain().getServerManager().connectToAddress(addr);
  399. }
  400. addresses.clear();
  401. }
  402. }
  403. }
  404. /**
  405. * This is called when Quit is selected from the Application menu.
  406. *
  407. * @param event an ApplicationEvent object
  408. * @param quitResponse QuitResponse object.
  409. */
  410. public void handleQuitRequestWith(final EventObject event, final Object quitResponse) {
  411. // Technically we should tell OS X if the quit succeeds or not, but we
  412. // have no way of knowing the result just yet.
  413. //
  414. // So instead we will just tell it that the quit was cancelled every
  415. // time, and then just quit anyway if we need to.
  416. reflectMethod(quitResponse, null, "cancelQuit", null, null);
  417. handleMenuBarEvent("Exit");
  418. }
  419. /**
  420. * Callback from our JNI library.
  421. * This should work when not launcher via JavaApplicationStub
  422. *
  423. * @param url The irc url string to connect to.
  424. */
  425. public void handleOpenURL(final String url) {
  426. try {
  427. final URI addr = NewServer.getURI(url);
  428. handleURI(addr);
  429. } catch (final URISyntaxException use) { }
  430. }
  431. /**
  432. * Callback from OSX Directly.
  433. * This will work if we were launched using the JavaApplicationStub
  434. *
  435. * @param event Event related to this callback. This event will have a
  436. * reflectable getURI method to get a URI.
  437. */
  438. public void openURI(final EventObject event) {
  439. if (!isApple()) {
  440. return;
  441. }
  442. final Object obj = reflectMethod(event, null, "getURI", null, null);
  443. if (obj instanceof URI) {
  444. final URI uri = (URI)obj;
  445. handleURI(uri);
  446. }
  447. }
  448. /**
  449. * Handle connecting to a URI.
  450. *
  451. * If called before the client has finished opening, the URI will be added
  452. * to a list that will be connected to once the CLIENT_OPENED action is
  453. * called. Otherwise we connect right away.
  454. *
  455. * @param uri URI to connect to.
  456. */
  457. private void handleURI(final URI uri) {
  458. synchronized (addresses) {
  459. if (clientOpened) {
  460. // When the JNI callback is called there is no
  461. // ContextClassLoader set, which causes an NPE in
  462. // IconManager if no servers have been connected to yet.
  463. if (Thread.currentThread().getContextClassLoader() == null) {
  464. Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
  465. }
  466. controller.getMain().getServerManager().connectToAddress(uri);
  467. } else {
  468. addresses.add(uri);
  469. }
  470. }
  471. }
  472. }