ko4j/src/main/java/org/netbeans/html/ko4j/Knockout.java
author Jaroslav Tulach <jtulach@netbeans.org>
Mon, 22 Feb 2016 19:58:32 +0100
branchNonMutable258088
changeset 1055 c61d247f087a
parent 1031 86218dd9270b
child 1073 076297c6bca3
permissions -rw-r--r--
#258088: Non-mutable values aren't wrapped into ko.observable, but rather stored as primitive values
     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 org.netbeans.html.ko4j;
    44 
    45 import java.lang.ref.ReferenceQueue;
    46 import java.lang.ref.WeakReference;
    47 import java.util.Collections;
    48 import java.util.HashSet;
    49 import java.util.Set;
    50 import net.java.html.js.JavaScriptBody;
    51 import net.java.html.js.JavaScriptResource;
    52 import net.java.html.json.Model;
    53 import org.netbeans.html.json.spi.FunctionBinding;
    54 import org.netbeans.html.json.spi.PropertyBinding;
    55 
    56 /** This is an implementation package - just
    57  * include its JAR on classpath and use official {@link Context} API
    58  * to access the functionality.
    59  * <p>
    60  * Provides binding between {@link Model models} and knockout.js running
    61  * inside a JavaFX WebView. 
    62  *
    63  * @author Jaroslav Tulach
    64  */
    65 @JavaScriptResource("knockout-3.4.0.js")
    66 final class Knockout extends WeakReference<Object> {
    67     private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue();
    68     private static final Set<Knockout> active = Collections.synchronizedSet(new HashSet<Knockout>());
    69 
    70     @JavaScriptBody(args = {"object", "property"}, body = 
    71         "var ret;\n" + 
    72         "if (property === null) ret = object;\n" + 
    73         "else if (object === null) ret = null;\n" + 
    74         "else ret = object[property];\n" + 
    75         "return ret ? ko.utils.unwrapObservable(ret) : null;"
    76     )
    77     static Object getProperty(Object object, String property) {
    78         return null;
    79     }
    80     
    81     private PropertyBinding[] props;
    82     private FunctionBinding[] funcs;
    83     private Object js;
    84     private Object strong;
    85 
    86     public Knockout(Object model, Object js, PropertyBinding[] props, FunctionBinding[] funcs) {
    87         super(model, QUEUE);
    88         this.js = js;
    89         this.props = new PropertyBinding[props.length];
    90         for (int i = 0; i < props.length; i++) {
    91             this.props[i] = props[i].weak();
    92         }
    93         this.funcs = new FunctionBinding[funcs.length];
    94         for (int i = 0; i < funcs.length; i++) {
    95             this.funcs[i] = funcs[i].weak();
    96         }
    97         active.add(this);
    98     }
    99     
   100     static void cleanUp() {
   101         for (;;) {
   102             Knockout ko = (Knockout)QUEUE.poll();
   103             if (ko == null) {
   104                 return;
   105             }
   106             active.remove(ko);
   107             clean(ko.js);
   108             ko.js = null;
   109             ko.props = null;
   110             ko.funcs = null;
   111         }
   112     }
   113     
   114     final void hold() {
   115         strong = get();
   116     }
   117     
   118     final Object getValue(int index) {
   119         return props[index].getValue();
   120     }
   121     
   122     final void setValue(int index, Object v) {
   123         if (v instanceof Knockout) {
   124             v = ((Knockout)v).get();
   125         }
   126         props[index].setValue(v);
   127     }
   128     
   129     final void call(int index, Object data, Object ev) {
   130         funcs[index].call(data, ev);
   131     }
   132     
   133     @JavaScriptBody(args = { "model", "prop", "oldValue", "newValue" }, 
   134         wait4js = false,
   135         body =
   136           "if (model) {\n"
   137         + "  var koProp = model[prop];\n"
   138         + "  if (koProp && koProp['valueHasMutated']) {\n"
   139         + "    if ((oldValue !== null || newValue !== null)) {\n"
   140         + "      koProp['valueHasMutated'](newValue);\n"
   141         + "    } else if (koProp['valueHasMutated']) {\n"
   142         + "      koProp['valueHasMutated']();\n"
   143         + "    }\n"
   144         + "  }\n"
   145         + "}\n"
   146     )
   147     public native static void valueHasMutated(
   148         Object model, String prop, Object oldValue, Object newValue
   149     );
   150 
   151     @JavaScriptBody(args = { "id", "bindings" }, body = 
   152         "var d = window['document'];\n" +
   153         "var e = id ? d['getElementById'](id) : d['body'];\n" +
   154         "ko['cleanNode'](e);\n" +
   155         "ko['applyBindings'](bindings, e);\n" +
   156         "return bindings['ko4j'];\n"
   157     )
   158     native static Object applyBindings(String id, Object bindings);
   159     
   160     @JavaScriptBody(args = { "cnt" }, body = 
   161         "var arr = new Array(cnt);\n" +
   162         "for (var i = 0; i < cnt; i++) arr[i] = new Object();\n" +
   163         "return arr;\n"
   164     )
   165     native static Object[] allocJS(int cnt);
   166     
   167     @JavaScriptBody(
   168         javacall = true,
   169         keepAlive = false,
   170         wait4js = false,
   171         args = { "ret", "copyFrom", "propNames", "propReadOnly", "propConstant", "propValues", "funcNames" },
   172         body = 
   173           "Object.defineProperty(ret, 'ko4j', { value : this });\n"
   174         + "function koComputed(index, name, readOnly, value) {\n"
   175         + "  var orig = copyFrom ? copyFrom[name] : null;\n"
   176         + "  if (!ko['isObservable'](orig)) {\n"
   177         + "    orig = null;\n"
   178         + "    var trigger = ko['observable']()['extend']({'notify':'always'});\n"
   179         + "  } else {\n"
   180         + "    var trigger = orig;\n"
   181         + "  }\n"
   182         + "  function realGetter() {\n"
   183         + "    var self = ret['ko4j'];\n"
   184         + "    try {\n"
   185         + "      var v = self ? self.@org.netbeans.html.ko4j.Knockout::getValue(I)(index) : null;\n"
   186         + "      return v;\n"
   187         + "    } catch (e) {\n"
   188         + "      alert(\"Cannot call getValue on \" + self + \" prop: \" + name + \" error: \" + e);\n"
   189         + "    }\n"
   190         + "  }\n"
   191         + "  var activeGetter = orig ? orig : function() { return value; };\n"
   192         + "  var bnd = {\n"
   193         + "    'read': function() {\n"
   194         + "      trigger();\n"
   195         + "      if (orig) {\n"
   196         + "        var r = orig();\n"
   197         + "      } else {\n"
   198         + "        var r = activeGetter();\n"
   199         + "        activeGetter = realGetter;\n"
   200         + "      }\n"
   201         + "      if (r) try { var br = r.valueOf(); } catch (err) {}\n"
   202         + "      return br === undefined ? r: br;\n"
   203         + "    },\n"
   204         + "    'owner': ret\n"
   205         + "  };\n"
   206         + "  if (!readOnly) {\n"
   207         + "    function write(val) {\n"
   208         + "      if (orig) orig(val);\n"
   209         + "      var self = ret['ko4j'];\n"
   210         + "      if (!self) return;\n"
   211         + "      var model = val ? val['ko4j'] : null;\n"
   212         + "      self.@org.netbeans.html.ko4j.Knockout::setValue(ILjava/lang/Object;)(index, model ? model : val);\n"
   213         + "    };\n"
   214         + "    bnd['write'] = write;\n"
   215         + "    if (orig) {\n"
   216         + "      write(orig());\n"
   217         + "      orig.subscribe(write);\n"
   218         + "    }\n"
   219         + "  };\n"
   220         + "  var cmpt = ko['computed'](bnd);\n"
   221         + "  cmpt['valueHasMutated'] = function(val) {\n"
   222         + "    if (arguments.length === 1) activeGetter = function() { return val; };\n"
   223         + "    trigger(val);\n"
   224         + "  };\n"
   225         + "  ret[name] = cmpt;\n"
   226         + "}\n"
   227         + "for (var i = 0; i < propNames.length; i++) {\n"
   228         + "  if (propConstant[i]) {\n"
   229         + "    ret[propNames[i]] = propValues[i];\n"
   230         + "  } else {\n"
   231         + "    koComputed(i, propNames[i], propReadOnly[i], propValues[i]);\n"
   232         + "  }\n"
   233         + "}\n"
   234         + "function koExpose(index, name) {\n"
   235         + "  ret[name] = function(data, ev) {\n"
   236         + "    var self = ret['ko4j'];\n"
   237         + "    if (!self) return;\n"
   238         + "    self.@org.netbeans.html.ko4j.Knockout::call(ILjava/lang/Object;Ljava/lang/Object;)(index, data, ev);\n"
   239         + "  };\n"
   240         + "}\n"
   241         + "for (var i = 0; i < funcNames.length; i++) {\n"
   242         + "  koExpose(i, funcNames[i]);\n"
   243         + "}\n"
   244         )
   245     native void wrapModel(
   246         Object ret, Object copyFrom,
   247         String[] propNames, Boolean[] propReadOnly, Boolean[] propConstant,
   248         Object propValues,
   249         String[] funcNames
   250     );
   251     
   252     @JavaScriptBody(args = { "js" }, wait4js = false, body = 
   253         "delete js['ko4j'];\n" +
   254         "for (var p in js) {\n" +
   255         "  delete js[p];\n" +
   256         "};\n" +
   257         "\n"
   258     )
   259     private static native void clean(Object js);
   260     
   261     @JavaScriptBody(args = { "o" }, body = "return o['ko4j'] ? o['ko4j'] : o;")
   262     private static native Object toModelImpl(Object wrapper);
   263     static Object toModel(Object wrapper) {
   264         Object o = toModelImpl(wrapper);
   265         if (o instanceof Knockout) {
   266             return ((Knockout)o).get();
   267         } else {
   268             return o;
   269         }
   270     }
   271 }