1 /*
   2  * Copyright (c) 1996, 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.awt.windows;
  27 
  28 import java.awt.peer.TaskbarPeer;
  29 import java.awt.*;
  30 import java.awt.im.InputMethodHighlight;
  31 import java.awt.im.spi.InputMethodDescriptor;
  32 import java.awt.image.*;
  33 import java.awt.peer.*;
  34 import java.awt.event.KeyEvent;
  35 import java.awt.datatransfer.Clipboard;
  36 import java.awt.TrayIcon;
  37 import java.beans.PropertyChangeListener;
  38 import java.security.AccessController;
  39 import java.security.PrivilegedAction;
  40 
  41 import sun.awt.AWTAccessor;
  42 import sun.awt.AppContext;
  43 import sun.awt.AWTAutoShutdown;
  44 import sun.awt.AWTPermissions;
  45 import sun.awt.AppContext;
  46 import sun.awt.LightweightFrame;
  47 import sun.awt.SunToolkit;
  48 import sun.awt.util.ThreadGroupUtils;
  49 import sun.awt.Win32GraphicsDevice;
  50 import sun.awt.Win32GraphicsEnvironment;
  51 import sun.awt.datatransfer.DataTransferer;
  52 import sun.java2d.d3d.D3DRenderQueue;
  53 import sun.java2d.opengl.OGLRenderQueue;
  54 
  55 import sun.misc.ManagedLocalsThread;
  56 import sun.print.PrintJob2D;
  57 
  58 import java.awt.dnd.DragSource;
  59 import java.awt.dnd.DragGestureListener;
  60 import java.awt.dnd.DragGestureEvent;
  61 import java.awt.dnd.DragGestureRecognizer;
  62 import java.awt.dnd.MouseDragGestureRecognizer;
  63 import java.awt.dnd.InvalidDnDOperationException;
  64 import java.awt.dnd.peer.DragSourceContextPeer;
  65 
  66 import java.util.Hashtable;
  67 import java.util.Locale;
  68 import java.util.Map;
  69 import java.util.Properties;
  70 
  71 import sun.font.FontManager;
  72 import sun.font.FontManagerFactory;
  73 import sun.font.SunFontManager;
  74 import sun.misc.PerformanceLogger;
  75 import sun.util.logging.PlatformLogger;
  76 
  77 public final class WToolkit extends SunToolkit implements Runnable {
  78 
  79     private static final PlatformLogger log = PlatformLogger.getLogger("sun.awt.windows.WToolkit");
  80 
  81     // Desktop property which specifies whether XP visual styles are in effect
  82     public static final String XPSTYLE_THEME_ACTIVE = "win.xpstyle.themeActive";
  83 
  84     static GraphicsConfiguration config;
  85 
  86     // System clipboard.
  87     WClipboard clipboard;
  88 
  89     // cache of font peers
  90     private Hashtable<String,FontPeer> cacheFontPeer;
  91 
  92     // Windows properties
  93     private WDesktopProperties  wprops;
  94 
  95     // Dynamic Layout Resize client code setting
  96     protected boolean dynamicLayoutSetting = false;
  97 
  98     //Is it allowed to generate events assigned to extra mouse buttons.
  99     //Set to true by default.
 100     private static boolean areExtraMouseButtonsEnabled = true;
 101 
 102     /**
 103      * Initialize JNI field and method IDs
 104      */
 105     private static native void initIDs();
 106     private static boolean loaded = false;
 107     public static void loadLibraries() {
 108         if (!loaded) {
 109             java.security.AccessController.doPrivileged(
 110                 new java.security.PrivilegedAction<Void>() {
 111                     @Override
 112                     public Void run() {
 113                         System.loadLibrary("awt");
 114                         return null;
 115                     }
 116                 });
 117             loaded = true;
 118         }
 119     }
 120 
 121     private static native String getWindowsVersion();
 122 
 123     static {
 124         loadLibraries();
 125         initIDs();
 126 
 127         // Print out which version of Windows is running
 128         if (log.isLoggable(PlatformLogger.Level.FINE)) {
 129             log.fine("Win version: " + getWindowsVersion());
 130         }
 131 
 132         AccessController.doPrivileged(
 133             new PrivilegedAction <Void> ()
 134         {
 135             @Override
 136             public Void run() {
 137                 String browserProp = System.getProperty("browser");
 138                 if (browserProp != null && browserProp.equals("sun.plugin")) {
 139                     disableCustomPalette();
 140                 }
 141                 return null;
 142             }
 143         });
 144     }
 145 
 146     private static native void disableCustomPalette();
 147 
 148     /*
 149      * Reset the static GraphicsConfiguration to the default.  Called on
 150      * startup and when display settings have changed.
 151      */
 152     public static void resetGC() {
 153         if (GraphicsEnvironment.isHeadless()) {
 154             config = null;
 155         } else {
 156           config = (GraphicsEnvironment
 157                   .getLocalGraphicsEnvironment()
 158           .getDefaultScreenDevice()
 159           .getDefaultConfiguration());
 160         }
 161     }
 162 
 163     /*
 164      * NOTE: The following embedded*() methods are non-public API intended
 165      * for internal use only.  The methods are unsupported and could go
 166      * away in future releases.
 167      *
 168      * New hook functions for using the AWT as an embedded service. These
 169      * functions replace the global C function AwtInit() which was previously
 170      * exported by awt.dll.
 171      *
 172      * When used as an embedded service, the AWT does NOT have its own
 173      * message pump. It instead relies on the parent application to provide
 174      * this functionality. embeddedInit() assumes that the thread on which it
 175      * is called is the message pumping thread. Violating this assumption
 176      * will lead to undefined behavior.
 177      *
 178      * embeddedInit must be called before the WToolkit() constructor.
 179      * embeddedDispose should be called before the applicaton terminates the
 180      * Java VM. It is currently unsafe to reinitialize the toolkit again
 181      * after it has been disposed. Instead, awt.dll must be reloaded and the
 182      * class loader which loaded WToolkit must be finalized before it is
 183      * safe to reuse AWT. Dynamic reusability may be added to the toolkit in
 184      * the future.
 185      */
 186 
 187     /**
 188      * Initializes the Toolkit for use in an embedded environment.
 189      *
 190      * @return true if the initialization succeeded; false if it failed.
 191      *         The function will fail if the Toolkit was already initialized.
 192      * @since 1.3
 193      */
 194     public static native boolean embeddedInit();
 195 
 196     /**
 197      * Disposes the Toolkit in an embedded environment. This method should
 198      * not be called on exit unless the Toolkit was constructed with
 199      * embeddedInit.
 200      *
 201      * @return true if the disposal succeeded; false if it failed. The
 202      *         function will fail if the calling thread is not the same
 203      *         thread which called embeddedInit(), or if the Toolkit was
 204      *         already disposed.
 205      * @since 1.3
 206      */
 207     public static native boolean embeddedDispose();
 208 
 209     /**
 210      * To be called after processing the event queue by users of the above
 211      * embeddedInit() function.  The reason for this additional call is that
 212      * there are some operations performed during idle time in the AwtToolkit
 213      * event loop which should also be performed during idle time in any
 214      * other native event loop.  Failure to do so could result in
 215      * deadlocks.
 216      *
 217      * This method was added at the last minute of the jdk1.4 release
 218      * to work around a specific customer problem.  As with the above
 219      * embedded*() class, this method is non-public and should not be
 220      * used by external applications.
 221      *
 222      * See bug #4526587 for more information.
 223      */
 224     public native void embeddedEventLoopIdleProcessing();
 225 
 226     static class ToolkitDisposer implements sun.java2d.DisposerRecord {
 227         @Override
 228         public void dispose() {
 229             WToolkit.postDispose();
 230         }
 231     }
 232 
 233     private final Object anchor = new Object();
 234 
 235     private static native void postDispose();
 236 
 237     private static native boolean startToolkitThread(Runnable thread, ThreadGroup rootThreadGroup);
 238 
 239     public WToolkit() {
 240         // Startup toolkit threads
 241         if (PerformanceLogger.loggingEnabled()) {
 242             PerformanceLogger.setTime("WToolkit construction");
 243         }
 244 
 245         sun.java2d.Disposer.addRecord(anchor, new ToolkitDisposer());
 246 
 247         /*
 248          * Fix for 4701990.
 249          * AWTAutoShutdown state must be changed before the toolkit thread
 250          * starts to avoid race condition.
 251          */
 252         AWTAutoShutdown.notifyToolkitThreadBusy();
 253 
 254         // Find a root TG and attach toolkit thread to it
 255         ThreadGroup rootTG = AccessController.doPrivileged(
 256                 (PrivilegedAction<ThreadGroup>) ThreadGroupUtils::getRootThreadGroup);
 257         if (!startToolkitThread(this, rootTG)) {
 258             String name = "AWT-Windows";
 259             Thread toolkitThread = new ManagedLocalsThread(rootTG, this, name);
 260             toolkitThread.setDaemon(true);
 261             toolkitThread.start();
 262         }
 263 
 264         try {
 265             synchronized(this) {
 266                 while(!inited) {
 267                     wait();
 268                 }
 269             }
 270         } catch (InterruptedException x) {
 271             // swallow the exception
 272         }
 273 
 274         // Enabled "live resizing" by default.  It remains controlled
 275         // by the native system though.
 276         setDynamicLayout(true);
 277 
 278         areExtraMouseButtonsEnabled = Boolean.parseBoolean(System.getProperty("sun.awt.enableExtraMouseButtons", "true"));
 279         //set system property if not yet assigned
 280         System.setProperty("sun.awt.enableExtraMouseButtons", ""+areExtraMouseButtonsEnabled);
 281         setExtraMouseButtonsEnabledNative(areExtraMouseButtonsEnabled);
 282     }
 283 
 284     private void registerShutdownHook() {
 285         AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 286             Thread shutdown = new ManagedLocalsThread(
 287                     ThreadGroupUtils.getRootThreadGroup(), this::shutdown);
 288             shutdown.setContextClassLoader(null);
 289             Runtime.getRuntime().addShutdownHook(shutdown);
 290             return null;
 291         });
 292      }
 293 
 294     @Override
 295     public void run() {
 296         AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 297             Thread.currentThread().setContextClassLoader(null);
 298             Thread.currentThread().setPriority(Thread.NORM_PRIORITY + 1);
 299             return null;
 300         });
 301 
 302         boolean startPump = init();
 303 
 304         if (startPump) {
 305             registerShutdownHook();
 306         }
 307 
 308         synchronized(this) {
 309             inited = true;
 310             notifyAll();
 311         }
 312 
 313         if (startPump) {
 314             eventLoop(); // will Dispose Toolkit when shutdown hook executes
 315         }
 316     }
 317 
 318     /*
 319      * eventLoop() begins the native message pump which retrieves and processes
 320      * native events.
 321      *
 322      * When shutdown() is called by the ShutdownHook added in run(), a
 323      * WM_QUIT message is posted to the Toolkit thread indicating that
 324      * eventLoop() should Dispose the toolkit and exit.
 325      */
 326     private native boolean init();
 327     private boolean inited = false;
 328 
 329     private native void eventLoop();
 330     private native void shutdown();
 331 
 332     /*
 333      * Instead of blocking the "AWT-Windows" thread uselessly on a semaphore,
 334      * use these functions. startSecondaryEventLoop() corresponds to wait()
 335      * and quitSecondaryEventLoop() corresponds to notify.
 336      *
 337      * These functions simulate blocking while allowing the AWT to continue
 338      * processing native events, eliminating a potential deadlock situation
 339      * with SendMessage.
 340      *
 341      * WARNING: startSecondaryEventLoop must only be called from the "AWT-
 342      * Windows" thread.
 343      */
 344     static native void startSecondaryEventLoop();
 345     static native void quitSecondaryEventLoop();
 346 
 347     /*
 348      * Create peer objects.
 349      */
 350 
 351     @Override
 352     public ButtonPeer createButton(Button target) {
 353         ButtonPeer peer = new WButtonPeer(target);
 354         targetCreatedPeer(target, peer);
 355         return peer;
 356     }
 357 
 358     @Override
 359     public TextFieldPeer createTextField(TextField target) {
 360         TextFieldPeer peer = new WTextFieldPeer(target);
 361         targetCreatedPeer(target, peer);
 362         return peer;
 363     }
 364 
 365     @Override
 366     public LabelPeer createLabel(Label target) {
 367         LabelPeer peer = new WLabelPeer(target);
 368         targetCreatedPeer(target, peer);
 369         return peer;
 370     }
 371 
 372     @Override
 373     public ListPeer createList(List target) {
 374         ListPeer peer = new WListPeer(target);
 375         targetCreatedPeer(target, peer);
 376         return peer;
 377     }
 378 
 379     @Override
 380     public CheckboxPeer createCheckbox(Checkbox target) {
 381         CheckboxPeer peer = new WCheckboxPeer(target);
 382         targetCreatedPeer(target, peer);
 383         return peer;
 384     }
 385 
 386     @Override
 387     public ScrollbarPeer createScrollbar(Scrollbar target) {
 388         ScrollbarPeer peer = new WScrollbarPeer(target);
 389         targetCreatedPeer(target, peer);
 390         return peer;
 391     }
 392 
 393     @Override
 394     public ScrollPanePeer createScrollPane(ScrollPane target) {
 395         ScrollPanePeer peer = new WScrollPanePeer(target);
 396         targetCreatedPeer(target, peer);
 397         return peer;
 398     }
 399 
 400     @Override
 401     public TextAreaPeer createTextArea(TextArea target) {
 402         TextAreaPeer peer = new WTextAreaPeer(target);
 403         targetCreatedPeer(target, peer);
 404         return peer;
 405     }
 406 
 407     @Override
 408     public ChoicePeer createChoice(Choice target) {
 409         ChoicePeer peer = new WChoicePeer(target);
 410         targetCreatedPeer(target, peer);
 411         return peer;
 412     }
 413 
 414     @Override
 415     public FramePeer  createFrame(Frame target) {
 416         FramePeer peer = new WFramePeer(target);
 417         targetCreatedPeer(target, peer);
 418         return peer;
 419     }
 420 
 421     @Override
 422     public FramePeer createLightweightFrame(LightweightFrame target) {
 423         FramePeer peer = new WLightweightFramePeer(target);
 424         targetCreatedPeer(target, peer);
 425         return peer;
 426     }
 427 
 428     @Override
 429     public CanvasPeer createCanvas(Canvas target) {
 430         CanvasPeer peer = new WCanvasPeer(target);
 431         targetCreatedPeer(target, peer);
 432         return peer;
 433     }
 434 
 435     @Override
 436     public void disableBackgroundErase(Canvas canvas) {
 437         WCanvasPeer peer = AWTAccessor.getComponentAccessor().getPeer(canvas);
 438         if (peer == null) {
 439             throw new IllegalStateException("Canvas must have a valid peer");
 440         }
 441         peer.disableBackgroundErase();
 442     }
 443 
 444     @Override
 445     public PanelPeer createPanel(Panel target) {
 446         PanelPeer peer = new WPanelPeer(target);
 447         targetCreatedPeer(target, peer);
 448         return peer;
 449     }
 450 
 451     @Override
 452     public WindowPeer createWindow(Window target) {
 453         WindowPeer peer = new WWindowPeer(target);
 454         targetCreatedPeer(target, peer);
 455         return peer;
 456     }
 457 
 458     @Override
 459     public DialogPeer createDialog(Dialog target) {
 460         DialogPeer peer = new WDialogPeer(target);
 461         targetCreatedPeer(target, peer);
 462         return peer;
 463     }
 464 
 465     @Override
 466     public FileDialogPeer createFileDialog(FileDialog target) {
 467         FileDialogPeer peer = new WFileDialogPeer(target);
 468         targetCreatedPeer(target, peer);
 469         return peer;
 470     }
 471 
 472     @Override
 473     public MenuBarPeer createMenuBar(MenuBar target) {
 474         MenuBarPeer peer = new WMenuBarPeer(target);
 475         targetCreatedPeer(target, peer);
 476         return peer;
 477     }
 478 
 479     @Override
 480     public MenuPeer createMenu(Menu target) {
 481         MenuPeer peer = new WMenuPeer(target);
 482         targetCreatedPeer(target, peer);
 483         return peer;
 484     }
 485 
 486     @Override
 487     public PopupMenuPeer createPopupMenu(PopupMenu target) {
 488         PopupMenuPeer peer = new WPopupMenuPeer(target);
 489         targetCreatedPeer(target, peer);
 490         return peer;
 491     }
 492 
 493     @Override
 494     public MenuItemPeer createMenuItem(MenuItem target) {
 495         MenuItemPeer peer = new WMenuItemPeer(target);
 496         targetCreatedPeer(target, peer);
 497         return peer;
 498     }
 499 
 500     @Override
 501     public CheckboxMenuItemPeer createCheckboxMenuItem(CheckboxMenuItem target) {
 502         CheckboxMenuItemPeer peer = new WCheckboxMenuItemPeer(target);
 503         targetCreatedPeer(target, peer);
 504         return peer;
 505     }
 506 
 507     @Override
 508     public RobotPeer createRobot(Robot target, GraphicsDevice screen) {
 509         // (target is unused for now)
 510         // Robot's don't need to go in the peer map since
 511         // they're not Component's
 512         return new WRobotPeer(screen);
 513     }
 514 
 515     public WEmbeddedFramePeer createEmbeddedFrame(WEmbeddedFrame target) {
 516         WEmbeddedFramePeer peer = new WEmbeddedFramePeer(target);
 517         targetCreatedPeer(target, peer);
 518         return peer;
 519     }
 520 
 521     WPrintDialogPeer createWPrintDialog(WPrintDialog target) {
 522         WPrintDialogPeer peer = new WPrintDialogPeer(target);
 523         targetCreatedPeer(target, peer);
 524         return peer;
 525     }
 526 
 527     WPageDialogPeer createWPageDialog(WPageDialog target) {
 528         WPageDialogPeer peer = new WPageDialogPeer(target);
 529         targetCreatedPeer(target, peer);
 530         return peer;
 531     }
 532 
 533     @Override
 534     public TrayIconPeer createTrayIcon(TrayIcon target) {
 535         WTrayIconPeer peer = new WTrayIconPeer(target);
 536         targetCreatedPeer(target, peer);
 537         return peer;
 538     }
 539 
 540     @Override
 541     public SystemTrayPeer createSystemTray(SystemTray target) {
 542         return new WSystemTrayPeer(target);
 543     }
 544 
 545     @Override
 546     public boolean isTraySupported() {
 547         return true;
 548     }
 549 
 550     @Override
 551     public DataTransferer getDataTransferer() {
 552         return WDataTransferer.getInstanceImpl();
 553     }
 554 
 555     @Override
 556     public KeyboardFocusManagerPeer getKeyboardFocusManagerPeer()
 557       throws HeadlessException
 558     {
 559         return WKeyboardFocusManagerPeer.getInstance();
 560     }
 561 
 562     private native void setDynamicLayoutNative(boolean b);
 563 
 564     @Override
 565     public void setDynamicLayout(boolean b) {
 566         if (b == dynamicLayoutSetting) {
 567             return;
 568         }
 569 
 570         dynamicLayoutSetting = b;
 571         setDynamicLayoutNative(b);
 572     }
 573 
 574     @Override
 575     protected boolean isDynamicLayoutSet() {
 576         return dynamicLayoutSetting;
 577     }
 578 
 579     /*
 580      * Called from lazilyLoadDynamicLayoutSupportedProperty because
 581      * Windows doesn't always send WM_SETTINGCHANGE when it should.
 582      */
 583     private native boolean isDynamicLayoutSupportedNative();
 584 
 585     @Override
 586     public boolean isDynamicLayoutActive() {
 587         return (isDynamicLayoutSet() && isDynamicLayoutSupported());
 588     }
 589 
 590     /**
 591      * Returns <code>true</code> if this frame state is supported.
 592      */
 593     @Override
 594     public boolean isFrameStateSupported(int state) {
 595         switch (state) {
 596           case Frame.NORMAL:
 597           case Frame.ICONIFIED:
 598           case Frame.MAXIMIZED_BOTH:
 599               return true;
 600           default:
 601               return false;
 602         }
 603     }
 604 
 605     static native ColorModel makeColorModel();
 606     static ColorModel screenmodel;
 607 
 608     static ColorModel getStaticColorModel() {
 609         if (GraphicsEnvironment.isHeadless()) {
 610             throw new IllegalArgumentException();
 611         }
 612         if (config == null) {
 613             resetGC();
 614         }
 615         return config.getColorModel();
 616     }
 617 
 618     @Override
 619     public ColorModel getColorModel() {
 620         return getStaticColorModel();
 621     }
 622 
 623     @Override
 624     public Insets getScreenInsets(GraphicsConfiguration gc)
 625     {
 626         return getScreenInsets(((Win32GraphicsDevice) gc.getDevice()).getScreen());
 627     }
 628 
 629     @Override
 630     public int getScreenResolution() {
 631         Win32GraphicsEnvironment ge = (Win32GraphicsEnvironment)
 632             GraphicsEnvironment.getLocalGraphicsEnvironment();
 633         return ge.getXResolution();
 634     }
 635     @Override
 636     protected native int getScreenWidth();
 637     @Override
 638     protected native int getScreenHeight();
 639     private native Insets getScreenInsets(int screen);
 640 
 641 
 642     @Override
 643     public FontMetrics getFontMetrics(Font font) {
 644         // This is an unsupported hack, but left in for a customer.
 645         // Do not remove.
 646         FontManager fm = FontManagerFactory.getInstance();
 647         if (fm instanceof SunFontManager
 648             && ((SunFontManager) fm).usePlatformFontMetrics()) {
 649             return WFontMetrics.getFontMetrics(font);
 650         }
 651         return super.getFontMetrics(font);
 652     }
 653 
 654     @Override
 655     public FontPeer getFontPeer(String name, int style) {
 656         FontPeer retval = null;
 657         String lcName = name.toLowerCase();
 658         if (null != cacheFontPeer) {
 659             retval = cacheFontPeer.get(lcName + style);
 660             if (null != retval) {
 661                 return retval;
 662             }
 663         }
 664         retval = new WFontPeer(name, style);
 665         if (retval != null) {
 666             if (null == cacheFontPeer) {
 667                 cacheFontPeer = new Hashtable<>(5, 0.9f);
 668             }
 669             if (null != cacheFontPeer) {
 670                 cacheFontPeer.put(lcName + style, retval);
 671             }
 672         }
 673         return retval;
 674     }
 675 
 676     private native void nativeSync();
 677 
 678     @Override
 679     public void sync() {
 680         // flush the GDI/DD buffers
 681         nativeSync();
 682         // now flush the OGL pipeline (this is a no-op if OGL is not enabled)
 683         OGLRenderQueue.sync();
 684         // now flush the D3D pipeline (this is a no-op if D3D is not enabled)
 685         D3DRenderQueue.sync();
 686     }
 687 
 688     @Override
 689     public PrintJob getPrintJob(Frame frame, String doctitle,
 690                                 Properties props) {
 691         return getPrintJob(frame, doctitle, null, null);
 692     }
 693 
 694     @Override
 695     public PrintJob getPrintJob(Frame frame, String doctitle,
 696                                 JobAttributes jobAttributes,
 697                                 PageAttributes pageAttributes)
 698     {
 699         if (frame == null) {
 700             throw new NullPointerException("frame must not be null");
 701         }
 702 
 703         PrintJob2D printJob = new PrintJob2D(frame, doctitle,
 704                                              jobAttributes, pageAttributes);
 705 
 706         if (printJob.printDialog() == false) {
 707             printJob = null;
 708         }
 709 
 710         return printJob;
 711     }
 712 
 713     @Override
 714     public native void beep();
 715 
 716     @Override
 717     public boolean getLockingKeyState(int key) {
 718         if (! (key == KeyEvent.VK_CAPS_LOCK || key == KeyEvent.VK_NUM_LOCK ||
 719                key == KeyEvent.VK_SCROLL_LOCK || key == KeyEvent.VK_KANA_LOCK)) {
 720             throw new IllegalArgumentException("invalid key for Toolkit.getLockingKeyState");
 721         }
 722         return getLockingKeyStateNative(key);
 723     }
 724 
 725     private native boolean getLockingKeyStateNative(int key);
 726 
 727     @Override
 728     public void setLockingKeyState(int key, boolean on) {
 729         if (! (key == KeyEvent.VK_CAPS_LOCK || key == KeyEvent.VK_NUM_LOCK ||
 730                key == KeyEvent.VK_SCROLL_LOCK || key == KeyEvent.VK_KANA_LOCK)) {
 731             throw new IllegalArgumentException("invalid key for Toolkit.setLockingKeyState");
 732         }
 733         setLockingKeyStateNative(key, on);
 734     }
 735 
 736     private native void setLockingKeyStateNative(int key, boolean on);
 737 
 738     @Override
 739     public Clipboard getSystemClipboard() {
 740         SecurityManager security = System.getSecurityManager();
 741         if (security != null) {
 742             security.checkPermission(AWTPermissions.ACCESS_CLIPBOARD_PERMISSION);
 743         }
 744         synchronized (this) {
 745             if (clipboard == null) {
 746                 clipboard = new WClipboard();
 747             }
 748         }
 749         return clipboard;
 750     }
 751 
 752     @Override
 753     protected native void loadSystemColors(int[] systemColors);
 754 
 755     public static Object targetToPeer(Object target) {
 756         return SunToolkit.targetToPeer(target);
 757     }
 758 
 759     public static void targetDisposedPeer(Object target, Object peer) {
 760         SunToolkit.targetDisposedPeer(target, peer);
 761     }
 762 
 763     /**
 764      * Returns a new input method adapter descriptor for native input methods.
 765      */
 766     @Override
 767     public InputMethodDescriptor getInputMethodAdapterDescriptor() {
 768         return new WInputMethodDescriptor();
 769     }
 770 
 771     /**
 772      * Returns a style map for the input method highlight.
 773      */
 774     @Override
 775     public Map<java.awt.font.TextAttribute,?> mapInputMethodHighlight(
 776         InputMethodHighlight highlight)
 777     {
 778         return WInputMethod.mapInputMethodHighlight(highlight);
 779     }
 780 
 781     /**
 782      * Returns whether enableInputMethods should be set to true for peered
 783      * TextComponent instances on this platform.
 784      */
 785     @Override
 786     public boolean enableInputMethodsForTextComponent() {
 787         return true;
 788     }
 789 
 790     /**
 791      * Returns the default keyboard locale of the underlying operating system
 792      */
 793     @Override
 794     public Locale getDefaultKeyboardLocale() {
 795         Locale locale = WInputMethod.getNativeLocale();
 796 
 797         if (locale == null) {
 798             return super.getDefaultKeyboardLocale();
 799         } else {
 800             return locale;
 801         }
 802     }
 803 
 804     /**
 805      * Returns a new custom cursor.
 806      */
 807     @Override
 808     public Cursor createCustomCursor(Image cursor, Point hotSpot, String name)
 809         throws IndexOutOfBoundsException {
 810         return new WCustomCursor(cursor, hotSpot, name);
 811     }
 812 
 813     /**
 814      * Returns the supported cursor size (Win32 only has one).
 815      */
 816     @Override
 817     public Dimension getBestCursorSize(int preferredWidth, int preferredHeight) {
 818         return new Dimension(WCustomCursor.getCursorWidth(),
 819                              WCustomCursor.getCursorHeight());
 820     }
 821 
 822     @Override
 823     public native int getMaximumCursorColors();
 824 
 825     static void paletteChanged() {
 826         ((Win32GraphicsEnvironment)GraphicsEnvironment
 827         .getLocalGraphicsEnvironment())
 828         .paletteChanged();
 829     }
 830 
 831     /*
 832      * Called from Toolkit native code when a WM_DISPLAYCHANGE occurs.
 833      * Have Win32GraphicsEnvironment execute the display change code on the
 834      * Event thread.
 835      */
 836     public static void displayChanged() {
 837         EventQueue.invokeLater(new Runnable() {
 838             @Override
 839             public void run() {
 840                 ((Win32GraphicsEnvironment)GraphicsEnvironment
 841                 .getLocalGraphicsEnvironment())
 842                 .displayChanged();
 843             }
 844         });
 845     }
 846 
 847     /**
 848      * create the peer for a DragSourceContext
 849      */
 850 
 851     @Override
 852     public DragSourceContextPeer createDragSourceContextPeer(DragGestureEvent dge) throws InvalidDnDOperationException {
 853         final LightweightFrame f = SunToolkit.getLightweightFrame(dge.getComponent());
 854         if (f != null) {
 855             return f.createDragSourceContextPeer(dge);
 856         }
 857 
 858         return WDragSourceContextPeer.createDragSourceContextPeer(dge);
 859     }
 860 
 861     @Override
 862     @SuppressWarnings("unchecked")
 863     public <T extends DragGestureRecognizer> T
 864         createDragGestureRecognizer(Class<T> abstractRecognizerClass,
 865                                     DragSource ds, Component c, int srcActions,
 866                                     DragGestureListener dgl)
 867     {
 868         final LightweightFrame f = SunToolkit.getLightweightFrame(c);
 869         if (f != null) {
 870             return f.createDragGestureRecognizer(abstractRecognizerClass, ds, c, srcActions, dgl);
 871         }
 872 
 873         if (MouseDragGestureRecognizer.class.equals(abstractRecognizerClass))
 874             return (T)new WMouseDragGestureRecognizer(ds, c, srcActions, dgl);
 875         else
 876             return null;
 877     }
 878 
 879     /**
 880      *
 881      */
 882 
 883     private static final String prefix  = "DnD.Cursor.";
 884     private static final String postfix = ".32x32";
 885     private static final String awtPrefix  = "awt.";
 886     private static final String dndPrefix  = "DnD.";
 887 
 888     @Override
 889     protected Object lazilyLoadDesktopProperty(String name) {
 890         if (name.startsWith(prefix)) {
 891             String cursorName = name.substring(prefix.length(), name.length()) + postfix;
 892 
 893             try {
 894                 return Cursor.getSystemCustomCursor(cursorName);
 895             } catch (AWTException awte) {
 896                 throw new RuntimeException("cannot load system cursor: " + cursorName, awte);
 897             }
 898         }
 899 
 900         if (name.equals("awt.dynamicLayoutSupported")) {
 901             return  Boolean.valueOf(isDynamicLayoutSupported());
 902         }
 903 
 904         if (WDesktopProperties.isWindowsProperty(name) ||
 905             name.startsWith(awtPrefix) || name.startsWith(dndPrefix))
 906         {
 907             synchronized(this) {
 908                 lazilyInitWProps();
 909                 return desktopProperties.get(name);
 910             }
 911         }
 912 
 913         return super.lazilyLoadDesktopProperty(name);
 914     }
 915 
 916     private synchronized void lazilyInitWProps() {
 917         if (wprops == null) {
 918             wprops = new WDesktopProperties(this);
 919             updateProperties(wprops.getProperties());
 920         }
 921     }
 922 
 923     /*
 924      * Called from lazilyLoadDesktopProperty because Windows doesn't
 925      * always send WM_SETTINGCHANGE when it should.
 926      */
 927     private synchronized boolean isDynamicLayoutSupported() {
 928         boolean nativeDynamic = isDynamicLayoutSupportedNative();
 929         lazilyInitWProps();
 930         Boolean prop = (Boolean) desktopProperties.get("awt.dynamicLayoutSupported");
 931 
 932         if (log.isLoggable(PlatformLogger.Level.FINER)) {
 933             log.finer("In WTK.isDynamicLayoutSupported()" +
 934                       "   nativeDynamic == " + nativeDynamic +
 935                       "   wprops.dynamic == " + prop);
 936         }
 937 
 938         if ((prop == null) || (nativeDynamic != prop.booleanValue())) {
 939             // We missed the WM_SETTINGCHANGE, so we pretend
 940             // we just got one - fire the propertyChange, etc.
 941             windowsSettingChange();
 942             return nativeDynamic;
 943         }
 944 
 945         return prop.booleanValue();
 946     }
 947 
 948     /*
 949      * Called from native toolkit code when WM_SETTINGCHANGE message received
 950      * Also called from lazilyLoadDynamicLayoutSupportedProperty because
 951      * Windows doesn't always send WM_SETTINGCHANGE when it should.
 952      */
 953     private void windowsSettingChange() {
 954         // JDK-8039383: Have to update the value of XPSTYLE_THEME_ACTIVE property
 955         // as soon as possible to prevent NPE and other errors because theme data
 956         // has become unavailable.
 957         final Map<String, Object> props = getWProps();
 958         if (props == null) {
 959             // props has not been initialized, so we have nothing to update
 960             return;
 961         }
 962 
 963         updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE));
 964 
 965         if (AppContext.getAppContext() == null) {
 966             // We cannot post the update to any EventQueue. Listeners will
 967             // be called on EDTs by DesktopPropertyChangeSupport
 968             updateProperties(props);
 969         } else {
 970             // Cannot update on Toolkit thread.
 971             // DesktopPropertyChangeSupport will call listeners on Toolkit
 972             // thread if it has AppContext (standalone mode)
 973             EventQueue.invokeLater(() -> updateProperties(props));
 974         }
 975     }
 976 
 977     private synchronized void updateProperties(final Map<String, Object> props) {
 978         if (null == props) {
 979             return;
 980         }
 981 
 982         updateXPStyleEnabled(props.get(XPSTYLE_THEME_ACTIVE));
 983 
 984         for (String propName : props.keySet()) {
 985             Object val = props.get(propName);
 986             if (log.isLoggable(PlatformLogger.Level.FINER)) {
 987                 log.finer("changed " + propName + " to " + val);
 988             }
 989             setDesktopProperty(propName, val);
 990         }
 991     }
 992 
 993     private synchronized Map<String, Object> getWProps() {
 994         return (wprops != null) ? wprops.getProperties() : null;
 995     }
 996 
 997     private void updateXPStyleEnabled(final Object dskProp) {
 998         ThemeReader.xpStyleEnabled = Boolean.TRUE.equals(dskProp);
 999     }
