1 /*
   2  * Copyright (c) 2010, 2014, 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 boolean                 inPulse = false;
 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             if (PULSE_LOGGING_ENABLED) {
 496                 PulseLogger.pulseStart();
 497             }
 498 
 499             if (!toolkitRunning.get()) {
 500                 return;
 501             }
 502             nextPulseRequested.set(false);
 503             inPulse = true;
 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 = false;
 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 Object enterNestedEventLoop(Object key) {
 559         checkFxUserThread();
 560 
 561         if (key == null) {
 562             throw new NullPointerException();
 563         }
 564         if (inPulse) {
 565             throw new IllegalStateException("Nested event loops are allowed only while handling system events");
 566         }
 567 
 568         if (eventLoopMap == null) {
 569             eventLoopMap = new HashMap<>();
 570         }
 571         if (eventLoopMap.containsKey(key)) {
 572             throw new IllegalArgumentException(
 573                     "Key already associated with a running event loop: " + key);
 574         }
 575         EventLoop eventLoop = Application.GetApplication().createEventLoop();
 576         eventLoopMap.put(key, eventLoop);
 577 
 578         Object ret = eventLoop.enter();
 579 
 580         if (!isNestedLoopRunning()) {
 581             notifyLastNestedLoopExited();
 582         }
 583         
 584         return ret;
 585     }
 586 
 587     @Override public void exitNestedEventLoop(Object key, Object rval) {
 588         checkFxUserThread();
 589 
 590         if (key == null) {
 591             throw new NullPointerException();
 592         }
 593         if (eventLoopMap == null || !eventLoopMap.containsKey(key)) {
 594             throw new IllegalArgumentException(
 595                     "Key not associated with a running event loop: " + key);
 596         }
 597         EventLoop eventLoop = eventLoopMap.get(key);
 598         eventLoopMap.remove(key);
 599         eventLoop.leave(rval);
 600     }
 601 
 602     @Override public TKStage createTKPopupStage(Window peerWindow,
 603                                                 StageStyle popupStyle,
 604                                                 TKStage owner,
 605                                                 AccessControlContext acc) {
 606         assertToolkitRunning();
 607         boolean securityDialog = owner instanceof WindowStage ?
 608                 ((WindowStage)owner).isSecurityDialog() : false;
 609         WindowStage stage = new WindowStage(peerWindow, securityDialog, popupStyle, null, owner);
 610         stage.setSecurityContext(acc);
 611         stage.setIsPopup();
 612         stage.init(systemMenu);
 613         return stage;
 614     }
 615 
 616     @Override public TKStage createTKEmbeddedStage(HostInterface host, AccessControlContext acc) {
 617         assertToolkitRunning();
 618         EmbeddedStage stage = new EmbeddedStage(host);
 619         stage.setSecurityContext(acc);
 620         return stage;
 621     }
 622 
 623     private static ScreenConfigurationAccessor screenAccessor =
 624         new ScreenConfigurationAccessor() {
 625             @Override public int getMinX(Object obj) {
 626                return ((Screen)obj).getX();
 627             }
 628             @Override public int getMinY(Object obj) {
 629                 return ((Screen)obj).getY();
 630             }
 631             @Override public int getWidth(Object obj) {
 632                 return ((Screen)obj).getWidth();
 633             }
 634             @Override public int getHeight(Object obj) {
 635                 return ((Screen)obj).getHeight();
 636             }
 637             @Override public int getVisualMinX(Object obj) {
 638                 return ((Screen)obj).getVisibleX();
 639             }
 640             @Override public int getVisualMinY(Object obj) {
 641                 return ((Screen)obj).getVisibleY();
 642             }
 643             @Override public int getVisualWidth(Object obj) {
 644                 return ((Screen)obj).getVisibleWidth();
 645             }
 646             @Override public int getVisualHeight(Object obj) {
 647                 return ((Screen)obj).getVisibleHeight();
 648             }
 649             @Override public float getDPI(Object obj) {
 650                 return ((Screen)obj).getResolutionX();
 651             }
 652             @Override public float getScale(Object obj) {
 653                 return ((Screen)obj).getScale();
 654             }
 655         };
 656 
 657     @Override public ScreenConfigurationAccessor
 658                     setScreenConfigurationListener(final TKScreenConfigurationListener listener) {
 659         Screen.setEventHandler(new Screen.EventHandler() {
 660             @Override public void handleSettingsChanged() {
 661                 notifyScreenListener(listener);
 662             }
 663         });
 664         return screenAccessor;
 665     }
 666 
 667     private static void assignScreensAdapters() {
 668         GraphicsPipeline pipeline = GraphicsPipeline.getPipeline();
 669         for (Screen screen : Screen.getScreens()) {
 670             screen.setAdapterOrdinal(pipeline.getAdapterOrdinal(screen));
 671         }
 672     }
 673 
 674     private static void notifyScreenListener(TKScreenConfigurationListener listener) {
 675         assignScreensAdapters();
 676         listener.screenConfigurationChanged();
 677     }
 678 
 679     @Override public Object getPrimaryScreen() {
 680         return Screen.getMainScreen();
 681     }
 682 
 683     @Override public List<?> getScreens() {
 684         return Screen.getScreens();
 685     }
 686 
 687     @Override
 688     public ScreenConfigurationAccessor getScreenConfigurationAccessor() {
 689         return screenAccessor;
 690     }
 691 
 692     @Override
 693     public PerformanceTracker getPerformanceTracker() {
 694         return perfTracker;
 695     }
 696 
 697     @Override
 698     public PerformanceTracker createPerformanceTracker() {
 699         return new PerformanceTrackerImpl();
 700     }
 701 
 702     public float getMaxPixelScale() {
 703         if (_maxPixelScale == 0) {
 704             for (Object o : getScreens()) {
 705                 _maxPixelScale = Math.max(_maxPixelScale, ((Screen) o).getScale());
 706             }
 707         }
 708         return _maxPixelScale;
 709     }
 710 
 711     @Override public ImageLoader loadImage(String url, int width, int height, boolean preserveRatio, boolean smooth) {
 712         return new PrismImageLoader2(url, width, height, preserveRatio, getMaxPixelScale(), smooth);
 713     }
 714 
 715     @Override public ImageLoader loadImage(InputStream stream, int width, int height,
 716                                            boolean preserveRatio, boolean smooth) {
 717         return new PrismImageLoader2(stream, width, height, preserveRatio, smooth);
 718     }
 719 
 720     @Override public AbstractRemoteResource<? extends ImageLoader> loadImageAsync(
 721             AsyncOperationListener listener, String url,
 722             int width, int height, boolean preserveRatio, boolean smooth) {
 723         return new PrismImageLoader2.AsyncImageLoader(listener, url, width, height, preserveRatio, smooth);
 724     }
 725 
 726     // Note that this method should only be called by PlatformImpl.runLater
 727     // It should not be called directly by other FX code since the underlying
 728     // glass invokeLater method is not thread-safe with respect to toolkit
 729     // shutdown. Calling Platform.runLater *is* thread-safe even when the
 730     // toolkit is shutting down.
 731     @Override public void defer(Runnable runnable) {
 732         if (!toolkitRunning.get()) return;
 733 
 734         Application.invokeLater(runnable);
 735     }
 736 
 737     @Override public void exit() {
 738         // This method must run on the FX application thread
 739         checkFxUserThread();
 740 
 741         // Turn off pulses so no extraneous runnables are submitted
 742         pulseTimer.stop();
 743 
 744         // We need to wait for the last frame to finish so that the renderer
 745         // is not running while we are shutting down glass.
 746         PaintCollector.getInstance().waitForRenderingToComplete();
 747 
 748         notifyShutdownHooks();
 749 
 750         runWithRenderLock(() -> {
 751             //TODO - should update glass scene view state
 752             //TODO - doesn't matter because we are exiting
 753             Application app = Application.GetApplication();
 754             app.terminate();
 755             return null;
 756         });
 757 
 758         dispose();
 759 
 760         super.exit();
 761     }
 762 
 763     public void dispose() {
 764         if (toolkitRunning.compareAndSet(true, false)) {
 765             pulseTimer.stop();
 766             renderer.stopRenderer();
 767 
 768             try {
 769                 AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 770                     Runtime.getRuntime().removeShutdownHook(shutdownHook);
 771                     return null;
 772                 });
 773             } catch (IllegalStateException ignore) {
 774                 // throw when shutdown hook already removed
 775             }
 776         }
 777     }
 778 
 779     @Override public boolean isForwardTraversalKey(KeyEvent e) {
 780         return (e.getCode() == KeyCode.TAB)
 781                    && (e.getEventType() == KeyEvent.KEY_PRESSED)
 782                    && !e.isShiftDown();
 783     }
 784 
 785     @Override public boolean isBackwardTraversalKey(KeyEvent e) {
 786         return (e.getCode() == KeyCode.TAB)
 787                    && (e.getEventType() == KeyEvent.KEY_PRESSED)
 788                    && e.isShiftDown();
 789     }
 790 
 791     private Map<Object, Object> contextMap = Collections.synchronizedMap(new HashMap<>());
 792     @Override public Map<Object, Object> getContextMap() {
 793         return contextMap;
 794     }
 795 
 796     @Override public int getRefreshRate() {
 797         if (pulseHZ == null) {
 798             return 60;
 799         } else {
 800             return pulseHZ;
 801         }
 802     }
 803 
 804     private DelayedRunnable animationRunnable;
 805     @Override public void setAnimationRunnable(DelayedRunnable animationRunnable) {
 806         if (animationRunnable != null) {
 807             animationRunning.set(true);
 808         }
 809         this.animationRunnable = animationRunnable;
 810     }
 811 
 812     @Override public void requestNextPulse() {
 813         nextPulseRequested.set(true);
 814     }
 815 
 816     @Override public void waitFor(Task t) {
 817         if (t.isFinished()) {
 818             return;
 819         }
 820     }
 821 
 822     @Override protected Object createColorPaint(Color color) {
 823         return new com.sun.prism.paint.Color(
 824                 (float)color.getRed(), (float)color.getGreen(),
 825                 (float)color.getBlue(), (float)color.getOpacity());
 826     }
 827 
 828     private com.sun.prism.paint.Color toPrismColor(Color color) {
 829         return (com.sun.prism.paint.Color) Toolkit.getPaintAccessor().getPlatformPaint(color);
 830     }
 831 
 832     private List<com.sun.prism.paint.Stop> convertStops(List<Stop> paintStops) {
 833         List<com.sun.prism.paint.Stop> stops =
 834             new ArrayList<>(paintStops.size());
 835         for (Stop s : paintStops) {
 836             stops.add(new com.sun.prism.paint.Stop(toPrismColor(s.getColor()),
 837                                                    (float) s.getOffset()));
 838         }
 839         return stops;
 840     }
 841 
 842     @Override protected Object createLinearGradientPaint(LinearGradient paint) {
 843         int cmi = com.sun.prism.paint.Gradient.REPEAT;
 844         CycleMethod cycleMethod = paint.getCycleMethod();
 845         if (cycleMethod == CycleMethod.NO_CYCLE) {
 846             cmi = com.sun.prism.paint.Gradient.PAD;
 847         } else if (cycleMethod == CycleMethod.REFLECT) {
 848             cmi = com.sun.prism.paint.Gradient.REFLECT;
 849         }
 850         // TODO: extract colors/offsets and pass them in directly...
 851         List<com.sun.prism.paint.Stop> stops = convertStops(paint.getStops());
 852         return new com.sun.prism.paint.LinearGradient(
 853             (float)paint.getStartX(), (float)paint.getStartY(), (float)paint.getEndX(), (float)paint.getEndY(),
 854             null, paint.isProportional(), cmi, stops);
 855     }
 856 
 857     @Override
 858     protected Object createRadialGradientPaint(RadialGradient paint) {
 859         float cx = (float)paint.getCenterX();
 860         float cy = (float)paint.getCenterY();
 861         float fa = (float)paint.getFocusAngle();
 862         float fd = (float)paint.getFocusDistance();
 863 
 864         int cmi = 0;
 865         if (paint.getCycleMethod() == CycleMethod.NO_CYCLE) {
 866             cmi = com.sun.prism.paint.Gradient.PAD;
 867         } else if (paint.getCycleMethod() == CycleMethod.REFLECT) {
 868             cmi = com.sun.prism.paint.Gradient.REFLECT;
 869         } else {
 870             cmi = com.sun.prism.paint.Gradient.REPEAT;
 871         }
 872 
 873         // TODO: extract colors/offsets and pass them in directly...
 874         List<com.sun.prism.paint.Stop> stops = convertStops(paint.getStops());
 875         return new com.sun.prism.paint.RadialGradient(cx, cy, fa, fd,
 876                 (float)paint.getRadius(), null, paint.isProportional(), cmi, stops);
 877     }
 878 
 879     @Override
 880     protected Object createImagePatternPaint(ImagePattern paint) {
 881         if (paint.getImage() == null) {
 882             return com.sun.prism.paint.Color.TRANSPARENT;
 883         } else {
 884             return new com.sun.prism.paint.ImagePattern((com.sun.prism.Image) paint.getImage().impl_getPlatformImage(),
 885                     (float)paint.getX(),
 886                     (float)paint.getY(),
 887                     (float)paint.getWidth(),
 888                     (float)paint.getHeight(),
 889                     paint.isProportional(),
 890                     Toolkit.getPaintAccessor().isMutable(paint));
 891         }
 892     }
 893 
 894     static BasicStroke tmpStroke = new BasicStroke();
 895     private void initStroke(StrokeType pgtype, double strokewidth,
 896                             StrokeLineCap pgcap,
 897                             StrokeLineJoin pgjoin, float miterLimit,
 898                             float[] dashArray, float dashOffset)
 899     {
 900         int type;
 901         if (pgtype == StrokeType.CENTERED) {
 902             type = BasicStroke.TYPE_CENTERED;
 903         } else if (pgtype == StrokeType.INSIDE) {
 904             type = BasicStroke.TYPE_INNER;
 905         } else {
 906             type = BasicStroke.TYPE_OUTER;
 907         }
 908 
 909         int cap;
 910         if (pgcap == StrokeLineCap.BUTT) {
 911             cap = BasicStroke.CAP_BUTT;
 912         } else if (pgcap == StrokeLineCap.SQUARE) {
 913             cap = BasicStroke.CAP_SQUARE;
 914         } else {
 915             cap = BasicStroke.CAP_ROUND;
 916         }
 917 
 918         int join;
 919         if (pgjoin == StrokeLineJoin.BEVEL) {
 920             join = BasicStroke.JOIN_BEVEL;
 921         } else if (pgjoin == StrokeLineJoin.MITER) {
 922             join = BasicStroke.JOIN_MITER;
 923         } else {
 924             join = BasicStroke.JOIN_ROUND;
 925         }
 926 
 927         tmpStroke.set(type, (float) strokewidth, cap, join, miterLimit);
 928         if ((dashArray != null) && (dashArray.length > 0)) {
 929             tmpStroke.set(dashArray, dashOffset);
 930         } else {
 931             tmpStroke.set((float[])null, 0);
 932         }
 933     }
 934 
 935     @Override
 936     public void accumulateStrokeBounds(Shape shape, float bbox[],
 937                                        StrokeType pgtype,
 938                                        double strokewidth,
 939                                        StrokeLineCap pgcap,
 940                                        StrokeLineJoin pgjoin,
 941                                        float miterLimit,
 942                                        BaseTransform tx)
 943     {
 944 
 945         initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit, null, 0);
 946         if (tx.isTranslateOrIdentity()) {
 947             tmpStroke.accumulateShapeBounds(bbox, shape, tx);
 948         } else {
 949             Shape.accumulate(bbox, tmpStroke.createStrokedShape(shape), tx);
 950         }
 951     }
 952 
 953     @Override
 954     public boolean strokeContains(Shape shape, double x, double y,
 955                                   StrokeType pgtype,
 956                                   double strokewidth,
 957                                   StrokeLineCap pgcap,
 958                                   StrokeLineJoin pgjoin,
 959                                   float miterLimit)
 960     {
 961         initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit, null, 0);
 962         // TODO: The contains testing could be done directly without creating a Shape
 963         return tmpStroke.createStrokedShape(shape).contains((float) x, (float) y);
 964     }
 965 
 966     @Override
 967     public Shape createStrokedShape(Shape shape,
 968                                     StrokeType pgtype,
 969                                     double strokewidth,
 970                                     StrokeLineCap pgcap,
 971                                     StrokeLineJoin pgjoin,
 972                                     float miterLimit,
 973                                     float[] dashArray,
 974                                     float dashOffset) {
 975         initStroke(pgtype, strokewidth, pgcap, pgjoin, miterLimit,
 976                    dashArray, dashOffset);
 977         return tmpStroke.createStrokedShape(shape);
 978     }
 979 
 980     @Override public Dimension2D getBestCursorSize(int preferredWidth, int preferredHeight) {
 981         return CursorUtils.getBestCursorSize(preferredWidth, preferredHeight);
 982     }
 983 
 984     @Override public int getMaximumCursorColors() {
 985         return 2;
 986     }
 987 
 988     @Override public int getKeyCodeForChar(String character) {
 989         return (character.length() == 1)
 990                 ? com.sun.glass.events.KeyEvent.getKeyCodeForChar(
 991                           character.charAt(0))
 992                 : com.sun.glass.events.KeyEvent.VK_UNDEFINED;
 993     }
 994 
 995     @Override public PathElement[] convertShapeToFXPath(Object shape) {
 996         if (shape == null) {
 997             return new PathElement[0];
 998         }
 999         List<PathElement> elements = new ArrayList<>();
1000         // iterate over the shape and turn it into a series of path
1001         // elements
1002         com.sun.javafx.geom.Shape geomShape = (com.sun.javafx.geom.Shape) shape;
1003         PathIterator itr = geomShape.getPathIterator(null);
1004         PathIteratorHelper helper = new PathIteratorHelper(itr);
1005         PathIteratorHelper.Struct struct = new PathIteratorHelper.Struct();
1006 
1007         while (!helper.isDone()) {
1008             // true if WIND_EVEN_ODD, false if WIND_NON_ZERO
1009             boolean windEvenOdd = helper.getWindingRule() == PathIterator.WIND_EVEN_ODD;
1010             int type = helper.currentSegment(struct);
1011             PathElement el;
1012             if (type == PathIterator.SEG_MOVETO) {
1013                 el = new MoveTo(struct.f0, struct.f1);
1014             } else if (type == PathIterator.SEG_LINETO) {
1015                 el = new LineTo(struct.f0, struct.f1);
1016             } else if (type == PathIterator.SEG_QUADTO) {
1017                 el = new QuadCurveTo(
1018                     struct.f0,
1019                     struct.f1,
1020                     struct.f2,
1021                     struct.f3);
1022             } else if (type == PathIterator.SEG_CUBICTO) {
1023                 el = new CubicCurveTo (
1024                     struct.f0,
1025                     struct.f1,
1026                     struct.f2,
1027                     struct.f3,
1028                     struct.f4,
1029                     struct.f5);
1030             } else if (type == PathIterator.SEG_CLOSE) {
1031                 el = new ClosePath();
1032             } else {
1033                 throw new IllegalStateException("Invalid element type: " + type);
1034             }
1035             helper.next();
1036             elements.add(el);
1037         }
1038 
1039         return elements.toArray(new PathElement[elements.size()]);
1040     }
1041 
1042     @Override public HitInfo convertHitInfoToFX(Object hit) {
1043         Integer textHitPos = (Integer) hit;
1044         HitInfo hitInfo = new HitInfo();
1045         hitInfo.setCharIndex(textHitPos);
1046         hitInfo.setLeading(true);
1047         return hitInfo;
1048     }
1049 
1050     @Override public Filterable toFilterable(Image img) {
1051         return PrImage.create((com.sun.prism.Image) img.impl_getPlatformImage());
1052     }
1053 
1054     @Override public FilterContext getFilterContext(Object config) {
1055         if (config == null || (!(config instanceof com.sun.glass.ui.Screen))) {
1056             return PrFilterContext.getDefaultInstance();
1057         }
1058         Screen screen = (Screen)config;
1059         return PrFilterContext.getInstance(screen);
1060     }
1061 
1062     @Override public AbstractMasterTimer getMasterTimer() {
1063         return MasterTimer.getInstance();
1064     }
1065 
1066     @Override public FontLoader getFontLoader() {
1067         return com.sun.javafx.font.PrismFontLoader.getInstance();
1068     }
1069 
1070     @Override public TextLayoutFactory getTextLayoutFactory() {
1071         return com.sun.javafx.text.PrismTextLayoutFactory.getFactory();
1072     }
1073 
1074     @Override public Object createSVGPathObject(SVGPath svgpath) {
1075         int windingRule = svgpath.getFillRule() == FillRule.NON_ZERO ? PathIterator.WIND_NON_ZERO : PathIterator.WIND_EVEN_ODD;
1076         Path2D path = new Path2D(windingRule);
1077         path.appendSVGPath(svgpath.getContent());
1078         return path;
1079     }
1080 
1081     @Override public Path2D createSVGPath2D(SVGPath svgpath) {
1082         int windingRule = svgpath.getFillRule() == FillRule.NON_ZERO ? PathIterator.WIND_NON_ZERO : PathIterator.WIND_EVEN_ODD;
1083         Path2D path = new Path2D(windingRule);
1084         path.appendSVGPath(svgpath.getContent());
1085         return path;
1086     }
1087 
1088     @Override public boolean imageContains(Object image, float x, float y) {
1089         if (image == null) {
1090             return false;
1091         }
1092 
1093         com.sun.prism.Image pImage = (com.sun.prism.Image)image;
1094         int intX = (int)x + pImage.getMinX();
1095         int intY = (int)y + pImage.getMinY();
1096 
1097         if (pImage.isOpaque()) {
1098             return true;
1099         }
1100 
1101         if (pImage.getPixelFormat() == PixelFormat.INT_ARGB_PRE) {
1102             IntBuffer ib = (IntBuffer) pImage.getPixelBuffer();
1103             int index = intX + intY * pImage.getRowLength();
1104             if (index >= ib.limit()) {
1105                 return false;
1106             } else {
1107                 return (ib.get(index) & 0xff000000) != 0;
1108             }
1109         } else if (pImage.getPixelFormat() == PixelFormat.BYTE_BGRA_PRE) {
1110             ByteBuffer bb = (ByteBuffer) pImage.getPixelBuffer();
1111             int index = intX * pImage.getBytesPerPixelUnit() + intY * pImage.getScanlineStride() + 3;
1112             if (index >= bb.limit()) {
1113                 return false;
1114             } else {
1115                 return (bb.get(index) & 0xff) != 0;
1116             }
1117         } else if (pImage.getPixelFormat() == PixelFormat.BYTE_ALPHA) {
1118             ByteBuffer bb = (ByteBuffer) pImage.getPixelBuffer();
1119             int index = intX * pImage.getBytesPerPixelUnit() + intY * pImage.getScanlineStride();
1120             if (index >= bb.limit()) {
1121                 return false;
1122             } else {
1123                 return (bb.get(index) & 0xff) != 0;
1124             }
1125         }
1126         return true;
1127     }
1128 
1129     @Override
1130     public boolean isNestedLoopRunning() {
1131         return Application.isNestedLoopRunning();
1132     }
1133 
1134     @Override
1135     public boolean isSupported(ConditionalFeature feature) {
1136         switch (feature) {
1137             case SCENE3D:
1138                 return GraphicsPipeline.getPipeline().is3DSupported();
1139             case EFFECT:
1140                 return GraphicsPipeline.getPipeline().isEffectSupported();
1141             case SHAPE_CLIP:
1142                 return true;
1143             case INPUT_METHOD:
1144                 return Application.GetApplication().supportsInputMethods();
1145             case TRANSPARENT_WINDOW:
1146                 return Application.GetApplication().supportsTransparentWindows();
1147             case UNIFIED_WINDOW:
1148                 return Application.GetApplication().supportsUnifiedWindows();
1149             case TWO_LEVEL_FOCUS:
1150                 return Application.GetApplication().hasTwoLevelFocus();
1151             case VIRTUAL_KEYBOARD:
1152                 return Application.GetApplication().hasVirtualKeyboard();
1153             case INPUT_TOUCH:
1154                 return Application.GetApplication().hasTouch();
1155             case INPUT_MULTITOUCH:
1156                 return Application.GetApplication().hasMultiTouch();
1157             case INPUT_POINTER:
1158                 return Application.GetApplication().hasPointer();
1159             default:
1160                 return false;
1161         }
1162     }
1163 
1164     @Override
1165     public boolean isMSAASupported() {
1166         return  GraphicsPipeline.getPipeline().isMSAASupported();
1167     }
1168 
1169     static TransferMode clipboardActionToTransferMode(final int action) {
1170         switch (action) {
1171             case Clipboard.ACTION_NONE:
1172                 return null;
1173             case Clipboard.ACTION_COPY:
1174             //IE drop action for URL copy
1175             case Clipboard.ACTION_COPY | Clipboard.ACTION_REFERENCE:
1176                 return TransferMode.COPY;
1177             case Clipboard.ACTION_MOVE:
1178             //IE drop action for URL move
1179             case Clipboard.ACTION_MOVE | Clipboard.ACTION_REFERENCE:
1180                 return TransferMode.MOVE;
1181             case Clipboard.ACTION_REFERENCE:
1182                 return TransferMode.LINK;
1183             case Clipboard.ACTION_ANY:
1184                 return TransferMode.COPY; // select a reasonable trasnfer mode as workaround until RT-22840
1185         }
1186         return null;
1187     }
1188 
1189     private QuantumClipboard clipboard;
1190     @Override public TKClipboard getSystemClipboard() {
1191         if (clipboard == null) {
1192             clipboard = QuantumClipboard.getClipboardInstance(new ClipboardAssistance(com.sun.glass.ui.Clipboard.SYSTEM));
1193         }
1194         return clipboard;
1195     }
1196 
1197     private GlassSystemMenu systemMenu = new GlassSystemMenu();
1198     @Override public TKSystemMenu getSystemMenu() {
1199         return systemMenu;
1200     }
1201 
1202     @Override public TKClipboard getNamedClipboard(String name) {
1203         return null;
1204     }
1205 
1206     @Override public void startDrag(TKScene scene, Set<TransferMode> tm, TKDragSourceListener l, Dragboard dragboard) {
1207         if (dragboard == null) {
1208             throw new IllegalArgumentException("dragboard should not be null");
1209         }
1210 
1211         GlassScene view = (GlassScene)scene;
1212         view.setTKDragSourceListener(l);
1213 
1214         QuantumClipboard gc = (QuantumClipboard)dragboard.impl_getPeer();
1215         gc.setSupportedTransferMode(tm);
1216         gc.flush();
1217 
1218         // flush causes a modal DnD event loop, when we return, close the clipboard
1219         gc.close();
1220     }
1221 
1222     @Override public void enableDrop(TKScene s, TKDropTargetListener l) {
1223 
1224         assert s instanceof GlassScene;
1225 
1226         GlassScene view = (GlassScene)s;
1227         view.setTKDropTargetListener(l);
1228     }
1229 
1230     @Override public void registerDragGestureListener(TKScene s, Set<TransferMode> tm, TKDragGestureListener l) {
1231 
1232         assert s instanceof GlassScene;
1233 
1234         GlassScene view = (GlassScene)s;
1235         view.setTKDragGestureListener(l);
1236     }
1237 
1238     @Override
1239     public void installInputMethodRequests(TKScene scene, InputMethodRequests requests) {
1240 
1241         assert scene instanceof GlassScene;
1242 
1243         GlassScene view = (GlassScene)scene;
1244         view.setInputMethodRequests(requests);
1245     }
1246 
1247     static class QuantumImage implements com.sun.javafx.tk.ImageLoader, ResourceFactoryListener {
1248 
1249         // cache rt here
1250         private com.sun.prism.RTTexture rt;
1251         private com.sun.prism.Image image;
1252         private ResourceFactory rf;
1253 
1254         QuantumImage(com.sun.prism.Image image) {
1255             this.image = image;
1256         }
1257 
1258         RTTexture getRT(int w, int h, ResourceFactory rfNew) {
1259             boolean rttOk = rt != null && rf == rfNew &&
1260                     rt.getContentWidth() == w && rt.getContentHeight() == h;
1261             if (rttOk) {
1262                 rt.lock();
1263                 if (rt.isSurfaceLost()) {
1264                     rttOk = false;
1265                 }
1266             }
1267 
1268             if (!rttOk) {
1269                 if (rt != null) {
1270                     rt.dispose();
1271                 }
1272                 if (rf != null) {
1273                     rf.removeFactoryListener(this);
1274                     rf = null;
1275                 }
1276                 rt = rfNew.createRTTexture(w, h, WrapMode.CLAMP_TO_ZERO);
1277                 if (rt != null) {
1278                     rf = rfNew;
1279                     rf.addFactoryListener(this);
1280                 }
1281             }
1282 
1283             return rt;
1284         }
1285 
1286         void dispose() {
1287             if (rt != null) {
1288                 rt.dispose();
1289                 rt = null;
1290             }
1291         }
1292 
1293         void setImage(com.sun.prism.Image img) {
1294             image = img;
1295         }
1296 
1297         @Override
1298         public Exception getException() {
1299             return (image == null)
1300                     ? new IllegalStateException("Unitialized image")
1301                     : null;
1302         }
1303         @Override
1304         public int getFrameCount() { return 1; }
1305         @Override
1306         public PlatformImage getFrame(int index) { return image; }
1307         @Override
1308         public int getFrameDelay(int index) { return 0; }
1309         @Override
1310         public int getLoopCount() { return 0; }
1311         @Override
1312         public int getWidth() { return image.getWidth(); }
1313         @Override
1314         public int getHeight() { return image.getHeight(); }
1315         @Override
1316         public void factoryReset() { dispose(); }
1317         @Override
1318         public void factoryReleased() { dispose(); }
1319     }
1320 
1321     @Override public ImageLoader loadPlatformImage(Object platformImage) {
1322         if (platformImage instanceof QuantumImage) {
1323             return (QuantumImage)platformImage;
1324         }
1325 
1326         if (platformImage instanceof com.sun.prism.Image) {
1327             return new QuantumImage((com.sun.prism.Image) platformImage);
1328         }
1329 
1330         throw new UnsupportedOperationException("unsupported class for loadPlatformImage");
1331     }
1332 
1333     @Override
1334     public PlatformImage createPlatformImage(int w, int h) {
1335         ByteBuffer bytebuf = ByteBuffer.allocate(w * h * 4);
1336         return com.sun.prism.Image.fromByteBgraPreData(bytebuf, w, h);
1337     }
1338 
1339     @Override
1340     public Object renderToImage(ImageRenderingContext p) {
1341         Object saveImage = p.platformImage;
1342         final ImageRenderingContext params = p;
1343         final com.sun.prism.paint.Paint currentPaint = p.platformPaint instanceof com.sun.prism.paint.Paint ?
1344                 (com.sun.prism.paint.Paint)p.platformPaint : null;
1345 
1346         RenderJob re = new RenderJob(new Runnable() {
1347 
1348             private com.sun.prism.paint.Color getClearColor() {
1349                 if (currentPaint == null) {
1350                     return com.sun.prism.paint.Color.WHITE;
1351                 } else if (currentPaint.getType() == com.sun.prism.paint.Paint.Type.COLOR) {
1352                     return (com.sun.prism.paint.Color) currentPaint;
1353                 } else if (currentPaint.isOpaque()) {
1354                     return com.sun.prism.paint.Color.TRANSPARENT;
1355                 } else {
1356                     return com.sun.prism.paint.Color.WHITE;
1357                 }
1358             }
1359 
1360             private void draw(Graphics g, int x, int y, int w, int h) {
1361                 g.setLights(params.lights);
1362                 g.setDepthBuffer(params.depthBuffer);
1363 
1364                 g.clear(getClearColor());
1365                 if (currentPaint != null &&
1366                         currentPaint.getType() != com.sun.prism.paint.Paint.Type.COLOR) {
1367                     g.getRenderTarget().setOpaque(currentPaint.isOpaque());
1368                     g.setPaint(currentPaint);
1369                     g.fillQuad(0, 0, w, h);
1370                 }
1371 
1372                 // Set up transform
1373                 if (x != 0 || y != 0) {
1374                     g.translate(-x, -y);
1375                 }
1376                 if (params.transform != null) {
1377                     g.transform(params.transform);
1378                 }
1379 
1380                 if (params.root != null) {
1381                     if (params.camera != null) {
1382                         g.setCamera(params.camera);
1383                     }
1384                     NGNode ngNode = params.root;
1385                     ngNode.render(g);
1386                 }
1387 
1388             }
1389 
1390             @Override
1391             public void run() {
1392 
1393                 ResourceFactory rf = GraphicsPipeline.getDefaultResourceFactory();
1394 
1395                 if (!rf.isDeviceReady()) {
1396                     return;
1397                 }
1398 
1399                 int x = params.x;
1400                 int y = params.y;
1401                 int w = params.width;
1402                 int h = params.height;
1403 
1404                 if (w <= 0 || h <= 0) {
1405                     return;
1406                 }
1407 
1408                 boolean errored = false;
1409                 try {
1410                     QuantumImage pImage = (params.platformImage instanceof QuantumImage) ?
1411                             (QuantumImage)params.platformImage : new QuantumImage(null);
1412 
1413                     com.sun.prism.RTTexture rt = pImage.getRT(w, h, rf);
1414 
1415                     if (rt == null) {
1416                         return;
1417                     }
1418 
1419                     Graphics g = rt.createGraphics();
1420 
1421                     draw(g, x, y, w, h);
1422 
1423                     int[] pixels = pImage.rt.getPixels();
1424 
1425                     if (pixels != null) {
1426                         pImage.setImage(com.sun.prism.Image.fromIntArgbPreData(pixels, w, h));
1427                     } else {
1428                         IntBuffer ib = IntBuffer.allocate(w*h);
1429                         if (pImage.rt.readPixels(ib, pImage.rt.getContentX(),
1430                                 pImage.rt.getContentY(), w, h))
1431                         {
1432                             pImage.setImage(com.sun.prism.Image.fromIntArgbPreData(ib, w, h));
1433                         } else {
1434                             pImage.dispose();
1435                             pImage = null;
1436                         }
1437                     }
1438 
1439                     rt.unlock();
1440 
1441                     params.platformImage = pImage;
1442 
1443                 } catch (Throwable t) {
1444                     errored = true;
1445                     t.printStackTrace(System.err);
1446                 } finally {
1447                     Disposer.cleanUp();
1448                     rf.getTextureResourcePool().freeDisposalRequestedAndCheckResources(errored);
1449                 }
1450             }
1451         });
1452 
1453         final CountDownLatch latch = new CountDownLatch(1);
1454         re.setCompletionListener(job -> latch.countDown());
1455         addRenderJob(re);
1456 
1457         do {
1458             try {
1459                 latch.await();
1460                 break;
1461             } catch (InterruptedException ex) {
1462                 ex.printStackTrace();
1463             }
1464         } while (true);
1465 
1466         Object image = params.platformImage;
1467         params.platformImage = saveImage;
1468 
1469         return image;
1470     }
1471 
1472     @Override
1473     public FileChooserResult showFileChooser(final TKStage ownerWindow,
1474                                       final String title,
1475                                       final File initialDirectory,
1476                                       final String initialFileName,
1477                                       final FileChooserType fileChooserType,
1478                                       final List<FileChooser.ExtensionFilter>
1479                                               extensionFilters,
1480                                       final FileChooser.ExtensionFilter selectedFilter) {
1481         WindowStage blockedStage = null;
1482         try {
1483             // NOTE: we block the owner of the owner deliberately.
1484             //       The native system blocks the nearest owner itself.
1485             //       Otherwise sheets on Mac are unusable.
1486             blockedStage = blockOwnerStage(ownerWindow);
1487 
1488             return CommonDialogs.showFileChooser(
1489                     (ownerWindow instanceof WindowStage)
1490                             ? ((WindowStage) ownerWindow).getPlatformWindow()
1491                             : null,
1492                     initialDirectory,
1493                     initialFileName,
1494                     title,
1495                     (fileChooserType == FileChooserType.SAVE)
1496                             ? CommonDialogs.Type.SAVE
1497                             : CommonDialogs.Type.OPEN,
1498                     (fileChooserType == FileChooserType.OPEN_MULTIPLE),
1499                     convertExtensionFilters(extensionFilters),
1500                     extensionFilters.indexOf(selectedFilter));
1501         } finally {
1502             if (blockedStage != null) {
1503                 blockedStage.setEnabled(true);
1504             }
1505         }
1506     }
1507 
1508     @Override
1509     public File showDirectoryChooser(final TKStage ownerWindow,
1510                                      final String title,
1511                                      final File initialDirectory) {
1512         WindowStage blockedStage = null;
1513         try {
1514             // NOTE: we block the owner of the owner deliberately.
1515             //       The native system blocks the nearest owner itself.
1516             //       Otherwise sheets on Mac are unusable.
1517             blockedStage = blockOwnerStage(ownerWindow);
1518 
1519             return CommonDialogs.showFolderChooser(
1520                     (ownerWindow instanceof WindowStage)
1521                             ? ((WindowStage) ownerWindow).getPlatformWindow()
1522                             : null,
1523                     initialDirectory, title);
1524         } finally {
1525             if (blockedStage != null) {
1526                 blockedStage.setEnabled(true);
1527             }
1528         }
1529     }
1530 
1531     private WindowStage blockOwnerStage(final TKStage stage) {
1532         if (stage instanceof WindowStage) {
1533             final TKStage ownerStage = ((WindowStage) stage).getOwner();
1534             if (ownerStage instanceof WindowStage) {
1535                 final WindowStage ownerWindowStage = (WindowStage) ownerStage;
1536                 ownerWindowStage.setEnabled(false);
1537                 return ownerWindowStage;
1538             }
1539         }
1540 
1541         return null;
1542     }
1543 
1544     private static List<CommonDialogs.ExtensionFilter>
1545             convertExtensionFilters(final List<FileChooser.ExtensionFilter>
1546                                             extensionFilters) {
1547         final CommonDialogs.ExtensionFilter[] glassExtensionFilters =
1548                 new CommonDialogs.ExtensionFilter[extensionFilters.size()];
1549 
1550         int i = 0;
1551         for (final FileChooser.ExtensionFilter extensionFilter:
1552                  extensionFilters) {
1553             glassExtensionFilters[i++] =
1554                     new CommonDialogs.ExtensionFilter(
1555                             extensionFilter.getDescription(),
1556                             extensionFilter.getExtensions());
1557         }
1558 
1559         return Arrays.asList(glassExtensionFilters);
1560     }
1561 
1562     @Override
1563     public long getMultiClickTime() {
1564         return View.getMultiClickTime();
1565     }
1566 
1567     @Override
1568     public int getMultiClickMaxX() {
1569         return View.getMultiClickMaxX();
1570     }
1571 
1572     @Override
1573     public int getMultiClickMaxY() {
1574         return View.getMultiClickMaxY();
1575     }
1576 
1577     @Override
1578     public String getThemeName() {
1579         return Application.GetApplication().getHighContrastTheme();
1580     }
1581 }