Author: mikesamuel
Date: Mon Jan 12 17:41:06 2009
New Revision: 3172

Added:
     
trunk/src/com/google/caja/lang/html/html4-elements-extensions-defs.json    
(contents, props changed)
     
trunk/src/com/google/caja/lang/html/html4-elements-extensions-whitelist.json    
(contents, props changed)
    trunk/src/com/google/caja/lang/html/html4-elements-extensions.json    
(contents, props changed)
Modified:
    trunk/src/com/google/caja/lang/html/HtmlSchema.java
    trunk/src/com/google/caja/lang/html/html4-elements-whitelist.json
    trunk/src/com/google/caja/plugin/bridal.js
    trunk/src/com/google/caja/plugin/domita.js
    trunk/tests/com/google/caja/plugin/domita_test.html
    trunk/tests/com/google/caja/plugin/domita_test_untrusted.html
    trunk/tests/com/google/caja/plugin/jsunit.js
    trunk/third_party/js/jqueryjs/runtest/env.js

Log:
Issue 11256  http://codereview.appspot.com/11256
DOMita resizing and scrolling

Implemented window.resize{To,By}, {window,Element}.scroll{To,By}
and fields {client,scroll,offset}{Top,Left,Width,Height}.

   * Defined operations for scrolling and resizing operations.
     All positioning against the window object actually affects
     the pseudo-body element.
   * Reimplemented the tame window as a regular class.
     This was necessary so that I could add getters and setters for
     scrollTop and the like.
   * New tests for resizing and scrolling functions, and positioning
     members.
   * Fixed testCustomEvents to run on IE.  Apparently I was running
     domita_test in my second instance of Firefox instead of IE last
     CL.
     Most of the event operations are now part of bridal, and
     I changed the way events are dispatched on IE since IE does
     not allow fireEvent to be called for custom events.  I took
     a page from Prototype, and use the ondataavailable event.
   * Modified JSUnit so that if the location has a query parameter
     ?test.filter=foo, only tests matching the value as a regular
     expression will be run.
   * Added NOBR to the HTML extensions schema.  It's in HTML5 and is
     widely supported by browsers though deprecated.  The CSS
     equivalent whitespace:no-break does not work on all browsers so
     NOBR is useful.

[email protected]


Modified: trunk/src/com/google/caja/lang/html/HtmlSchema.java
==============================================================================
--- trunk/src/com/google/caja/lang/html/HtmlSchema.java (original)
+++ trunk/src/com/google/caja/lang/html/HtmlSchema.java Mon Jan 12 17:41:06  
2009
@@ -61,9 +61,11 @@
      if (defaultSchema == null) {
        SimpleMessageQueue cacheMq = new SimpleMessageQueue();
        URI elSrc = URI.create(
-              "resource:///com/google/caja/lang/html/html4-elements.json");
+              "resource:///com/google/caja/lang/html/"
+              + "html4-elements-extensions.json");
        URI attrSrc = URI.create(
-              
"resource:///com/google/caja/lang/html/html4-attributes-extensions.json");
+              "resource:///com/google/caja/lang/html/"
+              + "html4-attributes-extensions.json");
        try {
          defaultSchema = Pair.pair(
              new HtmlSchema(

Added:  
trunk/src/com/google/caja/lang/html/html4-elements-extensions-defs.json
==============================================================================
--- (empty file)
+++ trunk/src/com/google/caja/lang/html/html4-elements-extensions-defs.json     
 
Mon Jan 12 17:41:06 2009
@@ -0,0 +1,10 @@
+{
+  "types": [
+      { "key":         "NOBR",
+        "empty":       false,
+        "optionalEnd": false,
+        "deprecated":  false,
+        "description": "present in HTML5, but not in HTML4 though widely  
used"
+      }
+  ]
+}

Added:  
trunk/src/com/google/caja/lang/html/html4-elements-extensions-whitelist.json
==============================================================================
--- (empty file)
+++  
trunk/src/com/google/caja/lang/html/html4-elements-extensions-whitelist.json    
 
Mon Jan 12 17:41:06 2009
@@ -0,0 +1,5 @@
+{
+  "allowed": [
+    "NOBR"
+  ]
+}

Added: trunk/src/com/google/caja/lang/html/html4-elements-extensions.json
==============================================================================
--- (empty file)
+++ trunk/src/com/google/caja/lang/html/html4-elements-extensions.json  Mon  
Jan 12 17:41:06 2009
@@ -0,0 +1,8 @@
+{
+  "description": "HTML4 plus some other stuff",
+  "inherits": [
+      "html4-elements.json",
+      "html4-elements-extensions-defs.json"
+      "html4-elements-extensions-whitelist.json"
+      ]
+}

Modified: trunk/src/com/google/caja/lang/html/html4-elements-whitelist.json
==============================================================================
--- trunk/src/com/google/caja/lang/html/html4-elements-whitelist.json    
(original)
+++ trunk/src/com/google/caja/lang/html/html4-elements-whitelist.json   Mon  
Jan 12 17:41:06 2009
@@ -119,5 +119,5 @@
          "reason": "allows global definition of styles." },
        { "key": "TITLE",
          "reason": "a global level tag" },
-      ],
+      ]
  }

