1 /*
   2  * Copyright (c) 2011, 2018, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package sun.lwawt.macosx;
  27 
  28 import java.awt.AWTError;
  29 import java.awt.CheckboxMenuItem;
  30 import java.awt.Color;
  31 import java.awt.Component;
  32 import java.awt.Cursor;
  33 import java.awt.Desktop;
  34 import java.awt.Dialog;
  35 import java.awt.Dimension;
  36 import java.awt.Event;
  37 import java.awt.EventQueue;
  38 import java.awt.FileDialog;
  39 import java.awt.Frame;
  40 import java.awt.GraphicsConfiguration;
  41 import java.awt.GraphicsDevice;
  42 import java.awt.GraphicsEnvironment;
  43 import java.awt.HeadlessException;
  44 import java.awt.Image;
  45 import java.awt.Insets;
  46 import java.awt.Menu;
  47 import java.awt.MenuBar;
  48 import java.awt.MenuItem;
  49 import java.awt.Point;
  50 import java.awt.PopupMenu;
  51 import java.awt.RenderingHints;
  52 import java.awt.Robot;
  53 import java.awt.SystemTray;
  54 import java.awt.Taskbar;
  55 import java.awt.Toolkit;
  56 import java.awt.TrayIcon;
  57 import java.awt.Window;
  58 import java.awt.datatransfer.Clipboard;
  59 import java.awt.dnd.DragGestureEvent;
  60 import java.awt.dnd.DragGestureListener;
  61 import java.awt.dnd.DragGestureRecognizer;
  62 import java.awt.dnd.DragSource;
  63 import java.awt.dnd.DropTarget;
  64 import java.awt.dnd.InvalidDnDOperationException;
  65 import java.awt.dnd.MouseDragGestureRecognizer;
  66 import java.awt.dnd.peer.DragSourceContextPeer;
  67 import java.awt.event.InputEvent;
  68 import java.awt.event.InvocationEvent;
  69 import java.awt.event.KeyEvent;
  70 import java.awt.font.TextAttribute;
  71 import java.awt.im.InputMethodHighlight;
  72 import java.awt.im.spi.InputMethodDescriptor;
  73 import java.awt.peer.CheckboxMenuItemPeer;
  74 import java.awt.peer.DesktopPeer;
  75 import java.awt.peer.DialogPeer;
  76 import java.awt.peer.FileDialogPeer;
  77 import java.awt.peer.FontPeer;
  78 import java.awt.peer.MenuBarPeer;
  79 import java.awt.peer.MenuItemPeer;
  80 import java.awt.peer.MenuPeer;
  81 import java.awt.peer.PopupMenuPeer;
  82 import java.awt.peer.RobotPeer;
  83 import java.awt.peer.SystemTrayPeer;
  84 import java.awt.peer.TaskbarPeer;
  85 import java.awt.peer.TrayIconPeer;
  86 import java.lang.reflect.InvocationTargetException;
  87 import java.lang.reflect.UndeclaredThrowableException;
  88 import java.net.MalformedURLException;
  89 import java.net.URL;
  90 import java.security.AccessController;
  91 import java.security.PrivilegedAction;
  92 import java.util.HashMap;
  93 import java.util.Locale;
  94 import java.util.Map;
  95 import java.util.MissingResourceException;
  96 import java.util.Objects;
  97 import java.util.ResourceBundle;
  98 import java.util.concurrent.Callable;
  99 
 100 import javax.swing.UIManager;
 101 
 102 import com.apple.laf.AquaMenuBarUI;
 103 import sun.awt.AWTAccessor;
 104 import sun.awt.AppContext;
 105 import sun.awt.CGraphicsConfig;
 106 import sun.awt.CGraphicsDevice;
 107 import sun.awt.LightweightFrame;
 108 import sun.awt.SunToolkit;
 109 import sun.awt.datatransfer.DataTransferer;
 110 import sun.awt.util.ThreadGroupUtils;
 111 import sun.java2d.macos.MacOSFlags;
 112 import sun.java2d.metal.MTLRenderQueue;
 113 import sun.java2d.opengl.OGLRenderQueue;
 114 import sun.lwawt.LWComponentPeer;
 115 import sun.lwawt.LWCursorManager;
 116 import sun.lwawt.LWToolkit;
 117 import sun.lwawt.LWWindowPeer;
 118 import sun.lwawt.LWWindowPeer.PeerType;
 119 import sun.lwawt.PlatformComponent;
 120 import sun.lwawt.PlatformDropTarget;
 121 import sun.lwawt.PlatformWindow;
 122 import sun.lwawt.SecurityWarningWindow;
 123 import sun.security.action.GetBooleanAction;
 124 
 125 @SuppressWarnings("serial") // JDK implementation class
 126 final class NamedCursor extends Cursor {
 127     NamedCursor(String name) {
 128         super(name);
 129     }
 130 }
 131 
 132 /**
 133  * Mac OS X Cocoa-based AWT Toolkit.
 134  */
 135 public final class LWCToolkit extends LWToolkit {
 136     // While it is possible to enumerate all mouse devices
 137     // and query them for the number of buttons, the code
 138     // that does it is rather complex. Instead, we opt for
 139     // the easy way and just support up to 5 mouse buttons,
 140     // like Windows.
 141     private static final int BUTTONS = 5;
 142 
 143     private static native void initIDs();
 144     private static native void initAppkit(ThreadGroup appKitThreadGroup, boolean headless);
 145     private static CInputMethodDescriptor sInputMethodDescriptor;
 146 
 147     static {
 148         System.err.flush();
 149 
 150         ResourceBundle platformResources = java.security.AccessController.doPrivileged(
 151                 new java.security.PrivilegedAction<ResourceBundle>() {
 152             @Override
 153             public ResourceBundle run() {
 154                 ResourceBundle platformResources = null;
 155                 try {
 156                     platformResources = ResourceBundle.getBundle("sun.awt.resources.awtosx");
 157                 } catch (MissingResourceException e) {
 158                     // No resource file; defaults will be used.
 159                 }
 160 
 161                 System.loadLibrary("awt");
 162                 System.loadLibrary("fontmanager");
 163 
 164                 return platformResources;
 165             }
 166         });
 167 
 168         if (!GraphicsEnvironment.isHeadless() && !isInAquaSession()) {
 169             throw new AWTError("WindowServer is not available");
 170         }
 171 
 172         AWTAccessor.getToolkitAccessor().setPlatformResources(platformResources);
 173 
 174         if (!GraphicsEnvironment.isHeadless()) {
 175             initIDs();
 176         }
 177         inAWT = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
 178             @Override
 179             public Boolean run() {
 180                 return !Boolean.parseBoolean(System.getProperty("javafx.embed.singleThread", "false"));
 181             }
 182         });
 183     }
 184 
 185     /*
 186      * If true  we operate in normal mode and nested runloop is executed in JavaRunLoopMode
 187      * If false we operate in singleThreaded FX/AWT interop mode and nested loop uses NSDefaultRunLoopMode
 188      */
 189     private static final boolean inAWT;
 190 
 191     public LWCToolkit() {
 192         areExtraMouseButtonsEnabled = Boolean.parseBoolean(System.getProperty("sun.awt.enableExtraMouseButtons", "true"));
 193         //set system property if not yet assigned
 194         System.setProperty("sun.awt.enableExtraMouseButtons", ""+areExtraMouseButtonsEnabled);
 195         initAppkit(ThreadGroupUtils.getRootThreadGroup(), GraphicsEnvironment.isHeadless());
 196     }
 197 
 198     /*
 199      * System colors with default initial values, overwritten by toolkit if system values differ and are available.
 200      */
 201     private static final int NUM_APPLE_COLORS = 3;
 202     public static final int KEYBOARD_FOCUS_COLOR = 0;
 203     public static final int INACTIVE_SELECTION_BACKGROUND_COLOR = 1;
 204     public static final int INACTIVE_SELECTION_FOREGROUND_COLOR = 2;
 205     private static int[] appleColors = {
 206         0xFF808080, // keyboardFocusColor = Color.gray;
 207         0xFFC0C0C0, // secondarySelectedControlColor
 208         0xFF303030, // controlDarkShadowColor
 209     };
 210 
 211     private native void loadNativeColors(final int[] systemColors, final int[] appleColors);
 212 
 213     @Override
 214     protected void loadSystemColors(final int[] systemColors) {
 215         if (systemColors == null) return;
 216         loadNativeColors(systemColors, appleColors);
 217     }
 218 
 219     @SuppressWarnings("serial") // JDK implementation class
 220     private static class AppleSpecificColor extends Color {
 221         private final int index;
 222         AppleSpecificColor(int index) {
 223             super(appleColors[index]);
 224             this.index = index;
 225         }
 226 
 227         @Override
 228         public int getRGB() {
 229             return appleColors[index];
 230         }
 231     }
 232 
 233     /**
 234      * Returns Apple specific colors that we may expose going forward.
 235      */
 236     public static Color getAppleColor(int color) {
 237         return new AppleSpecificColor(color);
 238     }
 239 
 240     // This is only called from native code.
 241     static void systemColorsChanged() {
 242         EventQueue.invokeLater(() -> {
 243             AccessController.doPrivileged( (PrivilegedAction<Object>) () -> {
 244                 AWTAccessor.getSystemColorAccessor().updateSystemColors();
 245                 return null;
 246             });
 247         });
 248     }
 249 
 250     public static LWCToolkit getLWCToolkit() {
 251         return (LWCToolkit)Toolkit.getDefaultToolkit();
 252     }
 253 
 254     @Override
 255     protected PlatformWindow createPlatformWindow(PeerType peerType) {
 256         if (peerType == PeerType.EMBEDDED_FRAME) {
 257             return new CPlatformEmbeddedFrame();
 258         } else if (peerType == PeerType.VIEW_EMBEDDED_FRAME) {
 259             return new CViewPlatformEmbeddedFrame();
 260         } else if (peerType == PeerType.LW_FRAME) {
 261             return new CPlatformLWWindow();
 262         } else {
 263             assert (peerType == PeerType.SIMPLEWINDOW
 264                     || peerType == PeerType.DIALOG
 265                     || peerType == PeerType.FRAME);
 266             return new CPlatformWindow();
 267         }
 268     }
 269 
 270     LWWindowPeer createEmbeddedFrame(CEmbeddedFrame target) {
 271         PlatformComponent platformComponent = createPlatformComponent();
 272         PlatformWindow platformWindow = createPlatformWindow(PeerType.EMBEDDED_FRAME);
 273         return createDelegatedPeer(target, platformComponent, platformWindow, PeerType.EMBEDDED_FRAME);
 274     }
 275 
 276     LWWindowPeer createEmbeddedFrame(CViewEmbeddedFrame target) {
 277         PlatformComponent platformComponent = createPlatformComponent();
 278         PlatformWindow platformWindow = createPlatformWindow(PeerType.VIEW_EMBEDDED_FRAME);
 279         return createDelegatedPeer(target, platformComponent, platformWindow, PeerType.VIEW_EMBEDDED_FRAME);
 280     }
 281 
 282     private CPrinterDialogPeer createCPrinterDialog(CPrinterDialog target) {
 283         PlatformComponent platformComponent = createPlatformComponent();
 284         PlatformWindow platformWindow = createPlatformWindow(PeerType.DIALOG);
 285         CPrinterDialogPeer peer = new CPrinterDialogPeer(target, platformComponent, platformWindow);
 286         targetCreatedPeer(target, peer);
 287         return peer;
 288     }
 289 
 290     @Override
 291     public DialogPeer createDialog(Dialog target) {
 292         if (target instanceof CPrinterDialog) {
 293             return createCPrinterDialog((CPrinterDialog)target);
 294         }
 295         return super.createDialog(target);
 296     }
 297 
 298     @Override
 299     protected SecurityWarningWindow createSecurityWarning(Window ownerWindow,
 300                                                           LWWindowPeer ownerPeer) {
 301         return new CWarningWindow(ownerWindow, ownerPeer);
 302     }
 303 
 304     @Override
 305     protected PlatformComponent createPlatformComponent() {
 306         return new CPlatformComponent();
 307     }
 308 
 309     @Override
 310     protected PlatformComponent createLwPlatformComponent() {
 311         return new CPlatformLWComponent();
 312     }
 313 
 314     @Override
 315     protected FileDialogPeer createFileDialogPeer(FileDialog target) {
 316         return new CFileDialog(target);
 317     }
 318 
 319     @Override
 320     public MenuPeer createMenu(Menu target) {
 321         MenuPeer peer = new CMenu(target);
 322         targetCreatedPeer(target, peer);
 323         return peer;
 324     }
 325 
 326     @Override
 327     public MenuBarPeer createMenuBar(MenuBar target) {
 328         MenuBarPeer peer = new CMenuBar(target);
 329         targetCreatedPeer(target, peer);
 330         return peer;
 331     }
 332 
 333     @Override
 334     public MenuItemPeer createMenuItem(MenuItem target) {
 335         MenuItemPeer peer = new CMenuItem(target);
 336         targetCreatedPeer(target, peer);
 337         return peer;
 338     }
 339 
 340     @Override
 341     public CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target) {
 342         CheckboxMenuItemPeer peer = new CCheckboxMenuItem(target);
 343         targetCreatedPeer(target, peer);
 344         return peer;
 345     }
 346 
 347     @Override
 348     public PopupMenuPeer createPopupMenu(PopupMenu target) {
 349         PopupMenuPeer peer = new CPopupMenu(target);
 350         targetCreatedPeer(target, peer);
 351         return peer;
 352     }
 353 
 354     @Override
 355     public SystemTrayPeer createSystemTray(SystemTray target) {
 356         return new CSystemTray();
 357     }
 358 
 359     @Override
 360     public TrayIconPeer createTrayIcon(TrayIcon target) {
 361         TrayIconPeer peer = new CTrayIcon(target);
 362         targetCreatedPeer(target, peer);
 363         return peer;
 364     }
 365 
 366     @Override
 367     public DesktopPeer createDesktopPeer(Desktop target) {
 368         return new CDesktopPeer();
 369     }
 370 
 371     @Override
 372     public TaskbarPeer createTaskbarPeer(Taskbar target) {
 373         return new CTaskbarPeer();
 374     }
 375 
 376     @Override
 377     public LWCursorManager getCursorManager() {
 378         return CCursorManager.getInstance();
 379     }
 380 
 381     @Override
 382     public Cursor createCustomCursor(final Image cursor, final Point hotSpot,
 383                                      final String name)
 384             throws IndexOutOfBoundsException, HeadlessException {
 385         return new CCustomCursor(cursor, hotSpot, name);
 386     }
 387 
 388     @Override
 389     public Dimension getBestCursorSize(final int preferredWidth,
 390                                        final int preferredHeight)
 391             throws HeadlessException {
 392         return CCustomCursor.getBestCursorSize(preferredWidth, preferredHeight);
 393     }
 394 
 395     @Override
 396     protected void platformCleanup() {
 397         // TODO Auto-generated method stub
 398     }
 399 
 400     @Override
 401     protected void platformInit() {
 402         // TODO Auto-generated method stub
 403     }
 404 
 405     @Override
 406     protected void platformRunMessage() {
 407         // TODO Auto-generated method stub
 408     }
 409 
 410     @Override
 411     protected void platformShutdown() {
 412         // TODO Auto-generated method stub
 413     }
 414 
 415     class OSXPlatformFont extends sun.awt.PlatformFont
 416     {
 417         OSXPlatformFont(String name, int style)
 418         {
 419             super(name, style);
 420         }
 421         @Override
 422         protected char getMissingGlyphCharacter()
 423         {
 424             // Follow up for real implementation
 425             return (char)0xfff8; // see http://developer.apple.com/fonts/LastResortFont/
 426         }
 427     }
 428     @Override
 429     public FontPeer getFontPeer(String name, int style) {
 430         return new OSXPlatformFont(name, style);
 431     }
 432 
 433     @Override
 434     protected void initializeDesktopProperties() {
 435         super.initializeDesktopProperties();
 436         Map <Object, Object> fontHints = new HashMap<>();
 437         fontHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
 438         desktopProperties.put(SunToolkit.DESKTOPFONTHINTS, fontHints);
 439         desktopProperties.put("awt.mouse.numButtons", BUTTONS);
 440 
 441         // These DnD properties must be set, otherwise Swing ends up spewing NPEs
 442         // all over the place. The values came straight off of MToolkit.
 443         desktopProperties.put("DnD.Autoscroll.initialDelay", Integer.valueOf(50));
 444         desktopProperties.put("DnD.Autoscroll.interval", Integer.valueOf(50));
 445         desktopProperties.put("DnD.Autoscroll.cursorHysteresis", Integer.valueOf(5));
 446 
 447         desktopProperties.put("DnD.isDragImageSupported", Boolean.TRUE);
 448 
 449         // Register DnD cursors
 450         desktopProperties.put("DnD.Cursor.CopyDrop", new NamedCursor("DnD.Cursor.CopyDrop"));
 451         desktopProperties.put("DnD.Cursor.MoveDrop", new NamedCursor("DnD.Cursor.MoveDrop"));
 452         desktopProperties.put("DnD.Cursor.LinkDrop", new NamedCursor("DnD.Cursor.LinkDrop"));
 453         desktopProperties.put("DnD.Cursor.CopyNoDrop", new NamedCursor("DnD.Cursor.CopyNoDrop"));
 454         desktopProperties.put("DnD.Cursor.MoveNoDrop", new NamedCursor("DnD.Cursor.MoveNoDrop"));
 455         desktopProperties.put("DnD.Cursor.LinkNoDrop", new NamedCursor("DnD.Cursor.LinkNoDrop"));
 456     }
 457 
 458     @Override
 459     protected boolean syncNativeQueue(long timeout) {
 460         return nativeSyncQueue(timeout);
 461     }
 462 
 463     @Override
 464     public native void beep();
 465 
 466     @Override
 467     public int getScreenResolution() throws HeadlessException {
 468         return (int) ((CGraphicsDevice) GraphicsEnvironment
 469                 .getLocalGraphicsEnvironment().getDefaultScreenDevice())
 470                 .getXResolution();
 471     }
 472 
 473     @Override
 474     public Insets getScreenInsets(final GraphicsConfiguration gc) {
 475         return ((CGraphicsConfig) gc).getDevice().getScreenInsets();
 476     }
 477 
 478     @Override
 479     public void sync() {
 480         // flush the OGL pipeline (this is a no-op if OGL is not enabled)
 481         if (MacOSFlags.isMetalEnabled()) {
 482             MTLRenderQueue.sync();
 483         } else {
 484             OGLRenderQueue.sync();
 485         }
 486         // setNeedsDisplay() selector was sent to the appropriate CALayer so now
 487         // we have to flush the native selectors queue.
 488         flushNativeSelectors();
 489     }
 490 
 491     @Override
 492     public RobotPeer createRobot(Robot target, GraphicsDevice screen) {
 493         return new CRobot(target, (CGraphicsDevice)screen);
 494     }
 495 
 496     private native boolean isCapsLockOn();
 497 
 498     /*
 499      * NOTE: Among the keys this method is supposed to check,
 500      * only Caps Lock works as a true locking key with OS X.
 501      * There is no Scroll Lock key on modern Apple keyboards,
 502      * and with a PC keyboard plugged in Scroll Lock is simply
 503      * ignored: no LED lights up if you press it.
 504      * The key located at the same position on Apple keyboards
 505      * as Num Lock on PC keyboards is called Clear, doesn't lock
 506      * anything and is used for entirely different purpose.
 507      */
 508     @Override
 509     public boolean getLockingKeyState(int keyCode) throws UnsupportedOperationException {
 510         switch (keyCode) {
 511             case KeyEvent.VK_NUM_LOCK:
 512             case KeyEvent.VK_SCROLL_LOCK:
 513             case KeyEvent.VK_KANA_LOCK:
 514                 throw new UnsupportedOperationException("Toolkit.getLockingKeyState");
 515 
 516             case KeyEvent.VK_CAPS_LOCK:
 517                 return isCapsLockOn();
 518 
 519             default:
 520                 throw new IllegalArgumentException("invalid key for Toolkit.getLockingKeyState");
 521         }
 522     }
 523 
 524     //Is it allowed to generate events assigned to extra mouse buttons.
 525     //Set to true by default.
 526     private static boolean areExtraMouseButtonsEnabled = true;
 527 
 528     @Override
 529     public boolean areExtraMouseButtonsEnabled() throws HeadlessException {
 530         return areExtraMouseButtonsEnabled;
 531     }
 532 
 533     @Override
 534     public int getNumberOfButtons(){
 535         return BUTTONS;
 536     }
 537 
 538     @Override
 539     public boolean isTraySupported() {
 540         return true;
 541     }
 542 
 543     @Override
 544     public DataTransferer getDataTransferer() {
 545         return CDataTransferer.getInstanceImpl();
 546     }
 547 
 548     @Override
 549     public boolean isAlwaysOnTopSupported() {
 550         return true;
 551     }
 552 
 553     private static final String APPKIT_THREAD_NAME = "AppKit Thread";
 554 
 555     // Intended to be called from the LWCToolkit.m only.
 556     private static void installToolkitThreadInJava() {
 557         Thread.currentThread().setName(APPKIT_THREAD_NAME);
 558         AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 559             Thread.currentThread().setContextClassLoader(null);
 560             return null;
 561         });
 562     }
 563 
 564     @Override
 565     public boolean isWindowOpacitySupported() {
 566         return true;
 567     }
 568 
 569     @Override
 570     public boolean isFrameStateSupported(int state) throws HeadlessException {
 571         switch (state) {
 572             case Frame.NORMAL:
 573             case Frame.ICONIFIED:
 574             case Frame.MAXIMIZED_BOTH:
 575                 return true;
 576             default:
 577                 return false;
 578         }
 579     }
 580 
 581     @Override
 582     @Deprecated(since = "10")
 583     public int getMenuShortcutKeyMask() {
 584         return Event.META_MASK;
 585     }
 586 
 587     @Override
 588     public int getMenuShortcutKeyMaskEx() {
 589         return InputEvent.META_DOWN_MASK;
 590     }
 591 
 592     @Override
 593     public Image getImage(final String filename) {
 594         final Image nsImage = checkForNSImage(filename);
 595         if (nsImage != null) {
 596             return nsImage;
 597         }
 598 
 599         if (imageCached(filename)) {
 600             return super.getImage(filename);
 601         }
 602 
 603         String filename2x = getScaledImageName(filename);
 604         return (imageExists(filename2x))
 605                 ? getImageWithResolutionVariant(filename, filename2x)
 606                 : super.getImage(filename);
 607     }
 608 
 609     @Override
 610     public Image getImage(URL url) {
 611 
 612         if (imageCached(url)) {
 613             return super.getImage(url);
 614         }
 615 
 616         URL url2x = getScaledImageURL(url);
 617         return (imageExists(url2x))
 618                 ? getImageWithResolutionVariant(url, url2x) : super.getImage(url);
 619     }
 620 
 621     private static final String nsImagePrefix = "NSImage://";
 622     private Image checkForNSImage(final String imageName) {
 623         if (imageName == null) return null;
 624         if (!imageName.startsWith(nsImagePrefix)) return null;
 625         return CImage.getCreator().createImageFromName(imageName.substring(nsImagePrefix.length()));
 626     }
 627 
 628     // Thread-safe Object.equals() called from native
 629     public static boolean doEquals(final Object a, final Object b, Component c) {
 630         if (a == b) return true;
 631 
 632         final boolean[] ret = new boolean[1];
 633 
 634         try {  invokeAndWait(new Runnable() { @Override
 635                                               public void run() { synchronized(ret) {
 636             ret[0] = a.equals(b);
 637         }}}, c); } catch (Exception e) { e.printStackTrace(); }
 638 
 639         synchronized(ret) { return ret[0]; }
 640     }
 641 
 642     public static <T> T invokeAndWait(final Callable<T> callable,
 643                                       Component component) throws Exception {
 644         final CallableWrapper<T> wrapper = new CallableWrapper<>(callable);
 645         invokeAndWait(wrapper, component);
 646         return wrapper.getResult();
 647     }
 648 
 649     static final class CallableWrapper<T> implements Runnable {
 650         final Callable<T> callable;
 651         T object;
 652         Exception e;
 653 
 654         CallableWrapper(final Callable<T> callable) {
 655             this.callable = callable;
 656         }
 657 
 658         @Override
 659         public void run() {
 660             try {
 661                 object = callable.call();
 662             } catch (final Exception e) {
 663                 this.e = e;
 664             }
 665         }
 666 
 667         public T getResult() throws Exception {
 668             if (e != null) throw e;
 669             return object;
 670         }
 671     }
 672 
 673     /**
 674      * Kicks an event over to the appropriate event queue and waits for it to
 675      * finish To avoid deadlocking, we manually run the NSRunLoop while waiting
 676      * Any selector invoked using ThreadUtilities performOnMainThread will be
 677      * processed in doAWTRunLoop The InvocationEvent will call
 678      * LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual
 679      * run loop. Does not dispatch native events while in the loop
 680      */
 681     public static void invokeAndWait(Runnable runnable, Component component)
 682             throws InvocationTargetException {
 683         Objects.requireNonNull(component, "Null component provided to invokeAndWait");
 684 
 685         long mediator = createAWTRunLoopMediator();
 686         InvocationEvent invocationEvent =
 687                 new InvocationEvent(component,
 688                         runnable,
 689                         () -> {
 690                             if (mediator != 0) {
 691                                 stopAWTRunLoop(mediator);
 692                             }
 693                         },
 694                         true);
 695 
 696         AppContext appContext = SunToolkit.targetToAppContext(component);
 697         SunToolkit.postEvent(appContext, invocationEvent);
 698         // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock
 699         SunToolkit.flushPendingEvents(appContext);
 700         doAWTRunLoop(mediator, false);
 701 
 702         checkException(invocationEvent);
 703     }
 704 
 705     public static void invokeLater(Runnable event, Component component)
 706             throws InvocationTargetException {
 707         Objects.requireNonNull(component, "Null component provided to invokeLater");
 708 
 709         InvocationEvent invocationEvent = new InvocationEvent(component, event);
 710 
 711         AppContext appContext = SunToolkit.targetToAppContext(component);
 712         SunToolkit.postEvent(SunToolkit.targetToAppContext(component), invocationEvent);
 713         // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock
 714         SunToolkit.flushPendingEvents(appContext);
 715 
 716         checkException(invocationEvent);
 717     }
 718 
 719     /**
 720      * Checks if exception occurred while {@code InvocationEvent} was processed and rethrows it as
 721      * an {@code InvocationTargetException}
 722      *
 723      * @param event the event to check for an exception
 724      * @throws InvocationTargetException if exception occurred when event was processed
 725      */
 726     private static void checkException(InvocationEvent event) throws InvocationTargetException {
 727         Throwable eventException = event.getException();
 728         if (eventException == null) return;
 729 
 730         if (eventException instanceof UndeclaredThrowableException) {
 731             eventException = ((UndeclaredThrowableException)eventException).getUndeclaredThrowable();
 732         }
 733         throw new InvocationTargetException(eventException);
 734     }
 735 
 736     /**
 737      * Schedules a {@code Runnable} execution on the Appkit thread after a delay
 738      * @param r a {@code Runnable} to execute
 739      * @param delay a delay in milliseconds
 740      */
 741     static native void performOnMainThreadAfterDelay(Runnable r, long delay);
 742 
 743 // DnD support
 744 
 745     @Override
 746     public DragSourceContextPeer createDragSourceContextPeer(
 747             DragGestureEvent dge) throws InvalidDnDOperationException {
 748         final LightweightFrame f = SunToolkit.getLightweightFrame(dge.getComponent());
 749         if (f != null) {
 750             return f.createDragSourceContextPeer(dge);
 751         }
 752 
 753         return CDragSourceContextPeer.createDragSourceContextPeer(dge);
 754     }
 755 
 756     @Override
 757     @SuppressWarnings("unchecked")
 758     public <T extends DragGestureRecognizer> T createDragGestureRecognizer(
 759             Class<T> abstractRecognizerClass, DragSource ds, Component c,
 760             int srcActions, DragGestureListener dgl) {
 761         final LightweightFrame f = SunToolkit.getLightweightFrame(c);
 762         if (f != null) {
 763             return f.createDragGestureRecognizer(abstractRecognizerClass, ds, c, srcActions, dgl);
 764         }
 765 
 766         DragGestureRecognizer dgr = null;
 767 
 768         // Create a new mouse drag gesture recognizer if we have a class match:
 769         if (MouseDragGestureRecognizer.class.equals(abstractRecognizerClass))
 770             dgr = new CMouseDragGestureRecognizer(ds, c, srcActions, dgl);
 771 
 772         return (T)dgr;
 773     }
 774 
 775     @Override
 776     protected PlatformDropTarget createDropTarget(DropTarget dropTarget,
 777                                                   Component component,
 778                                                   LWComponentPeer<?, ?> peer) {
 779         return new CDropTarget(dropTarget, component, peer);
 780     }
 781 
 782     // InputMethodSupport Method
 783     /**
 784      * Returns the default keyboard locale of the underlying operating system
 785      */
 786     @Override
 787     public Locale getDefaultKeyboardLocale() {
 788         Locale locale = CInputMethod.getNativeLocale();
 789 
 790         if (locale == null) {
 791             return super.getDefaultKeyboardLocale();
 792         }
 793 
 794         return locale;
 795     }
 796 
 797     @Override
 798     public InputMethodDescriptor getInputMethodAdapterDescriptor() {
 799         if (sInputMethodDescriptor == null)
 800             sInputMethodDescriptor = new CInputMethodDescriptor();
 801 
 802         return sInputMethodDescriptor;
 803     }
 804 
 805     /**
 806      * Returns a map of visual attributes for thelevel description
 807      * of the given input method highlight, or null if no mapping is found.
 808      * The style field of the input method highlight is ignored. The map
 809      * returned is unmodifiable.
 810      * @param highlight input method highlight
 811      * @return style attribute map, or null
 812      * @since 1.3
 813      */
 814     @Override
 815     public Map<TextAttribute, ?> mapInputMethodHighlight(InputMethodHighlight highlight) {
 816         return CInputMethod.mapInputMethodHighlight(highlight);
 817     }
 818 
 819     /**
 820      * Returns key modifiers used by Swing to set up a focus accelerator key
 821      * stroke.
 822      */
 823     @Override
 824     @SuppressWarnings("deprecation")
 825     public int getFocusAcceleratorKeyMask() {
 826         return InputEvent.CTRL_MASK | InputEvent.ALT_MASK;
 827     }
 828 
 829     /**
 830      * Tests whether specified key modifiers mask can be used to enter a
 831      * printable character.
 832      */
 833     @Override
 834     @SuppressWarnings("deprecation")
 835     public boolean isPrintableCharacterModifiersMask(int mods) {
 836         return ((mods & (InputEvent.META_MASK | InputEvent.CTRL_MASK)) == 0);
 837     }
 838 
 839     /**
 840      * Returns whether popup is allowed to be shown above the task bar.
 841      */
 842     @Override
 843     public boolean canPopupOverlapTaskBar() {
 844         return false;
 845     }
 846 
 847     private static Boolean sunAwtDisableCALayers = null;
 848 
 849     /**
 850      * Returns the value of "sun.awt.disableCALayers" property. Default
 851      * value is {@code false}.
 852      */
 853     public static synchronized boolean getSunAwtDisableCALayers() {
 854         if (sunAwtDisableCALayers == null) {
 855             sunAwtDisableCALayers = AccessController.doPrivileged(
 856                 new GetBooleanAction("sun.awt.disableCALayers"));
 857         }
 858         return sunAwtDisableCALayers;
 859     }
 860 
 861     /*
 862      * Returns true if the application (one of its windows) owns keyboard focus.
 863      */
 864     native boolean isApplicationActive();
 865 
 866     /**
 867      * Returns true if AWT toolkit is embedded, false otherwise.
 868      *
 869      * @return true if AWT toolkit is embedded, false otherwise
 870      */
 871     public static native boolean isEmbedded();
 872 
 873     /**
 874      * Returns true if the WindowServer is available, false otherwise.
 875      *
 876      * @return true if the WindowServer is available, false otherwise
 877      */
 878     private static native boolean isInAquaSession();
 879 
 880     /*
 881      * Activates application ignoring other apps.
 882      */
 883     public native void activateApplicationIgnoringOtherApps();
 884 
 885     /************************
 886      * Native methods section
 887      ************************/
 888 
 889     static native long createAWTRunLoopMediator();
 890     /**
 891      * Method to run a nested run-loop. The nested loop is spinned in the javaRunLoop mode, so selectors sent
 892      * by [JNFRunLoop performOnMainThreadWaiting] are processed.
 893      * @param mediator a native pointer to the mediator object created by createAWTRunLoopMediator
 894      * @param processEvents if true - dispatches event while in the nested loop. Used in DnD.
 895      *                      Additional attention is needed when using this feature as we short-circuit normal event
 896      *                      processing which could break Appkit.
 897      *                      (One known example is when the window is resized with the mouse)
 898      *
 899      *                      if false - all events come after exit form the nested loop
 900      */
 901     static void doAWTRunLoop(long mediator, boolean processEvents) {
 902         doAWTRunLoopImpl(mediator, processEvents, inAWT);
 903     }
 904     private static native void doAWTRunLoopImpl(long mediator, boolean processEvents, boolean inAWT);
 905     static native void stopAWTRunLoop(long mediator);
 906 
 907     private native boolean nativeSyncQueue(long timeout);
 908 
 909     /**
 910      * Just spin a single empty block synchronously.
 911      */
 912     static native void flushNativeSelectors();
 913 
 914     @Override
 915     public Clipboard createPlatformClipboard() {
 916         return new CClipboard("System");
 917     }
 918 
 919     @Override
 920     public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) {
 921         return (exclusionType == null) ||
 922             (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE) ||
 923             (exclusionType == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) ||
 924             (exclusionType == Dialog.ModalExclusionType.TOOLKIT_EXCLUDE);
 925     }
 926 
 927     @Override
 928     public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) {
 929         //TODO: FileDialog blocks excluded windows...
 930         //TODO: Test: 2 file dialogs, separate AppContexts: a) Dialog 1 blocked, shouldn't be. Frame 4 blocked (shouldn't be).
 931         return (modalityType == null) ||
 932             (modalityType == Dialog.ModalityType.MODELESS) ||
 933             (modalityType == Dialog.ModalityType.DOCUMENT_MODAL) ||
 934             (modalityType == Dialog.ModalityType.APPLICATION_MODAL) ||
 935             (modalityType == Dialog.ModalityType.TOOLKIT_MODAL);
 936     }
 937 
 938     @Override
 939     public boolean isWindowShapingSupported() {
 940         return true;
 941     }
 942 
 943     @Override
 944     public boolean isWindowTranslucencySupported() {
 945         return true;
 946     }
 947 
 948     @Override
 949     public boolean isTranslucencyCapable(GraphicsConfiguration gc) {
 950         return true;
 951     }
 952 
 953     @Override
 954     public boolean isSwingBackbufferTranslucencySupported() {
 955         return true;
 956     }
 957 
 958     @Override
 959     public boolean enableInputMethodsForTextComponent() {
 960         return true;
 961     }
 962 
 963     private static URL getScaledImageURL(URL url) {
 964         try {
 965             String scaledImagePath = getScaledImageName(url.getPath());
 966             return scaledImagePath == null ? null : new URL(url.getProtocol(),
 967                     url.getHost(), url.getPort(), scaledImagePath);
 968         } catch (MalformedURLException e) {
 969             return null;
 970         }
 971     }
 972 
 973     private static String getScaledImageName(String path) {
 974         if (!isValidPath(path)) {
 975             return null;
 976         }
 977 
 978         int slash = path.lastIndexOf('/');
 979         String name = (slash < 0) ? path : path.substring(slash + 1);
 980 
 981         if (name.contains("@2x")) {
 982             return null;
 983         }
 984 
 985         int dot = name.lastIndexOf('.');
 986         String name2x = (dot < 0) ? name + "@2x"
 987                 : name.substring(0, dot) + "@2x" + name.substring(dot);
 988         return (slash < 0) ? name2x : path.substring(0, slash + 1) + name2x;
 989     }
 990 
 991     private static boolean isValidPath(String path) {
 992         return path != null &&
 993                 !path.isEmpty() &&
 994                 !path.endsWith("/") &&
 995                 !path.endsWith(".");
 996     }
 997 
 998     @Override
 999     protected PlatformWindow getPlatformWindowUnderMouse() {
1000         return CPlatformWindow.nativeGetTopmostPlatformWindowUnderMouse();
1001     }
1002 
1003     @Override
1004     public void updateScreenMenuBarUI() {
1005         if (AquaMenuBarUI.getScreenMenuBarProperty())  {
1006             UIManager.put("MenuBarUI", "com.apple.laf.AquaMenuBarUI");
1007         } else {
1008             UIManager.put("MenuBarUI", null);
1009         }
1010     }
1011 }