javaquery/api/src/main/java/org/apidesign/bck2brwsr/htmlpage/Knockout.java
author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
Fri, 12 Apr 2013 15:59:24 +0200
branchfx
changeset 973 44cd2b184dd1
parent 972 fbabd1f33dda
child 975 094cd25a16d9
permissions -rw-r--r--
Surround calls to JavaScript with catch (Throwable)
     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             bnd.call("bnd", ko, bindings, model, prop, strip(getter), strip(setter), primitive, array);
   150             LOG.log(Level.FINE, "binding defined for {0}: {1}", new Object[]{prop, ((JSObject)bindings).getMember(prop)});
   151         } catch (Throwable ex) {
   152             LOG.log(Level.FINE, "binding failed for {0} on {1}", new Object[]{prop, bindings});
   153         }
   154     }
   155     
   156     private static String strip(String mangled) {
   157         if (mangled == null) {
   158             return null;
   159         }
   160         int under = mangled.indexOf("__");
   161         return mangled.substring(0, under);
   162     }
   163     @JavaScriptBody(args = { "bindings", "model", "prop", "sig" }, body = 
   164         "bindings[prop] = function(data, ev) { model[sig](data, ev); };"
   165     )
   166     private static void expose(
   167         Object bindings, Object model, String prop, String sig
   168     ) {
   169     }
   170     
   171     @JavaScriptBody(args = { "bindings" }, body = "ko.applyBindings(bindings);")
   172     private static void applyBindings(Object bindings) {
   173         JSObject ko = (JSObject) web().executeScript("ko");
   174         ko.call("applyBindings", bindings);
   175     }
   176     
   177     private static WebEngine web() {
   178         return (WebEngine) System.getProperties().get("webEngine");
   179     }
   180     
   181     
   182     private static void applyImpl(
   183         String[] propsGettersAndSetters,
   184         Class<?> modelClass,
   185         Object bindings,
   186         Object model,
   187         String[] methodsAndSignatures
   188     ) throws IllegalStateException, SecurityException {
   189         for (int i = 0; i < propsGettersAndSetters.length; i += 4) {
   190             try {
   191                 Method getter = modelClass.getMethod(propsGettersAndSetters[i + 3]);
   192                 bind(bindings, model, propsGettersAndSetters[i],
   193                     propsGettersAndSetters[i + 1],
   194                     propsGettersAndSetters[i + 2],
   195                     getter.getReturnType().isPrimitive(),
   196                     List.class.isAssignableFrom(getter.getReturnType()));
   197             } catch (NoSuchMethodException ex) {
   198                 throw new IllegalStateException(ex.getMessage());
   199             }
   200         }
   201         for (int i = 0; i < methodsAndSignatures.length; i += 2) {
   202             expose(
   203                 bindings, model, methodsAndSignatures[i], methodsAndSignatures[i + 1]);
   204         }
   205     }
   206 }