Modified: trunk/src/com/google/caja/plugin/bridal.js
==============================================================================
--- trunk/src/com/google/caja/plugin/bridal.js  (original)
+++ trunk/src/com/google/caja/plugin/bridal.js  Mon Jan 12 17:41:06 2009
@@ -41,6 +41,66 @@
    // Public section
     
////////////////////////////////////////////////////////////////////////////

+  var CUSTOM_EVENT_TYPE_SUFFIX = '_custom___';
+  function tameEventType(type, opt_isCustom) {
+    type = String(type);
+    if (endsWith__.test(type)) {
+      throw new Error('Invalid event type ' + type);
+    }
+    if (opt_isCustom
+        || html4.atype.SCRIPT !== html4.ATTRIBS['*:on' + type]) {
+      type = type + CUSTOM_EVENT_TYPE_SUFFIX;
+    }
+    return type;
+  }
+
+  function untameEventType(type) {
+    var suffix = CUSTOM_EVENT_TYPE_SUFFIX;
+    var tlen = type.length, slen = suffix.length;
+    var end = tlen - slen;
+    if (end >= 0 && suffix === type.substring(end)) {
+      type = type.substring(0, end);
+    }
+    return type;
+  }
+
+  function initEvent(event, type, bubbles, cancelable) {
+    type = tameEventType(type, true);
+    bubbles = Boolean(bubbles);
+    cancelable = Boolean(cancelable);
+
+    if (event.initEvent) {  // Non-IE
+      event.initEvent(type, bubbles, cancelable);
+    } else if (bubbles && cancelable) {  // IE
+      event.eventType___ = type;
+    } else {
+      // TODO(mikesamuel): can bubbling and cancelable on events be  
simulated
+      // via http://msdn.microsoft.com/en-us/library/ms533545(VS.85).aspx
+      throw new Error(
+          'Browser does not support non-bubbling/uncanceleable events');
+    }
+  }
+
+  function dispatchEvent(element, event) {
+    // TODO(mikesamuel): when we change event dispatching to happen
+    // asynchronously, we should exempt custom events since those
+    // need to return a useful value, and there may be code bracketing
+    // them which could observe asynchronous dispatch.
+
+    // "The return value of dispatchEvent indicates whether any of
+    //  the listeners which handled the event called
+    //  preventDefault. If preventDefault was called the value is
+    //  false, else the value is true."
+    if (element.dispatchEvent) {
+      return Boolean(element.dispatchEvent(event));
+    } else {
+      // Only dispatches custom events as when tameEventType(t) !== t.
+      element.fireEvent('ondataavailable', event);
+      return Boolean(event.returnValue);
+    }
+  }
+
+
    /**
     * Add an event listener function to an element.
     *
@@ -52,16 +112,38 @@
     * @param {string} type a string identifying the event type.
     * @param {boolean Element::function (event)} handler an event handler.
     * @param {boolean} useCapture whether the user wishes to initiate  
capture.
+   * @return {boolean Element::function (event)} the handler added.  May be
+   *     a wrapper around the input.
     */
    function addEventListener(element, type, handler, useCapture) {
+    type = String(type);
+    var tameType = tameEventType(type);
      if (features.attachEvent) {
        // TODO(ihab.awad): How do we emulate 'useCapture' here?
-      element.attachEvent('on' + type, handler);
+      if (type !== tameType) {
+        var wrapper = eventHandlerTypeFilter(handler, tameType);
+        element.attachEvent('ondataavailable', wrapper);
+        return wrapper;
+      } else {
+        element.attachEvent('on' + type, handler);
+        return handler;
+      }
      } else {
        // FF2 fails if useCapture not passed or is not a boolean.
-      element.addEventListener(type, handler, useCapture);
+      element.addEventListener(tameType, handler, useCapture);
+      return handler;
      }
    }
+  function eventHandlerTypeFilter(handler, tameType) {
+    // This does not need to check that handler is callable by untrusted  
code
+    // since the handler will invoke plugin_dispatchEvent which will do  
that
+    // check on the untrusted function reference.
+    return function (event) {
+      if (tameType === event.eventType___) {
+        return handler.call(this, event);
+      }
+    };
+  }

    /**
     * Remove an event listener function from an element.
@@ -76,11 +158,17 @@
     * @param useCapture whether the user wishes to initiate capture.
     */
    function removeEventListener(element, type, handler, useCapture) {
+    type = String(type);
+    var tameType = tameEventType(type);
      if (features.attachEvent) {
        // TODO(ihab.awad): How do we emulate 'useCapture' here?
-      element.detachEvent('on' + type, handler);
+      if (tameType !== type) {
+        element.detachEvent('ondataavailable', handler);
+      } else {
+        element.detachEvent('on' + type, handler);
+      }
      } else {
-      element.removeEventListener(type, handler, useCapture);
+      element.removeEventListener(tameType, handler, useCapture);
      }
    }

