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 final static int NUM_APPLE_COLORS = 3; 131 public final static int KEYBOARD_FOCUS_COLOR = 0; 132 public final static int INACTIVE_SELECTION_BACKGROUND_COLOR = 1; 133 public final static 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 LWCursorManager getCursorManager() { 302 return CCursorManager.getInstance(); 303 } 304 305 @Override 306 public Cursor createCustomCursor(final Image cursor, final Point hotSpot, 307 final String name) 308 throws IndexOutOfBoundsException, HeadlessException { 309 return new CCustomCursor(cursor, hotSpot, name); 310 } 311 312 @Override 313 public Dimension getBestCursorSize(final int preferredWidth, 314 final int preferredHeight) 315 throws HeadlessException { 316 return CCustomCursor.getBestCursorSize(preferredWidth, preferredHeight); 317 } 318 319 @Override 320 protected void platformCleanup() { 321 // TODO Auto-generated method stub 322 } 323 324 @Override 325 protected void platformInit() { 326 // TODO Auto-generated method stub 327 } 328 329 @Override 330 protected void platformRunMessage() { 331 // TODO Auto-generated method stub 332 } 333 334 @Override 335 protected void platformShutdown() { 336 // TODO Auto-generated method stub 337 } 338 339 class OSXPlatformFont extends sun.awt.PlatformFont 340 { 341 OSXPlatformFont(String name, int style) 342 { 343 super(name, style); 344 } 345 @Override 346 protected char getMissingGlyphCharacter() 347 { 348 // Follow up for real implementation 349 return (char)0xfff8; // see http://developer.apple.com/fonts/LastResortFont/ 350 } 351 } 352 @Override 353 @SuppressWarnings("deprecation") 354 public FontPeer getFontPeer(String name, int style) { 355 return new OSXPlatformFont(name, style); 356 } 357 358 @Override 359 protected int getScreenHeight() { 360 return GraphicsEnvironment.getLocalGraphicsEnvironment() 361 .getDefaultScreenDevice().getDefaultConfiguration().getBounds().height; 362 } 363 364 @Override 365 protected int getScreenWidth() { 366 return GraphicsEnvironment.getLocalGraphicsEnvironment() 367 .getDefaultScreenDevice().getDefaultConfiguration().getBounds().width; 368 } 369 370 @Override 371 protected void initializeDesktopProperties() { 372 super.initializeDesktopProperties(); 373 Map <Object, Object> fontHints = new HashMap<>(); 374 fontHints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); 375 fontHints.put(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); 376 desktopProperties.put(SunToolkit.DESKTOPFONTHINTS, fontHints); 377 desktopProperties.put("awt.mouse.numButtons", BUTTONS); 378 379 // These DnD properties must be set, otherwise Swing ends up spewing NPEs 380 // all over the place. The values came straight off of MToolkit. 381 desktopProperties.put("DnD.Autoscroll.initialDelay", new Integer(50)); 382 desktopProperties.put("DnD.Autoscroll.interval", new Integer(50)); 383 desktopProperties.put("DnD.Autoscroll.cursorHysteresis", new Integer(5)); 384 385 desktopProperties.put("DnD.isDragImageSupported", new Boolean(true)); 386 387 // Register DnD cursors 388 desktopProperties.put("DnD.Cursor.CopyDrop", new NamedCursor("DnD.Cursor.CopyDrop")); 389 desktopProperties.put("DnD.Cursor.MoveDrop", new NamedCursor("DnD.Cursor.MoveDrop")); 390 desktopProperties.put("DnD.Cursor.LinkDrop", new NamedCursor("DnD.Cursor.LinkDrop")); 391 desktopProperties.put("DnD.Cursor.CopyNoDrop", new NamedCursor("DnD.Cursor.CopyNoDrop")); 392 desktopProperties.put("DnD.Cursor.MoveNoDrop", new NamedCursor("DnD.Cursor.MoveNoDrop")); 393 desktopProperties.put("DnD.Cursor.LinkNoDrop", new NamedCursor("DnD.Cursor.LinkNoDrop")); 394 } 395 396 @Override 397 protected boolean syncNativeQueue(long timeout) { 398 return nativeSyncQueue(timeout); 399 } 400 401 @Override 402 public native void beep(); 403 404 @Override 405 public int getScreenResolution() throws HeadlessException { 406 return (int) ((CGraphicsDevice) GraphicsEnvironment 407 .getLocalGraphicsEnvironment().getDefaultScreenDevice()) 408 .getXResolution(); 409 } 410 411 @Override 412 public Insets getScreenInsets(final GraphicsConfiguration gc) { 413 return ((CGraphicsConfig) gc).getDevice().getScreenInsets(); 414 } 415 416 @Override 417 public void sync() { 418 // flush the OGL pipeline (this is a no-op if OGL is not enabled) 419 OGLRenderQueue.sync(); 420 // setNeedsDisplay() selector was sent to the appropriate CALayer so now 421 // we have to flush the native selectors queue. 422 flushNativeSelectors(); 423 } 424 425 @Override 426 public RobotPeer createRobot(Robot target, GraphicsDevice screen) { 427 return new CRobot(target, (CGraphicsDevice)screen); 428 } 429 430 private native boolean isCapsLockOn(); 431 432 /* 433 * NOTE: Among the keys this method is supposed to check, 434 * only Caps Lock works as a true locking key with OS X. 435 * There is no Scroll Lock key on modern Apple keyboards, 436 * and with a PC keyboard plugged in Scroll Lock is simply 437 * ignored: no LED lights up if you press it. 438 * The key located at the same position on Apple keyboards 439 * as Num Lock on PC keyboards is called Clear, doesn't lock 440 * anything and is used for entirely different purpose. 441 */ 442 @Override 443 public boolean getLockingKeyState(int keyCode) throws UnsupportedOperationException { 444 switch (keyCode) { 445 case KeyEvent.VK_NUM_LOCK: 446 case KeyEvent.VK_SCROLL_LOCK: 447 case KeyEvent.VK_KANA_LOCK: 448 throw new UnsupportedOperationException("Toolkit.getLockingKeyState"); 449 450 case KeyEvent.VK_CAPS_LOCK: 451 return isCapsLockOn(); 452 453 default: 454 throw new IllegalArgumentException("invalid key for Toolkit.getLockingKeyState"); 455 } 456 } 457 458 //Is it allowed to generate events assigned to extra mouse buttons. 459 //Set to true by default. 460 private static boolean areExtraMouseButtonsEnabled = true; 461 462 @Override 463 public boolean areExtraMouseButtonsEnabled() throws HeadlessException { 464 return areExtraMouseButtonsEnabled; 465 } 466 467 @Override 468 public int getNumberOfButtons(){ 469 return BUTTONS; 470 } 471 472 @Override 473 public boolean isTraySupported() { 474 return true; 475 } 476 477 @Override 478 public DataTransferer getDataTransferer() { 479 return CDataTransferer.getInstanceImpl(); 480 } 481 482 @Override 483 public boolean isAlwaysOnTopSupported() { 484 return true; 485 } 486 487 private static final String APPKIT_THREAD_NAME = "AppKit Thread"; 488 489 // Intended to be called from the LWCToolkit.m only. 490 private static void installToolkitThreadInJava() { 491 Thread.currentThread().setName(APPKIT_THREAD_NAME); 492 AccessController.doPrivileged((PrivilegedAction<Void>) () -> { 493 Thread.currentThread().setContextClassLoader(null); 494 return null; 495 }); 496 } 497 498 @Override 499 public boolean isWindowOpacitySupported() { 500 return true; 501 } 502 503 @Override 504 public boolean isFrameStateSupported(int state) throws HeadlessException { 505 switch (state) { 506 case Frame.NORMAL: 507 case Frame.ICONIFIED: 508 case Frame.MAXIMIZED_BOTH: 509 return true; 510 default: 511 return false; 512 } 513 } 514 515 /** 516 * Determines which modifier key is the appropriate accelerator 517 * key for menu shortcuts. 518 * <p> 519 * Menu shortcuts, which are embodied in the 520 * <code>MenuShortcut</code> class, are handled by the 521 * <code>MenuBar</code> class. 522 * <p> 523 * By default, this method returns <code>Event.CTRL_MASK</code>. 524 * Toolkit implementations should override this method if the 525 * <b>Control</b> key isn't the correct key for accelerators. 526 * @return the modifier mask on the <code>Event</code> class 527 * that is used for menu shortcuts on this toolkit. 528 * @see java.awt.MenuBar 529 * @see java.awt.MenuShortcut 530 * @since 1.1 531 */ 532 @Override 533 public int getMenuShortcutKeyMask() { 534 return Event.META_MASK; 535 } 536 537 @Override 538 public Image getImage(final String filename) { 539 final Image nsImage = checkForNSImage(filename); 540 if (nsImage != null) { 541 return nsImage; 542 } 543 544 if (imageCached(filename)) { 545 return super.getImage(filename); 546 } 547 548 String filename2x = getScaledImageName(filename); 549 return (imageExists(filename2x)) 550 ? getImageWithResolutionVariant(filename, filename2x) 551 : super.getImage(filename); 552 } 553 554 @Override 555 public Image getImage(URL url) { 556 557 if (imageCached(url)) { 558 return super.getImage(url); 559 } 560 561 URL url2x = getScaledImageURL(url); 562 return (imageExists(url2x)) 563 ? getImageWithResolutionVariant(url, url2x) : super.getImage(url); 564 } 565 566 private static final String nsImagePrefix = "NSImage://"; 567 private Image checkForNSImage(final String imageName) { 568 if (imageName == null) return null; 569 if (!imageName.startsWith(nsImagePrefix)) return null; 570 return CImage.getCreator().createImageFromName(imageName.substring(nsImagePrefix.length())); 571 } 572 573 // Thread-safe Object.equals() called from native 574 public static boolean doEquals(final Object a, final Object b, Component c) { 575 if (a == b) return true; 576 577 final boolean[] ret = new boolean[1]; 578 579 try { invokeAndWait(new Runnable() { @Override 580 public void run() { synchronized(ret) { 581 ret[0] = a.equals(b); 582 }}}, c); } catch (Exception e) { e.printStackTrace(); } 583 584 synchronized(ret) { return ret[0]; } 585 } 586 587 public static <T> T invokeAndWait(final Callable<T> callable, 588 Component component) throws Exception { 589 final CallableWrapper<T> wrapper = new CallableWrapper<>(callable); 590 invokeAndWait(wrapper, component); 591 return wrapper.getResult(); 592 } 593 594 static final class CallableWrapper<T> implements Runnable { 595 final Callable<T> callable; 596 T object; 597 Exception e; 598 599 CallableWrapper(final Callable<T> callable) { 600 this.callable = callable; 601 } 602 603 @Override 604 public void run() { 605 try { 606 object = callable.call(); 607 } catch (final Exception e) { 608 this.e = e; 609 } 610 } 611 612 public T getResult() throws Exception { 613 if (e != null) throw e; 614 return object; 615 } 616 } 617 618 /** 619 * Kicks an event over to the appropriate event queue and waits for it to 620 * finish To avoid deadlocking, we manually run the NSRunLoop while waiting 621 * Any selector invoked using ThreadUtilities performOnMainThread will be 622 * processed in doAWTRunLoop The InvocationEvent will call 623 * LWCToolkit.stopAWTRunLoop() when finished, which will stop our manual 624 * run loop. Does not dispatch native events while in the loop 625 */ 626 public static void invokeAndWait(Runnable runnable, Component component) 627 throws InvocationTargetException { 628 Objects.requireNonNull(component, "Null component provided to invokeAndWait"); 629 630 long mediator = createAWTRunLoopMediator(); 631 InvocationEvent invocationEvent = 632 new InvocationEvent(component, 633 runnable, 634 () -> { 635 if (mediator != 0) { 636 stopAWTRunLoop(mediator); 637 } 638 }, 639 true); 640 641 AppContext appContext = SunToolkit.targetToAppContext(component); 642 SunToolkit.postEvent(appContext, invocationEvent); 643 // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock 644 SunToolkit.flushPendingEvents(appContext); 645 doAWTRunLoop(mediator, false); 646 647 checkException(invocationEvent); 648 } 649 650 public static void invokeLater(Runnable event, Component component) 651 throws InvocationTargetException { 652 Objects.requireNonNull(component, "Null component provided to invokeLater"); 653 654 InvocationEvent invocationEvent = new InvocationEvent(component, event); 655 656 AppContext appContext = SunToolkit.targetToAppContext(component); 657 SunToolkit.postEvent(SunToolkit.targetToAppContext(component), invocationEvent); 658 // 3746956 - flush events from PostEventQueue to prevent them from getting stuck and causing a deadlock 659 SunToolkit.flushPendingEvents(appContext); 660 661 checkException(invocationEvent); 662 } 663 664 /** 665 * Checks if exception occurred while {@code InvocationEvent} was processed and rethrows it as 666 * an {@code InvocationTargetException} 667 * 668 * @param event the event to check for an exception 669 * @throws InvocationTargetException if exception occurred when event was processed 670 */ 671 private static void checkException(InvocationEvent event) throws InvocationTargetException { 672 Throwable eventException = event.getException(); 673 if (eventException == null) return; 674 675 if (eventException instanceof UndeclaredThrowableException) { 676 eventException = ((UndeclaredThrowableException)eventException).getUndeclaredThrowable(); 677 } 678 throw new InvocationTargetException(eventException); 679 } 680 681 /** 682 * Schedules a {@code Runnable} execution on the Appkit thread after a delay 683 * @param r a {@code Runnable} to execute 684 * @param delay a delay in milliseconds 685 */ 686 native static void performOnMainThreadAfterDelay(Runnable r, long delay); 687 688 // DnD support 689 690 @Override 691 public DragSourceContextPeer createDragSourceContextPeer( 692 DragGestureEvent dge) throws InvalidDnDOperationException { 693 final LightweightFrame f = SunToolkit.getLightweightFrame(dge.getComponent()); 694 if (f != null) { 695 return f.createDragSourceContextPeer(dge); 696 } 697 698 return CDragSourceContextPeer.createDragSourceContextPeer(dge); 699 } 700 701 @Override 702 @SuppressWarnings("unchecked") 703 public <T extends DragGestureRecognizer> T createDragGestureRecognizer( 704 Class<T> abstractRecognizerClass, DragSource ds, Component c, 705 int srcActions, DragGestureListener dgl) { 706 final LightweightFrame f = SunToolkit.getLightweightFrame(c); 707 if (f != null) { 708 return f.createDragGestureRecognizer(abstractRecognizerClass, ds, c, srcActions, dgl); 709 } 710 711 DragGestureRecognizer dgr = null; 712 713 // Create a new mouse drag gesture recognizer if we have a class match: 714 if (MouseDragGestureRecognizer.class.equals(abstractRecognizerClass)) 715 dgr = new CMouseDragGestureRecognizer(ds, c, srcActions, dgl); 716 717 return (T)dgr; 718 } 719 720 @Override 721 protected PlatformDropTarget createDropTarget(DropTarget dropTarget, 722 Component component, 723 LWComponentPeer<?, ?> peer) { 724 return new CDropTarget(dropTarget, component, peer); 725 } 726 727 // InputMethodSupport Method 728 /** 729 * Returns the default keyboard locale of the underlying operating system 730 */ 731 @Override 732 public Locale getDefaultKeyboardLocale() { 733 Locale locale = CInputMethod.getNativeLocale(); 734 735 if (locale == null) { 736 return super.getDefaultKeyboardLocale(); 737 } 738 739 return locale; 740 } 741 742 @Override 743 public InputMethodDescriptor getInputMethodAdapterDescriptor() { 744 if (sInputMethodDescriptor == null) 745 sInputMethodDescriptor = new CInputMethodDescriptor(); 746 747 return sInputMethodDescriptor; 748 } 749 750 /** 751 * Returns a map of visual attributes for thelevel description 752 * of the given input method highlight, or null if no mapping is found. 753 * The style field of the input method highlight is ignored. The map 754 * returned is unmodifiable. 755 * @param highlight input method highlight 756 * @return style attribute map, or null 757 * @since 1.3 758 */ 759 @Override 760 public Map<TextAttribute, ?> mapInputMethodHighlight(InputMethodHighlight highlight) { 761 return CInputMethod.mapInputMethodHighlight(highlight); 762 } 763 764 /** 765 * Returns key modifiers used by Swing to set up a focus accelerator key 766 * stroke. 767 */ 768 @Override 769 public int getFocusAcceleratorKeyMask() { 770 return InputEvent.CTRL_MASK | InputEvent.ALT_MASK; 771 } 772 773 /** 774 * Tests whether specified key modifiers mask can be used to enter a 775 * printable character. 776 */ 777 @Override 778 public boolean isPrintableCharacterModifiersMask(int mods) { 779 return ((mods & (InputEvent.META_MASK | InputEvent.CTRL_MASK)) == 0); 780 } 781 782 /** 783 * Returns whether popup is allowed to be shown above the task bar. 784 */ 785 @Override 786 public boolean canPopupOverlapTaskBar() { 787 return false; 788 } 789 790 private static Boolean sunAwtDisableCALayers = null; 791 792 /** 793 * Returns the value of "sun.awt.disableCALayers" property. Default 794 * value is {@code false}. 795 */ 796 public static synchronized boolean getSunAwtDisableCALayers() { 797 if (sunAwtDisableCALayers == null) { 798 sunAwtDisableCALayers = AccessController.doPrivileged( 799 new GetBooleanAction("sun.awt.disableCALayers")); 800 } 801 return sunAwtDisableCALayers; 802 } 803 804 /* 805 * Returns true if the application (one of its windows) owns keyboard focus. 806 */ 807 native boolean isApplicationActive(); 808 809 /** 810 * Returns true if AWT toolkit is embedded, false otherwise. 811 * 812 * @return true if AWT toolkit is embedded, false otherwise 813 */ 814 public static native boolean isEmbedded(); 815 816 /* 817 * Activates application ignoring other apps. 818 */ 819 public native void activateApplicationIgnoringOtherApps(); 820 821 /************************ 822 * Native methods section 823 ************************/ 824 825 static native long createAWTRunLoopMediator(); 826 /** 827 * Method to run a nested run-loop. The nested loop is spinned in the javaRunLoop mode, so selectors sent 828 * by [JNFRunLoop performOnMainThreadWaiting] are processed. 829 * @param mediator a native pointer to the mediator object created by createAWTRunLoopMediator 830 * @param processEvents if true - dispatches event while in the nested loop. Used in DnD. 831 * Additional attention is needed when using this feature as we short-circuit normal event 832 * processing which could break Appkit. 833 * (One known example is when the window is resized with the mouse) 834 * 835 * if false - all events come after exit form the nested loop 836 */ 837 static void doAWTRunLoop(long mediator, boolean processEvents) { 838 doAWTRunLoopImpl(mediator, processEvents, inAWT); 839 } 840 private static native void doAWTRunLoopImpl(long mediator, boolean processEvents, boolean inAWT); 841 static native void stopAWTRunLoop(long mediator); 842 843 private native boolean nativeSyncQueue(long timeout); 844 845 /** 846 * Just spin a single empty block synchronously. 847 */ 848 static native void flushNativeSelectors(); 849 850 @Override 851 public Clipboard createPlatformClipboard() { 852 return new CClipboard("System"); 853 } 854 855 @Override 856 public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) { 857 return (exclusionType == null) || 858 (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE) || 859 (exclusionType == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) || 860 (exclusionType == Dialog.ModalExclusionType.TOOLKIT_EXCLUDE); 861 } 862 863 @Override 864 public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) { 865 //TODO: FileDialog blocks excluded windows... 866 //TODO: Test: 2 file dialogs, separate AppContexts: a) Dialog 1 blocked, shouldn't be. Frame 4 blocked (shouldn't be). 867 return (modalityType == null) || 868 (modalityType == Dialog.ModalityType.MODELESS) || 869 (modalityType == Dialog.ModalityType.DOCUMENT_MODAL) || 870 (modalityType == Dialog.ModalityType.APPLICATION_MODAL) || 871 (modalityType == Dialog.ModalityType.TOOLKIT_MODAL); 872 } 873 874 @Override 875 public boolean isWindowShapingSupported() { 876 return true; 877 } 878 879 @Override 880 public boolean isWindowTranslucencySupported() { 881 return true; 882 } 883 884 @Override 885 public boolean isTranslucencyCapable(GraphicsConfiguration gc) { 886 return true; 887 } 888 889 @Override 890 public boolean isSwingBackbufferTranslucencySupported() { 891 return true; 892 } 893 894 @Override 895 public boolean enableInputMethodsForTextComponent() { 896 return true; 897 } 898 899 private static URL getScaledImageURL(URL url) { 900 try { 901 String scaledImagePath = getScaledImageName(url.getPath()); 902 return scaledImagePath == null ? null : new URL(url.getProtocol(), 903 url.getHost(), url.getPort(), scaledImagePath); 904 } catch (MalformedURLException e) { 905 return null; 906 } 907 } 908 909 private static String getScaledImageName(String path) { 910 if (!isValidPath(path)) { 911 return null; 912 } 913 914 int slash = path.lastIndexOf('/'); 915 String name = (slash < 0) ? path : path.substring(slash + 1); 916 917 if (name.contains("@2x")) { 918 return null; 919 } 920 921 int dot = name.lastIndexOf('.'); 922 String name2x = (dot < 0) ? name + "@2x" 923 : name.substring(0, dot) + "@2x" + name.substring(dot); 924 return (slash < 0) ? name2x : path.substring(0, slash + 1) + name2x; 925 } 926 927 private static boolean isValidPath(String path) { 928 return path != null && 929 !path.isEmpty() && 930 !path.endsWith("/") && 931 !path.endsWith("."); 932 } 933 }