1000 
1001     @Override
1002     public synchronized void addPropertyChangeListener(String name, PropertyChangeListener pcl) {
1003         if (name == null) {
1004             // See JavaDoc for the Toolkit.addPropertyChangeListener() method
1005             return;
1006         }
1007         if ( WDesktopProperties.isWindowsProperty(name)
1008              || name.startsWith(awtPrefix)
1009              || name.startsWith(dndPrefix))
1010         {
1011             // someone is interested in Windows-specific desktop properties
1012             // we should initialize wprops
1013             lazilyInitWProps();
1014         }
1015         super.addPropertyChangeListener(name, pcl);
1016     }
1017 
1018     /*
1019      * initialize only static props here and do not try to initialize props which depends on wprops,
1020      * this should be done in lazilyLoadDesktopProperty() only.
1021      */
1022     @Override
1023     protected synchronized void initializeDesktopProperties() {
1024         desktopProperties.put("DnD.Autoscroll.initialDelay",
1025                               Integer.valueOf(50));
1026         desktopProperties.put("DnD.Autoscroll.interval",
1027                               Integer.valueOf(50));
1028         desktopProperties.put("DnD.isDragImageSupported",
1029                               Boolean.TRUE);
1030         desktopProperties.put("Shell.shellFolderManager",
1031                               "sun.awt.shell.Win32ShellFolderManager2");
1032     }
1033 
1034     /*
1035      * This returns the value for the desktop property "awt.font.desktophints"
1036      * This requires that the Windows properties have already been gathered.
1037      */
1038     @Override
1039     protected synchronized RenderingHints getDesktopAAHints() {
1040         if (wprops == null) {
1041             return null;
1042         } else {
1043             return wprops.getDesktopAAHints();
1044         }
1045     }
1046 
1047     @Override
1048     public boolean isModalityTypeSupported(Dialog.ModalityType modalityType) {
1049         return (modalityType == null) ||
1050                (modalityType == Dialog.ModalityType.MODELESS) ||
1051                (modalityType == Dialog.ModalityType.DOCUMENT_MODAL) ||
1052                (modalityType == Dialog.ModalityType.APPLICATION_MODAL) ||
1053                (modalityType == Dialog.ModalityType.TOOLKIT_MODAL);
1054     }
1055 
1056     @Override
1057     public boolean isModalExclusionTypeSupported(Dialog.ModalExclusionType exclusionType) {
1058         return (exclusionType == null) ||
1059                (exclusionType == Dialog.ModalExclusionType.NO_EXCLUDE) ||
1060                (exclusionType == Dialog.ModalExclusionType.APPLICATION_EXCLUDE) ||
1061                (exclusionType == Dialog.ModalExclusionType.TOOLKIT_EXCLUDE);
1062     }
1063 
1064     public static WToolkit getWToolkit() {
1065         WToolkit toolkit = (WToolkit)Toolkit.getDefaultToolkit();
1066         return toolkit;
1067     }
1068 
1069     /**
1070      * There are two reasons why we don't use buffer per window when
1071      * Vista's DWM (aka Aero) is enabled:
1072      * - since with DWM all windows are already double-buffered, the application
1073      *   doesn't get expose events so we don't get to use our true back-buffer,
1074      *   wasting memory and performance (this is valid for both d3d and gdi
1075      *   pipelines)
1076      * - in some cases with buffer per window enabled it is possible for the
1077      *   paint manager to redirect rendering to the screen for some operations
1078      *   (like copyArea), and since bpw uses its own BufferStrategy the
1079      *   d3d onscreen rendering support is disabled and rendering goes through
1080      *   GDI. This doesn't work well with Vista's DWM since one
1081      *   can not perform GDI and D3D operations on the same surface
1082      *   (see 6630702 for more info)
1083      *
1084      * Note: even though DWM composition state can change during the lifetime
1085      * of the application it is a rare event, and it is more often that it
1086      * is temporarily disabled (because of some app) than it is getting
1087      * permanently enabled so we can live with this approach without the
1088      * complexity of dwm state listeners and such. This can be revisited if
1089      * proved otherwise.
1090      */
1091     @Override
1092     public boolean useBufferPerWindow() {
1093         return !Win32GraphicsEnvironment.isDWMCompositionEnabled();
1094     }
1095 
1096     @Override
1097     public void grab(Window w) {
1098         final Object peer = AWTAccessor.getComponentAccessor().getPeer(w);
1099         if (peer != null) {
1100             ((WWindowPeer) peer).grab();
1101         }
1102     }
1103 
1104     @Override
1105     public void ungrab(Window w) {
1106         final Object peer = AWTAccessor.getComponentAccessor().getPeer(w);
1107         if (peer != null) {
1108             ((WWindowPeer) peer).ungrab();
1109         }
1110     }
1111 
1112     @Override
1113     public native boolean syncNativeQueue(final long timeout);
1114 
1115     @Override
1116     public boolean isDesktopSupported() {
1117         return true;
1118     }
1119     
1120     @Override
1121     public DesktopPeer createDesktopPeer(Desktop target) {
1122         return new WDesktopPeer();
1123     }
1124 
1125     @Override
1126     public boolean isTaskbarSupported() {
1127         return WTaskbarPeer.isTaskbarSupported();
1128     }
1129 
1130     @Override
1131     public TaskbarPeer createTaskbarPeer(Taskbar target) {
1132         return new WTaskbarPeer();
1133     }
1134 
1135     private static native void setExtraMouseButtonsEnabledNative(boolean enable);
1136 
1137     @Override
1138     public boolean areExtraMouseButtonsEnabled() throws HeadlessException {
1139         return areExtraMouseButtonsEnabled;
1140     }
1141 
1142     private synchronized native int getNumberOfButtonsImpl();
1143 
1144     @Override
1145     public int getNumberOfButtons(){
1146         if (numberOfButtons == 0) {
1147             numberOfButtons = getNumberOfButtonsImpl();
1148         }
1149         return (numberOfButtons > MAX_BUTTONS_SUPPORTED)? MAX_BUTTONS_SUPPORTED : numberOfButtons;
1150     }
1151 
1152     @Override
1153     public boolean isWindowOpacitySupported() {
1154         // supported in Win2K and later
1155         return true;
1156     }
1157 
1158     @Override
1159     public boolean isWindowShapingSupported() {
1160         return true;
1161     }
1162 
1163     @Override
1164     public boolean isWindowTranslucencySupported() {
1165         // supported in Win2K and later
1166         return true;
1167     }
1168 
1169     @Override
1170     public boolean isTranslucencyCapable(GraphicsConfiguration gc) {
1171         //XXX: worth checking if 8-bit? Anyway, it doesn't hurt.
1172         return true;
1173     }
1174 
1175     // On MS Windows one must use the peer.updateWindow() to implement
1176     // non-opaque windows.
1177     @Override
1178     public boolean needUpdateWindow() {
1179         return true;
1180     }
1181 }