boot-fx/src/main/java/net/java/html/boot/fx/FXBrowsers.java
author Jaroslav Tulach <jtulach@netbeans.org>
Thu, 04 Dec 2014 09:21:55 +0100
changeset 886 88d62267a0b5
parent 771 ee3614350fc8
child 889 548982033730
permissions -rw-r--r--
#248918: Introducing technology identifiers
     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  * In case such detailed control is not necessary,
    66  * consider using {@link BrowserBuilder}.
    67  * 
    68  * @author Jaroslav Tulach
    69  * @since 0.6
    70  */
    71 public final class FXBrowsers {
    72     private FXBrowsers() {
    73     }
    74     
    75     /** Enables the Java/JavaScript bridge (that supports {@link JavaScriptBody} and co.)
    76      * in the provided <code>webView</code>. This method returns 
    77      * immediately. Once the support is active, it calls back specified
    78      * method in <code>onPageLoad</code> class - the class can possibly be
    79      * loaded by a different classloader (to enable replacement of
    80      * methods with {@link JavaScriptBody} annotations with executable
    81      * versions). The method <code>methodName</code> needs to be <code>public</code>
    82      * (in a public class), <code>static</code> and take either no parameters
    83      * or an array of {@link String}s.
    84      * <p>
    85      * This method sets {@link WebView#getUserData()} and {@link #runInBrowser(javafx.scene.web.WebView, java.lang.Runnable)}
    86      * relies on the value. Please don't alter it.
    87      * <p>
    88      * Since introduction of {@link Id technology identifiers} the 
    89      * provided <code>args</code> strings are also passed to the 
    90      * {@link BrwsrCtx context} when it is being 
    91      * {@link Contexts#newBuilder(java.lang.Object...) created}
    92      * and can influence the selection
    93      * of available technologies 
    94      * (like {@link org.netbeans.html.json.spi.Technology},
    95      * {@link org.netbeans.html.json.spi.Transfer} or
    96      * {@link org.netbeans.html.json.spi.WSTransfer}).
    97      * 
    98      * @param webView the instance of Web View to tweak
    99      * @param url the URL of the HTML page to load into the view
   100      * @param onPageLoad callback class with method <code>methodName</code>
   101      * @param methodName the method to call when the page is loaded
   102      * @param args arguments to pass to the <code>methodName</code> method
   103      */
   104     public static void load(
   105         final WebView webView, final URL url, 
   106         Class<?> onPageLoad, String methodName,
   107         String... args
   108     ) {
   109         Object[] context = new Object[args.length + 1];
   110         System.arraycopy(args, 0, context, 1, args.length);
   111         context[0] = new Load(webView);
   112         BrowserBuilder.newBrowser(context).
   113             loadPage(url.toExternalForm()).
   114             loadClass(onPageLoad).
   115             invoke(methodName, args).
   116             showAndWait();
   117     }
   118     
   119     /** Enables the Java/JavaScript bridge (that supports {@link JavaScriptBody} and co.)
   120      * in the provided <code>webView</code>. This method returns 
   121      * immediately. Once the support is active, it calls back specified
   122      * method in <code>onPageLoad</code>'s run method. 
   123      * This is more convenient way to initialize the webview, 
   124      * but it requires one to make sure
   125      * all {@link JavaScriptBody} methods has been post-processed during
   126      * compilation and there will be no need to instantiate new classloader.
   127      * <p>
   128      * This method sets {@link WebView#getUserData()} and {@link #runInBrowser(javafx.scene.web.WebView, java.lang.Runnable)}
   129      * relies on the value. Please don't alter it.
   130      * 
   131      * @param webView the instance of Web View to tweak
   132      * @param url the URL of the HTML page to load into the view
   133      * @param onPageLoad callback to call when the page is ready
   134      * @since 0.8.1
   135      */
   136     public static void load(
   137         WebView webView, final URL url, Runnable onPageLoad
   138     ) {
   139         load(webView, url, onPageLoad, null);
   140     }
   141     
   142     /** Enables the Java/JavaScript bridge (that supports {@link JavaScriptBody} and co.)
   143      * in the provided <code>webView</code>. This method returns 
   144      * immediately. Once the support is active, it calls back specified
   145      * method in <code>onPageLoad</code>'s run method. 
   146      * This is more convenient way to initialize the webview, 
   147      * but it requires one to make sure
   148      * all {@link JavaScriptBody} methods has been post-processed during
   149      * compilation and there will be no need to instantiate new classloader.
   150      * <p>
   151      * This method sets {@link WebView#getUserData()} and {@link #runInBrowser(javafx.scene.web.WebView, java.lang.Runnable)}
   152      * relies on the value. Please don't alter it.
   153      * 
   154      * @param webView the instance of Web View to tweak
   155      * @param url the URL of the HTML page to load into the view
   156      * @param onPageLoad callback to call when the page is ready
   157      * @param loader the loader to use when constructing initial {@link BrwsrCtx} or <code>null</code>
   158      * @since 0.9
   159      */
   160     public static void load(
   161         WebView webView, final URL url, Runnable onPageLoad, ClassLoader loader
   162     ) {
   163         BrowserBuilder.newBrowser(new Load(webView)).
   164                 loadPage(url.toExternalForm()).
   165                 loadFinished(onPageLoad).
   166                 classloader(loader).
   167                 showAndWait();
   168     }
   169     
   170     /** Executes a code inside of provided {@link WebView}. This method
   171      * associates the {@link BrwsrCtx execution context} with provided browser,
   172      * so the {@link JavaScriptBody} annotations know where to execute
   173      * their JavaScript bodies.
   174      * The code is going to be executed synchronously
   175      * in case {@link Platform#isFxApplicationThread()} returns <code>true</code>.
   176      * Otherwise this method returns immediately and the code is executed
   177      * later via {@link Platform#runLater(java.lang.Runnable)}.
   178      * <p>
   179      * This method relies on {@link WebView#getUserData()} being properly
   180      * provided by the <code>load</code> methods in this class.
   181      * 
   182      * @param webView the web view previously prepared by one of the <code>load</code>
   183      *   methods in this class
   184      * @param code the code to execute
   185      * @throws IllegalArgumentException if the web view was not properly
   186      *   initialized
   187      * @see BrwsrCtx#execute(java.lang.Runnable) 
   188      * @since 0.8.1
   189      */
   190     public static void runInBrowser(WebView webView, Runnable code) {
   191         Object ud = webView.getUserData();
   192         if (!(ud instanceof Load)) {
   193             throw new IllegalArgumentException();
   194         }
   195         ((Load)ud).execute(code);
   196     }
   197     
   198     private static class Load extends AbstractFXPresenter {
   199         private final WebView webView;
   200 
   201         public Load(WebView webView) {
   202             webView.setUserData(this);
   203             this.webView = webView;
   204         }
   205         
   206         @Override
   207         protected void waitFinished() {
   208             // don't wait
   209         }
   210 
   211         @Override
   212         protected WebView findView(final URL resource) {
   213             final Worker<Void> w = webView.getEngine().getLoadWorker();
   214             w.stateProperty().addListener(new ChangeListener<Worker.State>() {
   215                 private String previous;
   216 
   217                 @Override
   218                 public void changed(ObservableValue<? extends Worker.State> ov, Worker.State t, Worker.State newState) {
   219                     if (newState.equals(Worker.State.SUCCEEDED)) {
   220                         if (checkValid()) {
   221                             onPageLoad();
   222                         }
   223                     }
   224                     if (newState.equals(Worker.State.FAILED)) {
   225                         checkValid();
   226                         throw new IllegalStateException("Failed to load " + resource);
   227                     }
   228                 }
   229 
   230                 private boolean checkValid() {
   231                     final String crnt = webView.getEngine().getLocation();
   232                     if (previous != null && !previous.equals(crnt)) {
   233                         w.stateProperty().removeListener(this);
   234                         return false;
   235                     }
   236                     previous = crnt;
   237                     return true;
   238                 }
   239             });
   240 
   241             return webView;
   242         }
   243     }
   244     
   245 }