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 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /*
  2. * Copyright (c) 2006-2010 Chris Smith, Shane Mc Cormack, Gregory Holmes
  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;
  25. import com.dmdirc.actions.ActionManager;
  26. import com.dmdirc.actions.CoreActionType;
  27. import com.dmdirc.actions.interfaces.ActionType;
  28. import com.dmdirc.commandparser.commands.global.NewServer;
  29. import com.dmdirc.config.IdentityManager;
  30. import com.dmdirc.interfaces.ActionListener;
  31. import com.dmdirc.logger.ErrorLevel;
  32. import com.dmdirc.logger.Logger;
  33. import java.awt.event.ActionEvent;
  34. import java.lang.reflect.InvocationHandler;
  35. import java.lang.reflect.Method;
  36. import java.lang.reflect.Field;
  37. import java.lang.reflect.Proxy;
  38. import java.lang.reflect.InvocationTargetException;
  39. import java.net.URI;
  40. import java.net.URISyntaxException;
  41. import javax.swing.UIManager;
  42. import javax.swing.JMenu;
  43. import javax.swing.JMenuItem;
  44. import java.util.ArrayList;
  45. /**
  46. * Integrate DMDirc with OS X better.
  47. */
  48. public final class Apple implements InvocationHandler, ActionListener {
  49. /**
  50. * Dummy interface for ApplicationEvent from the Apple UI on non-Apple platforms.
  51. * http://developer.apple.com/documentation/Java/Reference/1.5.0/appledoc/api/com/apple/eawt/ApplicationEvent.html
  52. */
  53. public interface ApplicationEvent {
  54. /**
  55. * Provides the filename associated with a particular AppleEvent.
  56. *
  57. * @return The filename associated with a particular AppleEvent.
  58. */
  59. String getFilename();
  60. /**
  61. * Whether or not this event is handled.
  62. *
  63. * @return True if the event is handled, false otherwise
  64. */
  65. boolean isHandled();
  66. /**
  67. * Sets the handled state of this event.
  68. *
  69. * @param handled The new 'handled' state for this event.
  70. */
  71. void setHandled(boolean handled);
  72. /**
  73. * Retrieves the source of this event.
  74. *
  75. * @return This event's source
  76. */
  77. Object getSource();
  78. /**
  79. * Get a string representation of this object.
  80. *
  81. * @return A string representation of this object.
  82. */
  83. @Override
  84. String toString();
  85. }
  86. /** The singleton instance of Apple. */
  87. private static Apple me;
  88. /** The "Application" object used to do stuff on OS X. */
  89. private static Object application;
  90. /** The "NSApplication" object used to do cocoa stuff on OS X. */
  91. private static Object nsApplication;
  92. /** Are we listening? */
  93. private boolean isListener = false;
  94. /** The MenuBar for the application. */
  95. private MenuBar menuBar = null;
  96. /** Has the CLIENT_OPENED action been called? */
  97. private volatile boolean clientOpened = false;
  98. /** Store any addresses that are opened before CLIENT_OPENED. */
  99. private final ArrayList<URI> addresses = new ArrayList<URI>();
  100. /**
  101. * Get the "Apple" instance.
  102. *
  103. * @return Apple instance.
  104. */
  105. public static Apple getApple() {
  106. if (me == null) {
  107. me = new Apple();
  108. }
  109. return me;
  110. }
  111. /**
  112. * Create the Apple class.
  113. * <p>This attempts to:</p>
  114. *
  115. * <ul>
  116. * <li>load the JNI library</li>
  117. * <li>register the callback</li>
  118. * <li>register a CLIENT_OPENED listener</li>
  119. * </ul>
  120. */
  121. private Apple() {
  122. if (isApple()) {
  123. try {
  124. System.loadLibrary("DMDirc-Apple");
  125. registerOpenURLCallback();
  126. ActionManager.addListener(this, CoreActionType.CLIENT_OPENED);
  127. } catch (UnsatisfiedLinkError ule) {
  128. Logger.userError(ErrorLevel.MEDIUM,
  129. "Unable to load JNI library.", ule);
  130. }
  131. }
  132. }
  133. /**
  134. * Get the "Application" object
  135. *
  136. * @return Object that on OSX will be an "Application"
  137. */
  138. public static Object getApplication() {
  139. if (application == null && isApple()) {
  140. try {
  141. final Class<?> app = Class.forName("com.apple.eawt.Application");
  142. final Method method = app.getMethod("getApplication",
  143. new Class[0]);
  144. application = method.invoke(null, new Object[0]);
  145. } catch (ClassNotFoundException ex) { // Probably not on OS X, do nothing.
  146. } catch (NoSuchMethodException ex) { // Probably not on OS X, do nothing.
  147. } catch (SecurityException ex) { // Probably not on OS X, do nothing.
  148. } catch (IllegalAccessException ex) { // Probably not on OS X, do nothing.
  149. } catch (IllegalArgumentException ex) { // Probably not on OS X, do nothing.
  150. } catch (InvocationTargetException ex) { // Probably not on OS X, do nothing.
  151. }
  152. }
  153. return application;
  154. }
  155. /**
  156. * Get the "NSApplication" object
  157. *
  158. * @return Object that on OSX will be an "NSApplication"
  159. */
  160. public static Object getNSApplication() {
  161. if (nsApplication == null && isApple()) {
  162. try {
  163. final Class<?> app = Class.forName(
  164. "com.apple.cocoa.application.NSApplication");
  165. final Method method = app.getMethod("sharedApplication",
  166. new Class[0]);
  167. nsApplication = method.invoke(null, new Object[0]);
  168. } catch (ClassNotFoundException ex) { // Probably not on OS X, do nothing.
  169. } catch (NoSuchMethodException ex) { // Probably not on OS X, do nothing.
  170. } catch (IllegalAccessException ex) { // Probably not on OS X, do nothing.
  171. } catch (InvocationTargetException ex) { // Probably not on OS X, do nothing.
  172. }
  173. }
  174. return nsApplication;
  175. }
  176. /**
  177. * Are we on OS X?
  178. *
  179. * @return true if we are running on OS X
  180. */
  181. public static boolean isApple() {
  182. return (System.getProperty("mrj.version") != null);
  183. }
  184. /**
  185. * Are we using the OS X look and feel?
  186. *
  187. * @return true if we are using the OS X look and feel
  188. */
  189. public static boolean isAppleUI() {
  190. return isApple() && UIManager.getLookAndFeel().getClass().getName().
  191. equals("apple.laf.AquaLookAndFeel");
  192. }
  193. /**
  194. * Set some OS X only UI settings.
  195. */
  196. public void setUISettings() {
  197. if (!isApple()) {
  198. return;
  199. }
  200. // Set some Apple OS X related stuff from http://tinyurl.com/6xwuld
  201. final String aaText = IdentityManager.getGlobalConfig().getOptionBool(
  202. "ui", "antialias") ? "on" : "off";
  203. System.setProperty("apple.awt.antialiasing", aaText);
  204. System.setProperty("apple.awt.textantialiasing", aaText);
  205. System.setProperty("apple.awt.showGrowBox", "true");
  206. System.setProperty("com.apple.mrj.application.apple.menu.about.name",
  207. "DMDirc");
  208. System.setProperty("apple.laf.useScreenMenuBar", "true");
  209. System.setProperty("com.apple.mrj.application.growbox.intrudes", "false");
  210. System.setProperty("com.apple.mrj.application.live-resize", "true");
  211. }
  212. /**
  213. * Request user attention (Bounce the dock).
  214. *
  215. * @param isCritical If this is false, the dock icon only bounces once,
  216. * otherwise it will bounce until clicked on.
  217. */
  218. public void requestUserAttention(final boolean isCritical) {
  219. if (!isApple()) {
  220. return;
  221. }
  222. try {
  223. final Field type = isCritical ? getNSApplication().getClass().
  224. getField("UserAttentionRequestCritical") : getNSApplication().
  225. getClass().getField("Informational");
  226. final Method method = getNSApplication().getClass().getMethod(
  227. "requestUserAttention", new Class[]{Integer.TYPE});
  228. method.invoke(getNSApplication(), new Object[]{type.get(null)});
  229. } catch (NoSuchFieldException ex) { // Probably not on OS X, do nothing.
  230. } catch (NoSuchMethodException ex) { // Probably not on OS X, do nothing.
  231. } catch (IllegalAccessException ex) { // Probably not on OS X, do nothing.
  232. } catch (InvocationTargetException ex) { // Probably not on OS X, do nothing.
  233. }
  234. }
  235. /**
  236. * Set this up as a listener for the Apple Events
  237. *
  238. * @return True if the listener was added, else false.
  239. */
  240. public boolean setListener() {
  241. if (!isApple() || isListener) {
  242. return false;
  243. }
  244. try {
  245. final Class listenerClass = Class.forName(
  246. "com.apple.eawt.ApplicationListener");
  247. final Object listener = Proxy.newProxyInstance(getClass().
  248. getClassLoader(), new Class[]{listenerClass}, this);
  249. Method method = getApplication().getClass().getMethod(
  250. "addApplicationListener", new Class[]{listenerClass});
  251. method.invoke(getApplication(), listener);
  252. isListener = true;
  253. method = getApplication().getClass().getMethod(
  254. "setEnabledPreferencesMenu", new Class[]{Boolean.TYPE});
  255. method.invoke(getApplication(), new Object[]{Boolean.TRUE});
  256. method =
  257. getApplication().getClass().getMethod("setEnabledAboutMenu",
  258. new Class[]{Boolean.TYPE});
  259. method.invoke(getApplication(), new Object[]{Boolean.TRUE});
  260. return true;
  261. } catch (ClassNotFoundException ex) { // Probably not on OS X, do nothing.
  262. } catch (NoSuchMethodException ex) { // Probably not on OS X, do nothing.
  263. } catch (IllegalAccessException ex) { // Probably not on OS X, do nothing.
  264. } catch (InvocationTargetException ex) { // Probably not on OS X, do nothing.
  265. }
  266. return false;
  267. }
  268. /**
  269. * {@inheritDoc}
  270. *
  271. * @throws Throwable Throws stuff on errors
  272. */
  273. @Override
  274. public Object invoke(final Object proxy, final Method method,
  275. final Object[] args) throws Throwable {
  276. if (!isApple()) {
  277. return null;
  278. }
  279. try {
  280. final ApplicationEvent event = (ApplicationEvent) Proxy.
  281. newProxyInstance(getClass().getClassLoader(), new Class[]{
  282. ApplicationEvent.class}, new InvocationHandler() {
  283. /** {@inheritDoc} */
  284. @Override
  285. public Object invoke(final Object p, final Method m,
  286. final Object[] a) throws Throwable {
  287. return args[0].getClass().getMethod(m.getName(), m.
  288. getParameterTypes()).invoke(args[0], a);
  289. }
  290. });
  291. Method thisMethod = this.getClass().getMethod(method.getName(),
  292. new Class[]{ApplicationEvent.class});
  293. return thisMethod.invoke(this, event);
  294. } catch (NoSuchMethodException e) {
  295. if (method.getName().equals("equals") && args.length == 1) {
  296. return Boolean.valueOf(proxy == args[0]);
  297. }
  298. }
  299. return null;
  300. }
  301. /**
  302. * Set the MenuBar.
  303. * This will unset all menu mnemonics aswell if on the OSX ui.
  304. *
  305. * @param menuBar MenuBar to use to send events to,
  306. */
  307. public void setMenuBar(final MenuBar menuBar) {
  308. this.menuBar = menuBar;
  309. if (isAppleUI()) {
  310. for (int i = 0; i < menuBar.getMenuCount(); i++) {
  311. final JMenu menu = menuBar.getMenu(i);
  312. if (menu != null) {
  313. menu.setMnemonic(0);
  314. for (int j = 0; j < menu.getItemCount(); j++) {
  315. final JMenuItem menuItem = menu.getItem(j);
  316. if (menuItem != null) {
  317. menuItem.setMnemonic(0);
  318. }
  319. }
  320. }
  321. }
  322. }
  323. }
  324. /**
  325. * Handle an event using the menuBar
  326. *
  327. * @param name The name of the event according to the menubar
  328. * @param event The ApplicationEvent we are handingle
  329. */
  330. public void handleMenuBarEvent(final String name,
  331. final ApplicationEvent event) {
  332. if (!isApple() || menuBar == null) {
  333. return;
  334. }
  335. final ActionEvent actionEvent = new ActionEvent(this,
  336. ActionEvent.ACTION_PERFORMED, name);
  337. menuBar.actionPerformed(actionEvent);
  338. event.setHandled(true);
  339. }
  340. /**
  341. * This is called when Quit is selected from the Application menu
  342. *
  343. * @param event an ApplicationEvent object
  344. */
  345. public void handleQuit(final ApplicationEvent event) {
  346. handleMenuBarEvent("Exit", event);
  347. }
  348. /**
  349. * This is called when About is selected from the Application menu
  350. *
  351. * @param event an ApplicationEvent object
  352. */
  353. public void handleAbout(final ApplicationEvent event) {
  354. handleMenuBarEvent("About", event);
  355. }
  356. /**
  357. * This is called when Preferences is selected from the Application menu
  358. *
  359. * @param event an ApplicationEvent object
  360. */
  361. public void handlePreferences(final ApplicationEvent event) {
  362. handleMenuBarEvent("Preferences", event);
  363. }
  364. /**
  365. * This is called when the Application is opened
  366. *
  367. * @param event an ApplicationEvent object
  368. */
  369. public void handleOpenApplication(final ApplicationEvent event) {
  370. }
  371. /**
  372. * This is called when the application is asked to open a file
  373. *
  374. * @param event an ApplicationEvent object
  375. */
  376. public void handleOpenFile(final ApplicationEvent event) {
  377. }
  378. /**
  379. * This is called when asked to print
  380. *
  381. * @param event an ApplicationEvent object
  382. */
  383. public void handlePrintFile(final ApplicationEvent event) {
  384. }
  385. /**
  386. * This is called when the application is reopened
  387. *
  388. * @param event an ApplicationEvent object
  389. */
  390. public void handleReopenApplication(final ApplicationEvent event) {
  391. }
  392. /** {@inheritDoc} */
  393. @Override
  394. public void processEvent(final ActionType type, final StringBuffer format,
  395. final Object... arguments) {
  396. if (type == CoreActionType.CLIENT_OPENED) {
  397. synchronized (addresses) {
  398. clientOpened = true;
  399. for (URI addr : addresses) {
  400. ServerManager.getServerManager().connectToAddress(addr);
  401. }
  402. addresses.clear();
  403. }
  404. }
  405. }
  406. /**
  407. * Callback from JNI library.
  408. * If called before the client has finished opening, the URL will be added to
  409. * a list that will be connected to once the CLIENT_OPENED action is called.
  410. * Otherwise we connect right away.
  411. *
  412. * @param url The irc url to connect to.
  413. */
  414. public void handleOpenURL(final String url) {
  415. if (isApple()) {
  416. try {
  417. synchronized (addresses) {
  418. final URI addr = NewServer.getURI(url);
  419. if (!clientOpened) {
  420. addresses.add(addr);
  421. } else {
  422. // When the JNI callback is called there is no
  423. // ContextClassLoader set, which causes an NPE in
  424. // IconManager if no servers have been connected to yet.
  425. if (Thread.currentThread().getContextClassLoader() ==
  426. null) {
  427. Thread.currentThread().setContextClassLoader(ClassLoader.
  428. getSystemClassLoader());
  429. }
  430. ServerManager.getServerManager().connectToAddress(addr);
  431. }
  432. }
  433. } catch (URISyntaxException iae) {
  434. }
  435. }
  436. }
  437. /**
  438. * Register the getURL Callback.
  439. *
  440. * @return 0 on success, 1 on failure.
  441. */
  442. private synchronized final native int registerOpenURLCallback();
  443. }