You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cordova.apache.org by pm...@apache.org on 2012/02/15 18:42:37 UTC
[38/51] [partial] Apache-ization, port to node.js
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.build/vendor/webkit/WebCore/inspector/front-end/utilities.js
----------------------------------------------------------------------
diff --git a/weinre.build/vendor/webkit/WebCore/inspector/front-end/utilities.js b/weinre.build/vendor/webkit/WebCore/inspector/front-end/utilities.js
new file mode 100644
index 0000000..64670e1
--- /dev/null
+++ b/weinre.build/vendor/webkit/WebCore/inspector/front-end/utilities.js
@@ -0,0 +1,1087 @@
+/*
+ * Copyright (C) 2007 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in the
+ * documentation and/or other materials provided with the distribution.
+ * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ * its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Contains diff method based on Javascript Diff Algorithm By John Resig
+ * http://ejohn.org/files/jsdiff.js (released under the MIT license).
+ */
+
+Function.prototype.bind = function(thisObject)
+{
+ var func = this;
+ var args = Array.prototype.slice.call(arguments, 1);
+ function bound()
+ {
+ return func.apply(thisObject, args.concat(Array.prototype.slice.call(arguments, 0)));
+ }
+ bound.toString = function() {
+ return "bound: " + func;
+ };
+ return bound;
+}
+
+Node.prototype.rangeOfWord = function(offset, stopCharacters, stayWithinNode, direction)
+{
+ var startNode;
+ var startOffset = 0;
+ var endNode;
+ var endOffset = 0;
+
+ if (!stayWithinNode)
+ stayWithinNode = this;
+
+ if (!direction || direction === "backward" || direction === "both") {
+ var node = this;
+ while (node) {
+ if (node === stayWithinNode) {
+ if (!startNode)
+ startNode = stayWithinNode;
+ break;
+ }
+
+ if (node.nodeType === Node.TEXT_NODE) {
+ var start = (node === this ? (offset - 1) : (node.nodeValue.length - 1));
+ for (var i = start; i >= 0; --i) {
+ if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
+ startNode = node;
+ startOffset = i + 1;
+ break;
+ }
+ }
+ }
+
+ if (startNode)
+ break;
+
+ node = node.traversePreviousNode(stayWithinNode);
+ }
+
+ if (!startNode) {
+ startNode = stayWithinNode;
+ startOffset = 0;
+ }
+ } else {
+ startNode = this;
+ startOffset = offset;
+ }
+
+ if (!direction || direction === "forward" || direction === "both") {
+ node = this;
+ while (node) {
+ if (node === stayWithinNode) {
+ if (!endNode)
+ endNode = stayWithinNode;
+ break;
+ }
+
+ if (node.nodeType === Node.TEXT_NODE) {
+ var start = (node === this ? offset : 0);
+ for (var i = start; i < node.nodeValue.length; ++i) {
+ if (stopCharacters.indexOf(node.nodeValue[i]) !== -1) {
+ endNode = node;
+ endOffset = i;
+ break;
+ }
+ }
+ }
+
+ if (endNode)
+ break;
+
+ node = node.traverseNextNode(stayWithinNode);
+ }
+
+ if (!endNode) {
+ endNode = stayWithinNode;
+ endOffset = stayWithinNode.nodeType === Node.TEXT_NODE ? stayWithinNode.nodeValue.length : stayWithinNode.childNodes.length;
+ }
+ } else {
+ endNode = this;
+ endOffset = offset;
+ }
+
+ var result = this.ownerDocument.createRange();
+ result.setStart(startNode, startOffset);
+ result.setEnd(endNode, endOffset);
+
+ return result;
+}
+
+Node.prototype.traverseNextTextNode = function(stayWithin)
+{
+ var node = this.traverseNextNode(stayWithin);
+ if (!node)
+ return;
+
+ while (node && node.nodeType !== Node.TEXT_NODE)
+ node = node.traverseNextNode(stayWithin);
+
+ return node;
+}
+
+Node.prototype.rangeBoundaryForOffset = function(offset)
+{
+ var node = this.traverseNextTextNode(this);
+ while (node && offset > node.nodeValue.length) {
+ offset -= node.nodeValue.length;
+ node = node.traverseNextTextNode(this);
+ }
+ if (!node)
+ return { container: this, offset: 0 };
+ return { container: node, offset: offset };
+}
+
+Element.prototype.removeStyleClass = function(className)
+{
+ // Test for the simple case first.
+ if (this.className === className) {
+ this.className = "";
+ return;
+ }
+
+ var index = this.className.indexOf(className);
+ if (index === -1)
+ return;
+
+ this.className = this.className.split(" ").filter(function(s) {
+ return s && s !== className;
+ }).join(" ");
+}
+
+Element.prototype.removeMatchingStyleClasses = function(classNameRegex)
+{
+ var regex = new RegExp("(^|\\s+)" + classNameRegex + "($|\\s+)");
+ if (regex.test(this.className))
+ this.className = this.className.replace(regex, " ");
+}
+
+Element.prototype.addStyleClass = function(className)
+{
+ if (className && !this.hasStyleClass(className))
+ this.className += (this.className.length ? " " + className : className);
+}
+
+Element.prototype.hasStyleClass = function(className)
+{
+ if (!className)
+ return false;
+ // Test for the simple case
+ if (this.className === className)
+ return true;
+
+ var index = this.className.indexOf(className);
+ if (index === -1)
+ return false;
+ var toTest = " " + this.className + " ";
+ return toTest.indexOf(" " + className + " ", index) !== -1;
+}
+
+Element.prototype.positionAt = function(x, y)
+{
+ this.style.left = x + "px";
+ this.style.top = y + "px";
+}
+
+Element.prototype.pruneEmptyTextNodes = function()
+{
+ var sibling = this.firstChild;
+ while (sibling) {
+ var nextSibling = sibling.nextSibling;
+ if (sibling.nodeType === this.TEXT_NODE && sibling.nodeValue === "")
+ this.removeChild(sibling);
+ sibling = nextSibling;
+ }
+}
+
+Element.prototype.isScrolledToBottom = function()
+{
+ // This code works only for 0-width border
+ return this.scrollTop + this.clientHeight === this.scrollHeight;
+}
+
+Node.prototype.enclosingNodeOrSelfWithNodeNameInArray = function(nameArray)
+{
+ for (var node = this; node && node !== this.ownerDocument; node = node.parentNode)
+ for (var i = 0; i < nameArray.length; ++i)
+ if (node.nodeName.toLowerCase() === nameArray[i].toLowerCase())
+ return node;
+ return null;
+}
+
+Node.prototype.enclosingNodeOrSelfWithNodeName = function(nodeName)
+{
+ return this.enclosingNodeOrSelfWithNodeNameInArray([nodeName]);
+}
+
+Node.prototype.enclosingNodeOrSelfWithClass = function(className)
+{
+ for (var node = this; node && node !== this.ownerDocument; node = node.parentNode)
+ if (node.nodeType === Node.ELEMENT_NODE && node.hasStyleClass(className))
+ return node;
+ return null;
+}
+
+Node.prototype.enclosingNodeWithClass = function(className)
+{
+ if (!this.parentNode)
+ return null;
+ return this.parentNode.enclosingNodeOrSelfWithClass(className);
+}
+
+Element.prototype.query = function(query)
+{
+ return this.ownerDocument.evaluate(query, this, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue;
+}
+
+Element.prototype.removeChildren = function()
+{
+ if (this.firstChild)
+ this.textContent = "";
+}
+
+Element.prototype.isInsertionCaretInside = function()
+{
+ var selection = window.getSelection();
+ if (!selection.rangeCount || !selection.isCollapsed)
+ return false;
+ var selectionRange = selection.getRangeAt(0);
+ return selectionRange.startContainer === this || selectionRange.startContainer.isDescendant(this);
+}
+
+Element.prototype.createChild = function(elementName, className)
+{
+ var element = document.createElement(elementName);
+ if (className)
+ element.className = className;
+ this.appendChild(element);
+ return element;
+}
+
+Element.prototype.__defineGetter__("totalOffsetLeft", function()
+{
+ var total = 0;
+ for (var element = this; element; element = element.offsetParent)
+ total += element.offsetLeft + (this !== element ? element.clientLeft : 0);
+ return total;
+});
+
+Element.prototype.__defineGetter__("totalOffsetTop", function()
+{
+ var total = 0;
+ for (var element = this; element; element = element.offsetParent)
+ total += element.offsetTop + (this !== element ? element.clientTop : 0);
+ return total;
+});
+
+Element.prototype.offsetRelativeToWindow = function(targetWindow)
+{
+ var elementOffset = {x: 0, y: 0};
+ var curElement = this;
+ var curWindow = this.ownerDocument.defaultView;
+ while (curWindow && curElement) {
+ elementOffset.x += curElement.totalOffsetLeft;
+ elementOffset.y += curElement.totalOffsetTop;
+ if (curWindow === targetWindow)
+ break;
+
+ curElement = curWindow.frameElement;
+ curWindow = curWindow.parent;
+ }
+
+ return elementOffset;
+}
+
+KeyboardEvent.prototype.__defineGetter__("data", function()
+{
+ // Emulate "data" attribute from DOM 3 TextInput event.
+ // See http://www.w3.org/TR/DOM-Level-3-Events/#events-Events-TextEvent-data
+ switch (this.type) {
+ case "keypress":
+ if (!this.ctrlKey && !this.metaKey)
+ return String.fromCharCode(this.charCode);
+ else
+ return "";
+ case "keydown":
+ case "keyup":
+ if (!this.ctrlKey && !this.metaKey && !this.altKey)
+ return String.fromCharCode(this.which);
+ else
+ return "";
+ }
+});
+
+Text.prototype.select = function(start, end)
+{
+ start = start || 0;
+ end = end || this.textContent.length;
+
+ if (start < 0)
+ start = end + start;
+
+ var selection = window.getSelection();
+ selection.removeAllRanges();
+ var range = document.createRange();
+ range.setStart(this, start);
+ range.setEnd(this, end);
+ selection.addRange(range);
+ return this;
+}
+
+Element.prototype.__defineGetter__("selectionLeftOffset", function() {
+ // Calculate selection offset relative to the current element.
+
+ var selection = window.getSelection();
+ if (!selection.containsNode(this, true))
+ return null;
+
+ var leftOffset = selection.anchorOffset;
+ var node = selection.anchorNode;
+
+ while (node !== this) {
+ while (node.previousSibling) {
+ node = node.previousSibling;
+ leftOffset += node.textContent.length;
+ }
+ node = node.parentNode;
+ }
+
+ return leftOffset;
+});
+
+Node.prototype.isWhitespace = isNodeWhitespace;
+Node.prototype.displayName = nodeDisplayName;
+Node.prototype.isAncestor = function(node)
+{
+ return isAncestorNode(this, node);
+};
+Node.prototype.isDescendant = isDescendantNode;
+Node.prototype.traverseNextNode = traverseNextNode;
+Node.prototype.traversePreviousNode = traversePreviousNode;
+Node.prototype.onlyTextChild = onlyTextChild;
+
+String.prototype.hasSubstring = function(string, caseInsensitive)
+{
+ if (!caseInsensitive)
+ return this.indexOf(string) !== -1;
+ return this.match(new RegExp(string.escapeForRegExp(), "i"));
+}
+
+String.prototype.findAll = function(string)
+{
+ var matches = [];
+ var i = this.indexOf(string);
+ while (i !== -1) {
+ matches.push(i);
+ i = this.indexOf(string, i + string.length);
+ }
+ return matches;
+}
+
+String.prototype.lineEndings = function()
+{
+ if (!this._lineEndings) {
+ this._lineEndings = this.findAll("\n");
+ this._lineEndings.push(this.length);
+ }
+ return this._lineEndings;
+}
+
+String.prototype.asParsedURL = function()
+{
+ // RegExp groups:
+ // 1 - scheme
+ // 2 - hostname
+ // 3 - ?port
+ // 4 - ?path
+ // 5 - ?fragment
+ var match = this.match(/^([^:]+):\/\/([^\/:]*)(?::([\d]+))?(?:(\/[^#]*)(?:#(.*))?)?$/i);
+ if (!match)
+ return null;
+ var result = {};
+ result.scheme = match[1].toLowerCase();
+ result.host = match[2];
+ result.port = match[3];
+ result.path = match[4] || "/";
+ result.fragment = match[5];
+ return result;
+}
+
+String.prototype.escapeCharacters = function(chars)
+{
+ var foundChar = false;
+ for (var i = 0; i < chars.length; ++i) {
+ if (this.indexOf(chars.charAt(i)) !== -1) {
+ foundChar = true;
+ break;
+ }
+ }
+
+ if (!foundChar)
+ return this;
+
+ var result = "";
+ for (var i = 0; i < this.length; ++i) {
+ if (chars.indexOf(this.charAt(i)) !== -1)
+ result += "\\";
+ result += this.charAt(i);
+ }
+
+ return result;
+}
+
+String.prototype.escapeForRegExp = function()
+{
+ return this.escapeCharacters("^[]{}()\\.$*+?|");
+}
+
+String.prototype.escapeHTML = function()
+{
+ return this.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
+}
+
+String.prototype.collapseWhitespace = function()
+{
+ return this.replace(/[\s\xA0]+/g, " ");
+}
+
+String.prototype.trimURL = function(baseURLDomain)
+{
+ var result = this.replace(/^(https|http|file):\/\//i, "");
+ if (baseURLDomain)
+ result = result.replace(new RegExp("^" + baseURLDomain.escapeForRegExp(), "i"), "");
+ return result;
+}
+
+function isNodeWhitespace()
+{
+ if (!this || this.nodeType !== Node.TEXT_NODE)
+ return false;
+ if (!this.nodeValue.length)
+ return true;
+ return this.nodeValue.match(/^[\s\xA0]+$/);
+}
+
+function nodeDisplayName()
+{
+ if (!this)
+ return "";
+
+ switch (this.nodeType) {
+ case Node.DOCUMENT_NODE:
+ return "Document";
+
+ case Node.ELEMENT_NODE:
+ var name = "<" + this.nodeName.toLowerCase();
+
+ if (this.hasAttributes()) {
+ var value = this.getAttribute("id");
+ if (value)
+ name += " id=\"" + value + "\"";
+ value = this.getAttribute("class");
+ if (value)
+ name += " class=\"" + value + "\"";
+ if (this.nodeName.toLowerCase() === "a") {
+ value = this.getAttribute("name");
+ if (value)
+ name += " name=\"" + value + "\"";
+ value = this.getAttribute("href");
+ if (value)
+ name += " href=\"" + value + "\"";
+ } else if (this.nodeName.toLowerCase() === "img") {
+ value = this.getAttribute("src");
+ if (value)
+ name += " src=\"" + value + "\"";
+ } else if (this.nodeName.toLowerCase() === "iframe") {
+ value = this.getAttribute("src");
+ if (value)
+ name += " src=\"" + value + "\"";
+ } else if (this.nodeName.toLowerCase() === "input") {
+ value = this.getAttribute("name");
+ if (value)
+ name += " name=\"" + value + "\"";
+ value = this.getAttribute("type");
+ if (value)
+ name += " type=\"" + value + "\"";
+ } else if (this.nodeName.toLowerCase() === "form") {
+ value = this.getAttribute("action");
+ if (value)
+ name += " action=\"" + value + "\"";
+ }
+ }
+
+ return name + ">";
+
+ case Node.TEXT_NODE:
+ if (isNodeWhitespace.call(this))
+ return "(whitespace)";
+ return "\"" + this.nodeValue + "\"";
+
+ case Node.COMMENT_NODE:
+ return "<!--" + this.nodeValue + "-->";
+
+ case Node.DOCUMENT_TYPE_NODE:
+ var docType = "<!DOCTYPE " + this.nodeName;
+ if (this.publicId) {
+ docType += " PUBLIC \"" + this.publicId + "\"";
+ if (this.systemId)
+ docType += " \"" + this.systemId + "\"";
+ } else if (this.systemId)
+ docType += " SYSTEM \"" + this.systemId + "\"";
+ if (this.internalSubset)
+ docType += " [" + this.internalSubset + "]";
+ return docType + ">";
+ }
+
+ return this.nodeName.toLowerCase().collapseWhitespace();
+}
+
+function isAncestorNode(ancestor, node)
+{
+ if (!node || !ancestor)
+ return false;
+
+ var currentNode = node.parentNode;
+ while (currentNode) {
+ if (ancestor === currentNode)
+ return true;
+ currentNode = currentNode.parentNode;
+ }
+ return false;
+}
+
+function isDescendantNode(descendant)
+{
+ return isAncestorNode(descendant, this);
+}
+
+function traverseNextNode(stayWithin)
+{
+ if (!this)
+ return;
+
+ var node = this.firstChild;
+ if (node)
+ return node;
+
+ if (stayWithin && this === stayWithin)
+ return null;
+
+ node = this.nextSibling;
+ if (node)
+ return node;
+
+ node = this;
+ while (node && !node.nextSibling && (!stayWithin || !node.parentNode || node.parentNode !== stayWithin))
+ node = node.parentNode;
+ if (!node)
+ return null;
+
+ return node.nextSibling;
+}
+
+function traversePreviousNode(stayWithin)
+{
+ if (!this)
+ return;
+ if (stayWithin && this === stayWithin)
+ return null;
+ var node = this.previousSibling;
+ while (node && node.lastChild)
+ node = node.lastChild;
+ if (node)
+ return node;
+ return this.parentNode;
+}
+
+function onlyTextChild()
+{
+ if (!this)
+ return null;
+
+ var firstChild = this.firstChild;
+ if (!firstChild || firstChild.nodeType !== Node.TEXT_NODE)
+ return null;
+
+ var sibling = firstChild.nextSibling;
+ return sibling ? null : firstChild;
+}
+
+function appropriateSelectorForNode(node, justSelector)
+{
+ if (!node)
+ return "";
+
+ var lowerCaseName = node.localName || node.nodeName.toLowerCase();
+
+ var id = node.getAttribute("id");
+ if (id) {
+ var selector = "#" + id;
+ return (justSelector ? selector : lowerCaseName + selector);
+ }
+
+ var className = node.getAttribute("class");
+ if (className) {
+ var selector = "." + className.replace(/\s+/, ".");
+ return (justSelector ? selector : lowerCaseName + selector);
+ }
+
+ if (lowerCaseName === "input" && node.getAttribute("type"))
+ return lowerCaseName + "[type=\"" + node.getAttribute("type") + "\"]";
+
+ return lowerCaseName;
+}
+
+function getDocumentForNode(node)
+{
+ return node.nodeType == Node.DOCUMENT_NODE ? node : node.ownerDocument;
+}
+
+function parentNode(node)
+{
+ return node.parentNode;
+}
+
+Number.millisToString = function(ms, higherResolution)
+{
+ return Number.secondsToString(ms / 1000, higherResolution);
+}
+
+Number.secondsToString = function(seconds, higherResolution)
+{
+ if (seconds === 0)
+ return "0";
+
+ var ms = seconds * 1000;
+ if (higherResolution && ms < 1000)
+ return WebInspector.UIString("%.3fms", ms);
+ else if (ms < 1000)
+ return WebInspector.UIString("%.0fms", ms);
+
+ if (seconds < 60)
+ return WebInspector.UIString("%.2fs", seconds);
+
+ var minutes = seconds / 60;
+ if (minutes < 60)
+ return WebInspector.UIString("%.1fmin", minutes);
+
+ var hours = minutes / 60;
+ if (hours < 24)
+ return WebInspector.UIString("%.1fhrs", hours);
+
+ var days = hours / 24;
+ return WebInspector.UIString("%.1f days", days);
+}
+
+Number.bytesToString = function(bytes, higherResolution)
+{
+ if (typeof higherResolution === "undefined")
+ higherResolution = true;
+
+ if (bytes < 1024)
+ return WebInspector.UIString("%.0fB", bytes);
+
+ var kilobytes = bytes / 1024;
+ if (higherResolution && kilobytes < 1024)
+ return WebInspector.UIString("%.2fKB", kilobytes);
+ else if (kilobytes < 1024)
+ return WebInspector.UIString("%.0fKB", kilobytes);
+
+ var megabytes = kilobytes / 1024;
+ if (higherResolution)
+ return WebInspector.UIString("%.2fMB", megabytes);
+ else
+ return WebInspector.UIString("%.0fMB", megabytes);
+}
+
+Number.constrain = function(num, min, max)
+{
+ if (num < min)
+ num = min;
+ else if (num > max)
+ num = max;
+ return num;
+}
+
+HTMLTextAreaElement.prototype.moveCursorToEnd = function()
+{
+ var length = this.value.length;
+ this.setSelectionRange(length, length);
+}
+
+Object.defineProperty(Array.prototype, "remove", { value: function(value, onlyFirst)
+{
+ if (onlyFirst) {
+ var index = this.indexOf(value);
+ if (index !== -1)
+ this.splice(index, 1);
+ return;
+ }
+
+ var length = this.length;
+ for (var i = 0; i < length; ++i) {
+ if (this[i] === value)
+ this.splice(i, 1);
+ }
+}});
+
+Object.defineProperty(Array.prototype, "keySet", { value: function()
+{
+ var keys = {};
+ for (var i = 0; i < this.length; ++i)
+ keys[this[i]] = true;
+ return keys;
+}});
+
+Object.defineProperty(Array.prototype, "upperBound", { value: function(value)
+{
+ var first = 0;
+ var count = this.length;
+ while (count > 0) {
+ var step = count >> 1;
+ var middle = first + step;
+ if (value >= this[middle]) {
+ first = middle + 1;
+ count -= step + 1;
+ } else
+ count = step;
+ }
+ return first;
+}});
+
+Array.diff = function(left, right)
+{
+ var o = left;
+ var n = right;
+
+ var ns = {};
+ var os = {};
+
+ for (var i = 0; i < n.length; i++) {
+ if (ns[n[i]] == null)
+ ns[n[i]] = { rows: [], o: null };
+ ns[n[i]].rows.push(i);
+ }
+
+ for (var i = 0; i < o.length; i++) {
+ if (os[o[i]] == null)
+ os[o[i]] = { rows: [], n: null };
+ os[o[i]].rows.push(i);
+ }
+
+ for (var i in ns) {
+ if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) {
+ n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] };
+ o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] };
+ }
+ }
+
+ for (var i = 0; i < n.length - 1; i++) {
+ if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) {
+ n[i + 1] = { text: n[i + 1], row: n[i].row + 1 };
+ o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 };
+ }
+ }
+
+ for (var i = n.length - 1; i > 0; i--) {
+ if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null &&
+ n[i - 1] == o[n[i].row - 1]) {
+ n[i - 1] = { text: n[i - 1], row: n[i].row - 1 };
+ o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 };
+ }
+ }
+
+ return { left: o, right: n };
+}
+
+Array.convert = function(list)
+{
+ // Cast array-like object to an array.
+ return Array.prototype.slice.call(list);
+}
+
+function insertionIndexForObjectInListSortedByFunction(anObject, aList, aFunction)
+{
+ var first = 0;
+ var last = aList.length - 1;
+ var floor = Math.floor;
+ var mid, c;
+
+ while (first <= last) {
+ mid = floor((first + last) / 2);
+ c = aFunction(anObject, aList[mid]);
+
+ if (c > 0)
+ first = mid + 1;
+ else if (c < 0)
+ last = mid - 1;
+ else {
+ // Return the first occurance of an item in the list.
+ while (mid > 0 && aFunction(anObject, aList[mid - 1]) === 0)
+ mid--;
+ first = mid;
+ break;
+ }
+ }
+
+ return first;
+}
+
+String.sprintf = function(format)
+{
+ return String.vsprintf(format, Array.prototype.slice.call(arguments, 1));
+}
+
+String.tokenizeFormatString = function(format)
+{
+ var tokens = [];
+ var substitutionIndex = 0;
+
+ function addStringToken(str)
+ {
+ tokens.push({ type: "string", value: str });
+ }
+
+ function addSpecifierToken(specifier, precision, substitutionIndex)
+ {
+ tokens.push({ type: "specifier", specifier: specifier, precision: precision, substitutionIndex: substitutionIndex });
+ }
+
+ var index = 0;
+ for (var precentIndex = format.indexOf("%", index); precentIndex !== -1; precentIndex = format.indexOf("%", index)) {
+ addStringToken(format.substring(index, precentIndex));
+ index = precentIndex + 1;
+
+ if (format[index] === "%") {
+ addStringToken("%");
+ ++index;
+ continue;
+ }
+
+ if (!isNaN(format[index])) {
+ // The first character is a number, it might be a substitution index.
+ var number = parseInt(format.substring(index));
+ while (!isNaN(format[index]))
+ ++index;
+ // If the number is greater than zero and ends with a "$",
+ // then this is a substitution index.
+ if (number > 0 && format[index] === "$") {
+ substitutionIndex = (number - 1);
+ ++index;
+ }
+ }
+
+ var precision = -1;
+ if (format[index] === ".") {
+ // This is a precision specifier. If no digit follows the ".",
+ // then the precision should be zero.
+ ++index;
+ precision = parseInt(format.substring(index));
+ if (isNaN(precision))
+ precision = 0;
+ while (!isNaN(format[index]))
+ ++index;
+ }
+
+ addSpecifierToken(format[index], precision, substitutionIndex);
+
+ ++substitutionIndex;
+ ++index;
+ }
+
+ addStringToken(format.substring(index));
+
+ return tokens;
+}
+
+String.standardFormatters = {
+ d: function(substitution)
+ {
+ if (typeof substitution == "object" && WebInspector.RemoteObject.type(substitution) === "number")
+ substitution = substitution.description;
+ substitution = parseInt(substitution);
+ return !isNaN(substitution) ? substitution : 0;
+ },
+
+ f: function(substitution, token)
+ {
+ if (typeof substitution == "object" && WebInspector.RemoteObject.type(substitution) === "number")
+ substitution = substitution.description;
+ substitution = parseFloat(substitution);
+ if (substitution && token.precision > -1)
+ substitution = substitution.toFixed(token.precision);
+ return !isNaN(substitution) ? substitution : (token.precision > -1 ? Number(0).toFixed(token.precision) : 0);
+ },
+
+ s: function(substitution)
+ {
+ if (typeof substitution == "object" && WebInspector.RemoteObject.type(substitution) !== "null")
+ substitution = substitution.description;
+ return substitution;
+ },
+};
+
+String.vsprintf = function(format, substitutions)
+{
+ return String.format(format, substitutions, String.standardFormatters, "", function(a, b) { return a + b; }).formattedResult;
+}
+
+String.format = function(format, substitutions, formatters, initialValue, append)
+{
+ if (!format || !substitutions || !substitutions.length)
+ return { formattedResult: append(initialValue, format), unusedSubstitutions: substitutions };
+
+ function prettyFunctionName()
+ {
+ return "String.format(\"" + format + "\", \"" + substitutions.join("\", \"") + "\")";
+ }
+
+ function warn(msg)
+ {
+ console.warn(prettyFunctionName() + ": " + msg);
+ }
+
+ function error(msg)
+ {
+ console.error(prettyFunctionName() + ": " + msg);
+ }
+
+ var result = initialValue;
+ var tokens = String.tokenizeFormatString(format);
+ var usedSubstitutionIndexes = {};
+
+ for (var i = 0; i < tokens.length; ++i) {
+ var token = tokens[i];
+
+ if (token.type === "string") {
+ result = append(result, token.value);
+ continue;
+ }
+
+ if (token.type !== "specifier") {
+ error("Unknown token type \"" + token.type + "\" found.");
+ continue;
+ }
+
+ if (token.substitutionIndex >= substitutions.length) {
+ // If there are not enough substitutions for the current substitutionIndex
+ // just output the format specifier literally and move on.
+ error("not enough substitution arguments. Had " + substitutions.length + " but needed " + (token.substitutionIndex + 1) + ", so substitution was skipped.");
+ result = append(result, "%" + (token.precision > -1 ? token.precision : "") + token.specifier);
+ continue;
+ }
+
+ usedSubstitutionIndexes[token.substitutionIndex] = true;
+
+ if (!(token.specifier in formatters)) {
+ // Encountered an unsupported format character, treat as a string.
+ warn("unsupported format character \u201C" + token.specifier + "\u201D. Treating as a string.");
+ result = append(result, substitutions[token.substitutionIndex]);
+ continue;
+ }
+
+ result = append(result, formatters[token.specifier](substitutions[token.substitutionIndex], token));
+ }
+
+ var unusedSubstitutions = [];
+ for (var i = 0; i < substitutions.length; ++i) {
+ if (i in usedSubstitutionIndexes)
+ continue;
+ unusedSubstitutions.push(substitutions[i]);
+ }
+
+ return { formattedResult: result, unusedSubstitutions: unusedSubstitutions };
+}
+
+function isEnterKey(event) {
+ // Check if in IME.
+ return event.keyCode !== 229 && event.keyIdentifier === "Enter";
+}
+
+
+function highlightSearchResult(element, offset, length)
+{
+ var lineText = element.textContent;
+ var endOffset = offset + length;
+ var highlightNode = document.createElement("span");
+ highlightNode.className = "webkit-search-result";
+ highlightNode.textContent = lineText.substring(offset, endOffset);
+
+ var boundary = element.rangeBoundaryForOffset(offset);
+ var textNode = boundary.container;
+ var text = textNode.textContent;
+
+ if (boundary.offset + length < text.length) {
+ // Selection belong to a single split mode.
+ textNode.textContent = text.substring(boundary.offset + length);
+ textNode.parentElement.insertBefore(highlightNode, textNode);
+ var prefixNode = document.createTextNode(text.substring(0, boundary.offset));
+ textNode.parentElement.insertBefore(prefixNode, highlightNode);
+ return highlightNode;
+ }
+
+ var parentElement = textNode.parentElement;
+ var anchorElement = textNode.nextSibling;
+
+ length -= text.length - boundary.offset;
+ textNode.textContent = text.substring(0, boundary.offset);
+ textNode = textNode.traverseNextTextNode(element);
+
+ while (textNode) {
+ var text = textNode.textContent;
+ if (length < text.length) {
+ textNode.textContent = text.substring(length);
+ break;
+ }
+
+ length -= text.length;
+ textNode.textContent = "";
+ textNode = textNode.traverseNextTextNode(element);
+ }
+
+ parentElement.insertBefore(highlightNode, anchorElement);
+ return highlightNode;
+}
+
+function createSearchRegex(query)
+{
+ var regex = "";
+ for (var i = 0; i < query.length; ++i) {
+ var char = query.charAt(i);
+ if (char === "]")
+ char = "\\]";
+ regex += "[" + char + "]";
+ }
+ return new RegExp(regex, "i");
+}
+
+function offerFileForDownload(contents)
+{
+ var builder = new BlobBuilder();
+ builder.append(contents);
+ var blob = builder.getBlob("application/octet-stream");
+ var url = window.webkitURL.createObjectURL(blob);
+ window.open(url);
+}
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.build/weinre build.xml.launch
----------------------------------------------------------------------
diff --git a/weinre.build/weinre build.xml.launch b/weinre.build/weinre build.xml.launch
deleted file mode 100644
index 1f60c71..0000000
--- a/weinre.build/weinre build.xml.launch
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8" standalone="no"?>
-<launchConfiguration type="org.eclipse.ant.AntLaunchConfigurationType">
-<booleanAttribute key="org.eclipse.ant.ui.DEFAULT_VM_INSTALL" value="true"/>
-<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_PATHS"/>
-<listAttribute key="org.eclipse.debug.core.MAPPED_RESOURCE_TYPES"/>
-<listAttribute key="org.eclipse.debug.ui.favoriteGroups">
-<listEntry value="org.eclipse.ui.externaltools.launchGroup"/>
-</listAttribute>
-<stringAttribute key="org.eclipse.jdt.launching.CLASSPATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
-<stringAttribute key="org.eclipse.jdt.launching.JRE_CONTAINER" value="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.launching.macosx.MacOSXType/JVM 1.6.0 (MacOS X Default)"/>
-<stringAttribute key="org.eclipse.jdt.launching.MAIN_TYPE" value="org.eclipse.ant.internal.launching.remote.InternalAntRunner"/>
-<stringAttribute key="org.eclipse.jdt.launching.PROJECT_ATTR" value="weinre.build"/>
-<stringAttribute key="org.eclipse.jdt.launching.SOURCE_PATH_PROVIDER" value="org.eclipse.ant.ui.AntClasspathProvider"/>
-<stringAttribute key="org.eclipse.ui.externaltools.ATTR_LOCATION" value="${workspace_loc:/weinre.build/build.xml}"/>
-<stringAttribute key="org.eclipse.ui.externaltools.ATTR_WORKING_DIRECTORY" value="${workspace_loc:/weinre.build}"/>
-<stringAttribute key="process_factory_id" value="org.eclipse.ant.ui.remoteAntProcessFactory"/>
-</launchConfiguration>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/.classpath
----------------------------------------------------------------------
diff --git a/weinre.doc/.classpath b/weinre.doc/.classpath
deleted file mode 100644
index 8778ddd..0000000
--- a/weinre.doc/.classpath
+++ /dev/null
@@ -1,5 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/.project
----------------------------------------------------------------------
diff --git a/weinre.doc/.project b/weinre.doc/.project
deleted file mode 100644
index 2858af2..0000000
--- a/weinre.doc/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>weinre.doc</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/Building.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/Building.body.html b/weinre.doc/Building.body.html
index f5dc33b..2425714 100644
--- a/weinre.doc/Building.body.html
+++ b/weinre.doc/Building.body.html
@@ -18,9 +18,9 @@
-->
<p>The source repository for weinre is maintained at
-<a href="https://github.com/callback/callback-weinre">GitHub</a>.
+<a href="https://git-wip-us.apache.org/repos/asf?p=incubator-cordova-weinre.git">Apache</a>.
-<p>At development time, <span class="weinre">weinre</span> consists of 5
-directories / Eclipse projects. See the file <tt>README.md</tt> in the
-<tt>weinre.build</tt> directory for more instructions on
+<p>See the file
+<tt><a href="https://git-wip-us.apache.org/repos/asf?p=incubator-cordova-weinre.git;a=blob;f=README.md;hb=HEAD">README.md<a/></tt>
+in the top-most directory of the source distribution for more instructions on
how to perform a build.
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/ChangeLog.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/ChangeLog.body.html b/weinre.doc/ChangeLog.body.html
index 9759636..37bca7c 100644
--- a/weinre.doc/ChangeLog.body.html
+++ b/weinre.doc/ChangeLog.body.html
@@ -23,6 +23,16 @@
<p><a href="https://github.com/callback/callback-weinre/downloads">https://github.com/callback/callback-weinre/downloads</a>
<!-- ======================================================================= -->
+<h2>2012/??/?? - version 1.7.0</h2>
+
+<ul>
+
+<li><p>port the server from Java to node.js
+
+</ul>
+
+
+<!-- ======================================================================= -->
<h2>2011/12/01 - version 1.6.1</h2>
<ul>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/Home.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/Home.body.html b/weinre.doc/Home.body.html
index 281414a..fd0638a 100644
--- a/weinre.doc/Home.body.html
+++ b/weinre.doc/Home.body.html
@@ -32,8 +32,8 @@ on a mobile device such as a phone</b>.
<p>Interesting places to visit:
<table>
<tr><td>- videos at YouTube: <td><a href="http://www.youtube.com/results?search_query=weinre">http://www.youtube.com/results?search_query=weinre</a>
-<tr><td>- this documentation at GitHub: <td><a href="http://callback.github.com/callback-weinre">http://callback.github.com/callback-weinre</a>
-<tr><td>- source at GitHub: <td><a href="https://github.com/callback/callback-weinre">https://github.com/callback/callback-weinre</a>
+<tr><td>- this documentation at Apache: <td>[TBD]</a>
+<tr><td>- source at GitHub: <td><a href="https://git-wip-us.apache.org/repos/asf?p=incubator-cordova-weinre.git;a=summary">https://git-wip-us.apache.org/repos/asf?p=incubator-cordova-weinre.git;a=summary</a>
<tr><td>- discussion at Google Group: <td><a href="http://groups.google.com/group/weinre">http://groups.google.com/group/weinre</a>
</table>
@@ -139,11 +139,13 @@ attempt to debug it with <span class="weinre">weinre</span> and you are using an
version of Prototype.js.
</ul>
+<h3>Platforms supported - debug server</h3>
+<p>Any platform that supports <a href="http://nodejs.org/">node.js</a>.
+
<h3>Platforms supported - debug client</h3>
<p>The browser where the debugger user interface runs.
<ul>
-<li>weinre Mac application - Mac OS X 10.6 64-bit
<li>Google Chrome 8.x
<li>Apple Safari 5.x
</ul>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/Installing.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/Installing.body.html b/weinre.doc/Installing.body.html
index c64088a..c4854fc 100644
--- a/weinre.doc/Installing.body.html
+++ b/weinre.doc/Installing.body.html
@@ -17,20 +17,14 @@
* under the License.
-->
-<p><span class="weinre">weinre</span> is shipped as two archives
+<p><span class="weinre">weinre</span> is shipped as an archive
available at
-<a href="https://github.com/callback/callback-weinre/archives/master">https://github.com/callback/callback-weinre/archives/master</a>
+<a href="">[TBD]</a>
<ul class="spaced">
-<li><b><tt>weinre-jar-x.y.z.zip</tt></b>
-<br>This archive includes a Java .jar file.
-
-<li><b><tt>weinre-mac-x.y.z.zip</tt></b>
-<br>This archive includes a Mac OS X application.
+<li><b><tt>weinre-node-x.y.z.zip</tt></b>
</ul>
-<p>Install the .jar and/or Mac OS X application wherever you wish.
-At runtime, the .jar file is not sensive to the directory
-it is installed in, or the current directory when it's launched.
+<p>Unzip the archive wherever you wish.
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/License.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/License.body.html b/weinre.doc/License.body.html
index d775ca5..d42235b 100644
--- a/weinre.doc/License.body.html
+++ b/weinre.doc/License.body.html
@@ -17,35 +17,10 @@
* under the License.
-->
-<p>weinre contains code from the following other projects:
+<p>Source specific to weinre is all licensed under the
+<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache License, Version 2.0</a>.
-<ul class="spaced">
-
-<li>Files from <a href="http://webkit.org/">WebKit</a>.
-Web Inspector code. Although WebKit in general contains both BSD and
-LGPL code, only BSD licensed code is used by weinre.
-
-<li>Files from <a href="http://www.eclipse.org/jetty/">Eclipse Jetty</a>.
-HTTP server. License: ASLv2 and EPLv1
-
-<li>Files from <a href="http://www.eclipse.org/swt/">Eclipse SWT</a>.
-Platform UI toolkit. License: EPLv1
-
-<li>Files from <a href="https://github.com/pmuellr/modjewel">modjewel</a>.
-CommonJS runtime for the browser. License: MIT
-
-<li>Files from <a href="http://commons.apache.org/cli/">Apache Commons CLI</a>.
-Command-line parser. License: ASLv2
-
-<li>Files from <a href="http://incubator.apache.org/wink/">Apache Wink</a>.
-JSON codecs. License: ASLv2
-
-</ul>
-
-<p>The source for weinre itself is available under either
-the terms of the Apacle License, Version 2.0. You may obtain a copy of the
-License at
-
-<blockquote>
- <a href="http://www.apache.org/licenses/LICENSE-2.0">http://www.apache.org/licenses/LICENSE-2.0</a>
-</blockquote>
+<p>weinre also makes use of third party code; the licensing details for
+those is available in the
+<a href="https://git-wip-us.apache.org/repos/asf?p=incubator-cordova-weinre.git;a=blob;f=LICENSE;hb=HEAD">LICENSE</a>
+file in the top-most directory of the source distribution.
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/MultiUser.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/MultiUser.body.html b/weinre.doc/MultiUser.body.html
index 177f363..599f000 100644
--- a/weinre.doc/MultiUser.body.html
+++ b/weinre.doc/MultiUser.body.html
@@ -104,6 +104,4 @@ to list <b>id</b>'s in current use, for security reasons. From the Remote panel
of weinre, each connected client and target have their channel and id's listed,
if you can't remember what id you used with the client.
-<li>The client with the Mac application currently only supports the <code>anonymous</code> id.
-
</ul>
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/Running.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/Running.body.html b/weinre.doc/Running.body.html
index 652bddd..6c2f228 100644
--- a/weinre.doc/Running.body.html
+++ b/weinre.doc/Running.body.html
@@ -31,8 +31,8 @@ each other.
<dl class="spaced">
<dt>Debug Server
-<dd>This is the HTTP server that you run from the <tt>weinre.jar</tt> file
-or the Mac application. It's the HTTP server that's used by the
+<dd>This is the HTTP server that you run from the <tt>weinre-node</tt> distribution.
+It's the HTTP server that's used by the
<b>Debug Client</b> and <b>Debug Target</b>.
<dt>Debug Client
@@ -56,42 +56,19 @@ the <b>Debug Server</b> via HTTP using <tt>XMLHttpRequest</tt> (XHR).
<p>Typically, you run both the <b>Debug Client</b> and the <b>Debug Server</b>
on your desktop/laptop, and the <b>Debug Target</b> on your mobile device.
-<p>When using the Mac application, the
-<b>Debug Client</b> and <b>Debug Server</b> are running
-in the same process.
-When you launch the application,
-the server starts, and then the browser included in the
-application is launched
-on the appropriate URL automagically.
-
-<p>When using the <tt>weinre.jar</tt> program instead
-of the Mac application, only the <b>Debug Server</b>
-is started. You will need to launch the <b>Debug Client</b>
-in a web browser.
-
<p>The <b>Debug Target</b> is the squirrelliest bit. You
will need to arrange to inject some JavaScript code, provided
by the <b>Debug Server</b>, into your web page, in order for it
to function as a <b>Debug Target</b>.
<!-- ======================================================== -->
-<h2>Starting the debug server</h2>
-
-<p>There are two ways to run the <span class="weinre">weinre</span> debug server:
-
-<ul>
-<li>Running the debug server using the weinre.jar file
-<li>Running the debug server using the Mac application
-</ul>
+<h2>Running the debug server using the weinre-node distribution</h2>
-<!-- ======================================================== -->
-<h2>Running the debug server using the weinre.jar file</h2>
-
-<p>To run <span class="weinre">weinre</span> from the jar file,
+<p>To run <span class="weinre">weinre</span> from the weinre-node distribution,
execute the following command:
<pre>
-java -jar path/to/weinre.jar [options]
+node path-to-weinre-node/weinre [options]
</pre>
<p>Options available are:
@@ -130,12 +107,10 @@ on Windows, to get the ip addresses available on your machine.
<p>Default: <tt>false</tt>
</div>
-<li><tt>--reuseAddr [true | false]</tt>
+<li><tt>--debug [true | false]</tt>
<div class="indent">
-<p>Sets the "reuseAddr" flag for Jetty.
+<p>Causes even more jibberish to be written to stdout
<p>Default: <tt>false</tt>
-
-<p>May be needed if you restart your server frequently.
</div>
<li><tt>--readTimeout [seconds]</tt>
@@ -189,30 +164,6 @@ deathTimeout: 5
<p>The server will run until you kill it. Control-C will do the job.
-<p>Below is what you should see from the console after running
-<span class="weinre">weinre</span> from the <tt>weinre.jar</tt> file.
-
-<p><img src="images/shell.png">
-
-<!-- ======================================================== -->
-<h2>Running the debug server using the Mac application</h2>
-
-<p>Go back and read the description above about the weinre.jar settings.
-
-<p>Only the <tt>~/.weinre/server.properties</tt>
-file is available to configure the server, as there is no
-traditional command line used to launch Mac "applications".
-
-<p>The server will run until you quit the application.
-
-<p>Since there is no practical way to see the stdout and stdin
-from the server when running a Mac application, these streams
-are intercepted and displayed in the <b>Server Console</b>
-tab in the Mac application.
-
-<p>The Mac application also displays the server's home page
-in a separate tab.
-
<!-- ======================================================== -->
<h2>Running the debug server bound to something other than <tt>localhost</tt></h3>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/Security.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/Security.body.html b/weinre.doc/Security.body.html
index d8c09e6..ab73f49 100644
--- a/weinre.doc/Security.body.html
+++ b/weinre.doc/Security.body.html
@@ -30,7 +30,7 @@ no level of authentication for requests.
<p>The primary security exposure with <span class="weinre">weinre</span> is via
the debug server.
-<p>Currently, the server only reads files from the <tt>weinre.jar</tt> file,
+<p>Currently, the server only reads files from the weinre-node distribution,
and from the <tt>~/.weinre/</tt> directory (for property files).
The only thing the server writes to is <tt>stdout</tt> and <tt>stderr</tt>.
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/TestDrive.body.html
----------------------------------------------------------------------
diff --git a/weinre.doc/TestDrive.body.html b/weinre.doc/TestDrive.body.html
index 1bd1c2d..7a71a65 100644
--- a/weinre.doc/TestDrive.body.html
+++ b/weinre.doc/TestDrive.body.html
@@ -52,11 +52,11 @@ bind to something other than just localhost. The default configuration
is the safe one, and good enough to run this walk through.
<p>To start the server,
-<a href="Installing.html">install the <tt>weinre.jar</tt> file</a>,
+<a href="Installing.html">install the <tt>weinre.node</tt> server</a>,
then run the following command:
<pre>
-java -jar weinre.jar -httpPort 8081
+weinre -httpPort 8081
</pre>
<p><img src="images/weinre-con-01-h.jpg">
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.doc/boilerplate-header.html.txt
----------------------------------------------------------------------
diff --git a/weinre.doc/boilerplate-header.html.txt b/weinre.doc/boilerplate-header.html.txt
index 77ae9ed..8e4039a 100644
--- a/weinre.doc/boilerplate-header.html.txt
+++ b/weinre.doc/boilerplate-header.html.txt
@@ -28,7 +28,7 @@
<body>
-<a class="no-decoration" href="https://github.com/callback/callback-weinre"><div class="ribbon">Fork weinre on GitHub</div></a>
+<a class="no-decoration" href="https://git-wip-us.apache.org/repos/asf?p=incubator-cordova-weinre.git"><div class="ribbon">clone weinre at apache</div></a>
<!-- ======================================================================= -->
<h1 class="page-title">weinre - @PAGE_NAME@</h1>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/.classpath
----------------------------------------------------------------------
diff --git a/weinre.server/.classpath b/weinre.server/.classpath
deleted file mode 100644
index 349aa08..0000000
--- a/weinre.server/.classpath
+++ /dev/null
@@ -1,11 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<classpath>
- <classpathentry kind="src" path="src"/>
- <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
- <classpathentry combineaccessrules="false" kind="src" path="/weinre.build"/>
- <classpathentry exported="true" kind="lib" path="/weinre.build/vendor/cli/commons-cli.jar" sourcepath="/weinre.build/vendor/cli/commons-cli-src.jar"/>
- <classpathentry exported="true" kind="lib" path="/weinre.build/vendor/jetty/jetty.jar" sourcepath="/weinre.build/vendor/jetty/jetty-src.jar"/>
- <classpathentry exported="true" kind="lib" path="/weinre.build/vendor/json4j/json4j.jar" sourcepath="/weinre.build/vendor/json4j/json4j-src.jar"/>
- <classpathentry exported="true" kind="lib" path="/weinre.build/vendor/jetty/servlet-api.jar"/>
- <classpathentry kind="output" path="bin"/>
-</classpath>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/.gitignore
----------------------------------------------------------------------
diff --git a/weinre.server/.gitignore b/weinre.server/.gitignore
index ba077a4..9c2a02a 100644
--- a/weinre.server/.gitignore
+++ b/weinre.server/.gitignore
@@ -1 +1,4 @@
-bin
+tmp
+web
+build-info.txt
+package.json
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/.npmignore
----------------------------------------------------------------------
diff --git a/weinre.server/.npmignore b/weinre.server/.npmignore
new file mode 100644
index 0000000..38afd85
--- /dev/null
+++ b/weinre.server/.npmignore
@@ -0,0 +1,4 @@
+.DS_Store
+.git*
+Makefile
+test/
\ No newline at end of file
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/.project
----------------------------------------------------------------------
diff --git a/weinre.server/.project b/weinre.server/.project
deleted file mode 100644
index ba22530..0000000
--- a/weinre.server/.project
+++ /dev/null
@@ -1,17 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<projectDescription>
- <name>weinre.server</name>
- <comment></comment>
- <projects>
- </projects>
- <buildSpec>
- <buildCommand>
- <name>org.eclipse.jdt.core.javabuilder</name>
- <arguments>
- </arguments>
- </buildCommand>
- </buildSpec>
- <natures>
- <nature>org.eclipse.jdt.core.javanature</nature>
- </natures>
-</projectDescription>
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/README.md
----------------------------------------------------------------------
diff --git a/weinre.server/README.md b/weinre.server/README.md
new file mode 100644
index 0000000..fc2f570
--- /dev/null
+++ b/weinre.server/README.md
@@ -0,0 +1,47 @@
+<!--
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+-->
+
+The files contained in this directory are the source for the
+weinre server, implemented using the
+[express package](http://expressjs.com/)
+on the
+[node.js](http://nodejs.org)
+runtime.
+
+The weinre server uses numerous 3rd party libraries, installed in the
+`node_modules` directory, and stored in the SCM.
+In case these need to be updated, the file
+`package.json` should be updated with the dependencies and versions
+needed, then run
+
+ rm -rf node_modules; npm install
+
+to refresh the dependencies.
+
+
+before running the weinre server
+--------------------------------
+
+Before running the weinre server, after downloading the source,
+you will need to run a 'build'.
+
+
+running the weinre server
+-------------------------
+
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/lib/Channel.coffee
----------------------------------------------------------------------
diff --git a/weinre.server/lib/Channel.coffee b/weinre.server/lib/Channel.coffee
new file mode 100644
index 0000000..70f5841
--- /dev/null
+++ b/weinre.server/lib/Channel.coffee
@@ -0,0 +1,118 @@
+#-------------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#-------------------------------------------------------------------------------
+
+_ = require 'underscore'
+
+utils = require './utils'
+channelManager = require './channelManager'
+messageHandler = require './messageHandler'
+MessageQueue = require './MessageQueue'
+
+AnonymousId = 'anonymous'
+
+#-------------------------------------------------------------------------------
+module.exports = utils.registerClass class Channel
+
+ #---------------------------------------------------------------------------
+ constructor: (@pathPrefix, @id, @remoteAddress, @isClient) ->
+ prefix = if @isClient then 'c-' else 't-'
+ @name = "#{prefix}#{utils.getNextSequenceNumber()}"
+ @messageQueue = new MessageQueue
+ @isClosed = false
+ @connections = []
+ @isTarget = !@isClient
+ @readTimeout = utils.options.readTimeout * 1000
+
+ @id = AnonymousId if !@id
+
+ @description =
+ channel: @name
+ id: @id
+ hostName: @remoteAddress
+ remoteAddress: @remoteAddress
+
+ @updateLastRead()
+
+ channelManager.created @
+
+ #---------------------------------------------------------------------------
+ close: () ->
+ return if @isClosed
+
+ channelManager.destroyed @
+
+ @isClosed = true
+ @messageQueue.shutdown()
+
+ #---------------------------------------------------------------------------
+ sendCallback: (intfName, callbackId, args...) ->
+ return if !callbackId
+
+ args.unshift callbackId
+
+ @sendMessage intfName, 'sendCallback', args...
+
+ #---------------------------------------------------------------------------
+ sendMessage: (intfName, method, args...) ->
+
+ message = genJSON
+ interface: intfName
+ method: method
+ args: args
+
+ @messageQueue.push message
+
+ #---------------------------------------------------------------------------
+ handleMessages: (messages) ->
+
+ for message in messages
+ message = parseJSON(message)
+ continue if !message
+
+ messageHandler.handleMessage @, message
+
+ #---------------------------------------------------------------------------
+ getMessages: (callback) ->
+ @updateLastRead()
+ return callback.call(null, null) if @isClosed
+
+ @messageQueue.pullAll @readTimeout, callback
+
+ #---------------------------------------------------------------------------
+ updateLastRead: () ->
+ @lastRead = (new Date).valueOf()
+
+ #---------------------------------------------------------------------------
+ toString: () ->
+ connections = _.map(@connections, (val) -> val.name).join(',')
+ "Channel(#{@name}, closed:#{@isClosed}, connections:[#{connections}])"
+
+#-------------------------------------------------------------------------------
+parseJSON = (message) ->
+ try
+ return JSON.parse(message)
+ catch e
+ return null
+
+#-------------------------------------------------------------------------------
+genJSON = (message) ->
+ try
+ return JSON.stringify(message)
+ catch e
+ return null
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/lib/HttpChannelHandler.coffee
----------------------------------------------------------------------
diff --git a/weinre.server/lib/HttpChannelHandler.coffee b/weinre.server/lib/HttpChannelHandler.coffee
new file mode 100644
index 0000000..dd7f2f4
--- /dev/null
+++ b/weinre.server/lib/HttpChannelHandler.coffee
@@ -0,0 +1,154 @@
+#-------------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#-------------------------------------------------------------------------------
+
+_ = require 'underscore'
+
+utils = require './utils'
+Channel = require './Channel'
+channelManager = require './channelManager'
+
+#-------------------------------------------------------------------------------
+module.exports = utils.registerClass class HttpChannelHandler
+
+ #---------------------------------------------------------------------------
+ constructor: (@pathPrefix) ->
+
+ if @pathPrefix == '/ws/client'
+ @isClient = true
+
+ else if @pathPrefix == '/ws/target'
+ @isClient = false
+
+ else
+ utils.pitch "invalid pathPrefix: #{@pathPrefix}"
+
+ @isTarget = !@isClient
+
+ #---------------------------------------------------------------------------
+ handle: (request, response, uri) ->
+
+ setCORSHeaders request, response
+ setCacheHeaders request, response
+
+ #-----------------
+
+ # * #{pathPrefix}a
+ if uri[0] != '/'
+ return handleError(request, response, 404)
+
+ #-----------------
+
+ if uri == '/'
+
+ # OPTIONS #{pathPrefix}/
+ if request.method == 'OPTIONS'
+ return handleOptions(request, response)
+
+ # POST #{pathPrefix}/
+ if request.method == 'POST'
+ return handleCreate(@pathPrefix, @isClient, request, response)
+
+ # * #{pathPrefix}/
+ return handleError(request, response, 405)
+
+ #-----------------
+
+ parts = uri.split('/')
+
+ # * #{pathPrefix}/x/y
+ if parts.length > 2
+ return handleError(request, response, 404)
+
+ #-----------------
+
+ channelName = parts[1]
+
+ # OPTIONS #{pathPrefix}/x
+ if request.method == 'OPTIONS'
+ return handleOptions(request, response)
+
+ # GET #{pathPrefix}/x
+ if request.method == 'GET'
+ return handleGet(request, response, channelName)
+
+ # POST #{pathPrefix}/x
+ if request.method == 'POST'
+ return handlePost(request, response, channelName)
+
+ # anything else
+ return handleError(request, response, 405)
+
+#-------------------------------------------------------------------------------
+handleCreate = (pathPrefix, isClient, request, response) ->
+ id = request.body?.id
+
+ remoteAddress = request.connection?.remoteAddress || ""
+
+ channel = new Channel(pathPrefix, id, remoteAddress, isClient)
+
+ response.contentType 'application/json'
+ response.send JSON.stringify
+ channel: channel.name
+ id: channel.id
+
+#-------------------------------------------------------------------------------
+handleGet = (request, response, channelName) ->
+ remoteAddress = request.connection?.remoteAddress || ""
+ channel = channelManager.getChannel(channelName, remoteAddress)
+ return handleError(request, response, 404) if !channel
+
+ channel.getMessages (messages) =>
+ return handleError(request, response, 404) if channel.isClosed
+ return handleError(request, response, 404) if !messages
+
+ response.contentType 'application/json'
+ response.send JSON.stringify(messages)
+
+#-------------------------------------------------------------------------------
+handlePost = (request, response, channelName) ->
+ remoteAddress = request.connection?.remoteAddress || ""
+ channel = channelManager.getChannel(channelName, remoteAddress)
+ return handleError(request, response, 404) if !channel
+
+ channel.handleMessages(request.body)
+ response.send('')
+
+#-------------------------------------------------------------------------------
+handleOptions = (request, response) ->
+ response.send('')
+
+#-------------------------------------------------------------------------------
+handleError = (request, response, status) ->
+ response.send(status)
+
+#-------------------------------------------------------------------------------
+setCORSHeaders = (request, response) ->
+ origin = request.header 'Origin'
+ return if !origin
+
+ response.header 'Access-Control-Allow-Origin', origin
+ response.header 'Access-Control-Max-Age', '600'
+ response.header 'Access-Control-Allow-Methods', 'GET, POST'
+
+#-------------------------------------------------------------------------------
+setCacheHeaders = (request, response) ->
+ response.header 'Pragma', 'no-cache'
+ response.header 'Expires', '0'
+ response.header 'Cache-Control', 'no-cache'
+ response.header 'Cache-Control', 'no-store'
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/lib/MessageQueue.coffee
----------------------------------------------------------------------
diff --git a/weinre.server/lib/MessageQueue.coffee b/weinre.server/lib/MessageQueue.coffee
new file mode 100644
index 0000000..52af9ea
--- /dev/null
+++ b/weinre.server/lib/MessageQueue.coffee
@@ -0,0 +1,87 @@
+#-------------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#-------------------------------------------------------------------------------
+
+_ = require 'underscore'
+
+utils = require './utils'
+
+#-------------------------------------------------------------------------------
+module.exports = utils.registerClass class MessageQueue
+
+ #---------------------------------------------------------------------------
+ constructor: () ->
+ @messages = []
+ @closed = false
+ @callback = null
+ @timer = null
+
+ _.bindAll @, '_timerExpired', '_updated'
+
+ #---------------------------------------------------------------------------
+ shutdown: () ->
+ return if @closed
+
+ @closed = true
+
+ clearTimeout @timer if @timer
+ @callback.call(null, @messages) if @callback
+
+ @callback = null
+ @messages = null
+ @timer = null
+
+ #---------------------------------------------------------------------------
+ push: (message) ->
+ return if @closed
+
+ @messages.push message
+ process.nextTick @_updated
+
+ #---------------------------------------------------------------------------
+ pullAll: (timeout, callback) ->
+ return callback.call(null, null) if @closed
+ return callback.call(null, []) if @callback
+
+ if @messages.length
+ callback.call(null, @messages)
+ @messages = []
+ return
+
+ @callback = callback
+ @timer = setTimeout @_timerExpired, timeout
+
+ #---------------------------------------------------------------------------
+ _timerExpired: () ->
+ @_updated()
+
+ #---------------------------------------------------------------------------
+ _updated: () ->
+ return if @closed
+ return if !@callback
+
+ callback = @callback
+ messages = @messages
+ clearTimeout @timer if @timer
+
+ @callback = null
+ @messages = []
+ @timer = null
+
+ callback.call(null, messages)
+
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/lib/channelManager.coffee
----------------------------------------------------------------------
diff --git a/weinre.server/lib/channelManager.coffee b/weinre.server/lib/channelManager.coffee
new file mode 100644
index 0000000..48abca6
--- /dev/null
+++ b/weinre.server/lib/channelManager.coffee
@@ -0,0 +1,126 @@
+#-------------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#-------------------------------------------------------------------------------
+
+_ = require 'underscore'
+
+utils = require './utils'
+serviceManager = require './serviceManager'
+
+WeinreClientEvents = null
+WeinreTargetEvents = null
+
+channelManager = null
+
+#-------------------------------------------------------------------------------
+utils.registerClass class ChannelManager
+
+ #---------------------------------------------------------------------------
+ constructor: () ->
+ @channels = {}
+
+ #---------------------------------------------------------------------------
+ initialize: ->
+
+ WeinreClientEvents = serviceManager.get 'WeinreClientEvents'
+ WeinreTargetEvents = serviceManager.get 'WeinreTargetEvents'
+
+ if !WeinreClientEvents
+ utils.exit 'WeinreClientEvents service not registered'
+
+ if !WeinreTargetEvents
+ utils.exit 'WeinreTargetEvents service not registered'
+
+ #---------------------------------------------------------------------------
+ created: (channel) ->
+ @channels[channel.name] = channel
+
+ #---------------------------------------------------------------------------
+ destroyed: (channel) ->
+ if channel.isClient
+ for connection in channel.connections
+ @disconnectChannels(channel, connection)
+ else
+ for connection in channel.connections
+ @disconnectChannels(connection, channel)
+
+ clients = @getClientChannels(channel.id)
+
+ if channel.isClient
+ WeinreClientEvents.clientUnregistered(clients, channel.name)
+ else
+ WeinreClientEvents.targetUnregistered(clients, channel.name)
+
+ delete @channels[channel.name]
+
+ #---------------------------------------------------------------------------
+ getChannel: (name, remoteAddress) ->
+ return null if !_.has(@channels, name)
+
+ channel = @channels[name]
+
+ return null if !channel
+
+ if remoteAddress
+ return null if channel.remoteAddress != remoteAddress
+
+ channel
+
+ #---------------------------------------------------------------------------
+ connectChannels: (client, target) ->
+ return if client.isClosed or target.isClosed
+
+ if client.connections.length
+ @disconnectChannels(client, client.connections[0])
+
+ client.connections.push target
+ target.connections.push client
+
+ clients = @getClientChannels(client.id)
+
+ WeinreClientEvents.connectionCreated(clients, client.name, target.name)
+ WeinreTargetEvents.connectionCreated(target, client.name, target.name)
+
+ #---------------------------------------------------------------------------
+ disconnectChannels: (client, target) ->
+
+ clients = @getClientChannels(client.id)
+
+ WeinreClientEvents.connectionDestroyed(clients, client.name, target.name)
+ WeinreTargetEvents.connectionDestroyed(target, client.name, target.name)
+
+ client.connections = _.without(client.connections, target)
+ target.connections = _.without(target.connections, client)
+
+ #---------------------------------------------------------------------------
+ getChannels: (id) ->
+ if id?
+ _.filter(@channels, (item) -> item.id == id)
+ else
+ _.values(@channels)
+
+ #---------------------------------------------------------------------------
+ getClientChannels: (id) ->
+ _.filter(@channels, (item) -> item.isClient && item.id == id)
+
+ #---------------------------------------------------------------------------
+ getTargetChannels: (id) ->
+ _.filter(@channels, (item) -> item.isTarget && item.id == id)
+
+#-------------------------------------------------------------------------------
+module.exports = new ChannelManager
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/lib/cli.coffee
----------------------------------------------------------------------
diff --git a/weinre.server/lib/cli.coffee b/weinre.server/lib/cli.coffee
new file mode 100644
index 0000000..2598c68
--- /dev/null
+++ b/weinre.server/lib/cli.coffee
@@ -0,0 +1,130 @@
+#-------------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#-------------------------------------------------------------------------------
+
+fs = require 'fs'
+path = require 'path'
+
+_ = require 'underscore'
+nopt = require 'nopt'
+
+utils = require './utils'
+weinre = require './weinre'
+
+optionDefaults =
+ httpPort: 8080
+ boundHost: 'localhost'
+ verbose: false
+ debug: false
+ readTimeout: 5
+
+#-------------------------------------------------------------------------------
+exports.run = ->
+
+ knownOpts =
+ httpPort: Number
+ boundHost: String
+ verbose: Boolean
+ debug: Boolean
+ readTimeout: Number
+ deathTimeout: Number
+ help: Boolean
+
+ shortHands =
+ '?': ['--help']
+ 'h': ['--help']
+
+ nopt.invalidHandler = printNoptError
+ parsedOpts = nopt(knownOpts, shortHands, process.argv, 2)
+
+ #----
+
+ printHelp() if parsedOpts.help
+
+ args = parsedOpts.argv.remain
+
+ printHelp() if args.length != 0
+
+ #----
+
+ delete parsedOpts.argv
+ opts = _.extend {}, optionDefaults, getDotWeinreServerProperties(), parsedOpts
+
+ if !opts.deathTimeout?
+ opts.deathTimeout = 3 * opts.readTimeout
+
+ utils.setOptions opts
+
+ weinre.run opts
+
+#-------------------------------------------------------------------------------
+printNoptError = (key, val, types) ->
+ utils.exit "error with option '#{key}', value '#{val}'"
+
+#-------------------------------------------------------------------------------
+printHelp = () ->
+ version = weinre.getVersion()
+
+ console.error """
+usage: #{utils.Program} [options]
+version: #{version}
+
+options:
+ --httpPort port to run the http server on default: #{optionDefaults.httpPort}
+ --boundHost ip address to bind the server to default: #{optionDefaults.boundHost}
+ --verbose print more diagnostics default: #{optionDefaults.verbose}
+ --debug print even more diagnostics default: #{optionDefaults.debug}
+ --readTimeout seconds to wait for a client message default: #{optionDefaults.readTimeout}
+ --deathTimeout seconds to wait to kill client default: 3*readTimeout
+
+--boundHost can be an ip address, hostname, or -all-, where -all-
+means binding to all ip address on the current machine'
+
+for more info see: http://incubator.apache.org/callback/
+"""
+ process.exit()
+
+#-------------------------------------------------------------------------------
+getDotWeinreServerProperties = () ->
+ properties = {}
+
+ fileName = replaceTilde '~/.weinre/server.properties'
+ return options if !path.existsSync(fileName)
+
+ contents = fs.readFileSync(fileName, 'utf8')
+ lines = contents.split('\n')
+
+ for line in lines
+ line = line.replace(/#.*/,'')
+ match = line.match /\s*(\w+)\s*:\s*(.+)\s*/
+ continue if !match
+
+ key = utils.trim match[1]
+ val = utils.trim match[2]
+
+ properties[key] = val
+
+ properties
+
+#-------------------------------------------------------------------------------
+replaceTilde = (fileName) ->
+ fileName.replace('~', getTildeReplacement())
+
+#-------------------------------------------------------------------------------
+getTildeReplacement = () ->
+ process.env["HOME"] || process.env["USERPROFILE"] || '.'
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/lib/dumpingHandler.coffee
----------------------------------------------------------------------
diff --git a/weinre.server/lib/dumpingHandler.coffee b/weinre.server/lib/dumpingHandler.coffee
new file mode 100644
index 0000000..310852d
--- /dev/null
+++ b/weinre.server/lib/dumpingHandler.coffee
@@ -0,0 +1,77 @@
+#-------------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#-------------------------------------------------------------------------------
+
+_ = require 'underscore'
+
+utils = require './utils'
+
+#-------------------------------------------------------------------------------
+dumpingHandler = (request, response, uri) ->
+ originalSend = response.send
+ response.send = (body) ->
+ dumpResponse(originalSend, body, request, response, uri)
+
+ return if request.method != 'POST'
+
+ utils.logVerbose '--------------------------------------------------'
+ utils.logVerbose "#{request.method} #{uri} [request]"
+
+ if _.isArray(request.body)
+ for element in request.body
+ utils.logVerbose " #{enhance(JSON.parse(element))}"
+ else
+ utils.logVerbose " #{enhance(request.body)}"
+
+#-------------------------------------------------------------------------------
+dumpResponse = (originalSend, body, request, response, uri) ->
+ originalSend.call(response, body)
+
+ return if request.method not in ['GET', 'POST']
+
+ try
+ body = JSON.parse(body)
+ catch e
+ return
+
+ return if _.isArray(body) && (body.length == 0)
+
+ utils.logVerbose '--------------------------------------------------'
+ utils.logVerbose "#{request.method} #{uri} #{response.statusCode} [response]"
+
+ if _.isArray(body)
+ for element in body
+ utils.logVerbose " #{enhance(JSON.parse(element))}"
+ else
+ utils.logVerbose " #{enhance(body)}"
+
+#-------------------------------------------------------------------------------
+enhance = (object) ->
+ if !object.interface || !object.method || !object.args
+ return JSON.stringify(object)
+
+ signature = "#{object.interface}.#{object.method}"
+
+ args = JSON.stringify(object.args)
+ if args.length > 500
+ args = "#{args.substr(0,50)}..."
+
+ return "#{signature}(#{args})"
+
+#-------------------------------------------------------------------------------
+module.exports = dumpingHandler
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/lib/extensionManager.coffee
----------------------------------------------------------------------
diff --git a/weinre.server/lib/extensionManager.coffee b/weinre.server/lib/extensionManager.coffee
new file mode 100644
index 0000000..c367425
--- /dev/null
+++ b/weinre.server/lib/extensionManager.coffee
@@ -0,0 +1,30 @@
+#-------------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#-------------------------------------------------------------------------------
+
+utils = require './utils'
+
+#-------------------------------------------------------------------------------
+utils.registerClass class ExtensionManager
+
+ #---------------------------------------------------------------------------
+ constructor: () ->
+ @extensions = []
+
+#-------------------------------------------------------------------------------
+module.exports = new ExtensionManager
http://git-wip-us.apache.org/repos/asf/incubator-cordova-weinre/blob/c4fbd3d0/weinre.server/lib/jsonBodyParser.coffee
----------------------------------------------------------------------
diff --git a/weinre.server/lib/jsonBodyParser.coffee b/weinre.server/lib/jsonBodyParser.coffee
new file mode 100644
index 0000000..58f755b
--- /dev/null
+++ b/weinre.server/lib/jsonBodyParser.coffee
@@ -0,0 +1,47 @@
+#-------------------------------------------------------------------------------
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+#-------------------------------------------------------------------------------
+
+#-------------------------------------------------------------------------------
+jsonBodyParser = ->
+ return (request, response, next) -> parseBodyAsJSON(request, response, next)
+
+#-------------------------------------------------------------------------------
+parseBodyAsJSON = (request, response, next) ->
+
+ return next() if request.body
+
+ request.body = {}
+
+ return next() if request.method != 'POST'
+
+ request.setEncoding 'utf8'
+
+ buffer = ''
+ request.on 'data', (chunk) -> buffer += chunk
+ request.on 'end', ->
+ return next() if '' == buffer
+
+ try
+ request.body = JSON.parse(buffer)
+ next()
+ catch e
+ next(e)
+
+#-------------------------------------------------------------------------------
+module.exports = jsonBodyParser