boot/src/main/java/org/apidesign/html/boot/spi/Fn.java
author Jaroslav Tulach <jaroslav.tulach@netbeans.org>
Fri, 07 Feb 2014 07:44:34 +0100
changeset 551 7ca2253fa86d
parent 530 ce0da3e90343
child 555 cdae29ad68ec
permissions -rw-r--r--
Updating copyright headers to mention current year
jaroslav@123
     1
/**
jaroslav@358
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jaroslav@123
     3
 *
jaroslav@551
     4
 * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
jaroslav@123
     5
 *
jaroslav@358
     6
 * Oracle and Java are registered trademarks of Oracle and/or its affiliates.
jaroslav@358
     7
 * Other names may be trademarks of their respective owners.
jaroslav@123
     8
 *
jaroslav@358
     9
 * The contents of this file are subject to the terms of either the GNU
jaroslav@358
    10
 * General Public License Version 2 only ("GPL") or the Common
jaroslav@358
    11
 * Development and Distribution License("CDDL") (collectively, the
jaroslav@358
    12
 * "License"). You may not use this file except in compliance with the
jaroslav@358
    13
 * License. You can obtain a copy of the License at
jaroslav@358
    14
 * http://www.netbeans.org/cddl-gplv2.html
jaroslav@358
    15
 * or nbbuild/licenses/CDDL-GPL-2-CP. See the License for the
jaroslav@358
    16
 * specific language governing permissions and limitations under the
jaroslav@358
    17
 * License.  When distributing the software, include this License Header
jaroslav@358
    18
 * Notice in each file and include the License file at
jaroslav@358
    19
 * nbbuild/licenses/CDDL-GPL-2-CP.  Oracle designates this
jaroslav@358
    20
 * particular file as subject to the "Classpath" exception as provided
jaroslav@358
    21
 * by Oracle in the GPL Version 2 section of the License file that
jaroslav@358
    22
 * accompanied this code. If applicable, add the following below the
jaroslav@358
    23
 * License Header, with the fields enclosed by brackets [] replaced by
jaroslav@358
    24
 * your own identifying information:
jaroslav@358
    25
 * "Portions Copyrighted [year] [name of copyright owner]"
jaroslav@358
    26
 *
jaroslav@358
    27
 * Contributor(s):
jaroslav@358
    28
 *
jaroslav@358
    29
 * The Original Software is NetBeans. The Initial Developer of the Original
jaroslav@551
    30
 * Software is Oracle. Portions Copyright 2013-2014 Oracle. All Rights Reserved.
jaroslav@358
    31
 *
jaroslav@358
    32
 * If you wish your version of this file to be governed by only the CDDL
jaroslav@358
    33
 * or only the GPL Version 2, indicate your decision by adding
jaroslav@358
    34
 * "[Contributor] elects to include this software in this distribution
jaroslav@358
    35
 * under the [CDDL or GPL Version 2] license." If you do not indicate a
jaroslav@358
    36
 * single choice of license, a recipient has the option to distribute
jaroslav@358
    37
 * your version of this file under either the CDDL, the GPL Version 2 or
jaroslav@358
    38
 * to extend the choice of license to its licensees as provided above.
jaroslav@358
    39
 * However, if you add GPL Version 2 code and therefore, elected the GPL
jaroslav@358
    40
 * Version 2 license, then the option applies only if the new code is
jaroslav@358
    41
 * made subject to such option by the copyright holder.
jaroslav@123
    42
 */
jaroslav@123
    43
package org.apidesign.html.boot.spi;
jaroslav@123
    44
jaroslav@322
    45
import java.io.Closeable;
jaroslav@349
    46
import java.io.InputStream;
jaroslav@349
    47
import java.io.InputStreamReader;
jaroslav@163
    48
import java.io.Reader;
jaroslav@123
    49
import java.net.URL;
jaroslav@349
    50
import java.util.HashMap;
jaroslav@349
    51
import java.util.HashSet;
jaroslav@349
    52
import java.util.Map;
jaroslav@349
    53
import java.util.Set;
jaroslav@431
    54
import java.util.concurrent.Executor;
jaroslav@322
    55
import net.java.html.js.JavaScriptBody;
jaroslav@362
    56
import org.netbeans.html.boot.impl.FnContext;
jaroslav@123
    57
jaroslav@289
    58
/** Represents single JavaScript function that can be invoked. 
jaroslav@289
    59
 * Created via {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
jaroslav@123
    60
 *
jaroslav@123
    61
 * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
jaroslav@123
    62
 */
jaroslav@123
    63
