Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

Apple.java 18KB

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