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