@@ -278,8 +366,11 @@
    return {
      addEventListener: addEventListener,
      removeEventListener: removeEventListener,
+    initEvent: initEvent,
+    dispatchEvent: dispatchEvent,
      cloneNode: cloneNode,
      createStylesheet: createStylesheet,
-    setAttribute: setAttribute
+    setAttribute: setAttribute,
+    untameEventType: untameEventType
    };
  })();

Modified: trunk/src/com/google/caja/plugin/domita.js
==============================================================================
--- trunk/src/com/google/caja/plugin/domita.js  (original)
+++ trunk/src/com/google/caja/plugin/domita.js  Mon Jan 12 17:41:06 2009
@@ -20,9 +20,6 @@
   * <a href="http://www.w3.org/TR/DOM-Level-2-HTML/ecma-script-binding.html";
   * >ECMAScript Language Bindings</a>.
   *
- * Requires cajita.js, css-defs.js, html4-defs.js, html-emitter.js,
- * html-sanitizer.js, unicode.js.
- *
   * Caveats:
   * - This is not a full implementation.
   * - Security Review is pending.
@@ -453,6 +450,138 @@
    }
    ___.frozenFunc(tameClearInterval);

+  function makeScrollable(element) {
+    var overflow;
+    if (element.currentStyle) {
+      overflow = element.currentStyle.overflow;
+    } else if (window.getComputedStyle) {
+      overflow = window.getComputedStyle(element, void 0).overflow;
+    }
+    switch (overflow && overflow.toLowerCase()) {
+      case 'visible':
+      case 'hidden':
+        element.style.overflow = 'auto';
+        break;
+    }
+  }
+
+  /**
+   * Moves the given pixel within the element's frame of reference as  
close to
+   * the top-left-most pixel of the element's viewport as possible without
+   * moving the viewport beyond the bounds of the content.
+   * @param {number} x x-coord of a pixel in the element's frame of  
reference.
+   * @param {number} y y-coord of a pixel in the element's frame of  
reference.
+   */
+  function tameScrollTo(element, x, y) {
+    if (x !== +x || y !== +y || x < 0 || y < 0) {
+      throw new Error('Cannot scroll to ' + x + ':' + typeof x + ','
+                      + y + ' : ' + typeof y);
+    }
+    element.scrollLeft = x;
+    element.scrollTop = y;
+  }
+
+  /**
+   * Moves the origin of the given element's view-port by the given offset.
+   * @param {number} dx a delta in pixels.
+   * @param {number} dy a delta in pixels.
+   */
+  function tameScrollBy(element, dx, dy) {
+    if (dx !== +dx || dy !== +dy) {
+      throw new Error('Cannot scroll by ' + dx + ':' + typeof dx + ', '
+                      + dy + ':' + typeof dy);
+    }
+    element.scrollLeft += dx;
+    element.scrollTop += dy;
+  }
+
+  function guessPixelsFromCss(cssStr) {
+    if (!cssStr) { return 0; }
+    var m = cssStr.match(/^([0-9]+)/);
+    return m ? +m[1] : 0;
+  }
+
+  function tameResizeTo(element, w, h) {
+    if (w !== +w || h !== +h) {
+      throw new Error('Cannot resize to ' + w + ':' + typeof w + ', '
+                      + h + ':' + typeof h);
+    }
+    element.style.width = w + 'px';
+    element.style.height = h + 'px';
+  }
+
+  function tameResizeBy(element, dw, dh) {
+    if (dw !== +dw || dh !== +dh) {
+      throw new Error('Cannot resize by ' + dw + ':' + typeof dw + ', '
+                      + dh + ':' + typeof dh);
+    }
+    if (!dw && !dh) { return; }
+
+    // scrollWidth is width + padding + border.
+    // offsetWidth is width + padding + border, but excluding the  
non-visible
+    // area.
+    // clientWidth iw width + padding, and like offsetWidth, clips to the
+    // viewport.
+    // margin does not count in any of these calculations.
+    //
+    // scrollWidth/offsetWidth
+    //   +------------+
+    //   |            |
+    //
+    // +----------------+
+    // |                | Margin-top
+    // | +------------+ |
+    // | |############| | Border-top
+    // | |#+--------+#| |
+    // | |#|        |#| | Padding-top
+    // | |#| +----+ |#| |
+    // | |#| |    | |#| | Height
+    // | |#| |    | |#| |
+    // | |#| +----+ |#| |
+    // | |#|        |#| |
+    // | |#+--------+#| |
+    // | |############| |
+    // | +------------+ |
+    // |                |
+    // +----------------+
+    //
+    //     |        |
+    //     +--------+
+    //     clientWidth (but excludes content outside viewport)
+
+    var style = element.currentStyle;
+    if (!style) {
+      style = window.getComputedStyle(element, void 0);
+    }
+
+    // We guess the padding since it's not always expressed in px on IE
+    var extraHeight = guessPixelsFromCss(style.paddingBottom)
+        + guessPixelsFromCss(style.paddingTop);
+    var extraWidth = guessPixelsFromCss(style.paddingLeft)
+        + guessPixelsFromCss(style.paddingRight);
+
+    var goalHeight = element.clientHeight + dh;
+    var goalWidth = element.clientWidth + dw;
+
+    var h = goalHeight - extraHeight;
+    var w = goalWidth - extraWidth;
+
+    if (dh) { element.style.height = Math.max(0, h) + 'px'; }
+    if (dw) { element.style.width = Math.max(0, w) + 'px'; }
+
+    // Correct if our guesses re padding and borders were wrong.
+    // We may still not be able to resize if e.g. the deltas would take
+    // a dimension negative.
+    if (dh && element.clientHeight !== goalHeight) {
+      var hError = element.clientHeight - goalHeight;
+      element.style.height = Math.max(0, h - hError) + 'px';
+    }
+    if (dw && element.clientWidth !== goalWidth) {
+      var wError = element.clientWidth - goalWidth;
+      element.style.width = Math.max(0, w - wError) + 'px';
+    }
+  }
+
    // See above for a description of this function.
    function attachDocumentStub(
        idSuffix, uriCallback, imports, pseudoBodyNode,  
optPseudoWindowLocation) {
@@ -903,7 +1032,6 @@
          return plugin_dispatchEvent___(
              thisNode, event, ___.getId(imports), listener);
        }
