1 /*
   2  * Copyright (c) 2010, 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 com.sun.javafx.tk.quantum;
  27 
  28 import javafx.application.ConditionalFeature;
  29 import javafx.geometry.Dimension2D;
  30 import javafx.scene.image.Image;
  31 import javafx.scene.input.Dragboard;
  32 import javafx.scene.input.InputMethodRequests;
  33 import javafx.scene.input.KeyCode;
  34 import javafx.scene.input.KeyEvent;
  35 import javafx.scene.input.TransferMode;
  36 import javafx.scene.paint.Color;
  37 import javafx.scene.paint.CycleMethod;
  38 import javafx.scene.paint.ImagePattern;
  39 import javafx.scene.paint.LinearGradient;
  40 import javafx.scene.paint.RadialGradient;
  41 import javafx.scene.paint.Stop;
  42 import javafx.scene.shape.ClosePath;
  43 import javafx.scene.shape.CubicCurveTo;
  44 import javafx.scene.shape.FillRule;
  45 import javafx.scene.shape.LineTo;
  46 import javafx.scene.shape.MoveTo;
  47 import javafx.scene.shape.PathElement;
  48 import javafx.scene.shape.QuadCurveTo;
  49 import javafx.scene.shape.SVGPath;
  50 import javafx.scene.shape.StrokeLineCap;
  51 import javafx.scene.shape.StrokeLineJoin;
  52 import javafx.scene.shape.StrokeType;
  53 import javafx.stage.FileChooser;
  54 import javafx.stage.Modality;
  55 import javafx.stage.StageStyle;
  56 import javafx.stage.Window;
  57 import java.io.File;
  58 import java.io.InputStream;
  59 import java.nio.ByteBuffer;
  60 import java.nio.IntBuffer;
  61 import java.security.AccessControlContext;
  62 import java.security.AccessController;
  63 import java.security.PrivilegedAction;
  64 import java.util.ArrayList;
  65 import java.util.Arrays;
  66 import java.util.Collections;
  67 import java.util.HashMap;
  68 import java.util.List;
  69 import java.util.Map;
  70 import java.util.Set;
  71 import java.util.concurrent.CountDownLatch;
  72 import java.util.concurrent.Future;
  73 import java.util.concurrent.TimeUnit;
  74 import java.util.concurrent.atomic.AtomicBoolean;
  75 import java.util.function.Supplier;
  76 import com.sun.glass.ui.Application;
  77 import com.sun.glass.ui.Clipboard;
  78 import com.sun.glass.ui.ClipboardAssistance;
  79 import com.sun.glass.ui.CommonDialogs;
  80 import com.sun.glass.ui.CommonDialogs.FileChooserResult;
  81 import com.sun.glass.ui.EventLoop;
  82 import com.sun.glass.ui.Screen;
  83 import com.sun.glass.ui.Timer;
  84 import com.sun.glass.ui.View;
  85 import com.sun.javafx.PlatformUtil;
  86 import com.sun.javafx.application.PlatformImpl;
  87 import com.sun.javafx.embed.HostInterface;
  88 import com.sun.javafx.geom.Path2D;
  89 import com.sun.javafx.geom.PathIterator;
  90 import com.sun.javafx.geom.Shape;
  91 import com.sun.javafx.geom.transform.BaseTransform;
  92 import com.sun.javafx.perf.PerformanceTracker;
  93 import com.sun.javafx.runtime.async.AbstractRemoteResource;
  94 import com.sun.javafx.runtime.async.AsyncOperationListener;
  95 import com.sun.javafx.scene.text.HitInfo;
  96 import com.sun.javafx.scene.text.TextLayoutFactory;
  97 import com.sun.javafx.sg.prism.NGNode;
  98 import com.sun.javafx.tk.AppletWindow;
  99 import com.sun.javafx.tk.CompletionListener;
 100 import com.sun.javafx.tk.FileChooserType;
 101 import com.sun.javafx.tk.FontLoader;
 102 import com.sun.javafx.tk.ImageLoader;
 103 import com.sun.javafx.tk.PlatformImage;
 104 import com.sun.javafx.tk.RenderJob;
 105 import com.sun.javafx.tk.ScreenConfigurationAccessor;
 106 import com.sun.javafx.tk.TKClipboard;
 107 import com.sun.javafx.tk.TKDragGestureListener;
 108 import com.sun.javafx.tk.TKDragSourceListener;
 109 import com.sun.javafx.tk.TKDropTargetListener;
 110 import com.sun.javafx.tk.TKScene;
 111 import com.sun.javafx.tk.TKScreenConfigurationListener;
 112 import com.sun.javafx.tk.TKStage;
 113 import com.sun.javafx.tk.TKSystemMenu;
 114 import com.sun.javafx.tk.Toolkit;
 115 import com.sun.prism.BasicStroke;
 116 import com.sun.prism.Graphics;
 117 import com.sun.prism.GraphicsPipeline;
 118 import com.sun.prism.PixelFormat;
 119 import com.sun.prism.RTTexture;
 120 import com.sun.prism.ResourceFactory;
 121 import com.sun.prism.ResourceFactoryListener;
 122 import com.sun.prism.Texture.WrapMode;
 123 import com.sun.prism.impl.Disposer;
 124 import com.sun.prism.impl.PrismSettings;
 125 import com.sun.scenario.DelayedRunnable;
 126 import com.sun.scenario.animation.AbstractMasterTimer;
 127 import com.sun.scenario.effect.FilterContext;
 128 import com.sun.scenario.effect.Filterable;
 129 import com.sun.scenario.effect.impl.prism.PrFilterContext;
 130 import com.sun.scenario.effect.impl.prism.PrImage;
 131 import com.sun.javafx.logging.PulseLogger;
 132 import static com.sun.javafx.logging.PulseLogger.PULSE_LOGGING_ENABLED;
 133 import com.sun.prism.impl.ManagedResource;
 134 
 135 public final class QuantumToolkit extends Toolkit {
 136 
 137     public static final boolean verbose =
 138             AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> Boolean.getBoolean("quantum.verbose"));
 139 
 140     public static final boolean pulseDebug =
 141             AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> Boolean.getBoolean("quantum.pulse"));
 142 
 143     private static final boolean multithreaded =
 144             AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
 145                 // If it is not specified, or it is true, then it should
 146                 // be true. Otherwise it should be false.
 147                 String value = System.getProperty("quantum.multithreaded");
 148                 if (value == null) return true;
 149                 final boolean result = Boolean.parseBoolean(value);
 150                 if (verbose) {
 151                     System.out.println(result ? "Multi-Threading Enabled" : "Multi-Threading Disabled");
 152                 }
 153                 return result;
 154             });
 155 
 156     private static boolean debug =
 157             AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> Boolean.getBoolean("quantum.debug"));
 158 
 159     private static Integer pulseHZ =
 160             AccessController.doPrivileged((PrivilegedAction<Integer>) () -> Integer.getInteger("javafx.animation.pulse"));
 161 
 162     static final boolean liveResize =
 163             AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
 164                 boolean isSWT = "swt".equals(System.getProperty("glass.platform"));
 165                 String result = (PlatformUtil.isMac() || PlatformUtil.isWindows()) && !isSWT ? "true" : "false";
 166                 return "true".equals(System.getProperty("javafx.live.resize", result));
 167             });
 168 
 169     static final boolean drawInPaint =
 170             AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
 171                 boolean isSWT = "swt".equals(System.getProperty("glass.platform"));
 172                 String result = PlatformUtil.isMac() && isSWT ? "true" : "false";
 173                 return "true".equals(System.getProperty("javafx.draw.in.paint", result));});
 174 
 175     private static boolean singleThreaded =
 176             AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
 177                 Boolean result = Boolean.getBoolean("quantum.singlethreaded");
 178                 if (/*verbose &&*/ result) {
 179                     System.out.println("Warning: Single GUI Threadiong is enabled, FPS should be slower");
 180                 }
 181                 return result;
 182             });
 183 
 184     private static boolean noRenderJobs =
 185             AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> {
 186                 Boolean result = Boolean.getBoolean("quantum.norenderjobs");
 187                 if (/*verbose &&*/ result) {
 188                     System.out.println("Warning: Quantum will not submit render jobs, nothing should draw");
 189                 }
 190                 return result;
 191             });
 192 
 193     private AtomicBoolean           toolkitRunning = new AtomicBoolean(false);
 194     private AtomicBoolean           animationRunning = new AtomicBoolean(false);
 195     private AtomicBoolean           nextPulseRequested = new AtomicBoolean(false);
 196     private AtomicBoolean           pulseRunning = new AtomicBoolean(false);
 197     private int                     inPulse = 0;
 198     private CountDownLatch          launchLatch = new CountDownLatch(1);
 199 
 200     final int                       PULSE_INTERVAL = (int)(TimeUnit.SECONDS.toMillis(1L) / getRefreshRate());
 201     final int                       FULLSPEED_INTERVAL = 1;     // ms
 202     boolean                         nativeSystemVsync = false;
 203     private float                   _maxPixelScale;
 204     private Runnable                pulseRunnable, userRunnable, timerRunnable;
 205     private Timer                   pulseTimer = null;
 206     private Thread                  shutdownHook = null;
 207     private PaintCollector          collector;
 208     private QuantumRenderer         renderer;
 209     private GraphicsPipeline        pipeline;
 210 
 211     private ClassLoader             ccl;
 212 
 213     private HashMap<Object,EventLoop> eventLoopMap = null;
 214 
 215     private final PerformanceTracker perfTracker = new PerformanceTrackerImpl();
 216 
 217     @Override public boolean init() {
 218         /*
 219          * Glass Mac, X11 need Application.setDeviceDetails to happen prior to Glass Application.Run
 220          */
 221         renderer = QuantumRenderer.getInstance();
 222         collector = PaintCollector.createInstance(this);
 223         pipeline = GraphicsPipeline.getPipeline();
 224 
 225         /* shutdown the pipeline on System.exit, ^c
 226          * needed with X11 and Windows, see RT-32501
 227          */
 228         shutdownHook = new Thread("Glass/Prism Shutdown Hook") {
 229             @Override public void run() {
 230                 dispose();
 231             }
 232         };
 233         AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 234             Runtime.getRuntime().addShutdownHook(shutdownHook);
 235             return null;
 236         });
 237         return true;
 238     }
 239 
 240     /**
 241      * This method is invoked by PlatformImpl. It is typically called on the main
 242      * thread, NOT the JavaFX Application Thread. The userStartupRunnable will
 243      * be invoked on the JavaFX Application Thread.
 244      *
 245      * @param userStartupRunnable A runnable invoked on the JavaFX Application Thread
 246      *                            that allows the system to perform some startup
 247      *                            functionality after the toolkit has been initialized.
 248      */
 249     @Override public void startup(final Runnable userStartupRunnable) {
 250         // Save the context class loader of the launcher thread
 251         ccl = Thread.currentThread().getContextClassLoader();
 252 
 253         try {
 254             this.userRunnable = userStartupRunnable;
 255 
 256             // Ensure that the toolkit can only be started here
 257             Application.run(() -> runToolkit());
 258         } catch (RuntimeException ex) {
 259             if (verbose) {
 260                 ex.printStackTrace();
 261             }
 262             throw ex;
 263         } catch (Throwable t) {
 264             if (verbose) {
 265                 t.printStackTrace();
 266             }
 267             throw new RuntimeException(t);
 268         }
 269 
 270         try {
 271             launchLatch.await();
 272         } catch (InterruptedException ie) {
 273             ie.printStackTrace();
 274         }
 275     }
 276 
 277     // restart the toolkit if previously terminated
 278     private void assertToolkitRunning() {
 279         // not implemented
 280     }
 281 
 282     boolean shouldWaitForRenderingToComplete() {
 283         return !multithreaded;
 284     }
 285 
 286     /**
 287      * Method to initialize the Scene Graph on the JavaFX application thread.
 288      * Specifically, we will do static initialization for those classes in
 289      * the javafx.stage, javafx.scene, and javafx.controls packages necessary
 290      * to allow subsequent construction of the Scene or any Node, including
 291      * a PopupControl, on a background thread.
 292      *
 293      * This method is called on the JavaFX application thread.
 294      */
 295     private static void initSceneGraph() {
 296         // It is both necessary and sufficient to call a static method on the
 297         // Screen class to allow PopupControl instances to be created on any thread.
 298         javafx.stage.Screen.getPrimary();
 299     }
 300 
 301     // Called by Glass from Application.run()
 302     void runToolkit() {
 303         Thread user = Thread.currentThread();
 304 
 305         if (!toolkitRunning.getAndSet(true)) {
 306             user.setName("JavaFX Application Thread");
 307             // Set context class loader to the same as the thread that called startup
 308             user.setContextClassLoader(ccl);
 309             setFxUserThread(user);
 310 
 311             // Glass screens were inited in Application.run(), assign adapters
 312             assignScreensAdapters();
 313             /*
 314              *  Glass Application instance is now valid - create the ResourceFactory
 315              *  on the render thread
 316              */
 317             renderer.createResourceFactory();
 318 
 319             pulseRunnable = () -> QuantumToolkit.this.pulse();
 320             timerRunnable = () -> {
 321                 try {
 322                     QuantumToolkit.this.postPulse();
 323                 } catch (Throwable th) {
 324                     th.printStackTrace(System.err);
 325                 }
 326             };
 327             pulseTimer = Application.GetApplication().createTimer(timerRunnable);
 328 
 329             Application.GetApplication().setEventHandler(new Application.EventHandler() {
 330                 @Override public void handleQuitAction(Application app, long time) {
 331                     GlassStage.requestClosingAllWindows();
 332                 }
 333 
 334                 @Override public boolean handleThemeChanged(String themeName) {
 335                     return PlatformImpl.setAccessibilityTheme(themeName);
 336                 }
 337             });
 338         }
 339         // Initialize JavaFX scene graph
 340         initSceneGraph();
 341         launchLatch.countDown();
 342         try {
 343             Application.invokeAndWait(this.userRunnable);
 344 
 345             if (getMasterTimer().isFullspeed()) {
 346                 /*
 347                  * FULLSPEED_INTVERVAL workaround
 348                  *
 349                  * Application.invokeLater(pulseRunnable);
 350                  */
 351                 pulseTimer.start(FULLSPEED_INTERVAL);
 352             } else {
 353                 nativeSystemVsync = Screen.getVideoRefreshPeriod() != 0.0;
 354                 if (nativeSystemVsync) {
 355                     // system supports vsync
 356                     pulseTimer.start();
 357                 } else {
 358                     // rely on millisecond resolution timer to provide
 359                     // nominal pulse sync and use pulse hinting on
 360                     // synchronous pipelines to fine tune the interval
 361                     pulseTimer.start(PULSE_INTERVAL);
 362                 }
 363             }
 364         } catch (Throwable th) {
 365             th.printStackTrace(System.err);
 366         } finally {
 367             if (PrismSettings.verbose) {
 368                 System.err.println(" vsync: " + PrismSettings.isVsyncEnabled +
 369                                    " vpipe: " + pipeline.isVsyncSupported());
 370             }
 371             PerformanceTracker.logEvent("Toolkit.startup - finished");
 372         }
 373     }
 374 
 375     /**
 376      * Runs the specified supplier, releasing the renderLock if needed.
 377      * This is called by glass event handlers for Window, View, and
 378      * Accessible.
 379      * @param <T> the type of the return value
 380      * @param supplier the supplier to be run
 381      * @return the return value from calling supplier.get()
 382      */
 383     public static <T> T runWithoutRenderLock(Supplier<T> supplier) {
 384         final boolean locked = ViewPainter.renderLock.isHeldByCurrentThread();
 385         try {
 386             if (locked) {
 387                 ViewPainter.renderLock.unlock();
 388             }
 389             return supplier.get();
 390         } finally {
 391             if (locked) {
 392                 ViewPainter.renderLock.lock();
 393             }
 394         }
 395     }
 396 
 397     /**
 398      * Runs the specified supplier, first acquiring the renderLock.
 399      * The lock is released when done.
 400      * @param <T> the type of the return value
 401      * @param supplier the supplier to be run
 402      * @return the return value from calling supplier.get()
 403      */
 404     public static <T> T runWithRenderLock(Supplier<T> supplier) {
 405         ViewPainter.renderLock.lock();
 406         try {
 407             return supplier.get();
 408         } finally {
 409             ViewPainter.renderLock.unlock();
 410         }
 411     }
 412 
 413     boolean hasNativeSystemVsync() {
 414         return nativeSystemVsync;
 415     }
 416 
 417     boolean isVsyncEnabled() {
 418         return (PrismSettings.isVsyncEnabled &&
 419                 pipeline.isVsyncSupported());
 420     }
 421 
 422     @Override public void checkFxUserThread() {
 423         super.checkFxUserThread();
 424         renderer.checkRendererIdle();
 425     }
 426 
 427     protected static Thread getFxUserThread() {
 428         return Toolkit.getFxUserThread();
 429     }
 430 
 431     @Override public Future addRenderJob(RenderJob r) {
 432         // Do not run any render jobs (this is for benchmarking only)
 433         if (noRenderJobs) {
 434             CompletionListener listener = r.getCompletionListener();
 435             if (r instanceof PaintRenderJob) {
 436                 ((PaintRenderJob)r).getScene().setPainting(false);
 437             }
 438             if (listener != null) {
 439                 try {
 440                     listener.done(r);
 441                 } catch (Throwable th) {
 442                     th.printStackTrace();
 443                 }
 444             }
 445             return null;
 446         }
 447         // Run the render job in the UI thread (this is for benchmarking only)
 448         if (singleThreaded) {
 449             r.run();
 450             return null;
 451         }
 452         return (renderer.submitRenderJob(r));
 453     }
 454 
 455     void postPulse() {
 456         if (toolkitRunning.get() &&
 457             (animationRunning.get() || nextPulseRequested.get() || collector.hasDirty()) &&
 458             !setPulseRunning()) {
 459 
 460             Application.invokeLater(pulseRunnable);
 461 
 462             if (debug) {
 463                 System.err.println("QT.postPulse@(" + System.nanoTime() + "): " + pulseString());
 464             }
 465         } else if (debug) {
 466             System.err.println("QT.postPulse#(" + System.nanoTime() + ") DROP: " + pulseString());
 467         }
 468     }
 469 
 470     private String pulseString() {
 471         return ((toolkitRunning.get() ? "T" : "t") +
 472                 (animationRunning.get() ? "A" : "a") +
 473                 (pulseRunning.get() ? "P" : "p") +
 474                 (nextPulseRequested.get() ? "N" : "n") +
 475                 (collector.hasDirty() ? "D" : "d"));
 476     }
 477 
 478     private boolean setPulseRunning() {
 479         return (pulseRunning.getAndSet(true));
 480     }
 481 
 482     private void endPulseRunning() {
 483         pulseRunning.set(false);
 484         if (debug) {
 485             System.err.println("QT.endPulse: " + System.nanoTime());
 486         }
 487     }
 488 
 489     protected void pulse() {
 490         pulse(true);
 491     }
 492 
 493     void pulse(boolean collect) {
 494         try {
 495             inPulse++;
 496             if (PULSE_LOGGING_ENABLED) {
 497                 PulseLogger.pulseStart();
 498             }
 499 
 500             if (!toolkitRunning.get()) {
 501                 return;
 502             }
 503             nextPulseRequested.set(false);
 504             if (animationRunnable != null) {
 505                 animationRunning.set(true);
 506                 animationRunnable.run();
 507             } else {
 508                 animationRunning.set(false);
 509             }
 510             firePulse();
 511             if (collect) collector.renderAll();
 512         } finally {
 513             inPulse--;
 514             endPulseRunning();
 515             if (PULSE_LOGGING_ENABLED) {
 516                 PulseLogger.pulseEnd();
 517             }
 518         }
 519     }
 520 
 521     void vsyncHint() {
 522         if (isVsyncEnabled()) {
 523             if (debug) {
 524                 System.err.println("QT.vsyncHint: postPulse: " + System.nanoTime());
 525             }
 526             postPulse();
 527         }
 528     }
 529 
 530     @Override  public AppletWindow createAppletWindow(long parent, String serverName) {
 531         GlassAppletWindow parentWindow = new GlassAppletWindow(parent, serverName);
 532         // Make this the parent window for all future Stages
 533         WindowStage.setAppletWindow(parentWindow);
 534         return parentWindow;
 535     }
 536 
 537     @Override public void closeAppletWindow() {
 538         GlassAppletWindow gaw = WindowStage.getAppletWindow();
 539         if (null != gaw) {
 540             gaw.dispose();
 541             WindowStage.setAppletWindow(null);
 542             // any further strong refs will be in the applet itself
 543         }
 544     }
 545 
 546     @Override public TKStage createTKStage(Window peerWindow, boolean securityDialog, StageStyle stageStyle, boolean primary, Modality modality, TKStage owner, boolean rtl, AccessControlContext acc) {
 547         assertToolkitRunning();
 548         WindowStage stage = new WindowStage(peerWindow, securityDialog, stageStyle, modality, owner);
 549         stage.setSecurityContext(acc);
 550         if (primary) {
 551             stage.setIsPrimary();
 552         }
 553         stage.setRTL(rtl);
 554         stage.init(systemMenu);
 555         return stage;
 556     }
 557 
 558     @Override public boolean canStartNestedEventLoop() {
 559         return inPulse == 0;
 560     }
 561 
 562     @Override public Object enterNestedEventLoop(Object key) {
 563         checkFxUserThread();
 564 
 565         if (key == null) {
 566             throw new NullPointerException();
 567         }
 568 
 569         if (!canStartNestedEventLoop()) {
 570             throw new IllegalStateException("Cannot enter nested loop during animation or layout processing");
 571         }
 572 
 573         if (eventLoopMap == null) {
 574             eventLoopMap = new HashMap<>();
 575         }
 576         if (eventLoopMap.containsKey(key)) {
 577             throw new IllegalArgumentException(
 578                     "Key already associated with a running event loop: " + key);
 579         }
 580         EventLoop eventLoop = Application.GetApplication().createEventLoop();
 581         eventLoopMap.put(key, eventLoop);
 582 
 583         Object ret = eventLoop.enter();
 584 
 585         if (!isNestedLoopRunning()) {
 586             notifyLastNestedLoopExited();
 587         }
 588 
 589         return ret;
 590     }
 591 
 592     @Override public void exitNestedEventLoop(Object key, Object rval) {
 593         checkFxUserThread();
 594 
 595         if (key == null) {
 596             throw new NullPointerException();
 597         }
 598         if (eventLoopMap == null || !eventLoopMap.containsKey(key)) {
 599             throw new IllegalArgumentException(
 600                     "Key not associated with a running event loop: " + key);
 601         }
 602         EventLoop eventLoop = eventLoopMap.get(key);
 603         eventLoopMap.remove(key);
 604         eventLoop.leave(rval);
 605     }
 606 
 607     @Override public TKStage createTKPopupStage(Window peerWindow,
 608                                                 StageStyle popupStyle,
 609                                                 TKStage owner,
 610                                                 AccessControlContext acc) {
 611         assertToolkitRunning();
 612         boolean securityDialog = owner instanceof WindowStage ?
 613                 ((WindowStage)owner).isSecurityDialog() : false;
 614         WindowStage stage = new WindowStage(peerWindow, securityDialog, popupStyle, null, owner);
 615         stage.setSecurityContext(acc);
 616         stage.setIsPopup();
 617         stage.init(systemMenu);
 618         return stage;
 619     }
 620 
 621     @Override public TKStage createTKEmbeddedStage(HostInterface host, AccessControlContext acc) {
 622         assertToolkitRunning();
 623         EmbeddedStage stage = new EmbeddedStage(host);
 624         stage.setSecurityContext(acc);
 625         return stage;
 626     }
 627 
 628     private static ScreenConfigurationAccessor screenAccessor =
 629         new ScreenConfigurationAccessor() {
 630             @Override public int getMinX(Object obj) {
 631                return ((Screen)obj).getX();
 632             }
 633             @Override public int getMinY(Object obj) {
 634                 return ((Screen)obj).getY();
 635             }
 636             @Override public int getWidth(Object obj) {
 637                 return ((Screen)obj).getWidth();
 638             }
 639             @Override public int getHeight(Object obj) {
 640                 return ((Screen)obj).getHeight();
 641             }
 642             @Override public int getVisualMinX(Object obj) {
 643                 return ((Screen)obj).getVisibleX();
 644             }
 645             @Override public int getVisualMinY(Object obj) {
 646                 return ((Screen)obj).getVisibleY();
 647             }
 648             @Override public int getVisualWidth(Object obj) {
 649                 return ((Screen)obj).getVisibleWidth();
 650             }
 651             @Override public int getVisualHeight(Object obj) {
 652                 return ((Screen)obj).getVisibleHeight();
 653             }
 654             @Override public float getDPI(Object obj) {
 655                 return ((Screen)obj).getResolutionX();
 656             }
 657             @Override public float getUIScale(Object obj) {
 658                 return ((Screen)obj).getUIScale();
 659             }
 660             @Override public float getRenderScale(Object obj) {
 661                 return ((Screen)obj).getRenderScale();
 662             }
 663         };
 664 
 665     @Override public ScreenConfigurationAccessor
 666                     setScreenConfigurationListener(final TKScreenConfigurationListener listener) {
 667         Screen.setEventHandler(new Screen.EventHandler() {
 668             @Override public void handleSettingsChanged() {
 669                 notifyScreenListener(listener);
 670             }
 671         });
 672         return screenAccessor;
 673     }
 674 
 675     private static void assignScreensAdapters() {
 676         GraphicsPipeline pipeline = GraphicsPipeline.getPipeline();
 677         for (Screen screen : Screen.getScreens()) {
 678             screen.setAdapterOrdinal(pipeline.getAdapterOrdinal(screen));
 679         }
 680     }
 681 
 682     private static void notifyScreenListener(TKScreenConfigurationListener listener) {
 683         assignScreensAdapters();
 684         listener.screenConfigurationChanged();
 685     }
 686 
 687     @Override public Object getPrimaryScreen() {
 688         return Screen.getMainScreen();
 689     }
 690 
 691     @Override public List<?> getScreens() {
 692         return Screen.getScreens();
 693     }
 694 
 695     @Override
 696     public ScreenConfigurationAccessor getScreenConfigurationAccessor() {
 697         return screenAccessor;
 698     }
 699 
 700     @Override
 701     public PerformanceTracker getPerformanceTracker() {
 702         return perfTracker;
 703     }
 704 
 705     @Override
 706     public PerformanceTracker createPerformanceTracker() {
 707         return new PerformanceTrackerImpl();
 708     }
 709 
 710     public float getMaxRenderScale() {
 711         if (_maxPixelScale == 0) {
 712             for (Object o : getScreens()) {
 713                 _maxPixelScale = Math.max(_maxPixelScale, ((Screen) o).getRenderScale());
 714             }
 715         }
 716         return _maxPixelScale;
 717     }
 718 
 719     @Override public ImageLoader loadImage(String url, int width, int height, boolean preserveRatio, boolean smooth) {
 720         return new PrismImageLoader2(url, width, height, preserveRatio, getMaxRenderScale(), smooth);
 721     }
 722 
 723     @Override public ImageLoader loadImage(InputStream stream, int width, int height,
 724                                            boolean preserveRatio, boolean smooth) {
 725         return new PrismImageLoader2(stream, width, height, preserveRatio, smooth);
 726     }
 727 
 728     @Override public AbstractRemoteResource<? extends ImageLoader> loadImageAsync(
 729             AsyncOperationListener listener, String url,
 730             int width, int height, boolean preserveRatio, boolean smooth) {
 731         return new PrismImageLoader2.AsyncImageLoader(listener, url, width, height, preserveRatio, smooth);
 732     }
 733 
 734     // Note that this method should only be called by PlatformImpl.runLater
 735     // It should not be called directly by other FX code since the underlying
 736     // glass invokeLater method is not thread-safe with respect to toolkit
 737     // shutdown. Calling Platform.runLater *is* thread-safe even when the
 738     // toolkit is shutting down.
 739     @Override public void defer(Runnable runnable) {
 740         if (!toolkitRunning.get()) return;
 741 
 742         Application.invokeLater(runnable);
 743     }
 744 
 745     @Override public void exit() {
 746         // This method must run on the FX application thread
 747         checkFxUserThread();
 748 
 749         // Turn off pulses so no extraneous runnables are submitted
 750         pulseTimer.stop();
 751 
 752         // We need to wait for the last frame to finish so that the renderer
 753         // is not running while we are shutting down glass.
 754         PaintCollector.getInstance().waitForRenderingToComplete();
 755 
 756         notifyShutdownHooks();
 757 
 758         runWithRenderLock(() -> {
 759             //TODO - should update glass scene view state
 760             //TODO - doesn't matter because we are exiting
 761             Application app = Application.GetApplication();
 762             app.terminate();
 763             return null;
 764         });
 765 
 766         dispose();
 767 
 768         super.exit();
 769     }
 770 
 771     public void dispose() {
 772         if (toolkitRunning.compareAndSet(true, false)) {
 773             pulseTimer.stop();
 774             renderer.stopRenderer();
 775 
 776             try {
 777                 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 778                     Runtime.getRuntime().removeShutdownHook(shutdownHook);
 779                     return null;
 780                 });
 781             } catch (IllegalStateException ignore) {
 782                 // throw when shutdown hook already removed
 783             }
 784         }
 785     }
 786 
 787     @Override public boolean isForwardTraversalKey(KeyEvent e) {
 788         return (e.getCode() == KeyCode.TAB)
 789                    && (e.getEventType() == KeyEvent.KEY_PRESSED)
 790                    && !e.isShiftDown();
 791     }
 792 
 793     @Override public boolean isBackwardTraversalKey(KeyEvent e) {
 794         return (e.getCode() == KeyCode.TAB)
 795                    && (e.getEventType() == KeyEvent.KEY_PRESSED)
 796                    && e.isShiftDown();
 797     }
 798 
 799     private Map<Object, Object> contextMap = Collections.synchronizedMap(new HashMap<>());
 800     @Override public Map<Object, Object> getContextMap() {
 801         return contextMap;
 802     }
 803 
 804     @Override public int getRefreshRate() {
 805         if (pulseHZ == null) {
 806             return 60;
 807         } else {
 808             return pulseHZ;
 809         }
 810     }
 811 
 812     private DelayedRunnable animationRunnable;
 813     @Override public void setAnimationRunnable(DelayedRunnable animationRunnable) {
 814         if (animationRunnable != null) {
 815             animationRunning.set(true);
 816         }
 817         this.animationRunnable = animationRunnable;
 818     }
 819 
 820     @Override public void requestNextPulse() {
 821         nextPulseRequested.set(true);
 822     }
 823 
 824     @Override public void waitFor(Task t) {
 825         if (t.isFinished()) {
 826             return;
 827         }
 828     }
 829 
 830     @Override protected Object createColorPaint(Color color) {
 831         return new com.sun.prism.paint.Color(
 832                 (float)color.getRed(), (float)color.getGreen(),
 833                 (float)color.getBlue(), (float)color.getOpacity());
 834     }
 835 
 836     private com.sun.prism.paint.Color toPrismColor(Color color) {
 837         return (com.sun.prism.paint.Color) Toolkit.getPaintAccessor().getPlatformPaint(color);
 838     }
 839 
 840     private List<com.sun.prism.paint.Stop> convertStops(List<Stop> paintStops) {
 841         List<com.sun.prism.paint.Stop> stops =
 842             new ArrayList<>(paintStops.size());
 843         for (Stop s : paintStops) {
 844             stops.add(new com.sun.prism.paint.Stop(toPrismColor(s.getColor()),
 845                                                    (float) s.getOffset()));
 846         }
 847         return stops;
 848     }
 849 
 850     @Override protected Object createLinearGradientPaint(LinearGradient paint) {
 851         int cmi = com.sun.prism.paint.Gradient.REPEAT;
 852         CycleMethod cycleMethod = paint.getCycleMethod();
 853         if (cycleMethod == CycleMethod.NO_CYCLE) {
 854             cmi = com.sun.prism.paint.Gradient.PAD;
 855         } else if (cycleMethod == CycleMethod.REFLECT) {
 856             cmi = com.sun.prism.paint.Gradient.REFLECT;
 857         }
 858         // TODO: extract colors/offsets and pass them in directly...
 859         List<com.sun.prism.paint.Stop> stops = convertStops(paint.getStops());
 860         return new com.sun.prism.paint.LinearGradient(
 861             (float)paint.getStartX(), (float)paint.getStartY(), (float)paint.getEndX(), (float)paint.getEndY(),
 862             null, paint.isProportional(), cmi, stops);
 863     }
 864 
 865     @Override
 866     protected Object createRadialGradientPaint(RadialGradient paint) {
 867         float cx = (float)paint.getCenterX();
 868         float cy = (float)paint.getCenterY();
 869         float fa = (float)paint.getFocusAngle();
 870         float fd = (float)paint.getFocusDistance();
 871 
 872         int cmi = 0;
 873         if (paint.getCycleMethod() == CycleMethod.NO_CYCLE) {
 874             cmi = com.sun.prism.paint.Gradient.PAD;
 875         } else if (paint.getCycleMethod() == CycleMethod.REFLECT) {
 876             cmi = com.sun.prism.paint.Gradient.REFLECT;
 877         } else {
 878             cmi = com.sun.prism.paint.Gradient.REPEAT;
 879         }
 880 
 881         // TODO: extract colors/offsets and pass them in directly...
 882         List<com.sun.prism.paint.Stop> stops = convertStops(paint.getStops());
 883         return new com.sun.prism.paint.RadialGradient(cx, cy, fa, fd,
 884                 (float)paint.getRadius(), null, paint.isProportional(), cmi, stops);
 885     }
 886 
 887     @Override
 888     protected Object createImagePatternPaint(ImagePattern paint) {
 889         if (paint.getImage() == null) {
 890             return com.sun.prism.paint.Color.TRANSPARENT;
 891         } else {
 892             return new com.sun.prism.paint.ImagePattern((com.sun.prism.Image) paint.getImage().impl_getPlatformImage(),
 893                     (float)paint.getX(),
 894                     (float)paint.getY(),
 895                     (float)paint.getWidth(),
 896                     (float)paint.getHeight(),
 897                     paint.isProportional(),
 898                     Toolkit.getPaintAccessor().isMutable(paint));
 899         }
 900     }
 901 
 902     static BasicStroke tmpStroke = new BasicStroke();
 903     private void initStroke(StrokeType pgtype, double strokewidth,
 904                             StrokeLineCap pgcap,
 905                             StrokeLineJoin pgjoin, float miterLimit,
 906                             float[] dashArray, float dashOffset)
 907     {
 908         int type;
 909         if (pgtype == StrokeType.CENTERED) {
 910             type = BasicStroke.TYPE_CENTERED;
 911         } else if (pgtype == StrokeType.INSIDE) {
 912             type = BasicStroke.TYPE_INNER;
 913         } else {
 914             type = BasicStroke.TYPE_OUTER;
 915         }
 916 
 917         int cap;
 918         if (pgcap == StrokeLineCap.BUTT) {
 919             cap = BasicStroke.CAP_BUTT;
 920         } else if (pgcap == StrokeLineCap.SQUARE) {
 921             cap = BasicStroke.CAP_SQUARE;
 922         } else {
 923             cap = BasicStroke.CAP_ROUND;
 924         }
 925 
 926         int join;
 927         if (pgjoin == StrokeLineJoin.BEVEL) {
 928             join = BasicStroke.JOIN_BEVEL;
 929         } else if (pgjoin == StrokeLineJoin.MITER) {
 930             join = BasicStroke.JOIN_MITER;
 931         } else {
 932             join = BasicStroke.JOIN_ROUND;
 933         }
 934 
 935         tmpStroke.set(type, (float) strokewidth, cap, join, miterLimit);
 936         if ((dashArray != null) && (dashArray.length > 0)) {
 937             tmpStroke.set(dashArray, dashOffset);
 938         } else {
 939             tmpStroke.set((float[])null, 0);
 940         }
 941     }
 942 
 943     @Override
 944     public void accumulateStrokeBounds(Shape shape, float bbox[],
 945                                        StrokeType pgtype,
 946                                        double strokewidth,
 947                                        StrokeLineCap pgcap,
 948                                        StrokeLineJoin pgjoin,
 949                                        float miterLimit,
 950                                        BaseTransform tx)
 951     {
 952 
 953         initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit, null, 0);
 954         if (tx.isTranslateOrIdentity()) {
 955             tmpStroke.accumulateShapeBounds(bbox, shape, tx);
 956         } else {
 957             Shape.accumulate(bbox, tmpStroke.createStrokedShape(shape), tx);
 958         }
 959     }
 960 
 961     @Override
 962     public boolean strokeContains(Shape shape, double x, double y,
 963                                   StrokeType pgtype,
 964                                   double strokewidth,
 965                                   StrokeLineCap pgcap,
 966                                   StrokeLineJoin pgjoin,
 967                                   float miterLimit)
 968     {
 969         initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit, null, 0);
 970         // TODO: The contains testing could be done directly without creating a Shape
 971         return tmpStroke.createStrokedShape(shape).contains((float) x, (float) y);
 972     }
 973 
 974     @Override
 975     public Shape createStrokedShape(Shape shape,
 976                                     StrokeType pgtype,
 977                                     double strokewidth,
 978                                     StrokeLineCap pgcap,
 979                                     StrokeLineJoin pgjoin,
 980                                     float miterLimit,
 981                                     float[] dashArray,
 982                                     float dashOffset) {
 983         initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit,
 984                    dashArray, dashOffset);
 985         return tmpStroke.createStrokedShape(shape);
 986     }
 987 
 988     @Override public Dimension2D getBestCursorSize(int preferredWidth, int preferredHeight) {
 989         return CursorUtils.getBestCursorSize(preferredWidth, preferredHeight);
 990     }
 991 
 992     @Override public int getMaximumCursorColors() {
 993         return 2;
 994     }
 995 
 996     @Override public int getKeyCodeForChar(String character) {
 997         return (character.length() == 1)
 998                 ? com.sun.glass.events.KeyEvent.getKeyCodeForChar(
 999                           character.charAt(0))
1000                 : com.sun.glass.events.KeyEvent.VK_UNDEFINED;
1001     }
1002 
1003     @Override public PathElement[] convertShapeToFXPath(Object shape) {
1004         if (shape == null) {
1005             return new PathElement[0];
1006         }
1007         List<PathElement> elements = new ArrayList<>();
1008         // iterate over the shape and turn it into a series of path
1009         // elements
1010         com.sun.javafx.geom.Shape geomShape = (com.sun.javafx.geom.Shape) shape;
1011         PathIterator itr = geomShape.getPathIterator(null);
1012         PathIteratorHelper helper = new PathIteratorHelper(itr);
1013         PathIteratorHelper.Struct struct = new PathIteratorHelper.Struct();
1014 
1015         while (!helper.isDone()) {
1016             // true if WIND_EVEN_ODD, false if WIND_NON_ZERO
1017             boolean windEvenOdd = helper.getWindingRule() == PathIterator.WIND_EVEN_ODD;
1018             int type = helper.currentSegment(struct);
1019             PathElement el;
1020             if (type == PathIterator.SEG_MOVETO) {
1021                 el = new MoveTo(struct.f0, struct.f1);
1022             } else if (type == PathIterator.SEG_LINETO) {
1023                 el = new LineTo(struct.f0, struct.f1);
1024             } else if (type == PathIterator.SEG_QUADTO) {
1025                 el = new QuadCurveTo(
1026                     struct.f0,
1027                     struct.f1,
1028                     struct.f2,
1029                     struct.f3);
1030             } else if (type == PathIterator.SEG_CUBICTO) {
1031                 el = new CubicCurveTo (
1032                     struct.f0,
1033                     struct.f1,
1034                     struct.f2,
1035                     struct.f3,
1036                     struct.f4,
1037                     struct.f5);
1038             } else if (type == PathIterator.SEG_CLOSE) {
1039                 el = new ClosePath();
1040             } else {
1041                 throw new IllegalStateException("Invalid element type: " + type);
1042             }
1043             helper.next();
1044             elements.add(el);
1045         }
1046 
1047         return elements.toArray(new PathElement[elements.size()]);
1048     }
1049 
1050     @Override public HitInfo convertHitInfoToFX(Object hit) {
1051         Integer textHitPos = (Integer) hit;
1052         HitInfo hitInfo = new HitInfo();
1053         hitInfo.setCharIndex(textHitPos);
1054         hitInfo.setLeading(true);
1055         return hitInfo;
1056     }
1057 
1058     @Override public Filterable toFilterable(Image img) {
1059         return PrImage.create((com.sun.prism.Image) img.impl_getPlatformImage());
1060     }
1061 
1062     @Override public FilterContext getFilterContext(Object config) {
1063         if (config == null || (!(config instanceof com.sun.glass.ui.Screen))) {
1064             return PrFilterContext.getDefaultInstance();
1065         }
1066         Screen screen = (Screen)config;
1067         return PrFilterContext.getInstance(screen);
1068     }
1069 
1070     @Override public AbstractMasterTimer getMasterTimer() {
1071         return MasterTimer.getInstance();
1072     }
1073 
1074     @Override public FontLoader getFontLoader() {
1075         return com.sun.javafx.font.PrismFontLoader.getInstance();
1076     }
1077 
1078     @Override public TextLayoutFactory getTextLayoutFactory() {
1079         return com.sun.javafx.text.PrismTextLayoutFactory.getFactory();
1080     }
1081 
1082     @Override public Object createSVGPathObject(SVGPath svgpath) {
1083         int windingRule = svgpath.getFillRule() == FillRule.NON_ZERO ? PathIterator.WIND_NON_ZERO : PathIterator.WIND_EVEN_ODD;
1084         Path2D path = new Path2D(windingRule);
1085         path.appendSVGPath(svgpath.getContent());
1086         return path;
1087     }
1088 
1089     @Override public Path2D createSVGPath2D(SVGPath svgpath) {
1090         int windingRule = svgpath.getFillRule() == FillRule.NON_ZERO ? PathIterator.WIND_NON_ZERO : PathIterator.WIND_EVEN_ODD;
1091         Path2D path = new Path2D(windingRule);
1092         path.appendSVGPath(svgpath.getContent());
1093         return path;
1094     }
1095 
1096     @Override public boolean imageContains(Object image, float x, float y) {
1097         if (image == null) {
1098             return false;
1099         }
1100 
1101         com.sun.prism.Image pImage = (com.sun.prism.Image)image;
1102         int intX = (int)x + pImage.getMinX();
1103         int intY = (int)y + pImage.getMinY();
1104 
1105         if (pImage.isOpaque()) {
1106             return true;
1107         }
1108 
1109         if (pImage.getPixelFormat() == PixelFormat.INT_ARGB_PRE) {
1110             IntBuffer ib = (IntBuffer) pImage.getPixelBuffer();
1111             int index = intX + intY * pImage.getRowLength();
1112             if (index >= ib.limit()) {
1113                 return false;
1114             } else {
1115                 return (ib.get(index) & 0xff000000) != 0;
1116             }
1117         } else if (pImage.getPixelFormat() == PixelFormat.BYTE_BGRA_PRE) {
1118             ByteBuffer bb = (ByteBuffer) pImage.getPixelBuffer();
1119             int index = intX * pImage.getBytesPerPixelUnit() + intY * pImage.getScanlineStride() + 3;
1120             if (index >= bb.limit()) {
1121                 return false;
1122             } else {
1123                 return (bb.get(index) & 0xff) != 0;
1124             }
1125         } else if (pImage.getPixelFormat() == PixelFormat.BYTE_ALPHA) {
1126             ByteBuffer bb = (ByteBuffer) pImage.getPixelBuffer();
1127             int index = intX * pImage.getBytesPerPixelUnit() + intY * pImage.getScanlineStride();
1128             if (index >= bb.limit()) {
1129                 return false;
1130             } else {
1131                 return (bb.get(index) & 0xff) != 0;
1132             }
1133         }
1134         return true;
1135     }
1136 
1137     @Override
1138     public boolean isNestedLoopRunning() {
1139         return Application.isNestedLoopRunning();
1140     }
1141 
1142     @Override
1143     public boolean isSupported(ConditionalFeature feature) {
1144         switch (feature) {
1145             case SCENE3D:
1146                 return GraphicsPipeline.getPipeline().is3DSupported();
1147             case EFFECT:
1148                 return GraphicsPipeline.getPipeline().isEffectSupported();
1149             case SHAPE_CLIP:
1150                 return true;
1151             case INPUT_METHOD:
1152                 return Application.GetApplication().supportsInputMethods();
1153             case TRANSPARENT_WINDOW:
1154                 return Application.GetApplication().supportsTransparentWindows();
1155             case UNIFIED_WINDOW:
1156                 return Application.GetApplication().supportsUnifiedWindows();
1157             case TWO_LEVEL_FOCUS:
1158                 return Application.GetApplication().hasTwoLevelFocus();
1159             case VIRTUAL_KEYBOARD:
1160                 return Application.GetApplication().hasVirtualKeyboard();
1161             case INPUT_TOUCH:
1162                 return Application.GetApplication().hasTouch();
1163             case INPUT_MULTITOUCH:
1164                 return Application.GetApplication().hasMultiTouch();
1165             case INPUT_POINTER:
1166                 return Application.GetApplication().hasPointer();
1167             default:
1168                 return false;
1169         }
1170     }
1171 
1172     @Override
1173     public boolean isMSAASupported() {
1174         return  GraphicsPipeline.getPipeline().isMSAASupported();
1175     }
1176 
1177     static TransferMode clipboardActionToTransferMode(final int action) {
1178         switch (action) {
1179             case Clipboard.ACTION_NONE:
1180                 return null;
1181             case Clipboard.ACTION_COPY:
1182             //IE drop action for URL copy
1183             case Clipboard.ACTION_COPY | Clipboard.ACTION_REFERENCE:
1184                 return TransferMode.COPY;
1185             case Clipboard.ACTION_MOVE:
1186             //IE drop action for URL move
1187             case Clipboard.ACTION_MOVE | Clipboard.ACTION_REFERENCE:
1188                 return TransferMode.MOVE;
1189             case Clipboard.ACTION_REFERENCE:
1190                 return TransferMode.LINK;
1191             case Clipboard.ACTION_ANY:
1192                 return TransferMode.COPY; // select a reasonable trasnfer mode as workaround until RT-22840
1193         }
1194         return null;
1195     }
1196 
1197     private QuantumClipboard clipboard;
1198     @Override public TKClipboard getSystemClipboard() {
1199         if (clipboard == null) {
1200             clipboard = QuantumClipboard.getClipboardInstance(new ClipboardAssistance(com.sun.glass.ui.Clipboard.SYSTEM));
1201         }
1202         return clipboard;
1203     }
1204 
1205     private GlassSystemMenu systemMenu = new GlassSystemMenu();
1206     @Override public TKSystemMenu getSystemMenu() {
1207         return systemMenu;
1208     }
1209 
1210     @Override public TKClipboard getNamedClipboard(String name) {
1211         return null;
1212     }
1213 
1214     @Override public void startDrag(TKScene scene, Set<TransferMode> tm, TKDragSourceListener l, Dragboard dragboard) {
1215         if (dragboard == null) {
1216             throw new IllegalArgumentException("dragboard should not be null");
1217         }
1218 
1219         GlassScene view = (GlassScene)scene;
1220         view.setTKDragSourceListener(l);
1221 
1222         QuantumClipboard gc = (QuantumClipboard)dragboard.impl_getPeer();
1223         gc.setSupportedTransferMode(tm);
1224         gc.flush();
1225 
1226         // flush causes a modal DnD event loop, when we return, close the clipboard
1227         gc.close();
1228     }
1229 
1230     @Override public void enableDrop(TKScene s, TKDropTargetListener l) {
1231 
1232         assert s instanceof GlassScene;
1233 
1234         GlassScene view = (GlassScene)s;
1235         view.setTKDropTargetListener(l);
1236     }
1237 
1238     @Override public void registerDragGestureListener(TKScene s, Set<TransferMode> tm, TKDragGestureListener l) {
1239 
1240         assert s instanceof GlassScene;
1241 
1242         GlassScene view = (GlassScene)s;
1243         view.setTKDragGestureListener(l);
1244     }
1245 
1246     @Override
1247     public void installInputMethodRequests(TKScene scene, InputMethodRequests requests) {
1248 
1249         assert scene instanceof GlassScene;
1250 
1251         GlassScene view = (GlassScene)scene;
1252         view.setInputMethodRequests(requests);
1253     }
1254 
1255     static class QuantumImage implements com.sun.javafx.tk.ImageLoader, ResourceFactoryListener {
1256 
1257         // cache rt here
1258         private com.sun.prism.RTTexture rt;
1259         private com.sun.prism.Image image;
1260         private ResourceFactory rf;
1261 
1262         QuantumImage(com.sun.prism.Image image) {
1263             this.image = image;
1264         }
1265 
1266         RTTexture getRT(int w, int h, ResourceFactory rfNew) {
1267             boolean rttOk = rt != null && rf == rfNew &&
1268                     rt.getContentWidth() == w && rt.getContentHeight() == h;
1269             if (rttOk) {
1270                 rt.lock();
1271                 if (rt.isSurfaceLost()) {
1272                     rttOk = false;
1273                 }
1274             }
1275 
1276             if (!rttOk) {
1277                 if (rt != null) {
1278                     rt.dispose();
1279                 }
1280                 if (rf != null) {
1281                     rf.removeFactoryListener(this);
1282                     rf = null;
1283                 }
1284                 rt = rfNew.createRTTexture(w, h, WrapMode.CLAMP_TO_ZERO);
1285                 if (rt != null) {
1286                     rf = rfNew;
1287                     rf.addFactoryListener(this);
1288                 }
1289             }
1290 
1291             return rt;
1292         }
1293 
1294         void dispose() {
1295             if (rt != null) {
1296                 rt.dispose();
1297                 rt = null;
1298             }
1299         }
1300 
1301         void setImage(com.sun.prism.Image img) {
1302             image = img;
1303         }
1304 
1305         @Override
1306         public Exception getException() {
1307             return (image == null)
1308                     ? new IllegalStateException("Unitialized image")
1309                     : null;
1310         }
1311         @Override
1312         public int getFrameCount() { return 1; }
1313         @Override
1314         public PlatformImage getFrame(int index) { return image; }
1315         @Override
1316         public int getFrameDelay(int index) { return 0; }
1317         @Override
1318         public int getLoopCount() { return 0; }
1319         @Override
1320         public int getWidth() { return image.getWidth(); }
1321         @Override
1322         public int getHeight() { return image.getHeight(); }
1323         @Override
1324         public void factoryReset() { dispose(); }
1325         @Override
1326         public void factoryReleased() { dispose(); }
1327     }
1328 
1329     @Override public ImageLoader loadPlatformImage(Object platformImage) {
1330         if (platformImage instanceof QuantumImage) {
1331             return (QuantumImage)platformImage;
1332         }
1333 
1334         if (platformImage instanceof com.sun.prism.Image) {
1335             return new QuantumImage((com.sun.prism.Image) platformImage);
1336         }
1337 
1338         throw new UnsupportedOperationException("unsupported class for loadPlatformImage");
1339     }
1340 
1341     @Override
1342     public PlatformImage createPlatformImage(int w, int h) {
1343         ByteBuffer bytebuf = ByteBuffer.allocate(w * h * 4);
1344         return com.sun.prism.Image.fromByteBgraPreData(bytebuf, w, h);
1345     }
1346 
1347     @Override
1348     public Object renderToImage(ImageRenderingContext p) {
1349         Object saveImage = p.platformImage;
1350         final ImageRenderingContext params = p;
1351         final com.sun.prism.paint.Paint currentPaint = p.platformPaint instanceof com.sun.prism.paint.Paint ?
1352                 (com.sun.prism.paint.Paint)p.platformPaint : null;
1353 
1354         RenderJob re = new RenderJob(new Runnable() {
1355 
1356             private com.sun.prism.paint.Color getClearColor() {
1357                 if (currentPaint == null) {
1358                     return com.sun.prism.paint.Color.WHITE;
1359                 } else if (currentPaint.getType() == com.sun.prism.paint.Paint.Type.COLOR) {
1360                     return (com.sun.prism.paint.Color) currentPaint;
1361                 } else if (currentPaint.isOpaque()) {
1362                     return com.sun.prism.paint.Color.TRANSPARENT;
1363                 } else {
1364                     return com.sun.prism.paint.Color.WHITE;
1365                 }
1366             }
1367 
1368             private void draw(Graphics g, int x, int y, int w, int h) {
1369                 g.setLights(params.lights);
1370                 g.setDepthBuffer(params.depthBuffer);
1371 
1372                 g.clear(getClearColor());
1373                 if (currentPaint != null &&
1374                         currentPaint.getType() != com.sun.prism.paint.Paint.Type.COLOR) {
1375                     g.getRenderTarget().setOpaque(currentPaint.isOpaque());
1376                     g.setPaint(currentPaint);
1377                     g.fillQuad(0, 0, w, h);
1378                 }
1379 
1380                 // Set up transform
1381                 if (x != 0 || y != 0) {
1382                     g.translate(-x, -y);
1383                 }
1384                 if (params.transform != null) {
1385                     g.transform(params.transform);
1386                 }
1387 
1388                 if (params.root != null) {
1389                     if (params.camera != null) {
1390                         g.setCamera(params.camera);
1391                     }
1392                     NGNode ngNode = params.root;
1393                     ngNode.render(g);
1394                 }
1395 
1396             }
1397 
1398             @Override
1399             public void run() {
1400 
1401                 ResourceFactory rf = GraphicsPipeline.getDefaultResourceFactory();
1402 
1403                 if (!rf.isDeviceReady()) {
1404                     return;
1405                 }
1406 
1407                 int x = params.x;
1408                 int y = params.y;
1409                 int w = params.width;
1410                 int h = params.height;
1411 
1412                 if (w <= 0 || h <= 0) {
1413                     return;
1414                 }
1415 
1416                 boolean errored = false;
1417                 try {
1418                     QuantumImage pImage = (params.platformImage instanceof QuantumImage) ?
1419                             (QuantumImage)params.platformImage : new QuantumImage(null);
1420 
1421                     com.sun.prism.RTTexture rt = pImage.getRT(w, h, rf);
1422 
1423                     if (rt == null) {
1424                         return;
1425                     }
1426 
1427                     Graphics g = rt.createGraphics();
1428 
1429                     draw(g, x, y, w, h);
1430 
1431                     int[] pixels = pImage.rt.getPixels();
1432 
1433                     if (pixels != null) {
1434                         pImage.setImage(com.sun.prism.Image.fromIntArgbPreData(pixels, w, h));
1435                     } else {
1436                         IntBuffer ib = IntBuffer.allocate(w*h);
1437                         if (pImage.rt.readPixels(ib, pImage.rt.getContentX(),
1438                                 pImage.rt.getContentY(), w, h))
1439                         {
1440                             pImage.setImage(com.sun.prism.Image.fromIntArgbPreData(ib, w, h));
1441                         } else {
1442                             pImage.dispose();
1443                             pImage = null;
1444                         }
1445                     }
1446 
1447                     rt.unlock();
1448 
1449                     params.platformImage = pImage;
1450 
1451                 } catch (Throwable t) {
1452                     errored = true;
1453                     t.printStackTrace(System.err);
1454                 } finally {
1455                     Disposer.cleanUp();
1456                     rf.getTextureResourcePool().freeDisposalRequestedAndCheckResources(errored);
1457                 }
1458             }
1459         });
1460 
1461         final CountDownLatch latch = new CountDownLatch(1);
1462         re.setCompletionListener(job -> latch.countDown());
1463         addRenderJob(re);
1464 
1465         do {
1466             try {
1467                 latch.await();
1468                 break;
1469             } catch (InterruptedException ex) {
1470                 ex.printStackTrace();
1471             }
1472         } while (true);
1473 
1474         Object image = params.platformImage;
1475         params.platformImage = saveImage;
1476 
1477         return image;
1478     }
1479 
1480     @Override
1481     public FileChooserResult showFileChooser(final TKStage ownerWindow,
1482                                       final String title,
1483                                       final File initialDirectory,
1484                                       final String initialFileName,
1485                                       final FileChooserType fileChooserType,
1486                                       final List<FileChooser.ExtensionFilter>
1487                                               extensionFilters,
1488                                       final FileChooser.ExtensionFilter selectedFilter) {
1489         WindowStage blockedStage = null;
1490         try {
1491             // NOTE: we block the owner of the owner deliberately.
1492             //       The native system blocks the nearest owner itself.
1493             //       Otherwise sheets on Mac are unusable.
1494             blockedStage = blockOwnerStage(ownerWindow);
1495 
1496             return CommonDialogs.showFileChooser(
1497                     (ownerWindow instanceof WindowStage)
1498                             ? ((WindowStage) ownerWindow).getPlatformWindow()
1499                             : null,
1500                     initialDirectory,
1501                     initialFileName,
1502                     title,
1503                     (fileChooserType == FileChooserType.SAVE)
1504                             ? CommonDialogs.Type.SAVE
1505                             : CommonDialogs.Type.OPEN,
1506                     (fileChooserType == FileChooserType.OPEN_MULTIPLE),
1507                     convertExtensionFilters(extensionFilters),
1508                     extensionFilters.indexOf(selectedFilter));
1509         } finally {
1510             if (blockedStage != null) {
1511                 blockedStage.setEnabled(true);
1512             }
1513         }
1514     }
1515 
1516     @Override
1517     public File showDirectoryChooser(final TKStage ownerWindow,
1518                                      final String title,
1519                                      final File initialDirectory) {
1520         WindowStage blockedStage = null;
1521         try {
1522             // NOTE: we block the owner of the owner deliberately.
1523             //       The native system blocks the nearest owner itself.
1524             //       Otherwise sheets on Mac are unusable.
1525             blockedStage = blockOwnerStage(ownerWindow);
1526 
1527             return CommonDialogs.showFolderChooser(
1528                     (ownerWindow instanceof WindowStage)
1529                             ? ((WindowStage) ownerWindow).getPlatformWindow()
1530                             : null,
1531                     initialDirectory, title);
1532         } finally {
1533             if (blockedStage != null) {
1534                 blockedStage.setEnabled(true);
1535             }
1536         }
1537     }
1538 
1539     private WindowStage blockOwnerStage(final TKStage stage) {
1540         if (stage instanceof WindowStage) {
1541             final TKStage ownerStage = ((WindowStage) stage).getOwner();
1542             if (ownerStage instanceof WindowStage) {
1543                 final WindowStage ownerWindowStage = (WindowStage) ownerStage;
1544                 ownerWindowStage.setEnabled(false);
1545                 return ownerWindowStage;
1546             }
1547         }
1548 
1549         return null;
1550     }
1551 
1552     private static List<CommonDialogs.ExtensionFilter>
1553             convertExtensionFilters(final List<FileChooser.ExtensionFilter>
1554                                             extensionFilters) {
1555         final CommonDialogs.ExtensionFilter[] glassExtensionFilters =
1556                 new CommonDialogs.ExtensionFilter[extensionFilters.size()];
1557 
1558         int i = 0;
1559         for (final FileChooser.ExtensionFilter extensionFilter:
1560                  extensionFilters) {
1561             glassExtensionFilters[i++] =
1562                     new CommonDialogs.ExtensionFilter(
1563                             extensionFilter.getDescription(),
1564                             extensionFilter.getExtensions());
1565         }
1566 
1567         return Arrays.asList(glassExtensionFilters);
1568     }
1569 
1570     @Override
1571     public long getMultiClickTime() {
1572         return View.getMultiClickTime();
1573     }
1574 
1575     @Override
1576     public int getMultiClickMaxX() {
1577         return View.getMultiClickMaxX();
1578     }
1579 
1580     @Override
1581     public int getMultiClickMaxY() {
1582         return View.getMultiClickMaxY();
1583     }
1584 
1585     @Override
1586     public String getThemeName() {
1587         return Application.GetApplication().getHighContrastTheme();
1588     }
1589 }