javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/Knockout.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sat, 13 Apr 2013 09:14:54 +0200
branchfx
changeset 975 094cd25a16d9
parent 973 44cd2b184dd1
child 979 83f4aa79c130
permissions -rw-r--r--
Introducing KOProperty to allow us to call non-public methods and to do conversion of primitive types which is broken in WebView
     1 /**
     2  * Back 2 Browser Bytecode Translator
     3  * Copyright (C) 2012 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     4  *
     5  * This program is free software: you can redistribute it and/or modify
     6  * it under the terms of the GNU General Public License as published by
     7  * the Free Software Foundation, version 2 of the License.
     8  *
     9  * This program is distributed in the hope that it will be useful,
    10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
    11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    12  * GNU General Public License for more details.
    13  *
    14  * You should have received a copy of the GNU General Public License
    15  * along with this program. Look for COPYING file in the top folder.
    16  * If not, see http://opensource.org/licenses/GPL-2.0.
    17  */
    18 package org.apidesign.bck2brwsr.htmlpage;
    19 
    20 import java.io.BufferedReader;
    21 import java.io.IOException;
    22 import java.io.InputStreamReader;
    23 import java.lang.reflect.Method;
    24 import java.util.List;
    25 import java.util.logging.Level;
    26 import java.util.logging.Logger;
    27 import javafx.scene.web.WebEngine;
    28 import netscape.javascript.JSObject;
    29 import org.apidesign.bck2brwsr.core.ExtraJavaScript;
    30 import org.apidesign.bck2brwsr.core.JavaScriptBody;
    31 
    32 /** Provides binding between models and 
    33  *
    34  * @author Jaroslav Tulach <jtulach@netbeans.org>
    35  */
    36 @ExtraJavaScript(resource = "/org/apidesign/bck2brwsr/htmlpage/knockout-2.2.1.js")
    37 public class Knockout {
    38     private static final Logger LOG = Logger.getLogger(Knockout.class.getName());
    39     /** used by tests */
    40     static Knockout next;
    41     private final Object model;
    42 
    43     static {
    44         BufferedReader r = new BufferedReader(new InputStreamReader(Knockout.class.getResourceAsStream("knockout-2.2.1.js")));
    45         StringBuilder sb = new StringBuilder();
    46         for (;;) {
    47             try {
    48                 String l = r.readLine();
    49                 if (l == null) {
    50                     break;
    51                 }
    52                 sb.append(l).append('\n');
    53             } catch (IOException ex) {
    54                 throw new IllegalStateException(ex);
    55             }
    56         }
    57         web().executeScript(sb.toString());
    58         Object ko = web().executeScript("ko");
    59         assert ko != null : "Knockout library successfully defined 'ko'";
    60         
    61         Console.register(web());
    62     }
    63     
    64     
    65     Knockout(Object model) {
    66         this.model = model == null ? this : model;
    67     }
    68     
    69     public static <M> Knockout applyBindings(
    70         Object model, String[] propsGettersAndSetters,
    71         String[] methodsAndSignatures
    72     ) {
    73         applyImpl(propsGettersAndSetters, model.getClass(), model, model, methodsAndSignatures);
    74         return new Knockout(model);
    75     }
    76     public static <M> Knockout applyBindings(
    77         Class<M> modelClass, M model, String[] propsGettersAndSetters,
    78         String[] methodsAndSignatures
    79     ) {
    80         Object bindings = next;
    81         next = null;
    82         if (bindings == null) {
    83             bindings = web().executeScript("new Object()");
    84         }
    85         applyImpl(propsGettersAndSetters, modelClass, bindings, model, methodsAndSignatures);
    86         applyBindings(bindings);
    87         return new Knockout(bindings);
    88     }
    89 
    90     public void valueHasMutated(String prop) {
    91         LOG.log(Level.FINE, "property mutated: {0}", prop);
    92         try {
    93             JSObject koProp = (JSObject) ((JSObject) model).getMember(prop);
    94             koProp.call("valueHasMutated");
    95         } catch (Throwable t) {
    96             LOG.log(Level.FINE, "valueHasMutated failed for {0}", model);
    97         }
    98     }
    99     
   100 
   101     @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
   102     public static void triggerEvent(String id, String ev) {
   103     }
   104     
   105     @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
   106           "var bnd = {\n"
   107         + "  'read': function() {\n"
   108         + "    var v = model[getter]();\n"
   109         + "    if (array) v = v.koArray();\n"
   110         + "    return v;\n"
   111         + "  },\n"
   112         + "  'owner': bindings\n"
   113         + "};\n"
   114         + "if (setter != null) {\n"
   115         + "  bnd['write'] = function(val) {\n"
   116         + "    model[setter](primitive ? new Number(val) : val);\n"
   117         + "  };\n"
   118         + "}\n"
   119         + "bindings[prop] = ko['computed'](bnd);"
   120     )
   121     private static void bind(
   122         Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
   123     ) {
   124         WebEngine e = web();
   125         JSObject bnd = (JSObject) e.executeScript("var x = {}; x.bnd = "
   126         + "new Function('ko', 'bindings', 'model', 'prop', 'getter', 'setter', 'primitive', 'array', '"
   127         + "var bnd = {"
   128         + "  read: function() {"
   129         + "    try {"
   130         + "      var v = model[getter]();"
   131         + "      try { v = v.koData(); } catch (ignore) {};"
   132         + "      return v;"
   133         + "    } catch (e) {"
   134         + "      alert(\"Cannot call \" + getter + \" on \" + model + \" error: \" + e);"
   135         + "    }"
   136         + "  },"
   137         + "  owner: bindings"
   138         + "};"
   139         + "if (setter != null) {"
   140         + "  bnd.write = function(val) {"
   141         + "    model[setter](primitive ? new Number(val) : val);"
   142         + "  };"
   143         + "};"
   144         + "bindings[prop] = ko.computed(bnd);'"
   145         + "); x;");
   146         
   147         Object ko = e.executeScript("ko");
   148         try {
   149             KOProperty kop = new KOProperty(model, strip(getter), strip(setter));
   150             bnd.call("bnd", ko, bindings, kop, prop, "get", "set", primitive, array);
   151             LOG.log(Level.FINE, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
   152         } catch (Throwable ex) {
   153             LOG.log(Level.FINE, "binding failed for {0} on {1}", new Object[]{prop, bindings});
   154         }
   155     }
   156     
   157     private static String strip(String mangled) {
   158         if (mangled == null) {
   159             return null;
   160         }
   161         int under = mangled.indexOf("__");
   162         return mangled.substring(0, under);
   163     }
   164     @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body = 
   165         "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
   166     )
   167     private static void expose(
   168         Object bindings, Object model, String prop, String sig
   169     ) {
   170     }
   171     
   172     @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
   173     private static void applyBindings(Object bindings) {
   174         JSObject ko = (JSObject) web().executeScript("ko");
   175         ko.call("applyBindings", bindings);
   176     }
   177     
   178     private static WebEngine web() {
   179         return (WebEngine) System.getProperties().get("webEngine");
   180     }
   181     
   182     
   183     private static void applyImpl(
   184         String[] propsGettersAndSetters,
   185         Class<?> modelClass,
   186         Object bindings,
   187         Object model,
   188         String[] methodsAndSignatures
   189     ) throws IllegalStateException, SecurityException {
   190         for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
   191             try {
   192                 Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
   193                 bind(bindings, model, propsGettersAndSetters[i],
   194                     propsGettersAndSetters[i + 1],
   195                     propsGettersAndSetters[i + 2],
   196                     getter.getReturnType().isPrimitive(),
   197                     List.class.isAssignableFrom(getter.getReturnType()));
   198             } catch (NoSuchMethodException ex) {
   199                 throw new IllegalStateException(ex.getMessage());
   200             }
   201         }
   202         for (int i = 0; i < methodsAndSignatures.length; i += 2) {
   203             expose(
   204                 bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);
   205         }
   206     }
   207 }