boot-fx/src/main/java/net/java/html/boot/fx/FXBrowsers.java
author Jaroslav Tulach <jtulach@netbeans.org>
Fri, 02 Oct 2015 08:57:14 +0200
changeset 1006 a0f79e32d526
parent 889 548982033730
child 1037 e390a06dbfac
permissions -rw-r--r--
Ability to run the JavaFX presenter in headless mode is useful for testing
     1 /**
     2  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     3  *
     4  * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
     5  *
     6  * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
     7  * Other names may be trademarks of their respective owners.
     8  *
     9  * The contents of this file are subject to the terms of either the GNU
    10  * General Public License Version 2 only ("GPL") or the Common
    11  * Development and Distribution License("CDDL") (collectively, the
    12  * "License"). You may not use this file except in compliance with the
    13  * License. You can obtain a copy of the License at
    14  * http://www.netbeans.org/cddl-gplv2.html
    15  * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    16  * specific language governing permissions and limitations under the
    17  * License.  When distributing the software, include this License Header
    18  * Notice in each file and include the License file at
    19  * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    20  * particular file as subject to the "Classpath" exception as provided
    21  * by Oracle in the GPL Version 2 section of the License file that
    22  * accompanied this code. If applicable, add the following below the
    23  * License Header, with the fields enclosed by brackets [] replaced by
    24  * your own identifying information:
    25  * "Portions Copyrighted [year] [name of copyright owner]"
    26  *
    27  * Contributor(s):
    28  *
    29  * The Original Software is NetBeans. The Initial Developer of the Original
    30  * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
    31  *
    32  * If you wish your version of this file to be governed by only the CDDL
    33  * or only the GPL Version 2, indicate your decision by adding
    34  * "[Contributor] elects to include this software in this distribution
    35  * under the [CDDL or GPL Version 2] license." If you do not indicate a
    36  * single choice of license, a recipient has the option to distribute
    37  * your version of this file under either the CDDL, the GPL Version 2 or
    38  * to extend the choice of license to its licensees as provided above.
    39  * However, if you add GPL Version 2 code and therefore, elected the GPL
    40  * Version 2 license, then the option applies only if the new code is
    41  * made subject to such option by the copyright holder.
    42  */
    43 package net.java.html.boot.fx;
    44 
    45 import java.net.URL;
    46 import javafx.application.Platform;
    47 import javafx.beans.value.ChangeListener;
    48 import javafx.beans.value.ObservableValue;
    49 import javafx.concurrent.Worker;
    50 import javafx.scene.web.WebView;
    51 import net.java.html.BrwsrCtx;
    52 import net.java.html.boot.BrowserBuilder;
    53 import net.java.html.js.JavaScriptBody;
    54 import org.netbeans.html.boot.fx.AbstractFXPresenter;
    55 import org.netbeans.html.context.spi.Contexts;
    56 import org.netbeans.html.context.spi.Contexts.Id;
    57 
    58 /** Utility methods to use {@link WebView} and {@link JavaScriptBody} code
    59  * in existing <em>JavaFX</em> applications.
    60  * This class is for those who want to instantiate their own {@link WebView},
    61  * configure it manually, embed it into own <em>JavaFX</em>
    62  * application and based on other events in the application
    63  * {@link #runInBrowser(javafx.scene.web.WebView, java.lang.Runnable) re-execute code} 
    64  * inside of such {@link WebView}s.
    65  * <p>
    66  * In case such detailed control is not necessary,
    67  * consider using {@link BrowserBuilder}. Btw. when using the {@link BrowserBuilder}
    68  * one can execute presenter in headless mode. Just specify: <code>
    69  * {@link System}.{@link System#setProperty(java.lang.String, java.lang.String) setProperty}("fxpresenter.headless", "true");
    70  * </code>
    71  *
    72  * 
    73  * @author Jaroslav Tulach
    74  * @since 0.6
    75  */
    76 public final class FXBrowsers {
    77     private FXBrowsers() {
    78     }
    79     
    80     /** Enables the Java/JavaScript bridge (that supports {@link JavaScriptBody} and co.)
    81      * in the provided <code>webView</code>. This method returns 
    82      * immediately. Once the support is active, it calls back specified
    83      * method in <code>onPageLoad</code> class - the class can possibly be
    84      * loaded by a different classloader (to enable replacement of
    85      * methods with {@link JavaScriptBody} annotations with executable
    86      * versions). The method <code>methodName</code> needs to be <code>public</code>
    87      * (in a public class), <code>static</code> and take either no parameters
    88      * or an array of {@link String}s.
    89      * <p>
    90      * This method sets {@link WebView#getUserData()} and {@link #runInBrowser(javafx.scene.web.WebView, java.lang.Runnable)}
    91      * relies on the value. Please don't alter it.
    92      * <p>
    93      * Since introduction of {@link Id technology identifiers} the 
    94      * provided <code>args</code> strings are also passed to the 
    95      * {@link BrwsrCtx context} when it is being 
    96      * {@link Contexts#newBuilder(java.lang.Object...) created}
    97      * and can influence the selection
    98      * of available technologies 
    99      * (like {@link org.netbeans.html.json.spi.Technology},
   100      * {@link org.netbeans.html.json.spi.Transfer} or
   101      * {@link org.netbeans.html.json.spi.WSTransfer}).
   102      * 
   103      * @param webView the instance of Web View to tweak
   104      * @param url the URL of the HTML page to load into the view
   105      * @param onPageLoad callback class with method <code>methodName</code>
   106      * @param methodName the method to call when the page is loaded
   107      * @param args arguments to pass to the <code>methodName</code> method
   108      */
   109     public static void load(
   110         final WebView webView, final URL url, 
   111         Class<?> onPageLoad, String methodName,
   112         String... args
   113     ) {
   114         Object[] context = new Object[args.length + 1];
   115         System.arraycopy(args, 0, context, 1, args.length);
   116         context[0] = new Load(webView);
   117         BrowserBuilder.newBrowser(context).
   118             loadPage(url.toExternalForm()).
   119             loadClass(onPageLoad).
   120             invoke(methodName, args).
   121             showAndWait();
   122     }
   123     
   124     /** Enables the Java/JavaScript bridge (that supports {@link JavaScriptBody} and co.)
   125      * in the provided <code>webView</code>. This method returns 
   126      * immediately. Once the support is active, it calls back specified
   127      * method in <code>onPageLoad</code>'s run method. 
   128      * This is more convenient way to initialize the webview, 
   129      * but it requires one to make sure
   130      * all {@link JavaScriptBody} methods has been post-processed during
   131      * compilation and there will be no need to instantiate new classloader.
   132      * <p>
   133      * This method sets {@link WebView#getUserData()} and {@link #runInBrowser(javafx.scene.web.WebView, java.lang.Runnable)}
   134      * relies on the value. Please don't alter it.
   135      * 
   136      * @param webView the instance of Web View to tweak
   137      * @param url the URL of the HTML page to load into the view
   138      * @param onPageLoad callback to call when the page is ready
   139      * @since 0.8.1
   140      */
   141     public static void load(
   142         WebView webView, final URL url, Runnable onPageLoad
   143     ) {
   144         load(webView, url, onPageLoad, null);
   145     }
   146     
   147     /** Enables the Java/JavaScript bridge (that supports {@link JavaScriptBody} and co.)
   148      * in the provided <code>webView</code>. This method returns 
   149      * immediately. Once the support is active, it calls back {@link Runnable#run() run}
   150      * method in <code>onPageLoad</code>. 
   151      * This is more convenient way to initialize the webview, 
   152      * but it requires one to make sure
   153      * all {@link JavaScriptBody} methods has been post-processed during
   154      * compilation and there will be no need to instantiate new classloader.
   155      * <p>
   156      * This method sets {@link WebView#getUserData()} and {@link #runInBrowser(javafx.scene.web.WebView, java.lang.Runnable)}
   157      * relies on the value. Please don't alter it.
   158      * 
   159      * @param webView the instance of Web View to tweak
   160      * @param url the URL of the HTML page to load into the view
   161      * @param onPageLoad callback to call when the page is ready
   162      * @param loader the loader to use when constructing initial {@link BrwsrCtx} or <code>null</code>
   163      * @since 0.9
   164      */
   165     public static void load(
   166         WebView webView, final URL url, Runnable onPageLoad, ClassLoader loader
   167     ) {
   168         load(webView, url, onPageLoad, loader, new Object[0]);
   169     }
   170     
   171     /** Enables the Java/JavaScript bridge (that supports {@link JavaScriptBody} and co.)
   172      * in the provided <code>webView</code>. This method returns 
   173      * immediately. Once the support is active, it calls back {@link Runnable#run() run}
   174      * method in <code>onPageLoad</code>. 
   175      * This is more convenient way to initialize the webview, 
   176      * but it requires one to make sure
   177      * all {@link JavaScriptBody} methods has been post-processed during
   178      * compilation and there will be no need to instantiate new classloader.
   179      * <p>
   180      * This method sets {@link WebView#getUserData()} and {@link #runInBrowser(javafx.scene.web.WebView, java.lang.Runnable)}
   181      * relies on the value. Please don't alter it.
   182      * 
   183      * @param webView the instance of Web View to tweak
   184      * @param url the URL of the HTML page to load into the view
   185      * @param onPageLoad callback to call when the page is ready
   186      * @param loader the loader to use when constructing initial {@link BrwsrCtx} or <code>null</code>
   187      * @param context additonal configuration to pass to {@link BrowserBuilder#newBrowser(java.lang.Object...)}
   188      *   and {@link Contexts#newBuilder(java.lang.Object...)} factory methods 
   189      * @since 1.1
   190      */
   191     public static void load(
   192         WebView webView, final URL url, Runnable onPageLoad, ClassLoader loader,
   193         Object... context
   194     ) {
   195         Object[] newCtx = new Object[context.length + 1];
   196         System.arraycopy(context, 0, newCtx, 1, context.length);
   197         newCtx[0] = new Load(webView);
   198         BrowserBuilder.newBrowser(newCtx).
   199                 loadPage(url.toExternalForm()).
   200                 loadFinished(onPageLoad).
   201                 classloader(loader).
   202                 showAndWait();
   203     }
   204     
   205     /** Executes a code inside of provided {@link WebView}. This method
   206      * associates the {@link BrwsrCtx execution context} with provided browser,
   207      * so the {@link JavaScriptBody} annotations know where to execute
   208      * their JavaScript bodies.
   209      * The code is going to be executed synchronously
   210      * in case {@link Platform#isFxApplicationThread()} returns <code>true</code>.
   211      * Otherwise this method returns immediately and the code is executed
   212      * later via {@link Platform#runLater(java.lang.Runnable)}.
   213      * <p>
   214      * This method relies on {@link WebView#getUserData()} being properly
   215      * provided by the <code>load</code> methods in this class.
   216      * 
   217      * @param webView the web view previously prepared by one of the <code>load</code>
   218      *   methods in this class
   219      * @param code the code to execute
   220      * @throws IllegalArgumentException if the web view was not properly
   221      *   initialized
   222      * @see BrwsrCtx#execute(java.lang.Runnable) 
   223      * @since 0.8.1
   224      */
   225     public static void runInBrowser(WebView webView, Runnable code) {
   226         Object ud = webView.getUserData();
   227         if (!(ud instanceof Load)) {
   228             throw new IllegalArgumentException();
   229         }
   230         ((Load)ud).execute(code);
   231     }
   232     
   233     private static class Load extends AbstractFXPresenter {
   234         private final WebView webView;
   235 
   236         public Load(WebView webView) {
   237             webView.setUserData(this);
   238             this.webView = webView;
   239         }
   240         
   241         @Override
   242         protected void waitFinished() {
   243             // don't wait
   244         }
   245 
   246         @Override
   247         protected WebView findView(final URL resource) {
   248             final Worker<Void> w = webView.getEngine().getLoadWorker();
   249             w.stateProperty().addListener(new ChangeListener<Worker.State>() {
   250                 private String previous;
   251 
   252                 @Override
   253                 public void changed(ObservableValue<? extends Worker.State> ov, Worker.State t, Worker.State newState) {
   254                     if (newState.equals(Worker.State.SUCCEEDED)) {
   255                         if (checkValid()) {
   256                             onPageLoad();
   257                         }
   258                     }
   259                     if (newState.equals(Worker.State.FAILED)) {
   260                         checkValid();
   261                         throw new IllegalStateException("Failed to load " + resource);
   262                     }
   263                 }
   264 
   265                 private boolean checkValid() {
   266                     final String crnt = webView.getEngine().getLocation();
   267                     if (previous != null && !previous.equals(crnt)) {
   268                         w.stateProperty().removeListener(this);
   269                         return false;
   270                     }
   271                     previous = crnt;
   272                     return true;
   273                 }
   274             });
   275 
   276             return webView;
   277         }
   278     }
   279     
   280 }