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