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