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