1 /*
   2  * Copyright (c) 2010, 2017, 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;
  27 
  28 import javafx.application.ConditionalFeature;
  29 import javafx.beans.property.ReadOnlyObjectProperty;
  30 import javafx.geometry.Dimension2D;
  31 import javafx.scene.Scene;
  32 import javafx.scene.effect.BlurType;
  33 import javafx.scene.image.Image;
  34 import javafx.scene.image.PixelFormat;
  35 import javafx.scene.image.WritableImage;
  36 import javafx.scene.input.Dragboard;
  37 import javafx.scene.input.InputMethodRequests;
  38 import javafx.scene.input.KeyCode;
  39 import javafx.scene.input.KeyEvent;
  40 import javafx.scene.input.TransferMode;
  41 import javafx.scene.paint.Color;
  42 import javafx.scene.paint.ImagePattern;
  43 import javafx.scene.paint.LinearGradient;
  44 import javafx.scene.paint.Paint;
  45 import javafx.scene.paint.RadialGradient;
  46 import javafx.scene.paint.Stop;
  47 import javafx.scene.shape.PathElement;
  48 import javafx.scene.shape.SVGPath;
  49 import javafx.scene.shape.StrokeLineCap;
  50 import javafx.scene.shape.StrokeLineJoin;
  51 import javafx.scene.shape.StrokeType;
  52 import javafx.stage.FileChooser.ExtensionFilter;
  53 import javafx.stage.Modality;
  54 import javafx.stage.Stage;
  55 import javafx.stage.StageStyle;
  56 import javafx.stage.Window;
  57 import java.io.File;
  58 import java.io.IOException;
  59 import java.io.InputStream;
  60 import java.nio.ByteBuffer;
  61 import java.security.AccessControlContext;
  62 import java.security.AccessController;
  63 import java.security.PrivilegedAction;
  64 import java.util.ArrayList;
  65 import java.util.HashSet;
  66 import java.util.Iterator;
  67 import java.util.List;
  68 import java.util.Map;
  69 import java.util.Set;
  70 import java.util.WeakHashMap;
  71 import java.util.concurrent.CountDownLatch;
  72 import java.util.concurrent.Future;
  73 import com.sun.glass.ui.CommonDialogs.FileChooserResult;
  74 import com.sun.glass.utils.NativeLibLoader;
  75 import com.sun.javafx.PlatformUtil;
  76 import com.sun.javafx.beans.event.AbstractNotifyListener;
  77 import com.sun.javafx.embed.HostInterface;
  78 import com.sun.javafx.geom.Path2D;
  79 import com.sun.javafx.geom.transform.BaseTransform;
  80 import com.sun.javafx.perf.PerformanceTracker;
  81 import com.sun.javafx.runtime.VersionInfo;
  82 import com.sun.javafx.runtime.async.AsyncOperation;
  83 import com.sun.javafx.runtime.async.AsyncOperationListener;
  84 import com.sun.javafx.scene.SceneHelper;
  85 import com.sun.javafx.scene.text.TextLayoutFactory;
  86 import com.sun.javafx.sg.prism.NGCamera;
  87 import com.sun.javafx.sg.prism.NGLightBase;
  88 import com.sun.javafx.sg.prism.NGNode;
  89 import com.sun.javafx.util.Utils;
  90 import com.sun.scenario.DelayedRunnable;
  91 import com.sun.scenario.animation.AbstractMasterTimer;
  92 import com.sun.scenario.effect.AbstractShadow.ShadowMode;
  93 import com.sun.scenario.effect.Color4f;
  94 import com.sun.scenario.effect.FilterContext;
  95 import com.sun.scenario.effect.Filterable;
  96 
  97 
  98 public abstract class Toolkit {
  99     private static String tk;
 100     private static Toolkit TOOLKIT;
 101     private static Thread fxUserThread = null;
 102 
 103     private static final String QUANTUM_TOOLKIT     = "com.sun.javafx.tk.quantum.QuantumToolkit";
 104     private static final String DEFAULT_TOOLKIT     = QUANTUM_TOOLKIT;
 105 
 106     private static final Map gradientMap = new WeakHashMap();
 107 
 108     private static final boolean verbose = AccessController.doPrivileged((PrivilegedAction<Boolean>) () -> Boolean.getBoolean("javafx.verbose"));
 109 
 110     private static final String[] msLibNames = {
 111         "api-ms-win-core-console-l1-1-0",
 112         "api-ms-win-core-datetime-l1-1-0",
 113         "api-ms-win-core-debug-l1-1-0",
 114         "api-ms-win-core-errorhandling-l1-1-0",
 115         "api-ms-win-core-file-l1-1-0",
 116         "api-ms-win-core-file-l1-2-0",
 117         "api-ms-win-core-file-l2-1-0",
 118         "api-ms-win-core-handle-l1-1-0",
 119         "api-ms-win-core-heap-l1-1-0",
 120         "api-ms-win-core-interlocked-l1-1-0",
 121         "api-ms-win-core-libraryloader-l1-1-0",
 122         "api-ms-win-core-localization-l1-2-0",
 123         "api-ms-win-core-memory-l1-1-0",
 124         "api-ms-win-core-namedpipe-l1-1-0",
 125         "api-ms-win-core-processenvironment-l1-1-0",
 126         "api-ms-win-core-processthreads-l1-1-0",
 127         "api-ms-win-core-processthreads-l1-1-1",
 128         "api-ms-win-core-profile-l1-1-0",
 129         "api-ms-win-core-rtlsupport-l1-1-0",
 130         "api-ms-win-core-string-l1-1-0",
 131         "api-ms-win-core-synch-l1-1-0",
 132         "api-ms-win-core-synch-l1-2-0",
 133         "api-ms-win-core-sysinfo-l1-1-0",
 134         "api-ms-win-core-timezone-l1-1-0",
 135         "api-ms-win-core-util-l1-1-0",
 136         "api-ms-win-crt-conio-l1-1-0",
 137         "api-ms-win-crt-convert-l1-1-0",
 138         "api-ms-win-crt-environment-l1-1-0",
 139         "api-ms-win-crt-filesystem-l1-1-0",
 140         "api-ms-win-crt-heap-l1-1-0",
 141         "api-ms-win-crt-locale-l1-1-0",
 142         "api-ms-win-crt-math-l1-1-0",
 143         "api-ms-win-crt-multibyte-l1-1-0",
 144         "api-ms-win-crt-private-l1-1-0",
 145         "api-ms-win-crt-process-l1-1-0",
 146         "api-ms-win-crt-runtime-l1-1-0",
 147         "api-ms-win-crt-stdio-l1-1-0",
 148         "api-ms-win-crt-string-l1-1-0",
 149         "api-ms-win-crt-time-l1-1-0",
 150         "api-ms-win-crt-utility-l1-1-0",
 151         "ucrtbase",
 152 
 153         // Finally load VS 2017 DLLs in the following order
 154         "vcruntime140",
 155         "msvcp140",
 156         "concrt140"
 157 };
 158 
 159     private static String lookupToolkitClass(String name) {
 160         if ("prism".equalsIgnoreCase(name)) {
 161             return QUANTUM_TOOLKIT;
 162         } else if ("quantum".equalsIgnoreCase(name)) {
 163             return QUANTUM_TOOLKIT;
 164         }
 165         return name;
 166     }
 167 
 168     public static synchronized void loadMSWindowsLibraries() {
 169         for (String libName : msLibNames) {
 170             try {
 171                 NativeLibLoader.loadLibrary(libName);
 172             } catch (Throwable t) {
 173                 if (verbose) {
 174                     System.err.println("Error: failed to load "
 175                             + libName + ".dll : " + t);
 176                 }
 177             }
 178         }
 179     }
 180 
 181     private static String getDefaultToolkit() {
 182         if (PlatformUtil.isWindows()) {
 183             return DEFAULT_TOOLKIT;
 184         } else if (PlatformUtil.isMac()) {
 185             return DEFAULT_TOOLKIT;
 186         } else if (PlatformUtil.isLinux()) {
 187             return DEFAULT_TOOLKIT;
 188         } else if (PlatformUtil.isIOS()) {
 189             return DEFAULT_TOOLKIT;
 190         } else if (PlatformUtil.isAndroid()) {
 191            return DEFAULT_TOOLKIT;
 192         }
 193 
 194         throw new UnsupportedOperationException(System.getProperty("os.name") + " is not supported");
 195     }
 196 
 197     public static synchronized Toolkit getToolkit() {
 198         if (TOOLKIT != null) {
 199             return TOOLKIT;
 200         }
 201 
 202         // This loading of msvcp140.dll and vcruntime140.dll (VS2017) is required on Windows platforms
 203         if (PlatformUtil.isWindows()) {
 204             loadMSWindowsLibraries();
 205         }
 206 
 207         AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
 208             // Get the javafx.version and javafx.runtime.version from a preconstructed
 209             // java class, VersionInfo, created at build time.
 210             VersionInfo.setupSystemProperties();
 211             return null;
 212         });
 213 
 214         boolean userSpecifiedToolkit = true;
 215 
 216         // Check a system property to see if there is a specific toolkit to use.
 217         // This is not a doPriviledged check so that applets cannot use this.
 218         String forcedToolkit = null;
 219         try {
 220             forcedToolkit = System.getProperty("javafx.toolkit");
 221         } catch (SecurityException ex) {}
 222 
 223         if (forcedToolkit == null) {
 224             forcedToolkit = tk;
 225         }
 226         if (forcedToolkit == null) {
 227             userSpecifiedToolkit = false;
 228             forcedToolkit = getDefaultToolkit();
 229         }
 230 
 231         if (forcedToolkit.indexOf('.') == -1) {
 232             // Turn a short name into a fully qualified classname
 233             forcedToolkit = lookupToolkitClass(forcedToolkit);
 234         }
 235 
 236         boolean printToolkit = verbose
 237                 || (userSpecifiedToolkit && !forcedToolkit.endsWith("StubToolkit"));
 238 
 239         try {
 240             Class clz = null;
 241 
 242             try {
 243                 // try our priveledged loader first
 244                 final ClassLoader loader = Toolkit.class.getClassLoader();
 245                 clz = Class.forName(forcedToolkit, false, loader);
 246             } catch (ClassNotFoundException e) {
 247                 // fall back and try the application class loader
 248                 final ClassLoader loader = Thread.currentThread().getContextClassLoader();
 249                 clz = Class.forName(forcedToolkit, false, loader);
 250             }
 251 
 252             // Check that clz is a subclass of Toolkit
 253             if (!Toolkit.class.isAssignableFrom(clz)) {
 254                 throw new IllegalArgumentException("Unrecognized FX Toolkit class: "
 255                         + forcedToolkit);
 256             }
 257 
 258             TOOLKIT = (Toolkit)clz.newInstance();
 259             if (TOOLKIT.init()) {
 260                 if (printToolkit) {
 261                     System.err.println("JavaFX: using " + forcedToolkit);
 262                 }
 263                 return TOOLKIT;
 264             }
 265             TOOLKIT = null;
 266         } catch (Exception any) {
 267             TOOLKIT = null;
 268             any.printStackTrace();
 269         }
 270 
 271         throw new RuntimeException("No toolkit found");
 272     }
 273 
 274     protected static Thread getFxUserThread() {
 275         return fxUserThread;
 276     }
 277 
 278     protected static void setFxUserThread(Thread t) {
 279         if (fxUserThread != null) {
 280             throw new IllegalStateException("Error: FX User Thread already initialized");
 281         }
 282 
 283         fxUserThread = t;
 284     }
 285 
 286     public void checkFxUserThread() {
 287         // Throw exception if not on FX user thread
 288         if (!isFxUserThread()) {
 289             throw new IllegalStateException("Not on FX application thread; currentThread = "
 290                     + Thread.currentThread().getName());
 291         }
 292     }
 293 
 294     // Toolkit can override this if needed
 295     public boolean isFxUserThread() {
 296         return Thread.currentThread() == fxUserThread;
 297     }
 298 
 299     protected Toolkit() {
 300     }
 301 
 302     public abstract boolean init();
 303 
 304     /**
 305      * Indicates whether or not a nested event loop can be started
 306      * from the current thread in the current state. Note that a nested
 307      * event loop is not allowed outside of an event handler.
 308      *
 309      * @return flag indicating whether a nested event loop can be started.
 310      */
 311     public abstract boolean canStartNestedEventLoop();
 312 
 313     /**
 314      * Enter a nested event loop and block until the corresponding
 315      * exitNestedEventLoop call is made.
 316      * The key passed into this method is used to
 317      * uniquely identify the matched enter/exit pair. This method creates a
 318      * new nested event loop and blocks until the corresponding
 319      * exitNestedEventLoop method is called with the same key.
 320      * The return value of this method will be the {@code rval}
 321      * object supplied to the exitNestedEventLoop method call that unblocks it.
 322      *
 323      * @param key the Object that identifies the nested event loop, which
 324      * must not be null
 325      *
 326      * @throws IllegalArgumentException if the specified key is associated
 327      * with a nested event loop that has not yet returned
 328      *
 329      * @throws NullPointerException if the key is null
 330      *
 331      * @throws IllegalStateException if this method is called on a thread
 332      * other than the FX Application thread
 333      *
 334      * @return the value passed into the corresponding call to exitEventLoop
 335      */
 336     public abstract Object enterNestedEventLoop(Object key);
 337 
 338     /**
 339      * Exit a nested event loop and unblock the caller of the
 340      * corresponding enterNestedEventLoop.
 341      * The key passed into this method is used to
 342      * uniquely identify the matched enter/exit pair. This method causes the
 343      * nested event loop that was previously created with the key to exit and
 344      * return control to the caller. If the specified nested event loop is not
 345      * the inner-most loop then it will not return until all other inner loops
 346      * also exit.
 347      *
 348      * @param key the Object that identifies the nested event loop, which
 349      * must not be null
 350      *
 351      * @param rval an Object that is returned to the caller of the
 352      * corresponding enterNestedEventLoop. This may be null.
 353      *
 354      * @throws IllegalArgumentException if the specified key is not associated
 355      * with an active nested event loop
 356      *
 357      * @throws NullPointerException if the key is null
 358      *
 359      * @throws IllegalStateException if this method is called on a thread
 360      * other than the FX Application thread
 361      */
 362     public abstract void exitNestedEventLoop(Object key, Object rval);
 363 
 364     public abstract boolean isNestedLoopRunning();
 365 
 366     public abstract TKStage createTKStage(Window peerWindow, boolean securityDialog, StageStyle stageStyle, boolean primary, Modality modality, TKStage owner, boolean rtl, AccessControlContext acc);
 367 
 368     public abstract TKStage createTKPopupStage(Window peerWindow, StageStyle popupStyle, TKStage owner, AccessControlContext acc);
 369     public abstract TKStage createTKEmbeddedStage(HostInterface host, AccessControlContext acc);
 370 
 371     /**
 372      * Creates an AppletWindow using the provided window pointer as the parent
 373      * window.
 374      *
 375      * @param parent the native parent which will contain the primary stage
 376      * window(s). Used on Windows/Linux platforms.
 377      *
 378      * @param serverName the name of CARemoteLayerServer which
 379      * will be used to register native layer. Used on Mac platform.
 380      */
 381     public abstract AppletWindow createAppletWindow(long parent, String serverName);
 382 
 383     /**
 384      * Perform cleanup in preparation for applet termination, including closing
 385      * the applet window.
 386      */
 387     public abstract void closeAppletWindow();
 388 
 389     private final Map<TKPulseListener,AccessControlContext> stagePulseListeners =
 390             new WeakHashMap<TKPulseListener,AccessControlContext>();
 391     private final Map<TKPulseListener,AccessControlContext> scenePulseListeners =
 392             new WeakHashMap<TKPulseListener,AccessControlContext>();
 393     private final Map<TKPulseListener,AccessControlContext> postScenePulseListeners =
 394             new WeakHashMap<TKPulseListener,AccessControlContext>();
 395     private final Map<TKListener,AccessControlContext> toolkitListeners =
 396             new WeakHashMap<TKListener,AccessControlContext>();
 397 
 398     // The set of shutdown hooks is strongly held to avoid premature GC.
 399     private final Set<Runnable> shutdownHooks = new HashSet<Runnable>();
 400 
 401     private void runPulse(final TKPulseListener listener,
 402             final AccessControlContext acc) {
 403 
 404         if (acc == null) {
 405             throw new IllegalStateException("Invalid AccessControlContext");
 406         }
 407 
 408         AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 409             listener.pulse();
 410             return null;
 411         }, acc);
 412     }
 413 
 414     public void firePulse() {
 415         // Stages need to be notified of pulses before scenes so the Stage can resized
 416         // and those changes propogated to scene before it gets its pulse to update
 417 
 418         // Copy of listener map
 419         final Map<TKPulseListener,AccessControlContext> stagePulseList =
 420                 new WeakHashMap<TKPulseListener,AccessControlContext>();
 421         final Map<TKPulseListener,AccessControlContext> scenePulseList =
 422                 new WeakHashMap<TKPulseListener,AccessControlContext>();
 423         final Map<TKPulseListener,AccessControlContext> postScenePulseList =
 424                 new WeakHashMap<TKPulseListener,AccessControlContext>();
 425 
 426         synchronized (this) {
 427             stagePulseList.putAll(stagePulseListeners);
 428             scenePulseList.putAll(scenePulseListeners);
 429             postScenePulseList.putAll(postScenePulseListeners);
 430         }
 431         for (Map.Entry<TKPulseListener,AccessControlContext> entry : stagePulseList.entrySet()) {
 432             runPulse(entry.getKey(), entry.getValue());
 433         }
 434         for (Map.Entry<TKPulseListener,AccessControlContext> entry : scenePulseList.entrySet()) {
 435             runPulse(entry.getKey(), entry.getValue());
 436         }
 437         for (Map.Entry<TKPulseListener,AccessControlContext> entry : postScenePulseList.entrySet()) {
 438             runPulse(entry.getKey(), entry.getValue());
 439         }
 440 
 441         if (lastTkPulseListener != null) {
 442             runPulse(lastTkPulseListener, lastTkPulseAcc);
 443         }
 444     }
 445     public void addStageTkPulseListener(TKPulseListener listener) {
 446         if (listener == null) {
 447             return;
 448         }
 449         synchronized (this) {
 450             AccessControlContext acc = AccessController.getContext();
 451             stagePulseListeners.put(listener, acc);
 452         }
 453     }
 454     public void removeStageTkPulseListener(TKPulseListener listener) {
 455         synchronized (this) {
 456             stagePulseListeners.remove(listener);
 457         }
 458     }
 459     public void addSceneTkPulseListener(TKPulseListener listener) {
 460         if (listener == null) {
 461             return;
 462         }
 463         synchronized (this) {
 464             AccessControlContext acc = AccessController.getContext();
 465             scenePulseListeners.put(listener, acc);
 466         }
 467     }
 468     public void removeSceneTkPulseListener(TKPulseListener listener) {
 469         synchronized (this) {
 470             scenePulseListeners.remove(listener);
 471         }
 472     }
 473     public void addPostSceneTkPulseListener(TKPulseListener listener) {
 474         if (listener == null) {
 475             return;
 476         }
 477         synchronized (this) {
 478             AccessControlContext acc = AccessController.getContext();
 479             postScenePulseListeners.put(listener, acc);
 480         }
 481     }
 482     public void removePostSceneTkPulseListener(TKPulseListener listener) {
 483         synchronized (this) {
 484             postScenePulseListeners.remove(listener);
 485         }
 486     }
 487 
 488     public void addTkListener(TKListener listener) {
 489         if (listener == null) {
 490             return;
 491         }
 492         AccessControlContext acc = AccessController.getContext();
 493         toolkitListeners.put(listener, acc);
 494     }
 495 
 496     public void removeTkListener(TKListener listener) {
 497         toolkitListeners.remove(listener);
 498     }
 499 
 500     private TKPulseListener lastTkPulseListener = null;
 501     private AccessControlContext lastTkPulseAcc = null;
 502     public void setLastTkPulseListener(TKPulseListener listener) {
 503         lastTkPulseAcc = AccessController.getContext();
 504         lastTkPulseListener = listener;
 505     }
 506 
 507     public void addShutdownHook(Runnable hook) {
 508         if (hook == null) {
 509             return;
 510         }
 511         synchronized (shutdownHooks) {
 512             shutdownHooks.add(hook);
 513         }
 514     }
 515 
 516     public void removeShutdownHook(Runnable hook) {
 517         synchronized (shutdownHooks) {
 518             shutdownHooks.remove(hook);
 519         }
 520     }
 521 
 522     protected void notifyShutdownHooks() {
 523         List<Runnable> hooks;
 524         synchronized (shutdownHooks) {
 525             hooks = new ArrayList<Runnable>(shutdownHooks);
 526             shutdownHooks.clear();
 527         }
 528 
 529         for (Runnable hook : hooks) {
 530             hook.run();
 531         }
 532     }
 533 
 534     public void notifyWindowListeners(final List<TKStage> windows) {
 535         for (Map.Entry<TKListener,AccessControlContext> entry : toolkitListeners.entrySet()) {
 536             final TKListener listener = entry.getKey();
 537             final AccessControlContext acc = entry.getValue();
 538             if (acc == null) {
 539                 throw new IllegalStateException("Invalid AccessControlContext");
 540             }
 541 
 542             AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
 543                 listener.changedTopLevelWindows(windows);
 544                 return null;
 545             }, acc);
 546         }
 547     }
 548 
 549     public void notifyLastNestedLoopExited() {
 550         for (TKListener listener: toolkitListeners.keySet()) {
 551             listener.exitedLastNestedLoop();
 552         }
 553     }
 554 
 555     // notify the pulse timer code that we need the next pulse to happen
 556     // this flag is cleared each cycle so subsequent pulses must be requested
 557     public abstract void requestNextPulse();
 558 
 559     public abstract Future addRenderJob(RenderJob rj);
 560 
 561     public abstract ImageLoader loadImage(String url,
 562                                           double width, double height,
 563                                           boolean preserveRatio,
 564                                           boolean smooth);
 565     public abstract ImageLoader loadImage(InputStream stream,
 566                                           double width, double height,
 567                                           boolean preserveRatio,
 568                                           boolean smooth);
 569     public abstract AsyncOperation loadImageAsync(
 570                                           AsyncOperationListener<? extends ImageLoader> listener,
 571                                           String url,
 572                                           double width, double height,
 573                                           boolean preserveRatio,
 574                                           boolean smooth);
 575 
 576     /*
 577      * The loadPlatformImage method supports the following image types:
 578      *   - an object returned by the renderToImage method
 579      *   - an instance of com.sun.prism.Image (in case of prism)
 580      *   - an instance of an external image object, which can be a BufferedImage
 581      * If JavaFX Image had one more constructor Image(ImageLoader),
 582      * we could introduce a different method for external image loading support.
 583      */
 584 
 585     public abstract ImageLoader loadPlatformImage(Object platformImage);
 586 
 587     public abstract PlatformImage createPlatformImage(int w, int h);
 588 
 589     // Indicates the default state of smooth for ImageView and MediaView
 590     // Subclasses may override this to provide a platform-specific default
 591     public boolean getDefaultImageSmooth() { return true; }
 592 
 593     public abstract void startup(Runnable runnable);
 594     public abstract void defer(Runnable runnable);
 595     public void exit() {
 596         fxUserThread = null;
 597     }
 598 
 599     public abstract Map<Object, Object> getContextMap();
 600     public abstract int getRefreshRate();
 601     public abstract void setAnimationRunnable(DelayedRunnable animationRunnable);
 602     public abstract PerformanceTracker getPerformanceTracker();
 603     public abstract PerformanceTracker createPerformanceTracker();
 604 
 605     //to be used for testing only
 606     public abstract void waitFor(Task t);
 607 
 608     private Object checkSingleColor(List<Stop> stops) {
 609         if (stops.size() == 2) {
 610             Color c = stops.get(0).getColor();
 611             if (c.equals(stops.get(1).getColor())) {
 612                 return Toolkit.getPaintAccessor().getPlatformPaint(c);
 613             }
 614         }
 615         return null;
 616     }
 617 
 618     private Object getPaint(LinearGradient paint) {
 619         Object p = gradientMap.get(paint);
 620         if (p != null) {
 621             return p;
 622         }
 623         p = checkSingleColor(paint.getStops());
 624         if (p == null) {
 625             p = createLinearGradientPaint(paint);
 626         }
 627         gradientMap.put(paint, p);
 628         return p;
 629     }
 630 
 631     private Object getPaint(RadialGradient paint) {
 632         Object p = gradientMap.get(paint);
 633         if (p != null) {
 634             return p;
 635         }
 636         p = checkSingleColor(paint.getStops());
 637         if (p == null) {
 638             p = createRadialGradientPaint(paint);
 639         }
 640         gradientMap.put(paint, p);
 641         return p;
 642     }
 643 
 644     public Object getPaint(Paint paint) {
 645         if (paint instanceof Color) {
 646             return createColorPaint((Color) paint);
 647         }
 648 
 649         if (paint instanceof LinearGradient) {
 650             return getPaint((LinearGradient) paint);
 651         }
 652 
 653         if (paint instanceof RadialGradient) {
 654             return getPaint((RadialGradient) paint);
 655         }
 656 
 657         if (paint instanceof ImagePattern) {
 658             return createImagePatternPaint((ImagePattern) paint);
 659         }
 660 
 661         return null;
 662     }
 663 
 664     protected static final double clampStopOffset(double offset) {
 665         return (offset > 1.0) ? 1.0 :
 666                (offset < 0.0) ? 0.0 : offset;
 667     }
 668 
 669     protected abstract Object createColorPaint(Color paint);
 670     protected abstract Object createLinearGradientPaint(LinearGradient paint);
 671     protected abstract Object createRadialGradientPaint(RadialGradient paint);
 672     protected abstract Object createImagePatternPaint(ImagePattern paint);
 673 
 674     public abstract void
 675         accumulateStrokeBounds(com.sun.javafx.geom.Shape shape,
 676                                float bbox[],
 677                                StrokeType type,
 678                                double strokewidth,
 679                                StrokeLineCap cap,
 680                                StrokeLineJoin join,
 681                                float miterLimit,
 682                                BaseTransform tx);
 683 
 684     public abstract boolean
 685         strokeContains(com.sun.javafx.geom.Shape shape,
 686                        double x, double y,
 687                        StrokeType type,
 688                        double strokewidth,
 689                        StrokeLineCap cap,
 690                        StrokeLineJoin join,
 691                        float miterLimit);
 692 
 693     public abstract com.sun.javafx.geom.Shape
 694         createStrokedShape(com.sun.javafx.geom.Shape shape,
 695                            StrokeType type,
 696                            double strokewidth,
 697                            StrokeLineCap cap,
 698                            StrokeLineJoin join,
 699                            float miterLimit,
 700                            float[] dashArray,
 701                            float dashOffset);
 702 
 703     public abstract int getKeyCodeForChar(String character);
 704     public abstract Dimension2D getBestCursorSize(int preferredWidth, int preferredHeight);
 705     public abstract int getMaximumCursorColors();
 706     public abstract PathElement[] convertShapeToFXPath(Object shape);
 707 
 708     public abstract Filterable toFilterable(Image img);
 709     public abstract FilterContext getFilterContext(Object config);
 710 
 711     public abstract boolean isForwardTraversalKey(KeyEvent e);
 712     public abstract boolean isBackwardTraversalKey(KeyEvent e);
 713 
 714     public abstract AbstractMasterTimer getMasterTimer();
 715 
 716     public abstract FontLoader getFontLoader();
 717     public abstract TextLayoutFactory getTextLayoutFactory();
 718 
 719     public abstract Object createSVGPathObject(SVGPath svgpath);
 720     public abstract Path2D createSVGPath2D(SVGPath svgpath);
 721 
 722     /**
 723      * Tests whether the pixel on the given coordinates in the given image
 724      * is non-empty (not fully transparent). Return value is not defined
 725      * for pixels out of the image bounds.
 726      */
 727     public abstract boolean imageContains(Object image, float x, float y);
 728 
 729     public abstract TKClipboard getSystemClipboard();
 730 
 731     public TKClipboard createLocalClipboard() {
 732         return new LocalClipboard();
 733     }
 734 
 735     public abstract TKSystemMenu getSystemMenu();
 736 
 737     public abstract TKClipboard getNamedClipboard(String name);
 738 
 739     public boolean isSupported(ConditionalFeature feature) { return false; }
 740 
 741     public boolean isMSAASupported() { return false; }
 742 
 743     public abstract ScreenConfigurationAccessor setScreenConfigurationListener(TKScreenConfigurationListener listener);
 744 
 745     public abstract Object getPrimaryScreen();
 746 
 747     public abstract List<?> getScreens();
 748 
 749     public abstract ScreenConfigurationAccessor getScreenConfigurationAccessor();
 750 
 751     public abstract void registerDragGestureListener(TKScene s, Set<TransferMode> tm, TKDragGestureListener l);
 752 
 753     /**
 754      * This function is called when a drag originates within a JavaFX application.
 755      * This means that drags that originate in other applications / from the OS
 756      * do not call this function.
 757      * The argument o represents an object used to identify a scene on which
 758      * the drag has started.
 759      */
 760     public abstract void startDrag(TKScene scene, Set<TransferMode> tm, TKDragSourceListener l, Dragboard dragboard);
 761 
 762     // template function which can be implemented by toolkit impls such that they
 763     // can be informed when a drag and drop operation has completed. This allows
 764     // for any cleanup that may need to be done.
 765     public void stopDrag(Dragboard dragboard) {
 766         // no-op
 767     }
 768 
 769     public abstract void enableDrop(TKScene s, TKDropTargetListener l);
 770 
 771     public interface Task {
 772         boolean isFinished();
 773     }
 774 
 775     public Color4f toColor4f(Color color) {
 776         return new Color4f((float)color.getRed(), (float)color.getGreen(), (float)color.getBlue(), (float)color.getOpacity());
 777     }
 778 
 779 
 780     public ShadowMode toShadowMode(BlurType blurType) {
 781         switch (blurType) {
 782             case ONE_PASS_BOX:
 783                 return ShadowMode.ONE_PASS_BOX;
 784             case TWO_PASS_BOX:
 785                 return ShadowMode.TWO_PASS_BOX;
 786             case THREE_PASS_BOX:
 787                 return ShadowMode.THREE_PASS_BOX;
 788             default:
 789                 return ShadowMode.GAUSSIAN;
 790         }
 791     }
 792 
 793     public abstract void installInputMethodRequests(TKScene scene, InputMethodRequests requests);
 794 
 795     /*
 796      * ImageRenderingContext holds the many parameters passed to
 797      * the renderToImage method.
 798      * The use of the parameters is specified by the renderToImage
 799      * method.
 800      * @see #renderToImage
 801      */
 802     public static class ImageRenderingContext {
 803         // Node to be rendered
 804         public NGNode root;
 805 
 806         // Viewport for rendering
 807         public int x;
 808         public int y;
 809         public int width;
 810         public int height;
 811 
 812         // Initial transform for root node
 813         public BaseTransform transform;
 814 
 815         // Rendering parameters either from Scene or SnapShotParams
 816         public boolean depthBuffer;
 817         public Object platformPaint;
 818         public NGCamera camera;
 819         public NGLightBase[] lights;
 820 
 821         // PlatformImage into which to render or null
 822         public Object platformImage;
 823     }
 824 
 825     /*
 826      * This method renders a PG-graph to a platform image object.
 827      * The returned object can be turned into a useable
 828      * scene graph image using the appropriate factor of the
 829      * Image class.
 830      * The scale specified in the params is used to scale the
 831      * entire rendering before any transforms in the nodes are
 832      * applied.
 833      * The width and height specified in the params represent
 834      * the user space dimensions to be rendered.  The returned
 835      * image will be large enough to hold these dimensions
 836      * scaled by the scale parameter.
 837      * The depthBuffer specified in the params is used to determine
 838      * with or without depthBuffer rendering should be performed.
 839      * The root node is the root of a tree of toolkit-specific
 840      * scene graph peer nodes to be rendered and should have
 841      * been previously created by this toolkit.
 842      * The platformPaint specified in the params must be
 843      * generated by the appropriate Toolkit.createPaint method
 844      * and is used to fill the background of the image before
 845      * rendering the scene graph.
 846      * The platformImage specified in the params may be non-null
 847      * and should be a previous return value from this method.
 848      * If it is non-null then it may be reused as the return value
 849      * of this method if it is still valid and large enough to
 850      * hold the requested size.
 851      *
 852      * @param context a ImageRenderingContext instance specifying
 853      *               the various rendering parameters
 854      * @return a platform specific image object
 855      * @see Toolkit.getImageAccessor().fromPlatformImage
 856      */
 857 
 858     public abstract Object renderToImage(ImageRenderingContext context);
 859 
 860     /**
 861      * Returns the key code for the key which is commonly used on the
 862      * corresponding platform as a modifier key in shortcuts. For example
 863      * it is {@code KeyCode.CONTROL} on Windows (Ctrl + C, Ctrl + V ...) and
 864      * {@code KeyCode.META} on MacOS (Cmd + C, Cmd + V ...).
 865      *
 866      * @return the key code for shortcut modifier key
 867      */
 868     public KeyCode getPlatformShortcutKey() {
 869         return PlatformUtil.isMac() ? KeyCode.META : KeyCode.CONTROL;
 870     }
 871 
 872     public abstract FileChooserResult showFileChooser(
 873             TKStage ownerWindow,
 874             String title,
 875             File initialDirectory,
 876             String initialFileName,
 877             FileChooserType fileChooserType,
 878             List<ExtensionFilter> extensionFilters,
 879             ExtensionFilter selectedFilter);
 880 
 881     public abstract File showDirectoryChooser(
 882             TKStage ownerWindow,
 883             String title,
 884             File initialDirectory);
 885 
 886     /*
 887      * Methods for obtaining "double-click" speed value.
 888      */
 889     public abstract long getMultiClickTime();
 890     public abstract int getMultiClickMaxX();
 891     public abstract int getMultiClickMaxY();
 892 
 893     private CountDownLatch pauseScenesLatch = null;
 894 
 895     public interface WritableImageAccessor {
 896         public void loadTkImage(WritableImage wimg, Object loader);
 897         public Object getTkImageLoader(WritableImage wimg);
 898     }
 899 
 900     private static WritableImageAccessor writableImageAccessor = null;
 901 
 902     public static void setWritableImageAccessor(WritableImageAccessor accessor) {
 903         writableImageAccessor = accessor;
 904     }
 905 
 906     public static WritableImageAccessor getWritableImageAccessor() {
 907         return writableImageAccessor;
 908     }
 909 
 910     public interface PaintAccessor {
 911         public boolean isMutable(Paint paint);
 912         public Object getPlatformPaint(Paint paint);
 913         public void addListener(Paint paint, AbstractNotifyListener platformChangeListener);
 914         public void removeListener(Paint paint, AbstractNotifyListener platformChangeListener);
 915     }
 916 
 917     private static PaintAccessor paintAccessor = null;
 918 
 919     public static void setPaintAccessor(PaintAccessor accessor) {
 920         paintAccessor = accessor;
 921     }
 922 
 923     public static PaintAccessor getPaintAccessor() {
 924         return paintAccessor;
 925     }
 926 
 927     public interface ImageAccessor {
 928         public boolean isAnimation(Image image);
 929         public ReadOnlyObjectProperty<PlatformImage>getImageProperty(Image image);
 930         public int[] getPreColors(PixelFormat<ByteBuffer> pf);
 931         public int[] getNonPreColors(PixelFormat<ByteBuffer> pf);
 932         public Object getPlatformImage(Image image);
 933         public Image fromPlatformImage(Object image);
 934     }
 935 
 936     private static ImageAccessor imageAccessor;
 937 
 938     static {
 939         // Need to ensure that the Image class is loaded since Toolkit class
 940         // is the provider of getImageAccessor method and sets the accessor.
 941         Utils.forceInit(Image.class);
 942     }
 943 
 944     public static void setImageAccessor(ImageAccessor accessor) {
 945         imageAccessor = accessor;
 946     }
 947 
 948     public static ImageAccessor getImageAccessor() {
 949         return imageAccessor;
 950     }
 951 
 952     public String getThemeName() {
 953         return null;
 954     }
 955 }