Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

Apple.java 18KB

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