boot/src/main/java/org/netbeans/html/boot/spi/Fn.java
changeset 838 bdc3d696dd4a
parent 716 0654466b2273
child 898 18e17d0cd066
child 900 2ee22312e414
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/boot/src/main/java/org/netbeans/html/boot/spi/Fn.java	Tue Aug 26 18:13:30 2014 +0200
     1.3 @@ -0,0 +1,332 @@
     1.4 +/**
     1.5 + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
     1.6 + *
     1.7 + * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
     1.8 + *
     1.9 + * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
    1.10 + * Other names may be trademarks of their respective owners.
    1.11 + *
    1.12 + * The contents of this file are subject to the terms of either the GNU
    1.13 + * General Public License Version 2 only ("GPL") or the Common
    1.14 + * Development and Distribution License("CDDL") (collectively, the
    1.15 + * "License"). You may not use this file except in compliance with the
    1.16 + * License. You can obtain a copy of the License at
    1.17 + * http://www.netbeans.org/cddl-gplv2.html
    1.18 + * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
    1.19 + * specific language governing permissions and limitations under the
    1.20 + * License.  When distributing the software, include this License Header
    1.21 + * Notice in each file and include the License file at
    1.22 + * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
    1.23 + * particular file as subject to the "Classpath" exception as provided
    1.24 + * by Oracle in the GPL Version 2 section of the License file that
    1.25 + * accompanied this code. If applicable, add the following below the
    1.26 + * License Header, with the fields enclosed by brackets [] replaced by
    1.27 + * your own identifying information:
    1.28 + * "Portions Copyrighted [year] [name of copyright owner]"
    1.29 + *
    1.30 + * Contributor(s):
    1.31 + *
    1.32 + * The Original Software is NetBeans. The Initial Developer of the Original
    1.33 + * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
    1.34 + *
    1.35 + * If you wish your version of this file to be governed by only the CDDL
    1.36 + * or only the GPL Version 2, indicate your decision by adding
    1.37 + * "[Contributor] elects to include this software in this distribution
    1.38 + * under the [CDDL or GPL Version 2] license." If you do not indicate a
    1.39 + * single choice of license, a recipient has the option to distribute
    1.40 + * your version of this file under either the CDDL, the GPL Version 2 or
    1.41 + * to extend the choice of license to its licensees as provided above.
    1.42 + * However, if you add GPL Version 2 code and therefore, elected the GPL
    1.43 + * Version 2 license, then the option applies only if the new code is
    1.44 + * made subject to such option by the copyright holder.
    1.45 + */
    1.46 +package org.netbeans.html.boot.spi;
    1.47 +
    1.48 +import java.io.Closeable;
    1.49 +import java.io.IOException;
    1.50 +import java.io.InputStream;
    1.51 +import java.io.InputStreamReader;
    1.52 +import java.io.Reader;
    1.53 +import java.net.URL;
    1.54 +import java.util.HashMap;
    1.55 +import java.util.HashSet;
    1.56 +import java.util.Map;
    1.57 +import java.util.Set;
    1.58 +import java.util.concurrent.Executor;
    1.59 +import net.java.html.js.JavaScriptBody;
    1.60 +import org.netbeans.html.boot.impl.FnContext;
    1.61 +
    1.62 +/** Represents single JavaScript function that can be invoked. 
    1.63 + * Created via {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
    1.64 + *
    1.65 + * @author Jaroslav Tulach
    1.66 + */
    1.67 +public abstract class Fn {
    1.68 +    private final Presenter presenter;
    1.69 +    
    1.70 +    /**
    1.71 +     * @deprecated Ineffective as of 0.6. 
    1.72 +     * Provide a presenter via {@link #Fn(org.netbeans.html.boot.spi.Fn.Presenter)}
    1.73 +     * constructor
    1.74 +     */
    1.75 +    @Deprecated
    1.76 +    protected Fn() {
    1.77 +        this(null);
    1.78 +    }
    1.79 +    
    1.80 +    /** Creates new function object and associates it with given presenter.
    1.81 +     * 
    1.82 +     * @param presenter the browser presenter associated with this function
    1.83 +     * @since 0.6 
    1.84 +     */
    1.85 +    protected Fn(Presenter presenter) {
    1.86 +        this.presenter = presenter;
    1.87 +    }
    1.88 +
    1.89 +    /** True, if currently active presenter is the same as presenter this
    1.90 +     * function has been created for via {@link #Fn(org.netbeans.html.boot.spi.Fn.Presenter)}.
    1.91 +     * 
    1.92 +     * @return true, if proper presenter is used
    1.93 +     */
    1.94 +    public final boolean isValid() {
    1.95 +        return presenter != null && FnContext.currentPresenter(false) == presenter;
    1.96 +    }
    1.97 +    
    1.98 +    /** Helper method to check if the provided instance is valid function.
    1.99 +     * Checks if the parameter is non-null and if so, does {@link #isValid()}
   1.100 +     * check.
   1.101 +     * 
   1.102 +     * @param fnOrNull function or <code>null</code>
   1.103 +     * @return true if the parameter is non-null and valid
   1.104 +     * @since 0.7
   1.105 +     */
   1.106 +    public static boolean isValid(Fn fnOrNull) {
   1.107 +        return fnOrNull != null && fnOrNull.isValid();
   1.108 +    }
   1.109 +
   1.110 +    /** Helper method to find current presenter and ask it to define new
   1.111 +     * function by calling {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
   1.112 +     * 
   1.113 +     * @param caller the class who wishes to define the function
   1.114 +     * @param code the body of the function (can reference <code>this</code> and <code>names</code> variables)
   1.115 +     * @param names names of individual parameters
   1.116 +     * @return the function object that can be {@link Fn#invoke(java.lang.Object, java.lang.Object...) invoked}
   1.117 +     *    - can return <code>null</code> if there is {@link #activePresenter() no presenter}
   1.118 +     * @since 0.7
   1.119 +     */
   1.120 +    public static Fn define(Class<?> caller, String code, String... names) {
   1.121 +        final Presenter p = FnContext.currentPresenter(false);
   1.122 +        return p == null ? null : p.defineFn(code, names);
   1.123 +    }
   1.124 +    
   1.125 +    private static final Map<String,Set<Presenter>> LOADED = new HashMap<String, Set<Presenter>>();
   1.126 +    
   1.127 +    /** Wraps function to ensure that the script represented by <code>resource</code>
   1.128 +     * gets loaded into the browser environment before the function <code>fn</code>
   1.129 +     * is executed.
   1.130 +     * 
   1.131 +     * @param fn original function to call (if <code>null</code> returns <code>null</code>)
   1.132 +     * @param caller the class who wishes to define/call the function
   1.133 +     * @param resource resources (accessible via {@link ClassLoader#getResource(java.lang.String)}) 
   1.134 +     *   with a <em>JavaScript</em> that is supposed to loaded into the browser
   1.135 +     *   environment
   1.136 +     * @return function that ensures the script is loaded and then delegates
   1.137 +     *   to <code>fn</code>. Returns <code>null</code> if the input <code>fn</code> is null
   1.138 +     * @since 0.7
   1.139 +     */
   1.140 +    public static Fn preload(final Fn fn, final Class<?> caller, final String resource) {
   1.141 +        if (fn == null) {
   1.142 +            return null;
   1.143 +        }
   1.144 +        return new Fn(fn.presenter()) {
   1.145 +            @Override
   1.146 +            public Object invoke(Object thiz, Object... args) throws Exception {
   1.147 +                loadResource();
   1.148 +                return fn.invoke(thiz, args);
   1.149 +            }
   1.150 +
   1.151 +            @Override
   1.152 +            public void invokeLater(Object thiz, Object... args) throws Exception {
   1.153 +                loadResource();
   1.154 +                fn.invokeLater(thiz, args);
   1.155 +            }
   1.156 +            
   1.157 +            private void loadResource() throws Exception {
   1.158 +                Presenter p = presenter();
   1.159 +                if (p == null) {
   1.160 +                    p = FnContext.currentPresenter(false);
   1.161 +                }
   1.162 +                if (p != null) {
   1.163 +                    Set<Presenter> there = LOADED.get(resource);
   1.164 +                    if (there == null) {
   1.165 +                        there = new HashSet<Presenter>();
   1.166 +                        LOADED.put(resource, there);
   1.167 +                    }
   1.168 +                    if (there.add(p)) {
   1.169 +                        final ClassLoader l = caller.getClassLoader();
   1.170 +                        InputStream is = l.getResourceAsStream(resource);
   1.171 +                        if (is == null && resource.startsWith("/")) {
   1.172 +                            is = l.getResourceAsStream(resource.substring(1));
   1.173 +                        }
   1.174 +                        if (is == null) {
   1.175 +                            throw new IOException("Cannot find " + resource + " in " + l);
   1.176 +                        }
   1.177 +                        try {
   1.178 +                            InputStreamReader r = new InputStreamReader(is, "UTF-8");
   1.179 +                            p.loadScript(r);
   1.180 +                        } finally {
   1.181 +                            is.close();
   1.182 +                        }
   1.183 +                    }
   1.184 +                }
   1.185 +            }
   1.186 +        };
   1.187 +    }
   1.188 +
   1.189 +    
   1.190 +    /** The currently active presenter.
   1.191 +     * 
   1.192 +     * @return the currently active presenter or <code>null</code>
   1.193 +     * @since 0.7
   1.194 +     */
   1.195 +    public static Presenter activePresenter() {
   1.196 +        return FnContext.currentPresenter(false);
   1.197 +    }
   1.198 +    
   1.199 +    /** Activates given presenter. Used to associate the native 
   1.200 +     * JavaScript code specified by 
   1.201 +     * {@link JavaScriptBody} annotation with certain presenter:
   1.202 +     * <pre>
   1.203 +     * try ({@link Closeable} c = Fn.activate(presenter)) {
   1.204 +     *   doCallsInPresenterContext();
   1.205 +     * }
   1.206 +     * </pre>
   1.207 +     * 
   1.208 +     * @param p the presenter that should be active until closable is closed
   1.209 +     * @return the closable to close
   1.210 +     * @since 0.7
   1.211 +     */
   1.212 +    public static Closeable activate(Presenter p) {
   1.213 +        return FnContext.activate(p);
   1.214 +    }
   1.215 +    
   1.216 +    /** Invokes the defined function with specified <code>this</code> and
   1.217 +     * appropriate arguments.
   1.218 +     * 
   1.219 +     * @param thiz the meaning of <code>this</code> inside of the JavaScript
   1.220 +     *   function - can be <code>null</code>
   1.221 +     * @param args arguments for the function
   1.222 +     * @return return value from the function
   1.223 +     * @throws Exception if something goes wrong, as exception may be thrown
   1.224 +     */
   1.225 +    public abstract Object invoke(Object thiz, Object... args) throws Exception;
   1.226 +
   1.227 +    /** Invokes the defined function with specified <code>this</code> and
   1.228 +     * appropriate arguments asynchronously. The invocation may be 
   1.229 +     * happen <em>"later"</em>.
   1.230 +     * 
   1.231 +     * @param thiz the meaning of <code>this</code> inside of the JavaScript
   1.232 +     *   function - can be <code>null</code>
   1.233 +     * @param args arguments for the function
   1.234 +     * @throws Exception if something goes wrong, as exception may be thrown
   1.235 +     * @since 0.7.6
   1.236 +     */
   1.237 +    public void invokeLater(Object thiz, Object... args) throws Exception {
   1.238 +        invoke(this, args);
   1.239 +    }
   1.240 +    
   1.241 +    /** Provides the function implementation access to the presenter provided
   1.242 +     * in {@link #Fn(org.netbeans.html.boot.spi.Fn.Presenter) the constructor}.
   1.243 +     * 
   1.244 +     * @return presenter passed in the constructor (may be, but should not be <code>null</code>)
   1.245 +     * @since 0.7
   1.246 +     */
   1.247 +    protected final Presenter presenter() {
   1.248 +        return presenter;
   1.249 +    }
   1.250 +
   1.251 +    /** The representation of a <em>presenter</em> - usually a browser window.
   1.252 +     * Should be provided by a library included in the application and registered
   1.253 +     * in <code>META-INF/services</code>, for example with
   1.254 +     * <code>@ServiceProvider(service = Fn.Presenter.class)</code> annotation.
   1.255 +     * <p>
   1.256 +     * Since 0.7 a presenter may implement {@link Executor} interface, in case
   1.257 +     * it supports single threaded execution environment. The executor's
   1.258 +     * {@link Executor#execute(java.lang.Runnable)} method is then supposed
   1.259 +     * to invoke the runnable immediately (in case we are on the right thread
   1.260 +     * already) or return and asynchronously invoke the runnable later on the
   1.261 +     * right thread (if we are on wrong thread).
   1.262 +     */
   1.263 +    public interface Presenter {
   1.264 +        /** Creates new function with given parameter names and provided body.
   1.265 +         * 
   1.266 +         * @param code the body of the function. Can refer to variables named
   1.267 +         *   as <code>names</code>
   1.268 +         * @param names names of parameters of the function - these will be 
   1.269 +         *   available when the <code>code</code> body executes
   1.270 +         * 
   1.271 +         * @return function that can be later invoked
   1.272 +         */
   1.273 +        public Fn defineFn(String code, String... names);
   1.274 +        
   1.275 +        /** Opens the browser, loads provided page and when the
   1.276 +         * page is ready, it calls back to the provider runnable.
   1.277 +         * 
   1.278 +         * @param page the URL for the page to display
   1.279 +         * @param onPageLoad callback when the page is ready
   1.280 +         */
   1.281 +        public void displayPage(URL page, Runnable onPageLoad);
   1.282 +        
   1.283 +        /** Loads a script into the browser JavaScript interpreter and 
   1.284 +         * executes it.
   1.285 +         * @param code the script to execute
   1.286 +         * @throws Exception if something goes wrong, throw an exception
   1.287 +         */
   1.288 +        public void loadScript(Reader code) throws Exception;
   1.289 +    }
   1.290 +    
   1.291 +    /** Additional interface to be implemented by {@link Presenter}s that
   1.292 +     * wish to control what objects are passed into the JavaScript virtual 
   1.293 +     * machine.
   1.294 +     * <p>
   1.295 +     * If a JavaScript engine makes callback to Java method that returns 
   1.296 +     * a value, the {@link #toJavaScript(java.lang.Object)} method is
   1.297 +     * consulted to convert the Java value to something reasonable inside
   1.298 +     * JavaScript VM.
   1.299 +     * <p>
   1.300 +     * <em>Note:</em> The implementation based on <em>JavaFX</em> <code>WebView</code>
   1.301 +     * uses this interface to convert Java arrays to JavaScript ones.
   1.302 +     * 
   1.303 +     * @see Presenter
   1.304 +     * @since 0.7
   1.305 +     */
   1.306 +    public interface ToJavaScript {
   1.307 +        /** Convert a Java return value into some object suitable for
   1.308 +         * JavaScript virtual machine.
   1.309 +         * 
   1.310 +         * @param toReturn the Java object to be returned
   1.311 +         * @return the replacement value to return instead
   1.312 +         */
   1.313 +        public Object toJavaScript(Object toReturn);
   1.314 +    }
   1.315 +    
   1.316 +    /** Additional interface to be implemented by {@link Presenter}s that
   1.317 +     * need to convert JavaScript object (usually array) to Java object 
   1.318 +     * when calling back from JavaScript to Java.
   1.319 +     * <p>
   1.320 +     * <em>Note:</em> The implementation based on <em>JavaFX</em>
   1.321 +     * <code>WebView</code> uses this interface to convert JavaScript arrays to
   1.322 +     * Java ones.
   1.323 +      * 
   1.324 +     * @since 0.7
   1.325 +     */
   1.326 +    public interface FromJavaScript {
   1.327 +        /** Convert a JavaScript object into suitable Java representation
   1.328 +         * before a Java method is called with this object as an argument.
   1.329 +         * 
   1.330 +         * @param js the JavaScript object
   1.331 +         * @return replacement object for 
   1.332 +         */
   1.333 +        public Object toJava(Object js);
   1.334 +    }
   1.335 +}