public abstract class Fn {
jaroslav@288
    64
    private final Presenter presenter;
jaroslav@288
    65
    
jaroslav@289
    66
    /**
jaroslav@289
    67
     * @deprecated Ineffective as of 0.6. 
jaroslav@289
    68
     * Provide a presenter via {@link #Fn(org.apidesign.html.boot.spi.Fn.Presenter)}
jaroslav@289
    69
     * constructor
jaroslav@289
    70
     */
jaroslav@289
    71
    @Deprecated
jaroslav@289
    72
    protected Fn() {
jaroslav@289
    73
        this(null);
jaroslav@289
    74
    }
jaroslav@289
    75
    
jaroslav@289
    76
    /** Creates new function object and associates it with given presenter.
jaroslav@289
    77
     * 
jaroslav@289
    78
     * @param presenter the browser presenter associated with this function
jaroslav@289
    79
     * @since 0.6 
jaroslav@289
    80
     */
jaroslav@288
    81
    protected Fn(Presenter presenter) {
jaroslav@288
    82
        this.presenter = presenter;
jaroslav@288
    83
    }
jaroslav@289
    84
jaroslav@289
    85
    /** True, if currently active presenter is the same as presenter this
jaroslav@289
    86
     * function has been created for via {@link #Fn(org.apidesign.html.boot.spi.Fn.Presenter)}.
jaroslav@289
    87
     * 
jaroslav@289
    88
     * @return true, if proper presenter is used
jaroslav@289
    89
     */
jaroslav@288
    90
    public final boolean isValid() {
jaroslav@451
    91
        return presenter != null && FnContext.currentPresenter(false) == presenter;
jaroslav@288
    92
    }
jaroslav@288
    93
    
jaroslav@323
    94
    /** Helper method to check if the provided instance is valid function.
jaroslav@323
    95
     * Checks if the parameter is non-null and if so, does {@link #isValid()}
jaroslav@323
    96
     * check.
jaroslav@323
    97
     * 
jaroslav@323
    98
     * @param fnOrNull function or <code>null</code>
jaroslav@323
    99
     * @return true if the parameter is non-null and valid
jaroslav@323
   100
     * @since 0.7
jaroslav@323
   101
     */
jaroslav@323
   102
    public static boolean isValid(Fn fnOrNull) {
jaroslav@323
   103
        return fnOrNull != null && fnOrNull.isValid();
jaroslav@323
   104
    }
jaroslav@323
   105
jaroslav@323
   106
    /** Helper method to find current presenter and ask it to define new
jaroslav@323
   107
     * function by calling {@link Presenter#defineFn(java.lang.String, java.lang.String...)}.
jaroslav@323
   108
     * 
jaroslav@323
   109
     * @param caller the class who wishes to define the function
jaroslav@323
   110
     * @param code the body of the function (can reference <code>this</code> and <code>names</code> variables)
jaroslav@323
   111
     * @param names names of individual parameters
jaroslav@323
   112
     * @return the function object that can be {@link Fn#invoke(java.lang.Object, java.lang.Object...) invoked}
jaroslav@451
   113
     *    - can return <code>null</code> if there is {@link #activePresenter() no presenter}
jaroslav@323
   114
     * @since 0.7
jaroslav@323
   115
     */
jaroslav@323
   116
    public static Fn define(Class<?> caller, String code, String... names) {
jaroslav@451
   117
        final Presenter p = FnContext.currentPresenter(false);
jaroslav@451
   118
        return p == null ? null : p.defineFn(code, names);
jaroslav@323
   119
    }
jaroslav@323
   120
    
jaroslav@349
   121
    private static final Map<String,Set<Presenter>> LOADED = new HashMap<String, Set<Presenter>>();
jaroslav@427
   122
    
jaroslav@427
   123
    /** Wraps function to ensure that the script represented by <code>resource</code>
jaroslav@427
   124
     * gets loaded into the browser environment before the function <code>fn</code>
jaroslav@427
   125
     * is executed.
jaroslav@427
   126
     * 
jaroslav@427
   127
     * @param fn original function to call
jaroslav@427
   128
     * @param caller the class who wishes to define/call the function
jaroslav@427
   129
     * @param resource resources (accessible via {@link ClassLoader#getResource(java.lang.String)}) 
jaroslav@427
   130
     *   with a <em>JavaScript</em> that is supposed to loaded into the browser
jaroslav@427
   131
     *   environment
jaroslav@427
   132
     * @return function that ensures the script is loaded and then delegates
jaroslav@427
   133
     *   to <code>fn</code>
jaroslav@427
   134
     * @since 0.7
jaroslav@427
   135
     */
jaroslav@349
   136
    public static Fn preload(final Fn fn, final Class<?> caller, final String resource) {
jaroslav@349
   137
        return new Fn() {
jaroslav@349
   138
            @Override
jaroslav@349
   139
            public Object invoke(Object thiz, Object... args) throws Exception {
jaroslav@424
   140
                final Presenter p = FnContext.currentPresenter(false);
jaroslav@349
   141
                Set<Presenter> there = LOADED.get(resource);
jaroslav@349
   142
                if (there == null) {
jaroslav@349
   143
                    there = new HashSet<Presenter>();
jaroslav@349
   144
                    LOADED.put(resource, there);
jaroslav@349
   145
                }
jaroslav@349
   146
                if (there.add(p)) {
jaroslav@349
   147
                    InputStream is = caller.getClassLoader().getResourceAsStream(resource);
jaroslav@349
   148
                    try {
jaroslav@349
   149
                        InputStreamReader r = new InputStreamReader(is, "UTF-8");
jaroslav@349
   150
                        p.loadScript(r);
jaroslav@349
   151
                    } finally {
jaroslav@349
   152
                        is.close();
jaroslav@349
   153
                    }
jaroslav@349
   154
                }
jaroslav@349
   155
                return fn.invoke(thiz, args);
jaroslav@349
   156
            }
jaroslav@349
   157
        };
jaroslav@349
   158
    }
jaroslav@349
   159
    
jaroslav@322
   160
    /** The currently active presenter.
jaroslav@322
   161
     * 
jaroslav@322
   162
     * @return the currently active presenter or <code>null</code>
jaroslav@322
   163
     * @since 0.7
jaroslav@322
   164
     */
jaroslav@322
   165
    public static Presenter activePresenter() {
jaroslav@434
   166
        return FnContext.currentPresenter(false);
jaroslav@322
   167
    }
jaroslav@322
   168
    
jaroslav@322
   169
    /** Activates given presenter. Used by the code generated by 
jaroslav@322
   170
     * {@link JavaScriptBody} annotation: 
jaroslav@322
   171
     * <pre>
jaroslav@322
   172
     * try ({@link Closeable} c = Fn.activate(presenter)) {
jaroslav@322
   173
     *   doCallsInPresenterContext();
jaroslav@322
   174
     * }
jaroslav@322
   175
     * </pre>
jaroslav@322
   176
     * 
jaroslav@322
   177
     * @param p the presenter that should be active until closable is closed
jaroslav@322
   178
     * @return the closable to close
jaroslav@322
   179
     * @since 0.7
jaroslav@322
   180
     */
jaroslav@322
   181
    public static Closeable activate(Presenter p) {
jaroslav@322
   182
        return FnContext.activate(p);
jaroslav@322
   183
    }
jaroslav@322
   184
    
jaroslav@289
   185
    /** Invokes the defined function with specified <code>this</code> and
jaroslav@289
   186
     * appropriate arguments.
jaroslav@289
   187
     * 
jaroslav@289
   188
     * @param thiz the meaning of <code>this</code> inside of the JavaScript
jaroslav@289
   189
     *   function - can be <code>null</code>
jaroslav@289
   190
     * @param args arguments for the function
jaroslav@289
   191
     * @return return value from the function
jaroslav@289
   192
     * @throws Exception if something goes wrong, as exception may be thrown
jaroslav@289
   193
     */
jaroslav@289
   194
    public abstract Object invoke(Object thiz, Object... args) throws Exception;
jaroslav@429
   195
    
jaroslav@429
   196
    /** Provides the function implementation access to the presenter provided
jaroslav@530
   197
     * in {@link #Fn(org.apidesign.html.boot.spi.Fn.Presenter) the constructor}.
jaroslav@429
   198
     * 
jaroslav@530
   199
     * @return presenter passed in the constructor (may be, but should not be <code>null</code>)
jaroslav@429
   200
     * @since 0.7
jaroslav@429
   201
     */
jaroslav@429
   202
    protected final Presenter presenter() {
jaroslav@429
   203
        return presenter;
jaroslav@429
   204
    }
jaroslav@289
   205
jaroslav@289
   206
    /** The representation of a <em>presenter</em> - usually a browser window.
jaroslav@315
   207
     * Should be provided by a library included in the application and registered
jaroslav@315
   208
     * in <code>META-INF/services</code>, for example with
jaroslav@315
   209
     * <code>@ServiceProvider(service = Fn.Presenter.class)</code> annotation.
jaroslav@431
   210
     * <p>
jaroslav@431
   211
     * Since 0.7 a presenter may implement {@link Executor} interface, in case
jaroslav@431
   212
     * it supports single threaded execution environment. The executor's
jaroslav@431
   213
     * {@link Executor#execute(java.lang.Runnable)} method is then supposed
jaroslav@431
   214
     * to invoke the runnable immediately (in case we are on the right thread
jaroslav@431
   215
     * already) or return and asynchronously invoke the runnable later on the
jaroslav@431
   216
     * right thread (if we are on wrong thread).
jaroslav@289
   217
     */
jaroslav@127
   218
    public interface Presenter {
jaroslav@289
   219
        /** Creates new function with given parameter names and provided body.
jaroslav@289
   220
         * 
jaroslav@289
   221
         * @param code the body of the function. Can refer to variables named
jaroslav@289
   222
         *   as <code>names</code>
jaroslav@289
   223
         * @param names names of parameters of the function - these will be 
jaroslav@289
   224
         *   available when the <code>code</code> body executes
jaroslav@289
   225
         * 
jaroslav@289
   226
         * @return function that can be later invoked
jaroslav@289
   227
         */
jaroslav@127
   228
        public Fn defineFn(String code, String... names);
jaroslav@289
   229
        
jaroslav@289
   230
        /** Opens the browser, loads provided page and when the
jaroslav@289
   231
         * page is ready, it calls back to the provider runnable.
jaroslav@289
   232
         * 
jaroslav@289
   233
         * @param page the URL for the page to display
jaroslav@289
   234
         * @param onPageLoad callback when the page is ready
jaroslav@289
   235
         */
jaroslav@128
   236
        public void displayPage(URL page, Runnable onPageLoad);
jaroslav@289
   237
        
jaroslav@289
   238
        /** Loads a script into the browser JavaScript interpreter and 
jaroslav@289
   239
         * executes it.
jaroslav@289
   240
         * @param code the script to execute
jaroslav@289
   241
         * @throws Exception if something goes wrong, throw an exception
jaroslav@289
   242
         */
jaroslav@163
   243
        public void loadScript(Reader code) throws Exception;
jaroslav@123
   244
    }
jaroslav@430
   245
    
jaroslav@430
   246
    /** Additional interface to be implemented by {@link Presenter}s that
jaroslav@430
   247
     * wish to control what objects are passed into the JavaScript virtual 
jaroslav@430
   248
     * machine.
jaroslav@430
   249
     * <p>
jaroslav@430
   250
     * If a JavaScript engine makes callback to Java method that returns 
jaroslav@430
   251
     * a value, the {@link #toJavaScript(java.lang.Object)} method is
jaroslav@430
   252
     * consulted to convert the Java value to something reasonable inside
jaroslav@430
   253
     * JavaScript VM.
jaroslav@430
   254
     * <p>
jaroslav@430
   255
     * <em>Note:</em> The implementation based on <em>JavaFX</em> <code>WebView</code>
jaroslav@430
   256
     * uses this interface to convert Java arrays to JavaScript ones.
jaroslav@430
   257
     * 
jaroslav@430
   258
     * @see Presenter
jaroslav@430
   259
     * @since 0.7
jaroslav@430
   260
     */
jaroslav@430
   261
    public interface ToJavaScript {
jaroslav@430
   262
        /** Convert a Java return value into some object suitable for
jaroslav@430
   263
         * JavaScript virtual machine.
jaroslav@430
   264
         * 
jaroslav@430
   265
         * @param toReturn the Java object to be returned
jaroslav@430
   266
         * @return the replacement value to return instead
jaroslav@430
   267
         */
jaroslav@430
   268
        public Object toJavaScript(Object toReturn);
jaroslav@430
   269
    }
jaroslav@446
   270
    
jaroslav@446
   271
    /** Additional interface to be implemented by {@link Presenter}s that
jaroslav@446
   272
     * need to convert JavaScript object (usually array) to Java object 
jaroslav@446
   273
     * when calling back from JavaScript to Java.
jaroslav@446
   274
     * <p>
jaroslav@446
   275
     * <em>Note:</em> The implementation based on <em>JavaFX</em>
jaroslav@446
   276
     * <code>WebView</code> uses this interface to convert JavaScript arrays to
jaroslav@446
   277
     * Java ones.
jaroslav@446
   278
      * 
jaroslav@446
   279
     * @since 0.7
jaroslav@446
   280
     */
jaroslav@446
   281
    public interface FromJavaScript {
jaroslav@446
   282
        /** Convert a JavaScript object into suitable Java representation
jaroslav@446
   283
         * before a Java method is called with this object as an argument.
jaroslav@446
   284
         * 
jaroslav@446
   285
         * @param js the JavaScript object
jaroslav@446
   286
         * @return replacement object for 
jaroslav@446
   287
         */
jaroslav@446
   288
        public Object toJava(Object js);
jaroslav@446
   289
    }
jaroslav@123
   290
}