javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/Knockout.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Sun, 14 Apr 2013 11:52:36 +0200
branchfx
changeset 979 83f4aa79c130
parent 975 094cd25a16d9
child 980 1ea155524be4
permissions -rw-r--r--
Tons of in VM and in page logging
     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 Object koData() {
    70         return model;
    71     }
    72 
    73     private static final JSObject KObject;
    74     static {
    75         KObject = (JSObject) web().executeScript(
    76             "(function(scope) {"
    77             + "  var kCnt = 0; "
    78             + "  scope.KObject = {};"
    79             + "  scope.KObject.create= function(value) {"
    80             + "    var cnt = ++kCnt;"
    81             + "    var ret = {};"
    82             + "    ret.toString = function() { return 'KObject' + cnt + ' value: ' + value; };"
    83             + "    return ret;"
    84             + "  };"
    85             + "})(window); window.KObject"
    86             );
    87     }
    88     
    89     public static <M> Knockout applyBindings(
    90         Object model, String[] propsGettersAndSetters,
    91         String[] methodsAndSignatures
    92     ) {
    93         Object bindings = KObject.call("create", model);
    94         applyImpl(propsGettersAndSetters, model.getClass(), bindings, model, methodsAndSignatures);
    95         return new Knockout(bindings);
    96     }
    97     public static <M> Knockout applyBindings(
    98         Class<M> modelClass, M model, String[] propsGettersAndSetters,
    99         String[] methodsAndSignatures
   100     ) {
   101         Object bindings = next;
   102         next = null;
   103         if (bindings == null) {
   104             bindings = KObject.call("create", model);
   105         }
   106         applyImpl(propsGettersAndSetters, modelClass, bindings, model, methodsAndSignatures);
   107         applyBindings(bindings);
   108         return new Knockout(bindings);
   109     }
   110 
   111     public void valueHasMutated(String prop) {
   112         LOG.log(Level.FINE, "property mutated: {0}", prop);
   113         try {
   114             JSObject koProp = (JSObject) ((JSObject) model).getMember(prop);
   115             koProp.call("valueHasMutated");
   116         } catch (Throwable t) {
   117             LOG.log(Level.FINE, "valueHasMutated failed for {0}", model);
   118         }
   119     }
   120     
   121 
   122     @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
   123     public static void triggerEvent(String id, String ev) {
   124     }
   125     
   126     @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
   127           "var bnd = {\n"
   128         + "  'read': function() {\n"
   129         + "    var v = model[getter]();\n"
   130         + "    if (array) v = v.koArray();\n"
   131         + "    return v;\n"
   132         + "  },\n"
   133         + "  'owner': bindings\n"
   134         + "};\n"
   135         + "if (setter != null) {\n"
   136         + "  bnd['write'] = function(val) {\n"
   137         + "    model[setter](primitive ? new Number(val) : val);\n"
   138         + "  };\n"
   139         + "}\n"
   140         + "bindings[prop] = ko['computed'](bnd);"
   141     )
   142     private static void bind(
   143         Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
   144     ) {
   145         WebEngine e = web();
   146         JSObject bnd = (JSObject) e.executeScript("var x = {}; x.bnd = "
   147         + "new Function('ko', 'bindings', 'model', 'prop', 'getter', 'setter', 'primitive', 'array', '"
   148         + "var bnd = {"
   149         + "  read: function() {"
   150         + "    try {"
   151         + "      var v = model[getter]();"
   152         + "      console.log(\" getter value \" + v + \" for property \" + prop);"
   153         + "      try { v = v.koData(); } catch (ignore) {"
   154         + "        console.log(\"Cannot convert to koData: \" + ignore);"
   155         + "      };"
   156         + "      console.log(\" getter ret value \" + v);"
   157         + "      for (var pn in v) {"
   158         + "         console.log(\"  prop: \" + pn + \" + in + \" + v + \" = \" + v[pn]);"
   159         + "         if (typeof v[pn] == \"function\") console.log(\"  its function value:\" + v[pn]());"
   160         + "      }"
   161         + "      console.log(\" all props printed for \" + (typeof v));"
   162         + "      return v;"
   163         + "    } catch (e) {"
   164         + "      alert(\"Cannot call \" + getter + \" on \" + model + \" error: \" + e);"
   165         + "    }"
   166         + "  },"
   167         + "  owner: bindings,"
   168         + "  deferEvaluation: true"
   169         + "};"
   170         + "if (setter != null) {"
   171         + "  bnd.write = function(val) {"
   172         + "    model[setter](primitive ? new Number(val) : val);"
   173         + "  };"
   174         + "};"
   175         + "bindings[prop] = ko.computed(bnd);'"
   176         + "); x;");
   177         
   178         Object ko = e.executeScript("ko");
   179         try {
   180             KOProperty kop = new KOProperty(model, strip(getter), strip(setter));
   181             bnd.call("bnd", ko, bindings, kop, prop, "get", "set", primitive, array);
   182             LOG.log(Level.INFO, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
   183         } catch (Throwable ex) {
   184             LOG.log(Level.INFO, "binding failed for {0} on {1}", new Object[]{prop, bindings});
   185         }
   186     }
   187     
   188     private static String strip(String mangled) {
   189         if (mangled == null) {
   190             return null;
   191         }
   192         int under = mangled.indexOf("__");
   193         return mangled.substring(0, under);
   194     }
   195     @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body = 
   196         "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
   197     )
   198     private static void expose(
   199         Object bindings, Object model, String prop, String sig
   200     ) {
   201     }
   202     
   203     @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
   204     private static void applyBindings(Object bindings) {
   205         JSObject ko = (JSObject) web().executeScript("ko");
   206         ko.call("applyBindings", bindings);
   207     }
   208     
   209     private static WebEngine web() {
   210         return (WebEngine) System.getProperties().get("webEngine");
   211     }
   212     
   213     
   214     private static void applyImpl(
   215         String[] propsGettersAndSetters,
   216         Class<?> modelClass,
   217         Object bindings,
   218         Object model,
   219         String[] methodsAndSignatures
   220     ) throws IllegalStateException, SecurityException {
   221         for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
   222             try {
   223                 Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
   224                 bind(bindings, model, propsGettersAndSetters[i],
   225                     propsGettersAndSetters[i + 1],
   226                     propsGettersAndSetters[i + 2],
   227                     getter.getReturnType().isPrimitive(),
   228                     List.class.isAssignableFrom(getter.getReturnType()));
   229             } catch (NoSuchMethodException ex) {
   230                 throw new IllegalStateException(ex.getMessage());
   231             }
   232         }
   233         for (int i = 0; i < methodsAndSignatures.length; i += 2) {
   234             expose(
   235                 bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);
   236         }
   237     }
   238 }