ko4j/src/main/java/org/netbeans/html/ko4j/Knockout.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sun, 04 Oct 2015 14:55:01 +0200
changeset 1007 2ea65c6d3a8b
parent 984 3dfb8f1fd2f5
child 1020 b5d5cbb44ce0
permissions -rw-r--r--
#255677: Keep reference to Knockout object until its model object is GCed
jaroslav@37
     1
/**
jaroslav@358
     2
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
jaroslav@37
     3
 *
jaroslav@551
     4
 * Copyright 2013-2014 Oracle and/or its affiliates. All rights reserved.
jaroslav@37
     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@37
     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@37
    42
 */
jaroslav@442
    43
package org.netbeans.html.ko4j;
jaroslav@37
    44
jtulach@877
    45
import java.lang.ref.ReferenceQueue;
jtulach@870
    46
import java.lang.ref.WeakReference;
jtulach@1007
    47
import java.util.Collections;
jtulach@1007
    48
import java.util.HashSet;
jtulach@1007
    49
import java.util.Set;
jaroslav@131
    50
import net.java.html.js.JavaScriptBody;
jaroslav@163
    51
import net.java.html.js.JavaScriptResource;
jaroslav@37
    52
import net.java.html.json.Model;
jtulach@838
    53
import org.netbeans.html.json.spi.FunctionBinding;
jtulach@838
    54
import org.netbeans.html.json.spi.PropertyBinding;
jaroslav@37
    55
jaroslav@54
    56
/** This is an implementation package - just
jaroslav@54
    57
 * include its JAR on classpath and use official {@link Context} API
jaroslav@54
    58
 * to access the functionality.
jaroslav@54
    59
 * <p>
jaroslav@54
    60
 * Provides binding between {@link Model models} and knockout.js running
jaroslav@54
    61
 * inside a JavaFX WebView. 
jaroslav@37
    62
 *
jtulach@790
    63
 * @author Jaroslav Tulach
jaroslav@37
    64
 */
jtulach@816
    65
@JavaScriptResource("knockout-3.2.0.debug.js")
jtulach@870
    66
