? mochi.patch
? mochitest/MochiKit/.svn
? mochitest/tests/test_bug357776.html
? mochitest/tests/SimpleTest/.svn
Index: mochitest/README.txt
===================================================================
RCS file: mochitest/README.txt
diff -N mochitest/README.txt
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/README.txt 25 Oct 2006 20:24:40 -0000
@@ -0,0 +1,119 @@
+ ----------------
+ mochitest README
+ ----------------
+
+Steps to get started:
+
+ 1.) Right now, you will need to edit some constants in runtests.pl.
+
+ 2.) Start the python server in a separate console:
+
+ %> python server.py
+
+ It runs at http://localhost:8888/. Control-C will kill it. We are looking
+ at other server options, because we don't want to require python.
+
+ 3.) New test cases can be added to the tests/ directory. We are working on
+ easy test navigation and automated test addition.
+
+ 4.) gen_template.pl takes a bug number as its only argument and outputs a
+ test template to stdout.
+
+ 5.) Write a test.
+
+
+Checkin rules (FIXME: strawman -- davel needs to review):
+
+ 1.) Any module owner/peer/member should feel free to check in a test case.
+
+ 2.) Modifications to Makefiles, Perl, or JS code need a bugzilla bug with
+ davel and sayrer cc'd.
+
+Example test:
+
+
+
+
+
+ Test for Bug 345656
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: mochitest/gen_template.pl
===================================================================
RCS file: mochitest/gen_template.pl
diff -N mochitest/gen_template.pl
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/gen_template.pl 25 Oct 2006 20:24:40 -0000
@@ -0,0 +1,18 @@
+#!/usr/bin/perl
+#
+# gen_template.pl
+# Makes test case templates.
+# Takes one argument: a bug number
+#
+# perl gen_template.pl 345876
+#
+# sends a test case template for bug 345876 to stdout
+
+$bug_number = $ARGV[0];
+
+open(IN,"static/test.template.txt") or die("Failed to open myfile for reading.");
+while((defined(IN)) && ($line = )) {
+ $line =~ s/{BUGNUMBER}/$bug_number/g;
+ print STDOUT $line;
+}
+close(IN);
Index: mochitest/runtests.pl
===================================================================
RCS file: mochitest/runtests.pl
diff -N mochitest/runtests.pl
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/runtests.pl 25 Oct 2006 20:24:40 -0000
@@ -0,0 +1,62 @@
+#!/usr/bin/perl
+use File::Path;
+
+# URL parameters:
+#
+# closeWhenDone -- runs quit.js after tests
+# logFile -- logs test run to an absolute path
+# quiet -- turns of console dumps
+#
+# consoleLevel, fileLevel -- set the logging level of the console and file logs, if activated.
+#
+
+$test_url = "http://localhost:8888/tests/index.html";
+#$test_url = "about:blank";
+# XXXsayrer these are specific to my mac, need to make them general
+#$app = "/Applications/Firefox.app/Contents/MacOS/firefox-bin";
+$app = "/Users/sayrer/firefox/mozilla/fb-debug/dist/MinefieldDebug.app/Contents/MacOS/firefox-bin";
+$profile = "dhtml_test_profile";
+$profile_dir = "/tmp/$profile";
+
+$pref_content = <>$profile_dir/user.js") || die("Could not open user.js file $!");
+print PREFOUTFILE ($pref_content);
+close(PREFOUTFILE);
+
+# now run with the profile we created
+@runargs = ($app, '-P', "$profile", $test_url);
+$rc = 0xffff & system @runargs;
+
+# remove the profile we created
+rmtree($profile_dir, 0, 0);
+
+# print test run times
+$finish = localtime;
+print " started: $start\n";
+print "finished: $finish\n";
Index: mochitest/server.py
===================================================================
RCS file: mochitest/server.py
diff -N mochitest/server.py
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/server.py 25 Oct 2006 20:24:40 -0000
@@ -0,0 +1,14 @@
+import SimpleHTTPServer
+import SocketServer
+
+# minimal web server. serves files relative to the
+# current directory.
+
+PORT = 8888
+
+Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
+Handler.extensions_map[".xhtml"] = "application/xhtml+xml"
+httpd = SocketServer.TCPServer(("", PORT), Handler)
+
+print "serving at port", PORT
+httpd.serve_forever()
Index: mochitest/MochiKit/Async.js
===================================================================
RCS file: mochitest/MochiKit/Async.js
diff -N mochitest/MochiKit/Async.js
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/MochiKit/Async.js 25 Oct 2006 20:24:40 -0000
@@ -0,0 +1,632 @@
+/***
+
+MochiKit.Async 1.4
+
+See for documentation, downloads, license, etc.
+
+(c) 2005 Bob Ippolito. All rights Reserved.
+
+***/
+
+if (typeof(dojo) != 'undefined') {
+ dojo.provide("MochiKit.Async");
+ dojo.require("MochiKit.Base");
+}
+if (typeof(JSAN) != 'undefined') {
+ JSAN.use("MochiKit.Base", []);
+}
+
+try {
+ if (typeof(MochiKit.Base) == 'undefined') {
+ throw "";
+ }
+} catch (e) {
+ throw "MochiKit.Async depends on MochiKit.Base!";
+}
+
+if (typeof(MochiKit.Async) == 'undefined') {
+ MochiKit.Async = {};
+}
+
+MochiKit.Async.NAME = "MochiKit.Async";
+MochiKit.Async.VERSION = "1.4";
+MochiKit.Async.__repr__ = function () {
+ return "[" + this.NAME + " " + this.VERSION + "]";
+};
+MochiKit.Async.toString = function () {
+ return this.__repr__();
+};
+
+/** @id MochiKit.Async.Deferred */
+MochiKit.Async.Deferred = function (/* optional */ canceller) {
+ this.chain = [];
+ this.id = this._nextId();
+ this.fired = -1;
+ this.paused = 0;
+ this.results = [null, null];
+ this.canceller = canceller;
+ this.silentlyCancelled = false;
+ this.chained = false;
+};
+
+MochiKit.Async.Deferred.prototype = {
+ /** @id MochiKit.Async.Deferred.prototype.repr */
+ repr: function () {
+ var state;
+ if (this.fired == -1) {
+ state = 'unfired';
+ } else if (this.fired === 0) {
+ state = 'success';
+ } else {
+ state = 'error';
+ }
+ return 'Deferred(' + this.id + ', ' + state + ')';
+ },
+
+ toString: MochiKit.Base.forwardCall("repr"),
+
+ _nextId: MochiKit.Base.counter(),
+
+ /** @id MochiKit.Async.Deferred.prototype.cancel */
+ cancel: function () {
+ var self = MochiKit.Async;
+ if (this.fired == -1) {
+ if (this.canceller) {
+ this.canceller(this);
+ } else {
+ this.silentlyCancelled = true;
+ }
+ if (this.fired == -1) {
+ this.errback(new self.CancelledError(this));
+ }
+ } else if ((this.fired === 0) && (this.results[0] instanceof self.Deferred)) {
+ this.results[0].cancel();
+ }
+ },
+
+ _resback: function (res) {
+ /***
+
+ The primitive that means either callback or errback
+
+ ***/
+ this.fired = ((res instanceof Error) ? 1 : 0);
+ this.results[this.fired] = res;
+ this._fire();
+ },
+
+ _check: function () {
+ if (this.fired != -1) {
+ if (!this.silentlyCancelled) {
+ throw new MochiKit.Async.AlreadyCalledError(this);
+ }
+ this.silentlyCancelled = false;
+ return;
+ }
+ },
+
+ /** @id MochiKit.Async.Deferred.prototype.callback */
+ callback: function (res) {
+ this._check();
+ if (res instanceof MochiKit.Async.Deferred) {
+ throw new Error("Deferred instances can only be chained if they are the result of a callback");
+ }
+ this._resback(res);
+ },
+
+ /** @id MochiKit.Async.Deferred.prototype.errback */
+ errback: function (res) {
+ this._check();
+ var self = MochiKit.Async;
+ if (res instanceof self.Deferred) {
+ throw new Error("Deferred instances can only be chained if they are the result of a callback");
+ }
+ if (!(res instanceof Error)) {
+ res = new self.GenericError(res);
+ }
+ this._resback(res);
+ },
+
+ /** @id MochiKit.Async.Deferred.prototype.addBoth */
+ addBoth: function (fn) {
+ if (arguments.length > 1) {
+ fn = MochiKit.Base.partial.apply(null, arguments);
+ }
+ return this.addCallbacks(fn, fn);
+ },
+
+ /** @id MochiKit.Async.Deferred.prototype.addCallback */
+ addCallback: function (fn) {
+ if (arguments.length > 1) {
+ fn = MochiKit.Base.partial.apply(null, arguments);
+ }
+ return this.addCallbacks(fn, null);
+ },
+
+ /** @id MochiKit.Async.Deferred.prototype.addErrback */
+ addErrback: function (fn) {
+ if (arguments.length > 1) {
+ fn = MochiKit.Base.partial.apply(null, arguments);
+ }
+ return this.addCallbacks(null, fn);
+ },
+
+ /** @id MochiKit.Async.Deferred.prototype.addCallbacks */
+ addCallbacks: function (cb, eb) {
+ if (this.chained) {
+ throw new Error("Chained Deferreds can not be re-used");
+ }
+ this.chain.push([cb, eb]);
+ if (this.fired >= 0) {
+ this._fire();
+ }
+ return this;
+ },
+
+ _fire: function () {
+ /***
+
+ Used internally to exhaust the callback sequence when a result
+ is available.
+
+ ***/
+ var chain = this.chain;
+ var fired = this.fired;
+ var res = this.results[fired];
+ var self = this;
+ var cb = null;
+ while (chain.length > 0 && this.paused === 0) {
+ // Array
+ var pair = chain.shift();
+ var f = pair[fired];
+ if (f === null) {
+ continue;
+ }
+ try {
+ res = f(res);
+ fired = ((res instanceof Error) ? 1 : 0);
+ if (res instanceof MochiKit.Async.Deferred) {
+ cb = function (res) {
+ self._resback(res);
+ self.paused--;
+ if ((self.paused === 0) && (self.fired >= 0)) {
+ self._fire();
+ }
+ };
+ this.paused++;
+ }
+ } catch (err) {
+ fired = 1;
+ if (!(err instanceof Error)) {
+ err = new MochiKit.Async.GenericError(err);
+ }
+ res = err;
+ }
+ }
+ this.fired = fired;
+ this.results[fired] = res;
+ if (cb && this.paused) {
+ // this is for "tail recursion" in case the dependent deferred
+ // is already fired
+ res.addBoth(cb);
+ res.chained = true;
+ }
+ }
+};
+
+MochiKit.Base.update(MochiKit.Async, {
+ /** @id MochiKit.Async.evalJSONRequest */
+ evalJSONRequest: function (/* req */) {
+ return eval('(' + arguments[0].responseText + ')');
+ },
+
+ /** @id MochiKit.Async.succeed */
+ succeed: function (/* optional */result) {
+ var d = new MochiKit.Async.Deferred();
+ d.callback.apply(d, arguments);
+ return d;
+ },
+
+ /** @id MochiKit.Async.fail */
+ fail: function (/* optional */result) {
+ var d = new MochiKit.Async.Deferred();
+ d.errback.apply(d, arguments);
+ return d;
+ },
+
+ /** @id MochiKit.Async.getXMLHttpRequest */
+ getXMLHttpRequest: function () {
+ var self = arguments.callee;
+ if (!self.XMLHttpRequest) {
+ var tryThese = [
+ function () { return new XMLHttpRequest(); },
+ function () { return new ActiveXObject('Msxml2.XMLHTTP'); },
+ function () { return new ActiveXObject('Microsoft.XMLHTTP'); },
+ function () { return new ActiveXObject('Msxml2.XMLHTTP.4.0'); },
+ function () {
+ throw new MochiKit.Async.BrowserComplianceError("Browser does not support XMLHttpRequest");
+ }
+ ];
+ for (var i = 0; i < tryThese.length; i++) {
+ var func = tryThese[i];
+ try {
+ self.XMLHttpRequest = func;
+ return func();
+ } catch (e) {
+ // pass
+ }
+ }
+ }
+ return self.XMLHttpRequest();
+ },
+
+ _xhr_onreadystatechange: function (d) {
+ // MochiKit.Logging.logDebug('this.readyState', this.readyState);
+ var m = MochiKit.Base;
+ if (this.readyState == 4) {
+ // IE SUCKS
+ try {
+ this.onreadystatechange = null;
+ } catch (e) {
+ try {
+ this.onreadystatechange = m.noop;
+ } catch (e) {
+ }
+ }
+ var status = null;
+ try {
+ status = this.status;
+ if (!status && m.isNotEmpty(this.responseText)) {
+ // 0 or undefined seems to mean cached or local
+ status = 304;
+ }
+ } catch (e) {
+ // pass
+ // MochiKit.Logging.logDebug('error getting status?', repr(items(e)));
+ }
+ // 200 is OK, 304 is NOT_MODIFIED
+ if (status == 200 || status == 304) { // OK
+ d.callback(this);
+ } else {
+ var err = new MochiKit.Async.XMLHttpRequestError(this, "Request failed");
+ if (err.number) {
+ // XXX: This seems to happen on page change
+ d.errback(err);
+ } else {
+ // XXX: this seems to happen when the server is unreachable
+ d.errback(err);
+ }
+ }
+ }
+ },
+
+ _xhr_canceller: function (req) {
+ // IE SUCKS
+ try {
+ req.onreadystatechange = null;
+ } catch (e) {
+ try {
+ req.onreadystatechange = MochiKit.Base.noop;
+ } catch (e) {
+ }
+ }
+ req.abort();
+ },
+
+
+ /** @id MochiKit.Async.sendXMLHttpRequest */
+ sendXMLHttpRequest: function (req, /* optional */ sendContent) {
+ if (typeof(sendContent) == "undefined" || sendContent === null) {
+ sendContent = "";
+ }
+
+ var m = MochiKit.Base;
+ var self = MochiKit.Async;
+ var d = new self.Deferred(m.partial(self._xhr_canceller, req));
+
+ try {
+ req.onreadystatechange = m.bind(self._xhr_onreadystatechange,
+ req, d);
+ req.send(sendContent);
+ } catch (e) {
+ try {
+ req.onreadystatechange = null;
+ } catch (ignore) {
+ // pass
+ }
+ d.errback(e);
+ }
+
+ return d;
+
+ },
+
+ /** @id MochiKit.Async.doSimpleXMLHttpRequest */
+ doSimpleXMLHttpRequest: function (url/*, ...*/) {
+ var self = MochiKit.Async;
+ var req = self.getXMLHttpRequest();
+ if (arguments.length > 1) {
+ var m = MochiKit.Base;
+ var qs = m.queryString.apply(null, m.extend(null, arguments, 1));
+ if (qs) {
+ url += "?" + qs;
+ }
+ }
+ req.open("GET", url, true);
+ return self.sendXMLHttpRequest(req);
+ },
+
+ /** @id MochiKit.Async.loadJSONDoc */
+ loadJSONDoc: function (url) {
+ var self = MochiKit.Async;
+ var d = self.doSimpleXMLHttpRequest.apply(self, arguments);
+ d = d.addCallback(self.evalJSONRequest);
+ return d;
+ },
+
+ /** @id MochiKit.Async.wait */
+ wait: function (seconds, /* optional */value) {
+ var d = new MochiKit.Async.Deferred();
+ var m = MochiKit.Base;
+ if (typeof(value) != 'undefined') {
+ d.addCallback(function () { return value; });
+ }
+ var timeout = setTimeout(
+ m.bind("callback", d),
+ Math.floor(seconds * 1000));
+ d.canceller = function () {
+ try {
+ clearTimeout(timeout);
+ } catch (e) {
+ // pass
+ }
+ };
+ return d;
+ },
+
+ /** @id MochiKit.Async.callLater */
+ callLater: function (seconds, func) {
+ var m = MochiKit.Base;
+ var pfunc = m.partial.apply(m, m.extend(null, arguments, 1));
+ return MochiKit.Async.wait(seconds).addCallback(
+ function (res) { return pfunc(); }
+ );
+ }
+});
+
+
+/** @id MochiKit.Async.DeferredLock */
+MochiKit.Async.DeferredLock = function () {
+ this.waiting = [];
+ this.locked = false;
+ this.id = this._nextId();
+};
+
+MochiKit.Async.DeferredLock.prototype = {
+ __class__: MochiKit.Async.DeferredLock,
+ /** @id MochiKit.Async.DeferredLock.prototype.acquire */
+ acquire: function () {
+ var d = new MochiKit.Async.Deferred();
+ if (this.locked) {
+ this.waiting.push(d);
+ } else {
+ this.locked = true;
+ d.callback(this);
+ }
+ return d;
+ },
+ /** @id MochiKit.Async.DeferredLock.prototype.release */
+ release: function () {
+ if (!this.locked) {
+ throw TypeError("Tried to release an unlocked DeferredLock");
+ }
+ this.locked = false;
+ if (this.waiting.length > 0) {
+ this.locked = true;
+ this.waiting.shift().callback(this);
+ }
+ },
+ _nextId: MochiKit.Base.counter(),
+ repr: function () {
+ var state;
+ if (this.locked) {
+ state = 'locked, ' + this.waiting.length + ' waiting';
+ } else {
+ state = 'unlocked';
+ }
+ return 'DeferredLock(' + this.id + ', ' + state + ')';
+ },
+ toString: MochiKit.Base.forwardCall("repr")
+
+};
+
+/** @id MochiKit.Async.DeferredList */
+MochiKit.Async.DeferredList = function (list, /* optional */fireOnOneCallback, fireOnOneErrback, consumeErrors, canceller) {
+
+ // call parent constructor
+ MochiKit.Async.Deferred.apply(this, [canceller]);
+
+ this.list = list;
+ var resultList = [];
+ this.resultList = resultList;
+
+ this.finishedCount = 0;
+ this.fireOnOneCallback = fireOnOneCallback;
+ this.fireOnOneErrback = fireOnOneErrback;
+ this.consumeErrors = consumeErrors;
+
+ var cb = MochiKit.Base.bind(this._cbDeferred, this);
+ for (var i = 0; i < list.length; i++) {
+ var d = list[i];
+ resultList.push(undefined);
+ d.addCallback(cb, i, true);
+ d.addErrback(cb, i, false);
+ }
+
+ if (list.length === 0 && !fireOnOneCallback) {
+ this.callback(this.resultList);
+ }
+
+};
+
+MochiKit.Async.DeferredList.prototype = new MochiKit.Async.Deferred();
+
+MochiKit.Async.DeferredList.prototype._cbDeferred = function (index, succeeded, result) {
+ this.resultList[index] = [succeeded, result];
+ this.finishedCount += 1;
+ if (this.fired == -1) {
+ if (succeeded && this.fireOnOneCallback) {
+ this.callback([index, result]);
+ } else if (!succeeded && this.fireOnOneErrback) {
+ this.errback(result);
+ } else if (this.finishedCount == this.list.length) {
+ this.callback(this.resultList);
+ }
+ }
+ if (!succeeded && this.consumeErrors) {
+ result = null;
+ }
+ return result;
+};
+
+/** @id MochiKit.Async.gatherResults */
+MochiKit.Async.gatherResults = function (deferredList) {
+ var d = new MochiKit.Async.DeferredList(deferredList, false, true, false);
+ d.addCallback(function (results) {
+ var ret = [];
+ for (var i = 0; i < results.length; i++) {
+ ret.push(results[i][1]);
+ }
+ return ret;
+ });
+ return d;
+};
+
+/** @id MochiKit.Async.maybeDeferred */
+MochiKit.Async.maybeDeferred = function (func) {
+ var self = MochiKit.Async;
+ var result;
+ try {
+ var r = func.apply(null, MochiKit.Base.extend([], arguments, 1));
+ if (r instanceof self.Deferred) {
+ result = r;
+ } else if (r instanceof Error) {
+ result = self.fail(r);
+ } else {
+ result = self.succeed(r);
+ }
+ } catch (e) {
+ result = self.fail(e);
+ }
+ return result;
+};
+
+
+MochiKit.Async.EXPORT = [
+ "AlreadyCalledError",
+ "CancelledError",
+ "BrowserComplianceError",
+ "GenericError",
+ "XMLHttpRequestError",
+ "Deferred",
+ "succeed",
+ "fail",
+ "getXMLHttpRequest",
+ "doSimpleXMLHttpRequest",
+ "loadJSONDoc",
+ "wait",
+ "callLater",
+ "sendXMLHttpRequest",
+ "DeferredLock",
+ "DeferredList",
+ "gatherResults",
+ "maybeDeferred"
+];
+
+MochiKit.Async.EXPORT_OK = [
+ "evalJSONRequest"
+];
+
+MochiKit.Async.__new__ = function () {
+ var m = MochiKit.Base;
+ var ne = m.partial(m._newNamedError, this);
+
+ ne("AlreadyCalledError",
+ /** @id MochiKit.Async.AlreadyCalledError */
+ function (deferred) {
+ /***
+
+ Raised by the Deferred if callback or errback happens
+ after it was already fired.
+
+ ***/
+ this.deferred = deferred;
+ }
+ );
+
+ ne("CancelledError",
+ /** @id MochiKit.Async.CancelledError */
+ function (deferred) {
+ /***
+
+ Raised by the Deferred cancellation mechanism.
+
+ ***/
+ this.deferred = deferred;
+ }
+ );
+
+ ne("BrowserComplianceError",
+ /** @id MochiKit.Async.BrowserComplianceError */
+ function (msg) {
+ /***
+
+ Raised when the JavaScript runtime is not capable of performing
+ the given function. Technically, this should really never be
+ raised because a non-conforming JavaScript runtime probably
+ isn't going to support exceptions in the first place.
+
+ ***/
+ this.message = msg;
+ }
+ );
+
+ ne("GenericError",
+ /** @id MochiKit.Async.GenericError */
+ function (msg) {
+ this.message = msg;
+ }
+ );
+
+ ne("XMLHttpRequestError",
+ /** @id MochiKit.Async.XMLHttpRequestError */
+ function (req, msg) {
+ /***
+
+ Raised when an XMLHttpRequest does not complete for any reason.
+
+ ***/
+ this.req = req;
+ this.message = msg;
+ try {
+ // Strange but true that this can raise in some cases.
+ this.number = req.status;
+ } catch (e) {
+ // pass
+ }
+ }
+ );
+
+
+ this.EXPORT_TAGS = {
+ ":common": this.EXPORT,
+ ":all": m.concat(this.EXPORT, this.EXPORT_OK)
+ };
+
+ m.nameFunctions(this);
+
+};
+
+MochiKit.Async.__new__();
+
+MochiKit.Base._exportSymbols(this, MochiKit.Async);
Index: mochitest/MochiKit/Base.js
===================================================================
RCS file: mochitest/MochiKit/Base.js
diff -N mochitest/MochiKit/Base.js
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/MochiKit/Base.js 25 Oct 2006 20:24:41 -0000
@@ -0,0 +1,1398 @@
+/***
+
+MochiKit.Base 1.4
+
+See for documentation, downloads, license, etc.
+
+(c) 2005 Bob Ippolito. All rights Reserved.
+
+***/
+
+if (typeof(dojo) != 'undefined') {
+ dojo.provide("MochiKit.Base");
+}
+if (typeof(MochiKit) == 'undefined') {
+ MochiKit = {};
+}
+if (typeof(MochiKit.Base) == 'undefined') {
+ MochiKit.Base = {};
+}
+if (typeof(MochiKit.__export__) == "undefined") {
+ MochiKit.__export__ = (MochiKit.__compat__ ||
+ (typeof(JSAN) == 'undefined' && typeof(dojo) == 'undefined')
+ );
+}
+
+MochiKit.Base.VERSION = "1.4";
+MochiKit.Base.NAME = "MochiKit.Base";
+/** @id MochiKit.Base.update */
+MochiKit.Base.update = function (self, obj/*, ... */) {
+ if (self === null) {
+ self = {};
+ }
+ for (var i = 1; i < arguments.length; i++) {
+ var o = arguments[i];
+ if (typeof(o) != 'undefined' && o !== null) {
+ for (var k in o) {
+ self[k] = o[k];
+ }
+ }
+ }
+ return self;
+};
+
+MochiKit.Base.update(MochiKit.Base, {
+ __repr__: function () {
+ return "[" + this.NAME + " " + this.VERSION + "]";
+ },
+
+ toString: function () {
+ return this.__repr__();
+ },
+
+ /** @id MochiKit.Base.camelize */
+ camelize: function (selector) {
+ /* from dojo.style.toCamelCase */
+ var arr = selector.split('-');
+ var cc = arr[0];
+ for (var i = 1; i < arr.length; i++) {
+ cc += arr[i].charAt(0).toUpperCase() + arr[i].substring(1);
+ }
+ return cc;
+ },
+
+ /** @id MochiKit.Base.counter */
+ counter: function (n/* = 1 */) {
+ if (arguments.length === 0) {
+ n = 1;
+ }
+ return function () {
+ return n++;
+ };
+ },
+
+ /** @id MochiKit.Base.clone */
+ clone: function (obj) {
+ var me = arguments.callee;
+ if (arguments.length == 1) {
+ me.prototype = obj;
+ return new me();
+ }
+ },
+
+ _flattenArray: function (res, lst) {
+ for (var i = 0; i < lst.length; i++) {
+ var o = lst[i];
+ if (o instanceof Array) {
+ arguments.callee(res, o);
+ } else {
+ res.push(o);
+ }
+ }
+ return res;
+ },
+
+ /** @id MochiKit.Base.flattenArray */
+ flattenArray: function (lst) {
+ return MochiKit.Base._flattenArray([], lst);
+ },
+
+ /** @id MochiKit.Base.flattenArguments */
+ flattenArguments: function (lst/* ...*/) {
+ var res = [];
+ var m = MochiKit.Base;
+ var args = m.extend(null, arguments);
+ while (args.length) {
+ var o = args.shift();
+ if (o && typeof(o) == "object" && typeof(o.length) == "number") {
+ for (var i = o.length - 1; i >= 0; i--) {
+ args.unshift(o[i]);
+ }
+ } else {
+ res.push(o);
+ }
+ }
+ return res;
+ },
+
+ /** @id MochiKit.Base.extend */
+ extend: function (self, obj, /* optional */skip) {
+ // Extend an array with an array-like object starting
+ // from the skip index
+ if (!skip) {
+ skip = 0;
+ }
+ if (obj) {
+ // allow iterable fall-through, but skip the full isArrayLike
+ // check for speed, this is called often.
+ var l = obj.length;
+ if (typeof(l) != 'number' /* !isArrayLike(obj) */) {
+ if (typeof(MochiKit.Iter) != "undefined") {
+ obj = MochiKit.Iter.list(obj);
+ l = obj.length;
+ } else {
+ throw new TypeError("Argument not an array-like and MochiKit.Iter not present");
+ }
+ }
+ if (!self) {
+ self = [];
+ }
+ for (var i = skip; i < l; i++) {
+ self.push(obj[i]);
+ }
+ }
+ // This mutates, but it's convenient to return because
+ // it's often used like a constructor when turning some
+ // ghetto array-like to a real array
+ return self;
+ },
+
+
+ /** @id MochiKit.Base.updatetree */
+ updatetree: function (self, obj/*, ...*/) {
+ if (self === null) {
+ self = {};
+ }
+ for (var i = 1; i < arguments.length; i++) {
+ var o = arguments[i];
+ if (typeof(o) != 'undefined' && o !== null) {
+ for (var k in o) {
+ var v = o[k];
+ if (typeof(self[k]) == 'object' && typeof(v) == 'object') {
+ arguments.callee(self[k], v);
+ } else {
+ self[k] = v;
+ }
+ }
+ }
+ }
+ return self;
+ },
+
+ /** @id MochiKit.Base.setdefault */
+ setdefault: function (self, obj/*, ...*/) {
+ if (self === null) {
+ self = {};
+ }
+ for (var i = 1; i < arguments.length; i++) {
+ var o = arguments[i];
+ for (var k in o) {
+ if (!(k in self)) {
+ self[k] = o[k];
+ }
+ }
+ }
+ return self;
+ },
+
+ /** @id MochiKit.Base.keys */
+ keys: function (obj) {
+ var rval = [];
+ for (var prop in obj) {
+ rval.push(prop);
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Base.values */
+ values: function (obj) {
+ var rval = [];
+ for (var prop in obj) {
+ rval.push(obj[prop]);
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Base.items */
+ items: function (obj) {
+ var rval = [];
+ var e;
+ for (var prop in obj) {
+ var v;
+ try {
+ v = obj[prop];
+ } catch (e) {
+ continue;
+ }
+ rval.push([prop, v]);
+ }
+ return rval;
+ },
+
+
+ _newNamedError: function (module, name, func) {
+ func.prototype = new MochiKit.Base.NamedError(module.NAME + "." + name);
+ module[name] = func;
+ },
+
+
+ /** @id MochiKit.Base.operator */
+ operator: {
+ // unary logic operators
+ /** @id MochiKit.Base.truth */
+ truth: function (a) { return !!a; },
+ /** @id MochiKit.Base.lognot */
+ lognot: function (a) { return !a; },
+ /** @id MochiKit.Base.identity */
+ identity: function (a) { return a; },
+
+ // bitwise unary operators
+ /** @id MochiKit.Base.not */
+ not: function (a) { return ~a; },
+ /** @id MochiKit.Base.neg */
+ neg: function (a) { return -a; },
+
+ // binary operators
+ /** @id MochiKit.Base.add */
+ add: function (a, b) { return a + b; },
+ /** @id MochiKit.Base.sub */
+ sub: function (a, b) { return a - b; },
+ /** @id MochiKit.Base.div */
+ div: function (a, b) { return a / b; },
+ /** @id MochiKit.Base.mod */
+ mod: function (a, b) { return a % b; },
+ /** @id MochiKit.Base.mul */
+ mul: function (a, b) { return a * b; },
+
+ // bitwise binary operators
+ /** @id MochiKit.Base.and */
+ and: function (a, b) { return a & b; },
+ /** @id MochiKit.Base.or */
+ or: function (a, b) { return a | b; },
+ /** @id MochiKit.Base.xor */
+ xor: function (a, b) { return a ^ b; },
+ /** @id MochiKit.Base.lshift */
+ lshift: function (a, b) { return a << b; },
+ /** @id MochiKit.Base.rshift */
+ rshift: function (a, b) { return a >> b; },
+ /** @id MochiKit.Base.zrshift */
+ zrshift: function (a, b) { return a >>> b; },
+
+ // near-worthless built-in comparators
+ /** @id MochiKit.Base.eq */
+ eq: function (a, b) { return a == b; },
+ /** @id MochiKit.Base.ne */
+ ne: function (a, b) { return a != b; },
+ /** @id MochiKit.Base.gt */
+ gt: function (a, b) { return a > b; },
+ /** @id MochiKit.Base.ge */
+ ge: function (a, b) { return a >= b; },
+ /** @id MochiKit.Base.lt */
+ lt: function (a, b) { return a < b; },
+ /** @id MochiKit.Base.le */
+ le: function (a, b) { return a <= b; },
+
+ // strict built-in comparators
+ seq: function (a, b) { return a === b; },
+ sne: function (a, b) { return a !== b; },
+
+ // compare comparators
+ /** @id MochiKit.Base.ceq */
+ ceq: function (a, b) { return MochiKit.Base.compare(a, b) === 0; },
+ /** @id MochiKit.Base.cne */
+ cne: function (a, b) { return MochiKit.Base.compare(a, b) !== 0; },
+ /** @id MochiKit.Base.cgt */
+ cgt: function (a, b) { return MochiKit.Base.compare(a, b) == 1; },
+ /** @id MochiKit.Base.cge */
+ cge: function (a, b) { return MochiKit.Base.compare(a, b) != -1; },
+ /** @id MochiKit.Base.clt */
+ clt: function (a, b) { return MochiKit.Base.compare(a, b) == -1; },
+ /** @id MochiKit.Base.cle */
+ cle: function (a, b) { return MochiKit.Base.compare(a, b) != 1; },
+
+ // binary logical operators
+ /** @id MochiKit.Base.logand */
+ logand: function (a, b) { return a && b; },
+ /** @id MochiKit.Base.logor */
+ logor: function (a, b) { return a || b; },
+ /** @id MochiKit.Base.contains */
+ contains: function (a, b) { return b in a; }
+ },
+
+ /** @id MochiKit.Base.forwardCall */
+ forwardCall: function (func) {
+ return function () {
+ return this[func].apply(this, arguments);
+ };
+ },
+
+ /** @id MochiKit.Base.itemgetter */
+ itemgetter: function (func) {
+ return function (arg) {
+ return arg[func];
+ };
+ },
+
+ /** @id MochiKit.Base.typeMatcher */
+ typeMatcher: function (/* typ */) {
+ var types = {};
+ for (var i = 0; i < arguments.length; i++) {
+ var typ = arguments[i];
+ types[typ] = typ;
+ }
+ return function () {
+ for (var i = 0; i < arguments.length; i++) {
+ if (!(typeof(arguments[i]) in types)) {
+ return false;
+ }
+ }
+ return true;
+ };
+ },
+
+ /** @id MochiKit.Base.isNull */
+ isNull: function (/* ... */) {
+ for (var i = 0; i < arguments.length; i++) {
+ if (arguments[i] !== null) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ /** @id MochiKit.Base.isUndefinedOrNull */
+ isUndefinedOrNull: function (/* ... */) {
+ for (var i = 0; i < arguments.length; i++) {
+ var o = arguments[i];
+ if (!(typeof(o) == 'undefined' || o === null)) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ /** @id MochiKit.Base.isEmpty */
+ isEmpty: function (obj) {
+ return !MochiKit.Base.isNotEmpty.apply(this, arguments);
+ },
+
+ /** @id MochiKit.Base.isNotEmpty */
+ isNotEmpty: function (obj) {
+ for (var i = 0; i < arguments.length; i++) {
+ var o = arguments[i];
+ if (!(o && o.length)) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ /** @id MochiKit.Base.isArrayLike */
+ isArrayLike: function () {
+ for (var i = 0; i < arguments.length; i++) {
+ var o = arguments[i];
+ var typ = typeof(o);
+ if (
+ (typ != 'object' && !(typ == 'function' && typeof(o.item) == 'function')) ||
+ o === null ||
+ typeof(o.length) != 'number' ||
+ o.nodeType === 3
+ ) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ /** @id MochiKit.Base.isDateLike */
+ isDateLike: function () {
+ for (var i = 0; i < arguments.length; i++) {
+ var o = arguments[i];
+ if (typeof(o) != "object" || o === null
+ || typeof(o.getTime) != 'function') {
+ return false;
+ }
+ }
+ return true;
+ },
+
+
+ /** @id MochiKit.Base.xmap */
+ xmap: function (fn/*, obj... */) {
+ if (fn === null) {
+ return MochiKit.Base.extend(null, arguments, 1);
+ }
+ var rval = [];
+ for (var i = 1; i < arguments.length; i++) {
+ rval.push(fn(arguments[i]));
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Base.map */
+ map: function (fn, lst/*, lst... */) {
+ var m = MochiKit.Base;
+ var itr = MochiKit.Iter;
+ var isArrayLike = m.isArrayLike;
+ if (arguments.length <= 2) {
+ // allow an iterable to be passed
+ if (!isArrayLike(lst)) {
+ if (itr) {
+ // fast path for map(null, iterable)
+ lst = itr.list(lst);
+ if (fn === null) {
+ return lst;
+ }
+ } else {
+ throw new TypeError("Argument not an array-like and MochiKit.Iter not present");
+ }
+ }
+ // fast path for map(null, lst)
+ if (fn === null) {
+ return m.extend(null, lst);
+ }
+ // disabled fast path for map(fn, lst)
+ /*
+ if (false && typeof(Array.prototype.map) == 'function') {
+ // Mozilla fast-path
+ return Array.prototype.map.call(lst, fn);
+ }
+ */
+ var rval = [];
+ for (var i = 0; i < lst.length; i++) {
+ rval.push(fn(lst[i]));
+ }
+ return rval;
+ } else {
+ // default for map(null, ...) is zip(...)
+ if (fn === null) {
+ fn = Array;
+ }
+ var length = null;
+ for (i = 1; i < arguments.length; i++) {
+ // allow iterables to be passed
+ if (!isArrayLike(arguments[i])) {
+ if (itr) {
+ return itr.list(itr.imap.apply(null, arguments));
+ } else {
+ throw new TypeError("Argument not an array-like and MochiKit.Iter not present");
+ }
+ }
+ // find the minimum length
+ var l = arguments[i].length;
+ if (length === null || length > l) {
+ length = l;
+ }
+ }
+ rval = [];
+ for (i = 0; i < length; i++) {
+ var args = [];
+ for (var j = 1; j < arguments.length; j++) {
+ args.push(arguments[j][i]);
+ }
+ rval.push(fn.apply(this, args));
+ }
+ return rval;
+ }
+ },
+
+ /** @id MochiKit.Base.xfilter */
+ xfilter: function (fn/*, obj... */) {
+ var rval = [];
+ if (fn === null) {
+ fn = MochiKit.Base.operator.truth;
+ }
+ for (var i = 1; i < arguments.length; i++) {
+ var o = arguments[i];
+ if (fn(o)) {
+ rval.push(o);
+ }
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Base.filter */
+ filter: function (fn, lst, self) {
+ var rval = [];
+ // allow an iterable to be passed
+ var m = MochiKit.Base;
+ if (!m.isArrayLike(lst)) {
+ if (MochiKit.Iter) {
+ lst = MochiKit.Iter.list(lst);
+ } else {
+ throw new TypeError("Argument not an array-like and MochiKit.Iter not present");
+ }
+ }
+ if (fn === null) {
+ fn = m.operator.truth;
+ }
+ if (typeof(Array.prototype.filter) == 'function') {
+ // Mozilla fast-path
+ return Array.prototype.filter.call(lst, fn, self);
+ } else if (typeof(self) == 'undefined' || self === null) {
+ for (var i = 0; i < lst.length; i++) {
+ var o = lst[i];
+ if (fn(o)) {
+ rval.push(o);
+ }
+ }
+ } else {
+ for (i = 0; i < lst.length; i++) {
+ o = lst[i];
+ if (fn.call(self, o)) {
+ rval.push(o);
+ }
+ }
+ }
+ return rval;
+ },
+
+
+ _wrapDumbFunction: function (func) {
+ return function () {
+ // fast path!
+ switch (arguments.length) {
+ case 0: return func();
+ case 1: return func(arguments[0]);
+ case 2: return func(arguments[0], arguments[1]);
+ case 3: return func(arguments[0], arguments[1], arguments[2]);
+ }
+ var args = [];
+ for (var i = 0; i < arguments.length; i++) {
+ args.push("arguments[" + i + "]");
+ }
+ return eval("(func(" + args.join(",") + "))");
+ };
+ },
+
+ /** @id MochiKit.Base.methodcaller */
+ methodcaller: function (func/*, args... */) {
+ var args = MochiKit.Base.extend(null, arguments, 1);
+ if (typeof(func) == "function") {
+ return function (obj) {
+ return func.apply(obj, args);
+ };
+ } else {
+ return function (obj) {
+ return obj[func].apply(obj, args);
+ };
+ }
+ },
+
+ /** @id MochiKit.Base.method */
+ method: function (self, func) {
+ var m = MochiKit.Base;
+ return m.bind.apply(this, m.extend([func, self], arguments, 2));
+ },
+
+ /** @id MochiKit.Base.compose */
+ compose: function (f1, f2/*, f3, ... fN */) {
+ var fnlist = [];
+ var m = MochiKit.Base;
+ if (arguments.length === 0) {
+ throw new TypeError("compose() requires at least one argument");
+ }
+ for (var i = 0; i < arguments.length; i++) {
+ var fn = arguments[i];
+ if (typeof(fn) != "function") {
+ throw new TypeError(m.repr(fn) + " is not a function");
+ }
+ fnlist.push(fn);
+ }
+ return function () {
+ var args = arguments;
+ for (var i = fnlist.length - 1; i >= 0; i--) {
+ args = [fnlist[i].apply(this, args)];
+ }
+ return args[0];
+ };
+ },
+
+ /** @id MochiKit.Base.bind */
+ bind: function (func, self/* args... */) {
+ if (typeof(func) == "string") {
+ func = self[func];
+ }
+ var im_func = func.im_func;
+ var im_preargs = func.im_preargs;
+ var im_self = func.im_self;
+ var m = MochiKit.Base;
+ if (typeof(func) == "function" && typeof(func.apply) == "undefined") {
+ // this is for cases where JavaScript sucks ass and gives you a
+ // really dumb built-in function like alert() that doesn't have
+ // an apply
+ func = m._wrapDumbFunction(func);
+ }
+ if (typeof(im_func) != 'function') {
+ im_func = func;
+ }
+ if (typeof(self) != 'undefined') {
+ im_self = self;
+ }
+ if (typeof(im_preargs) == 'undefined') {
+ im_preargs = [];
+ } else {
+ im_preargs = im_preargs.slice();
+ }
+ m.extend(im_preargs, arguments, 2);
+ var newfunc = function () {
+ var args = arguments;
+ var me = arguments.callee;
+ if (me.im_preargs.length > 0) {
+ args = m.concat(me.im_preargs, args);
+ }
+ var self = me.im_self;
+ if (!self) {
+ self = this;
+ }
+ return me.im_func.apply(self, args);
+ };
+ newfunc.im_self = im_self;
+ newfunc.im_func = im_func;
+ newfunc.im_preargs = im_preargs;
+ return newfunc;
+ },
+
+ /** @id MochiKit.Base.bindMethods */
+ bindMethods: function (self) {
+ var bind = MochiKit.Base.bind;
+ for (var k in self) {
+ var func = self[k];
+ if (typeof(func) == 'function') {
+ self[k] = bind(func, self);
+ }
+ }
+ },
+
+ /** @id MochiKit.Base.registerComparator */
+ registerComparator: function (name, check, comparator, /* optional */ override) {
+ MochiKit.Base.comparatorRegistry.register(name, check, comparator, override);
+ },
+
+ _primitives: {'boolean': true, 'string': true, 'number': true},
+
+ /** @id MochiKit.Base.compare */
+ compare: function (a, b) {
+ if (a == b) {
+ return 0;
+ }
+ var aIsNull = (typeof(a) == 'undefined' || a === null);
+ var bIsNull = (typeof(b) == 'undefined' || b === null);
+ if (aIsNull && bIsNull) {
+ return 0;
+ } else if (aIsNull) {
+ return -1;
+ } else if (bIsNull) {
+ return 1;
+ }
+ var m = MochiKit.Base;
+ // bool, number, string have meaningful comparisons
+ var prim = m._primitives;
+ if (!(typeof(a) in prim && typeof(b) in prim)) {
+ try {
+ return m.comparatorRegistry.match(a, b);
+ } catch (e) {
+ if (e != m.NotFound) {
+ throw e;
+ }
+ }
+ }
+ if (a < b) {
+ return -1;
+ } else if (a > b) {
+ return 1;
+ }
+ // These types can't be compared
+ var repr = m.repr;
+ throw new TypeError(repr(a) + " and " + repr(b) + " can not be compared");
+ },
+
+ /** @id MochiKit.Base.compareDateLike */
+ compareDateLike: function (a, b) {
+ return MochiKit.Base.compare(a.getTime(), b.getTime());
+ },
+
+ /** @id MochiKit.Base.compareArrayLike */
+ compareArrayLike: function (a, b) {
+ var compare = MochiKit.Base.compare;
+ var count = a.length;
+ var rval = 0;
+ if (count > b.length) {
+ rval = 1;
+ count = b.length;
+ } else if (count < b.length) {
+ rval = -1;
+ }
+ for (var i = 0; i < count; i++) {
+ var cmp = compare(a[i], b[i]);
+ if (cmp) {
+ return cmp;
+ }
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Base.registerRepr */
+ registerRepr: function (name, check, wrap, /* optional */override) {
+ MochiKit.Base.reprRegistry.register(name, check, wrap, override);
+ },
+
+ /** @id MochiKit.Base.repr */
+ repr: function (o) {
+ if (typeof(o) == "undefined") {
+ return "undefined";
+ } else if (o === null) {
+ return "null";
+ }
+ try {
+ if (typeof(o.__repr__) == 'function') {
+ return o.__repr__();
+ } else if (typeof(o.repr) == 'function' && o.repr != arguments.callee) {
+ return o.repr();
+ }
+ return MochiKit.Base.reprRegistry.match(o);
+ } catch (e) {
+ if (typeof(o.NAME) == 'string' && (
+ o.toString == Function.prototype.toString ||
+ o.toString == Object.prototype.toString
+ )) {
+ return o.NAME;
+ }
+ }
+ try {
+ var ostring = (o + "");
+ } catch (e) {
+ return "[" + typeof(o) + "]";
+ }
+ if (typeof(o) == "function") {
+ o = ostring.replace(/^\s+/, "");
+ var idx = o.indexOf("{");
+ if (idx != -1) {
+ o = o.substr(0, idx) + "{...}";
+ }
+ }
+ return ostring;
+ },
+
+ /** @id MochiKit.Base.reprArrayLike */
+ reprArrayLike: function (o) {
+ var m = MochiKit.Base;
+ return "[" + m.map(m.repr, o).join(", ") + "]";
+ },
+
+ /** @id MochiKit.Base.reprString */
+ reprString: function (o) {
+ return ('"' + o.replace(/(["\\])/g, '\\$1') + '"'
+ ).replace(/[\f]/g, "\\f"
+ ).replace(/[\b]/g, "\\b"
+ ).replace(/[\n]/g, "\\n"
+ ).replace(/[\t]/g, "\\t"
+ ).replace(/[\r]/g, "\\r");
+ },
+
+ /** @id MochiKit.Base.reprNumber */
+ reprNumber: function (o) {
+ return o + "";
+ },
+
+ /** @id MochiKit.Base.registerJSON */
+ registerJSON: function (name, check, wrap, /* optional */override) {
+ MochiKit.Base.jsonRegistry.register(name, check, wrap, override);
+ },
+
+
+ /** @id MochiKit.Base.evalJSON */
+ evalJSON: function () {
+ return eval("(" + arguments[0] + ")");
+ },
+
+ /** @id MochiKit.Base.serializeJSON */
+ serializeJSON: function (o) {
+ var objtype = typeof(o);
+ if (objtype == "number" || objtype == "boolean") {
+ return o + "";
+ } else if (o === null) {
+ return "null";
+ }
+ var m = MochiKit.Base;
+ var reprString = m.reprString;
+ if (objtype == "string") {
+ return reprString(o);
+ }
+ // recurse
+ var me = arguments.callee;
+ // short-circuit for objects that support "json" serialization
+ // if they return "self" then just pass-through...
+ var newObj;
+ if (typeof(o.__json__) == "function") {
+ newObj = o.__json__();
+ if (o !== newObj) {
+ return me(newObj);
+ }
+ }
+ if (typeof(o.json) == "function") {
+ newObj = o.json();
+ if (o !== newObj) {
+ return me(newObj);
+ }
+ }
+ // array
+ if (objtype != "function" && typeof(o.length) == "number") {
+ var res = [];
+ for (var i = 0; i < o.length; i++) {
+ var val = me(o[i]);
+ if (typeof(val) != "string") {
+ val = "undefined";
+ }
+ res.push(val);
+ }
+ return "[" + res.join(", ") + "]";
+ }
+ // look in the registry
+ try {
+ newObj = m.jsonRegistry.match(o);
+ if (o !== newObj) {
+ return me(newObj);
+ }
+ } catch (e) {
+ if (e != m.NotFound) {
+ // something really bad happened
+ throw e;
+ }
+ }
+ // undefined is outside of the spec
+ if (objtype == "undefined") {
+ throw new TypeError("undefined can not be serialized as JSON");
+ }
+ // it's a function with no adapter, bad
+ if (objtype == "function") {
+ return null;
+ }
+ // generic object code path
+ res = [];
+ for (var k in o) {
+ var useKey;
+ if (typeof(k) == "number") {
+ useKey = '"' + k + '"';
+ } else if (typeof(k) == "string") {
+ useKey = reprString(k);
+ } else {
+ // skip non-string or number keys
+ continue;
+ }
+ val = me(o[k]);
+ if (typeof(val) != "string") {
+ // skip non-serializable values
+ continue;
+ }
+ res.push(useKey + ":" + val);
+ }
+ return "{" + res.join(", ") + "}";
+ },
+
+
+ /** @id MochiKit.Base.objEqual */
+ objEqual: function (a, b) {
+ return (MochiKit.Base.compare(a, b) === 0);
+ },
+
+ /** @id MochiKit.Base.arrayEqual */
+ arrayEqual: function (self, arr) {
+ if (self.length != arr.length) {
+ return false;
+ }
+ return (MochiKit.Base.compare(self, arr) === 0);
+ },
+
+ /** @id MochiKit.Base.concat */
+ concat: function (/* lst... */) {
+ var rval = [];
+ var extend = MochiKit.Base.extend;
+ for (var i = 0; i < arguments.length; i++) {
+ extend(rval, arguments[i]);
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Base.keyComparator */
+ keyComparator: function (key/* ... */) {
+ // fast-path for single key comparisons
+ var m = MochiKit.Base;
+ var compare = m.compare;
+ if (arguments.length == 1) {
+ return function (a, b) {
+ return compare(a[key], b[key]);
+ };
+ }
+ var compareKeys = m.extend(null, arguments);
+ return function (a, b) {
+ var rval = 0;
+ // keep comparing until something is inequal or we run out of
+ // keys to compare
+ for (var i = 0; (rval === 0) && (i < compareKeys.length); i++) {
+ var key = compareKeys[i];
+ rval = compare(a[key], b[key]);
+ }
+ return rval;
+ };
+ },
+
+ /** @id MochiKit.Base.reverseKeyComparator */
+ reverseKeyComparator: function (key) {
+ var comparator = MochiKit.Base.keyComparator.apply(this, arguments);
+ return function (a, b) {
+ return comparator(b, a);
+ };
+ },
+
+ /** @id MochiKit.Base.partial */
+ partial: function (func) {
+ var m = MochiKit.Base;
+ return m.bind.apply(this, m.extend([func, undefined], arguments, 1));
+ },
+
+ /** @id MochiKit.Base.listMinMax */
+ listMinMax: function (which, lst) {
+ if (lst.length === 0) {
+ return null;
+ }
+ var cur = lst[0];
+ var compare = MochiKit.Base.compare;
+ for (var i = 1; i < lst.length; i++) {
+ var o = lst[i];
+ if (compare(o, cur) == which) {
+ cur = o;
+ }
+ }
+ return cur;
+ },
+
+ /** @id MochiKit.Base.objMax */
+ objMax: function (/* obj... */) {
+ return MochiKit.Base.listMinMax(1, arguments);
+ },
+
+ /** @id MochiKit.Base.objMin */
+ objMin: function (/* obj... */) {
+ return MochiKit.Base.listMinMax(-1, arguments);
+ },
+
+ /** @id MochiKit.Base.findIdentical */
+ findIdentical: function (lst, value, start/* = 0 */, /* optional */end) {
+ if (typeof(end) == "undefined" || end === null) {
+ end = lst.length;
+ }
+ if (typeof(start) == "undefined" || start === null) {
+ start = 0;
+ }
+ for (var i = start; i < end; i++) {
+ if (lst[i] === value) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ /** @id MochiKit.Base.mean */
+ mean: function(/* lst... */) {
+ /* http://www.nist.gov/dads/HTML/mean.html */
+ var sum = 0;
+
+ var m = MochiKit.Base;
+ var args = m.extend(null, arguments);
+ var count = args.length;
+
+ while (args.length) {
+ var o = args.shift();
+ if (o && typeof(o) == "object" && typeof(o.length) == "number") {
+ count += o.length - 1;
+ for (var i = o.length - 1; i >= 0; i--) {
+ sum += o[i];
+ }
+ } else {
+ sum += o;
+ }
+ }
+
+ if (count <= 0) {
+ throw new TypeError('mean() requires at least one argument');
+ }
+
+ return sum/count;
+ },
+
+ /** @id MochiKit.Base.median */
+ median: function(/* lst... */) {
+ /* http://www.nist.gov/dads/HTML/median.html */
+ var data = MochiKit.Base.flattenArguments(arguments);
+ if (data.length === 0) {
+ throw new TypeError('median() requires at least one argument');
+ }
+ data.sort(compare);
+ if (data.length % 2 == 0) {
+ var upper = data.length / 2;
+ return (data[upper] + data[upper - 1]) / 2;
+ } else {
+ return data[(data.length - 1) / 2];
+ }
+ },
+
+ /** @id MochiKit.Base.findValue */
+ findValue: function (lst, value, start/* = 0 */, /* optional */end) {
+ if (typeof(end) == "undefined" || end === null) {
+ end = lst.length;
+ }
+ if (typeof(start) == "undefined" || start === null) {
+ start = 0;
+ }
+ var cmp = MochiKit.Base.compare;
+ for (var i = start; i < end; i++) {
+ if (cmp(lst[i], value) === 0) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ /** @id MochiKit.Base.nodeWalk */
+ nodeWalk: function (node, visitor) {
+ var nodes = [node];
+ var extend = MochiKit.Base.extend;
+ while (nodes.length) {
+ var res = visitor(nodes.shift());
+ if (res) {
+ extend(nodes, res);
+ }
+ }
+ },
+
+
+ /** @id MochiKit.Base.nameFunctions */
+ nameFunctions: function (namespace) {
+ var base = namespace.NAME;
+ if (typeof(base) == 'undefined') {
+ base = '';
+ } else {
+ base = base + '.';
+ }
+ for (var name in namespace) {
+ var o = namespace[name];
+ if (typeof(o) == 'function' && typeof(o.NAME) == 'undefined') {
+ try {
+ o.NAME = base + name;
+ } catch (e) {
+ // pass
+ }
+ }
+ }
+ },
+
+
+ /** @id MochiKit.Base.queryString */
+ queryString: function (names, values) {
+ // check to see if names is a string or a DOM element, and if
+ // MochiKit.DOM is available. If so, drop it like it's a form
+ // Ugliest conditional in MochiKit? Probably!
+ if (typeof(MochiKit.DOM) != "undefined" && arguments.length == 1
+ && (typeof(names) == "string" || (
+ typeof(names.nodeType) != "undefined" && names.nodeType > 0
+ ))
+ ) {
+ var kv = MochiKit.DOM.formContents(names);
+ names = kv[0];
+ values = kv[1];
+ } else if (arguments.length == 1) {
+ var o = names;
+ names = [];
+ values = [];
+ for (var k in o) {
+ var v = o[k];
+ if (typeof(v) == "function") {
+ continue;
+ } else if (typeof(v) != "string" &&
+ typeof(v.length) == "number") {
+ for (var i = 0; i < v.length; i++) {
+ names.push(k);
+ values.push(v[i]);
+ }
+ } else {
+ names.push(k);
+ values.push(v);
+ }
+ }
+ }
+ var rval = [];
+ var len = Math.min(names.length, values.length);
+ var urlEncode = MochiKit.Base.urlEncode;
+ for (var i = 0; i < len; i++) {
+ v = values[i];
+ if (typeof(v) != 'undefined' && v !== null) {
+ rval.push(urlEncode(names[i]) + "=" + urlEncode(v));
+ }
+ }
+ return rval.join("&");
+ },
+
+
+ /** @id MochiKit.Base.parseQueryString */
+ parseQueryString: function (encodedString, useArrays) {
+ // strip a leading '?' from the encoded string
+ var qstr = (encodedString[0] == "?") ? encodedString.substring(1) :
+ encodedString;
+ var pairs = qstr.replace(/\+/g, "%20").split(/(\&\;|\&\#38\;|\&|\&)/);
+ var o = {};
+ var decode;
+ if (typeof(decodeURIComponent) != "undefined") {
+ decode = decodeURIComponent;
+ } else {
+ decode = unescape;
+ }
+ if (useArrays) {
+ for (var i = 0; i < pairs.length; i++) {
+ var pair = pairs[i].split("=");
+ if (pair.length !== 2) {
+ continue;
+ }
+ var name = decode(pair[0]);
+ var arr = o[name];
+ if (!(arr instanceof Array)) {
+ arr = [];
+ o[name] = arr;
+ }
+ arr.push(decode(pair[1]));
+ }
+ } else {
+ for (i = 0; i < pairs.length; i++) {
+ pair = pairs[i].split("=");
+ if (pair.length !== 2) {
+ continue;
+ }
+ o[decode(pair[0])] = decode(pair[1]);
+ }
+ }
+ return o;
+ }
+});
+
+/** @id MochiKit.Base.AdapterRegistry */
+MochiKit.Base.AdapterRegistry = function () {
+ this.pairs = [];
+};
+
+MochiKit.Base.AdapterRegistry.prototype = {
+ /** @id MochiKit.Base.AdapterRegistry.prototype.register */
+ register: function (name, check, wrap, /* optional */ override) {
+ if (override) {
+ this.pairs.unshift([name, check, wrap]);
+ } else {
+ this.pairs.push([name, check, wrap]);
+ }
+ },
+
+ /** @id MochiKit.Base.AdapterRegistry.prototype.match */
+ match: function (/* ... */) {
+ for (var i = 0; i < this.pairs.length; i++) {
+ var pair = this.pairs[i];
+ if (pair[1].apply(this, arguments)) {
+ return pair[2].apply(this, arguments);
+ }
+ }
+ throw MochiKit.Base.NotFound;
+ },
+
+ /** @id MochiKit.Base.AdapterRegistry.prototype.unregister */
+ unregister: function (name) {
+ for (var i = 0; i < this.pairs.length; i++) {
+ var pair = this.pairs[i];
+ if (pair[0] == name) {
+ this.pairs.splice(i, 1);
+ return true;
+ }
+ }
+ return false;
+ }
+};
+
+
+MochiKit.Base.EXPORT = [
+ "flattenArray",
+ "noop",
+ "camelize",
+ "counter",
+ "clone",
+ "extend",
+ "update",
+ "updatetree",
+ "setdefault",
+ "keys",
+ "values",
+ "items",
+ "NamedError",
+ "operator",
+ "forwardCall",
+ "itemgetter",
+ "typeMatcher",
+ "isCallable",
+ "isUndefined",
+ "isUndefinedOrNull",
+ "isNull",
+ "isEmpty",
+ "isNotEmpty",
+ "isArrayLike",
+ "isDateLike",
+ "xmap",
+ "map",
+ "xfilter",
+ "filter",
+ "methodcaller",
+ "compose",
+ "bind",
+ "bindMethods",
+ "NotFound",
+ "AdapterRegistry",
+ "registerComparator",
+ "compare",
+ "registerRepr",
+ "repr",
+ "objEqual",
+ "arrayEqual",
+ "concat",
+ "keyComparator",
+ "reverseKeyComparator",
+ "partial",
+ "merge",
+ "listMinMax",
+ "listMax",
+ "listMin",
+ "objMax",
+ "objMin",
+ "nodeWalk",
+ "zip",
+ "urlEncode",
+ "queryString",
+ "serializeJSON",
+ "registerJSON",
+ "evalJSON",
+ "parseQueryString",
+ "findValue",
+ "findIdentical",
+ "flattenArguments",
+ "method",
+ "average",
+ "mean",
+ "median"
+];
+
+MochiKit.Base.EXPORT_OK = [
+ "nameFunctions",
+ "comparatorRegistry",
+ "reprRegistry",
+ "jsonRegistry",
+ "compareDateLike",
+ "compareArrayLike",
+ "reprArrayLike",
+ "reprString",
+ "reprNumber"
+];
+
+MochiKit.Base._exportSymbols = function (globals, module) {
+ if (!MochiKit.__export__) {
+ return;
+ }
+ var all = module.EXPORT_TAGS[":all"];
+ for (var i = 0; i < all.length; i++) {
+ globals[all[i]] = module[all[i]];
+ }
+};
+
+MochiKit.Base.__new__ = function () {
+ // A singleton raised when no suitable adapter is found
+ var m = this;
+
+ // convenience
+ /** @id MochiKit.Base.noop */
+ m.noop = m.operator.identity;
+
+ // Backwards compat
+ m.forward = m.forwardCall;
+ m.find = m.findValue;
+
+ if (typeof(encodeURIComponent) != "undefined") {
+ /** @id MochiKit.Base.urlEncode */
+ m.urlEncode = function (unencoded) {
+ return encodeURIComponent(unencoded).replace(/\'/g, '%27');
+ };
+ } else {
+ m.urlEncode = function (unencoded) {
+ return escape(unencoded
+ ).replace(/\+/g, '%2B'
+ ).replace(/\"/g,'%22'
+ ).rval.replace(/\'/g, '%27');
+ };
+ }
+
+ /** @id MochiKit.Base.NamedError */
+ m.NamedError = function (name) {
+ this.message = name;
+ this.name = name;
+ };
+ m.NamedError.prototype = new Error();
+ m.update(m.NamedError.prototype, {
+ repr: function () {
+ if (this.message && this.message != this.name) {
+ return this.name + "(" + m.repr(this.message) + ")";
+ } else {
+ return this.name + "()";
+ }
+ },
+ toString: m.forwardCall("repr")
+ });
+
+ /** @id MochiKit.Base.NotFound */
+ m.NotFound = new m.NamedError("MochiKit.Base.NotFound");
+
+
+ /** @id MochiKit.Base.listMax */
+ m.listMax = m.partial(m.listMinMax, 1);
+ /** @id MochiKit.Base.listMin */
+ m.listMin = m.partial(m.listMinMax, -1);
+
+ /** @id MochiKit.Base.isCallable */
+ m.isCallable = m.typeMatcher('function');
+ /** @id MochiKit.Base.isUndefined */
+ m.isUndefined = m.typeMatcher('undefined');
+
+ /** @id MochiKit.Base.merge */
+ m.merge = m.partial(m.update, null);
+ /** @id MochiKit.Base.zip */
+ m.zip = m.partial(m.map, null);
+
+ /** @id MochiKit.Base.average */
+ m.average = m.mean;
+
+ /** @id MochiKit.Base.comparatorRegistry */
+ m.comparatorRegistry = new m.AdapterRegistry();
+ m.registerComparator("dateLike", m.isDateLike, m.compareDateLike);
+ m.registerComparator("arrayLike", m.isArrayLike, m.compareArrayLike);
+
+ /** @id MochiKit.Base.reprRegistry */
+ m.reprRegistry = new m.AdapterRegistry();
+ m.registerRepr("arrayLike", m.isArrayLike, m.reprArrayLike);
+ m.registerRepr("string", m.typeMatcher("string"), m.reprString);
+ m.registerRepr("numbers", m.typeMatcher("number", "boolean"), m.reprNumber);
+
+ /** @id MochiKit.Base.jsonRegistry */
+ m.jsonRegistry = new m.AdapterRegistry();
+
+ var all = m.concat(m.EXPORT, m.EXPORT_OK);
+ m.EXPORT_TAGS = {
+ ":common": m.concat(m.EXPORT_OK),
+ ":all": all
+ };
+
+ m.nameFunctions(this);
+
+};
+
+MochiKit.Base.__new__();
+
+//
+// XXX: Internet Explorer blows
+//
+if (MochiKit.__export__) {
+ compare = MochiKit.Base.compare;
+ compose = MochiKit.Base.compose;
+ serializeJSON = MochiKit.Base.serializeJSON;
+}
+
+MochiKit.Base._exportSymbols(this, MochiKit.Base);
Index: mochitest/MochiKit/Color.js
===================================================================
RCS file: mochitest/MochiKit/Color.js
diff -N mochitest/MochiKit/Color.js
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/MochiKit/Color.js 25 Oct 2006 20:24:41 -0000
@@ -0,0 +1,902 @@
+/***
+
+MochiKit.Color 1.4
+
+See for documentation, downloads, license, etc.
+
+(c) 2005 Bob Ippolito and others. All rights Reserved.
+
+***/
+
+if (typeof(dojo) != 'undefined') {
+ dojo.provide('MochiKit.Color');
+ dojo.require('MochiKit.Base');
+ dojo.require('MochiKit.DOM');
+ dojo.require('MochiKit.Style');
+}
+
+if (typeof(JSAN) != 'undefined') {
+ JSAN.use("MochiKit.Base", []);
+ JSAN.use("MochiKit.DOM", []);
+ JSAN.use("MochiKit.Style", []);
+}
+
+try {
+ if (typeof(MochiKit.Base) == 'undefined') {
+ throw "";
+ }
+} catch (e) {
+ throw "MochiKit.Color depends on MochiKit.Base";
+}
+
+try {
+ if (typeof(MochiKit.Base) == 'undefined') {
+ throw "";
+ }
+} catch (e) {
+ throw "MochiKit.Color depends on MochiKit.DOM";
+}
+
+try {
+ if (typeof(MochiKit.Base) == 'undefined') {
+ throw "";
+ }
+} catch (e) {
+ throw "MochiKit.Color depends on MochiKit.Style";
+}
+
+if (typeof(MochiKit.Color) == "undefined") {
+ MochiKit.Color = {};
+}
+
+MochiKit.Color.NAME = "MochiKit.Color";
+MochiKit.Color.VERSION = "1.4";
+
+MochiKit.Color.__repr__ = function () {
+ return "[" + this.NAME + " " + this.VERSION + "]";
+};
+
+MochiKit.Color.toString = function () {
+ return this.__repr__();
+};
+
+
+/** @id MochiKit.Color.Color */
+MochiKit.Color.Color = function (red, green, blue, alpha) {
+ if (typeof(alpha) == 'undefined' || alpha === null) {
+ alpha = 1.0;
+ }
+ this.rgb = {
+ r: red,
+ g: green,
+ b: blue,
+ a: alpha
+ };
+};
+
+
+// Prototype methods
+
+MochiKit.Color.Color.prototype = {
+
+ __class__: MochiKit.Color.Color,
+
+ /** @id MochiKit.Color.Color.prototype.colorWithAlpha */
+ colorWithAlpha: function (alpha) {
+ var rgb = this.rgb;
+ var m = MochiKit.Color;
+ return m.Color.fromRGB(rgb.r, rgb.g, rgb.b, alpha);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.colorWithHue */
+ colorWithHue: function (hue) {
+ // get an HSL model, and set the new hue...
+ var hsl = this.asHSL();
+ hsl.h = hue;
+ var m = MochiKit.Color;
+ // convert back to RGB...
+ return m.Color.fromHSL(hsl);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.colorWithSaturation */
+ colorWithSaturation: function (saturation) {
+ // get an HSL model, and set the new hue...
+ var hsl = this.asHSL();
+ hsl.s = saturation;
+ var m = MochiKit.Color;
+ // convert back to RGB...
+ return m.Color.fromHSL(hsl);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.colorWithLightness */
+ colorWithLightness: function (lightness) {
+ // get an HSL model, and set the new hue...
+ var hsl = this.asHSL();
+ hsl.l = lightness;
+ var m = MochiKit.Color;
+ // convert back to RGB...
+ return m.Color.fromHSL(hsl);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.darkerColorWithLevel */
+ darkerColorWithLevel: function (level) {
+ var hsl = this.asHSL();
+ hsl.l = Math.max(hsl.l - level, 0);
+ var m = MochiKit.Color;
+ return m.Color.fromHSL(hsl);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.lighterColorWithLevel */
+ lighterColorWithLevel: function (level) {
+ var hsl = this.asHSL();
+ hsl.l = Math.min(hsl.l + level, 1);
+ var m = MochiKit.Color;
+ return m.Color.fromHSL(hsl);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.blendedColor */
+ blendedColor: function (other, /* optional */ fraction) {
+ if (typeof(fraction) == 'undefined' || fraction === null) {
+ fraction = 0.5;
+ }
+ var sf = 1.0 - fraction;
+ var s = this.rgb;
+ var d = other.rgb;
+ var df = fraction;
+ return MochiKit.Color.Color.fromRGB(
+ (s.r * sf) + (d.r * df),
+ (s.g * sf) + (d.g * df),
+ (s.b * sf) + (d.b * df),
+ (s.a * sf) + (d.a * df)
+ );
+ },
+
+ /** @id MochiKit.Color.Color.prototype.compareRGB */
+ compareRGB: function (other) {
+ var a = this.asRGB();
+ var b = other.asRGB();
+ return MochiKit.Base.compare(
+ [a.r, a.g, a.b, a.a],
+ [b.r, b.g, b.b, b.a]
+ );
+ },
+
+ /** @id MochiKit.Color.Color.prototype.isLight */
+ isLight: function () {
+ return this.asHSL().b > 0.5;
+ },
+
+ /** @id MochiKit.Color.Color.prototype.isDark */
+ isDark: function () {
+ return (!this.isLight());
+ },
+
+ /** @id MochiKit.Color.Color.prototype.toHSLString */
+ toHSLString: function () {
+ var c = this.asHSL();
+ var ccc = MochiKit.Color.clampColorComponent;
+ var rval = this._hslString;
+ if (!rval) {
+ var mid = (
+ ccc(c.h, 360).toFixed(0)
+ + "," + ccc(c.s, 100).toPrecision(4) + "%"
+ + "," + ccc(c.l, 100).toPrecision(4) + "%"
+ );
+ var a = c.a;
+ if (a >= 1) {
+ a = 1;
+ rval = "hsl(" + mid + ")";
+ } else {
+ if (a <= 0) {
+ a = 0;
+ }
+ rval = "hsla(" + mid + "," + a + ")";
+ }
+ this._hslString = rval;
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Color.Color.prototype.toRGBString */
+ toRGBString: function () {
+ var c = this.rgb;
+ var ccc = MochiKit.Color.clampColorComponent;
+ var rval = this._rgbString;
+ if (!rval) {
+ var mid = (
+ ccc(c.r, 255).toFixed(0)
+ + "," + ccc(c.g, 255).toFixed(0)
+ + "," + ccc(c.b, 255).toFixed(0)
+ );
+ if (c.a != 1) {
+ rval = "rgba(" + mid + "," + c.a + ")";
+ } else {
+ rval = "rgb(" + mid + ")";
+ }
+ this._rgbString = rval;
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Color.Color.prototype.asRGB */
+ asRGB: function () {
+ return MochiKit.Base.clone(this.rgb);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.toHexString */
+ toHexString: function () {
+ var m = MochiKit.Color;
+ var c = this.rgb;
+ var ccc = MochiKit.Color.clampColorComponent;
+ var rval = this._hexString;
+ if (!rval) {
+ rval = ("#" +
+ m.toColorPart(ccc(c.r, 255)) +
+ m.toColorPart(ccc(c.g, 255)) +
+ m.toColorPart(ccc(c.b, 255))
+ );
+ this._hexString = rval;
+ }
+ return rval;
+ },
+
+ /** @id MochiKit.Color.Color.prototype.asHSV */
+ asHSV: function () {
+ var hsv = this.hsv;
+ var c = this.rgb;
+ if (typeof(hsv) == 'undefined' || hsv === null) {
+ hsv = MochiKit.Color.rgbToHSV(this.rgb);
+ this.hsv = hsv;
+ }
+ return MochiKit.Base.clone(hsv);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.asHSL */
+ asHSL: function () {
+ var hsl = this.hsl;
+ var c = this.rgb;
+ if (typeof(hsl) == 'undefined' || hsl === null) {
+ hsl = MochiKit.Color.rgbToHSL(this.rgb);
+ this.hsl = hsl;
+ }
+ return MochiKit.Base.clone(hsl);
+ },
+
+ /** @id MochiKit.Color.Color.prototype.toString */
+ toString: function () {
+ return this.toRGBString();
+ },
+
+ /** @id MochiKit.Color.Color.prototype.repr */
+ repr: function () {
+ var c = this.rgb;
+ var col = [c.r, c.g, c.b, c.a];
+ return this.__class__.NAME + "(" + col.join(", ") + ")";
+ }
+
+};
+
+// Constructor methods
+
+MochiKit.Base.update(MochiKit.Color.Color, {
+ /** @id MochiKit.Color.Color.fromRGB */
+ fromRGB: function (red, green, blue, alpha) {
+ // designated initializer
+ var Color = MochiKit.Color.Color;
+ if (arguments.length == 1) {
+ var rgb = red;
+ red = rgb.r;
+ green = rgb.g;
+ blue = rgb.b;
+ if (typeof(rgb.a) == 'undefined') {
+ alpha = undefined;
+ } else {
+ alpha = rgb.a;
+ }
+ }
+ return new Color(red, green, blue, alpha);
+ },
+
+ /** @id MochiKit.Color.Color.fromHSL */
+ fromHSL: function (hue, saturation, lightness, alpha) {
+ var m = MochiKit.Color;
+ return m.Color.fromRGB(m.hslToRGB.apply(m, arguments));
+ },
+
+ /** @id MochiKit.Color.Color.fromHSV */
+ fromHSV: function (hue, saturation, value, alpha) {
+ var m = MochiKit.Color;
+ return m.Color.fromRGB(m.hsvToRGB.apply(m, arguments));
+ },
+
+ /** @id MochiKit.Color.Color.fromName */
+ fromName: function (name) {
+ var Color = MochiKit.Color.Color;
+ // Opera 9 seems to "quote" named colors(?!)
+ if (name.charAt(0) == '"') {
+ name = name.substr(1, name.length - 2);
+ }
+ var htmlColor = Color._namedColors[name.toLowerCase()];
+ if (typeof(htmlColor) == 'string') {
+ return Color.fromHexString(htmlColor);
+ } else if (name == "transparent") {
+ return Color.transparentColor();
+ }
+ return null;
+ },
+
+ /** @id MochiKit.Color.Color.fromString */
+ fromString: function (colorString) {
+ var self = MochiKit.Color.Color;
+ var three = colorString.substr(0, 3);
+ if (three == "rgb") {
+ return self.fromRGBString(colorString);
+ } else if (three == "hsl") {
+ return self.fromHSLString(colorString);
+ } else if (colorString.charAt(0) == "#") {
+ return self.fromHexString(colorString);
+ }
+ return self.fromName(colorString);
+ },
+
+
+ /** @id MochiKit.Color.Color.fromHexString */
+ fromHexString: function (hexCode) {
+ if (hexCode.charAt(0) == '#') {
+ hexCode = hexCode.substring(1);
+ }
+ var components = [];
+ var i, hex;
+ if (hexCode.length == 3) {
+ for (i = 0; i < 3; i++) {
+ hex = hexCode.substr(i, 1);
+ components.push(parseInt(hex + hex, 16) / 255.0);
+ }
+ } else {
+ for (i = 0; i < 6; i += 2) {
+ hex = hexCode.substr(i, 2);
+ components.push(parseInt(hex, 16) / 255.0);
+ }
+ }
+ var Color = MochiKit.Color.Color;
+ return Color.fromRGB.apply(Color, components);
+ },
+
+
+ _fromColorString: function (pre, method, scales, colorCode) {
+ // parses either HSL or RGB
+ if (colorCode.indexOf(pre) === 0) {
+ colorCode = colorCode.substring(colorCode.indexOf("(", 3) + 1, colorCode.length - 1);
+ }
+ var colorChunks = colorCode.split(/\s*,\s*/);
+ var colorFloats = [];
+ for (var i = 0; i < colorChunks.length; i++) {
+ var c = colorChunks[i];
+ var val;
+ var three = c.substring(c.length - 3);
+ if (c.charAt(c.length - 1) == '%') {
+ val = 0.01 * parseFloat(c.substring(0, c.length - 1));
+ } else if (three == "deg") {
+ val = parseFloat(c) / 360.0;
+ } else if (three == "rad") {
+ val = parseFloat(c) / (Math.PI * 2);
+ } else {
+ val = scales[i] * parseFloat(c);
+ }
+ colorFloats.push(val);
+ }
+ return this[method].apply(this, colorFloats);
+ },
+
+ /** @id MochiKit.Color.Color.fromComputedStyle */
+ fromComputedStyle: function (elem, style) {
+ var d = MochiKit.DOM;
+ var cls = MochiKit.Color.Color;
+ for (elem = d.getElement(elem); elem; elem = elem.parentNode) {
+ var actualColor = MochiKit.Style.computedStyle.apply(d, arguments);
+ if (!actualColor) {
+ continue;
+ }
+ var color = cls.fromString(actualColor);
+ if (!color) {
+ break;
+ }
+ if (color.asRGB().a > 0) {
+ return color;
+ }
+ }
+ return null;
+ },
+
+ /** @id MochiKit.Color.Color.fromBackground */
+ fromBackground: function (elem) {
+ var cls = MochiKit.Color.Color;
+ return cls.fromComputedStyle(
+ elem, "backgroundColor", "background-color") || cls.whiteColor();
+ },
+
+ /** @id MochiKit.Color.Color.fromText */
+ fromText: function (elem) {
+ var cls = MochiKit.Color.Color;
+ return cls.fromComputedStyle(
+ elem, "color", "color") || cls.blackColor();
+ },
+
+ /** @id MochiKit.Color.Color.namedColors */
+ namedColors: function () {
+ return MochiKit.Base.clone(MochiKit.Color.Color._namedColors);
+ }
+});
+
+
+// Module level functions
+
+MochiKit.Base.update(MochiKit.Color, {
+ /** @id MochiKit.Color.clampColorComponent */
+ clampColorComponent: function (v, scale) {
+ v *= scale;
+ if (v < 0) {
+ return 0;
+ } else if (v > scale) {
+ return scale;
+ } else {
+ return v;
+ }
+ },
+
+ _hslValue: function (n1, n2, hue) {
+ if (hue > 6.0) {
+ hue -= 6.0;
+ } else if (hue < 0.0) {
+ hue += 6.0;
+ }
+ var val;
+ if (hue < 1.0) {
+ val = n1 + (n2 - n1) * hue;
+ } else if (hue < 3.0) {
+ val = n2;
+ } else if (hue < 4.0) {
+ val = n1 + (n2 - n1) * (4.0 - hue);
+ } else {
+ val = n1;
+ }
+ return val;
+ },
+
+ /** @id MochiKit.Color.hsvToRGB */
+ hsvToRGB: function (hue, saturation, value, alpha) {
+ if (arguments.length == 1) {
+ var hsv = hue;
+ hue = hsv.h;
+ saturation = hsv.s;
+ value = hsv.v;
+ alpha = hsv.a;
+ }
+ var red;
+ var green;
+ var blue;
+ if (saturation === 0) {
+ red = 0;
+ green = 0;
+ blue = 0;
+ } else {
+ var i = Math.floor(hue * 6);
+ var f = (hue * 6) - i;
+ var p = value * (1 - saturation);
+ var q = value * (1 - (saturation * f));
+ var t = value * (1 - (saturation * (1 - f)));
+ switch (i) {
+ case 1: red = q; green = value; blue = p; break;
+ case 2: red = p; green = value; blue = t; break;
+ case 3: red = p; green = q; blue = value; break;
+ case 4: red = t; green = p; blue = value; break;
+ case 5: red = value; green = p; blue = q; break;
+ case 6: // fall through
+ case 0: red = value; green = t; blue = p; break;
+ }
+ }
+ return {
+ r: red,
+ g: green,
+ b: blue,
+ a: alpha
+ };
+ },
+
+ /** @id MochiKit.Color.hslToRGB */
+ hslToRGB: function (hue, saturation, lightness, alpha) {
+ if (arguments.length == 1) {
+ var hsl = hue;
+ hue = hsl.h;
+ saturation = hsl.s;
+ lightness = hsl.l;
+ alpha = hsl.a;
+ }
+ var red;
+ var green;
+ var blue;
+ if (saturation === 0) {
+ red = lightness;
+ green = lightness;
+ blue = lightness;
+ } else {
+ var m2;
+ if (lightness <= 0.5) {
+ m2 = lightness * (1.0 + saturation);
+ } else {
+ m2 = lightness + saturation - (lightness * saturation);
+ }
+ var m1 = (2.0 * lightness) - m2;
+ var f = MochiKit.Color._hslValue;
+ var h6 = hue * 6.0;
+ red = f(m1, m2, h6 + 2);
+ green = f(m1, m2, h6);
+ blue = f(m1, m2, h6 - 2);
+ }
+ return {
+ r: red,
+ g: green,
+ b: blue,
+ a: alpha
+ };
+ },
+
+ /** @id MochiKit.Color.rgbToHSV */
+ rgbToHSV: function (red, green, blue, alpha) {
+ if (arguments.length == 1) {
+ var rgb = red;
+ red = rgb.r;
+ green = rgb.g;
+ blue = rgb.b;
+ alpha = rgb.a;
+ }
+ var max = Math.max(Math.max(red, green), blue);
+ var min = Math.min(Math.min(red, green), blue);
+ var hue;
+ var saturation;
+ var value = max;
+ if (min == max) {
+ hue = 0;
+ saturation = 0;
+ } else {
+ var delta = (max - min);
+ saturation = delta / max;
+
+ if (red == max) {
+ hue = (green - blue) / delta;
+ } else if (green == max) {
+ hue = 2 + ((blue - red) / delta);
+ } else {
+ hue = 4 + ((red - green) / delta);
+ }
+ hue /= 6;
+ if (hue < 0) {
+ hue += 1;
+ }
+ if (hue > 1) {
+ hue -= 1;
+ }
+ }
+ return {
+ h: hue,
+ s: saturation,
+ v: value,
+ a: alpha
+ };
+ },
+
+ /** @id MochiKit.Color.rgbToHSL */
+ rgbToHSL: function (red, green, blue, alpha) {
+ if (arguments.length == 1) {
+ var rgb = red;
+ red = rgb.r;
+ green = rgb.g;
+ blue = rgb.b;
+ alpha = rgb.a;
+ }
+ var max = Math.max(red, Math.max(green, blue));
+ var min = Math.min(red, Math.min(green, blue));
+ var hue;
+ var saturation;
+ var lightness = (max + min) / 2.0;
+ var delta = max - min;
+ if (delta === 0) {
+ hue = 0;
+ saturation = 0;
+ } else {
+ if (lightness <= 0.5) {
+ saturation = delta / (max + min);
+ } else {
+ saturation = delta / (2 - max - min);
+ }
+ if (red == max) {
+ hue = (green - blue) / delta;
+ } else if (green == max) {
+ hue = 2 + ((blue - red) / delta);
+ } else {
+ hue = 4 + ((red - green) / delta);
+ }
+ hue /= 6;
+ if (hue < 0) {
+ hue += 1;
+ }
+ if (hue > 1) {
+ hue -= 1;
+ }
+
+ }
+ return {
+ h: hue,
+ s: saturation,
+ l: lightness,
+ a: alpha
+ };
+ },
+
+ /** @id MochiKit.Color.toColorPart */
+ toColorPart: function (num) {
+ num = Math.round(num);
+ var digits = num.toString(16);
+ if (num < 16) {
+ return '0' + digits;
+ }
+ return digits;
+ },
+
+ __new__: function () {
+ var m = MochiKit.Base;
+ /** @id MochiKit.Color.fromRGBString */
+ this.Color.fromRGBString = m.bind(
+ this.Color._fromColorString, this.Color, "rgb", "fromRGB",
+ [1.0/255.0, 1.0/255.0, 1.0/255.0, 1]
+ );
+ /** @id MochiKit.Color.fromHSLString */
+ this.Color.fromHSLString = m.bind(
+ this.Color._fromColorString, this.Color, "hsl", "fromHSL",
+ [1.0/360.0, 0.01, 0.01, 1]
+ );
+
+ var third = 1.0 / 3.0;
+ /** @id MochiKit.Color.colors */
+ var colors = {
+ // NSColor colors plus transparent
+ /** @id MochiKit.Color.blackColor */
+ black: [0, 0, 0],
+ /** @id MochiKit.Color.blueColor */
+ blue: [0, 0, 1],
+ /** @id MochiKit.Color.brownColor */
+ brown: [0.6, 0.4, 0.2],
+ /** @id MochiKit.Color.cyanColor */
+ cyan: [0, 1, 1],
+ /** @id MochiKit.Color.darkGrayColor */
+ darkGray: [third, third, third],
+ /** @id MochiKit.Color.grayColor */
+ gray: [0.5, 0.5, 0.5],
+ /** @id MochiKit.Color.greenColor */
+ green: [0, 1, 0],
+ /** @id MochiKit.Color.lightGrayColor */
+ lightGray: [2 * third, 2 * third, 2 * third],
+ /** @id MochiKit.Color.magentaColor */
+ magenta: [1, 0, 1],
+ /** @id MochiKit.Color.orangeColor */
+ orange: [1, 0.5, 0],
+ /** @id MochiKit.Color.purpleColor */
+ purple: [0.5, 0, 0.5],
+ /** @id MochiKit.Color.redColor */
+ red: [1, 0, 0],
+ /** @id MochiKit.Color.transparentColor */
+ transparent: [0, 0, 0, 0],
+ /** @id MochiKit.Color.whiteColor */
+ white: [1, 1, 1],
+ /** @id MochiKit.Color.yellowColor */
+ yellow: [1, 1, 0]
+ };
+
+ var makeColor = function (name, r, g, b, a) {
+ var rval = this.fromRGB(r, g, b, a);
+ this[name] = function () { return rval; };
+ return rval;
+ };
+
+ for (var k in colors) {
+ var name = k + "Color";
+ var bindArgs = m.concat(
+ [makeColor, this.Color, name],
+ colors[k]
+ );
+ this.Color[name] = m.bind.apply(null, bindArgs);
+ }
+
+ var isColor = function () {
+ for (var i = 0; i < arguments.length; i++) {
+ if (!(arguments[i] instanceof Color)) {
+ return false;
+ }
+ }
+ return true;
+ };
+
+ var compareColor = function (a, b) {
+ return a.compareRGB(b);
+ };
+
+ m.nameFunctions(this);
+
+ m.registerComparator(this.Color.NAME, isColor, compareColor);
+
+ this.EXPORT_TAGS = {
+ ":common": this.EXPORT,
+ ":all": m.concat(this.EXPORT, this.EXPORT_OK)
+ };
+
+ }
+});
+
+MochiKit.Color.EXPORT = [
+ "Color"
+];
+
+MochiKit.Color.EXPORT_OK = [
+ "clampColorComponent",
+ "rgbToHSL",
+ "hslToRGB",
+ "rgbToHSV",
+ "hsvToRGB",
+ "toColorPart"
+];
+
+MochiKit.Color.__new__();
+
+MochiKit.Base._exportSymbols(this, MochiKit.Color);
+
+// Full table of css3 X11 colors
+
+MochiKit.Color.Color._namedColors = {
+ aliceblue: "#f0f8ff",
+ antiquewhite: "#faebd7",
+ aqua: "#00ffff",
+ aquamarine: "#7fffd4",
+ azure: "#f0ffff",
+ beige: "#f5f5dc",
+ bisque: "#ffe4c4",
+ black: "#000000",
+ blanchedalmond: "#ffebcd",
+ blue: "#0000ff",
+ blueviolet: "#8a2be2",
+ brown: "#a52a2a",
+ burlywood: "#deb887",
+ cadetblue: "#5f9ea0",
+ chartreuse: "#7fff00",
+ chocolate: "#d2691e",
+ coral: "#ff7f50",
+ cornflowerblue: "#6495ed",
+ cornsilk: "#fff8dc",
+ crimson: "#dc143c",
+ cyan: "#00ffff",
+ darkblue: "#00008b",
+ darkcyan: "#008b8b",
+ darkgoldenrod: "#b8860b",
+ darkgray: "#a9a9a9",
+ darkgreen: "#006400",
+ darkgrey: "#a9a9a9",
+ darkkhaki: "#bdb76b",
+ darkmagenta: "#8b008b",
+ darkolivegreen: "#556b2f",
+ darkorange: "#ff8c00",
+ darkorchid: "#9932cc",
+ darkred: "#8b0000",
+ darksalmon: "#e9967a",
+ darkseagreen: "#8fbc8f",
+ darkslateblue: "#483d8b",
+ darkslategray: "#2f4f4f",
+ darkslategrey: "#2f4f4f",
+ darkturquoise: "#00ced1",
+ darkviolet: "#9400d3",
+ deeppink: "#ff1493",
+ deepskyblue: "#00bfff",
+ dimgray: "#696969",
+ dimgrey: "#696969",
+ dodgerblue: "#1e90ff",
+ firebrick: "#b22222",
+ floralwhite: "#fffaf0",
+ forestgreen: "#228b22",
+ fuchsia: "#ff00ff",
+ gainsboro: "#dcdcdc",
+ ghostwhite: "#f8f8ff",
+ gold: "#ffd700",
+ goldenrod: "#daa520",
+ gray: "#808080",
+ green: "#008000",
+ greenyellow: "#adff2f",
+ grey: "#808080",
+ honeydew: "#f0fff0",
+ hotpink: "#ff69b4",
+ indianred: "#cd5c5c",
+ indigo: "#4b0082",
+ ivory: "#fffff0",
+ khaki: "#f0e68c",
+ lavender: "#e6e6fa",
+ lavenderblush: "#fff0f5",
+ lawngreen: "#7cfc00",
+ lemonchiffon: "#fffacd",
+ lightblue: "#add8e6",
+ lightcoral: "#f08080",
+ lightcyan: "#e0ffff",
+ lightgoldenrodyellow: "#fafad2",
+ lightgray: "#d3d3d3",
+ lightgreen: "#90ee90",
+ lightgrey: "#d3d3d3",
+ lightpink: "#ffb6c1",
+ lightsalmon: "#ffa07a",
+ lightseagreen: "#20b2aa",
+ lightskyblue: "#87cefa",
+ lightslategray: "#778899",
+ lightslategrey: "#778899",
+ lightsteelblue: "#b0c4de",
+ lightyellow: "#ffffe0",
+ lime: "#00ff00",
+ limegreen: "#32cd32",
+ linen: "#faf0e6",
+ magenta: "#ff00ff",
+ maroon: "#800000",
+ mediumaquamarine: "#66cdaa",
+ mediumblue: "#0000cd",
+ mediumorchid: "#ba55d3",
+ mediumpurple: "#9370db",
+ mediumseagreen: "#3cb371",
+ mediumslateblue: "#7b68ee",
+ mediumspringgreen: "#00fa9a",
+ mediumturquoise: "#48d1cc",
+ mediumvioletred: "#c71585",
+ midnightblue: "#191970",
+ mintcream: "#f5fffa",
+ mistyrose: "#ffe4e1",
+ moccasin: "#ffe4b5",
+ navajowhite: "#ffdead",
+ navy: "#000080",
+ oldlace: "#fdf5e6",
+ olive: "#808000",
+ olivedrab: "#6b8e23",
+ orange: "#ffa500",
+ orangered: "#ff4500",
+ orchid: "#da70d6",
+ palegoldenrod: "#eee8aa",
+ palegreen: "#98fb98",
+ paleturquoise: "#afeeee",
+ palevioletred: "#db7093",
+ papayawhip: "#ffefd5",
+ peachpuff: "#ffdab9",
+ peru: "#cd853f",
+ pink: "#ffc0cb",
+ plum: "#dda0dd",
+ powderblue: "#b0e0e6",
+ purple: "#800080",
+ red: "#ff0000",
+ rosybrown: "#bc8f8f",
+ royalblue: "#4169e1",
+ saddlebrown: "#8b4513",
+ salmon: "#fa8072",
+ sandybrown: "#f4a460",
+ seagreen: "#2e8b57",
+ seashell: "#fff5ee",
+ sienna: "#a0522d",
+ silver: "#c0c0c0",
+ skyblue: "#87ceeb",
+ slateblue: "#6a5acd",
+ slategray: "#708090",
+ slategrey: "#708090",
+ snow: "#fffafa",
+ springgreen: "#00ff7f",
+ steelblue: "#4682b4",
+ tan: "#d2b48c",
+ teal: "#008080",
+ thistle: "#d8bfd8",
+ tomato: "#ff6347",
+ turquoise: "#40e0d0",
+ violet: "#ee82ee",
+ wheat: "#f5deb3",
+ white: "#ffffff",
+ whitesmoke: "#f5f5f5",
+ yellow: "#ffff00",
+ yellowgreen: "#9acd32"
+};
Index: mochitest/MochiKit/Controls.js
===================================================================
RCS file: mochitest/MochiKit/Controls.js
diff -N mochitest/MochiKit/Controls.js
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/MochiKit/Controls.js 25 Oct 2006 20:24:42 -0000
@@ -0,0 +1,1388 @@
+/***
+Copyright (c) 2005 Thomas Fuchs (http://script.aculo.us, http://mir.aculo.us)
+ (c) 2005 Ivan Krstic (http://blogs.law.harvard.edu/ivan)
+ (c) 2005 Jon Tirsen (http://www.tirsen.com)
+Contributors:
+ Richard Livsey
+ Rahul Bhargava
+ Rob Wills
+ Mochi-ized By Thomas Herve (_firstname_@nimail.org)
+
+See scriptaculous.js for full license.
+
+Autocompleter.Base handles all the autocompletion functionality
+that's independent of the data source for autocompletion. This
+includes drawing the autocompletion menu, observing keyboard
+and mouse events, and similar.
+
+Specific autocompleters need to provide, at the very least,
+a getUpdatedChoices function that will be invoked every time
+the text inside the monitored textbox changes. This method
+should get the text for which to provide autocompletion by
+invoking this.getToken(), NOT by directly accessing
+this.element.value. This is to allow incremental tokenized
+autocompletion. Specific auto-completion logic (AJAX, etc)
+belongs in getUpdatedChoices.
+
+Tokenized incremental autocompletion is enabled automatically
+when an autocompleter is instantiated with the 'tokens' option
+in the options parameter, e.g.:
+new Ajax.Autocompleter('id','upd', '/url/', { tokens: ',' });
+will incrementally autocomplete with a comma as the token.
+Additionally, ',' in the above example can be replaced with
+a token array, e.g. { tokens: [',', '\n'] } which
+enables autocompletion on multiple tokens. This is most
+useful when one of the tokens is \n (a newline), as it
+allows smart autocompletion after linebreaks.
+
+***/
+
+MochiKit.Base.update(MochiKit.Base, {
+ ScriptFragment: '(?:)((\n|\r|.)*?)(?:<\/script>)',
+
+/** @id MochiKit.Base.stripScripts */
+ stripScripts: function (str) {
+ return str.replace(new RegExp(MochiKit.Base.ScriptFragment, 'img'), '');
+ },
+
+/** @id MochiKit.Base.stripTags */
+ stripTags: function(str) {
+ return str.replace(/<\/?[^>]+>/gi, '');
+ },
+
+/** @id MochiKit.Base.extractScripts */
+ extractScripts: function (str) {
+ var matchAll = new RegExp(MochiKit.Base.ScriptFragment, 'img');
+ var matchOne = new RegExp(MochiKit.Base.ScriptFragment, 'im');
+ return MochiKit.Base.map(function (scriptTag) {
+ return (scriptTag.match(matchOne) || ['', ''])[1];
+ }, str.match(matchAll) || []);
+ },
+
+/** @id MochiKit.Base.evalScripts */
+ evalScripts: function (str) {
+ return MochiKit.Base.map(function (scr) {
+ eval(scr);
+ }, MochiKit.Base.extractScripts(str));
+ }
+});
+
+MochiKit.Form = {
+
+/** @id MochiKit.Form.serialize */
+ serialize: function (form) {
+ var elements = MochiKit.Form.getElements(form);
+ var queryComponents = [];
+
+ for (var i = 0; i < elements.length; i++) {
+ var queryComponent = MochiKit.Form.serializeElement(elements[i]);
+ if (queryComponent) {
+ queryComponents.push(queryComponent);
+ }
+ }
+
+ return queryComponents.join('&');
+ },
+
+/** @id MochiKit.Form.getElements */
+ getElements: function (form) {
+ form = MochiKit.DOM.getElement(form);
+ var elements = [];
+
+ for (tagName in MochiKit.Form.Serializers) {
+ var tagElements = form.getElementsByTagName(tagName);
+ for (var j = 0; j < tagElements.length; j++) {
+ elements.push(tagElements[j]);
+ }
+ }
+ return elements;
+ },
+
+/** @id MochiKit.Form.serializeElement */
+ serializeElement: function (element) {
+ element = MochiKit.DOM.getElement(element);
+ var method = element.tagName.toLowerCase();
+ var parameter = MochiKit.Form.Serializers[method](element);
+
+ if (parameter) {
+ var key = encodeURIComponent(parameter[0]);
+ if (key.length === 0) {
+ return;
+ }
+
+ if (!(parameter[1] instanceof Array)) {
+ parameter[1] = [parameter[1]];
+ }
+
+ return parameter[1].map(function (value) {
+ return key + '=' + encodeURIComponent(value);
+ }).join('&');
+ }
+ }
+};
+
+MochiKit.Form.Serializers = {
+
+/** @id MochiKit.Form.Serializers.input */
+ input: function (element) {
+ switch (element.type.toLowerCase()) {
+ case 'submit':
+ case 'hidden':
+ case 'password':
+ case 'text':
+ return MochiKit.Form.Serializers.textarea(element);
+ case 'checkbox':
+ case 'radio':
+ return MochiKit.Form.Serializers.inputSelector(element);
+ }
+ return false;
+ },
+
+/** @id MochiKit.Form.Serializers.inputSelector */
+ inputSelector: function (element) {
+ if (element.checked) {
+ return [element.name, element.value];
+ }
+ },
+
+/** @id MochiKit.Form.Serializers.textarea */
+ textarea: function (element) {
+ return [element.name, element.value];
+ },
+
+/** @id MochiKit.Form.Serializers.select */
+ select: function (element) {
+ return MochiKit.Form.Serializers[element.type == 'select-one' ?
+ 'selectOne' : 'selectMany'](element);
+ },
+
+/** @id MochiKit.Form.Serializers.selectOne */
+ selectOne: function (element) {
+ var value = '', opt, index = element.selectedIndex;
+ if (index >= 0) {
+ opt = element.options[index];
+ value = opt.value;
+ if (!value && !('value' in opt)) {
+ value = opt.text;
+ }
+ }
+ return [element.name, value];
+ },
+
+/** @id MochiKit.Form.Serializers.selectMany */
+ selectMany: function (element) {
+ var value = [];
+ for (var i = 0; i < element.length; i++) {
+ var opt = element.options[i];
+ if (opt.selected) {
+ var optValue = opt.value;
+ if (!optValue && !('value' in opt)) {
+ optValue = opt.text;
+ }
+ value.push(optValue);
+ }
+ }
+ return [element.name, value];
+ }
+};
+
+/** @id Ajax */
+var Ajax = {
+ activeRequestCount: 0
+};
+
+Ajax.Responders = {
+ responders: [],
+
+/** @id Ajax.Responders.register */
+ register: function (responderToAdd) {
+ if (MochiKit.Base.find(this.responders, responderToAdd) == -1) {
+ this.responders.push(responderToAdd);
+ }
+ },
+
+/** @id Ajax.Responders.unregister */
+ unregister: function (responderToRemove) {
+ this.responders = this.responders.without(responderToRemove);
+ },
+
+/** @id Ajax.Responders.dispatch */
+ dispatch: function (callback, request, transport, json) {
+ MochiKit.Iter.forEach(this.responders, function (responder) {
+ if (responder[callback] &&
+ typeof(responder[callback]) == 'function') {
+ try {
+ responder[callback].apply(responder, [request, transport, json]);
+ } catch (e) {}
+ }
+ });
+ }
+};
+
+Ajax.Responders.register({
+
+/** @id Ajax.Responders.onCreate */
+ onCreate: function () {
+ Ajax.activeRequestCount++;
+ },
+
+/** @id Ajax.Responders.onComplete */
+ onComplete: function () {
+ Ajax.activeRequestCount--;
+ }
+});
+
+/** @id Ajax.Base */
+Ajax.Base = function () {};
+
+Ajax.Base.prototype = {
+
+/** @id Ajax.Base.prototype.setOptions */
+ setOptions: function (options) {
+ this.options = {
+ method: 'post',
+ asynchronous: true,
+ parameters: ''
+ }
+ MochiKit.Base.update(this.options, options || {});
+ },
+
+/** @id Ajax.Base.prototype.responseIsSuccess */
+ responseIsSuccess: function () {
+ return this.transport.status == undefined
+ || this.transport.status === 0
+ || (this.transport.status >= 200 && this.transport.status < 300);
+ },
+
+/** @id Ajax.Base.prototype.responseIsFailure */
+ responseIsFailure: function () {
+ return !this.responseIsSuccess();
+ }
+};
+
+/** @id Ajax.Request */
+Ajax.Request = function (url, options) {
+ this.__init__(url, options);
+};
+
+/** @id Ajax.Events */
+Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded',
+ 'Interactive', 'Complete'];
+
+MochiKit.Base.update(Ajax.Request.prototype, Ajax.Base.prototype);
+
+MochiKit.Base.update(Ajax.Request.prototype, {
+ __init__: function (url, options) {
+ this.transport = MochiKit.Async.getXMLHttpRequest();
+ this.setOptions(options);
+ this.request(url);
+ },
+
+/** @id Ajax.Request.prototype.request */
+ request: function (url) {
+ var parameters = this.options.parameters || '';
+ if (parameters.length > 0){
+ parameters += '&_=';
+ }
+
+ try {
+ this.url = url;
+ if (this.options.method == 'get' && parameters.length > 0) {
+ this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;
+ }
+ Ajax.Responders.dispatch('onCreate', this, this.transport);
+
+ this.transport.open(this.options.method, this.url,
+ this.options.asynchronous);
+
+ if (this.options.asynchronous) {
+ this.transport.onreadystatechange = MochiKit.Base.bind(this.onStateChange, this);
+ setTimeout(MochiKit.Base.bind(function () {
+ this.respondToReadyState(1);
+ }, this), 10);
+ }
+
+ this.setRequestHeaders();
+
+ var body = this.options.postBody ? this.options.postBody : parameters;
+ this.transport.send(this.options.method == 'post' ? body : null);
+
+ } catch (e) {
+ this.dispatchException(e);
+ }
+ },
+
+/** @id Ajax.Request.prototype.setRequestHeaders */
+ setRequestHeaders: function () {
+ var requestHeaders = ['X-Requested-With', 'XMLHttpRequest'];
+
+ if (this.options.method == 'post') {
+ requestHeaders.push('Content-type',
+ 'application/x-www-form-urlencoded');
+
+ /* Force 'Connection: close' for Mozilla browsers to work around
+ * a bug where XMLHttpRequest sends an incorrect Content-length
+ * header. See Mozilla Bugzilla #246651.
+ */
+ if (this.transport.overrideMimeType) {
+ requestHeaders.push('Connection', 'close');
+ }
+ }
+
+ if (this.options.requestHeaders) {
+ requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);
+ }
+
+ for (var i = 0; i < requestHeaders.length; i += 2) {
+ this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
+ }
+ },
+
+/** @id Ajax.Request.prototype.onStateChange */
+ onStateChange: function () {
+ var readyState = this.transport.readyState;
+ if (readyState != 1) {
+ this.respondToReadyState(this.transport.readyState);
+ }
+ },
+
+/** @id Ajax.Request.prototype.header */
+ header: function (name) {
+ try {
+ return this.transport.getResponseHeader(name);
+ } catch (e) {}
+ },
+
+/** @id Ajax.Request.prototype.evalJSON */
+ evalJSON: function () {
+ try {
+ return eval(this.header('X-JSON'));
+ } catch (e) {}
+ },
+
+/** @id Ajax.Request.prototype.evalResponse */
+ evalResponse: function () {
+ try {
+ return eval(this.transport.responseText);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+ },
+
+/** @id Ajax.Request.prototype.respondToReadyState */
+ respondToReadyState: function (readyState) {
+ var event = Ajax.Request.Events[readyState];
+ var transport = this.transport, json = this.evalJSON();
+
+ if (event == 'Complete') {
+ try {
+ (this.options['on' + this.transport.status]
+ || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
+ || MochiKit.Base.noop)(transport, json);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+
+ if ((this.header('Content-type') || '').match(/^text\/javascript/i)) {
+ this.evalResponse();
+ }
+ }
+
+ try {
+ (this.options['on' + event] || MochiKit.Base.noop)(transport, json);
+ Ajax.Responders.dispatch('on' + event, this, transport, json);
+ } catch (e) {
+ this.dispatchException(e);
+ }
+
+ /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
+ if (event == 'Complete') {
+ this.transport.onreadystatechange = MochiKit.Base.noop;
+ }
+ },
+
+/** @id Ajax.Request.prototype.dispatchException */
+ dispatchException: function (exception) {
+ (this.options.onException || MochiKit.Base.noop)(this, exception);
+ Ajax.Responders.dispatch('onException', this, exception);
+ }
+});
+
+/** @id Ajax.Updater */
+Ajax.Updater = function (container, url, options) {
+ this.__init__(container, url, options);
+};
+
+MochiKit.Base.update(Ajax.Updater.prototype, Ajax.Request.prototype);
+
+MochiKit.Base.update(Ajax.Updater.prototype, {
+ __init__: function (container, url, options) {
+ this.containers = {
+ success: container.success ? MochiKit.DOM.getElement(container.success) : MochiKit.DOM.getElement(container),
+ failure: container.failure ? MochiKit.DOM.getElement(container.failure) :
+ (container.success ? null : MochiKit.DOM.getElement(container))
+ }
+ this.transport = MochiKit.Async.getXMLHttpRequest();
+ this.setOptions(options);
+
+ var onComplete = this.options.onComplete || MochiKit.Base.noop;
+ this.options.onComplete = MochiKit.Base.bind(function (transport, object) {
+ this.updateContent();
+ onComplete(transport, object);
+ }, this);
+
+ this.request(url);
+ },
+
+/** @id Ajax.Updater.prototype.updateContent */
+ updateContent: function () {
+ var receiver = this.responseIsSuccess() ?
+ this.containers.success : this.containers.failure;
+ var response = this.transport.responseText;
+
+ if (!this.options.evalScripts) {
+ response = MochiKit.Base.stripScripts(response);
+ }
+
+ if (receiver) {
+ if (this.options.insertion) {
+ new this.options.insertion(receiver, response);
+ } else {
+ MochiKit.DOM.getElement(receiver).innerHTML =
+ MochiKit.Base.stripScripts(response);
+ setTimeout(function () {
+ MochiKit.Base.evalScripts(response);
+ }, 10);
+ }
+ }
+
+ if (this.responseIsSuccess()) {
+ if (this.onComplete) {
+ setTimeout(MochiKit.Base.bind(this.onComplete, this), 10);
+ }
+ }
+ }
+});
+
+/** @id Field */
+var Field = {
+
+/** @id clear */
+ clear: function () {
+ for (var i = 0; i < arguments.length; i++) {
+ MochiKit.DOM.getElement(arguments[i]).value = '';
+ }
+ },
+
+/** @id focus */
+ focus: function (element) {
+ MochiKit.DOM.getElement(element).focus();
+ },
+
+/** @id present */
+ present: function () {
+ for (var i = 0; i < arguments.length; i++) {
+ if (MochiKit.DOM.getElement(arguments[i]).value == '') {
+ return false;
+ }
+ }
+ return true;
+ },
+
+/** @id select */
+ select: function (element) {
+ MochiKit.DOM.getElement(element).select();
+ },
+
+/** @id activate */
+ activate: function (element) {
+ element = MochiKit.DOM.getElement(element);
+ element.focus();
+ if (element.select) {
+ element.select();
+ }
+ },
+
+/** @id scrollFreeActivate */
+ scrollFreeActivate: function (field) {
+ setTimeout(function () {
+ Field.activate(field);
+ }, 1);
+ }
+};
+
+
+/** @id Autocompleter */
+var Autocompleter = {};
+
+/** @id Autocompleter.Base */
+Autocompleter.Base = function () {};
+
+Autocompleter.Base.prototype = {
+
+/** @id Autocompleter.Base.prototype.baseInitialize */
+ baseInitialize: function (element, update, options) {
+ this.element = MochiKit.DOM.getElement(element);
+ this.update = MochiKit.DOM.getElement(update);
+ this.hasFocus = false;
+ this.changed = false;
+ this.active = false;
+ this.index = 0;
+ this.entryCount = 0;
+
+ if (this.setOptions) {
+ this.setOptions(options);
+ }
+ else {
+ this.options = options || {};
+ }
+
+ this.options.paramName = this.options.paramName || this.element.name;
+ this.options.tokens = this.options.tokens || [];
+ this.options.frequency = this.options.frequency || 0.4;
+ this.options.minChars = this.options.minChars || 1;
+ this.options.onShow = this.options.onShow || function (element, update) {
+ if (!update.style.position || update.style.position == 'absolute') {
+ update.style.position = 'absolute';
+ MochiKit.Position.clone(element, update, {
+ setHeight: false,
+ offsetTop: element.offsetHeight
+ });
+ }
+ MochiKit.Visual.appear(update, {duration:0.15});
+ };
+ this.options.onHide = this.options.onHide || function (element, update) {
+ MochiKit.Visual.fade(update, {duration: 0.15});
+ };
+
+ if (typeof(this.options.tokens) == 'string') {
+ this.options.tokens = new Array(this.options.tokens);
+ }
+
+ this.observer = null;
+
+ this.element.setAttribute('autocomplete', 'off');
+
+ MochiKit.Style.hideElement(this.update);
+
+ MochiKit.Signal.connect(this.element, 'onblur', this, this.onBlur);
+ MochiKit.Signal.connect(this.element, 'onkeypress', this, this.onKeyPress, this);
+ },
+
+/** @id Autocompleter.Base.prototype.show */
+ show: function () {
+ if (MochiKit.Style.getStyle(this.update, 'display') == 'none') {
+ this.options.onShow(this.element, this.update);
+ }
+ if (!this.iefix && /MSIE/.test(navigator.userAgent &&
+ (MochiKit.Style.getStyle(this.update, 'position') == 'absolute')) {
+ new Insertion.After(this.update,
+ '');
+ this.iefix = MochiKit.DOM.getElement(this.update.id + '_iefix');
+ }
+ if (this.iefix) {
+ setTimeout(MochiKit.Base.bind(this.fixIEOverlapping, this), 50);
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.fixIEOverlapping */
+ fixIEOverlapping: function () {
+ MochiKit.Position.clone(this.update, this.iefix);
+ this.iefix.style.zIndex = 1;
+ this.update.style.zIndex = 2;
+ MochiKit.Style.showElement(this.iefix);
+ },
+
+/** @id Autocompleter.Base.prototype.hide */
+ hide: function () {
+ this.stopIndicator();
+ if (MochiKit.Style.getStyle(this.update, 'display') != 'none') {
+ this.options.onHide(this.element, this.update);
+ }
+ if (this.iefix) {
+ MochiKit.Style.hideElement(this.iefix);
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.startIndicator */
+ startIndicator: function () {
+ if (this.options.indicator) {
+ MochiKit.Style.showElement(this.options.indicator);
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.stopIndicator */
+ stopIndicator: function () {
+ if (this.options.indicator) {
+ MochiKit.Style.hideElement(this.options.indicator);
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.onKeyPress */
+ onKeyPress: function (event) {
+ if (this.active) {
+ if (event.key().string == "KEY_TAB" || event.key().string == "KEY_RETURN") {
+ this.selectEntry();
+ MochiKit.Event.stop(event);
+ } else if (event.key().string == "KEY_ESCAPE") {
+ this.hide();
+ this.active = false;
+ MochiKit.Event.stop(event);
+ return;
+ } else if (event.key().string == "KEY_LEFT" || event.key().string == "KEY_RIGHT") {
+ return;
+ } else if (event.key().string == "KEY_UP") {
+ this.markPrevious();
+ this.render();
+ if (/AppleWebKit'/.test(navigator.appVersion)) {
+ event.stop();
+ }
+ return;
+ } else if (event.key().string == "KEY_DOWN") {
+ this.markNext();
+ this.render();
+ if (/AppleWebKit'/.test(navigator.appVersion)) {
+ event.stop();
+ }
+ return;
+ }
+ } else {
+ if (event.key().string == "KEY_TAB" || event.key().string == "KEY_RETURN") {
+ return;
+ }
+ }
+
+ this.changed = true;
+ this.hasFocus = true;
+
+ if (this.observer) {
+ clearTimeout(this.observer);
+ }
+ this.observer = setTimeout(MochiKit.Base.bind(this.onObserverEvent, this),
+ this.options.frequency*1000);
+ },
+
+/** @id Autocompleter.Base.prototype.findElement */
+ findElement: function (event, tagName) {
+ var element = event.target;
+ while (element.parentNode && (!element.tagName ||
+ (element.tagName.toUpperCase() != tagName.toUpperCase()))) {
+ element = element.parentNode;
+ }
+ return element;
+ },
+
+/** @id Autocompleter.Base.prototype.hover */
+ onHover: function (event) {
+ var element = this.findElement(event, 'LI');
+ if (this.index != element.autocompleteIndex) {
+ this.index = element.autocompleteIndex;
+ this.render();
+ }
+ event.stop();
+ },
+
+/** @id Autocompleter.Base.prototype.onClick */
+ onClick: function (event) {
+ var element = this.findElement(event, 'LI');
+ this.index = element.autocompleteIndex;
+ this.selectEntry();
+ this.hide();
+ },
+
+/** @id Autocompleter.Base.prototype.onBlur */
+ onBlur: function (event) {
+ // needed to make click events working
+ setTimeout(MochiKit.Base.bind(this.hide, this), 250);
+ this.hasFocus = false;
+ this.active = false;
+ },
+
+/** @id Autocompleter.Base.prototype.render */
+ render: function () {
+ if (this.entryCount > 0) {
+ for (var i = 0; i < this.entryCount; i++) {
+ this.index == i ?
+ MochiKit.DOM.addElementClass(this.getEntry(i), 'selected') :
+ MochiKit.DOM.removeElementClass(this.getEntry(i), 'selected');
+ }
+ if (this.hasFocus) {
+ this.show();
+ this.active = true;
+ }
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.markPrevious */
+ markPrevious: function () {
+ if (this.index > 0) {
+ this.index--
+ } else {
+ this.index = this.entryCount-1;
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.markNext */
+ markNext: function () {
+ if (this.index < this.entryCount-1) {
+ this.index++
+ } else {
+ this.index = 0;
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.getEntry */
+ getEntry: function (index) {
+ return this.update.firstChild.childNodes[index];
+ },
+
+/** @id Autocompleter.Base.prototype.getCurrentEntry */
+ getCurrentEntry: function () {
+ return this.getEntry(this.index);
+ },
+
+/** @id Autocompleter.Base.prototype.selectEntry */
+ selectEntry: function () {
+ this.active = false;
+ this.updateElement(this.getCurrentEntry());
+ },
+
+/** @id Autocompleter.Base.prototype.collectTextNodesIgnoreClass */
+ collectTextNodesIgnoreClass: function (element, className) {
+ return MochiKit.Base.flattenArray(MochiKit.Base.map(function (node) {
+ if (node.nodeType == 3) {
+ return node.nodeValue;
+ } else if (node.hasChildNodes() && !MochiKit.DOM.hasElementClass(node, className)) {
+ return this.collectTextNodesIgnoreClass(node, className);
+ }
+ return '';
+ }, MochiKit.DOM.getElement(element).childNodes)).join('');
+ },
+
+/** @id Autocompleter.Base.prototype.updateElement */
+ updateElement: function (selectedElement) {
+ if (this.options.updateElement) {
+ this.options.updateElement(selectedElement);
+ return;
+ }
+ var value = '';
+ if (this.options.select) {
+ var nodes = document.getElementsByClassName(this.options.select, selectedElement) || [];
+ if (nodes.length > 0) {
+ value = MochiKit.DOM.scrapeText(nodes[0]);
+ }
+ } else {
+ value = this.collectTextNodesIgnoreClass(selectedElement, 'informal');
+ }
+ var lastTokenPos = this.findLastToken();
+ if (lastTokenPos != -1) {
+ var newValue = this.element.value.substr(0, lastTokenPos + 1);
+ var whitespace = this.element.value.substr(lastTokenPos + 1).match(/^\s+/);
+ if (whitespace) {
+ newValue += whitespace[0];
+ }
+ this.element.value = newValue + value;
+ } else {
+ this.element.value = value;
+ }
+ this.element.focus();
+
+ if (this.options.afterUpdateElement) {
+ this.options.afterUpdateElement(this.element, selectedElement);
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.updateChoices */
+ updateChoices: function (choices) {
+ if (!this.changed && this.hasFocus) {
+ this.update.innerHTML = choices;
+ var d = MochiKit.DOM;
+ d.removeEmptyTextNodes(this.update);
+ d.removeEmptyTextNodes(this.update.firstChild);
+
+ if (this.update.firstChild && this.update.firstChild.childNodes) {
+ this.entryCount = this.update.firstChild.childNodes.length;
+ for (var i = 0; i < this.entryCount; i++) {
+ var entry = this.getEntry(i);
+ entry.autocompleteIndex = i;
+ this.addObservers(entry);
+ }
+ } else {
+ this.entryCount = 0;
+ }
+
+ this.stopIndicator();
+
+ this.index = 0;
+ this.render();
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.addObservers */
+ addObservers: function (element) {
+ MochiKit.Signal.connect(element, 'onmouseover', this, this.onHover);
+ MochiKit.Signal.connect(element, 'onclick', this, this.onClick);
+ },
+
+/** @id Autocompleter.Base.prototype.onObserverEvent */
+ onObserverEvent: function () {
+ this.changed = false;
+ if (this.getToken().length >= this.options.minChars) {
+ this.startIndicator();
+ this.getUpdatedChoices();
+ } else {
+ this.active = false;
+ this.hide();
+ }
+ },
+
+/** @id Autocompleter.Base.prototype.getToken */
+ getToken: function () {
+ var tokenPos = this.findLastToken();
+ if (tokenPos != -1) {
+ var ret = this.element.value.substr(tokenPos + 1).replace(/^\s+/,'').replace(/\s+$/,'');
+ } else {
+ var ret = this.element.value;
+ }
+ return /\n/.test(ret) ? '' : ret;
+ },
+
+/** @id Autocompleter.Base.prototype.findLastToken */
+ findLastToken: function () {
+ var lastTokenPos = -1;
+
+ for (var i = 0; i < this.options.tokens.length; i++) {
+ var thisTokenPos = this.element.value.lastIndexOf(this.options.tokens[i]);
+ if (thisTokenPos > lastTokenPos) {
+ lastTokenPos = thisTokenPos;
+ }
+ }
+ return lastTokenPos;
+ }
+}
+
+/** @id Ajax.Autocompleter */
+Ajax.Autocompleter = function (element, update, url, options) {
+ this.__init__(element, update, url, options);
+};
+
+MochiKit.Base.update(Ajax.Autocompleter.prototype, Autocompleter.Base.prototype);
+
+MochiKit.Base.update(Ajax.Autocompleter.prototype, {
+ __init__: function (element, update, url, options) {
+ this.baseInitialize(element, update, options);
+ this.options.asynchronous = true;
+ this.options.onComplete = MochiKit.Base.bind(this.onComplete, this);
+ this.options.defaultParams = this.options.parameters || null;
+ this.url = url;
+ },
+
+/** @id Ajax.Autocompleter.prototype.getUpdatedChoices */
+ getUpdatedChoices: function () {
+ var entry = encodeURIComponent(this.options.paramName) + '=' +
+ encodeURIComponent(this.getToken());
+
+ this.options.parameters = this.options.callback ?
+ this.options.callback(this.element, entry) : entry;
+
+ if (this.options.defaultParams) {
+ this.options.parameters += '&' + this.options.defaultParams;
+ }
+ new Ajax.Request(this.url, this.options);
+ },
+
+/** @id Ajax.Autocompleter.prototype.onComplete */
+ onComplete: function (request) {
+ this.updateChoices(request.responseText);
+ }
+});
+
+/***
+
+The local array autocompleter. Used when you'd prefer to
+inject an array of autocompletion options into the page, rather
+than sending out Ajax queries, which can be quite slow sometimes.
+
+The constructor takes four parameters. The first two are, as usual,
+the id of the monitored textbox, and id of the autocompletion menu.
+The third is the array you want to autocomplete from, and the fourth
+is the options block.
+
+Extra local autocompletion options:
+- choices - How many autocompletion choices to offer
+
+- partialSearch - If false, the autocompleter will match entered
+ text only at the beginning of strings in the
+ autocomplete array. Defaults to true, which will
+ match text at the beginning of any *word* in the
+ strings in the autocomplete array. If you want to
+ search anywhere in the string, additionally set
+ the option fullSearch to true (default: off).
+
+- fullSsearch - Search anywhere in autocomplete array strings.
+
+- partialChars - How many characters to enter before triggering
+ a partial match (unlike minChars, which defines
+ how many characters are required to do any match
+ at all). Defaults to 2.
+
+- ignoreCase - Whether to ignore case when autocompleting.
+ Defaults to true.
+
+It's possible to pass in a custom function as the 'selector'
+option, if you prefer to write your own autocompletion logic.
+In that case, the other options above will not apply unless
+you support them.
+
+***/
+
+/** @id Autocompleter.Local */
+Autocompleter.Local = function (element, update, array, options) {
+ this.__init__(element, update, array, options);
+};
+
+MochiKit.Base.update(Autocompleter.Local.prototype, Autocompleter.Base.prototype);
+
+MochiKit.Base.update(Autocompleter.Local.prototype, {
+ __init__: function (element, update, array, options) {
+ this.baseInitialize(element, update, options);
+ this.options.array = array;
+ },
+
+/** @id Autocompleter.Local.prototype.getUpdatedChoices */
+ getUpdatedChoices: function () {
+ this.updateChoices(this.options.selector(this));
+ },
+
+/** @id Autocompleter.Local.prototype.setOptions */
+ setOptions: function (options) {
+ this.options = MochiKit.Base.update({
+ choices: 10,
+ partialSearch: true,
+ partialChars: 2,
+ ignoreCase: true,
+ fullSearch: false,
+ selector: function (instance) {
+ var ret = []; // Beginning matches
+ var partial = []; // Inside matches
+ var entry = instance.getToken();
+ var count = 0;
+
+ for (var i = 0; i < instance.options.array.length &&
+ ret.length < instance.options.choices ; i++) {
+
+ var elem = instance.options.array[i];
+ var foundPos = instance.options.ignoreCase ?
+ elem.toLowerCase().indexOf(entry.toLowerCase()) :
+ elem.indexOf(entry);
+
+ while (foundPos != -1) {
+ if (foundPos === 0 && elem.length != entry.length) {
+ ret.push('
+
+
Index: mochitest/tests/SimpleTest/MozillaFileLogger.js
===================================================================
RCS file: mochitest/tests/SimpleTest/MozillaFileLogger.js
diff -N mochitest/tests/SimpleTest/MozillaFileLogger.js
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/tests/SimpleTest/MozillaFileLogger.js 25 Oct 2006 20:24:48 -0000
@@ -0,0 +1,66 @@
+/**
+ * MozillaFileLogger, a log listener that can write to a local file.
+ */
+
+netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+const Cc = Components.classes;
+const Ci = Components.interfaces;
+const FOSTREAM_CID = "@mozilla.org/network/file-output-stream;1";
+const LF_CID = "@mozilla.org/file/local;1";
+
+// File status flags. It is a bitwise OR of the following bit flags.
+// Only one of the first three flags below may be used.
+const PR_READ_ONLY = 0x01; // Open for reading only.
+const PR_WRITE_ONLY = 0x02; // Open for writing only.
+const PR_READ_WRITE = 0x04; // Open for reading and writing.
+
+// If the file does not exist, the file is created.
+// If the file exists, this flag has no effect.
+const PR_CREATE_FILE = 0x08;
+
+// The file pointer is set to the end of the file prior to each write.
+const PR_APPEND = 0x10;
+
+// If the file exists, its length is truncated to 0.
+const PR_TRUNCATE = 0x20;
+
+// If set, each write will wait for both the file data
+// and file status to be physically updated.
+const PR_SYNC = 0x40;
+
+// If the file does not exist, the file is created. If the file already
+// exists, no action and NULL is returned.
+const PR_EXCL = 0x80;
+
+
+/** Init the file logger with the absolute path to the file.
+ It will create and append if the file already exists **/
+var MozillaFileLogger = {}
+
+MozillaFileLogger.init = function(path) {
+ netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+ MozillaFileLogger._file = Cc[LF_CID].createInstance(Ci.nsILocalFile);
+ MozillaFileLogger._file.initWithPath(path);
+ MozillaFileLogger._foStream = Cc[FOSTREAM_CID].createInstance(Ci.nsIFileOutputStream);
+ MozillaFileLogger._foStream.init(this._file, PR_WRITE_ONLY | PR_CREATE_FILE | PR_APPEND,
+ 0664, 0);
+}
+
+MozillaFileLogger.getLogCallback = function() {
+ var self = MozillaFileLogger;
+ return function (msg) {
+ netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+ var data = msg.num + " " + msg.level + " " + msg.info.join(' ') + "\n";
+ self._foStream.write(data, data.length);
+ if (data.indexOf("SimpleTest FINISH") >= 0) {
+ self.close();
+ }
+ }
+}
+
+MozillaFileLogger.close = function() {
+ netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect");
+ MozillaFileLogger._foStream.close();
+ MozillaFileLogger._foStream = null;
+ MozillaFileLogger._file = null;
+}
Index: mochitest/tests/SimpleTest/SimpleTest.js
===================================================================
RCS file: mochitest/tests/SimpleTest/SimpleTest.js
diff -N mochitest/tests/SimpleTest/SimpleTest.js
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/tests/SimpleTest/SimpleTest.js 25 Oct 2006 20:24:48 -0000
@@ -0,0 +1,366 @@
+/**
+ * SimpleTest, a partial Test.Simple/Test.More API compatible test library.
+ *
+ * Why?
+ *
+ * Test.Simple doesn't work on IE < 6.
+ * TODO:
+ * * Support the Test.Simple API used by MochiKit, to be able to test MochiKit
+ * itself against IE 5.5
+ *
+**/
+
+if (typeof(SimpleTest) == "undefined") {
+ var SimpleTest = {};
+}
+
+// Check to see if the TestRunner is present and has logging
+if (typeof(parent) != "undefined" && parent.TestRunner) {
+ SimpleTest._logEnabled = parent.TestRunner.logEnabled;
+}
+
+SimpleTest._tests = [];
+SimpleTest._stopOnLoad = true;
+
+/**
+ * Something like assert.
+**/
+SimpleTest.ok = function (condition, name, diag) {
+ var test = {'result': !!condition, 'name': name, 'diag': diag || ""};
+ if (SimpleTest._logEnabled) {
+ var msg = test.result ? "PASS" : "FAIL";
+ msg += " | " + test.name;
+ if (test.result) {
+ parent.TestRunner.logger.log(msg);
+ } else {
+ msg += " | " + test.diag;
+ parent.TestRunner.logger.error(msg);
+ }
+ }
+ SimpleTest._tests.push(test);
+};
+
+/**
+ * Roughly equivalent to ok(a==b, name)
+**/
+SimpleTest.is = function (a, b, name) {
+ var repr = MochiKit.Base.repr;
+ SimpleTest.ok(a == b, name, "got " + repr(a) + ", expected " + repr(b));
+};
+
+
+/**
+ * Makes a test report, returns it as a DIV element.
+**/
+SimpleTest.report = function () {
+ var DIV = MochiKit.DOM.DIV;
+ var passed = 0;
+ var failed = 0;
+ var results = MochiKit.Base.map(
+ function (test) {
+ var cls, msg;
+ if (test.result) {
+ passed++;
+ cls = "test_ok";
+ msg = "ok - " + test.name;
+ } else {
+ failed++;
+ cls = "test_not_ok";
+ msg = "not ok - " + test.name + " " + test.diag;
+ }
+ return DIV({"class": cls}, msg);
+ },
+ SimpleTest._tests
+ );
+ var summary_class = ((failed == 0) ? 'all_pass' : 'some_fail');
+ return DIV({'class': 'tests_report'},
+ DIV({'class': 'tests_summary ' + summary_class},
+ DIV({'class': 'tests_passed'}, "Passed: " + passed),
+ DIV({'class': 'tests_failed'}, "Failed: " + failed)),
+ results
+ );
+};
+
+/**
+ * Toggle element visibility
+**/
+SimpleTest.toggle = function(el) {
+ if (MochiKit.Style.computedStyle(el, 'display') == 'block') {
+ el.style.display = 'none';
+ } else {
+ el.style.display = 'block';
+ }
+};
+
+/**
+ * Toggle visibility for divs with a specific class.
+**/
+SimpleTest.toggleByClass = function (cls) {
+ var elems = getElementsByTagAndClassName('div', cls);
+ MochiKit.Base.map(SimpleTest.toggle, elems);
+};
+
+/**
+ * Shows the report in the browser
+**/
+
+SimpleTest.showReport = function() {
+ var togglePassed = A({'href': '#'}, "Toggle passed tests");
+ var toggleFailed = A({'href': '#'}, "Toggle failed tests");
+ togglePassed.onclick = partial(SimpleTest.toggleByClass, 'test_ok');
+ toggleFailed.onclick = partial(SimpleTest.toggleByClass, 'test_not_ok');
+ var body = document.getElementsByTagName("body")[0];
+ var firstChild = body.childNodes[0];
+ var addNode;
+ if (firstChild) {
+ addNode = function (el) {
+ body.insertBefore(el, firstChild);
+ };
+ } else {
+ addNode = function (el) {
+ body.appendChild(el)
+ };
+ }
+ addNode(togglePassed);
+ addNode(SPAN(null, " "));
+ addNode(toggleFailed);
+ addNode(SimpleTest.report());
+};
+
+/**
+ * Tells SimpleTest to don't finish the test when the document is loaded,
+ * useful for asynchronous tests.
+ *
+ * When SimpleTest.waitForExplicitFinish is called,
+ * explicit SimpleTest.finish() is required.
+**/
+SimpleTest.waitForExplicitFinish = function () {
+ SimpleTest._stopOnLoad = false;
+};
+
+/**
+ * Talks to the TestRunner if being ran on a iframe and the parent has a
+ * TestRunner object.
+**/
+SimpleTest.talkToRunner = function () {
+ if (typeof(parent) != "undefined" && parent.TestRunner) {
+ parent.TestRunner.testFinished(document);
+ }
+};
+
+/**
+ * Finishes the tests. This is automatically called, except when
+ * SimpleTest.waitForExplicitFinish() has been invoked.
+**/
+SimpleTest.finish = function () {
+ SimpleTest.showReport();
+ SimpleTest.talkToRunner();
+};
+
+
+addLoadEvent(function() {
+ if (SimpleTest._stopOnLoad) {
+ SimpleTest.finish();
+ }
+});
+
+// --------------- Test.Builder/Test.More isDeeply() -----------------
+
+
+SimpleTest.DNE = {dne: 'Does not exist'};
+SimpleTest.LF = "\r\n";
+SimpleTest._isRef = function (object) {
+ var type = typeof(object);
+ return type == 'object' || type == 'function';
+};
+
+
+SimpleTest._deepCheck = function (e1, e2, stack, seen) {
+ var ok = false;
+ // Either they're both references or both not.
+ var sameRef = !(!SimpleTest._isRef(e1) ^ !SimpleTest._isRef(e2));
+ if (e1 == null && e2 == null) {
+ ok = true;
+ } else if (e1 != null ^ e2 != null) {
+ ok = false;
+ } else if (e1 == SimpleTest.DNE ^ e2 == SimpleTest.DNE) {
+ ok = false;
+ } else if (sameRef && e1 == e2) {
+ // Handles primitives and any variables that reference the same
+ // object, including functions.
+ ok = true;
+ } else if (SimpleTest.isa(e1, 'Array') && SimpleTest.isa(e2, 'Array')) {
+ ok = SimpleTest._eqArray(e1, e2, stack, seen);
+ } else if (typeof e1 == "object" && typeof e2 == "object") {
+ ok = SimpleTest._eqAssoc(e1, e2, stack, seen);
+ } else {
+ // If we get here, they're not the same (function references must
+ // always simply rererence the same function).
+ stack.push({ vals: [e1, e2] });
+ ok = false;
+ }
+ return ok;
+};
+
+SimpleTest._eqArray = function (a1, a2, stack, seen) {
+ // Return if they're the same object.
+ if (a1 == a2) return true;
+
+ // JavaScript objects have no unique identifiers, so we have to store
+ // references to them all in an array, and then compare the references
+ // directly. It's slow, but probably won't be much of an issue in
+ // practice. Start by making a local copy of the array to as to avoid
+ // confusing a reference seen more than once (such as [a, a]) for a
+ // circular reference.
+ for (var j = 0; j < seen.length; j++) {
+ if (seen[j][0] == a1) {
+ return seen[j][1] == a2;
+ }
+ }
+
+ // If we get here, we haven't seen a1 before, so store it with reference
+ // to a2.
+ seen.push([ a1, a2 ]);
+
+ var ok = true;
+ // Only examines enumerable attributes. Only works for numeric arrays!
+ // Associative arrays return 0. So call _eqAssoc() for them, instead.
+ var max = a1.length > a2.length ? a1.length : a2.length;
+ if (max == 0) return SimpleTest._eqAssoc(a1, a2, stack, seen);
+ for (var i = 0; i < max; i++) {
+ var e1 = i > a1.length - 1 ? SimpleTest.DNE : a1[i];
+ var e2 = i > a2.length - 1 ? SimpleTest.DNE : a2[i];
+ stack.push({ type: 'Array', idx: i, vals: [e1, e2] });
+ if (ok = SimpleTest._deepCheck(e1, e2, stack, seen)) {
+ stack.pop();
+ } else {
+ break;
+ }
+ }
+ return ok;
+};
+
+SimpleTest._eqAssoc = function (o1, o2, stack, seen) {
+ // Return if they're the same object.
+ if (o1 == o2) return true;
+
+ // JavaScript objects have no unique identifiers, so we have to store
+ // references to them all in an array, and then compare the references
+ // directly. It's slow, but probably won't be much of an issue in
+ // practice. Start by making a local copy of the array to as to avoid
+ // confusing a reference seen more than once (such as [a, a]) for a
+ // circular reference.
+ seen = seen.slice(0);
+ for (var j = 0; j < seen.length; j++) {
+ if (seen[j][0] == o1) {
+ return seen[j][1] == o2;
+ }
+ }
+
+ // If we get here, we haven't seen o1 before, so store it with reference
+ // to o2.
+ seen.push([ o1, o2 ]);
+
+ // They should be of the same class.
+
+ var ok = true;
+ // Only examines enumerable attributes.
+ var o1Size = 0; for (var i in o1) o1Size++;
+ var o2Size = 0; for (var i in o2) o2Size++;
+ var bigger = o1Size > o2Size ? o1 : o2;
+ for (var i in bigger) {
+ var e1 = o1[i] == undefined ? SimpleTest.DNE : o1[i];
+ var e2 = o2[i] == undefined ? SimpleTest.DNE : o2[i];
+ stack.push({ type: 'Object', idx: i, vals: [e1, e2] });
+ if (ok = SimpleTest._deepCheck(e1, e2, stack, seen)) {
+ stack.pop();
+ } else {
+ break;
+ }
+ }
+ return ok;
+};
+
+SimpleTest._formatStack = function (stack) {
+ var variable = '$Foo';
+ for (var i = 0; i < stack.length; i++) {
+ var entry = stack[i];
+ var type = entry['type'];
+ var idx = entry['idx'];
+ if (idx != null) {
+ if (/^\d+$/.test(idx)) {
+ // Numeric array index.
+ variable += '[' + idx + ']';
+ } else {
+ // Associative array index.
+ idx = idx.replace("'", "\\'");
+ variable += "['" + idx + "']";
+ }
+ }
+ }
+
+ var vals = stack[stack.length-1]['vals'].slice(0, 2);
+ var vars = [
+ variable.replace('$Foo', 'got'),
+ variable.replace('$Foo', 'expected')
+ ];
+
+ var out = "Structures begin differing at:" + SimpleTest.LF;
+ for (var i = 0; i < vals.length; i++) {
+ var val = vals[i];
+ if (val == null) {
+ val = 'undefined';
+ } else {
+ val == SimpleTest.DNE ? "Does not exist" : "'" + val + "'";
+ }
+ }
+
+ out += vars[0] + ' = ' + vals[0] + SimpleTest.LF;
+ out += vars[1] + ' = ' + vals[1] + SimpleTest.LF;
+
+ return ' ' + out;
+};
+
+
+SimpleTest.isDeeply = function (it, as, name) {
+ var ok;
+ // ^ is the XOR operator.
+ if (SimpleTest._isRef(it) ^ SimpleTest._isRef(as)) {
+ // One's a reference, one isn't.
+ ok = false;
+ } else if (!SimpleTest._isRef(it) && !SimpleTest._isRef(as)) {
+ // Neither is an object.
+ ok = SimpleTest.is(it, as, name);
+ } else {
+ // We have two objects. Do a deep comparison.
+ var stack = [], seen = [];
+ if ( SimpleTest._deepCheck(it, as, stack, seen)) {
+ ok = SimpleTest.ok(true, name);
+ } else {
+ ok = SimpleTest.ok(false, name, SimpleTest._formatStack(stack));
+ }
+ }
+ return ok;
+};
+
+SimpleTest.typeOf = function (object) {
+ var c = Object.prototype.toString.apply(object);
+ var name = c.substring(8, c.length - 1);
+ if (name != 'Object') return name;
+ // It may be a non-core class. Try to extract the class name from
+ // the constructor function. This may not work in all implementations.
+ if (/function ([^(\s]+)/.test(Function.toString.call(object.constructor))) {
+ return RegExp.$1;
+ }
+ // No idea. :-(
+ return name;
+};
+
+SimpleTest.isa = function (object, clas) {
+ return SimpleTest.typeOf(object) == clas;
+};
+
+// Global symbols:
+var ok = SimpleTest.ok;
+var is = SimpleTest.is;
+var isDeeply = SimpleTest.isDeeply;
Index: mochitest/tests/SimpleTest/TestRunner.js
===================================================================
RCS file: mochitest/tests/SimpleTest/TestRunner.js
diff -N mochitest/tests/SimpleTest/TestRunner.js
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/tests/SimpleTest/TestRunner.js 25 Oct 2006 20:24:48 -0000
@@ -0,0 +1,159 @@
+/**
+ * TestRunner: A test runner for SimpleTest
+ * TODO:
+ *
+ * * Avoid moving iframes: That causes reloads on mozilla and opera.
+ *
+ *
+**/
+var TestRunner = {};
+TestRunner.logEnabled = false;
+TestRunner._iframes = {};
+TestRunner._iframeDocuments = {};
+TestRunner._iframeRows = {};
+TestRunner._currentTest = 0;
+TestRunner._urls = [];
+TestRunner._testsDiv = DIV();
+TestRunner._progressDiv = DIV();
+TestRunner._summaryDiv = DIV({'id': "summaryDiv"},
+ H1(null, "Tests Summary"),
+ TABLE(null,
+ THEAD(null,
+ TR(null,
+ TH(null, "Test"),
+ TH(null, "Passed"),
+ TH(null, "Failed")
+ )
+ ),
+ TBODY()
+ )
+);
+
+/**
+ * This function is called after generating the summary.
+**/
+TestRunner.onComplete = null;
+
+/**
+ * If logEnabled is true, this is the logger that will be used.
+**/
+TestRunner.logger = MochiKit.Logging.logger;
+
+/**
+ * Toggle element visibility
+**/
+TestRunner._toggle = function(el) {
+ if (el.className == "noshow") {
+ el.className = "";
+ el.style.cssText = "";
+ } else {
+ el.className = "noshow";
+ el.style.cssText = "width:0px; height:0px; border:0px;";
+ }
+};
+
+
+/**
+ * Creates the iframe that contains a test
+**/
+TestRunner._makeIframe = function (url) {
+ var iframe = document.createElement('iframe');
+ iframe.src = url;
+ iframe.name = url;
+ iframe.width = "500";
+ var tbody = TestRunner._summaryDiv.getElementsByTagName("tbody")[0];
+ var tr = TR(null, TD({'colspan': '3'}, iframe));
+ iframe._row = tr;
+ tbody.appendChild(tr);
+ return iframe;
+};
+
+/**
+ * TestRunner entry point.
+ *
+ * The arguments are the URLs of the test to be ran.
+ *
+**/
+TestRunner.runTests = function (/*url...*/) {
+ if (TestRunner.logEnabled)
+ TestRunner.logger.log("SimpleTest START");
+
+ var body = document.getElementsByTagName("body")[0];
+ appendChildNodes(body,
+ TestRunner._testsDiv,
+ TestRunner._progressDiv,
+ TestRunner._summaryDiv
+ );
+ for (var i = 0; i < arguments.length; i++) {
+ TestRunner._urls.push(arguments[i]);
+ }
+ TestRunner.runNextTest();
+};
+
+/**
+ * Run the next test. If no test remains, calls makeSummary
+**/
+TestRunner.runNextTest = function() {
+ if (TestRunner._currentTest < TestRunner._urls.length) {
+ var url = TestRunner._urls[TestRunner._currentTest];
+ var progress = SPAN(null,
+ "Running ", A({href:url}, url), "..."
+ );
+
+ if (TestRunner.logEnabled)
+ TestRunner.logger.log(scrapeText(progress));
+
+ TestRunner._progressDiv.appendChild(progress);
+ TestRunner._iframes[url] = TestRunner._makeIframe(url);
+ } else {
+ TestRunner.makeSummary();
+ if (TestRunner.onComplete)
+ TestRunner.onComplete();
+ }
+};
+
+/**
+ * This stub is called by SimpleTest when a test is finished.
+**/
+TestRunner.testFinished = function (doc) {
+ appendChildNodes(TestRunner._progressDiv, SPAN(null, "Done"), BR());
+ var finishedURL = TestRunner._urls[TestRunner._currentTest];
+
+ if (TestRunner.logEnabled)
+ TestRunner.logger.debug("SimpleTest finished " + finishedURL);
+
+ TestRunner._iframeDocuments[finishedURL] = doc;
+ // TestRunner._iframes[finishedURL].style.display = "none";
+ TestRunner._toggle(TestRunner._iframes[finishedURL]);
+ TestRunner._currentTest++;
+ TestRunner.runNextTest();
+};
+
+/**
+ * Display the summary in the browser
+**/
+TestRunner.makeSummary = function() {
+ if (TestRunner.logEnabled)
+ TestRunner.logger.log("SimpleTest FINISHED");
+ var rows = [];
+ for (var url in TestRunner._iframeDocuments) {
+ var doc = TestRunner._iframeDocuments[url];
+ var nOK = withDocument(doc,
+ partial(getElementsByTagAndClassName, 'div', 'test_ok')
+ ).length;
+ var nNotOK = withDocument(doc,
+ partial(getElementsByTagAndClassName, 'div', 'test_not_ok')
+ ).length;
+ var toggle = partial(TestRunner._toggle, TestRunner._iframes[url]);
+ var jsurl = "TestRunner._toggle(TestRunner._iframes['" + url + "'])";
+ var row = TR(
+ {'style': {'backgroundColor': nNotOK > 0 ? "#f00":"#0f0"}},
+ TD(null, url),
+ TD(null, nOK),
+ TD(null, nNotOK)
+ );
+ row.onclick = toggle;
+ var tbody = TestRunner._summaryDiv.getElementsByTagName("tbody")[0];
+ tbody.insertBefore(row, TestRunner._iframes[url]._row)
+ }
+};
Index: mochitest/tests/SimpleTest/quit.js
===================================================================
RCS file: mochitest/tests/SimpleTest/quit.js
diff -N mochitest/tests/SimpleTest/quit.js
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/tests/SimpleTest/quit.js 25 Oct 2006 20:24:48 -0000
@@ -0,0 +1,141 @@
+/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; -*- */
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (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.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is The Original Code is Mozilla Automated Testing Code
+ *
+ * The Initial Developer of the Original Code is
+ * Mozilla Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2005
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s): Bob Clary
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/*
+ From mozilla/toolkit/content
+ These files did not have a license
+*/
+
+function canQuitApplication()
+{
+ var os = Components.classes["@mozilla.org/observer-service;1"]
+ .getService(Components.interfaces.nsIObserverService);
+ if (!os)
+ {
+ return true;
+ }
+
+ try
+ {
+ var cancelQuit = Components.classes["@mozilla.org/supports-PRBool;1"]
+ .createInstance(Components.interfaces.nsISupportsPRBool);
+ os.notifyObservers(cancelQuit, "quit-application-requested", null);
+
+ // Something aborted the quit process.
+ if (cancelQuit.data)
+ {
+ return false;
+ }
+ }
+ catch (ex)
+ {
+ }
+ os.notifyObservers(null, "quit-application-granted", null);
+ return true;
+}
+
+function goQuitApplication()
+{
+ const privs = 'UniversalXPConnect';
+
+ try
+ {
+ netscape.security.PrivilegeManager.enablePrivilege(privs);
+ }
+ catch(ex)
+ {
+ throw('goQuitApplication: privilege failure ' + ex);
+ }
+
+ if (!canQuitApplication())
+ {
+ return false;
+ }
+
+ const kAppStartup = '@mozilla.org/toolkit/app-startup;1';
+ const kAppShell = '@mozilla.org/appshell/appShellService;1';
+ var appService;
+ var forceQuit;
+
+ if (kAppStartup in Components.classes)
+ {
+ appService = Components.classes[kAppStartup].
+ getService(Components.interfaces.nsIAppStartup);
+ forceQuit = Components.interfaces.nsIAppStartup.eForceQuit;
+
+ }
+ else if (kAppShell in Components.classes)
+ {
+ appService = Components.classes[kAppShell].
+ getService(Components.interfaces.nsIAppShellService);
+ forceQuit = Components.interfaces.nsIAppShellService.eForceQuit;
+ }
+ else
+ {
+ throw 'goQuitApplication: no AppStartup/appShell';
+ }
+
+ var windowManager = Components.
+ classes['@mozilla.org/appshell/window-mediator;1'].getService();
+
+ var windowManagerInterface = windowManager.
+ QueryInterface(Components.interfaces.nsIWindowMediator);
+
+ var enumerator = windowManagerInterface.getEnumerator(null);
+
+ while (enumerator.hasMoreElements())
+ {
+ var domWindow = enumerator.getNext();
+ if (("tryToClose" in domWindow) && !domWindow.tryToClose())
+ {
+ return false;
+ }
+ domWindow.close();
+ }
+
+ try
+ {
+ appService.quit(forceQuit);
+ }
+ catch(ex)
+ {
+ throw('goQuitApplication: ' + ex);
+ }
+
+ return true;
+}
+
Index: mochitest/tests/SimpleTest/test.css
===================================================================
RCS file: mochitest/tests/SimpleTest/test.css
diff -N mochitest/tests/SimpleTest/test.css
--- /dev/null 1 Jan 1970 00:00:00 -0000
+++ mochitest/tests/SimpleTest/test.css 25 Oct 2006 20:24:48 -0000
@@ -0,0 +1,28 @@
+.test_ok {
+ color: green;
+ display: none;
+}
+.test_not_ok {
+ color: red;
+ display: block;
+}
+
+.test_ok, .test_not_ok {
+ border-bottom-width: 2px;
+ border-bottom-style: solid;
+ border-bottom-color: black;
+}
+
+.all_pass {
+ background-color: lime;
+}
+
+.some_fail {
+ background-color: red;
+}
+
+.tests_report {
+ border-width: 2px;
+ border-style: solid;
+ width: 20em;
+}