javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/Knockout.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 12 Apr 2013 15:42:05 +0200
branchfx
changeset 972 fbabd1f33dda
parent 971 545ffab9c29a
child 973 44cd2b184dd1
permissions -rw-r--r--
console.log(...) realy logs something
     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         JSObject koProp = (JSObject) ((JSObject)model).getMember(prop);
    93         koProp.call("valueHasMutated");
    94     }
    95     
    96 
    97     @JavaScriptBody(args = { "id", "ev" }, body = "ko.utils.triggerEvent(window.document.getElementById(id), ev.substring(2));")
    98     public static void triggerEvent(String id, String ev) {
    99     }
   100     
   101     @JavaScriptBody(args = { "bindings", "model", "prop", "getter", "setter", "primitive", "array" }, body =
   102           "var bnd = {\n"
   103         + "  'read': function() {\n"
   104         + "    var v = model[getter]();\n"
   105         + "    if (array) v = v.koArray();\n"
   106         + "    return v;\n"
   107         + "  },\n"
   108         + "  'owner': bindings\n"
   109         + "};\n"
   110         + "if (setter != null) {\n"
   111         + "  bnd['write'] = function(val) {\n"
   112         + "    model[setter](primitive ? new Number(val) : val);\n"
   113         + "  };\n"
   114         + "}\n"
   115         + "bindings[prop] = ko['computed'](bnd);"
   116     )
   117     private static void bind(
   118         Object bindings, Object model, String prop, String getter, String setter, boolean primitive, boolean array
   119     ) {
   120         WebEngine e = web();
   121         JSObject bnd = (JSObject) e.executeScript("var x = {}; x.bnd = "
   122         + "new Function('ko', 'bindings', 'model', 'prop', 'getter', 'setter', 'primitive', 'array', '"
   123         + "var bnd = {"
   124         + "  read: function() {"
   125         + "    try {"
   126         + "      var v = model[getter]();"
   127         + "      try { v = v.koData(); } catch (ignore) {};"
   128         + "      return v;"
   129         + "    } catch (e) {"
   130         + "      alert(\"Cannot call \" + getter + \" on \" + model + \" error: \" + e);"
   131         + "    }"
   132         + "  },"
   133         + "  owner: bindings"
   134         + "};"
   135         + "if (setter != null) {"
   136         + "  bnd.write = function(val) {"
   137         + "    model[setter](primitive ? new Number(val) : val);"
   138         + "  };"
   139         + "};"
   140         + "bindings[prop] = ko.computed(bnd);'"
   141         + "); x;");
   142         
   143         Object ko = e.executeScript("ko");
   144         bnd.call("bnd", ko, bindings, model, prop, strip(getter), strip(setter), primitive, array);
   145         LOG.log(Level.FINE, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
   146     }
   147     
   148     private static String strip(String mangled) {
   149         if (mangled == null) {
   150             return null;
   151         }
   152         int under = mangled.indexOf("__");
   153         return mangled.substring(0, under);
   154     }
   155     @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body = 
   156         "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
   157     )
   158     private static void expose(
   159         Object bindings, Object model, String prop, String sig
   160     ) {
   161     }
   162     
   163     @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
   164     private static void applyBindings(Object bindings) {
   165         JSObject ko = (JSObject) web().executeScript("ko");
   166         ko.call("applyBindings", bindings);
   167     }
   168     
   169     private static WebEngine web() {
   170         return (WebEngine) System.getProperties().get("webEngine");
   171     }
   172     
   173     
   174     private static void applyImpl(
   175         String[] propsGettersAndSetters,
   176         Class<?> modelClass,
   177         Object bindings,
   178         Object model,
   179         String[] methodsAndSignatures
   180     ) throws IllegalStateException, SecurityException {
   181         for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
   182             try {
   183                 Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
   184                 bind(bindings, model, propsGettersAndSetters[i],
   185                     propsGettersAndSetters[i + 1],
   186                     propsGettersAndSetters[i + 2],
   187                     getter.getReturnType().isPrimitive(),
   188                     List.class.isAssignableFrom(getter.getReturnType()));
   189             } catch (NoSuchMethodException ex) {
   190                 throw new IllegalStateException(ex.getMessage());
   191             }
   192         }
   193         for (int i = 0; i < methodsAndSignatures.length; i += 2) {
   194             expose(
   195                 bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);
   196         }
   197     }
   198 }