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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. /*
  2. * Copyright (c) 2006-2014 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.ServerManager;
  24. import com.dmdirc.addons.ui_swing.components.menubar.MenuBar;
  25. import com.dmdirc.events.ClientOpenedEvent;
  26. import com.dmdirc.interfaces.config.AggregateConfigProvider;
  27. import com.dmdirc.logger.ErrorLevel;
  28. import com.dmdirc.logger.Logger;
  29. import com.dmdirc.util.InvalidURIException;
  30. import com.dmdirc.util.URIParser;
  31. import com.google.common.eventbus.EventBus;
  32. import com.google.common.eventbus.Subscribe;
  33. import java.awt.Image;
  34. import java.awt.PopupMenu;
  35. import java.awt.event.ActionEvent;
  36. import java.lang.reflect.InvocationHandler;
  37. import java.lang.reflect.InvocationTargetException;
  38. import java.lang.reflect.Method;
  39. import java.lang.reflect.Proxy;
  40. import java.net.URI;
  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 class Apple implements InvocationHandler {
  52. /** Store any addresses that are opened before CLIENT_OPENED. */
  53. private final List<URI> addresses = new ArrayList<>();
  54. /** Config manager used to read settings. */
  55. private final AggregateConfigProvider configManager;
  56. /** The "Application" object used to do stuff on OS X. */
  57. private Object application;
  58. /** Whether we're listening or not. */
  59. private boolean isListener = false;
  60. /** The MenuBar for the application. */
  61. private MenuBar menuBar = null;
  62. /** Whether the CLIENT_OPENED action has been called or not. */
  63. private boolean clientOpened = false;
  64. /** The server manager to use to connect to URLs. */
  65. private final ServerManager serverManager;
  66. /**
  67. * Creates a new instance of {@link Apple}.
  68. *
  69. * <p>
  70. * This will attempt to load the native library and register the URL open callback.
  71. *
  72. * @param configManager Config manager
  73. * @param serverManager The server manager to use to connect to URLs.
  74. * @param eventBus The bus to listen for events on.
  75. */
  76. public Apple(
  77. final AggregateConfigProvider configManager,
  78. final ServerManager serverManager,
  79. final EventBus eventBus) {
  80. this.configManager = configManager;
  81. this.serverManager = serverManager;
  82. if (isApple()) {
  83. try {
  84. System.loadLibrary("DMDirc-Apple"); // NOPMD
  85. registerOpenURLCallback();
  86. eventBus.register(this);
  87. } catch (UnsatisfiedLinkError ule) {
  88. Logger.appError(ErrorLevel.MEDIUM, "Unable to load JNI library.", ule);
  89. }
  90. }
  91. }
  92. /**
  93. * Register the getURL Callback.
  94. *
  95. * @return 0 on success, 1 on failure.
  96. */
  97. private synchronized native int registerOpenURLCallback();
  98. /**
  99. * Call a method on the given object.
  100. *
  101. * @param obj Object to call method on.
  102. * @param className Name of class that object really is.
  103. * @param methodName Method to call
  104. * @param classes Array of classes to pass when calling getMethod
  105. * @param objects Array of objects to pass when invoking.
  106. *
  107. * @return Output from method.invoke()
  108. */
  109. private Object reflectMethod(final Object obj, final String className, final String methodName,
  110. final Class[] classes, final Object[] objects) {
  111. try {
  112. final Class<?> clazz = className == null ? obj.getClass() : Class.forName(className);
  113. final Method method = clazz.getMethod(methodName, classes == null ? new Class<?>[0]
  114. : classes);
  115. return method.invoke(obj, objects == null ? new Object[0] : objects);
  116. } catch (ReflectiveOperationException ex) {
  117. Logger.userError(ErrorLevel.LOW, "Unable to find OS X classes");
  118. }
  119. return null;
  120. }
  121. /**
  122. * Handle a method call to the apple Application class.
  123. *
  124. * @param methodName Method to call
  125. * @param classes Array of classes to pass when calling getMethod
  126. * @param objects Array of objects to pass when invoking.
  127. *
  128. * @return Output from method.invoke()
  129. */
  130. private Object doAppleMethod(final String methodName, final Class[] classes,
  131. final Object[] objects) {
  132. if (!isApple()) {
  133. return null;
  134. }
  135. return reflectMethod(getApplication(), null, methodName, classes, objects);
  136. }
  137. /**
  138. * Get the "Application" object.
  139. *
  140. * @return Object that on OSX will be an "Application"
  141. */
  142. public Object getApplication() {
  143. synchronized (Apple.class) {
  144. if (isApple() && application == null) {
  145. application = reflectMethod(null, "com.apple.eawt.Application", "getApplication",
  146. null, null);
  147. }
  148. return application;
  149. }
  150. }
  151. /**
  152. * Are we on OS X?
  153. *
  154. * @return true if we are running on OS X
  155. */
  156. public static boolean isApple() {
  157. return System.getProperty("os.name").contains("OS X");
  158. }
  159. /**
  160. * Are we using the OS X look and feel?
  161. *
  162. * @return true if we are using the OS X look and feel
  163. */
  164. public static boolean isAppleUI() {
  165. final String name = UIManager.getLookAndFeel().getClass().getName();
  166. return isApple() && (name.equals("apple.laf.AquaLookAndFeel") || name.equals(
  167. "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 the foreground, or
  190. * 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 the Dock icon).
  197. * Critical requests will continue to bounce the Dock icon until the app is activated. An
  198. * already active application requesting attention does nothing.
  199. *
  200. * @param isCritical If this is false, the dock icon only bounces once, otherwise it will bounce
  201. * until clicked on.
  202. */
  203. public void requestUserAttention(final boolean isCritical) {
  204. doAppleMethod("requestUserAttention", new Class<?>[]{Boolean.TYPE}, new Object[]{isCritical});
  205. }
  206. /**
  207. * Attaches the contents of the provided PopupMenu to the application's Dock icon.
  208. *
  209. * @param menu the PopupMenu to attach to this application's Dock icon
  210. */
  211. public void setDockMenu(final PopupMenu menu) {
  212. doAppleMethod("setDockMenu", new Class<?>[]{PopupMenu.class}, new Object[]{menu});
  213. }
  214. /**
  215. * Get the PopupMenu attached to the application's Dock icon.
  216. *
  217. * @return the PopupMenu attached to this application's Dock icon
  218. */
  219. public PopupMenu getDockMenu() {
  220. final Object result = doAppleMethod("getDockMenu", null, null);
  221. return (result instanceof PopupMenu) ? (PopupMenu) result : null;
  222. }
  223. /**
  224. * Changes this application's Dock icon to the provided image.
  225. *
  226. * @param image The image to use
  227. */
  228. public void setDockIconImage(final Image image) {
  229. doAppleMethod("setDockIconImage", new Class<?>[]{Image.class}, new Object[]{image});
  230. }
  231. /**
  232. * Obtains an image of this application's Dock icon.
  233. *
  234. * @return The application's dock icon.
  235. */
  236. public Image getDockIconImage() {
  237. final Object result = doAppleMethod("getDockIconImage", null, null);
  238. return (result instanceof Image) ? (Image) result : null;
  239. }
  240. /**
  241. * Affixes a small system provided badge to this application's Dock icon. Usually a number.
  242. *
  243. * @param badge textual label to affix to the Dock icon
  244. */
  245. public void setDockIconBadge(final String badge) {
  246. doAppleMethod("setDockIconBadge", new Class<?>[]{String.class}, new Object[]{badge});
  247. }
  248. /**
  249. * Sets the default menu bar to use when there are no active frames. Only used when the system
  250. * property "apple.laf.useScreenMenuBar" is "true", and the Aqua Look and Feel is active.
  251. *
  252. * @param menuBar to use when no other frames are active
  253. */
  254. public void setDefaultMenuBar(final JMenuBar menuBar) {
  255. doAppleMethod("setDefaultMenuBar", new Class<?>[]{JMenuBar.class}, new Object[]{menuBar});
  256. }
  257. /**
  258. * Add this application as a handler for the given event.
  259. *
  260. * @param handlerClass Class used as the handler.
  261. * @param handlerMethod Method used to set the handler.
  262. *
  263. * @return True if we succeeded.
  264. */
  265. private boolean addHandler(final String handlerClass, final String handlerMethod) {
  266. try {
  267. final Class<?> listenerClass = Class.forName(handlerClass);
  268. final Object listener = Proxy.newProxyInstance(getClass().getClassLoader(),
  269. new Class<?>[]{listenerClass}, this);
  270. final Method method = getApplication().getClass().getMethod(handlerMethod,
  271. new Class<?>[]{listenerClass});
  272. method.invoke(getApplication(), listener);
  273. return true;
  274. } catch (ClassNotFoundException | NoSuchMethodException |
  275. IllegalAccessException | InvocationTargetException ex) {
  276. return false;
  277. }
  278. }
  279. /**
  280. * Set this up as a listener for the Apple Events.
  281. *
  282. * @return True if the listener was added, else false.
  283. */
  284. public boolean setListener() {
  285. if (!isApple() || isListener) {
  286. return false;
  287. }
  288. addHandler("com.apple.eawt.OpenURIHandler", "setOpenURIHandler");
  289. addHandler("com.apple.eawt.AboutHandler", "setAboutHandler");
  290. addHandler("com.apple.eawt.QuitHandler", "setQuitHandler");
  291. addHandler("com.apple.eawt.PreferencesHandler", "setPreferencesHandler");
  292. isListener = true;
  293. return true;
  294. }
  295. /**
  296. * {@inheritDoc}
  297. *
  298. * @throws ReflectiveOperationException if attempting to invoke the method fails.
  299. */
  300. @Override
  301. public Object invoke(final Object proxy, final Method method, final Object[] args)
  302. throws ReflectiveOperationException {
  303. if (!isApple()) {
  304. return null;
  305. }
  306. try {
  307. final Class<?>[] classes = new Class<?>[args.length];
  308. for (int i = 0; i < args.length; i++) {
  309. if (EventObject.class.isInstance(args[i])) {
  310. classes[i] = EventObject.class;
  311. } else {
  312. final Class<?> c = args[i].getClass();
  313. if (c.getCanonicalName().equals("com.apple.eawt.QuitResponse")) {
  314. classes[i] = Object.class;
  315. } else {
  316. classes[i] = c;
  317. }
  318. }
  319. }
  320. final Method thisMethod = this.getClass().getMethod(method.getName(), classes);
  321. return thisMethod.invoke(this, args);
  322. } catch (final NoSuchMethodException e) {
  323. if (method.getName().equals("equals") && args.length == 1) {
  324. return proxy == args[0];
  325. }
  326. }
  327. return null;
  328. }
  329. /**
  330. * Set the MenuBar. This will unset all menu mnemonics aswell if on the OSX ui.
  331. *
  332. * @param newMenuBar MenuBar to use to send events to,
  333. */
  334. public void setMenuBar(final MenuBar newMenuBar) {
  335. menuBar = newMenuBar;
  336. if (!isAppleUI()) {
  337. return;
  338. }
  339. for (int i = 0; i < menuBar.getMenuCount(); i++) {
  340. final JMenu menu = menuBar.getMenu(i);
  341. if (menu == null) {
  342. continue;
  343. }
  344. menu.setMnemonic(0);
  345. for (int j = 0; j < menu.getItemCount(); j++) {
  346. final JMenuItem menuItem = menu.getItem(j);
  347. if (menuItem != null) {
  348. menuItem.setMnemonic(0);
  349. }
  350. }
  351. }
  352. }
  353. /**
  354. * Handle an event using the menuBar.
  355. *
  356. * @param name The name of the event according to the menubar
  357. */
  358. public void handleMenuBarEvent(final String name) {
  359. if (!isApple() || menuBar == null) {
  360. return;
  361. }
  362. final ActionEvent actionEvent = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, name);
  363. for (int i = 0; i < menuBar.getMenuCount(); i++) {
  364. final JMenu menu = menuBar.getMenu(i);
  365. if (menu instanceof java.awt.event.ActionListener) {
  366. ((java.awt.event.ActionListener) menu).actionPerformed(actionEvent);
  367. }
  368. }
  369. }
  370. /**
  371. * This is called when About is selected from the Application menu.
  372. *
  373. * @param event an ApplicationEvent object
  374. */
  375. public void handleAbout(final EventObject event) {
  376. handleMenuBarEvent("About");
  377. }
  378. /**
  379. * This is called when Preferences is selected from the Application menu.
  380. *
  381. * @param event an ApplicationEvent object
  382. */
  383. public void handlePreferences(final EventObject event) {
  384. handleMenuBarEvent("Preferences");
  385. }
  386. /**
  387. * Called when the client is opened for the first time.
  388. *
  389. * @param event The event describing the client opening.
  390. */
  391. @Subscribe
  392. public void handleClientOpened(final ClientOpenedEvent event) {
  393. synchronized (addresses) {
  394. clientOpened = true;
  395. for (final URI addr : addresses) {
  396. serverManager.connectToAddress(addr);
  397. }
  398. addresses.clear();
  399. }
  400. }
  401. /**
  402. * This is called when Quit is selected from the Application menu.
  403. *
  404. * @param event an ApplicationEvent object
  405. * @param quitResponse QuitResponse object.
  406. */
  407. public void handleQuitRequestWith(final EventObject event, final Object quitResponse) {
  408. // Technically we should tell OS X if the quit succeeds or not, but we
  409. // have no way of knowing the result just yet.
  410. //
  411. // So instead we will just tell it that the quit was cancelled every
  412. // time, and then just quit anyway if we need to.
  413. reflectMethod(quitResponse, null, "cancelQuit", null, null);
  414. handleMenuBarEvent("Exit");
  415. }
  416. /**
  417. * Callback from our JNI library. This should work when not launcher via JavaApplicationStub
  418. *
  419. * @param url The irc url string to connect to.
  420. */
  421. public void handleOpenURL(final String url) {
  422. try {
  423. handleURI(new URIParser().parseFromText(url));
  424. } catch (final InvalidURIException ex) {
  425. // Do nothing?...
  426. }
  427. }
  428. /**
  429. * Callback from OSX Directly. This will work if we were launched using the JavaApplicationStub
  430. *
  431. * @param event Event related to this callback. This event will have a reflectable getURI method
  432. * to get a URI.
  433. */
  434. public void openURI(final EventObject event) {
  435. if (!isApple()) {
  436. return;
  437. }
  438. final Object obj = reflectMethod(event, null, "getURI", null, null);
  439. if (obj instanceof URI) {
  440. handleURI((URI) obj);
  441. }
  442. }
  443. /**
  444. * Handle connecting to a URI.
  445. *
  446. * If called before the client has finished opening, the URI will be added to a list that will
  447. * be connected to once the CLIENT_OPENED action is called. Otherwise we connect right away.
  448. *
  449. * @param uri URI to connect to.
  450. */
  451. private void handleURI(final URI uri) {
  452. synchronized (addresses) {
  453. if (clientOpened) {
  454. // When the JNI callback is called there is no
  455. // ContextClassLoader set, which causes an NPE in
  456. // IconManager if no servers have been connected to yet.
  457. if (Thread.currentThread().getContextClassLoader() == null) {
  458. Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
  459. }
  460. serverManager.connectToAddress(uri);
  461. } else {
  462. addresses.add(uri);
  463. }
  464. }
  465. }
  466. }