1 /* 2 * Copyright (c) 2011, 2016, 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 /** 506 * Determines which modifier key is the appropriate accelerator 507 * key for menu shortcuts. 508 * <p> 509 * Menu shortcuts, which are embodied in the 510 * {@code MenuShortcut} class, are handled by the 511 * {@code MenuBar} class. 512 * <p> 513 * By default, this method returns {@code Event.CTRL_MASK}. 514 * Toolkit implementations should override this method if the 515 * <b>Control</b> key isn't the correct key for accelerators. 516 * @return the modifier mask on the {@code Event} class 517 * that is used for menu shortcuts on this toolkit. 518 * @see java.awt.MenuBar 519 * @see java.awt.MenuShortcut 520 * @since 1.1 521 */ 522 @Override 523 @SuppressWarnings("deprecation") 524 public int getMenuShortcutKeyMask() { 525 return Event.META_MASK; 526 } 527 528 @Override 529 public Image getImage(final String filename) { 530 final Image nsImage = checkForNSImage(filename); 531 if (nsImage != null) { 532 return nsImage; 533 } 534 535 if (imageCached(filename)) { 536 return super.getImage(filename); 537 } 538 539 String filename2x = getScaledImageName(filename); 540 return (imageExists(filename2x)) 541 ? getImageWithResolutionVariant(filename, filename2x) 542 : super.getImage(filename); 543 } 544 545 @Override 546 public Image getImage(URL url) { 547 548 if (imageCached(url)) { 549 return super.getImage(url); 550 } 551 552 URL url2x = getScaledImageURL(url); 553 return (imageExists(url2x)) 554 ? getImageWithResolutionVariant(url, url2x) : super.getImage(url); 555 } 556 557 private static final String nsImagePrefix = "NSImage://"; 558 private Image checkForNSImage(final String imageName) { 559 if (imageName == null) return null; 560 if (!imageName.startsWith(nsImagePrefix)) return null; 561 return CImage.getCreator().createImageFromName(imageName.substring(nsImagePrefix.length())); 562 } 563 564 // Thread-safe Object.equals() called from native 565 public static boolean doEquals(final Object a, final Object b, Component c) { 566 if (a == b) return true; 567 568 final boolean[] ret = new boolean[1]; 569 570 try { invokeAndWait(new Runnable() { @Override 571 public void run() { synchronized(ret) { 572 ret[0] = a.equals(b); 573 }}}, c); } catch (Exception e) { e.printStackTrace(); } 574 575 synchronized(ret) { return ret[0]; } 576 } 577 578 public static <T> T invokeAndWait(final Callable<T> callable, 579 Component component) throws Exception { 580 final CallableWrapper<T> wrapper = new CallableWrapper<>(callable); 581 invokeAndWait(wrapper, component); 582 return wrapper.getResult(); 583 } 584 585 static final class CallableWrapper<T> implements Runnable { 586 final Callable<T> callable; 587 T object; 588 Exception e; 589 590 CallableWrapper(final Callable<T> callable) { 591 this.callable = callable; 592 } 593 594 @Override 595 public void run() { 596 try { 597 object = callable.call(); 598 } catch (final Exception e) { 599 this.e = e; 600 } 601 } 602 603 public T getResult() throws Exception { 604 if (e != null) throw e; 605 return object; 606 } 607 } 608 609 /** 610 * Kicks an event over to the appropriate event queue and waits for it to 611 * finish To avoid deadlocking, we manually run the NSRunLoop while waiting 612 * Any selector invoked using ThreadUtilities performOnMainThread will be 613 * processed in doAWTRunLoop The InvocationEvent will call 614 * LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual 615 * run loop. Does not dispatch native events while in the loop 616 */ 617 public static void invokeAndWait(Runnable runnable, Component component) 618 throws InvocationTargetException { 619 Objects.requireNonNull(component, "Null component provided to invokeAndWait"); 620 621 long mediator = createAWTRunLoopMediator(); 622 InvocationEvent invocationEvent = 623 new InvocationEvent(component, 624 runnable, 625 () -> { 626 if (mediator != 0) { 627 stopAWTRunLoop(mediator); 628 } 629 }, 630 true); 631 632 AppContext appContext = SunToolkit.targetToAppContext(component); 633 SunToolkit.postEvent(appContext, invocationEvent); 634 // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock 635 SunToolkit.flushPendingEvents(appContext); 636 doAWTRunLoop(mediator, false); 637 638 checkException(invocationEvent); 639 } 640 641 public static void invokeLater(Runnable event, Component component) 642 throws InvocationTargetException { 643 Objects.requireNonNull(component, "Null component provided to invokeLater"); 644 645 InvocationEvent invocationEvent = new InvocationEvent(component, event); 646 647 AppContext appContext = SunToolkit.targetToAppContext(component); 648 SunToolkit.postEvent(SunToolkit.targetToAppContext(component), invocationEvent); 649 // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock 650 SunToolkit.flushPendingEvents(appContext); 651 652 checkException(invocationEvent); 653 } 654 655 /** 656 * Checks if exception occurred while {@code InvocationEvent} was processed and rethrows it as 657 * an {@code InvocationTargetException} 658 * 659 * @param event the event to check for an exception 660 * @throws InvocationTargetException if exception occurred when event was processed 661 */ 662 private static void checkException(InvocationEvent event) throws InvocationTargetException { 663 Throwable eventException = event.getException(); 664 if (eventException == null) return; 665 666 if (eventException instanceof UndeclaredThrowableException) { 667 eventException = ((UndeclaredThrowableException)eventException).getUndeclaredThrowable(); 668 } 669 throw new InvocationTargetException(eventException); 670 } 671 672 /** 673 * Schedules a {@code Runnable} execution on the Appkit thread after a delay 674 * @param r a {@code Runnable} to execute 675 * @param delay a delay in milliseconds 676 */ 677 static native void performOnMainThreadAfterDelay(Runnable r, long delay); 678 679 // DnD support 680 681 @Override 682 public DragSourceContextPeer createDragSourceContextPeer( 683 DragGestureEvent dge) throws InvalidDnDOperationException { 684 final LightweightFrame f = SunToolkit.getLightweightFrame(dge.getComponent()); 685 if (f != null) { 686 return f.createDragSourceContextPeer(dge); 687 } 688 689 return CDragSourceContextPeer.createDragSourceContextPeer(dge); 690 } 691 692 @Override 693 @SuppressWarnings("unchecked") 694 public <T extends DragGestureRecognizer> T createDragGestureRecognizer( 695 Class<T> abstractRecognizerClass, DragSource ds, Component c, 696 int srcActions, DragGestureListener dgl) { 697 final LightweightFrame f = SunToolkit.getLightweightFrame(c); 698 if (f != null) { 699 return f.createDragGestureRecognizer(abstractRecognizerClass, ds, c, srcActions, dgl); 700 } 701 702 DragGestureRecognizer dgr = null; 703 704 // Create a new mouse drag gesture recognizer if we have a class match: 705 if (MouseDragGestureRecognizer.class.equals(abstractRecognizerClass)) 706 dgr = new CMouseDragGestureRecognizer(ds, c, srcActions, dgl); 707 708 return (T)dgr; 709 } 710 711 @Override 712 protected PlatformDropTarget createDropTarget(DropTarget dropTarget, 713 Component component, 714 LWComponentPeer<?, ?> peer) { 715 return new CDropTarget(dropTarget, component, peer); 716 } 717 718 // InputMethodSupport Method 719 /** 720 * Returns the default keyboard locale of the underlying operating system 721 */ 722 @Override 723 public Locale getDefaultKeyboardLocale() { 724 Locale locale = CInputMethod.getNativeLocale(); 725 726 if (locale == null) { 727 return super.getDefaultKeyboardLocale(); 728 } 729 730 return locale; 731 } 732 733 @Override 734 public InputMethodDescriptor getInputMethodAdapterDescriptor() { 735 if (sInputMethodDescriptor == null) 736 sInputMethodDescriptor = new CInputMethodDescriptor(); 737 738 return sInputMethodDescriptor; 739 } 740 741 /** 742 * Returns a map of visual attributes for thelevel description 743 * of the given input method highlight, or null if no mapping is found. 744 * The style field of the input method highlight is ignored. The map 745 * returned is unmodifiable. 746 * @param highlight input method highlight 747 * @return style attribute map, or null 748 * @since 1.3 749 */ 750 @Override 751 public Map<TextAttribute, ?> mapInputMethodHighlight(InputMethodHighlight highlight) { 752 return CInputMethod.mapInputMethodHighlight(highlight); 753 } 754 755 /** 756 * Returns key modifiers used by Swing to set up a focus accelerator key 757 * stroke. 758 */ 759 @Override 760 @SuppressWarnings("deprecation") 761 public int getFocusAcceleratorKeyMask() { 762 return InputEvent.CTRL_MASK | InputEvent.ALT_MASK; 763 } 764 765 /** 766 * Tests whether specified key modifiers mask can be used to enter a 767 * printable character. 768 */ 769 @Override 770 @SuppressWarnings("deprecation") 771 public boolean isPrintableCharacterModifiersMask(int mods) { 772 return ((mods & (InputEvent.META_MASK | InputEvent.CTRL_MASK)) == 0); 773 } 774 775 /** 776 * Returns whether popup is allowed to be shown above the task bar. 777 */ 778 @Override 779 public boolean canPopupOverlapTaskBar() { 780 return false; 781 } 782 783 private static Boolean sunAwtDisableCALayers = null; 784 785 /** 786 * Returns the value of "sun.awt.disableCALayers" property. Default 787 * value is {@code false}. 788 */ 789 public static synchronized boolean getSunAwtDisableCALayers() { 790 if (sunAwtDisableCALayers == null) { 791 sunAwtDisableCALayers = AccessController.doPrivileged( 792 new GetBooleanAction("sun.awt.disableCALayers")); 793 } 794 return sunAwtDisableCALayers; 795 } 796 797 /* 798 * Returns true if the application (one of its windows) owns keyboard focus. 799 */ 800 native boolean isApplicationActive(); 801 802 /** 803 * Returns true if AWT toolkit is embedded, false otherwise. 804 * 805 * @return true if AWT toolkit is embedded, false otherwise 806 */ 807 public static native boolean isEmbedded(); 808 809 /* 810 * Activates application ignoring other apps. 811 */ 812 public native void activateApplicationIgnoringOtherApps(); 813 814 /************************ 815 * Native methods section 816 ************************/ 817 818 static native long createAWTRunLoopMediator(); 819 /** 820 * Method to run a nested run-loop. The nested loop is spinned in the javaRunLoop mode, so selectors sent 821 * by [JNFRunLoop performOnMainThreadWaiting] are processed. 822 * @param mediator a native pointer to the mediator object created by createAWTRunLoopMediator 823 * @param processEvents if true - dispatches event while in the nested loop. Used in DnD. 824 * Additional attention is needed when using this feature as we short-circuit normal event 825 * processing which could break Appkit. 826 * (One known example is when the window is resized with the mouse) 827 * 828 * if false - all events come after exit form the nested loop 829 */ 830 static void doAWTRunLoop(long mediator, boolean processEvents) { 831 doAWTRunLoopImpl(mediator, processEvents, inAWT); 832 } 833 private static native void doAWTRunLoopImpl(long mediator, boolean processEvents, boolean inAWT); 834 static native void stopAWTRunLoop(long mediator); 835 836 private native boolean nativeSyncQueue(long timeout); 837 838 /** 839 * Just spin a single empty block synchronously. 840 */ 841 static native void flushNativeSelectors(); 842 843 @Override 844 public Clipboard createPlatformClipboard() { 845 return new CClipboard("System"); 846 } 847 848 @Override 849 public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) { 850 return (exclusionType == null) || 851 (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE) || 852 (exclusionType == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) || 853 (exclusionType == Dialog.ModalExclusionType.TOOLKIT_EXCLUDE); 854 } 855 856 @Override 857 public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) { 858 //TODO: FileDialog blocks excluded windows... 859 //TODO: Test: 2 file dialogs, separate AppContexts: a) Dialog 1 blocked, shouldn't be. Frame 4 blocked (shouldn't be). 860 return (modalityType == null) || 861 (modalityType == Dialog.ModalityType.MODELESS) || 862 (modalityType == Dialog.ModalityType.DOCUMENT_MODAL) || 863 (modalityType == Dialog.ModalityType.APPLICATION_MODAL) || 864 (modalityType == Dialog.ModalityType.TOOLKIT_MODAL); 865 } 866 867 @Override 868 public boolean isWindowShapingSupported() { 869 return true; 870 } 871 872 @Override 873 public boolean isWindowTranslucencySupported() { 874 return true; 875 } 876 877 @Override 878 public boolean isTranslucencyCapable(GraphicsConfiguration gc) { 879 return true; 880 } 881 882 @Override 883 public boolean isSwingBackbufferTranslucencySupported() { 884 return true; 885 } 886 887 @Override 888 public boolean enableInputMethodsForTextComponent() { 889 return true; 890 } 891 892 private static URL getScaledImageURL(URL url) { 893 try { 894 String scaledImagePath = getScaledImageName(url.getPath()); 895 return scaledImagePath == null ? null : new URL(url.getProtocol(), 896 url.getHost(), url.getPort(), scaledImagePath); 897 } catch (MalformedURLException e) { 898 return null; 899 } 900 } 901 902 private static String getScaledImageName(String path) { 903 if (!isValidPath(path)) { 904 return null; 905 } 906 907 int slash = path.lastIndexOf('/'); 908 String name = (slash < 0) ? path : path.substring(slash + 1); 909 910 if (name.contains("@2x")) { 911 return null; 912 } 913 914 int dot = name.lastIndexOf('.'); 915 String name2x = (dot < 0) ? name + "@2x" 916 : name.substring(0, dot) + "@2x" + name.substring(dot); 917 return (slash < 0) ? name2x : path.substring(0, slash + 1) + name2x; 918 } 919 920 private static boolean isValidPath(String path) { 921 return path != null && 922 !path.isEmpty() && 923 !path.endsWith("/") && 924 !path.endsWith("."); 925 } 926 927 @Override 928 protected PlatformWindow getPlatformWindowUnderMouse() { 929 return CPlatformWindow.nativeGetTopmostPlatformWindowUnderMouse(); 930 } 931 932 @Override 933 public void updateScreenMenuBarUI() { 934 if (AquaMenuBarUI.getScreenMenuBarProperty()) { 935 UIManager.put("MenuBarUI", "com.apple.laf.AquaMenuBarUI"); 936 } else { 937 UIManager.put("MenuBarUI", null); 938 } 939 } 940 }