-      wrapper.originalListener___ = listener;
        return wrapper;
      }

@@ -912,34 +1040,21 @@
      var UNSAFE_TAGNAME = "Unsafe tag name.";
      var UNKNOWN_TAGNAME = "Unknown tag name.";

-    var CUSTOM_EVENT_TYPE_SUFFIX = ':custom';
-    function tameEventName(name, opt_isCustom) {
-      name = String(name);
-      if (endsWith__.test(name)) {
-        throw new Error('Invalid event name ' + name);
-      }
-      if (opt_isCustom
-          || html4.atype.SCRIPT !== html4.ATTRIBS['*:on' + name]) {
-        name = name + CUSTOM_EVENT_TYPE_SUFFIX;
-      }
-      return name;
-    }
-
      // Implementation of EventTarget::addEventListener
      function tameAddEventListener(name, listener, useCapture) {
        if (!this.editable___) { throw new Error(NOT_EDITABLE); }
        if (!this.wrappedListeners___) { this.wrappedListeners___ = []; }
-      name = tameEventName(name);
        useCapture = Boolean(useCapture);
        var wrappedListener = makeEventHandlerWrapper(this.node___,  
listener);
+      wrappedListener = bridal.addEventListener(
+          this.node___, name, wrappedListener, useCapture);
+      wrappedListener.originalListener___ = listener;
        this.wrappedListeners___.push(wrappedListener);
-      bridal.addEventListener(this.node___, name, wrappedListener,  
useCapture);
      }

      // Implementation of EventTarget::removeEventListener
      function tameRemoveEventListener(name, listener, useCapture) {
        if (!this.editable___) { throw new Error(NOT_EDITABLE); }
-      name = tameEventName(name);
        if (!this.wrappedListeners___) { return; }
        var wrappedListener;
        for (var i = this.wrappedListeners___.length; --i >= 0;) {
@@ -951,7 +1066,7 @@
        }
        if (!wrappedListener) { return; }
        bridal.removeEventListener(
-           this.node___, name, wrappedListener, useCapture);
+          this.node___, name, wrappedListener, useCapture);
      }

      // A map of tamed node classes, keyed by DOM Level 2 standard name,  
which
@@ -1203,16 +1318,7 @@
      // "The EventTarget interface is implemented by all Nodes"
      TameBackedNode.prototype.dispatchEvent = function dispatchEvent(evt) {
        cajita.guard(tameEventTrademark, evt);
-      // TODO(mikesamuel): when we change event dispatching to happen
-      // asynchronously, we should exempt custom events since those
-      // need to return a useful value, and there may be code bracketing
-      // them which could observe asynchronous dispatch.
-
-      // "The return value of dispatchEvent indicates whether any of
-      //  the listeners which handled the event called
-      //  preventDefault. If preventDefault was called the value is
-      //  false, else the value is true."
-      return Boolean(this.node___.dispatchEvent(evt.event___));
+      bridal.dispatchEvent(this.node___, evt.event___);
      };
      ___.ctor(TameBackedNode, TameNode, 'TameBackedNode');
      ___.all2(___.grantTypedGeneric, TameBackedNode.prototype,  
tameNodeMembers);
@@ -1505,14 +1611,13 @@
        classUtils.exportFields(
            this,
            ['className', 'id', 'innerHTML', 'tagName', 'style',
-            'offsetLeft', 'offsetTop', 'offsetWidth', 'offsetHeight',
-            'offsetParent',
-            'scrollLeft',
-            'scrollTop',
-            'scrollWidth',
-            'scrollHeight',
-            'title',
-            'dir']);
+           'clientWidth', 'clientHeight',
+           'offsetLeft', 'offsetTop', 'offsetWidth', 'offsetHeight',
+           'offsetParent',
+           'scrollLeft', 'scrollTop',
+           'scrollWidth', 'scrollHeight',
+           'title',
+           'dir']);
      }
      classUtils.extend(TameElement, TameBackedNode);
      nodeClasses.Element = nodeClasses.HTMLElement = TameElement;