final class Knockout extends WeakReference<Object> {
jtulach@877
    67
    private static final ReferenceQueue<Object> QUEUE = new ReferenceQueue();
jtulach@1007
    68
    private static final Set<Knockout> active = Collections.synchronizedSet(new HashSet<Knockout>());
jtulach@877
    69
    
jtulach@877
    70
    private PropertyBinding[] props;
jtulach@877
    71
    private FunctionBinding[] funcs;
jtulach@877
    72
    private Object js;
jtulach@871
    73
    private Object strong;
jtulach@868
    74
jtulach@877
    75
    public Knockout(Object model, Object js, PropertyBinding[] props, FunctionBinding[] funcs) {
jtulach@877
    76
        super(model, QUEUE);
jtulach@877
    77
        this.js = js;
jtulach@870
    78
        this.props = new PropertyBinding[props.length];
jtulach@870
    79
        for (int i = 0; i < props.length; i++) {
jtulach@870
    80
            this.props[i] = props[i].weak();
jtulach@870
    81
        }
jtulach@870
    82
        this.funcs = new FunctionBinding[funcs.length];
jtulach@870
    83
        for (int i = 0; i < funcs.length; i++) {
jtulach@870
    84
            this.funcs[i] = funcs[i].weak();
jtulach@870
    85
        }
jtulach@1007
    86
        active.add(this);
jtulach@868
    87
    }
jtulach@868
    88
    
jtulach@877
    89
    static void cleanUp() {
jtulach@877
    90
        for (;;) {
jtulach@877
    91
            Knockout ko = (Knockout)QUEUE.poll();
jtulach@877
    92
            if (ko == null) {
jtulach@877
    93
                return;
jtulach@877
    94
            }
jtulach@1007
    95
            active.remove(ko);
jtulach@877
    96
            clean(ko.js);
jtulach@877
    97
            ko.js = null;
jtulach@877
    98
            ko.props = null;
jtulach@877
    99
            ko.funcs = null;
jtulach@877
   100
        }
jtulach@877
   101
    }
jtulach@877
   102
    
jtulach@871
   103
    final void hold() {
jtulach@871
   104
        strong = get();
jtulach@871
   105
    }
jtulach@871
   106
    
jtulach@868
   107
    final Object getValue(int index) {
jtulach@868
   108
        return props[index].getValue();
jtulach@868
   109
    }
jtulach@868
   110
    
jtulach@868
   111
    final void setValue(int index, Object v) {
jtulach@870
   112
        if (v instanceof Knockout) {
jtulach@870
   113
            v = ((Knockout)v).get();
jtulach@870
   114
        }
jtulach@868
   115
        props[index].setValue(v);
jtulach@868
   116
    }
jtulach@868
   117
    
jtulach@868
   118
    final void call(int index, Object data, Object ev) {
jtulach@868
   119
        funcs[index].call(data, ev);
jtulach@868
   120
    }
jtulach@868
   121
    
jaroslav@570
   122
    @JavaScriptBody(args = { "model", "prop", "oldValue", "newValue" }, 
jaroslav@570
   123
        wait4js = false,
jaroslav@570
   124
        body =
jaroslav@276
   125
          "if (model) {\n"
jaroslav@276
   126
        + "  var koProp = model[prop];\n"
jaroslav@276
   127
        + "  if (koProp && koProp['valueHasMutated']) {\n"
jaroslav@567
   128
        + "    if ((oldValue !== null || newValue !== null)) {\n"
jaroslav@567
   129
        + "      koProp['valueHasMutated'](newValue);\n"
jaroslav@567
   130
        + "    } else if (koProp['valueHasMutated']) {\n"
jaroslav@567
   131
        + "      koProp['valueHasMutated']();\n"
jaroslav@567
   132
        + "    }\n"
jaroslav@276
   133
        + "  }\n"
jaroslav@276
   134
        + "}\n"
jaroslav@276
   135
    )
jaroslav@567
   136
    public native static void valueHasMutated(
jaroslav@567
   137
        Object model, String prop, Object oldValue, Object newValue
jaroslav@567
   138
    );
jaroslav@37
   139
jtulach@908
   140
    @JavaScriptBody(args = { "id", "bindings" }, body = 
jtulach@908
   141
        "var d = window['document'];\n" +
jtulach@908
   142
        "var e = id ? d['getElementById'](id) : d['body'];\n" +
jtulach@908
   143
        "ko['cleanNode'](e);\n" +
jtulach@908
   144
        "ko['applyBindings'](bindings, e);\n" +
jtulach@871
   145
        "return bindings['ko4j'];\n"
jaroslav@570
   146
    )
jtulach@908
   147
    native static Object applyBindings(String id, Object bindings);
jaroslav@276
   148
    
jaroslav@574
   149
    @JavaScriptBody(args = { "cnt" }, body = 
jaroslav@574
   150
        "var arr = new Array(cnt);\n" +
jaroslav@574
   151
        "for (var i = 0; i < cnt; i++) arr[i] = new Object();\n" +
jaroslav@574
   152
        "return arr;\n"
jaroslav@574
   153
    )
jaroslav@574
   154
    native static Object[] allocJS(int cnt);
jaroslav@574
   155
    
jaroslav@276
   156
    @JavaScriptBody(
jaroslav@276
   157
        javacall = true,
jtulach@900
   158
        keepAlive = false,
jaroslav@570
   159
        wait4js = false,
jtulach@898
   160
        args = { "ret", "propNames", "propReadOnly", "propValues", "funcNames" },
jaroslav@570
   161
        body = 
jtulach@898
   162
          "Object.defineProperty(ret, 'ko4j', { value : this });\n"
jtulach@868
   163
        + "function koComputed(index, name, readOnly, value) {\n"
jtulach@861
   164
        + "  var trigger = ko['observable']()['extend']({'notify':'always'});"
jaroslav@279
   165
        + "  function realGetter() {\n"
jtulach@877
   166
        + "    var self = ret['ko4j'];\n"
jaroslav@437
   167
        + "    try {\n"
jtulach@877
   168
        + "      var v = self ? self.@org.netbeans.html.ko4j.Knockout::getValue(I)(index) : null;\n"
jaroslav@437
   169
        + "      return v;\n"
jaroslav@437
   170
        + "    } catch (e) {\n"
jtulach@871
   171
        + "      alert(\"Cannot call getValue on \" + self + \" prop: \" + name + \" error: \" + e);\n"
jaroslav@437
   172
        + "    }\n"
jaroslav@279
   173
        + "  }\n"
jaroslav@279
   174
        + "  var activeGetter = function() { return value; };\n"
jaroslav@437
   175
        + "  var bnd = {\n"
jtulach@672
   176
        + "    'read': function() {\n"
jtulach@816
   177
        + "      trigger();\n"
jaroslav@437
   178
        + "      var r = activeGetter();\n"
jaroslav@437
   179
        + "      activeGetter = realGetter;\n"
jtulach@758
   180
        + "      if (r) try { var br = r.valueOf(); } catch (err) {}\n"
jtulach@764
   181
        + "      return br === undefined ? r: br;\n"
jaroslav@437
   182
        + "    },\n"
jtulach@672
   183
        + "    'owner': ret\n"
jaroslav@276
   184
        + "  };\n"
jaroslav@276
   185
        + "  if (!readOnly) {\n"
jtulach@672
   186
        + "    bnd['write'] = function(val) {\n"
jtulach@877
   187
        + "      var self = ret['ko4j'];\n"
jtulach@877
   188
        + "      if (!self) return;\n"
jtulach@870
   189
        + "      var model = val['ko4j'];\n"
jtulach@925
   190
        + "      self.@org.netbeans.html.ko4j.Knockout::setValue(ILjava/lang/Object;)(index, model ? model : val);\n"
jaroslav@437
   191
        + "    };\n"
jaroslav@437
   192
        + "  };\n"
jtulach@672
   193
        + "  var cmpt = ko['computed'](bnd);\n"
jtulach@672
   194
        + "  cmpt['valueHasMutated'] = function(val) {\n"
jaroslav@567
   195
        + "    if (arguments.length === 1) activeGetter = function() { return val; };\n"
jtulach@861
   196
        + "    trigger['valueHasMutated']();\n"
jaroslav@567
   197
        + "  };\n"
jaroslav@567
   198
        + "  ret[name] = cmpt;\n"
jaroslav@276
   199
        + "}\n"
jaroslav@276
   200
        + "for (var i = 0; i < propNames.length; i++) {\n"
jtulach@868
   201
        + "  koComputed(i, propNames[i], propReadOnly[i], propValues[i]);\n"
jaroslav@276
   202
        + "}\n"
jtulach@868
   203
        + "function koExpose(index, name) {\n"
jaroslav@276
   204
        + "  ret[name] = function(data, ev) {\n"
jtulach@877
   205
        + "    var self = ret['ko4j'];\n"
jtulach@877
   206
        + "    if (!self) return;\n"
jtulach@871
   207
        + "    self.@org.netbeans.html.ko4j.Knockout::call(ILjava/lang/Object;Ljava/lang/Object;)(index, data, ev);\n"
jaroslav@276
   208
        + "  };\n"
jaroslav@276
   209
        + "}\n"
jaroslav@276
   210
        + "for (var i = 0; i < funcNames.length; i++) {\n"
jtulach@868
   211
        + "  koExpose(i, funcNames[i]);\n"
jaroslav@276
   212
        + "}\n"
jaroslav@276
   213
        )
jtulach@898
   214
    native void wrapModel(
jtulach@870
   215
        Object ret, 
jtulach@868
   216
        String[] propNames, boolean[] propReadOnly, Object propValues,
jtulach@868
   217
        String[] funcNames
jaroslav@276
   218
    );
jaroslav@430
   219
    
jtulach@877
   220
    @JavaScriptBody(args = { "js" }, wait4js = false, body = 
jtulach@877
   221
        "delete js['ko4j'];\n" +
jtulach@877
   222
        "for (var p in js) {\n" +
jtulach@877
   223
        "  delete js[p];\n" +
jtulach@877
   224
        "};\n" +
jtulach@877
   225
        "\n"
jtulach@877
   226
    )
jtulach@877
   227
    private static native void clean(Object js);
jtulach@877
   228
    
jtulach@870
   229
    @JavaScriptBody(args = { "o" }, body = "return o['ko4j'] ? o['ko4j'] : o;")
jaroslav@570
   230
    private static native Object toModelImpl(Object wrapper);
jaroslav@570
   231
    static Object toModel(Object wrapper) {
jtulach@870
   232
        Object o = toModelImpl(wrapper);
jtulach@870
   233
        if (o instanceof Knockout) {
jtulach@870
   234
            return ((Knockout)o).get();
jtulach@870
   235
        } else {
jtulach@870
   236
            return o;
jtulach@870
   237
        }
jaroslav@570
   238
    }
jaroslav@37
   239
}