@@ -1693,6 +1798,12 @@
        }
      };

+    TameElement.prototype.getClientWidth = function () {
+      return this.node___.clientWidth;
+    };
+    TameElement.prototype.getClientHeight = function () {
+      return this.node___.clientHeight;
+    };
      TameElement.prototype.getOffsetLeft = function () {
        return this.node___.offsetLeft;
      };
@@ -1714,6 +1825,16 @@
      TameElement.prototype.getScrollTop = function () {
        return this.node___.scrollTop;
      };
+    TameElement.prototype.setScrollLeft = function (x) {
+      if (!this.editable___) { throw new Error(NOT_EDITABLE); }
+      this.node___.scrollLeft = +x;
+      return x;
+    };
+    TameElement.prototype.setScrollTop = function (y) {
+      if (!this.editable___) { throw new Error(NOT_EDITABLE); }
+      this.node___.scrollTop = +y;
+      return y;
+    };
      TameElement.prototype.getScrollWidth = function () {
        return this.node___.scrollWidth;
      };
@@ -1734,8 +1855,7 @@
          'hasAttribute',
          'getClassName', 'setClassName', 'getId', 'setId',
          'getInnerHTML', 'setInnerHTML', 'updateStyle', 'getStyle', 'setStyle',
-        'getTagName', 'getOffsetLeft', 'getOffsetTop', 'getOffsetWidth',
-        'getOffsetHeight']);
+        'getTagName']);

      // Register set handlers for onclick, onmouseover, etc.
      (function () {
@@ -2187,14 +2307,7 @@
      }
      nodeClasses.Event = TameEvent;
      TameEvent.prototype.getType = function () {
-      var type = String(this.event___.type);
-      var suffix = CUSTOM_EVENT_TYPE_SUFFIX;
-      var tlen = type.length, slen = suffix.length;
-      var end = tlen - slen;
-      if (end >= 0) {
-        type = type.substring(0, end);
-      }
-      return type;
+      return bridal.untameEventType(String(this.event___.type));
      };
      TameEvent.prototype.getTarget = function () {
        var event = this.event___;
@@ -2307,11 +2420,7 @@
      classUtils.extend(TameCustomHTMLEvent, TameEvent);
      TameCustomHTMLEvent.prototype.initEvent
          = function (type, bubbles, cancelable) {
-      type = tameEventName(type, true);
-      bubbles = Boolean(bubbles);
-      cancelable = Boolean(cancelable);
-
-      this.event___.initEvent(type, bubbles, cancelable);
+      bridal.initEvent(this.event___, type, bubbles, cancelable);
      };
      TameCustomHTMLEvent.prototype.handleRead___ = function (name) {
        name = String(name);
@@ -2815,11 +2924,13 @@
          'first-line': true
      };

-    // See  
http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#window
  
for the full API.
-    // TODO(mikesamuel): This implements only the parts needed by  
prototype.
-    // The rest can be added on an as-needed basis as long as DOMado rules  
are
-    // obeyed.
-    var tameWindow = {
+    /**
+     * See  
http://www.whatwg.org/specs/web-apps/current-work/multipage/browsers.html#window
  
for the full API.
+     */
+    function TameWindow() {
+      this.properties___ = {};
+    }
+    cajita.forOwnKeys({
        document: imports.document,
        location: tameLocation,
        navigator: tameNavigator,
@@ -2827,16 +2938,27 @@
        setInterval: tameSetInterval,
        clearTimeout: tameClearTimeout,
        clearInterval: tameClearInterval,
+      scrollBy: ___.frozenFunc(
+          function (dx, dy) {
+            // The window is always auto scrollable, so make the apparent  
window
+            // body scrollable if the gadget tries to scroll it.
+            if (dx || dy) { makeScrollable(tameDocument.body___); }
+            tameScrollBy(tameDocument.body___, dx, dy);
+          }),
        scrollTo: ___.frozenFunc(
            function (x, y) {
-            // Per DOMado rules, the window can only be scrolled in  
response to
-            // a user action.  Hence the isProcessingEvent___ check.
-            if ('number' === typeof x
-                && 'number' === typeof y
-                && !isNaN(x - y)
-                && imports.isProcessingEvent___) {
-              window.scrollTo(x, y);
-            }
+            // The window is always auto scrollable, so make the apparent  
window
+            // body scrollable if the gadget tries to scroll it.
+            makeScrollable(tameDocument.body___);
+            tameScrollTo(tameDocument.body___, x, y);
+          }),
+      resizeTo: ___.frozenFunc(
+          function (w, h) {
+            tameResizeTo(tameDocument.body___, w, h);
+          }),
+      resizeBy: ___.frozenFunc(
+          function (dw, dh) {
+            tameResizeBy(tameDocument.body___, dw, dh);
            }),
        addEventListener: ___.frozenFunc(
            function (name, listener, useCapture) {
@@ -2883,10 +3005,137 @@
        // event: a global on IE.  We always define it in scopes that can  
handle
        //        events.
        // opera: defined only on Opera.
-      // pageXOffset, pageYOffset: used if document.body.scroll{Left,Top}
-      //        unavailable
+    }, ___.func(function (propertyName, value) {
+      TameWindow.prototype[propertyName] = value;
+      ___.grantRead(TameWindow.prototype, propertyName);
+    }));
+    TameWindow.prototype.handleRead___ = function (name) {
+      name = String(name);
+      if (endsWith__.test(name)) { return void 0; }
+      var handlerName = name + '_getter___';
+      if (this[handlerName]) {
+        return this[handlerName]();
+      }
+      handlerName = handlerName.toLowerCase();
+      if (this[handlerName]) {
+        return this[handlerName]();
+      }
+      if (___.hasOwnProp(this.properties___, name)) {
+        return this.properties___[name];
+      } else {
+        return void 0;
+      }
+    };
+    TameWindow.prototype.handleSet___ = function (name, val) {
+      name = String(name);
+      if (endsWith__.test(name)) { throw new Error(INVALID_SUFFIX); }
+      var handlerName = name + '_setter___';
+      if (this[handlerName]) {
+        return this[handlerName](val);
+      }
+      handlerName = handlerName.toLowerCase();
+      if (this[handlerName]) {
+        return this[handlerName](val);
+      }
+      if (!this.properties___) {
+        this.properties___ = {};
+      }
+      this[name + '_canEnum___'] = true;
+      return this.properties___[name] = val;
+    };
+    TameWindow.prototype.handleDelete___ = function (name) {
+      name = String(name);
+      if (endsWith__.test(name)) { throw new Error(INVALID_SUFFIX); }
+      var handlerName = name + '_deleter___';
+      if (this[handlerName]) {
+        return this[handlerName]();
+      }
+      handlerName = handlerName.toLowerCase();
+      if (this[handlerName]) {
+        return this[handlerName]();
+      }
+      if (this.properties___) {
+        return (
+            delete this.properties___[name]
+            && delete this[name + '_canEnum___']);
+      } else {
+        return true;
+      }
+    };
+    TameWindow.prototype.handleEnum___ = function (ownFlag) {
+      // TODO(metaweta): Add code to list all the other handled stuff we  
know
+      // about.
+      if (this.properties___) {
+        return cajita.allKeys(this.properties___);
+      }
+      return [];
      };

+    var tameWindow = new TameWindow();
+
+    function propertyOnlyHasGetter(_) {
+      throw new TypeError('setting a property that only has a getter');
+    }
+    cajita.forOwnKeys({
+      // We define all the window positional properties relative to
+      // the fake body element to maintain the illusion that the fake
+      // document is completely defined by the nodes under the fake body.
+      clientLeft: {
+        get: function () { return tameDocument.body___.clientLeft; }
+      },
+      clientTop: {
+        get: function () { return tameDocument.body___.clientTop; }
+      },
+      clientHeight: {
+        get: function () { return tameDocument.body___.clientHeight; }
+      },
+      clientWidth: {
+        get: function () { return tameDocument.body___.clientWidth; }
+      },
+      offsetLeft: {
+        get: function () { return tameDocument.body___.offsetLeft; }
+      },
+      offsetTop: {
+        get: function () { return tameDocument.body___.offsetTop; }
+      },
+      offsetHeight: {
+        get: function () { return tameDocument.body___.offsetHeight; }
+      },
+      offsetWidth: {
+        get: function () { return tameDocument.body___.offsetWidth; }
+      },
+      // page{X,Y}Offset appear only as members of window, not on all  
elements
+      // but  
http://www.howtocreate.co.uk/tutorials/javascript/browserwindow
+      // says that they are identical to the scrollTop/Left on all  
browsers but
+      // old versions of Safari.
+      pageXOffset: {
+        get: function () { return tameDocument.body___.scrollLeft; }
+      },
+      pageYOffset: {
+        get: function () { return tameDocument.body___.scrollTop; }
+      },
+      scrollLeft: {
+        get: function () { return tameDocument.body___.scrollLeft; },
+        set: function (x) { tameDocument.body___.scrollLeft = +x; return  
x; }
+      },
+      scrollTop: {
+        get: function () { return tameDocument.body___.scrollTop; },
+        set: function (y) { tameDocument.body___.scrollTop = +y; return y;  
}
+      },
+      scrollHeight: {
+        get: function () { return tameDocument.body___.scrollHeight; }
+      },
+      scrollWidth: {
+        get: function () { return tameDocument.body___.scrollWidth; }
+      }
+    }, ___.func(function (propertyName, def) {
+      // TODO(mikesamuel): define on prototype.
+      ___.useGetHandler(tameWindow, propertyName, def.get);
+      ___.useSetHandler(tameWindow, propertyName,
+                        def.set || propertyOnlyHasGetter);
+    }));
+
+
      // Attach reflexive properties to 'window' object
      tameWindow.top = tameWindow.self = tameWindow.opener =  
tameWindow.parent
          = tameWindow.window = tameWindow;
@@ -2962,17 +3211,15 @@

      var outers = imports.outers;
      if (___.isJSONContainer(outers)) {
-      // For Valija, attach window object members to outers instead so that
-      // the members of window show up as global variables as well.
-      for (var k in tameWindow) {
-        if (!___.hasOwnProp(outers, k) && ___.canEnumPub(tameWindow, k)) {
-          var v = tameWindow[k];
-          outers[k] = v === tameWindow ? outers : v;
+      // For Valija, attach use the window object as outers.
+      cajita.forOwnKeys(outers, ___.func(function(k, v) {
+        if (!(k in tameWindow)) {
+          tameWindow[k] = v;
+          ___.grantRead(tameWindow, k);
          }
-      }
-      outers.window = outers;
+      }));
+      imports.outers = window;
      } else {
-      cajita.freeze(tameWindow);
        imports.window = tameWindow;
      }
    }

Modified: trunk/tests/com/google/caja/plugin/domita_test.html
==============================================================================
--- trunk/tests/com/google/caja/plugin/domita_test.html (original)
+++ trunk/tests/com/google/caja/plugin/domita_test.html Mon Jan 12 17:41:06  
2009
@@ -41,7 +41,7 @@
      <div id="console-results"></div>

      <div id="untrusted_content" class="xyz___"
-     title="<Untrusted Content Title>">
+     title="<Untrusted Content Title>" style="width:1200px; height: 600px">
        <!-- inaccessible to document.getElementById -->
        <div id="foo"></div>

@@ -149,6 +149,9 @@
          }),
          getAttribute: ___.frozenFunc(function (tameNode, name) {
            return tameNode.node___.getAttribute(name);
+        }),
+        getBodyNode: ___.frozenFunc(function () {
+          return testImports.tameNode___(testDomContainer);
          }),
          getComputedStyle: ___.frozenFunc(function (tameNode, styleProp) {
            var node = tameNode.node___;

Modified: trunk/tests/com/google/caja/plugin/domita_test_untrusted.html
==============================================================================
--- trunk/tests/com/google/caja/plugin/domita_test_untrusted.html       
(original)
+++ trunk/tests/com/google/caja/plugin/domita_test_untrusted.html       Mon Jan 
 
12 17:41:06 2009
@@ -217,10 +217,27 @@
    I will have a custom attribute
  </p>

-<p class="testcontainer" id="test-custom-events">&nbsp;</p>
+<p class="testcontainer" id="test-custom-events">Custom Events<br></p>

  <p class="testcontainer" id="test-factories-not-bypassable">&nbsp;</p>

+<p class="testcontainer" id="test-scrolling"><nobr
+>A really  
looooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooong
+line that will force the viewport to have a horizontal scroll bar so that  
we
+can test window.scrollBy with a positive x value with a visible effect.
+</nobr><br></p>
+
+<p class="testcontainer" id="test-resizing">Resizing</p>
+
+<div class="testcontainer" id="test-size-properties"
+ style="
+    width: 100px;
+    height: 50px;
+    border: 2px solid black;
+    padding: 3px;
+    margin: 7px"
+ ></div>
+
  <p class="testcontainer" id="test-document-element">Test Document  
Element</p>

  <p class="testcontainer" id="test-document-body-appendChild"
@@ -1543,7 +1560,7 @@
      fired = true;
    }

-  var eventTarget = document.createElement('DIV');
+  var eventTarget = document.getElementById('test-custom-events');
    eventTarget.addEventListener('howdy', myHandler, true);

    var event = document.createEvent('HTMLEvents');
@@ -1568,6 +1585,85 @@
    pass('test-factories-not-bypassable');
  });

+jsunitRegister('testScrolling',
+               function testScrolling() {
+  assertEquals('0,0', String([window.scrollLeft, window.scrollTop]));
+  assertEquals(
+      'visible',
+       
directAccess.getComputedStyle(directAccess.getBodyNode(), 'overflow'));
+
+  window.scrollBy(0, 0);
+  assertEquals('0,0', String([window.scrollLeft, window.scrollTop]));
+  assertEquals(
+      'visible',
+       
directAccess.getComputedStyle(directAccess.getBodyNode(), 'overflow'));
+
+  window.scrollTo(0, 10);
+  assertEquals(
+      'auto',
+       
directAccess.getComputedStyle(directAccess.getBodyNode(), 'overflow'));
+  assertEquals('0,10', String([window.scrollLeft, window.scrollTop]));
+
+  window.scrollBy(10, -5);
+  assertEquals(
+      'auto',
+       
directAccess.getComputedStyle(directAccess.getBodyNode(), 'overflow'));
+  assertEquals('10,5', String([window.scrollLeft, window.scrollTop]));
+
+  window.scrollTo(0, 0);
+  assertEquals(
+      'auto',
+       
directAccess.getComputedStyle(directAccess.getBodyNode(), 'overflow'));
+  assertEquals('0,0', String([window.scrollLeft, window.scrollTop]));
+
+  pass('test-scrolling');
+});
+
+jsunitRegister('testResizing',
+               function testResizing() {
+  function windowDims() {
+    return String([window.clientWidth, window.clientHeight]);
+  }
+
+  function windowStyleWidth() {
+    return  
directAccess.getComputedStyle(directAccess.getBodyNode(), 'width');
+  }
+
+  assertEquals('initial scrollable dimensions', '1200,600', windowDims());
+  assertEquals('initial width', '1200px', windowStyleWidth());
+
+  window.resizeBy(0, 0);
+  assertEquals('scrollable dimensions 1', '1200,600', windowDims());
+  assertEquals('width 1', '1200px', windowStyleWidth());
+
+  window.resizeBy(-100, 200);
+  assertEquals('scrollable dimensions 2', '1100,800', windowDims());
+  assertEquals('width 2', '1100px', windowStyleWidth());
+
+  window.resizeTo(1200, 800);
+  assertEquals('scrollable dimensions 3', '1200,800', windowDims());
+  assertEquals('width 3', '1200px', windowStyleWidth());
+
+  pass('test-resizing');
+});
+
+jsunitRegister('testSizeProperties',
+               function testSizeProperties() {
+  assertEquals('number', typeof window.pageXOffset);
+  assertEquals('number', typeof window.pageYOffset);
+  assertTrue('sign of pageXOffset', window.pageXOffset >= 0);
+  assertTrue('sign of pageYOffset', window.pageYOffset >= 0);
+
+  var el = document.getElementById('test-size-properties');
+  // includes 2*padding
+  assertEquals(106, el.clientWidth);
+  assertEquals(56, el.clientHeight);
+  // includes 2*padding + 2*border
+  assertEquals(110, el.offsetWidth);
+  assertEquals(60, el.offsetHeight);
+
+  pass('test-size-properties');
+});

  jsunitRegister('testDocumentElement',
                 function testDocumentElement() {

Modified: trunk/tests/com/google/caja/plugin/jsunit.js
==============================================================================
--- trunk/tests/com/google/caja/plugin/jsunit.js        (original)
+++ trunk/tests/com/google/caja/plugin/jsunit.js        Mon Jan 12 17:41:06 2009
@@ -41,10 +41,34 @@
    }
    testNames.sort();

+  var queryParams = (function () {
+    var queryParams = {};
+    var parts = location.search.match(/[^&?]+/g) || [];
+    for (var i = 0, n = parts.length; i < n; ++i) {
+      var part = parts[i];
+      var eq = part.indexOf('=');
+      var key = decodeURIComponent(eq < 0 ? part : part.substring(0, eq));
+      var value = decodeURIComponent(eq >= 0 ? part.substring(eq +  
1) : '');
+      var values = queryParams.hasOwnProperty(key)
+          ? queryParams[key]
+          : (queryParams[key] = []);
+      values.push(value);
+    }
+    return queryParams;
+  })();
+
+  // If loaded with ?test.filter=Foo, should run testFoo and testFooBar,  
but not
+  // testBar.
+  var testFilter = null;
+  if (queryParams['test.filter']) {
+    testFilter = new RegExp(queryParams['test.filter'][0]);
+  }
+
    var firstFailure = null;
    var nFailures = 0;
    for (var i = 0; i < testNames.length; ++i) {
      var testName = testNames[i];
+    if (testFilter && !testFilter.test(testName)) { continue; }
      var groupLogMessages = (typeof console !== 'undefined'
                              && 'group' in console);  // Not on Safari.
      if (groupLogMessages) {

Modified: trunk/third_party/js/jqueryjs/runtest/env.js
==============================================================================
--- trunk/third_party/js/jqueryjs/runtest/env.js        (original)
+++ trunk/third_party/js/jqueryjs/runtest/env.js        Mon Jan 12 17:41:06 2009
@@ -35,13 +35,32 @@

    window.__defineGetter__("location", function(url){
      return {
-      get protocol(){
+      get hash() {
+        return curLocation.getRef() || '';
+      },
+      get host() {
+        var hostname = this.hostname, port = this.port;
+        return hostname + (port ? ':' + port : '');
+      },
+      get hostname() {
+        return curLocation.getHost() || '';
+      },
+      get href() {
+        return curLocation.toString() || '';
+      },
+      get pathname() {
+        return curLocation.getPath() || '';
+      },
+      get port() {
+        return curLocation.getPort() || 0;
+      },
+      get protocol() {
          return curLocation.getProtocol() + ":";
        },
-      get href(){
-        return curLocation.toString();
+      get search() {
+        return curLocation.getQuery() || '';
        },
-      toString: function(){
+      toString: function () {
          return this.href;
        }
      };

Reply via email to