From 6f4abdfbd519e8f8a416e24fdb541a88ef3104c6 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 6 Aug 2012 11:46:27 +0200 Subject: [IMP] move eval functions for domains, groupbys and contexts outside of corelib, as well as the standard evaluation context building (and related objects) bzr revid: xmo@openerp.com-20120806094627-8c9lwtfkbfws2bmj --- addons/web/static/src/js/boot.js | 2 +- addons/web/static/src/js/corelib.js | 229 +-------------------------------- addons/web/static/src/js/pyeval.js | 244 ++++++++++++++++++++++++++++++++++++ addons/web/static/test/evals.js | 13 +- addons/web/static/test/test.html | 1 + addons/web/static/test/testing.js | 3 +- 6 files changed, 257 insertions(+), 235 deletions(-) create mode 100644 addons/web/static/src/js/pyeval.js (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/boot.js b/addons/web/static/src/js/boot.js index 844dd88a0ac..dd014846884 100644 --- a/addons/web/static/src/js/boot.js +++ b/addons/web/static/src/js/boot.js @@ -48,7 +48,7 @@ * OpenERP Web web module split *---------------------------------------------------------*/ openerp.web = function(session) { - var files = ["corelib","coresetup","dates","formats","chrome","data","views","search","list","form","list_editable","web_mobile","view_tree","data_export","data_import"]; + var files = ["pyeval", "corelib","coresetup","dates","formats","chrome","data","views","search","list","form","list_editable","web_mobile","view_tree","data_export","data_import"]; for(var i=0; i 12) { - year += 1; - month -= 12; - } - } - - var lastMonthDay = new Date(year, month, 0).getDate(); - var day = asJS(this.ops.day) || asJS(other.day); - if (day > lastMonthDay) { day = lastMonthDay; } - var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0); - if (days_offset) { - day = new Date(year, month-1, day + days_offset).getDate(); - } - // TODO: leapdays? - // TODO: hours, minutes, seconds? Not used in XML domains - // TODO: weekday? - return new datetime.date(year, month, day); - }, - __radd__: function (other) { - return this.__add__(other); - }, - - __sub__: function (other) { - if (!(other instanceof datetime.date)) { - return py.NotImplemented; - } - // TODO: test this whole mess - var year = asJS(this.ops.year) || asJS(other.year); - if (asJS(this.ops.years)) { - year -= asJS(this.ops.years); - } - - var month = asJS(this.ops.month) || asJS(other.month); - if (asJS(this.ops.months)) { - month -= asJS(this.ops.months); - // FIXME: no divmod in JS? - while (month < 1) { - year -= 1; - month += 12; - } - while (month > 12) { - year += 1; - month -= 12; - } - } - - var lastMonthDay = new Date(year, month, 0).getDate(); - var day = asJS(this.ops.day) || asJS(other.day); - if (day > lastMonthDay) { day = lastMonthDay; } - var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0); - if (days_offset) { - day = new Date(year, month-1, day - days_offset).getDate(); - } - // TODO: leapdays? - // TODO: hours, minutes, seconds? Not used in XML domains - // TODO: weekday? - return new datetime.date(year, month, day); - }, - __rsub__: function (other) { - return this.__sub__(other); - } - }); - - return { - uid: new py.float(this.uid), - datetime: datetime, - time: time, - relativedelta: relativedelta, - current_date: date.today.__call__().strftime(['%Y-%m-%d']) - }; - }, /** * FIXME: Huge testing hack, especially the evaluation context, rewrite + test for real before switching */ @@ -1154,8 +1006,8 @@ instance.web.JsonRPC = instance.web.CallbackEnabled.extend({ ''; try { // see Session.eval_context in Python - var ctx = this.test_eval_contexts( - ([this.context] || []).concat(source.contexts)); + var ctx = instance.web.pyeval.eval('contexts', + ([this.context] || []).concat(source.contexts)); if (!_.isEqual(ctx, expected.context)) { instance.webclient.notification.warn('Context mismatch, report to xmo', _.str.sprintf(match_template, { @@ -1173,7 +1025,7 @@ instance.web.JsonRPC = instance.web.CallbackEnabled.extend({ } try { - var dom = this.test_eval_domains(source.domains, this.test_eval_get_context()); + var dom = instance.web.pyeval.eval('domains', source.domains); if (!_.isEqual(dom, expected.domain)) { instance.webclient.notification.warn('Domains mismatch, report to xmo', _.str.sprintf(match_template, { @@ -1191,7 +1043,7 @@ instance.web.JsonRPC = instance.web.CallbackEnabled.extend({ } try { - var groups = this.test_eval_groupby(source.group_by_seq); + var groups = instance.web.pyeval.eval('groupbys', source.group_by_seq); if (!_.isEqual(groups, expected.group_by)) { instance.webclient.notification.warn('GroupBy mismatch, report to xmo', _.str.sprintf(match_template, { @@ -1208,79 +1060,6 @@ instance.web.JsonRPC = instance.web.CallbackEnabled.extend({ }), true); } }, - test_eval_contexts: function (contexts, evaluation_context) { - evaluation_context = evaluation_context || {}; - var self = this; - return _(contexts).reduce(function (result_context, ctx) { - // __eval_context evaluations can lead to some of `contexts`'s - // values being null, skip them as well as empty contexts - if (_.isEmpty(ctx)) { return result_context; } - var evaluated = ctx; - switch(ctx.__ref) { - case 'context': - evaluated = py.eval(ctx.__debug, evaluation_context); - break; - case 'compound_context': - var eval_context = self.test_eval_contexts([ctx.__eval_context]); - evaluated = self.test_eval_contexts( - ctx.__contexts, _.extend({}, evaluation_context, eval_context)); - break; - } - // add newly evaluated context to evaluation context for following - // siblings - _.extend(evaluation_context, evaluated); - return _.extend(result_context, evaluated); - }, _.extend({}, this.user_context)); - }, - test_eval_domains: function (domains, evaluation_context) { - var result_domain = [], self = this; - _(domains).each(function (dom) { - switch(dom.__ref) { - case 'domain': - result_domain.push.apply( - result_domain, py.eval(dom.__debug, evaluation_context)); - break; - case 'compound_domain': - var eval_context = self.test_eval_contexts([dom.__eval_context]); - result_domain.push.apply( - result_domain, self.test_eval_domains( - dom.__domains, _.extend( - {}, evaluation_context, eval_context))); - break; - default: - result_domain.push.apply( - result_domain, dom); - } - }); - return result_domain; - }, - test_eval_groupby: function (contexts) { - var result_group = [], self = this; - _(contexts).each(function (ctx) { - var group; - switch(ctx.__ref) { - case 'context': - group = py.eval(ctx.__debug).group_by; - break; - case 'compound_context': - group = self.test_eval_contexts( - ctx.__contexts, ctx.__eval_context).group_by; - break; - default: - group = ctx.group_by - } - if (!group) { return; } - if (typeof group === 'string') { - result_group.push(group); - } else if (group instanceof Array) { - result_group.push.apply(result_group, group); - } else { - throw new Error('Got invalid groupby {{' - + JSON.stringify(group) + '}}'); - } - }); - return result_group; - }, /** * Executes an RPC call, registering the provided callbacks. * diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js new file mode 100644 index 00000000000..8c498c3f885 --- /dev/null +++ b/addons/web/static/src/js/pyeval.js @@ -0,0 +1,244 @@ +/* + * py.js helpers and setup + */ +openerp.web.pyeval = function (instance) { + instance.web.pyeval = {}; + + var asJS = function (arg) { + if (arg instanceof py.object) { + return arg.toJSON(); + } + return arg; + }; + + var datetime = new py.object(); + datetime.datetime = new py.type(function datetime() { + throw new Error('datetime.datetime not implemented'); + }); + var date = datetime.date = new py.type(function date(y, m, d) { + if (y instanceof Array) { + d = y[2]; + m = y[1]; + y = y[0]; + } + this.year = asJS(y); + this.month = asJS(m); + this.day = asJS(d); + }, py.object, { + strftime: function (args) { + var f = asJS(args[0]), self = this; + return new py.str(f.replace(/%([A-Za-z])/g, function (m, c) { + switch (c) { + case 'Y': return self.year; + case 'm': return _.str.sprintf('%02d', self.month); + case 'd': return _.str.sprintf('%02d', self.day); + } + throw new Error('ValueError: No known conversion for ' + m); + })); + } + }); + date.__getattribute__ = function (name) { + if (name === 'today') { + return date.today; + } + throw new Error("AttributeError: object 'date' has no attribute '" + name +"'"); + }; + date.today = new py.def(function () { + var d = new Date(); + return new date(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); + }); + datetime.time = new py.type(function time() { + throw new Error('datetime.time not implemented'); + }); + + var time = new py.object(); + time.strftime = new py.def(function (args) { + return date.today.__call__().strftime(args); + }); + + var relativedelta = new py.type(function relativedelta(args, kwargs) { + if (!_.isEmpty(args)) { + throw new Error('Extraction of relative deltas from existing datetimes not supported'); + } + this.ops = kwargs; + }, py.object, { + __add__: function (other) { + if (!(other instanceof datetime.date)) { + return py.NotImplemented; + } + // TODO: test this whole mess + var year = asJS(this.ops.year) || asJS(other.year); + if (asJS(this.ops.years)) { + year += asJS(this.ops.years); + } + + var month = asJS(this.ops.month) || asJS(other.month); + if (asJS(this.ops.months)) { + month += asJS(this.ops.months); + // FIXME: no divmod in JS? + while (month < 1) { + year -= 1; + month += 12; + } + while (month > 12) { + year += 1; + month -= 12; + } + } + + var lastMonthDay = new Date(year, month, 0).getDate(); + var day = asJS(this.ops.day) || asJS(other.day); + if (day > lastMonthDay) { day = lastMonthDay; } + var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0); + if (days_offset) { + day = new Date(year, month-1, day + days_offset).getDate(); + } + // TODO: leapdays? + // TODO: hours, minutes, seconds? Not used in XML domains + // TODO: weekday? + return new datetime.date(year, month, day); + }, + __radd__: function (other) { + return this.__add__(other); + }, + + __sub__: function (other) { + if (!(other instanceof datetime.date)) { + return py.NotImplemented; + } + // TODO: test this whole mess + var year = asJS(this.ops.year) || asJS(other.year); + if (asJS(this.ops.years)) { + year -= asJS(this.ops.years); + } + + var month = asJS(this.ops.month) || asJS(other.month); + if (asJS(this.ops.months)) { + month -= asJS(this.ops.months); + // FIXME: no divmod in JS? + while (month < 1) { + year -= 1; + month += 12; + } + while (month > 12) { + year += 1; + month -= 12; + } + } + + var lastMonthDay = new Date(year, month, 0).getDate(); + var day = asJS(this.ops.day) || asJS(other.day); + if (day > lastMonthDay) { day = lastMonthDay; } + var days_offset = ((asJS(this.ops.weeks) || 0) * 7) + (asJS(this.ops.days) || 0); + if (days_offset) { + day = new Date(year, month-1, day - days_offset).getDate(); + } + // TODO: leapdays? + // TODO: hours, minutes, seconds? Not used in XML domains + // TODO: weekday? + return new datetime.date(year, month, day); + }, + __rsub__: function (other) { + return this.__sub__(other); + } + }); + + var eval_contexts = function (contexts, evaluation_context) { + evaluation_context = evaluation_context || {}; + return _(contexts).reduce(function (result_context, ctx) { + // __eval_context evaluations can lead to some of `contexts`'s + // values being null, skip them as well as empty contexts + if (_.isEmpty(ctx)) { return result_context; } + var evaluated = ctx; + switch(ctx.__ref) { + case 'context': + evaluated = py.eval(ctx.__debug, evaluation_context); + break; + case 'compound_context': + var eval_context = eval_contexts([ctx.__eval_context]); + evaluated = eval_contexts( + ctx.__contexts, _.extend({}, evaluation_context, eval_context)); + break; + } + // add newly evaluated context to evaluation context for following + // siblings + _.extend(evaluation_context, evaluated); + return _.extend(result_context, evaluated); + }, _.extend({}, instance.connection.user_context)); + }; + var eval_domains = function (domains, evaluation_context) { + var result_domain = []; + _(domains).each(function (domain) { + switch(domain.__ref) { + case 'domain': + result_domain.push.apply( + result_domain, py.eval(domain.__debug, evaluation_context)); + break; + case 'compound_domain': + var eval_context = eval_contexts([domain.__eval_context]); + result_domain.push.apply( + result_domain, eval_domains( + domain.__domains, _.extend( + {}, evaluation_context, eval_context))); + break; + default: + result_domain.push.apply(result_domain, domain); + } + }); + return result_domain; + }; + var eval_groupbys = function (contexts, evaluation_context) { + var result_group = []; + _(contexts).each(function (ctx) { + var group; + var evaluated = ctx; + switch(ctx.__ref) { + case 'context': + evaluated = py.eval(ctx.__debug), evaluation_context; + break; + case 'compound_context': + var eval_context = eval_contexts([ctx.__eval_context]); + evaluated = eval_contexts( + ctx.__contexts, _.extend({}, evaluation_context, eval_context)); + break; + } + group = evaluated.group_by; + if (!group) { return; } + if (typeof group === 'string') { + result_group.push(group); + } else if (group instanceof Array) { + result_group.push.apply(result_group, group); + } else { + throw new Error('Got invalid groupby {{' + + JSON.stringify(group) + '}}'); + } + _.extend(evaluation_context, evaluated); + }); + return result_group; + }; + + instance.web.pyeval.context = function () { + return { + uid: new py.float(instance.connection.uid), + datetime: datetime, + time: time, + relativedelta: relativedelta, + current_date: date.today.__call__().strftime(['%Y-%m-%d']), + }; + }; + + /** + * @param {String} type "domains", "contexts" or "groupbys" + * @param {Array} object domains or contexts to evaluate + * @param {Object} [context] evaluation context + */ + instance.web.pyeval.eval = function (type, object, context) { + if (!context) { context = instance.web.pyeval.context()} + switch(type) { + case 'contexts': return eval_contexts(object, context); + case 'domains': return eval_domains(object, context); + case 'groupbys': return eval_groupbys(object, context); + } + throw new Error("Unknow evaluation type " + type) + }; +}; diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index 7bc6554e074..ee4aef4bf79 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -3,16 +3,14 @@ $(document).ready(function () { module("eval.contexts", { setup: function () { - openerp = window.openerp.init([]); - window.openerp.web.corelib(openerp); - window.openerp.web.coresetup(openerp); + openerp = window.openerp.testing.instanceFor('coresetup'); } }); test('context_sequences', function () { // Context n should have base evaluation context + all of contexts // 0..n-1 in its own evaluation context var active_id = 4; - var result = openerp.connection.test_eval_contexts([ + var result = openerp.web.pyeval.eval('contexts', [ { "__contexts": [ { @@ -56,7 +54,7 @@ $(document).ready(function () { }); }); test('non-literal_eval_contexts', function () { - var result = openerp.connection.test_eval_contexts([{ + var result = openerp.web.pyeval.eval('contexts', [{ "__ref": "compound_context", "__contexts": [ {"__ref": "context", "__debug": "{'type':parent.type}", @@ -141,9 +139,8 @@ $(document).ready(function () { }); test('current_date', function () { var current_date = openerp.web.date_to_str(new Date()); - var result = openerp.connection.test_eval_domains( - [[],{"__ref":"domain","__debug":"[('name','>=',current_date),('name','<=',current_date)]","__id":"5dedcfc96648"}], - openerp.connection.test_eval_get_context()); + var result = openerp.web.pyeval.eval('domains', + [[],{"__ref":"domain","__debug":"[('name','>=',current_date),('name','<=',current_date)]","__id":"5dedcfc96648"}]); deepEqual(result, [ ['name', '>=', current_date], ['name', '<=', current_date] diff --git a/addons/web/static/test/test.html b/addons/web/static/test/test.html index 35d57d3c3a6..91b45c44bad 100644 --- a/addons/web/static/test/test.html +++ b/addons/web/static/test/test.html @@ -28,6 +28,7 @@ + diff --git a/addons/web/static/test/testing.js b/addons/web/static/test/testing.js index e9525fc82a0..9a449a40493 100644 --- a/addons/web/static/test/testing.js +++ b/addons/web/static/test/testing.js @@ -6,7 +6,8 @@ openerp.testing = (function () { var doc = xhr.responseXML; var dependencies = { - corelib: [], + pyeval: [], + corelib: ['pyeval'], coresetup: ['corelib'], data: ['corelib', 'coresetup'], dates: [], -- cgit v1.2.3 From 6a23c24da13f5907d4c407e919bff187a3a0ae1d Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 6 Aug 2012 13:06:38 +0200 Subject: [UP] py.js, old != operator and basic dict handling bzr revid: xmo@openerp.com-20120806110638-1m4rg205sb3vjvm5 --- addons/web/static/lib/py.js/.hg_archival.txt | 4 ++-- addons/web/static/lib/py.js/README.rst | 26 +++++++++++++--------- addons/web/static/lib/py.js/lib/py.js | 32 +++++++++++++++++++++++++--- addons/web/static/lib/py.js/test/test.js | 28 ++++++++++++++++++++++++ 4 files changed, 75 insertions(+), 15 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/lib/py.js/.hg_archival.txt b/addons/web/static/lib/py.js/.hg_archival.txt index 35e98c8501d..2aa926eb56a 100644 --- a/addons/web/static/lib/py.js/.hg_archival.txt +++ b/addons/web/static/lib/py.js/.hg_archival.txt @@ -1,5 +1,5 @@ repo: 076b192d0d8ab2b92d1dbcfa3da055382f30eaea -node: 1758bfec1ec1dcff95dcc4c72269cc0e3d000afd +node: 87e977311edbbb5f281b87390a9a304eb194ce89 branch: default latesttag: 0.5 -latesttagdistance: 11 +latesttagdistance: 15 diff --git a/addons/web/static/lib/py.js/README.rst b/addons/web/static/lib/py.js/README.rst index 046db7153d1..eea1cbbf963 100644 --- a/addons/web/static/lib/py.js/README.rst +++ b/addons/web/static/lib/py.js/README.rst @@ -60,7 +60,7 @@ Builtins Same as tuple (``list`` is currently an alias for ``tuple``) ``dict`` - Implements just about nothing + Implements trivial getting and setting, nothing beyond that. Note that most methods are probably missing from all of these. @@ -72,14 +72,14 @@ sub-protocols) of the `Python 2.7 data model `_: Rich comparisons - Roughly complete implementation but for two limits: ``__eq__`` and - ``__ne__`` can't return ``NotImplemented`` (well they can but it's - not going to work right), and the behavior is undefined if a - rich-comparison operation does not return a ``py.bool``. + Pretty much complete (including operator fallbacks), although the + behavior is currently undefined if an operation does not return + either a ``py.bool`` or ``NotImplemented``. - Also, a ``NotImplemented`` result does not try the reverse - operation, not sure if it's supposed to. It directly falls back to - comparing type names. + ``__hash__`` is supported (and used), but it should return **a + javascript string**. ``py.js``'s dict build on javascript objects, + reimplementing numeral hashing is worthless complexity at this + point. Boolean conversion Implementing ``__nonzero__`` should work. @@ -93,6 +93,12 @@ Descriptor protocol As with attributes, ``__delete__`` is not implemented. Callable objects + Work, although the handling of arguments isn't exactly nailed + down. For now, callables get two (javascript) arguments ``args`` + and ``kwargs``, holding (respectively) positional and keyword + arguments. + + Conflicts are *not* handled at this point. Collections Abstract Base Classes Container is the only implemented ABC protocol (ABCs themselves @@ -119,8 +125,8 @@ implementation: ``py.js`` types. When accessing instance methods, ``py.js`` automatically wraps - these in a variant of ``py.def`` automatically, to behave as - Python's (bound) methods. + these in a variant of ``py.def``, to behave as Python's (bound) + methods. Why === diff --git a/addons/web/static/lib/py.js/lib/py.js b/addons/web/static/lib/py.js/lib/py.js index a8c952679af..79a0ace1995 100644 --- a/addons/web/static/lib/py.js/lib/py.js +++ b/addons/web/static/lib/py.js/lib/py.js @@ -433,7 +433,8 @@ var py = {}; if (this._hash) { return this._hash; } - return this._hash = hash_counter++; + // tagged counter, to avoid collisions with e.g. number hashes + return this._hash = '\0\0\0' + String(hash_counter++); }, __eq__: function (other) { return (this === other) ? py.True : py.False; @@ -597,6 +598,9 @@ var py = {}; throw new Error('TypeError: __str__ returned non-string (type ' + v.constructor.name + ')'); }, py.object, { + __hash__: function () { + return '\1\0\1' + this._value; + }, __eq__: function (other) { if (other instanceof py.str && this._value === other._value) { return py.True; @@ -654,12 +658,33 @@ var py = {}; } }); py.list = py.tuple; - py.dict = py.type(function dict() { + py.dict = py.type(function dict(d) { this._store = {}; + for (var k in (d || {})) { + if (!d.hasOwnProperty(k)) { continue; } + var py_k = new py.str(k); + var val = PY_ensurepy(d[k]); + this._store[py_k.__hash__()] = [py_k, val]; + } }, py.object, { + __getitem__: function (key) { + var h = key.__hash__(); + if (!(h in this._store)) { + throw new Error("KeyError: '" + key.toJSON() + "'"); + } + return this._store[h][1]; + }, __setitem__: function (key, value) { this._store[key.__hash__()] = [key, value]; }, + get: function (args) { + var h = args[0].__hash__(); + var def = args.length > 1 ? args[1] : py.None; + if (!(h in this._store)) { + return def; + } + return this._store[h][1]; + }, toJSON: function () { var out = {}; for(var k in this._store) { @@ -700,6 +725,7 @@ var py = {}; var PY_operators = { '==': ['eq', 'eq', function (a, b) { return a === b; }], '!=': ['ne', 'ne', function (a, b) { return a !== b; }], + '<>': ['ne', 'ne', function (a, b) { return a !== b; }], '<': ['lt', 'gt', function (a, b) {return a.constructor.name < b.constructor.name;}], '<=': ['le', 'ge', function (a, b) {return a.constructor.name <= b.constructor.name;}], '>': ['gt', 'lt', function (a, b) {return a.constructor.name > b.constructor.name;}], @@ -782,7 +808,7 @@ var py = {}; return b.__contains__(a); case 'not in': return b.__contains__(a) === py.True ? py.False : py.True; - case '==': case '!=': + case '==': case '!=': case '<>': case '<': case '<=': case '>': case '>=': return PY_op(a, b, operator); diff --git a/addons/web/static/lib/py.js/test/test.js b/addons/web/static/lib/py.js/test/test.js index c1f92c44d81..f09245a38c8 100644 --- a/addons/web/static/lib/py.js/test/test.js +++ b/addons/web/static/lib/py.js/test/test.js @@ -117,6 +117,11 @@ describe('Comparisons', function () { expect(py.eval('foo != bar', {foo: 'qux', bar: 'quux'})) .to.be(true); }); + it('should accept deprecated form', function () { + expect(py.eval('1 <> 2')).to.be(true); + expect(py.eval('"foo" <> "foo"')).to.be(false); + expect(py.eval('"foo" <> "bar"')).to.be(true); + }); }); describe('rich comparisons', function () { it('should work with numbers', function () { @@ -377,6 +382,29 @@ describe('numerical protocols', function () { }); }); }); +describe('dicts', function () { + it('should be possible to retrieve their value', function () { + var d = new py.dict({foo: 3, bar: 4, baz: 5}); + expect(py.eval('d["foo"]', {d: d})).to.be(3); + expect(py.eval('d["baz"]', {d: d})).to.be(5); + }); + it('should raise KeyError if a key is missing', function () { + var d = new py.dict(); + expect(function () { + py.eval('d["foo"]', {d: d}); + }).to.throwException(/^KeyError/); + }); + it('should have a method to provide a default value', function () { + var d = new py.dict({foo: 3}); + expect(py.eval('d.get("foo")', {d: d})).to.be(3); + expect(py.eval('d.get("bar")', {d: d})).to.be(null); + expect(py.eval('d.get("bar", 42)', {d: d})).to.be(42); + + var e = new py.dict({foo: null}); + expect(py.eval('d.get("foo")', {d: e})).to.be(null); + expect(py.eval('d.get("bar")', {d: e})).to.be(null); + }); +}); describe('Type converter', function () { it('should convert bare objects to objects', function () { expect(py.eval('foo.bar', {foo: {bar: 3}})).to.be(3); -- cgit v1.2.3 From 0e101c63a3355e2aebce2d38f985e9ac6dc96376 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 5 Oct 2012 15:12:05 +0200 Subject: [FIX] evaluator: connection -> session bzr revid: xmo@openerp.com-20121005131205-ffk746ac5xrua62j --- addons/web/static/src/js/pyeval.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 8c498c3f885..007d73081ce 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -164,7 +164,7 @@ openerp.web.pyeval = function (instance) { // siblings _.extend(evaluation_context, evaluated); return _.extend(result_context, evaluated); - }, _.extend({}, instance.connection.user_context)); + }, _.extend({}, instance.session.user_context)); }; var eval_domains = function (domains, evaluation_context) { var result_domain = []; @@ -219,7 +219,7 @@ openerp.web.pyeval = function (instance) { instance.web.pyeval.context = function () { return { - uid: new py.float(instance.connection.uid), + uid: new py.float(instance.session.uid), datetime: datetime, time: time, relativedelta: relativedelta, -- cgit v1.2.3 From 10bc6ddfe4e12e792d856369b482ae74f73197d0 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 5 Oct 2012 16:28:08 +0200 Subject: [ADD] groupby eval tests bzr revid: xmo@openerp.com-20121005142808-yx6o8nfnn0o4ms56 --- addons/web/static/src/js/pyeval.js | 2 +- addons/web/static/test/evals.js | 73 +++++++++++++++++++++++++++++++++++++- 2 files changed, 73 insertions(+), 2 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 007d73081ce..34ddf0e119b 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -194,7 +194,7 @@ openerp.web.pyeval = function (instance) { var evaluated = ctx; switch(ctx.__ref) { case 'context': - evaluated = py.eval(ctx.__debug), evaluation_context; + evaluated = py.eval(ctx.__debug, evaluation_context); break; case 'compound_context': var eval_context = eval_contexts([ctx.__eval_context]); diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index ee4aef4bf79..dc8ceb83daf 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -145,5 +145,76 @@ $(document).ready(function () { ['name', '>=', current_date], ['name', '<=', current_date] ]); - }) + }); + + module('eval.groupbys', { + setup: function () { + openerp = window.openerp.testing.instanceFor('coresetup'); + } + }); + test('groupbys_00', function () { + var result = openerp.web.pyeval.eval('groupbys', [ + {group_by: 'foo'}, + {group_by: ['bar', 'qux']}, + {group_by: null}, + {group_by: 'grault'} + ]); + deepEqual(result, ['foo', 'bar', 'qux', 'grault']); + }); + test('groupbys_01', function () { + var result = openerp.web.pyeval.eval('groupbys', [ + {group_by: 'foo'}, + { __ref: 'context', __debug: '{"group_by": "bar"}' }, + {group_by: 'grault'} + ]); + deepEqual(result, ['foo', 'bar', 'grault']); + }); + test('groupbys_02', function () { + var result = openerp.web.pyeval.eval('groupbys', [ + {group_by: 'foo'}, + { + __ref: 'compound_context', + __contexts: [ {group_by: 'bar'} ], + __eval_context: null + }, + {group_by: 'grault'} + ]); + deepEqual(result, ['foo', 'bar', 'grault']); + }); + test('groupbys_03', function () { + var result = openerp.web.pyeval.eval('groupbys', [ + {group_by: 'foo'}, + { + __ref: 'compound_context', + __contexts: [ + { __ref: 'context', __debug: '{"group_by": value}' } + ], + __eval_context: { value: 'bar' } + }, + {group_by: 'grault'} + ]); + deepEqual(result, ['foo', 'bar', 'grault']); + }); + test('groupbys_04', function () { + var result = openerp.web.pyeval.eval('groupbys', [ + {group_by: 'foo'}, + { + __ref: 'compound_context', + __contexts: [ + { __ref: 'context', __debug: '{"group_by": value}' } + ], + __eval_context: { value: 'bar' } + }, + {group_by: 'grault'} + ], { value: 'bar' }); + deepEqual(result, ['foo', 'bar', 'grault']); + }); + test('groupbys_05', function () { + var result = openerp.web.pyeval.eval('groupbys', [ + {group_by: 'foo'}, + { __ref: 'context', __debug: '{"group_by": value}' }, + {group_by: 'grault'} + ], { value: 'bar' }); + deepEqual(result, ['foo', 'bar', 'grault']); + }); }); -- cgit v1.2.3 From 7bcbadb099a71b731812ace299b98317edc49ae4 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 8 Oct 2012 14:06:19 +0200 Subject: [FIX] update py.js to 0.6, port existin classes to it, attempt to implement timedelta bzr revid: xmo@openerp.com-20121008120619-lhmexjnujjrigjn9 --- addons/web/static/lib/py.js/.hg_archival.txt | 6 +- addons/web/static/lib/py.js/README.rst | 9 +- addons/web/static/lib/py.js/doc/Makefile | 153 +++++++ addons/web/static/lib/py.js/doc/builtins.rst | 53 +++ addons/web/static/lib/py.js/doc/conf.py | 247 +++++++++++ addons/web/static/lib/py.js/doc/differences.rst | 64 +++ addons/web/static/lib/py.js/doc/index.rst | 161 ++++++++ addons/web/static/lib/py.js/doc/make.bat | 190 +++++++++ addons/web/static/lib/py.js/doc/types.rst | 248 +++++++++++ addons/web/static/lib/py.js/doc/utility.rst | 111 +++++ addons/web/static/lib/py.js/lib/py.js | 528 +++++++++++++++++------- addons/web/static/lib/py.js/test/parser.js | 132 ------ addons/web/static/lib/py.js/test/test.js | 416 ------------------- addons/web/static/src/js/pyeval.js | 195 ++++++--- addons/web/static/test/evals.js | 44 ++ 15 files changed, 1795 insertions(+), 762 deletions(-) create mode 100644 addons/web/static/lib/py.js/doc/Makefile create mode 100644 addons/web/static/lib/py.js/doc/builtins.rst create mode 100644 addons/web/static/lib/py.js/doc/conf.py create mode 100644 addons/web/static/lib/py.js/doc/differences.rst create mode 100644 addons/web/static/lib/py.js/doc/index.rst create mode 100644 addons/web/static/lib/py.js/doc/make.bat create mode 100644 addons/web/static/lib/py.js/doc/types.rst create mode 100644 addons/web/static/lib/py.js/doc/utility.rst delete mode 100644 addons/web/static/lib/py.js/test/parser.js delete mode 100644 addons/web/static/lib/py.js/test/test.js (limited to 'addons/web/static') diff --git a/addons/web/static/lib/py.js/.hg_archival.txt b/addons/web/static/lib/py.js/.hg_archival.txt index 2aa926eb56a..e97bf6a334b 100644 --- a/addons/web/static/lib/py.js/.hg_archival.txt +++ b/addons/web/static/lib/py.js/.hg_archival.txt @@ -1,5 +1,5 @@ repo: 076b192d0d8ab2b92d1dbcfa3da055382f30eaea -node: 87e977311edbbb5f281b87390a9a304eb194ce89 +node: e47d717cf47d165a5a9916abbb5ceb138661efc6 branch: default -latesttag: 0.5 -latesttagdistance: 15 +latesttag: 0.6 +latesttagdistance: 1 diff --git a/addons/web/static/lib/py.js/README.rst b/addons/web/static/lib/py.js/README.rst index eea1cbbf963..7601318df6d 100644 --- a/addons/web/static/lib/py.js/README.rst +++ b/addons/web/static/lib/py.js/README.rst @@ -1,14 +1,7 @@ What ==== -``py.js`` is a parser and evaluator of Python expressions, written in -pure javascript. -``py.js`` is not intended to implement a full Python interpreter -(although it could be used for such an effort later on), its -specification document is the `Python 2.7 Expressions spec -`_ (along with the -lexical analysis part). Syntax ------ @@ -69,7 +62,7 @@ Data model protocols ``py.js`` currently implements the following protocols (or sub-protocols) of the `Python 2.7 data model -`_: +<>`_: Rich comparisons Pretty much complete (including operator fallbacks), although the diff --git a/addons/web/static/lib/py.js/doc/Makefile b/addons/web/static/lib/py.js/doc/Makefile new file mode 100644 index 00000000000..cb7d658e796 --- /dev/null +++ b/addons/web/static/lib/py.js/doc/Makefile @@ -0,0 +1,153 @@ +# Makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +PAPER = +BUILDDIR = _build + +# Internal variables. +PAPEROPT_a4 = -D latex_paper_size=a4 +PAPEROPT_letter = -D latex_paper_size=letter +ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . +# the i18n builder cannot share the environment and doctrees with the others +I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . + +.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext + +help: + @echo "Please use \`make ' where is one of" + @echo " html to make standalone HTML files" + @echo " dirhtml to make HTML files named index.html in directories" + @echo " singlehtml to make a single large HTML file" + @echo " pickle to make pickle files" + @echo " json to make JSON files" + @echo " htmlhelp to make HTML files and a HTML help project" + @echo " qthelp to make HTML files and a qthelp project" + @echo " devhelp to make HTML files and a Devhelp project" + @echo " epub to make an epub" + @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" + @echo " latexpdf to make LaTeX files and run them through pdflatex" + @echo " text to make text files" + @echo " man to make manual pages" + @echo " texinfo to make Texinfo files" + @echo " info to make Texinfo files and run them through makeinfo" + @echo " gettext to make PO message catalogs" + @echo " changes to make an overview of all changed/added/deprecated items" + @echo " linkcheck to check all external links for integrity" + @echo " doctest to run all doctests embedded in the documentation (if enabled)" + +clean: + -rm -rf $(BUILDDIR)/* + +html: + $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." + +dirhtml: + $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml + @echo + @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." + +singlehtml: + $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml + @echo + @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." + +pickle: + $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle + @echo + @echo "Build finished; now you can process the pickle files." + +json: + $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json + @echo + @echo "Build finished; now you can process the JSON files." + +htmlhelp: + $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp + @echo + @echo "Build finished; now you can run HTML Help Workshop with the" \ + ".hhp project file in $(BUILDDIR)/htmlhelp." + +qthelp: + $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp + @echo + @echo "Build finished; now you can run "qcollectiongenerator" with the" \ + ".qhcp project file in $(BUILDDIR)/qthelp, like this:" + @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pyjs.qhcp" + @echo "To view the help file:" + @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pyjs.qhc" + +devhelp: + $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp + @echo + @echo "Build finished." + @echo "To view the help file:" + @echo "# mkdir -p $$HOME/.local/share/devhelp/pyjs" + @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pyjs" + @echo "# devhelp" + +epub: + $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub + @echo + @echo "Build finished. The epub file is in $(BUILDDIR)/epub." + +latex: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo + @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." + @echo "Run \`make' in that directory to run these through (pdf)latex" \ + "(use \`make latexpdf' here to do that automatically)." + +latexpdf: + $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex + @echo "Running LaTeX files through pdflatex..." + $(MAKE) -C $(BUILDDIR)/latex all-pdf + @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." + +text: + $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text + @echo + @echo "Build finished. The text files are in $(BUILDDIR)/text." + +man: + $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man + @echo + @echo "Build finished. The manual pages are in $(BUILDDIR)/man." + +texinfo: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo + @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." + @echo "Run \`make' in that directory to run these through makeinfo" \ + "(use \`make info' here to do that automatically)." + +info: + $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo + @echo "Running Texinfo files through makeinfo..." + make -C $(BUILDDIR)/texinfo info + @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." + +gettext: + $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale + @echo + @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." + +changes: + $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes + @echo + @echo "The overview file is in $(BUILDDIR)/changes." + +linkcheck: + $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck + @echo + @echo "Link check complete; look for any errors in the above output " \ + "or in $(BUILDDIR)/linkcheck/output.txt." + +doctest: + $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest + @echo "Testing of doctests in the sources finished, look at the " \ + "results in $(BUILDDIR)/doctest/output.txt." diff --git a/addons/web/static/lib/py.js/doc/builtins.rst b/addons/web/static/lib/py.js/doc/builtins.rst new file mode 100644 index 00000000000..e46926566d3 --- /dev/null +++ b/addons/web/static/lib/py.js/doc/builtins.rst @@ -0,0 +1,53 @@ +.. default-domain: python + +.. _builtins: + +Supported Python builtins +========================= + +.. function:: py.type(object) + + Gets the class of a provided object, if possible. + + .. note:: currently doesn't work correctly when called on a class + object, will return the class itself (also, classes + don't currently have a type). + +.. js:function:: py.type(name, bases, dict) + + Not exactly a builtin as this form is solely javascript-level + (currently). Used to create new ``py.js`` types. See :doc:`types` + for its usage. + +.. data:: py.None + +.. data:: py.True + +.. data:: py.False + +.. data:: py.NotImplemented + +.. class:: py.object + + Base class for all types, even implicitly (if no bases are + provided to :js:func:`py.type`) + +.. class:: py.bool([object]) + +.. class:: py.float([object]) + +.. class:: py.str([object]) + +.. class:: py.unicode([object]) + +.. class:: py.tuple() + +.. class:: py.list() + +.. class:: py.dict() + +.. function:: py.isinstance(object, type) + +.. function:: py.issubclass(type, other_type) + +.. class:: py.classmethod diff --git a/addons/web/static/lib/py.js/doc/conf.py b/addons/web/static/lib/py.js/doc/conf.py new file mode 100644 index 00000000000..287f21af577 --- /dev/null +++ b/addons/web/static/lib/py.js/doc/conf.py @@ -0,0 +1,247 @@ +# -*- coding: utf-8 -*- +# +# py.js documentation build configuration file, created by +# sphinx-quickstart on Sun Sep 9 19:36:23 2012. +# +# This file is execfile()d with the current directory set to its containing dir. +# +# Note that not all possible configuration values are present in this +# autogenerated file. +# +# All configuration values have a default; values that are commented out +# serve to show the default. + +import sys, os + +# If extensions (or modules to document with autodoc) are in another directory, +# add these directories to sys.path here. If the directory is relative to the +# documentation root, use os.path.abspath to make it absolute, like shown here. +#sys.path.insert(0, os.path.abspath('.')) + +# -- General configuration ----------------------------------------------------- + +# If your documentation needs a minimal Sphinx version, state it here. +#needs_sphinx = '1.0' + +# Add any Sphinx extension module names here, as strings. They can be extensions +# coming with Sphinx (named 'sphinx.ext.*') or your custom ones. +extensions = ['sphinx.ext.todo'] + +# Add any paths that contain templates here, relative to this directory. +templates_path = ['_templates'] + +# The suffix of source filenames. +source_suffix = '.rst' + +# The encoding of source files. +#source_encoding = 'utf-8-sig' + +# The master toctree document. +master_doc = 'index' + +# General information about the project. +project = u'py.js' +copyright = u'2012, Xavier Morel' + +# The version info for the project you're documenting, acts as replacement for +# |version| and |release|, also used in various other places throughout the +# built documents. +# +# The short X.Y version. +version = '0.6' +# The full version, including alpha/beta/rc tags. +release = '0.6' + +# The language for content autogenerated by Sphinx. Refer to documentation +# for a list of supported languages. +#language = None + +# There are two options for replacing |today|: either, you set today to some +# non-false value, then it is used: +#today = '' +# Else, today_fmt is used as the format for a strftime call. +#today_fmt = '%B %d, %Y' + +# List of patterns, relative to source directory, that match files and +# directories to ignore when looking for source files. +exclude_patterns = ['_build'] + +# The reST default role (used for this markup: `text`) to use for all documents. +#default_role = None + +# Default sphinx domain +default_domain = 'js' + +# If true, '()' will be appended to :func: etc. cross-reference text. +#add_function_parentheses = True + +# If true, the current module name will be prepended to all description +# unit titles (such as .. function::). +#add_module_names = True + +# If true, sectionauthor and moduleauthor directives will be shown in the +# output. They are ignored by default. +#show_authors = False + +# The name of the Pygments (syntax highlighting) style to use. +pygments_style = 'sphinx' +# default code-block highlighting +highlight_language = 'javascript' + +# A list of ignored prefixes for module index sorting. +#modindex_common_prefix = [] + + +# -- Options for HTML output --------------------------------------------------- + +# The theme to use for HTML and HTML Help pages. See the documentation for +# a list of builtin themes. +html_theme = 'default' + +# Theme options are theme-specific and customize the look and feel of a theme +# further. For a list of options available for each theme, see the +# documentation. +#html_theme_options = {} + +# Add any paths that contain custom themes here, relative to this directory. +#html_theme_path = [] + +# The name for this set of Sphinx documents. If None, it defaults to +# " v documentation". +#html_title = None + +# A shorter title for the navigation bar. Default is the same as html_title. +#html_short_title = None + +# The name of an image file (relative to this directory) to place at the top +# of the sidebar. +#html_logo = None + +# The name of an image file (within the static path) to use as favicon of the +# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 +# pixels large. +#html_favicon = None + +# Add any paths that contain custom static files (such as style sheets) here, +# relative to this directory. They are copied after the builtin static files, +# so a file named "default.css" will overwrite the builtin "default.css". +html_static_path = ['_static'] + +# If not '', a 'Last updated on:' timestamp is inserted at every page bottom, +# using the given strftime format. +#html_last_updated_fmt = '%b %d, %Y' + +# If true, SmartyPants will be used to convert quotes and dashes to +# typographically correct entities. +#html_use_smartypants = True + +# Custom sidebar templates, maps document names to template names. +#html_sidebars = {} + +# Additional templates that should be rendered to pages, maps page names to +# template names. +#html_additional_pages = {} + +# If false, no module index is generated. +#html_domain_indices = True + +# If false, no index is generated. +#html_use_index = True + +# If true, the index is split into individual pages for each letter. +#html_split_index = False + +# If true, links to the reST sources are added to the pages. +#html_show_sourcelink = True + +# If true, "Created using Sphinx" is shown in the HTML footer. Default is True. +#html_show_sphinx = True + +# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. +#html_show_copyright = True + +# If true, an OpenSearch description file will be output, and all pages will +# contain a tag referring to it. The value of this option must be the +# base URL from which the finished HTML is served. +#html_use_opensearch = '' + +# This is the file name suffix for HTML files (e.g. ".xhtml"). +#html_file_suffix = None + +# Output file base name for HTML help builder. +htmlhelp_basename = 'pyjsdoc' + + +# -- Options for LaTeX output -------------------------------------------------- + +latex_elements = { +# The paper size ('letterpaper' or 'a4paper'). +#'papersize': 'letterpaper', + +# The font size ('10pt', '11pt' or '12pt'). +#'pointsize': '10pt', + +# Additional stuff for the LaTeX preamble. +#'preamble': '', +} + +# Grouping the document tree into LaTeX files. List of tuples +# (source start file, target name, title, author, documentclass [howto/manual]). +latex_documents = [ + ('index', 'pyjs.tex', u'py.js Documentation', + u'Xavier Morel', 'manual'), +] + +# The name of an image file (relative to this directory) to place at the top of +# the title page. +#latex_logo = None + +# For "manual" documents, if this is true, then toplevel headings are parts, +# not chapters. +#latex_use_parts = False + +# If true, show page references after internal links. +#latex_show_pagerefs = False + +# If true, show URL addresses after external links. +#latex_show_urls = False + +# Documents to append as an appendix to all manuals. +#latex_appendices = [] + +# If false, no module index is generated. +#latex_domain_indices = True + + +# -- Options for manual page output -------------------------------------------- + +# One entry per manual page. List of tuples +# (source start file, name, description, authors, manual section). +man_pages = [ + ('index', 'pyjs', u'py.js Documentation', + [u'Xavier Morel'], 1) +] + +# If true, show URL addresses after external links. +#man_show_urls = False + + +# -- Options for Texinfo output ------------------------------------------------ + +# Grouping the document tree into Texinfo files. List of tuples +# (source start file, target name, title, author, +# dir menu entry, description, category) +texinfo_documents = [ + ('index', 'pyjs', u'py.js Documentation', + u'Xavier Morel', 'pyjs', 'One line description of project.', + 'Miscellaneous'), +] + +# Documents to append as an appendix to all manuals. +#texinfo_appendices = [] + +# If false, no module index is generated. +#texinfo_domain_indices = True + +# How to display URL addresses: 'footnote', 'no', or 'inline'. +#texinfo_show_urls = 'footnote' diff --git a/addons/web/static/lib/py.js/doc/differences.rst b/addons/web/static/lib/py.js/doc/differences.rst new file mode 100644 index 00000000000..d81acd240a2 --- /dev/null +++ b/addons/web/static/lib/py.js/doc/differences.rst @@ -0,0 +1,64 @@ +Differences with Python +======================= + +* ``py.js`` completely ignores old-style classes as well as their + lookup details. All ``py.js`` types should be considered matching + the behavior of new-style classes + +* New types can only have a single base. This is due to ``py.js`` + implementing its types on top of Javascript's, and javascript being + a single-inheritance language. + + This may change if ``py.js`` ever reimplements its object model from + scratch. + +* Piggybacking on javascript's object model also means metaclasses are + not available (:js:func:`py.type` is a function) + +* A python-level function (created through :js:class:`py.PY_def`) set + on a new type will not become a method, it'll remain a function. + +* :js:func:`py.PY_parseArgs` supports keyword-only arguments (though + it's a Python 3 feature) + +* Because the underlying type is a javascript ``String``, there + currently is no difference between :js:class:`py.str` and + :js:class:`py.unicode`. As a result, there also is no difference + between :js:func:`__str__` and :js:func:`__unicode__`. + +Unsupported features +-------------------- + +These are Python features which are not supported at all in ``py.js``, +usually because they don't make sense or there is no way to support them + +* The ``__delattr__``, ``__delete__`` and ``__delitem__``: as + ``py.js`` only handles expressions and these are accessed via the + ``del`` statement, there would be no way to call them. + +* ``__del__`` the lack of cross-platform GC hook means there is no way + to know when an object is deallocated. + +* ``__slots__`` are not handled + +* Dedicated (and deprecated) slicing special methods are unsupported + +Missing features +---------------- + +These are Python features which are missing because they haven't been +implemented yet: + +* Class-binding of descriptors doesn't currently work. + +* Instance and subclass checks can't be customized + +* "poor" comparison methods (``__cmp__`` and ``__rcmp__``) are not + supported and won't be falled-back to. + +* ``__coerce__`` is currently supported + +* Context managers are not currently supported + +* Unbound methods are not supported, instance methods can only be + accessed from instances. diff --git a/addons/web/static/lib/py.js/doc/index.rst b/addons/web/static/lib/py.js/doc/index.rst new file mode 100644 index 00000000000..1b9167529b8 --- /dev/null +++ b/addons/web/static/lib/py.js/doc/index.rst @@ -0,0 +1,161 @@ +.. py.js documentation master file, created by + sphinx-quickstart on Sun Sep 9 19:36:23 2012. + You can adapt this file completely to your liking, but it should at least + contain the root `toctree` directive. + +py.js, a Python expressions parser and evaluator +================================================ + +``py.js`` is a parser and evaluator of Python expressions, written in +pure javascript. + +``py.js`` is not intended to implement a full Python interpreter, its +specification document is the `Python 2.7 Expressions spec +`_ (along with the +lexical analysis part) as well as the Python builtins. + + +.. toctree:: + :maxdepth: 2 + + builtins + types + utility + differences + +Usage +----- + +To evaluate a Python expression, simply call +:func:`py.eval`. :func:`py.eval` takes a mandatory Python expression +parameter, as a string, and an optional evaluation context (namespace +for the expression's free variables), and returns a javascript value:: + + > py.eval("t in ('a', 'b', 'c') and foo", {t: 'c', foo: true}); + true + +If the expression needs to be repeatedly evaluated, or the result of +the expression is needed in its "python" form without being converted +back to javascript, you can use the underlying triplet of functions +:func:`py.tokenize`, :func:`py.parse` and :func:`py.evaluate` +directly. + +API +--- + +Core functions +++++++++++++++ + +.. function:: py.eval(expr[, context]) + + "Do everything" function, to use for one-shot evaluation of Python + expressions. Chains tokenizing, parsing and evaluating the + expression then :ref:`converts the result back to javascript + ` + + :param expr: Python expression to evaluate + :type expr: String + :param context: evaluation context for the expression's free + variables + :type context: Object + :returns: the expression's result, converted back to javascript + +.. function:: py.tokenize(expr) + + Expression tokenizer + + :param expr: Python expression to tokenize + :type expr: String + :returns: token stream + +.. function:: py.parse(tokens) + + Parses a token stream and returns the corresponding parse tree. + + The parse tree is stateless and can be memoized and reused for + frequently evaluated expressions. + + :param tokens: token stream from :func:`py.tokenize` + :returns: parse tree + +.. function:: py.evaluate(tree[, context]) + + Evaluates the expression represented by the provided parse tree, + using the provided context for the exprssion's free variables. + + :param tree: parse tree returned by :func:`py.parse` + :param context: evaluation context + :returns: the "python object" resulting from the expression's + evaluation + :rtype: :class:`py.object` + +.. _convert-py: + +Conversions from Javascript to Python ++++++++++++++++++++++++++++++++++++++ + +``py.js`` will automatically attempt to convert non-:class:`py.object` +values into their ``py.js`` equivalent in the following situations: + +* Values passed through the context of :func:`py.eval` or + :func:`py.evaluate` + +* Attributes accessed directly on objects + +* Values of mappings passed to :class:`py.dict` + +Notably, ``py.js`` will *not* attempt an automatic conversion of +values returned by functions or methods, these must be +:class:`py.object` instances. + +The automatic conversions performed by ``py.js`` are the following: + +* ``null`` is converted to :data:`py.None` + +* ``true`` is converted to :data:`py.True` + +* ``false`` is converted to :data:`py.False` + +* numbers are converted to :class:`py.float` + +* strings are converted to :class:`py.str` + +* functions are wrapped into :class:`py.PY_dev` + +* ``Array`` instances are converted to :class:`py.list` + +The rest generates an error, except for ``undefined`` which +specifically generates a ``NameError``. + +.. _convert-js: + +Conversions from Python to Javascript ++++++++++++++++++++++++++++++++++++++ + +py.js types (extensions of :js:class:`py.object`) can be converted +back to javascript by calling their :js:func:`py.object.toJSON` +method. + +The default implementation raises an error, as arbitrary objects can +not be converted back to javascript. + +Most built-in objects provide a :js:func:`py.object.toJSON` +implementation out of the box. + +Javascript-level exceptions ++++++++++++++++++++++++++++ + +Javascript allows throwing arbitrary things, but runtimes don't seem +to provide any useful information (when they ever do) if what is +thrown isn't a direct instance of ``Error``. As a result, while +``py.js`` tries to match the exception-throwing semantics of Python it +only ever throws bare ``Error`` at the javascript-level. Instead, it +prefixes the error message with the name of the Python expression, a +colon, a space, and the actual message. + +For instance, where Python would throw ``KeyError("'foo'")`` when +accessing an invalid key on a ``dict``, ``py.js`` will throw +``Error("KeyError: 'foo'")``. + +.. _Python Data Model: http://docs.python.org/reference/datamodel.html + diff --git a/addons/web/static/lib/py.js/doc/make.bat b/addons/web/static/lib/py.js/doc/make.bat new file mode 100644 index 00000000000..c3db032e01a --- /dev/null +++ b/addons/web/static/lib/py.js/doc/make.bat @@ -0,0 +1,190 @@ +@ECHO OFF + +REM Command file for Sphinx documentation + +if "%SPHINXBUILD%" == "" ( + set SPHINXBUILD=sphinx-build +) +set BUILDDIR=_build +set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . +set I18NSPHINXOPTS=%SPHINXOPTS% . +if NOT "%PAPER%" == "" ( + set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% + set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS% +) + +if "%1" == "" goto help + +if "%1" == "help" ( + :help + echo.Please use `make ^` where ^ is one of + echo. html to make standalone HTML files + echo. dirhtml to make HTML files named index.html in directories + echo. singlehtml to make a single large HTML file + echo. pickle to make pickle files + echo. json to make JSON files + echo. htmlhelp to make HTML files and a HTML help project + echo. qthelp to make HTML files and a qthelp project + echo. devhelp to make HTML files and a Devhelp project + echo. epub to make an epub + echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter + echo. text to make text files + echo. man to make manual pages + echo. texinfo to make Texinfo files + echo. gettext to make PO message catalogs + echo. changes to make an overview over all changed/added/deprecated items + echo. linkcheck to check all external links for integrity + echo. doctest to run all doctests embedded in the documentation if enabled + goto end +) + +if "%1" == "clean" ( + for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i + del /q /s %BUILDDIR%\* + goto end +) + +if "%1" == "html" ( + %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/html. + goto end +) + +if "%1" == "dirhtml" ( + %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. + goto end +) + +if "%1" == "singlehtml" ( + %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. + goto end +) + +if "%1" == "pickle" ( + %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the pickle files. + goto end +) + +if "%1" == "json" ( + %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can process the JSON files. + goto end +) + +if "%1" == "htmlhelp" ( + %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run HTML Help Workshop with the ^ +.hhp project file in %BUILDDIR%/htmlhelp. + goto end +) + +if "%1" == "qthelp" ( + %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; now you can run "qcollectiongenerator" with the ^ +.qhcp project file in %BUILDDIR%/qthelp, like this: + echo.^> qcollectiongenerator %BUILDDIR%\qthelp\pyjs.qhcp + echo.To view the help file: + echo.^> assistant -collectionFile %BUILDDIR%\qthelp\pyjs.ghc + goto end +) + +if "%1" == "devhelp" ( + %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. + goto end +) + +if "%1" == "epub" ( + %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The epub file is in %BUILDDIR%/epub. + goto end +) + +if "%1" == "latex" ( + %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex + if errorlevel 1 exit /b 1 + echo. + echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. + goto end +) + +if "%1" == "text" ( + %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The text files are in %BUILDDIR%/text. + goto end +) + +if "%1" == "man" ( + %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The manual pages are in %BUILDDIR%/man. + goto end +) + +if "%1" == "texinfo" ( + %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo. + goto end +) + +if "%1" == "gettext" ( + %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale + if errorlevel 1 exit /b 1 + echo. + echo.Build finished. The message catalogs are in %BUILDDIR%/locale. + goto end +) + +if "%1" == "changes" ( + %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes + if errorlevel 1 exit /b 1 + echo. + echo.The overview file is in %BUILDDIR%/changes. + goto end +) + +if "%1" == "linkcheck" ( + %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck + if errorlevel 1 exit /b 1 + echo. + echo.Link check complete; look for any errors in the above output ^ +or in %BUILDDIR%/linkcheck/output.txt. + goto end +) + +if "%1" == "doctest" ( + %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest + if errorlevel 1 exit /b 1 + echo. + echo.Testing of doctests in the sources finished, look at the ^ +results in %BUILDDIR%/doctest/output.txt. + goto end +) + +:end diff --git a/addons/web/static/lib/py.js/doc/types.rst b/addons/web/static/lib/py.js/doc/types.rst new file mode 100644 index 00000000000..61d950c6ec6 --- /dev/null +++ b/addons/web/static/lib/py.js/doc/types.rst @@ -0,0 +1,248 @@ +Implementing a custom type +========================== + +To implement a custom python-level type, one can use the +:func:`py.type` builtin. At the JS-level, it is a function with the +same signature as the :py:class:`type` builtin [#bases]_. It returns a +child type of its one base (or :py:class:`py.object` if no base is +provided). + +The ``dict`` parameter to :func:`py.type` can contain any +attribute, javascript-level or python-level: the default +``__getattribute__`` implementation will ensure they are converted to +Python-level attributes if needed. Most methods are also wrapped and +converted to :ref:`types-methods-python`, although there are a number +of special cases: + +* Most "magic methods" of the data model ("dunder" methods) remain + javascript-level. See :ref:`the listing of magic methods and their + signatures `. As a result, they do not respect + the :ref:`types-methods-python-call` + +* The ``toJSON`` and ``fromJSON`` methods are special-cased to remain + javascript-level and don't follow the + :ref:`types-methods-python-call` + +* Functions which have been wrapped explicitly (via + :class:`py.PY_def`, :py:class:`py.classmethod` or + :py:class:`py.staticmethod`) are associated to the class + untouched. But due to their wrapper, they will use the + :ref:`types-methods-python-call` anyway + +.. _types-methods-python: + +Python-level callable +--------------------- + +Wrapped javascript function *or* the :func:`__call__` method itself +follow the :ref:`types-methods-python-call`. As a result, they can't +(easily) be called directly from javascript code. Because +:func:`__new__` and :func:`__init__` follow from :func:`__call__`, +they also follow the :ref:`types-methods-python-call`. + +:func:`py.PY_call` should be used when interacting with them from +javascript is necessary. + +Because ``__call__`` follows the :ref:`types-methods-python-call`, +instantiating a ``py.js`` type from javascript requires using +:func:`py.PY_call`. + +.. _types-methods-python-call: + +Python calling conventions +++++++++++++++++++++++++++ + +The python-level arguments should be considered completely opaque, +they should be interacted with through :func:`py.PY_parseArgs` (to +extract python-level arguments to javascript implementation code) and +:func:`py.PY_call` (to call :ref:`types-methods-python` from +javascript code). + +A callable following the :ref:`types-methods-python-call` *must* +return a ``py.js`` object, an error will be generated when failing to +do so. + +.. todo:: arguments forwarding when e.g. overriding methods? + +.. _types-methods-dunder: + +Magic methods +------------- + +``py.js`` doesn't support calling magic ("dunder") methods of the +datamodel from Python code, and these methods remain javascript-level +(they don't follow the :ref:`types-methods-python-call`). + +Here is a list of the understood datamodel methods, refer to `the +relevant Python documentation +`_ +for their roles. + +Basic customization ++++++++++++++++++++ + +.. function:: __hash__() + + :returns: String + +.. function:: __eq__(other) + + The default implementation tests for identity + + :param other: :py:class:`py.object` to compare this object with + :returns: :py:class:`py.bool` + +.. function:: __ne__(other) + + The default implementation calls :func:`__eq__` and reverses + its result. + + :param other: :py:class:`py.object` to compare this object with + :returns: :py:class:`py.bool` + +.. function:: __lt__(other) + + The default implementation simply returns + :data:`py.NotImplemented`. + + :param other: :py:class:`py.object` to compare this object with + :returns: :py:class:`py.bool` + + +.. function:: __le__(other) + + The default implementation simply returns + :data:`py.NotImplemented`. + + :param other: :py:class:`py.object` to compare this object with + :returns: :py:class:`py.bool` + + +.. function:: __ge__(other) + + The default implementation simply returns + :data:`py.NotImplemented`. + + :param other: :py:class:`py.object` to compare this object with + :returns: :py:class:`py.bool` + + +.. function:: __gt__(other) + + The default implementation simply returns + :data:`py.NotImplemented`. + + :param other: :py:class:`py.object` to compare this object with + :returns: :py:class:`py.bool` + +.. function:: __str__() + + Simply calls :func:`__unicode__`. This method should not be + overridden, :func:`__unicode__` should be overridden instead. + + :returns: :py:class:`py.str` + +.. function:: __unicode__() + + :returns: :py:class:`py.unicode` + +.. function:: __nonzero__() + + The default implementation always returns :data:`py.True` + + :returns: :py:class:`py.bool` + +Customizing attribute access +++++++++++++++++++++++++++++ + +.. function:: __getattribute__(name) + + :param String name: name of the attribute, as a javascript string + :returns: :py:class:`py.object` + +.. function:: __getattr__(name) + + :param String name: name of the attribute, as a javascript string + :returns: :py:class:`py.object` + +.. function:: __setattr__(name, value) + + :param String name: name of the attribute, as a javascript string + :param value: :py:class:`py.object` + +Implementing descriptors +++++++++++++++++++++++++ + +.. function:: __get__(instance) + + .. note:: readable descriptors don't currently handle "owner + classes" + + :param instance: :py:class:`py.object` + :returns: :py:class:`py.object` + +.. function:: __set__(instance, value) + + :param instance: :py:class:`py.object` + :param value: :py:class:`py.object` + +Emulating Numeric Types ++++++++++++++++++++++++ + +* Non-in-place binary numeric methods (e.g. ``__add__``, ``__mul__``, + ...) should all be supported including reversed calls (in case the + primary call is not available or returns + :py:data:`py.NotImplemented`). They take a single + :py:class:`py.object` parameter and return a single + :py:class:`py.object` parameter. + +* Unary operator numeric methods are all supported: + + .. function:: __pos__() + + :returns: :py:class:`py.object` + + .. function:: __neg__() + + :returns: :py:class:`py.object` + + .. function:: __invert__() + + :returns: :py:class:`py.object` + +* For non-operator numeric methods, support is contingent on the + corresponding :ref:`builtins ` being implemented + +Emulating container types ++++++++++++++++++++++++++ + +.. function:: __len__() + + :returns: :py:class:`py.int` + +.. function:: __getitem__(name) + + :param name: :py:class:`py.object` + :returns: :py:class:`py.object` + +.. function:: __setitem__(name, value) + + :param name: :py:class:`py.object` + :param value: :py:class:`py.object` + +.. function:: __iter__() + + :returns: :py:class:`py.object` + +.. function:: __reversed__() + + :returns: :py:class:`py.object` + +.. function:: __contains__(other) + + :param other: :py:class:`py.object` + :returns: :py:class:`py.bool` + +.. [#bases] with the limitation that, because :ref:`py.js builds its + object model on top of javascript's + `, only one base is allowed. diff --git a/addons/web/static/lib/py.js/doc/utility.rst b/addons/web/static/lib/py.js/doc/utility.rst new file mode 100644 index 00000000000..90c05d448e1 --- /dev/null +++ b/addons/web/static/lib/py.js/doc/utility.rst @@ -0,0 +1,111 @@ +Utility functions for interacting with ``py.js`` objects +======================================================== + +Essentially the ``py.js`` version of the Python C API, these functions +are used to implement new ``py.js`` types or to interact with existing +ones. + +They are prefixed with ``PY_``. + +.. function:: py.PY_call(callable[, args][, kwargs]) + + Call an arbitrary python-level callable from javascript. + + :param callable: A ``py.js`` callable object (broadly speaking, + either a class or an object with a ``__call__`` + method) + + :param args: javascript Array of :class:`py.object`, used as + positional arguments to ``callable`` + + :param kwargs: javascript Object mapping names to + :class:`py.object`, used as named arguments to + ``callable`` + + :returns: nothing or :class:`py.object` + +.. function:: py.PY_parseArgs(arguments, format) + + Arguments parser converting from the :ref:`user-defined calling + conventions ` to a JS object mapping + argument names to values. It serves the same role as + `PyArg_ParseTupleAndKeywords`_. + + :: + + var args = py.PY_parseArgs( + arguments, ['foo', 'bar', ['baz', 3], ['qux', "foo"]]); + + roughly corresponds to the argument spec: + + .. code-block:: python + + def func(foo, bar, baz=3, qux="foo"): + pass + + .. note:: a significant difference is that "default values" will + be re-evaluated at each call, since they are within the + function. + + :param arguments: array-like objects holding the args and kwargs + passed to the callable, generally the + ``arguments`` of the caller. + + :param format: mapping declaration to the actual arguments of the + function. A javascript array composed of five + possible types of elements: + + * The literal string ``'*'`` marks all following + parameters as keyword-only, regardless of them + having a default value or not [#kwonly]_. Can + only be present once in the parameters list. + + * A string prefixed by ``*``, marks the positional + variadic parameter for the function: gathers all + provided positional arguments left and makes all + following parameters keyword-only + [#star-args]_. ``*args`` is incompatible with + ``*``. + + * A string prefixed with ``**``, marks the + positional keyword variadic parameter for the + function: gathers all provided keyword arguments + left and closes the argslist. If present, this + must be the last parameter of the format list. + + * A string defines a required parameter, accessible + positionally or through keyword + + * A pair of ``[String, py.object]`` defines an + optional parameter and its default value. + + For simplicity, when not using optional parameters + it is possible to use a simple string as the format + (using space-separated elements). The string will + be split on whitespace and processed as a normal + format array. + + :returns: a javascript object mapping argument names to values + + :raises: ``TypeError`` if the provided arguments don't match the + format + +.. class:: py.PY_def(fn) + + Type wrapping javascript functions into py.js callables. The + wrapped function follows :ref:`the py.js calling conventions + ` + + :param Function fn: the javascript function to wrap + :returns: a callable py.js object + +.. [#kwonly] Python 2, which py.js currently implements, does not + support Python-level keyword-only parameters (it can be + done through the C-API), but it seemed neat and easy + enough so there. + +.. [#star-args] due to this and contrary to Python 2, py.js allows + arguments other than ``**kwargs`` to follow ``*args``. + +.. _PyArg_ParseTupleAndKeywords: + http://docs.python.org/c-api/arg.html#PyArg_ParseTupleAndKeywords diff --git a/addons/web/static/lib/py.js/lib/py.js b/addons/web/static/lib/py.js/lib/py.js index 79a0ace1995..d03de622689 100644 --- a/addons/web/static/lib/py.js/lib/py.js +++ b/addons/web/static/lib/py.js/lib/py.js @@ -369,24 +369,26 @@ var py = {}; return py.False; } - if (val instanceof py.object - || val === py.object - || py.issubclass.__call__([val, py.object]) === py.True) { + var fn = function () {} + fn.prototype = py.object; + if (py.PY_call(py.isinstance, [val, py.object]) === py.True + || py.PY_call(py.issubclass, [val, py.object]) === py.True) { return val; } switch (typeof val) { case 'number': - return new py.float(val); + return py.float.fromJSON(val); case 'string': - return new py.str(val); + return py.str.fromJSON(val); case 'function': - return new py.def(val); + return py.PY_def.fromJSON(val); } switch(val.constructor) { case Object: - var o = new py.object(); + // TODO: why py.object instead of py.dict? + var o = py.PY_call(py.object); for (var prop in val) { if (val.hasOwnProperty(prop)) { o[prop] = val[prop]; @@ -394,40 +396,170 @@ var py = {}; } return o; case Array: - var a = new py.list(); - a.values = val; + var a = py.PY_call(py.list); + a._values = val; return a; } throw new Error("Could not convert " + val + " to a pyval"); } + + // JSAPI, JS-level utility functions for implementing new py.js + // types + py.py = {}; + + py.PY_parseArgs = function PY_parseArgs(argument, format) { + var out = {}; + var args = argument[0]; + var kwargs = {}; + for (var k in argument[1]) { + kwargs[k] = argument[1][k]; + } + if (typeof format === 'string') { + format = format.split(/\s+/); + } + var name = function (spec) { + if (typeof spec === 'string') { + return spec; + } else if (spec instanceof Array && spec.length === 2) { + return spec[0]; + } + throw new Error( + "TypeError: unknown format specification " + + JSON.stringify(spec)); + }; + // TODO: ensure all format arg names are actual names? + for(var i=0; i 1) { + throw new Error("ValueError: can't provide multiple bases for a " + + "new type"); } - proto = constructor.prototype = create(base.prototype); - proto.constructor = constructor; + var base = bases[0]; + var ClassObj = create(base); if (dict) { - for(var k in dict) { + for (var k in dict) { if (!dict.hasOwnProperty(k)) { continue; } - proto[k] = dict[k]; + ClassObj[k] = dict[k]; } } - constructor.__call__ = function () { - // create equivalent type with same prototype - var instance = create(proto); - // call actual constructor - var res = constructor.apply(instance, arguments); - // return result of constructor if any, otherwise instance - return res || instance; - }; - return constructor; + ClassObj.__class__ = ClassObj; + ClassObj.__name__ = name; + ClassObj.__bases__ = bases; + ClassObj.__is_type = true; + + return ClassObj; + }; + py.type.__call__ = function () { + var args = py.PY_parseArgs(arguments, ['object']); + return args.object.__class__; }; var hash_counter = 0; - py.object = py.type(function object() {}, {}, { + py.object = py.type('object', [{}], { + __new__: function () { + // If ``this`` isn't the class object, this is going to be + // beyond fucked up + var inst = create(this); + inst.__is_type = false; + return inst; + }, + __init__: function () {}, // Basic customization __hash__: function () { if (this._hash) { @@ -466,11 +598,11 @@ var py = {}; var val = this[name]; if (typeof val === 'object' && '__get__' in val) { // TODO: second argument should be class - return val.__get__(this); + return val.__get__(this, py.PY_call(py.type, [this])); } if (typeof val === 'function' && !this.hasOwnProperty(name)) { // val is a method from the class - return new PY_instancemethod(val, this); + return PY_instancemethod.fromJSON(val, this); } return PY_ensurepy(val); } @@ -492,140 +624,182 @@ var py = {}; throw new Error(this.constructor.name + ' can not be converted to JSON'); } }); - var NoneType = py.type(function NoneType() {}, py.object, { + var NoneType = py.type('NoneType', null, { __nonzero__: function () { return py.False; }, toJSON: function () { return null; } }); - py.None = new NoneType(); - var NotImplementedType = py.type(function NotImplementedType(){}); - py.NotImplemented = new NotImplementedType(); + py.None = py.PY_call(NoneType); + var NotImplementedType = py.type('NotImplementedType', null, {}); + py.NotImplemented = py.PY_call(NotImplementedType); var booleans_initialized = false; - py.bool = py.type(function bool(value) { - value = (value instanceof Array) ? value[0] : value; - // The only actual instance of py.bool should be py.True - // and py.False. Return the new instance of py.bool if we - // are initializing py.True and py.False, otherwise always - // return either py.True or py.False. - if (!booleans_initialized) { - return; - } - if (value === undefined) { return py.False; } - return value.__nonzero__() === py.True ? py.True : py.False; - }, py.object, { + py.bool = py.type('bool', null, { + __new__: function () { + if (!booleans_initialized) { + return py.object.__new__.apply(this); + } + + var ph = {}; + var args = py.PY_parseArgs(arguments, [['value', ph]]); + if (args.value === ph) { + return py.False; + } + return args.value.__nonzero__() === py.True ? py.True : py.False; + }, __nonzero__: function () { return this; }, toJSON: function () { return this === py.True; } }); - py.True = new py.bool(); - py.False = new py.bool(); + py.True = py.PY_call(py.bool); + py.False = py.PY_call(py.bool); booleans_initialized = true; - py.float = py.type(function float(value) { - value = (value instanceof Array) ? value[0] : value; - if (value === undefined) { this._value = 0; return; } - if (value instanceof py.float) { return value; } - if (typeof value === 'number' || value instanceof Number) { - this._value = value; - return; - } - if (typeof value === 'string' || value instanceof String) { - this._value = parseFloat(value); - return; - } - if (value instanceof py.object && '__float__' in value) { - var res = value.__float__(); - if (res instanceof py.float) { - return res; - } - throw new Error('TypeError: __float__ returned non-float (type ' + - res.constructor.name + ')'); - } - throw new Error('TypeError: float() argument must be a string or a number'); - }, py.object, { + py.float = py.type('float', null, { + __init__: function () { + var placeholder = {}; + var args = py.PY_parseArgs(arguments, [['value', placeholder]]); + var value = args.value; + if (value === placeholder) { + this._value = 0; return; + } + if (py.PY_call(py.isinstance, [value, py.float]) === py.True) { + this._value = value._value; + } + if (py.PY_call(py.isinstance, [value, py.object]) === py.True + && '__float__' in value) { + var res = value.__float__(); + if (py.PY_call(py.isinstance, [res, py.float]) === py.True) { + this._value = res._value; + return; + } + throw new Error('TypeError: __float__ returned non-float (type ' + + res.__class__.__name__ + ')'); + } + throw new Error('TypeError: float() argument must be a string or a number'); + }, __eq__: function (other) { return this._value === other._value ? py.True : py.False; }, __lt__: function (other) { - if (!(other instanceof py.float)) { return py.NotImplemented; } + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } return this._value < other._value ? py.True : py.False; }, __le__: function (other) { - if (!(other instanceof py.float)) { return py.NotImplemented; } + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } return this._value <= other._value ? py.True : py.False; }, __gt__: function (other) { - if (!(other instanceof py.float)) { return py.NotImplemented; } + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } return this._value > other._value ? py.True : py.False; }, __ge__: function (other) { - if (!(other instanceof py.float)) { return py.NotImplemented; } + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } return this._value >= other._value ? py.True : py.False; }, __add__: function (other) { - if (!(other instanceof py.float)) { return py.NotImplemented; } - return new py.float(this._value + other._value); + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } + return py.float.fromJSON(this._value + other._value); }, __neg__: function () { - return new py.float(-this._value); + return py.float.fromJSON(-this._value); }, __sub__: function (other) { - if (!(other instanceof py.float)) { return py.NotImplemented; } - return new py.float(this._value - other._value); + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } + return py.float.fromJSON(this._value - other._value); }, __mul__: function (other) { - if (!(other instanceof py.float)) { return py.NotImplemented; } - return new py.float(this._value * other._value); + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } + return py.float.fromJSON(this._value * other._value); }, __div__: function (other) { - if (!(other instanceof py.float)) { return py.NotImplemented; } - return new py.float(this._value / other._value); + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } + return py.float.fromJSON(this._value / other._value); }, __nonzero__: function () { return this._value ? py.True : py.False; }, + fromJSON: function (v) { + if (!(typeof v === 'number')) { + throw new Error('py.float.fromJSON can only take numbers '); + } + var instance = py.PY_call(py.float); + instance._value = v; + return instance; + }, toJSON: function () { return this._value; } }); - py.str = py.type(function str(s) { - s = (s instanceof Array) ? s[0] : s; - if (s === undefined) { this._value = ''; return; } - if (s instanceof py.str) { return s; } - if (typeof s === 'string' || s instanceof String) { - this._value = s; - return; - } - var v = s.__str__(); - if (v instanceof py.str) { return v; } - throw new Error('TypeError: __str__ returned non-string (type ' + - v.constructor.name + ')'); - }, py.object, { + py.str = py.type('str', null, { + __init__: function () { + var placeholder = {}; + var args = py.PY_parseArgs(arguments, [['value', placeholder]]); + var s = args.value; + if (s === placeholder) { this._value = ''; return; } + if (py.PY_call(py.isinstance, [s, py.str]) === py.True) { + this._value = s._value; + return; + } + var v = s.__str__(); + if (py.PY_call(py.isinstance, [v, py.str]) === py.True) { + this._value = v._value; + return; + } + throw new Error('TypeError: __str__ returned non-string (type ' + + v.__class__.__name__ + ')'); + }, __hash__: function () { return '\1\0\1' + this._value; }, __eq__: function (other) { - if (other instanceof py.str && this._value === other._value) { + if (py.PY_call(py.isinstance, [other, py.str]) === py.True + && this._value === other._value) { return py.True; } return py.False; }, __lt__: function (other) { - if (!(other instanceof py.str)) { return py.NotImplemented; } + if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + return py.NotImplemented; + } return this._value < other._value ? py.True : py.False; }, __le__: function (other) { - if (!(other instanceof py.str)) { return py.NotImplemented; } + if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + return py.NotImplemented; + } return this._value <= other._value ? py.True : py.False; }, __gt__: function (other) { - if (!(other instanceof py.str)) { return py.NotImplemented; } + if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + return py.NotImplemented; + } return this._value > other._value ? py.True : py.False; }, __ge__: function (other) { - if (!(other instanceof py.str)) { return py.NotImplemented; } + if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + return py.NotImplemented; + } return this._value >= other._value ? py.True : py.False; }, __add__: function (other) { - if (!(other instanceof py.str)) { return py.NotImplemented; } - return new py.str(this._value + other._value); + if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + return py.NotImplemented; + } + return py.str.fromJSON(this._value + other._value); }, __nonzero__: function () { return this._value.length ? py.True : py.False; @@ -633,40 +807,46 @@ var py = {}; __contains__: function (s) { return (this._value.indexOf(s._value) !== -1) ? py.True : py.False; }, + fromJSON: function (s) { + if (typeof s === 'string') { + var instance = py.PY_call(py.str); + instance._value = s; + return instance; + }; + throw new Error("str.fromJSON can only take strings"); + }, toJSON: function () { return this._value; } }); - py.tuple = py.type(function tuple() {}, null, { + py.tuple = py.type('tuple', null, { + __init__: function () { + this._values = []; + }, __contains__: function (value) { - for(var i=0, len=this.values.length; i 1 ? args[1] : py.None; + get: function () { + var args = py.PY_parseArgs(arguments, ['k', ['d', py.None]]); + var h = args.k.__hash__(); if (!(h in this._store)) { - return def; + return args.d; } return this._store[h][1]; }, + fromJSON: function (d) { + var instance = py.PY_call(py.dict); + for (var k in (d || {})) { + if (!d.hasOwnProperty(k)) { continue; } + instance.__setitem__( + py.str.fromJSON(k), + PY_ensurepy(d[k])); + } + return instance; + }, toJSON: function () { var out = {}; for(var k in this._store) { @@ -694,30 +884,57 @@ var py = {}; return out; } }); - py.def = py.type(function def(nativefunc) { - this._inst = null; - this._func = nativefunc; - }, py.object, { - __call__: function (args, kwargs) { + py.PY_def = py.type('function', null, { + __call__: function () { // don't want to rewrite __call__ for instancemethod - return this._func.call(this._inst, args, kwargs); + return this._func.apply(this._inst, arguments); + }, + fromJSON: function (nativefunc) { + var instance = py.PY_call(py.PY_def); + instance._inst = null; + instance._func = nativefunc; + return instance; }, toJSON: function () { return this._func; } }); - var PY_instancemethod = py.type(function instancemethod(nativefunc, instance, _cls) { - // could also use bind? - this._inst = instance; - this._func = nativefunc; - }, py.def, {}); - - py.issubclass = new py.def(function issubclass(args) { - var derived = args[0], parent = args[1]; - // still hurts my brain that this can work - return derived.prototype instanceof py.object - ? py.True - : py.False; + py.classmethod = py.type('classmethod', null, { + __init__: function () { + var args = py.PY_parseArgs(arguments, 'function'); + this._func = args['function']; + }, + __get__: function (obj, type) { + return PY_instancemethod.fromJSON(this._func, type); + }, + fromJSON: function (func) { + return py.PY_call(py.classmethod, [func]); + } + }); + var PY_instancemethod = py.type('instancemethod', [py.PY_def], { + fromJSON: function (nativefunc, instance) { + var inst = py.PY_call(PY_instancemethod); + // could also use bind? + inst._inst = instance; + inst._func = nativefunc; + return inst; + } + }); + + py.isinstance = new py.PY_def.fromJSON(function isinstance() { + var args = py.PY_parseArgs(arguments, ['object', 'class']); + var fn = function () {}; + fn.prototype = args['class']; + return (args.object instanceof fn) ? py.True : py.False; + }); + py.issubclass = new py.PY_def.fromJSON(function issubclass() { + var args = py.PY_parseArgs(arguments, ['C', 'B']); + var fn = function () {}; + fn.prototype = args.B; + if (args.C === args.B || args.C instanceof fn) { + return py.True; + } + return py.False; }); @@ -726,10 +943,10 @@ var py = {}; '==': ['eq', 'eq', function (a, b) { return a === b; }], '!=': ['ne', 'ne', function (a, b) { return a !== b; }], '<>': ['ne', 'ne', function (a, b) { return a !== b; }], - '<': ['lt', 'gt', function (a, b) {return a.constructor.name < b.constructor.name;}], - '<=': ['le', 'ge', function (a, b) {return a.constructor.name <= b.constructor.name;}], - '>': ['gt', 'lt', function (a, b) {return a.constructor.name > b.constructor.name;}], - '>=': ['ge', 'le', function (a, b) {return a.constructor.name >= b.constructor.name;}], + '<': ['lt', 'gt', function (a, b) {return a.__class__.__name__ < b.__class__.__name__;}], + '<=': ['le', 'ge', function (a, b) {return a.__class__.__name__ <= b.__class__.__name__;}], + '>': ['gt', 'lt', function (a, b) {return a.__class__.__name__ > b.__class__.__name__;}], + '>=': ['ge', 'le', function (a, b) {return a.__class__.__name__ >= b.__class__.__name__;}], '+': ['add', 'radd'], '-': ['sub', 'rsub'], @@ -772,8 +989,8 @@ var py = {}; } throw new Error( "TypeError: unsupported operand type(s) for " + op + ": '" - + o1.constructor.name + "' and '" - + o2.constructor.name + "'"); + + o1.__class__.__name__ + "' and '" + + o2.__class__.__name__ + "'"); }; var PY_builtins = { @@ -787,10 +1004,15 @@ var py = {}; object: py.object, bool: py.bool, float: py.float, + str: py.str, + unicode: py.unicode, tuple: py.tuple, list: py.list, dict: py.dict, - issubclass: py.issubclass + + isinstance: py.isinstance, + issubclass: py.issubclass, + classmethod: py.classmethod, }; py.parse = function (toks) { @@ -825,9 +1047,9 @@ var py = {}; } return PY_ensurepy(val, expr.value); case '(string)': - return new py.str(expr.value); + return py.str.fromJSON(expr.value); case '(number)': - return new py.float(expr.value); + return py.float.fromJSON(expr.value); case '(constant)': switch (expr.value) { case 'None': return py.None; @@ -876,7 +1098,7 @@ var py = {}; py.evaluate(arg.second, context); } } - return callable.__call__(args, kwargs); + return py.PY_call(callable, args, kwargs); } var tuple_exprs = expr.first, tuple_values = []; @@ -884,8 +1106,8 @@ var py = {}; tuple_values.push(py.evaluate( tuple_exprs[j], context)); } - var t = new py.tuple(); - t.values = tuple_values; + var t = py.PY_call(py.tuple); + t._values = tuple_values; return t; case '[': if (expr.second) { @@ -897,11 +1119,11 @@ var py = {}; list_values.push(py.evaluate( list_exprs[k], context)); } - var l = new py.list(); - l.values = list_values; + var l = py.PY_call(py.list); + l._values = list_values; return l; case '{': - var dict_exprs = expr.first, dict = new py.dict; + var dict_exprs = expr.first, dict = py.PY_call(py.dict); for(var l=0; l 2')).to.be(true); - expect(py.eval('"foo" <> "foo"')).to.be(false); - expect(py.eval('"foo" <> "bar"')).to.be(true); - }); - }); - describe('rich comparisons', function () { - it('should work with numbers', function () { - expect(py.eval('3 < 5')).to.be(true); - expect(py.eval('5 >= 3')).to.be(true); - expect(py.eval('3 >= 3')).to.be(true); - expect(py.eval('3 > 5')).to.be(false); - }); - it('should support comparison chains', function () { - expect(py.eval('1 < 3 < 5')).to.be(true); - expect(py.eval('5 > 3 > 1')).to.be(true); - expect(py.eval('1 < 3 > 2 == 2 > -2')).to.be(true); - }); - it('should compare strings', function () { - expect(py.eval('date >= current', - {date: '2010-06-08', current: '2010-06-05'})) - .to.be(true); - expect(py.eval('state == "cancel"', {state: 'cancel'})) - .to.be(true); - expect(py.eval('state == "cancel"', {state: 'open'})) - .to.be(false); - }); - }); - describe('missing eq/neq', function () { - it('should fall back on identity', function () { - var typ = new py.type(function MyType() {}); - expect(py.eval('MyType() == MyType()', {MyType: typ})).to.be(false); - }); - }); - describe('un-comparable types', function () { - it('should default to type-name ordering', function () { - var t1 = new py.type(function Type1() {}); - var t2 = new py.type(function Type2() {}); - expect(py.eval('T1() < T2()', {T1: t1, T2: t2})).to.be(true); - expect(py.eval('T1() > T2()', {T1: t1, T2: t2})).to.be(false); - }); - it('should handle native stuff', function () { - expect(py.eval('None < 42')).to.be(true); - expect(py.eval('42 > None')).to.be(true); - expect(py.eval('None > 42')).to.be(false); - - expect(py.eval('None < False')).to.be(true); - expect(py.eval('None < True')).to.be(true); - expect(py.eval('False > None')).to.be(true); - expect(py.eval('True > None')).to.be(true); - expect(py.eval('None > False')).to.be(false); - expect(py.eval('None > True')).to.be(false); - - expect(py.eval('False < ""')).to.be(true); - expect(py.eval('"" > False')).to.be(true); - expect(py.eval('False > ""')).to.be(false); - }); - }); -}); -describe('Boolean operators', function () { - it('should work', function () { - expect(py.eval("foo == 'foo' or foo == 'bar'", - {foo: 'bar'})) - .to.be(true);; - expect(py.eval("foo == 'foo' and bar == 'bar'", - {foo: 'foo', bar: 'bar'})) - .to.be(true);; - }); - it('should be lazy', function () { - // second clause should nameerror if evaluated - expect(py.eval("foo == 'foo' or bar == 'bar'", - {foo: 'foo'})) - .to.be(true);; - expect(py.eval("foo == 'foo' and bar == 'bar'", - {foo: 'bar'})) - .to.be(false);; - }); - it('should return the actual object', function () { - expect(py.eval('"foo" or "bar"')).to.be('foo'); - expect(py.eval('None or "bar"')).to.be('bar'); - expect(py.eval('False or None')).to.be(null); - expect(py.eval('0 or 1')).to.be(1); - }); -}); -describe('Containment', function () { - describe('in sequences', function () { - it('should match collection items', function () { - expect(py.eval("'bar' in ('foo', 'bar')")) - .to.be(true); - expect(py.eval('1 in (1, 2, 3, 4)')) - .to.be(true);; - expect(py.eval('1 in (2, 3, 4)')) - .to.be(false);; - expect(py.eval('"url" in ("url",)')) - .to.be(true); - expect(py.eval('"foo" in ["foo", "bar"]')) - .to.be(true); - }); - it('should not be recursive', function () { - expect(py.eval('"ur" in ("url",)')) - .to.be(false);; - }); - it('should be negatable', function () { - expect(py.eval('1 not in (2, 3, 4)')).to.be(true); - expect(py.eval('"ur" not in ("url",)')).to.be(true); - expect(py.eval('-2 not in (1, 2, 3)')).to.be(true); - }); - }); - describe('in dict', function () { - // TODO - }); - describe('in strings', function () { - it('should match the whole string', function () { - expect(py.eval('"view" in "view"')).to.be(true); - expect(py.eval('"bob" in "view"')).to.be(false); - }); - it('should match substrings', function () { - expect(py.eval('"ur" in "url"')).to.be(true); - }); - }); -}); -describe('Conversions', function () { - describe('to bool', function () { - describe('strings', function () { - it('should be true if non-empty', function () { - expect(py.eval('bool(date_deadline)', - {date_deadline: '2008'})) - .to.be(true); - }); - it('should be false if empty', function () { - expect(py.eval('bool(s)', {s: ''})) .to.be(false); - }); - }); - }); -}); -describe('Attribute access', function () { - it("should return the attribute's value", function () { - var o = new py.object(); - o.bar = py.True; - expect(py.eval('foo.bar', {foo: o})).to.be(true); - o.bar = py.False; - expect(py.eval('foo.bar', {foo: o})).to.be(false); - }); - it("should work with functions", function () { - var o = new py.object(); - o.bar = new py.def(function () { - return new py.str("ok"); - }); - expect(py.eval('foo.bar()', {foo: o})).to.be('ok'); - }); - it('should not convert function attributes into methods', function () { - var o = new py.object(); - o.bar = new py.type(function bar() {}); - o.bar.__getattribute__ = function () { - return o.bar.baz; - } - o.bar.baz = py.True; - expect(py.eval('foo.bar.baz', {foo: o})).to.be(true); - }); - it('should work on instance attributes', function () { - var typ = py.type(function MyType() { - this.attr = new py.float(3); - }, py.object, {}); - expect(py.eval('MyType().attr', {MyType: typ})).to.be(3); - }); - it('should work on class attributes', function () { - var typ = py.type(function MyType() {}, py.object, { - attr: new py.float(3) - }); - expect(py.eval('MyType().attr', {MyType: typ})).to.be(3); - }); - it('should work with methods', function () { - var typ = py.type(function MyType() { - this.attr = new py.float(3); - }, py.object, { - some_method: function () { return new py.str('ok'); }, - get_attr: function () { return this.attr; } - }); - expect(py.eval('MyType().some_method()', {MyType: typ})).to.be('ok'); - expect(py.eval('MyType().get_attr()', {MyType: typ})).to.be(3); - }); -}); -describe('Callables', function () { - it('should wrap JS functions', function () { - expect(py.eval('foo()', {foo: function foo() { return new py.float(3); }})) - .to.be(3); - }); - it('should work on custom types', function () { - var typ = py.type(function MyType() {}, py.object, { - toJSON: function () { return true; } - }); - expect(py.eval('MyType()', {MyType: typ})).to.be(true); - }); - it('should accept kwargs', function () { - expect(py.eval('foo(ok=True)', { - foo: function foo() { return py.True; } - })).to.be(true); - }); - it('should be able to get its kwargs', function () { - expect(py.eval('foo(ok=True)', { - foo: function foo(args, kwargs) { return kwargs.ok; } - })).to.be(true); - }); - it('should be able to have both args and kwargs', function () { - expect(py.eval('foo(1, 2, 3, ok=True, nok=False)', { - foo: function (args, kwargs) { - expect(args).to.have.length(3); - expect(args[0].toJSON()).to.be(1); - expect(kwargs).to.only.have.keys('ok', 'nok') - expect(kwargs.nok.toJSON()).to.be(false); - return kwargs.ok; - } - })).to.be(true); - }); -}); -describe('issubclass', function () { - it('should say a type is its own subclass', function () { - expect(py.issubclass.__call__([py.dict, py.dict]).toJSON()) - .to.be(true); - expect(py.eval('issubclass(dict, dict)')) - .to.be(true); - }); - it('should work with subtypes', function () { - expect(py.issubclass.__call__([py.bool, py.object]).toJSON()) - .to.be(true); - }); -}); -describe('builtins', function () { - it('should aways be available', function () { - expect(py.eval('bool("foo")')).to.be(true); - }); -}); - -describe('numerical protocols', function () { - describe('True numbers (float)', function () { - describe('Basic arithmetic', function () { - it('can be added', function () { - expect(py.eval('1 + 1')).to.be(2); - expect(py.eval('1.5 + 2')).to.be(3.5); - expect(py.eval('1 + -1')).to.be(0); - }); - it('can be subtracted', function () { - expect(py.eval('1 - 1')).to.be(0); - expect(py.eval('1.5 - 2')).to.be(-0.5); - expect(py.eval('2 - 1.5')).to.be(0.5); - }); - it('can be multiplied', function () { - expect(py.eval('1 * 3')).to.be(3); - expect(py.eval('0 * 5')).to.be(0); - expect(py.eval('42 * -2')).to.be(-84); - }); - it('can be divided', function () { - expect(py.eval('1 / 2')).to.be(0.5); - expect(py.eval('2 / 1')).to.be(2); - }); - }); - }); - describe('Strings', function () { - describe('Basic arithmetics operators', function () { - it('can be added (concatenation)', function () { - expect(py.eval('"foo" + "bar"')).to.be('foobar'); - }); - }); - }); -}); -describe('dicts', function () { - it('should be possible to retrieve their value', function () { - var d = new py.dict({foo: 3, bar: 4, baz: 5}); - expect(py.eval('d["foo"]', {d: d})).to.be(3); - expect(py.eval('d["baz"]', {d: d})).to.be(5); - }); - it('should raise KeyError if a key is missing', function () { - var d = new py.dict(); - expect(function () { - py.eval('d["foo"]', {d: d}); - }).to.throwException(/^KeyError/); - }); - it('should have a method to provide a default value', function () { - var d = new py.dict({foo: 3}); - expect(py.eval('d.get("foo")', {d: d})).to.be(3); - expect(py.eval('d.get("bar")', {d: d})).to.be(null); - expect(py.eval('d.get("bar", 42)', {d: d})).to.be(42); - - var e = new py.dict({foo: null}); - expect(py.eval('d.get("foo")', {d: e})).to.be(null); - expect(py.eval('d.get("bar")', {d: e})).to.be(null); - }); -}); -describe('Type converter', function () { - it('should convert bare objects to objects', function () { - expect(py.eval('foo.bar', {foo: {bar: 3}})).to.be(3); - }); - it('should convert arrays to lists', function () { - expect(py.eval('foo[3]', {foo: [9, 8, 7, 6, 5]})) - .to.be(6); - }); -}); diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 34ddf0e119b..80aac87ecbe 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -4,66 +4,151 @@ openerp.web.pyeval = function (instance) { instance.web.pyeval = {}; + var obj = function () {}; + obj.prototype = py.object; var asJS = function (arg) { - if (arg instanceof py.object) { + if (arg instanceof obj) { return arg.toJSON(); } return arg; }; - var datetime = new py.object(); - datetime.datetime = new py.type(function datetime() { - throw new Error('datetime.datetime not implemented'); + var datetime = py.PY_call(py.object); + datetime.datetime = py.type('datetime', null, { + __init__: function () { + var zero = py.float.fromJSON(0); + var args = py.PY_parseArgs(arguments, [ + 'year', 'month', 'day', + ['hour', zero], ['minute', zero], ['second', zero], + ['microsecond', zero], ['tzinfo', py.None] + ]); + for(var key in args) { + if (!args.hasOwnProperty(key)) { continue; } + this[key] = asJS(args[key]); + } + }, + strftime: function () { + var self = this; + var args = py.PY_parseArgs(arguments, 'format'); + return py.str.fromJSON(args.format.toJSON() + .replace(/%([A-Za-z])/g, function (m, c) { + switch (c) { + case 'Y': return self.year; + case 'm': return _.str.sprintf('%02d', self.month); + case 'd': return _.str.sprintf('%02d', self.day); + case 'H': return _.str.sprintf('%02d', self.hour); + case 'M': return _.str.sprintf('%02d', self.minute); + case 'S': return _.str.sprintf('%02d', self.second); + } + throw new Error('ValueError: No known conversion for ' + m); + })); + }, + now: py.classmethod.fromJSON(function () { + var d = new Date(); + return py.PY_call(datetime.datetime, + [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), + d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), + d.getUTCMilliseconds() * 1000]); + }), + today: py.classmethod.fromJSON(function () { + var d = new Date(); + return py.PY_call(datetime.datetime, + [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]); + }), + combine: py.classmethod.fromJSON(function () { + var args = py.PY_parseArgs(arguments, 'date time'); + return py.PY_call(datetime.datetime, [ + // FIXME: should use getattr + args.date.year, + args.date.month, + args.date.day, + args.time.hour, + args.time.minute, + args.time.second + ]); + }) }); - var date = datetime.date = new py.type(function date(y, m, d) { - if (y instanceof Array) { - d = y[2]; - m = y[1]; - y = y[0]; - } - this.year = asJS(y); - this.month = asJS(m); - this.day = asJS(d); - }, py.object, { - strftime: function (args) { - var f = asJS(args[0]), self = this; - return new py.str(f.replace(/%([A-Za-z])/g, function (m, c) { - switch (c) { - case 'Y': return self.year; - case 'm': return _.str.sprintf('%02d', self.month); - case 'd': return _.str.sprintf('%02d', self.day); - } - throw new Error('ValueError: No known conversion for ' + m); - })); - } + datetime.date = py.type('date', null, { + __init__: function () { + var args = py.PY_parseArgs(arguments, 'year month day'); + this.year = asJS(args.year); + this.month = asJS(args.month); + this.day = asJS(args.day); + }, + strftime: function () { + var self = this; + var args = py.PY_parseArgs(arguments, 'format'); + return py.str.fromJSON(args.format.toJSON() + .replace(/%([A-Za-z])/g, function (m, c) { + switch (c) { + case 'Y': return self.year; + case 'm': return _.str.sprintf('%02d', self.month); + case 'd': return _.str.sprintf('%02d', self.day); + } + throw new Error('ValueError: No known conversion for ' + m); + })); + }, + today: py.classmethod.fromJSON(function () { + var d = new Date(); + return py.PY_call( + datetime.date, [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]); + }) }); - date.__getattribute__ = function (name) { - if (name === 'today') { - return date.today; + datetime.time = py.type('time', null, { + __init__: function () { + var zero = py.float.fromJSON(0); + var args = py.PY_parseArgs(arguments, [ + ['hour', zero], ['minute', zero], ['second', zero], ['microsecond', zero], + ['tzinfo', py.None] + ]); + + for(var k in args) { + if (!args.hasOwnProperty(k)) { continue; } + this[k] = asJS(args[k]); + } } - throw new Error("AttributeError: object 'date' has no attribute '" + name +"'"); - }; - date.today = new py.def(function () { - var d = new Date(); - return new date(d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); }); - datetime.time = new py.type(function time() { - throw new Error('datetime.time not implemented'); + + datetime.timedelta = py.type('timedelta', null, { + __init__: function () { + var zero = py.float.fromJSON(0); + var args = py.PY_parseArgs(arguments, + [['days', zero], ['seconds', zero], ['microseconds', zero], + ['milliseconds', zero], ['minutes', zero], ['hours', zero], + ['weeks', zero]]); + var ms = args['microseconds'].toJSON() + + 1000 * args['milliseconds'].toJSON(); + this.milliseconds = ms % 1000000; + var sec = Math.floor(ms / 1000000) + + args['seconds'].toJSON() + + 60 * args['minutes'].toJSON() + + 3600 * args['hours'].toJSON(); + this.seconds = sec % 86400; + this.days = Math.floor(sec / 86400) + + args['days'].toJSON() + + 7 * args['weeks'].toJSON(); + } }); - var time = new py.object(); - time.strftime = new py.def(function (args) { - return date.today.__call__().strftime(args); + var time = py.PY_call(py.object); + time.strftime = py.PY_def.fromJSON(function () { + // FIXME: needs PY_getattr + var d = py.PY_call(datetime.__getattribute__('datetime') + .__getattribute__('now')); + var args = [].slice.call(arguments); + return py.PY_call.apply( + null, [d.__getattribute__('strftime')].concat(args)); }); - var relativedelta = new py.type(function relativedelta(args, kwargs) { - if (!_.isEmpty(args)) { - throw new Error('Extraction of relative deltas from existing datetimes not supported'); - } - this.ops = kwargs; - }, py.object, { + var relativedelta = py.type('relativedelta', null, { + __init__: function () { + this.ops = py.PY_parseArgs(arguments, + '* year month day hour minute second microsecond ' + + 'years months weeks days hours minutes secondes microseconds ' + + 'weekday leakdays yearday nlyearday'); + }, __add__: function (other) { - if (!(other instanceof datetime.date)) { + if (py.PY_call(py.isinstance, [datetime.date]) !== py.True) { return py.NotImplemented; } // TODO: test this whole mess @@ -96,14 +181,19 @@ openerp.web.pyeval = function (instance) { // TODO: leapdays? // TODO: hours, minutes, seconds? Not used in XML domains // TODO: weekday? - return new datetime.date(year, month, day); + // FIXME: use date.replace + return py.PY_call(datetime.date, [ + py.float.fromJSON(year), + py.float.fromJSON(month), + py.float.fromJSON(day) + ]); }, __radd__: function (other) { return this.__add__(other); }, __sub__: function (other) { - if (!(other instanceof datetime.date)) { + if (py.PY_call(py.isinstance, [datetime.date]) !== py.True) { return py.NotImplemented; } // TODO: test this whole mess @@ -136,7 +226,11 @@ openerp.web.pyeval = function (instance) { // TODO: leapdays? // TODO: hours, minutes, seconds? Not used in XML domains // TODO: weekday? - return new datetime.date(year, month, day); + return py.PY_call(datetime.date, [ + py.float.fromJSON(year), + py.float.fromJSON(month), + py.float.fromJSON(day) + ]); }, __rsub__: function (other) { return this.__sub__(other); @@ -219,11 +313,12 @@ openerp.web.pyeval = function (instance) { instance.web.pyeval.context = function () { return { - uid: new py.float(instance.session.uid), + uid: py.float.fromJSON(instance.session.uid), datetime: datetime, time: time, relativedelta: relativedelta, - current_date: date.today.__call__().strftime(['%Y-%m-%d']), + current_date: py.PY_call( + time.strftime, [py.str.fromJSON('%Y-%m-%d')]), }; }; diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index dc8ceb83daf..3c3bface529 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -1,9 +1,51 @@ $(document).ready(function () { var openerp; + module("eval.types", { + setup: function () { + openerp = window.openerp.testing.instanceFor('coresetup'); + openerp.session.uid = 42; + } + }); + test('datetime.datetime', function () { + }); + test('datetime.date', function () { + + }); + test('datetime.timedelta', function () { + var d = new Date(); + d.setUTCDate(d.getUTCDate() - 15); + strictEqual( + py.eval("(datetime.date.today()" + + "- datetime.timedelta(days=15))" + + ".strftime('%Y-%m-%d')", openerp.web.pyeval.context()), + _.str.strftime('%04d-%02d-%02d', + d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate())); + + }); + test('relativedelta', function () { + + }); + test('strftime', function () { + var d = new Date(); + var context = openerp.web.pyeval.context(); + strictEqual( + py.eval("time.strftime('%Y')", context), + String(d.getUTCFullYear())); + strictEqual( + py.eval("time.strftime('%Y')+'-01-30'", context), + String(d.getUTCFullYear()) + '-01-30'); + strictEqual( + py.eval("time.strftime('%Y-%m-%d %H:%M:%S')", context), + _.str.sprintf('%04d-%02d-%02d %02d:%02d:%02d', + d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), + d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds())); + }); + module("eval.contexts", { setup: function () { openerp = window.openerp.testing.instanceFor('coresetup'); + openerp.session.uid = 42; } }); test('context_sequences', function () { @@ -135,6 +177,7 @@ $(document).ready(function () { setup: function () { openerp = window.openerp.testing.instanceFor('coresetup'); window.openerp.web.dates(openerp); + openerp.session.uid = 42; } }); test('current_date', function () { @@ -150,6 +193,7 @@ $(document).ready(function () { module('eval.groupbys', { setup: function () { openerp = window.openerp.testing.instanceFor('coresetup'); + openerp.session.uid = 42; } }); test('groupbys_00', function () { -- cgit v1.2.3 From 894bd34e6275fe838bb0de30e25de4b0e09d4636 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 8 Oct 2012 14:55:23 +0200 Subject: [REM] timedelta, because pain bzr revid: xmo@openerp.com-20121008125523-ed1g42vjxbcfo62r --- addons/web/static/src/js/pyeval.js | 21 --------------------- addons/web/static/test/evals.js | 19 ------------------- 2 files changed, 40 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 80aac87ecbe..8b56d17c14e 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -109,27 +109,6 @@ openerp.web.pyeval = function (instance) { } }); - datetime.timedelta = py.type('timedelta', null, { - __init__: function () { - var zero = py.float.fromJSON(0); - var args = py.PY_parseArgs(arguments, - [['days', zero], ['seconds', zero], ['microseconds', zero], - ['milliseconds', zero], ['minutes', zero], ['hours', zero], - ['weeks', zero]]); - var ms = args['microseconds'].toJSON() - + 1000 * args['milliseconds'].toJSON(); - this.milliseconds = ms % 1000000; - var sec = Math.floor(ms / 1000000) - + args['seconds'].toJSON() - + 60 * args['minutes'].toJSON() - + 3600 * args['hours'].toJSON(); - this.seconds = sec % 86400; - this.days = Math.floor(sec / 86400) - + args['days'].toJSON() - + 7 * args['weeks'].toJSON(); - } - }); - var time = py.PY_call(py.object); time.strftime = py.PY_def.fromJSON(function () { // FIXME: needs PY_getattr diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index 3c3bface529..72c4cd7323a 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -6,25 +6,6 @@ $(document).ready(function () { openerp = window.openerp.testing.instanceFor('coresetup'); openerp.session.uid = 42; } - }); - test('datetime.datetime', function () { - }); - test('datetime.date', function () { - - }); - test('datetime.timedelta', function () { - var d = new Date(); - d.setUTCDate(d.getUTCDate() - 15); - strictEqual( - py.eval("(datetime.date.today()" + - "- datetime.timedelta(days=15))" + - ".strftime('%Y-%m-%d')", openerp.web.pyeval.context()), - _.str.strftime('%04d-%02d-%02d', - d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate())); - - }); - test('relativedelta', function () { - }); test('strftime', function () { var d = new Date(); -- cgit v1.2.3 From 1fa00288b269e68a47849eaa3fefc090759a357d Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Wed, 10 Oct 2012 16:59:45 +0200 Subject: [FIX] add 'context' free variable in evaluation contexts for domains and contexts bzr revid: xmo@openerp.com-20121010145945-16shdry3udum0mn1 --- addons/web/static/src/js/pyeval.js | 4 +++- addons/web/static/test/evals.js | 30 ++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 8b56d17c14e..a00fd186d58 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -307,7 +307,9 @@ openerp.web.pyeval = function (instance) { * @param {Object} [context] evaluation context */ instance.web.pyeval.eval = function (type, object, context) { - if (!context) { context = instance.web.pyeval.context()} + context = _.extend(instance.web.pyeval.context(), context || {}); + context['context'] = py.dict.fromJSON(context); + switch(type) { case 'contexts': return eval_contexts(object, context); case 'domains': return eval_domains(object, context); diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index 72c4cd7323a..72503d5313b 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -29,6 +29,21 @@ $(document).ready(function () { openerp.session.uid = 42; } }); + test('context_recursive', function () { + var context_to_eval = [{ + __ref: 'context', + __debug: '{"foo": context.get("bar", "qux")}' + }]; + deepEqual( + openerp.web.pyeval.eval('contexts', context_to_eval, {bar: "ok"}), + {foo: 'ok'}); + deepEqual( + openerp.web.pyeval.eval('contexts', context_to_eval, {bar: false}), + {foo: false}); + deepEqual( + openerp.web.pyeval.eval('contexts', context_to_eval), + {foo: 'qux'}); + }); test('context_sequences', function () { // Context n should have base evaluation context + all of contexts // 0..n-1 in its own evaluation context @@ -170,6 +185,21 @@ $(document).ready(function () { ['name', '<=', current_date] ]); }); + test('context_freevar', function () { + var domains_to_eval = [{ + __ref: 'domain', + __debug: '[("foo", "=", context.get("bar", "qux"))]' + }, [['bar', '>=', 42]]]; + deepEqual( + openerp.web.pyeval.eval('domains', domains_to_eval, {bar: "ok"}), + [['foo', '=', 'ok'], ['bar', '>=', 42]]); + deepEqual( + openerp.web.pyeval.eval('domains', domains_to_eval, {bar: false}), + [['foo', '=', false], ['bar', '>=', 42]]); + deepEqual( + openerp.web.pyeval.eval('domains', domains_to_eval), + [['foo', '=', 'qux'], ['bar', '>=', 42]]); + }); module('eval.groupbys', { setup: function () { -- cgit v1.2.3 From b94e9c30a78e0047457977bf8ff5bd6bdda81372 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Thu, 11 Oct 2012 09:57:59 +0200 Subject: [FIX] after discussions with odo, date/datetime/time for locally-evaluated contexts and domains should be local, not UTC bzr revid: xmo@openerp.com-20121011075759-qfwkfws5tu9yidab --- addons/web/static/src/js/pyeval.js | 10 +++++----- addons/web/static/test/evals.js | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index a00fd186d58..51fdc63e84c 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -46,14 +46,14 @@ openerp.web.pyeval = function (instance) { now: py.classmethod.fromJSON(function () { var d = new Date(); return py.PY_call(datetime.datetime, - [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), - d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), - d.getUTCMilliseconds() * 1000]); + [d.getFullYear(), d.getMonth() + 1, d.getDate(), + d.getHours(), d.getMinutes(), d.getSeconds(), + d.getMilliseconds() * 1000]); }), today: py.classmethod.fromJSON(function () { var d = new Date(); return py.PY_call(datetime.datetime, - [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]); + [d.getFullYear(), d.getMonth() + 1, d.getDate()]); }), combine: py.classmethod.fromJSON(function () { var args = py.PY_parseArgs(arguments, 'date time'); @@ -91,7 +91,7 @@ openerp.web.pyeval = function (instance) { today: py.classmethod.fromJSON(function () { var d = new Date(); return py.PY_call( - datetime.date, [d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()]); + datetime.date, [d.getFullYear(), d.getMonth() + 1, d.getDate()]); }) }); datetime.time = py.type('time', null, { diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index 72503d5313b..276636c1ed2 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -12,15 +12,15 @@ $(document).ready(function () { var context = openerp.web.pyeval.context(); strictEqual( py.eval("time.strftime('%Y')", context), - String(d.getUTCFullYear())); + String(d.getFullYear())); strictEqual( py.eval("time.strftime('%Y')+'-01-30'", context), - String(d.getUTCFullYear()) + '-01-30'); + String(d.getFullYear()) + '-01-30'); strictEqual( py.eval("time.strftime('%Y-%m-%d %H:%M:%S')", context), _.str.sprintf('%04d-%02d-%02d %02d:%02d:%02d', - d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate(), - d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds())); + d.getFullYear(), d.getMonth() + 1, d.getDate(), + d.getHours(), d.getMinutes(), d.getSeconds())); }); module("eval.contexts", { -- cgit v1.2.3 From e6b77eb820a7670b416319f314808e4b90931a01 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Thu, 11 Oct 2012 12:05:32 +0200 Subject: [IMP] shortcut call to eval_domain_and_context to be evaluated on the JS side, also add some offline-evaluation of contexts and domains in rpc call methods bzr revid: xmo@openerp.com-20121011100532-5ihje0maslp37zpf --- addons/web/static/src/js/corelib.js | 83 ++++--------------------------------- addons/web/static/src/js/data.js | 14 +++++-- addons/web/static/src/js/pyeval.js | 57 +++++++++++++++++++++++++ 3 files changed, 77 insertions(+), 77 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/corelib.js b/addons/web/static/src/js/corelib.js index 228cee5e411..e26a839639c 100644 --- a/addons/web/static/src/js/corelib.js +++ b/addons/web/static/src/js/corelib.js @@ -997,75 +997,6 @@ instance.web.JsonRPC = instance.web.CallbackEnabled.extend({ this.server = this.origin; // keep chs happy this.rpc_function = (this.origin == window_origin) ? this.rpc_json : this.rpc_jsonp; }, - /** - * FIXME: Huge testing hack, especially the evaluation context, rewrite + test for real before switching - */ - test_eval: function (source, expected) { - var match_template = '
    ' + - '
  • Source: %(source)s
  • ' + - '
  • Local: %(local)s
  • ' + - '
  • Remote: %(remote)s
  • ' + - '
', - fail_template = '
    ' + - '
  • Error: %(error)s
  • ' + - '
  • Source: %(source)s
  • ' + - '
'; - try { - // see Session.eval_context in Python - var ctx = instance.web.pyeval.eval('contexts', - ([this.context] || []).concat(source.contexts)); - if (!_.isEqual(ctx, expected.context)) { - instance.webclient.notification.warn('Context mismatch, report to xmo', - _.str.sprintf(match_template, { - source: JSON.stringify(source.contexts), - local: JSON.stringify(ctx), - remote: JSON.stringify(expected.context) - }), true); - } - } catch (e) { - instance.webclient.notification.warn('Context fail, report to xmo', - _.str.sprintf(fail_template, { - error: e.message, - source: JSON.stringify(source.contexts) - }), true); - } - - try { - var dom = instance.web.pyeval.eval('domains', source.domains); - if (!_.isEqual(dom, expected.domain)) { - instance.webclient.notification.warn('Domains mismatch, report to xmo', - _.str.sprintf(match_template, { - source: JSON.stringify(source.domains), - local: JSON.stringify(dom), - remote: JSON.stringify(expected.domain) - }), true); - } - } catch (e) { - instance.webclient.notification.warn('Domain fail, report to xmo', - _.str.sprintf(fail_template, { - error: e.message, - source: JSON.stringify(source.domains) - }), true); - } - - try { - var groups = instance.web.pyeval.eval('groupbys', source.group_by_seq); - if (!_.isEqual(groups, expected.group_by)) { - instance.webclient.notification.warn('GroupBy mismatch, report to xmo', - _.str.sprintf(match_template, { - source: JSON.stringify(source.group_by_seq), - local: JSON.stringify(groups), - remote: JSON.stringify(expected.group_by) - }), true); - } - } catch (e) { - instance.webclient.notification.warn('GroupBy fail, report to xmo', - _.str.sprintf(fail_template, { - error: e.message, - source: JSON.stringify(source.group_by_seq) - }), true); - } - }, /** * Executes an RPC call, registering the provided callbacks. * @@ -1098,13 +1029,17 @@ instance.web.JsonRPC = instance.web.CallbackEnabled.extend({ this.trigger('request', url, payload); var aborter = params.aborter; delete params.aborter; - var request = this.rpc_function(url, payload).then( - function (response, textStatus, jqXHR) { + var request; + if (url.url === '/web/session/eval_domain_and_context') { + // intercept eval_domain_and_context + request = instance.web.pyeval.eval_domains_and_contexts( + params) + } else { + request = this.rpc_function(url, payload); + } + request.then(function (response, textStatus, jqXHR) { self.trigger('response', response); if (!response.error) { - if (url.url === '/web/session/eval_domain_and_context') { - self.test_eval(params, response.result); - } deferred.resolve(response["result"], textStatus, jqXHR); } else if (response.error.data.type === "session_invalid") { self.uid = false; diff --git a/addons/web/static/src/js/data.js b/addons/web/static/src/js/data.js index 2b82e618203..af887a5152f 100644 --- a/addons/web/static/src/js/data.js +++ b/addons/web/static/src/js/data.js @@ -61,8 +61,10 @@ instance.web.Query = instance.web.Class.extend({ return instance.session.rpc('/web/dataset/search_read', { model: this._model.name, fields: this._fields || false, - domain: this._model.domain(this._filter), - context: this._model.context(this._context), + domain: instance.web.pyeval.eval('domains', + [this._model.domain(this._filter)]), + context: instance.web.pyeval.eval('contexts', + [this._model.context(this._context)]), offset: this._offset, limit: this._limit, sort: instance.web.serialize_sort(this._order_by) @@ -280,6 +282,7 @@ instance.web.Model = instance.web.Class.extend({ kwargs = args; args = []; } + instance.web.pyeval.ensure_evaluated(args, kwargs); return instance.session.rpc('/web/dataset/call_kw', { model: this.name, method: method, @@ -291,7 +294,7 @@ instance.web.Model = instance.web.Class.extend({ * Fetches a Query instance bound to this model, for searching * * @param {Array} [fields] fields to ultimately fetch during the search - * @returns {openerp.web.Query} + * @returns {instance.web.Query} */ query: function (fields) { return new instance.web.Query(this, fields); @@ -339,9 +342,11 @@ instance.web.Model = instance.web.Class.extend({ * FIXME: remove when evaluator integrated */ call_button: function (method, args) { + instance.web.pyeval.ensure_evaluated(args, {}); return instance.session.rpc('/web/dataset/call_button', { model: this.name, method: method, + // Should not be necessary anymore. Integrate remote in this? domain_id: null, context_id: args.length - 1, args: args || [] @@ -599,9 +604,12 @@ instance.web.DataSet = instance.web.CallbackEnabled.extend({ * @returns {$.Deferred} */ call_and_eval: function (method, args, domain_index, context_index) { + instance.web.pyeval.ensure_evaluated(args, {}); return instance.session.rpc('/web/dataset/call', { model: this.model, method: method, + // Should not be necessary anymore as ensure_evaluated traverses + // all of the args array domain_id: domain_index == undefined ? null : domain_index, context_id: context_index == undefined ? null : context_index, args: args || [] diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 51fdc63e84c..ca4d5a0a1e7 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -2,6 +2,7 @@ * py.js helpers and setup */ openerp.web.pyeval = function (instance) { + var _t = instance.web._t; instance.web.pyeval = {}; var obj = function () {}; @@ -317,4 +318,60 @@ openerp.web.pyeval = function (instance) { } throw new Error("Unknow evaluation type " + type) }; + + var eval_arg = function (arg) { + if (typeof arg !== 'object' || !arg.__ref) { return arg; } + switch(arg.__ref) { + case 'domain': case 'compound_domain': + return instance.web.pyeval.eval('domains', [arg]); + case 'context': case 'compound_context': + return instance.web.pyeval.eval('contexts', [arg]); + default: + throw new Error(_t("Unknown nonliteral type " + arg.__ref)); + } + }; + /** + * If args or kwargs are unevaluated contexts or domains (compound or not), + * evaluated them in-place. + * + * Potentially mutates both parameters. + * + * @param args + * @param kwargs + */ + instance.web.pyeval.ensure_evaluated = function (args, kwargs) { + for (var i=0; i Date: Thu, 22 Nov 2012 10:59:42 +0100 Subject: [IMP] mail: cursor=pointer for attachment input bzr revid: chm@openerp.com-20121122095942-fktfff4xrt0krxtv --- addons/web/static/src/css/base.css | 10 ++++++---- addons/web/static/src/css/base.sass | 10 ++++++---- 2 files changed, 12 insertions(+), 8 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/css/base.css b/addons/web/static/src/css/base.css index f361a3c879d..3392a2ae817 100644 --- a/addons/web/static/src/css/base.css +++ b/addons/web/static/src/css/base.css @@ -2367,6 +2367,7 @@ width: 100%; left: 2px; top: 7px; + overflow: hidden; } .openerp .oe_fileupload .oe_add button { display: inline; @@ -2393,10 +2394,11 @@ } .openerp .oe_fileupload .oe_add input.oe_form_binary_file { display: inline-block; - margin-left: -5px; - height: 28px; - width: 52px; - margin-top: -26px; + margin-left: -85px; + height: 22px; + width: 152px; + margin-top: -24px; + cursor: pointer; } .openerp .oe_fileupload .oe_add .oe_attach_label { color: #7c7bad; diff --git a/addons/web/static/src/css/base.sass b/addons/web/static/src/css/base.sass index b2f71befbaa..5b89f4e8185 100644 --- a/addons/web/static/src/css/base.sass +++ b/addons/web/static/src/css/base.sass @@ -1893,6 +1893,7 @@ $sheet-padding: 16px width: 100% left: +2px top: +7px + overflow: hidden button display: inline height: 24px @@ -1915,10 +1916,11 @@ $sheet-padding: 16px left: -9px input.oe_form_binary_file display: inline-block - margin-left: -5px - height: 28px - width: 52px - margin-top: -26px + margin-left: -85px + height: 22px + width: 152px + margin-top: -24px + cursor: pointer .oe_attach_label color: #7C7BAD margin-left: -3px -- cgit v1.2.3 From 04398646fbdbc5a5616d037dfc739fd666ab1b47 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Thu, 22 Nov 2012 12:16:08 +0100 Subject: [CHG] temporarily disable eval-domain-and-context interception bzr revid: xmo@openerp.com-20121122111608-hckowmw71b8any9f --- addons/web/static/src/js/corelib.js | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/corelib.js b/addons/web/static/src/js/corelib.js index 9726a5640f4..54eb6ce3e81 100644 --- a/addons/web/static/src/js/corelib.js +++ b/addons/web/static/src/js/corelib.js @@ -966,13 +966,13 @@ instance.web.JsonRPC = instance.web.Class.extend(instance.web.PropertiesMixin, { if (! options.shadow) this.trigger('request', url, payload); var request; - if (url.url === '/web/session/eval_domain_and_context') { - // intercept eval_domain_and_context - request = instance.web.pyeval.eval_domains_and_contexts( - params) - } else { +// if (url.url === '/web/session/eval_domain_and_context') { +// // intercept eval_domain_and_context +// request = instance.web.pyeval.eval_domains_and_contexts( +// params) +// } else { request = this.rpc_function(url, payload); - } +// } request.then( function (response, textStatus, jqXHR) { if (! options.shadow) -- cgit v1.2.3 From 3909d1ff0218203755f554eba8ee2a86dbd1405c Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Thu, 22 Nov 2012 12:16:28 +0100 Subject: [ADD] a bunch of eval domain and context tests bzr revid: xmo@openerp.com-20121122111628-4khivcp97xoy121i --- addons/web/static/test/evals.js | 250 +++++++++++++++++++++++++++++++++++++++- 1 file changed, 249 insertions(+), 1 deletion(-) (limited to 'addons/web/static') diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index bef8edb1568..2fe3168a357 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -17,6 +17,254 @@ openerp.testing.section('eval.types', { d.getHours(), d.getMinutes(), d.getSeconds())); }); }); +openerp.testing.section('eval.edc', { + dependencies: ['web.data'], + rpc: 'rpc', + setup: function (instance) { + instance.edc = function (domains, contexts) { + return this.session.rpc('/web/session/eval_domain_and_context', { + contexts: contexts || [], + domains: domains || [] + }); + } + } +}, function (test) { + test('empty, basic', {asserts: 3}, function (instance) { + return instance.edc().then(function (result) { + // default values for new db + deepEqual(result.context, { + lang: 'en_US', + tz: false, + uid: 1 + }); + deepEqual(result.domain, []); + deepEqual(result.group_by, []); + }); + }); + test('empty, context altered', { + asserts: 3, + setup: function (instance) { + var lang = new instance.web.Model('res.lang'); + var users = new instance.web.Model('res.users'); + return lang.call('load_lang', ['ru_RU']).then(function () { + return users.call('write', [instance.session.uid, { + lang: 'ru_RU', + tz: 'America/Santarem' + }]); + }).then(function () { + return instance.session.session_reload(); + }); + } + }, function (instance) { + return instance.edc().then(function (result) { + // default values for new db + deepEqual(result.context, { + lang: 'ru_RU', + tz: 'America/Santarem', + uid: 1 + }); + deepEqual(result.domain, []); + deepEqual(result.group_by, []); + }); + }); + test('context_merge_00', {asserts: 1}, function (instance) { + var ctx = [ + { + "__contexts": [ + { "lang": "en_US", "tz": false, "uid": 1 }, + { + "active_id": 8, + "active_ids": [ 8 ], + "active_model": "sale.order", + "bin_raw": true, + "default_composition_mode": "comment", + "default_model": "sale.order", + "default_res_id": 8, + "default_template_id": 18, + "default_use_template": true, + "edi_web_url_view": "faaaake", + "lang": "en_US", + "mark_so_as_sent": null, + "show_address": null, + "tz": false, + "uid": null + }, + {} + ], + "__eval_context": null, + "__ref": "compound_context" + }, + { "active_id": 9, "active_ids": [ 9 ], "active_model": "mail.compose.message" } + ]; + return instance.edc([], ctx).then(function (result) { + deepEqual(result.context, { + active_id: 9, + active_ids: [9], + active_model: 'mail.compose.message', + bin_raw: true, + default_composition_mode: 'comment', + default_model: 'sale.order', + default_res_id: 8, + default_template_id: 18, + default_use_template: true, + edi_web_url_view: "faaaake", + lang: 'en_US', + mark_so_as_sent: null, + show_address: null, + tz: false, + uid: null + }); + }); + }); + test('context_merge_01', {asserts: 1}, function (instance) { + var ctx = [{ + "__contexts": [ + { + "lang": "en_US", + "tz": false, + "uid": 1 + }, + { + "default_attachment_ids": [], + "default_body": "", + "default_content_subtype": "html", + "default_model": "res.users", + "default_parent_id": false, + "default_res_id": 1 + }, + {} + ], + "__eval_context": null, + "__ref": "compound_context" + }]; + return instance.edc([], ctx).then(function (result) { + deepEqual(result.context, { + "default_attachment_ids": [], + "default_body": "", + "default_content_subtype": "html", + "default_model": "res.users", + "default_parent_id": false, + "default_res_id": 1, + "lang": "en_US", + "tz": false, + "uid": 1 + }); + }); + }); +}); +openerp.testing.section('eval.edc.nonliterals', { + dependencies: ['web.data'], + rpc: 'rpc', + setup: function (instance) { + _.extend(instance, { + edc: function (domains, contexts) { + return this.session.rpc('/web/session/eval_domain_and_context', { + contexts: contexts || [], + domains: domains || [] + }); + }, + load_context: function (index) { + return this.session.rpc('/web/tests/load_context', {index: index}); + }, + load_domain: function (index) { + return this.session.rpc('/web/tests/load_domain', {index: index}); + }, + }); + } +}, function (test) { + test('domain with time', {asserts: 2}, function (instance) { + return instance.load_domain(0).then(function (d) { + strictEqual(d.__ref, 'domain'); + return instance.edc([ + [['type', '=', 'contract']], + { "__domains": [["|"], [["state", "in", ["open", "draft"]]], [["state", "=", "pending"]]], + "__eval_context": null, + "__ref": "compound_domain" + }, + d, + [['user_id', '=', 1]] + ]) + }).then(function (result) { + var d = new Date(); + var today = _.str.sprintf("%04d-%02d-%02d", + d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); + deepEqual(result.domain, [ + ["type", "=", "contract"], + "|", ["state", "in", ["open", "draft"]], + ["state", "=", "pending"], + "|", + "&", ["date", "!=", false], + ["date", "<=", today], + ["is_overdue_quantity", "=", true], + ["user_id", "=", 1] + ]); + }); + }); + test('conditional context', {asserts: 2}, function (instance) { + return instance.load_domain(1).then(function (d) { + var e1 = instance.edc([d]).then(function (result) { + deepEqual(result.domain, [ + ['company_id', '=', false] + ]); + }); + var cd = new instance.web.CompoundDomain(d); + cd.set_eval_context({company_id: 42}); + var e2 = instance.edc([cd]).then(function (result) { + deepEqual(result.domain, [ + ['company_id', '=', 42] + ]); + }); + + return $.when(e1, e2); + }); + }); + test('substitution in context', {asserts: 1}, function (instance) { + return instance.load_context(0).then(function (c) { + var cc = new instance.web.CompoundContext(c); + cc.set_eval_context({active_id: 42}); + return instance.edc([], [cc]); + }).then(function (result) { + deepEqual(result.context, { + lang: "en_US", + tz: false, + uid: 1, + default_opportunity_id: 42, + default_duration: 1.0, + lng: "en_US" + }); + }); + }); + test('date', {asserts: 1}, function (instance) { + return instance.load_domain(4).then(function (d) { + return instance.edc([d]); + }).then(function (result) { + var d = new Date(); + var today = _.str.sprintf("%04d-%02d-%02d", + d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); + deepEqual(result.domain, [ + ['state', '!=', 'cancel'], + ['opening_date', '>', today] + ]); + }); + }); + test('delta', {asserts: 1}, function (instance) { + return instance.load_domain(5).then(function (d) { + return instance.edc([d]); + }).then(function (result) { + var d = new Date(); + var today = _.str.sprintf("%04d-%02d-%02d", + d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); + d.setDate(d.getDate() - 15); + var ago_15_d = _.str.sprintf("%04d-%02d-%02d", + d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); + deepEqual(result.domain, [ + ['type', '=', 'in'], + ['day', '<=', today], + ['day', '>', ago_15_d] + ]); + }); + }); +}); openerp.testing.section('eval.contexts', { dependencies: ['web.coresetup'] }, function (test) { @@ -161,7 +409,7 @@ openerp.testing.section('eval.contexts', { deepEqual(result, {type: 'out_invoice'}); }); }); -openerp.testing.section('eval.contexts', { +openerp.testing.section('eval.domains', { dependencies: ['web.coresetup', 'web.dates'] }, function (test) { test('current_date', function (instance) { -- cgit v1.2.3 From 9105afcd68643c97235a87058d576ebdd10cad4b Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Thu, 22 Nov 2012 13:41:30 +0100 Subject: [FIX] put evaluation context in evaluation context so you can access the context while you're accessing the context bzr revid: xmo@openerp.com-20121122124130-t8j6sggtnl4f0b8r --- addons/web/static/src/js/pyeval.js | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index ca4d5a0a1e7..fe68d5652a5 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -2,7 +2,6 @@ * py.js helpers and setup */ openerp.web.pyeval = function (instance) { - var _t = instance.web._t; instance.web.pyeval = {}; var obj = function () {}; @@ -226,6 +225,7 @@ openerp.web.pyeval = function (instance) { var evaluated = ctx; switch(ctx.__ref) { case 'context': + evaluation_context.context = py.dict.fromJSON(evaluation_context); evaluated = py.eval(ctx.__debug, evaluation_context); break; case 'compound_context': @@ -245,6 +245,7 @@ openerp.web.pyeval = function (instance) { _(domains).each(function (domain) { switch(domain.__ref) { case 'domain': + evaluation_context.context = py.dict.fromJSON(evaluation_context); result_domain.push.apply( result_domain, py.eval(domain.__debug, evaluation_context)); break; @@ -268,6 +269,7 @@ openerp.web.pyeval = function (instance) { var evaluated = ctx; switch(ctx.__ref) { case 'context': + evaluation_context.context = py.dict.fromJSON(evaluation_context); evaluated = py.eval(ctx.__debug, evaluation_context); break; case 'compound_context': @@ -327,7 +329,7 @@ openerp.web.pyeval = function (instance) { case 'context': case 'compound_context': return instance.web.pyeval.eval('contexts', [arg]); default: - throw new Error(_t("Unknown nonliteral type " + arg.__ref)); + throw new Error(instance.web._t("Unknown nonliteral type " + arg.__ref)); } }; /** @@ -362,11 +364,11 @@ openerp.web.pyeval = function (instance) { } catch (e) { d.resolve({ error: { code: 400, - message: _t("Evaluation Error"), + message: instance.web._t("Evaluation Error"), data: { type: 'local_exception', debug: _.str.sprintf( - _t("Local evaluation failure\n%s\n\n%s"), + instance.web._t("Local evaluation failure\n%s\n\n%s"), e.message, JSON.stringify(source)) } }}); -- cgit v1.2.3 From 815b908759451efd2d74cdb8d16a46bb83fe25c0 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 23 Nov 2012 08:59:38 +0100 Subject: [ADD] partial but sufficient (I think) implementation of datetime.timedelta bzr revid: xmo@openerp.com-20121123075938-oazwt4bn2l639r3a --- addons/web/static/src/js/pyeval.js | 187 ++++++++++++++++++++++++++++++++++++- addons/web/static/test/evals.js | 149 ++++++++++++++++++++++++++++- 2 files changed, 332 insertions(+), 4 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index fe68d5652a5..e0f465279ef 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -14,6 +14,188 @@ openerp.web.pyeval = function (instance) { }; var datetime = py.PY_call(py.object); + + /** + * computes (Math.floor(a/b), a%b and passes that to the callback. + * + * returns the callback's result + */ + var divmod = function (a, b, fn) { + var mod = a%b; + // in python, sign(a % b) === sign(b). Not in JS. If wrong side, add a + // round of b + if (mod > 0 && b < 0 || mod < 0 && b > 0) { + mod += b; + } + return fn(Math.floor(a/b), mod); + }; + /** + * Passes the fractional and integer parts of x to the callback, returns + * the callback's result + */ + var modf = function (x, fn) { + var mod = x%1; + if (mod < 0) { + mod += 1; + } + return fn(mod, Math.floor(x)); + }; + var zero = py.float.fromJSON(0); + // Port from pypy/lib_pypy/datetime.py + datetime.timedelta = py.type('timedelta', null, { + __init__: function () { + var args = py.PY_parseArgs(arguments, [ + ['days', zero], ['seconds', zero], ['microseconds', zero], + ['milliseconds', zero], ['minutes', zero], ['hours', zero], + ['weeks', zero] + ]); + + var d = 0, s = 0, m = 0; + var days = args.days.toJSON() + args.weeks.toJSON() * 7; + var seconds = args.seconds.toJSON() + + args.minutes.toJSON() * 60 + + args.hours.toJSON() * 3600; + var microseconds = args.microseconds.toJSON() + + args.milliseconds.toJSON() * 1000; + + // Get rid of all fractions, and normalize s and us. + // Take a deep breath . + var daysecondsfrac = modf(days, function (dayfrac, days) { + d = days; + if (dayfrac) { + return modf(dayfrac * 24 * 3600, function (dsf, dsw) { + s = dsw; + return dsf; + }); + } + return 0; + }); + + var secondsfrac = modf(seconds, function (sf, s) { + seconds = s; + return sf + daysecondsfrac; + }); + divmod(seconds, 24*3600, function (days, seconds) { + d += days; + s += seconds + }); + // seconds isn't referenced again before redefinition + + microseconds += secondsfrac * 1e6; + divmod(microseconds, 1000000, function (seconds, microseconds) { + divmod(seconds, 24*3600, function (days, seconds) { + d += days; + s += seconds; + m += Math.round(microseconds); + }); + }); + + // Carrying still possible here? + + this.days = d; + this.seconds = s; + this.microseconds = m; + }, + __str__: function () { + var hh, mm, ss; + divmod(this.seconds, 60, function (m, s) { + divmod(m, 60, function (h, m) { + hh = h; + mm = m; + ss = s; + }); + }); + var s = _.str.sprintf("%d:%02d:%02d", hh, mm, ss); + if (this.days) { + s = _.str.sprintf("%d day%s, %s", + this.days, + (this.days != 1 && this.days != -1) ? 's' : '', + s); + } + if (this.microseconds) { + s = _.str.sprintf("%s.%06d", s, this.microseconds); + } + return py.str.fromJSON(s); + }, + __eq__: function (other) { + if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + return py.False; + } + return (this.days === other.days + && this.seconds === other.seconds + && this.microseconds === other.microseconds) + ? py.True : py.False; + }, + __add__: function (other) { + if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + return py.NotImplemented; + } + return py.PY_call(datetime.timedelta, [ + py.float.fromJSON(this.days + other.days), + py.float.fromJSON(this.seconds + other.seconds), + py.float.fromJSON(this.microseconds + other.microseconds) + ]); + }, + __radd__: function (other) { return this.__add__(other); }, + __sub__: function (other) { + if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + return py.NotImplemented; + } + return py.PY_call(datetime.timedelta, [ + py.float.fromJSON(this.days - other.days), + py.float.fromJSON(this.seconds - other.seconds), + py.float.fromJSON(this.microseconds - other.microseconds) + ]); + }, + __rsub__: function (other) { + if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + return py.NotImplemented; + } + return this.__neg__().__add__(other); + }, + __neg__: function () { + return py.PY_call(datetime.timedelta, [ + py.float.fromJSON(-this.days), + py.float.fromJSON(-this.seconds), + py.float.fromJSON(-this.microseconds) + ]); + }, + __pos__: function () { return this; }, + __mul__: function (other) { + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } + var n = other.toJSON(); + return py.PY_call(datetime.timedelta, [ + py.float.fromJSON(this.days * n), + py.float.fromJSON(this.seconds * n), + py.float.fromJSON(this.microseconds * n) + ]); + }, + __rmul__: function (other) { return this.__mul__(other); }, + __div__: function (other) { + if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + return py.NotImplemented; + } + var usec = ((this.days * 24 * 3600) + this.seconds) * 1000000 + + this.microseconds; + return py.PY_call( + datetime.timedelta, [ + zero, zero, py.float.fromJSON(usec / other.toJSON())]); + }, + __floordiv__: function (other) { return this.__div__(other); }, + total_seconds: function () { + return py.float.fromJSON( + this.days * 86400 + + this.seconds + + this.microseconds / 1000000) + }, + __nonzero__: function () { + return (!!this.days || !!this.seconds || !!this.microseconds) + ? py.True + : py.False; + } + }); datetime.datetime = py.type('datetime', null, { __init__: function () { var zero = py.float.fromJSON(0); @@ -108,7 +290,6 @@ openerp.web.pyeval = function (instance) { } } }); - var time = py.PY_call(py.object); time.strftime = py.PY_def.fromJSON(function () { // FIXME: needs PY_getattr @@ -127,7 +308,7 @@ openerp.web.pyeval = function (instance) { + 'weekday leakdays yearday nlyearday'); }, __add__: function (other) { - if (py.PY_call(py.isinstance, [datetime.date]) !== py.True) { + if (py.PY_call(py.isinstance, [other, datetime.date]) !== py.True) { return py.NotImplemented; } // TODO: test this whole mess @@ -172,7 +353,7 @@ openerp.web.pyeval = function (instance) { }, __sub__: function (other) { - if (py.PY_call(py.isinstance, [datetime.date]) !== py.True) { + if (py.PY_call(py.isinstance, [other, datetime.date]) !== py.True) { return py.NotImplemented; } // TODO: test this whole mess diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index 2fe3168a357..ba9888617ee 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -1,5 +1,8 @@ openerp.testing.section('eval.types', { - dependencies: ['web.coresetup'] + dependencies: ['web.coresetup'], + setup: function (instance) { + instance.session.uid = 42; + } }, function (test) { test('strftime', function (instance) { var d = new Date(); @@ -16,6 +19,150 @@ openerp.testing.section('eval.types', { d.getFullYear(), d.getMonth() + 1, d.getDate(), d.getHours(), d.getMinutes(), d.getSeconds())); }); + // Port from pypy/lib_pypy/test_datetime.py + var makeEq = function (instance, c2) { + var ctx = instance.web.pyeval.context(); + var c = _.extend({ td: ctx.datetime.timedelta }, c2 || {}); + return function (a, b, message) { + ok(py.eval(a + ' == ' + b, c), message); + }; + }; + test('timedelta.test_constructor', function (instance) { + var eq = makeEq(instance); + + // keyword args to constructor + eq('td()', 'td(weeks=0, days=0, hours=0, minutes=0, seconds=0, ' + + 'milliseconds=0, microseconds=0)'); + eq('td(1)', 'td(days=1)'); + eq('td(0, 1)', 'td(seconds=1)'); + eq('td(0, 0, 1)', 'td(microseconds=1)'); + eq('td(weeks=1)', 'td(days=7)'); + eq('td(days=1)', 'td(hours=24)'); + eq('td(hours=1)', 'td(minutes=60)'); + eq('td(minutes=1)', 'td(seconds=60)'); + eq('td(seconds=1)', 'td(milliseconds=1000)'); + eq('td(milliseconds=1)', 'td(microseconds=1000)'); + + // Check float args to constructor + eq('td(weeks=1.0/7)', 'td(days=1)'); + eq('td(days=1.0/24)', 'td(hours=1)'); + eq('td(hours=1.0/60)', 'td(minutes=1)'); + eq('td(minutes=1.0/60)', 'td(seconds=1)'); + eq('td(seconds=0.001)', 'td(milliseconds=1)'); + eq('td(milliseconds=0.001)', 'td(microseconds=1)'); + }); + test('timedelta.test_computations', function (instance) { + var c = instance.web.pyeval.context(); + var zero = py.float.fromJSON(0); + var eq = makeEq(instance, { + // one week + a: py.PY_call(c.datetime.timedelta, [ + py.float.fromJSON(7)]), + // one minute + b: py.PY_call(c.datetime.timedelta, [ + zero, py.float.fromJSON(60)]), + // one millisecond + c: py.PY_call(c.datetime.timedelta, [ + zero, zero, py.float.fromJSON(1000)]), + }); + + eq('a+b+c', 'td(7, 60, 1000)'); + eq('a-b', 'td(6, 24*3600 - 60)'); + eq('-a', 'td(-7)'); + eq('+a', 'td(7)'); + eq('-b', 'td(-1, 24*3600 - 60)'); + eq('-c', 'td(-1, 24*3600 - 1, 999000)'); +// eq('abs(a)', 'a'); +// eq('abs(-a)', 'a'); + eq('td(6, 24*3600)', 'a'); + eq('td(0, 0, 60*1000000)', 'b'); + eq('a*10', 'td(70)'); + eq('a*10', '10*a'); + // eq('a*10L', '10*a'); + eq('b*10', 'td(0, 600)'); + eq('10*b', 'td(0, 600)'); + // eq('b*10L', 'td(0, 600)'); + eq('c*10', 'td(0, 0, 10000)'); + eq('10*c', 'td(0, 0, 10000)'); + // eq('c*10L', 'td(0, 0, 10000)'); + eq('a*-1', '-a'); + eq('b*-2', '-b-b'); + eq('c*-2', '-c+-c'); + eq('b*(60*24)', '(b*60)*24'); + eq('b*(60*24)', '(60*b)*24'); + eq('c*1000', 'td(0, 1)'); + eq('1000*c', 'td(0, 1)'); + eq('a//7', 'td(1)'); + eq('b//10', 'td(0, 6)'); + eq('c//1000', 'td(0, 0, 1)'); + eq('a//10', 'td(0, 7*24*360)'); + eq('a//3600000', 'td(0, 0, 7*24*1000)'); + + // Issue #11576 + eq('td(999999999, 86399, 999999) - td(999999999, 86399, 999998)', 'td(0, 0, 1)'); + eq('td(999999999, 1, 1) - td(999999999, 1, 0)', + 'td(0, 0, 1)') + }); + test('timedelta.test_basic_attributes', function (instance) { + var ctx = instance.web.pyeval.context(); + strictEqual(py.eval('datetime.timedelta(1, 7, 31).days', ctx), 1); + strictEqual(py.eval('datetime.timedelta(1, 7, 31).seconds', ctx), 7); + strictEqual(py.eval('datetime.timedelta(1, 7, 31).microseconds', ctx), 31); + }); + test('timedelta.test_total_seconds', function (instance) { + var c = { timedelta: instance.web.pyeval.context().datetime.timedelta }; + strictEqual(py.eval('timedelta(365).total_seconds()', c), 31536000); + strictEqual( + py.eval('timedelta(seconds=123456.789012).total_seconds()', c), + 123456.789012); + strictEqual( + py.eval('timedelta(seconds=-123456.789012).total_seconds()', c), + -123456.789012); + strictEqual( + py.eval('timedelta(seconds=0.123456).total_seconds()', c), 0.123456); + strictEqual(py.eval('timedelta().total_seconds()', c), 0); + strictEqual( + py.eval('timedelta(seconds=1000000).total_seconds()', c), 1e6); + }); + test('timedelta.test_str', function (instance) { + var c = { td: instance.web.pyeval.context().datetime.timedelta }; + + strictEqual(py.eval('str(td(1))', c), "1 day, 0:00:00"); + strictEqual(py.eval('str(td(-1))', c), "-1 day, 0:00:00"); + strictEqual(py.eval('str(td(2))', c), "2 days, 0:00:00"); + strictEqual(py.eval('str(td(-2))', c), "-2 days, 0:00:00"); + + strictEqual(py.eval('str(td(hours=12, minutes=58, seconds=59))', c), + "12:58:59"); + strictEqual(py.eval('str(td(hours=2, minutes=3, seconds=4))', c), + "2:03:04"); + strictEqual( + py.eval('str(td(weeks=-30, hours=23, minutes=12, seconds=34))', c), + "-210 days, 23:12:34"); + + strictEqual(py.eval('str(td(milliseconds=1))', c), "0:00:00.001000"); + strictEqual(py.eval('str(td(microseconds=3))', c), "0:00:00.000003"); + + strictEqual( + py.eval('str(td(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999))', c), + "999999999 days, 23:59:59.999999"); + }); + test('timedelta.test_massive_normalization', function (instance) { + var td = py.PY_call( + instance.web.pyeval.context().datetime.timedelta, + {microseconds: py.float.fromJSON(-1)}); + strictEqual(td.days, -1); + strictEqual(td.seconds, 24 * 3600 - 1); + strictEqual(td.microseconds, 999999); + }); + test('timedelta.test_bool', function (instance) { + var c = { td: instance.web.pyeval.context().datetime.timedelta }; + ok(py.eval('bool(td(1))', c)); + ok(py.eval('bool(td(0, 1))', c)); + ok(py.eval('bool(td(0, 0, 1))', c)); + ok(py.eval('bool(td(microseconds=1))', c)); + ok(py.eval('bool(not td(0))', c)); + }); }); openerp.testing.section('eval.edc', { dependencies: ['web.data'], -- cgit v1.2.3 From 328537a7ba845d3cdf90826998d066dddec5c0de Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 23 Nov 2012 10:52:06 +0100 Subject: [ADD] arithmetics between date and timedelta bzr revid: xmo@openerp.com-20121123095206-dtvoiignb7xnzsl0 --- addons/web/static/src/js/pyeval.js | 205 ++++++++++++++++++++++++++++++++++++- addons/web/static/test/evals.js | 81 +++++++++++++++ 2 files changed, 285 insertions(+), 1 deletion(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index e0f465279ef..df8f4132af5 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -41,7 +41,177 @@ openerp.web.pyeval = function (instance) { return fn(mod, Math.floor(x)); }; var zero = py.float.fromJSON(0); + // Port from pypy/lib_pypy/datetime.py + var DAYS_IN_MONTH = [null, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + var DAYS_BEFORE_MONTH = [null]; + var dbm = 0; + for (var i=1; i 2 && is_leap(year); + return DAYS_BEFORE_MONTH[month] + + (post_leap_feb ? 1 : 0); + }; + var ymd2ord = function (year, month, day) { + var dim = days_in_month(year, month); + if (!(1 <= day && day <= dim)) { + throw new Error("ValueError: day must be in 1.." + dim); + } + return days_before_year(year) + + days_before_month(year, month) + + day; + }; + var DI400Y = days_before_year(401); + var DI100Y = days_before_year(101); + var DI4Y = days_before_year(5); + var assert = function (bool) { + if (!bool) { + throw new Error("AssertionError"); + } + }; + var ord2ymd = function (n) { + --n; + var n400, n100, n4, n1, n0; + divmod(n, DI400Y, function (_n400, n) { + n400 = _n400; + divmod(n, DI100Y, function (_n100, n) { + n100 = _n100; + divmod(n, DI4Y, function (_n4, n) { + n4 = _n4; + divmod(n, 365, function (_n1, n) { + n1 = _n1; + n0 = n; + }) + }); + }); + }); + + n = n0; + var year = n400 * 400 + 1 + n100 * 100 + n4 * 4 + n1; + if (n1 == 4 || n100 == 100) { + assert(n0 === 0); + return { + year: year - 1, + month: 12, + day: 31 + }; + } + + var leapyear = n1 === 3 && (n4 !== 24 || n100 == 3); + assert(leapyear == is_leap(year)); + var month = (n + 50) >> 5; + var preceding = DAYS_BEFORE_MONTH[month] + ((month > 2 && leapyear) ? 1 : 0); + if (preceding > n) { + --month; + preceding -= DAYS_IN_MONTH[month] + ((month === 2 && leapyear) ? 1 : 0); + } + n -= preceding; + return { + year: year, + month: month, + day: n+1 + }; + }; + + /** + * Converts the stuff passed in into a valid date, applying overflows as needed + */ + var tmxxx = function (year, month, day, hour, minute, second, microsecond) { + hour = hour || 0; minute = minute || 0; second = second || 0; + microsecond = microsecond || 0; + + if (microsecond < 0 || microsecond > 999999) { + divmod(microsecond, 1000000, function (carry, ms) { + microsecond = ms; + second += carry + }); + } + if (second < 0 || second > 59) { + divmod(second, 60, function (carry, s) { + second = s; + minute += carry; + }); + } + if (minute < 0 || minute > 59) { + divmod(minute, 60, function (carry, m) { + minute = m; + hour += carry; + }) + } + if (hour < 0 || hour > 23) { + divmod(hour, 24, function (carry, h) { + hour = h; + day += carry; + }) + } + // That was easy. Now it gets muddy: the proper range for day + // can't be determined without knowing the correct month and year, + // but if day is, e.g., plus or minus a million, the current month + // and year values make no sense (and may also be out of bounds + // themselves). + // Saying 12 months == 1 year should be non-controversial. + if (month < 1 || month > 12) { + divmod(month-1, 12, function (carry, m) { + month = m + 1; + year += carry; + }) + } + // Now only day can be out of bounds (year may also be out of bounds + // for a datetime object, but we don't care about that here). + // If day is out of bounds, what to do is arguable, but at least the + // method here is principled and explainable. + var dim = days_in_month(year, month); + if (day < 1 || day > dim) { + // Move day-1 days from the first of the month. First try to + // get off cheap if we're only one day out of range (adjustments + // for timezone alone can't be worse than that). + if (day === 0) { + --month; + if (month > 0) { + day = days_in_month(year, month); + } else { + --year; month=12; day=31; + } + } else if (day == dim + 1) { + ++month; + day = 1; + if (month > 12) { + month = 1; + ++year; + } + } else { + var r = ord2ymd(ymd2ord(year, month, 1) + (day - 1)); + year = r.year; + month = r.month; + day = r.day; + } + } + return { + year: year, + month: month, + day: day, + hour: hour, + minute: minute, + second: second, + microsecond: microsecond + }; + }; datetime.timedelta = py.type('timedelta', null, { __init__: function () { var args = py.PY_parseArgs(arguments, [ @@ -274,7 +444,40 @@ openerp.web.pyeval = function (instance) { var d = new Date(); return py.PY_call( datetime.date, [d.getFullYear(), d.getMonth() + 1, d.getDate()]); - }) + }), + __eq__: function (other) { + return (this.year === other.year + && this.month === other.month + && this.day === other.day) + ? py.True : py.False; + }, + __add__: function (other) { + if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + return py.NotImplemented; + } + var s = tmxxx(this.year, this.month, this.day + other.days); + console.log(this, other, s); + return datetime.date.fromJSON(s.year, s.month, s.day); + }, + __radd__: function (other) { return this.__add__(other); }, + __sub__: function (other) { + if (py.PY_call(py.isinstance, [other, datetime.timedelta]) === py.True) { + return this.__add__(other.__neg__()); + } + if (py.PY_call(py.isinstance, [other, datetime.date]) === py.True) { + // FIXME: getattr and sub API methods + return py.PY_call(datetime.timedelta, [ + this.toordinal().__sub__(other.toordinal()) + ]); + } + return py.NotImplemented; + }, + toordinal: function () { + return py.float.fromJSON(ymd2ord(this.year, this.month, this.day)); + }, + fromJSON: function (year, month, day) { + return py.PY_call(datetime.date, [year, month, day]) + } }); datetime.time = py.type('time', null, { __init__: function () { diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index ba9888617ee..d4f72b1c374 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -163,6 +163,87 @@ openerp.testing.section('eval.types', { ok(py.eval('bool(td(microseconds=1))', c)); ok(py.eval('bool(not td(0))', c)); }); + + test('date.test_computations', function (instance) { + var d = instance.web.pyeval.context().datetime; + + var a = d.date.fromJSON(2002, 1, 31); + var b = d.date.fromJSON(1956, 1, 31); + strictEqual( + py.eval('(a - b).days', {a: a, b: b}), + 46 * 365 + 12); + strictEqual(py.eval('(a - b).seconds', {a: a, b: b}), 0); + strictEqual(py.eval('(a - b).microseconds', {a: a, b: b}), 0); + + var day = py.PY_call(d.timedelta, [py.float.fromJSON(1)]); + var week = py.PY_call(d.timedelta, [py.float.fromJSON(7)]); + a = d.date.fromJSON(2002, 3, 2); + var ctx = { + a: a, + day: day, + week: week, + date: d.date + }; + ok(py.eval('a + day == date(2002, 3, 3)', ctx)); + ok(py.eval('day + a == date(2002, 3, 3)', ctx)); // 5 + ok(py.eval('a - day == date(2002, 3, 1)', ctx)); + ok(py.eval('-day + a == date(2002, 3, 1)', ctx)); + ok(py.eval('a + week == date(2002, 3, 9)', ctx)); + console.group(9) + ok(py.eval('a - week == date(2002, 2, 23)', ctx)); + console.groupEnd(); + ok(py.eval('a + 52*week == date(2003, 3, 1)', ctx)); // 10 + ok(py.eval('a - 52*week == date(2001, 3, 3)', ctx)); + ok(py.eval('(a + week) - a == week', ctx)); + ok(py.eval('(a + day) - a == day', ctx)); + ok(py.eval('(a - week) - a == -week', ctx)); + ok(py.eval('(a - day) - a == -day', ctx)); // 15 + ok(py.eval('a - (a + week) == -week', ctx)); + ok(py.eval('a - (a + day) == -day', ctx)); + ok(py.eval('a - (a - week) == week', ctx)); + ok(py.eval('a - (a - day) == day', ctx)); + + raises(function () { + py.eval('a + 1', ctx); + }, /^Error: TypeError:/); // 20 + raises(function () { + py.eval('a - 1', ctx); + }, /^Error: TypeError:/); + raises(function () { + py.eval('1 + a', ctx); + }, /^Error: TypeError:/); + raises(function () { + py.eval('1 - a', ctx); + }, /^Error: TypeError:/); + + // delta - date is senseless. + raises(function () { + py.eval('day - a', ctx); + }, /^Error: TypeError:/); + // mixing date and (delta or date) via * or // is senseless + raises(function () { + py.eval('day * a', ctx); + }, /^Error: TypeError:/); // 25 + raises(function () { + py.eval('a * day', ctx); + }, /^Error: TypeError:/); + raises(function () { + py.eval('day // a', ctx); + }, /^Error: TypeError:/); + raises(function () { + py.eval('a // day', ctx); + }, /^Error: TypeError:/); + raises(function () { + py.eval('a * a', ctx); + }, /^Error: TypeError:/); + raises(function () { + py.eval('a // a', ctx); + }, /^Error: TypeError:/); // 30 + // date + date is senseless + raises(function () { + py.eval('a + a', ctx); + }, /^Error: TypeError:/); + }); }); openerp.testing.section('eval.edc', { dependencies: ['web.data'], -- cgit v1.2.3 From 242a5da5a9f4b71b3ced9f583a461c397f6be22a Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 23 Nov 2012 10:58:24 +0100 Subject: [REM] stray logging bzr revid: xmo@openerp.com-20121123095824-xg6afc1l01t3y48y --- addons/web/static/src/js/pyeval.js | 1 - addons/web/static/test/evals.js | 2 -- 2 files changed, 3 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index df8f4132af5..2b4d1ef5eea 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -456,7 +456,6 @@ openerp.web.pyeval = function (instance) { return py.NotImplemented; } var s = tmxxx(this.year, this.month, this.day + other.days); - console.log(this, other, s); return datetime.date.fromJSON(s.year, s.month, s.day); }, __radd__: function (other) { return this.__add__(other); }, diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index d4f72b1c374..994c122f1e6 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -189,9 +189,7 @@ openerp.testing.section('eval.types', { ok(py.eval('a - day == date(2002, 3, 1)', ctx)); ok(py.eval('-day + a == date(2002, 3, 1)', ctx)); ok(py.eval('a + week == date(2002, 3, 9)', ctx)); - console.group(9) ok(py.eval('a - week == date(2002, 2, 23)', ctx)); - console.groupEnd(); ok(py.eval('a + 52*week == date(2003, 3, 1)', ctx)); // 10 ok(py.eval('a - 52*week == date(2001, 3, 3)', ctx)); ok(py.eval('(a + week) - a == week', ctx)); -- cgit v1.2.3 From 7c09e23de7fb106f087c71bd4cbd6844b8ab3e57 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 23 Nov 2012 11:16:58 +0100 Subject: [ADD] todo notes bzr revid: xmo@openerp.com-20121123101658-xoynynruwnuzyrv3 --- addons/web/static/src/js/pyeval.js | 3 +++ 1 file changed, 3 insertions(+) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 2b4d1ef5eea..ed9c1ce9e82 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -602,6 +602,7 @@ openerp.web.pyeval = function (instance) { var eval_contexts = function (contexts, evaluation_context) { evaluation_context = evaluation_context || {}; return _(contexts).reduce(function (result_context, ctx) { + // TODO: wrap string contexts in nonlit? // __eval_context evaluations can lead to some of `contexts`'s // values being null, skip them as well as empty contexts if (_.isEmpty(ctx)) { return result_context; } @@ -626,6 +627,7 @@ openerp.web.pyeval = function (instance) { var eval_domains = function (domains, evaluation_context) { var result_domain = []; _(domains).each(function (domain) { + // TODO: wrap string domains in nonlit? switch(domain.__ref) { case 'domain': evaluation_context.context = py.dict.fromJSON(evaluation_context); @@ -648,6 +650,7 @@ openerp.web.pyeval = function (instance) { var eval_groupbys = function (contexts, evaluation_context) { var result_group = []; _(contexts).each(function (ctx) { + // TODO: wrap string contexts in nonlit? var group; var evaluated = ctx; switch(ctx.__ref) { -- cgit v1.2.3 From 49bd834725989b1b59221cd335db53094ec88479 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 23 Nov 2012 11:18:22 +0100 Subject: [IMP] deferred init style bzr revid: xmo@openerp.com-20121123101822-inox7gkxvd0gtqbp --- addons/web/static/src/js/pyeval.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index ed9c1ce9e82..d00654fc8ef 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -737,8 +737,7 @@ openerp.web.pyeval = function (instance) { } }; instance.web.pyeval.eval_domains_and_contexts = function (source) { - var d = new $.Deferred(); - setTimeout(function () { + return new $.Deferred(function (d) {setTimeout(function () { try { var contexts = ([instance.session.context] || []).concat(source.contexts); // see Session.eval_context in Python @@ -759,7 +758,6 @@ openerp.web.pyeval = function (instance) { } }}); } - }, 0); - return d; + }, 0); }); } }; -- cgit v1.2.3 From 709f2506ff40d799aada58df74dd78522d965868 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 23 Nov 2012 12:39:32 +0100 Subject: [REM] server-side eval_domain_and_context bzr revid: xmo@openerp.com-20121123113932-siz0u2vp2u7z6wk2 --- addons/web/static/src/js/corelib.js | 11 ++--------- addons/web/static/src/js/pyeval.js | 8 ++++---- addons/web/static/src/js/search.js | 2 +- addons/web/static/src/js/view_form.js | 4 ++-- addons/web/static/src/js/view_tree.js | 2 +- addons/web/static/src/js/views.js | 6 +++--- addons/web/static/test/evals.js | 18 ++++++++++++++---- 7 files changed, 27 insertions(+), 24 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/corelib.js b/addons/web/static/src/js/corelib.js index 54eb6ce3e81..d05a42061de 100644 --- a/addons/web/static/src/js/corelib.js +++ b/addons/web/static/src/js/corelib.js @@ -965,15 +965,8 @@ instance.web.JsonRPC = instance.web.Class.extend(instance.web.PropertiesMixin, { var deferred = $.Deferred(); if (! options.shadow) this.trigger('request', url, payload); - var request; -// if (url.url === '/web/session/eval_domain_and_context') { -// // intercept eval_domain_and_context -// request = instance.web.pyeval.eval_domains_and_contexts( -// params) -// } else { - request = this.rpc_function(url, payload); -// } - request.then( + + this.rpc_function(url, payload).then( function (response, textStatus, jqXHR) { if (! options.shadow) self.trigger('response', response); diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index d00654fc8ef..e16880889d2 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -739,13 +739,13 @@ openerp.web.pyeval = function (instance) { instance.web.pyeval.eval_domains_and_contexts = function (source) { return new $.Deferred(function (d) {setTimeout(function () { try { - var contexts = ([instance.session.context] || []).concat(source.contexts); + var contexts = ([instance.session.user_context] || []).concat(source.contexts); // see Session.eval_context in Python - d.resolve({result: { + d.resolve({ context: instance.web.pyeval.eval('contexts', contexts), domain: instance.web.pyeval.eval('domains', source.domains), - group_by: instance.web.pyeval.eval('groupbys', source.group_by_seq) - }}, 'success', {}); + group_by: instance.web.pyeval.eval('groupbys', source.group_by_seq || []) + }); } catch (e) { d.resolve({ error: { code: 400, diff --git a/addons/web/static/src/js/search.js b/addons/web/static/src/js/search.js index 0f25b2484c3..e0a95df37ce 100644 --- a/addons/web/static/src/js/search.js +++ b/addons/web/static/src/js/search.js @@ -1614,7 +1614,7 @@ instance.web.search.CustomFilters = instance.web.search.Input.extend({ var set_as_default = this.$('#oe_searchview_custom_default').prop('checked'); var search = this.view.build_search_data(); - this.rpc('/web/session/eval_domain_and_context', { + instance.web.pyeval.eval_domains_and_contexts({ domains: search.domains, contexts: search.contexts, group_by_seq: search.groupbys || [] diff --git a/addons/web/static/src/js/view_form.js b/addons/web/static/src/js/view_form.js index c784b169d12..a2768e196c7 100644 --- a/addons/web/static/src/js/view_form.js +++ b/addons/web/static/src/js/view_form.js @@ -4588,7 +4588,7 @@ instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend var self = this; this.init_dataset(); if (this.options.initial_view == "search") { - self.rpc('/web/session/eval_domain_and_context', { + instance.web.pyeval.eval_domains_and_contexts({ domains: [], contexts: [this.context] }).done(function (results) { @@ -4659,7 +4659,7 @@ instance.web.form.SelectCreatePopup = instance.web.form.AbstractFormPopup.extend }, do_search: function(domains, contexts, groupbys) { var self = this; - this.rpc('/web/session/eval_domain_and_context', { + instance.web.pyeval.eval_domains_and_contexts({ domains: domains || [], contexts: contexts || [], group_by_seq: groupbys || [] diff --git a/addons/web/static/src/js/view_tree.js b/addons/web/static/src/js/view_tree.js index 8265be77ba1..8fd3b25ade5 100644 --- a/addons/web/static/src/js/view_tree.js +++ b/addons/web/static/src/js/view_tree.js @@ -236,7 +236,7 @@ instance.web.TreeView = instance.web.View.extend(/** @lends instance.web.TreeVie if (action.context) { c.add(action.context); } - return self.rpc('/web/session/eval_domain_and_context', { + return instance.web.pyeval.eval_domains_and_contexts({ contexts: [c], domains: [] }).then(function (res) { action.context = res.context; diff --git a/addons/web/static/src/js/views.js b/addons/web/static/src/js/views.js index 6fbbd3199ad..4c6b422cfbb 100644 --- a/addons/web/static/src/js/views.js +++ b/addons/web/static/src/js/views.js @@ -396,7 +396,7 @@ instance.web.ActionManager = instance.web.Widget.extend({ ir_actions_report_xml: function(action, options) { var self = this; instance.web.blockUI(); - self.rpc("/web/session/eval_domain_and_context", { + instance.web.pyeval.eval_domains_and_contexts({ contexts: [action.context], domains: [] }).done(function(res) { @@ -667,7 +667,7 @@ instance.web.ViewManager = instance.web.Widget.extend({ var self = this, controller = this.views[this.active_view].controller, action_context = this.action.context || {}; - this.rpc('/web/session/eval_domain_and_context', { + instance.web.pyeval.eval_domains_and_contexts({ domains: [this.action.domain || []].concat(domains || []), contexts: [action_context].concat(contexts || []), group_by_seq: groupbys || [] @@ -1227,7 +1227,7 @@ instance.web.View = instance.web.Widget.extend({ }); } ncontext.add(action.context || {}); - return self.rpc('/web/session/eval_domain_and_context', { + return instance.web.pyeval.eval_domains_and_contexts({ contexts: [ncontext], domains: [] }).then(function (results) { diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index 994c122f1e6..86da3ae2876 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -247,8 +247,13 @@ openerp.testing.section('eval.edc', { dependencies: ['web.data'], rpc: 'rpc', setup: function (instance) { + instance.session.user_context = { + lang: 'en_US', + tz: false, + uid: 1 + }; instance.edc = function (domains, contexts) { - return this.session.rpc('/web/session/eval_domain_and_context', { + return instance.web.pyeval.eval_domains_and_contexts({ contexts: contexts || [], domains: domains || [] }); @@ -382,9 +387,14 @@ openerp.testing.section('eval.edc.nonliterals', { dependencies: ['web.data'], rpc: 'rpc', setup: function (instance) { + instance.session.user_context = { + lang: 'en_US', + tz: false, + uid: 1 + }; _.extend(instance, { edc: function (domains, contexts) { - return this.session.rpc('/web/session/eval_domain_and_context', { + return instance.web.pyeval.eval_domains_and_contexts({ contexts: contexts || [], domains: domains || [] }); @@ -398,7 +408,7 @@ openerp.testing.section('eval.edc.nonliterals', { }); } }, function (test) { - test('domain with time', {asserts: 2}, function (instance) { + test('domain with time', {asserts: 1}, function (instance) { return instance.load_domain(0).then(function (d) { strictEqual(d.__ref, 'domain'); return instance.edc([ @@ -409,7 +419,7 @@ openerp.testing.section('eval.edc.nonliterals', { }, d, [['user_id', '=', 1]] - ]) + ]); }).then(function (result) { var d = new Date(); var today = _.str.sprintf("%04d-%02d-%02d", -- cgit v1.2.3 From 6b2b2d889c94b0cbab5fbe14a4555f4c8dbe179c Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 23 Nov 2012 12:49:23 +0100 Subject: [IMP] move nonliteral domains and contexts to JS test case bzr revid: xmo@openerp.com-20121123114923-t4047w6jztria91x --- addons/web/static/src/js/pyeval.js | 15 +++++-- addons/web/static/test/evals.js | 81 ++++++++++++++++---------------------- 2 files changed, 47 insertions(+), 49 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index e16880889d2..3c6b6619513 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -602,10 +602,13 @@ openerp.web.pyeval = function (instance) { var eval_contexts = function (contexts, evaluation_context) { evaluation_context = evaluation_context || {}; return _(contexts).reduce(function (result_context, ctx) { - // TODO: wrap string contexts in nonlit? // __eval_context evaluations can lead to some of `contexts`'s // values being null, skip them as well as empty contexts if (_.isEmpty(ctx)) { return result_context; } + if (_.isString(ctx)) { + // wrap raw strings in context + ctx = { __ref: 'context', __debug: ctx }; + } var evaluated = ctx; switch(ctx.__ref) { case 'context': @@ -627,7 +630,10 @@ openerp.web.pyeval = function (instance) { var eval_domains = function (domains, evaluation_context) { var result_domain = []; _(domains).each(function (domain) { - // TODO: wrap string domains in nonlit? + if (_.isString(domain)) { + // wrap raw strings in domain + domain = { __ref: 'domain', __debug: domain }; + } switch(domain.__ref) { case 'domain': evaluation_context.context = py.dict.fromJSON(evaluation_context); @@ -650,7 +656,10 @@ openerp.web.pyeval = function (instance) { var eval_groupbys = function (contexts, evaluation_context) { var result_group = []; _(contexts).each(function (ctx) { - // TODO: wrap string contexts in nonlit? + if (_.isString(ctx)) { + // wrap raw strings in context + ctx = { __ref: 'context', __debug: ctx }; + } var group; var evaluated = ctx; switch(ctx.__ref) { diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index 86da3ae2876..e65f697eea2 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -385,7 +385,6 @@ openerp.testing.section('eval.edc', { }); openerp.testing.section('eval.edc.nonliterals', { dependencies: ['web.data'], - rpc: 'rpc', setup: function (instance) { instance.session.user_context = { lang: 'en_US', @@ -398,29 +397,20 @@ openerp.testing.section('eval.edc.nonliterals', { contexts: contexts || [], domains: domains || [] }); - }, - load_context: function (index) { - return this.session.rpc('/web/tests/load_context', {index: index}); - }, - load_domain: function (index) { - return this.session.rpc('/web/tests/load_domain', {index: index}); - }, + } }); } }, function (test) { test('domain with time', {asserts: 1}, function (instance) { - return instance.load_domain(0).then(function (d) { - strictEqual(d.__ref, 'domain'); - return instance.edc([ - [['type', '=', 'contract']], - { "__domains": [["|"], [["state", "in", ["open", "draft"]]], [["state", "=", "pending"]]], - "__eval_context": null, - "__ref": "compound_domain" - }, - d, - [['user_id', '=', 1]] - ]); - }).then(function (result) { + return instance.edc([ + [['type', '=', 'contract']], + { "__domains": [["|"], [["state", "in", ["open", "draft"]]], [["state", "=", "pending"]]], + "__eval_context": null, + "__ref": "compound_domain" + }, + "['|', '&', ('date', '!=', False), ('date', '<=', time.strftime('%Y-%m-%d')), ('is_overdue_quantity', '=', True)]", + [['user_id', '=', 1]] + ]).then(function (result) { var d = new Date(); var today = _.str.sprintf("%04d-%02d-%02d", d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); @@ -437,29 +427,30 @@ openerp.testing.section('eval.edc.nonliterals', { }); }); test('conditional context', {asserts: 2}, function (instance) { - return instance.load_domain(1).then(function (d) { - var e1 = instance.edc([d]).then(function (result) { - deepEqual(result.domain, [ - ['company_id', '=', false] - ]); - }); - var cd = new instance.web.CompoundDomain(d); - cd.set_eval_context({company_id: 42}); - var e2 = instance.edc([cd]).then(function (result) { - deepEqual(result.domain, [ - ['company_id', '=', 42] - ]); - }); - - return $.when(e1, e2); + var d = { + __ref: 'domain', + __debug: "[('company_id', '=', context.get('company_id',False))]" + }; + var e1 = instance.edc([d]).then(function (result) { + deepEqual(result.domain, [ + ['company_id', '=', false] + ]); }); + var cd = new instance.web.CompoundDomain(d); + cd.set_eval_context({company_id: 42}); + var e2 = instance.edc([cd]).then(function (result) { + deepEqual(result.domain, [ + ['company_id', '=', 42] + ]); + }); + + return $.when(e1, e2); }); test('substitution in context', {asserts: 1}, function (instance) { - return instance.load_context(0).then(function (c) { - var cc = new instance.web.CompoundContext(c); - cc.set_eval_context({active_id: 42}); - return instance.edc([], [cc]); - }).then(function (result) { + var c = "{'default_opportunity_id': active_id, 'default_duration': 1.0, 'lng': lang}"; + var cc = new instance.web.CompoundContext(c); + cc.set_eval_context({active_id: 42}); + return instance.edc([], [cc]).then(function (result) { deepEqual(result.context, { lang: "en_US", tz: false, @@ -471,9 +462,8 @@ openerp.testing.section('eval.edc.nonliterals', { }); }); test('date', {asserts: 1}, function (instance) { - return instance.load_domain(4).then(function (d) { - return instance.edc([d]); - }).then(function (result) { + var d = "[('state','!=','cancel'),('opening_date','>',datetime.date.today().strftime('%Y-%m-%d'))]"; + return instance.edc([d]).then(function (result) { var d = new Date(); var today = _.str.sprintf("%04d-%02d-%02d", d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); @@ -484,9 +474,8 @@ openerp.testing.section('eval.edc.nonliterals', { }); }); test('delta', {asserts: 1}, function (instance) { - return instance.load_domain(5).then(function (d) { - return instance.edc([d]); - }).then(function (result) { + var d = "[('type','=','in'),('day','<=', time.strftime('%Y-%m-%d')),('day','>',(datetime.date.today()-datetime.timedelta(days=15)).strftime('%Y-%m-%d'))]"; + return instance.edc([d]).then(function (result) { var d = new Date(); var today = _.str.sprintf("%04d-%02d-%02d", d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate()); -- cgit v1.2.3 From 2c7f30a047bd5b4e2ada23448029549dc6c28f61 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Fri, 23 Nov 2012 13:05:00 +0100 Subject: [REM] session reload dependency on db bzr revid: xmo@openerp.com-20121123120500-k7fhwoocu0zbiali --- addons/web/static/test/evals.js | 35 ++++++++++++++++++++++++----------- 1 file changed, 24 insertions(+), 11 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index e65f697eea2..e71457a07e6 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -245,19 +245,34 @@ openerp.testing.section('eval.types', { }); openerp.testing.section('eval.edc', { dependencies: ['web.data'], - rpc: 'rpc', - setup: function (instance) { - instance.session.user_context = { - lang: 'en_US', - tz: false, - uid: 1 - }; + rpc: 'mock', + setup: function (instance, $fix, mock) { + var user = { login: 'admin', id: 1, lang: 'en_US', tz: false }; instance.edc = function (domains, contexts) { return instance.web.pyeval.eval_domains_and_contexts({ contexts: contexts || [], domains: domains || [] }); - } + }; + mock('res.lang:load_lang', function () { return true; }); + mock('res.users:write', function (args) { + _.extend(user, args[1]); + return true; + }); + mock('/web/session/get_session_info', function () { + return { + session_id: 'foobar', + db: '3', + login: user.login, + uid: user.id, + context: { + uid: user.id, + lang: user.lang, + tz: user.tz + } + }; + }); + return instance.session.session_reload(); } }, function (test) { test('empty, basic', {asserts: 3}, function (instance) { @@ -282,9 +297,7 @@ openerp.testing.section('eval.edc', { lang: 'ru_RU', tz: 'America/Santarem' }]); - }).then(function () { - return instance.session.session_reload(); - }); + }).then(instance.session.session_reload.bind(instance.session)); } }, function (instance) { return instance.edc().then(function (result) { -- cgit v1.2.3 From 65db450c8173b7aa69f21c1870167ef692e5bb5e Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 26 Nov 2012 08:30:02 +0100 Subject: [IMP] update py.js to 0.7 bzr revid: xmo@openerp.com-20121126073002-deta3rdrwmzao6fy --- addons/web/static/lib/py.js/.hg_archival.txt | 4 +- addons/web/static/lib/py.js/doc/builtins.rst | 2 + addons/web/static/lib/py.js/doc/utility.rst | 149 +++++++++++++++++--- addons/web/static/lib/py.js/lib/py.js | 200 +++++++++++++++++++-------- 4 files changed, 282 insertions(+), 73 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/lib/py.js/.hg_archival.txt b/addons/web/static/lib/py.js/.hg_archival.txt index e97bf6a334b..3da757d145d 100644 --- a/addons/web/static/lib/py.js/.hg_archival.txt +++ b/addons/web/static/lib/py.js/.hg_archival.txt @@ -1,5 +1,5 @@ repo: 076b192d0d8ab2b92d1dbcfa3da055382f30eaea -node: e47d717cf47d165a5a9916abbb5ceb138661efc6 +node: 7c9ac450ae180524cfdf69e0e03439caef4a43ac branch: default -latesttag: 0.6 +latesttag: 0.7 latesttagdistance: 1 diff --git a/addons/web/static/lib/py.js/doc/builtins.rst b/addons/web/static/lib/py.js/doc/builtins.rst index e46926566d3..6958d83b884 100644 --- a/addons/web/static/lib/py.js/doc/builtins.rst +++ b/addons/web/static/lib/py.js/doc/builtins.rst @@ -46,6 +46,8 @@ Supported Python builtins .. class:: py.dict() +.. function:: py.len(object) + .. function:: py.isinstance(object, type) .. function:: py.issubclass(type, other_type) diff --git a/addons/web/static/lib/py.js/doc/utility.rst b/addons/web/static/lib/py.js/doc/utility.rst index 90c05d448e1..86cfb1cfe36 100644 --- a/addons/web/static/lib/py.js/doc/utility.rst +++ b/addons/web/static/lib/py.js/doc/utility.rst @@ -7,23 +7,6 @@ ones. They are prefixed with ``PY_``. -.. function:: py.PY_call(callable[, args][, kwargs]) - - Call an arbitrary python-level callable from javascript. - - :param callable: A ``py.js`` callable object (broadly speaking, - either a class or an object with a ``__call__`` - method) - - :param args: javascript Array of :class:`py.object`, used as - positional arguments to ``callable`` - - :param kwargs: javascript Object mapping names to - :class:`py.object`, used as named arguments to - ``callable`` - - :returns: nothing or :class:`py.object` - .. function:: py.PY_parseArgs(arguments, format) Arguments parser converting from the :ref:`user-defined calling @@ -99,6 +82,138 @@ They are prefixed with ``PY_``. :param Function fn: the javascript function to wrap :returns: a callable py.js object +Object Protocol +--------------- + +.. function:: py.PY_hasAttr(o, attr_name) + + Returns ``true`` if ``o`` has the attribute ``attr_name``, + otherwise returns ``false``. Equivalent to Python's ``hasattr(o, + attr_name)`` + + :param o: A :class:`py.object` + :param attr_name: a javascript ``String`` + :rtype: ``Boolean`` + +.. function:: py.PY_getAttr(o, attr_name) + + Retrieve an attribute ``attr_name`` from the object ``o``. Returns + the attribute value on success, raises ``AttributeError`` on + failure. Equivalent to the python expression ``o.attr_name``. + + :param o: A :class:`py.object` + :param attr_name: a javascript ``String`` + :returns: A :class:`py.object` + :raises: ``AttributeError`` + +.. function:: py.PY_str(o) + + Computes a string representation of ``o``, returns the string + representation. Equivalent to ``str(o)`` + + :param o: A :class:`py.object` + :returns: :class:`py.str` + +.. function:: py.PY_isInstance(inst, cls) + + Returns ``true`` if ``inst`` is an instance of ``cls``, ``false`` + otherwise. + +.. function:: py.PY_isSubclass(derived, cls) + + Returns ``true`` if ``derived`` is ``cls`` or a subclass thereof. + +.. function:: py.PY_call(callable[, args][, kwargs]) + + Call an arbitrary python-level callable from javascript. + + :param callable: A ``py.js`` callable object (broadly speaking, + either a class or an object with a ``__call__`` + method) + + :param args: javascript Array of :class:`py.object`, used as + positional arguments to ``callable`` + + :param kwargs: javascript Object mapping names to + :class:`py.object`, used as named arguments to + ``callable`` + + :returns: nothing or :class:`py.object` + +.. function:: py.PY_isTrue(o) + + Returns ``true`` if the object is considered truthy, ``false`` + otherwise. Equivalent to ``bool(o)``. + + :param o: A :class:`py.object` + :rtype: Boolean + +.. function:: py.PY_not(o) + + Inverse of :func:`py.PY_isTrue`. + +.. function:: py.PY_size(o) + + If ``o`` is a sequence or mapping, returns its length. Otherwise, + raises ``TypeError``. + + :param o: A :class:`py.object` + :returns: ``Number`` + :raises: ``TypeError`` if the object doesn't have a length + +Number Protocol +--------------- + +.. function:: py.PY_add(o1, o2) + + Returns the result of adding ``o1`` and ``o2``, equivalent to + ``o1 + o2``. + + :param o1: :class:`py.object` + :param o2: :class:`py.object` + :returns: :class:`py.object` + +.. function:: py.PY_subtract(o1, o2) + + Returns the result of subtracting ``o2`` from ``o1``, equivalent + to ``o1 - o2``. + + :param o1: :class:`py.object` + :param o2: :class:`py.object` + :returns: :class:`py.object` + +.. function:: py.PY_multiply(o1, o2) + + Returns the result of multiplying ``o1`` by ``o2``, equivalent to + ``o1 * o2``. + + :param o1: :class:`py.object` + :param o2: :class:`py.object` + :returns: :class:`py.object` + +.. function:: py.PY_divide(o1, o2) + + Returns the result of dividing ``o1`` by ``o2``, equivalent to + ``o1 / o2``. + + :param o1: :class:`py.object` + :param o2: :class:`py.object` + :returns: :class:`py.object` + +.. function:: py.PY_negative(o) + + Returns the negation of ``o``, equivalent to ``-o``. + + :param o: :class:`py.object` + :returns: :class:`py.object` + +.. function:: py.PY_positive(o) + + Returns the "positive" of ``o``, equivalent to ``+o``. + + :param o: :class:`py.object` + :returns: :class:`py.object` + .. [#kwonly] Python 2, which py.js currently implements, does not support Python-level keyword-only parameters (it can be done through the C-API), but it seemed neat and easy diff --git a/addons/web/static/lib/py.js/lib/py.js b/addons/web/static/lib/py.js/lib/py.js index d03de622689..382247c2745 100644 --- a/addons/web/static/lib/py.js/lib/py.js +++ b/addons/web/static/lib/py.js/lib/py.js @@ -371,8 +371,8 @@ var py = {}; var fn = function () {} fn.prototype = py.object; - if (py.PY_call(py.isinstance, [val, py.object]) === py.True - || py.PY_call(py.issubclass, [val, py.object]) === py.True) { + if (py.PY_isInstance(val, py.object) + || py.PY_isSubclass(val, py.object)) { return val; } @@ -497,7 +497,43 @@ var py = {}; return out; }; - // Builtins + py.PY_hasAttr = function (o, attr_name) { + try { + py.PY_getAttr(o, attr_name); + return true; + } catch (e) { + return false; + } + }; + py.PY_getAttr = function (o, attr_name) { + return PY_ensurepy(o.__getattribute__(attr_name)); + }; + py.PY_str = function (o) { + var v = o.__str__(); + if (py.PY_isInstance(v, py.str)) { + return v; + } + var typename; + if (v.__class__) { // py type + typename = v.__class__.__name__; + } else if(typeof v !== 'object') { // JS primitive + typename = typeof v; + } else { // JS object + typename = v.constructor.name; + } + throw new Error( + 'TypeError: __str__ returned non-string (type '+typename+')'); + }; + py.PY_isInstance = function (inst, cls) { + var fn = function () {}; + fn.prototype = cls; + return inst instanceof fn; + }; + py.PY_isSubclass = function (derived, cls) { + var fn = function () {}; + fn.prototype = cls; + return derived === cls || derived instanceof fn; + }; py.PY_call = function (callable, args, kwargs) { if (!args) { args = []; kwargs = {}; @@ -519,6 +555,66 @@ var py = {}; } return callable.__call__(args, kwargs); }; + py.PY_isTrue = function (o) { + var res = o.__nonzero__(); + if (res === py.True) { + return true; + } + if (res === py.False) { + return false; + } + throw new Error( + "TypeError: __nonzero__ should return bool, returned " + + res.__class__.__name__); + }; + py.PY_not = function (o) { + return !py.PY_isTrue(o); + }; + py.PY_size = function (o) { + if (!o.__len__) { + throw new Error( + "TypeError: object of type '" + + o.__class__.__name__ + + "' has no len()"); + } + var v = o.__len__(); + if (typeof v !== 'number') { + throw new Error("TypeError: a number is required"); + } + return v; + }; + py.PY_add = function (o1, o2) { + return PY_op(o1, o2, '+'); + }; + py.PY_subtract = function (o1, o2) { + return PY_op(o1, o2, '-'); + }; + py.PY_multiply = function (o1, o2) { + return PY_op(o1, o2, '*'); + }; + py.PY_divide = function (o1, o2) { + return PY_op(o1, o2, '/'); + }; + py.PY_negative = function (o) { + if (!o.__neg__) { + throw new Error( + "TypeError: bad operand for unary -: '" + + o.__class__.__name + + "'"); + } + return o.__neg__(); + }; + py.PY_positive = function (o) { + if (!o.__pos__) { + throw new Error( + "TypeError: bad operand for unary +: '" + + o.__class__.__name + + "'"); + } + return o.__pos__(); + }; + + // Builtins py.type = function type(name, bases, dict) { var proto; if (typeof name !== 'string') { @@ -586,8 +682,7 @@ var py = {}; return this.__unicode__(); }, __unicode__: function () { - // TODO: return python string - return ''; + return py.str.fromJSON('<' + this.__class__.__name__ + ' object>'); }, __nonzero__: function () { return py.True; @@ -604,7 +699,7 @@ var py = {}; // val is a method from the class return PY_instancemethod.fromJSON(val, this); } - return PY_ensurepy(val); + return val; } if ('__getattr__' in this) { return this.__getattr__(name); @@ -643,9 +738,13 @@ var py = {}; if (args.value === ph) { return py.False; } - return args.value.__nonzero__() === py.True ? py.True : py.False; + return py.PY_isTrue(args.value) ? py.True : py.False; + }, + __str__: function () { + return py.str.fromJSON((this === py.True) ? "True" : "False"); }, __nonzero__: function () { return this; }, + fromJSON: function (val) { return val ? py.True : py.False }, toJSON: function () { return this === py.True; } }); py.True = py.PY_call(py.bool); @@ -659,13 +758,12 @@ var py = {}; if (value === placeholder) { this._value = 0; return; } - if (py.PY_call(py.isinstance, [value, py.float]) === py.True) { + if (py.PYisInstance(value, py.float)) { this._value = value._value; } - if (py.PY_call(py.isinstance, [value, py.object]) === py.True - && '__float__' in value) { + if (py.PY_isInstance(value, py.object) && '__float__' in value) { var res = value.__float__(); - if (py.PY_call(py.isinstance, [res, py.float]) === py.True) { + if (py.PY_isInstance(res, py.float)) { this._value = res._value; return; } @@ -674,35 +772,38 @@ var py = {}; } throw new Error('TypeError: float() argument must be a string or a number'); }, + __str__: function () { + return py.str.fromJSON(String(this._value)); + }, __eq__: function (other) { return this._value === other._value ? py.True : py.False; }, __lt__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } return this._value < other._value ? py.True : py.False; }, __le__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } return this._value <= other._value ? py.True : py.False; }, __gt__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } return this._value > other._value ? py.True : py.False; }, __ge__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } return this._value >= other._value ? py.True : py.False; }, __add__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } return py.float.fromJSON(this._value + other._value); @@ -711,19 +812,19 @@ var py = {}; return py.float.fromJSON(-this._value); }, __sub__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } return py.float.fromJSON(this._value - other._value); }, __mul__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } return py.float.fromJSON(this._value * other._value); }, __div__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } return py.float.fromJSON(this._value / other._value); @@ -733,7 +834,7 @@ var py = {}; }, fromJSON: function (v) { if (!(typeof v === 'number')) { - throw new Error('py.float.fromJSON can only take numbers '); + throw new Error('py.float.fromJSON can only take numbers'); } var instance = py.PY_call(py.float); instance._value = v; @@ -749,54 +850,47 @@ var py = {}; var args = py.PY_parseArgs(arguments, [['value', placeholder]]); var s = args.value; if (s === placeholder) { this._value = ''; return; } - if (py.PY_call(py.isinstance, [s, py.str]) === py.True) { - this._value = s._value; - return; - } - var v = s.__str__(); - if (py.PY_call(py.isinstance, [v, py.str]) === py.True) { - this._value = v._value; - return; - } - throw new Error('TypeError: __str__ returned non-string (type ' + - v.__class__.__name__ + ')'); + this._value = py.PY_str(s)._value; }, __hash__: function () { return '\1\0\1' + this._value; }, + __str__: function () { + return this; + }, __eq__: function (other) { - if (py.PY_call(py.isinstance, [other, py.str]) === py.True + if (py.PY_isInstance(other, py.str) && this._value === other._value) { return py.True; } return py.False; }, __lt__: function (other) { - if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + if (py.PY_not(py.PY_call(py.isinstance, [other, py.str]))) { return py.NotImplemented; } return this._value < other._value ? py.True : py.False; }, __le__: function (other) { - if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + if (!py.PY_isInstance(other, py.str)) { return py.NotImplemented; } return this._value <= other._value ? py.True : py.False; }, __gt__: function (other) { - if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + if (!py.PY_isInstance(other, py.str)) { return py.NotImplemented; } return this._value > other._value ? py.True : py.False; }, __ge__: function (other) { - if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + if (!py.PY_isInstance(other, py.str)) { return py.NotImplemented; } return this._value >= other._value ? py.True : py.False; }, __add__: function (other) { - if (py.PY_call(py.isinstance, [other, py.str]) !== py.True) { + if (!py.PY_isInstance(other, py.str)) { return py.NotImplemented; } return py.str.fromJSON(this._value + other._value); @@ -812,7 +906,7 @@ var py = {}; var instance = py.PY_call(py.str); instance._value = s; return instance; - }; + } throw new Error("str.fromJSON can only take strings"); }, toJSON: function () { @@ -921,20 +1015,19 @@ var py = {}; } }); + py.len = new py.PY_def.fromJSON(function len() { + var args = py.PY_parseArgs(arguments, ['object']); + return py.float.fromJSON(py.PY_size(args.object)); + }); py.isinstance = new py.PY_def.fromJSON(function isinstance() { var args = py.PY_parseArgs(arguments, ['object', 'class']); - var fn = function () {}; - fn.prototype = args['class']; - return (args.object instanceof fn) ? py.True : py.False; + return py.PY_isInstance(args.object, args['class']) + ? py.True : py.False; }); py.issubclass = new py.PY_def.fromJSON(function issubclass() { var args = py.PY_parseArgs(arguments, ['C', 'B']); - var fn = function () {}; - fn.prototype = args.B; - if (args.C === args.B || args.C instanceof fn) { - return py.True; - } - return py.False; + return py.PY_isSubclass(args.C, args.B) + ? py.True : py.False; }); @@ -1010,6 +1103,7 @@ var py = {}; list: py.list, dict: py.dict, + len: py.len, isinstance: py.isinstance, issubclass: py.issubclass, classmethod: py.classmethod, @@ -1068,9 +1162,7 @@ var py = {}; } return py.True; case 'not': - return py.evaluate(expr.first, context).__nonzero__() === py.True - ? py.False - : py.True; + return py.PY_isTrue(py.evaluate(expr.first, context)) ? py.False : py.True; case 'and': var and_first = py.evaluate(expr.first, context); if (and_first.__nonzero__() === py.True) { @@ -1134,18 +1226,18 @@ var py = {}; if (expr.second.id !== '(name)') { throw new Error('SyntaxError: ' + expr); } - return py.evaluate(expr.first, context) - .__getattribute__(expr.second.value); + return py.PY_getAttr(py.evaluate(expr.first, context), + expr.second.value); // numerical operators case '~': return (py.evaluate(expr.first, context)).__invert__(); case '+': if (!expr.second) { - return (py.evaluate(expr.first, context)).__pos__(); + return py.PY_positive(py.evaluate(expr.first, context)); } case '-': if (!expr.second) { - return (py.evaluate(expr.first, context)).__neg__(); + return py.PY_negative(py.evaluate(expr.first, context)); } case '*': case '/': case '//': case '%': -- cgit v1.2.3 From 7de2a2c965df23a518a3aaf737edecee3538156c Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 26 Nov 2012 08:53:27 +0100 Subject: [FIX] small typo bzr revid: xmo@openerp.com-20121126075327-m3ljltvbhrwm8cbm --- addons/web/static/lib/py.js/lib/py.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'addons/web/static') diff --git a/addons/web/static/lib/py.js/lib/py.js b/addons/web/static/lib/py.js/lib/py.js index 382247c2745..3af06a8eb99 100644 --- a/addons/web/static/lib/py.js/lib/py.js +++ b/addons/web/static/lib/py.js/lib/py.js @@ -758,7 +758,7 @@ var py = {}; if (value === placeholder) { this._value = 0; return; } - if (py.PYisInstance(value, py.float)) { + if (py.PY_isInstance(value, py.float)) { this._value = value._value; } if (py.PY_isInstance(value, py.object) && '__float__' in value) { -- cgit v1.2.3 From aab69ae7a9cb27211392c84bcd97a42fe0917f11 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 26 Nov 2012 09:41:59 +0100 Subject: [TEST] for crazy bzr revid: xmo@openerp.com-20121126084159-lbgfa56vafg4bxc4 --- addons/web/static/test/evals.js | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'addons/web/static') diff --git a/addons/web/static/test/evals.js b/addons/web/static/test/evals.js index e71457a07e6..8e836dade7e 100644 --- a/addons/web/static/test/evals.js +++ b/addons/web/static/test/evals.js @@ -502,6 +502,41 @@ openerp.testing.section('eval.edc.nonliterals', { ]); }); }); + test('horror from the deep', {asserts: 1}, function (instance) { + var cs = [ + {"__ref": "compound_context", + "__contexts": [ + {"__ref": "context", "__debug": "{'k': 'foo,' + str(context.get('test_key', False))}"}, + {"__ref": "compound_context", + "__contexts": [ + {"lang": "en_US", "tz": false, "uid": 1}, + {"lang": "en_US", "tz": false, "uid": 1, + "active_model": "sale.order", "default_type": "out", + "show_address": 1, "contact_display": "partner_address", + "active_ids": [9], "active_id": 9}, + {} + ], "__eval_context": null }, + {"active_id": 8, "active_ids": [8], + "active_model": "stock.picking.out"}, + {"__ref": "context", "__debug": "{'default_ref': 'stock.picking.out,'+str(context.get('active_id', False))}", "__id": "54d6ad1d6c45"} + ], "__eval_context": null} + ]; + return instance.edc([], cs).then(function (result) { + deepEqual(result.context, { + k: 'foo,False', + lang: 'en_US', + tz: false, + uid: 1, + active_model: 'stock.picking.out', + active_id: 8, + active_ids: [8], + default_type: 'out', + show_address: 1, + contact_display: 'partner_address', + default_ref: 'stock.picking.out,8' + }); + }); + }); }); openerp.testing.section('eval.contexts', { dependencies: ['web.coresetup'] -- cgit v1.2.3 From 929a656619578bbf5c91add35f890bfc623e3a25 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 26 Nov 2012 09:42:29 +0100 Subject: [IMP] allow eval'ing a single context or domain bzr revid: xmo@openerp.com-20121126084229-wgpjszmquhibbrpf --- addons/web/static/src/js/pyeval.js | 3 +++ 1 file changed, 3 insertions(+) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 3c6b6619513..4a77eead90f 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -708,8 +708,11 @@ openerp.web.pyeval = function (instance) { context = _.extend(instance.web.pyeval.context(), context || {}); context['context'] = py.dict.fromJSON(context); + //noinspection FallthroughInSwitchStatementJS switch(type) { + case 'context': object = [object]; case 'contexts': return eval_contexts(object, context); + case 'domain': object = [object]; case 'domains': return eval_domains(object, context); case 'groupbys': return eval_groupbys(object, context); } -- cgit v1.2.3 From 720f3faf9386b7509c57459e8e5830bba9269c18 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 26 Nov 2012 10:38:18 +0100 Subject: [IMP] stop using custom /web/searchview endpoints in search view bzr revid: xmo@openerp.com-20121126093818-omxaj3qljolgq8qj --- addons/web/static/src/js/search.js | 47 ++++++++++++++++++-------------------- addons/web/static/test/search.js | 22 +++++++++--------- 2 files changed, 33 insertions(+), 36 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/search.js b/addons/web/static/src/js/search.js index e0a95df37ce..b7514e81c88 100644 --- a/addons/web/static/src/js/search.js +++ b/addons/web/static/src/js/search.js @@ -341,17 +341,19 @@ instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.Sea if (this.headless) { this.ready.resolve(); } else { - var load_view = this.rpc("/web/searchview/load", { + var load_view = this.rpc("/web/view/load", { model: this.model, view_id: this.view_id, - context: this.dataset.get_context() }); - - $.when(load_view) - .then(function(r) { - self.search_view_loaded(r) - }, function () { - self.ready.reject.apply(null, arguments); - }); + view_type: 'search', + context: instance.web.pyeval.eval( + 'context', this.dataset.get_context()) + }); + + $.when(load_view).then(function (r) { + return self.search_view_loaded(r) + }).fail(function () { + self.ready.reject.apply(null, arguments); + }); } instance.web.bus.on('click', this, function(ev) { @@ -615,16 +617,16 @@ instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.Sea search_view_loaded: function(data) { var self = this; - this.fields_view = data.fields_view; - if (data.fields_view.type !== 'search' || - data.fields_view.arch.tag !== 'search') { + this.fields_view = data; + if (data.type !== 'search' || + data.arch.tag !== 'search') { throw new Error(_.str.sprintf( "Got non-search view after asking for a search view: type %s, arch root %s", - data.fields_view.type, data.fields_view.arch.tag)); + data.type, data.arch.tag)); } this.make_widgets( - data.fields_view['arch'].children, - data.fields_view.fields); + data['arch'].children, + data.fields); this.add_common_inputs(); @@ -632,6 +634,7 @@ instance.web.SearchView = instance.web.Widget.extend(/** @lends instance.web.Sea var drawer_started = $.when.apply( null, _(this.select_for_drawer()).invoke( 'appendTo', this.$('.oe_searchview_drawer'))); + // load defaults var defaults_fetched = $.when.apply(null, _(this.inputs).invoke( @@ -1506,16 +1509,10 @@ instance.web.search.CustomFilters = instance.web.search.Input.extend({ this.$el.on('click', 'h4', function () { self.$el.toggleClass('oe_opened'); }); - // FIXME: local eval of domain and context to get rid of special endpoint - return this.rpc('/web/searchview/get_filters', { - model: this.view.model - }) + return this.model.call('get_filters', [this.view.model]) .then(this.proxy('set_filters')) - .then(function () { - self.is_ready.resolve(null); - }, function () { - self.is_ready.reject(); - }); + .done(function () { self.is_ready.resolve(); }) + .fail(function () { self.is_ready.reject.apply(self.is_ready, arguments); }); }, /** * Special implementation delaying defaults until CustomFilters is loaded @@ -1708,7 +1705,7 @@ instance.web.search.Advanced = instance.web.search.Input.extend({ }); return $.when( this._super(), - this.rpc("/web/searchview/fields_get", {model: this.view.model}).done(function(data) { + new instance.web.Model(this.view.model).call('fields_get').done(function(data) { self.fields = _.extend({ id: { string: 'ID', type: 'id' } }, data.fields); diff --git a/addons/web/static/test/search.js b/addons/web/static/test/search.js index 20534eff76a..870ce241d15 100644 --- a/addons/web/static/test/search.js +++ b/addons/web/static/test/search.js @@ -152,9 +152,9 @@ var makeSearchView = function (instance, dummy_widget_attributes, defaults) { instance.dummy = {}; instance.dummy.DummyWidget = instance.web.search.Field.extend( dummy_widget_attributes || {}); - if (!('/web/searchview/load' in instance.session.responses)) { - instance.session.responses['/web/searchview/load'] = function () { - return {fields_view: { + if (!('/web/view/load' in instance.session.responses)) { + instance.session.responses['/web/view/load'] = function () { + return { type: 'search', fields: { dummy: {type: 'char', string: "Dummy"} @@ -171,13 +171,13 @@ var makeSearchView = function (instance, dummy_widget_attributes, defaults) { children: [] }] } - }}; + }; }; } - instance.session.responses['/web/searchview/get_filters'] = function () { + instance.session.responses['ir.filters:get_filters'] = function () { return []; }; - instance.session.responses['/web/searchview/fields_get'] = function () { + instance.session.responses['dummy.model:fields_get'] = function () { return {fields: { dummy: {type: 'char', string: 'Dummy'} }}; @@ -890,9 +890,9 @@ openerp.testing.section('filters', { rpc: 'mock', templates: true, setup: function (instance, $s, mock) { - mock('/web/searchview/load', function () { + mock('/web/view/load', function () { // view with a single group of filters - return {fields_view: { + return { type: 'search', fields: {}, arch: { @@ -915,7 +915,7 @@ openerp.testing.section('filters', { children: [] }] } - }}; + }; }); } }, function (test) { @@ -992,7 +992,7 @@ openerp.testing.section('saved_filters', { }, function (test) { test('checkboxing', {asserts: 6}, function (instance, $fix, mock) { var view = makeSearchView(instance); - mock('/web/searchview/get_filters', function () { + mock('ir.filters:get_filters', function () { return [{ name: "filter name", user_id: 42 }]; }); @@ -1015,7 +1015,7 @@ openerp.testing.section('saved_filters', { }); test('removal', {asserts: 1}, function (instance, $fix, mock) { var view = makeSearchView(instance); - mock('/web/searchview/get_filters', function () { + mock('ir.filters:get_filters', function () { return [{ name: "filter name", user_id: 42 }]; }); -- cgit v1.2.3 From eb9a1c7d55bf4b07b5e516698a3b96a3f9f43d5b Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 26 Nov 2012 11:54:50 +0100 Subject: [REM] EVALPOCALYPSE PART ONE bzr revid: xmo@openerp.com-20121126105450-0f6xowd3dhj4jmbl --- addons/web/static/src/js/views.js | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/views.js b/addons/web/static/src/js/views.js index 4c6b422cfbb..efd5f890544 100644 --- a/addons/web/static/src/js/views.js +++ b/addons/web/static/src/js/views.js @@ -878,7 +878,11 @@ instance.web.ViewManagerAction = instance.web.ViewManager.extend({ nested: true, } }; - this.session.get_file({ url: '/web/report', data: {action: JSON.stringify(action)}, complete: instance.web.unblockUI }); + this.session.get_file({ + url: '/web/report', + data: {action: JSON.stringify(action)}, + complete: instance.web.unblockUI + }); } break; default: @@ -1074,7 +1078,8 @@ instance.web.Sidebar = instance.web.Widget.extend({ }, context); self.rpc("/web/action/load", { action_id: item.action.id, - context: additional_context + context: instance.web.pyeval.eval( + 'context', additional_context) }).done(function(result) { result.context = _.extend(result.context || {}, additional_context); @@ -1126,7 +1131,6 @@ instance.web.Sidebar = instance.web.Widget.extend({ } }, on_attachment_delete: function(e) { - var self = this; e.preventDefault(); e.stopPropagation(); var self = this; @@ -1171,7 +1175,8 @@ instance.web.View = instance.web.Widget.extend({ "view_id": this.view_id, "view_type": this.view_type, toolbar: !!this.options.$sidebar, - context: this.dataset.get_context(context) + context: instance.web.pyeval.eval( + 'context', this.dataset.get_context(context)) }); } return view_loaded.then(function(r) { @@ -1262,7 +1267,11 @@ instance.web.View = instance.web.Widget.extend({ args.push(context); return dataset.call_button(action_data.name, args).done(handler); } else if (action_data.type=="action") { - return this.rpc('/web/action/load', { action_id: action_data.name, context: context, do_not_eval: true}).done(handler); + return this.rpc('/web/action/load', { + action_id: action_data.name, + context: instance.web.pyeval.eval('context', context), + do_not_eval: true + }).done(handler); } else { return dataset.exec_workflow(record_id, action_data.name).done(handler); } -- cgit v1.2.3 From 4a5cb1ebc478cb650a2bf33081f101e4f74bc6fe Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 26 Nov 2012 15:05:25 +0100 Subject: [REM] EVALPOCALYPSE PART 2: no more python-side eval trigger an error if a nonliteral context is pushed to the server (through a new object_hook) bzr revid: xmo@openerp.com-20121126140525-ni2x5m56upss610b --- addons/web/static/src/js/chrome.js | 7 ++++--- addons/web/static/src/js/view_tree.js | 8 +++++--- addons/web/static/src/js/views.js | 14 +++++++++++++- addons/web/static/src/xml/base.xml | 4 ++-- 4 files changed, 24 insertions(+), 9 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/chrome.js b/addons/web/static/src/js/chrome.js index 2cca57f0b56..77d23d8fa53 100644 --- a/addons/web/static/src/js/chrome.js +++ b/addons/web/static/src/js/chrome.js @@ -1191,11 +1191,12 @@ instance.web.WebClient = instance.web.Client.extend({ var self = this; return this.rpc("/web/action/load", { action_id: options.action_id }) .then(function (result) { - var action = result; if (options.needaction) { - action.context.search_default_message_unread = true; + result.context = new instance.web.CompoundContext( + result.context, + {search_default_message_unread: true}); } - return $.when(self.action_manager.do_action(action, { + return $.when(self.action_manager.do_action(result, { clear_breadcrumbs: true, action_menu_id: self.menu.current_menu, })).fail(function() { diff --git a/addons/web/static/src/js/view_tree.js b/addons/web/static/src/js/view_tree.js index 8fd3b25ade5..4d08da385fd 100644 --- a/addons/web/static/src/js/view_tree.js +++ b/addons/web/static/src/js/view_tree.js @@ -44,7 +44,8 @@ instance.web.TreeView = instance.web.View.extend(/** @lends instance.web.TreeVie view_id: this.view_id, view_type: "tree", toolbar: this.view_manager ? !!this.view_manager.sidebar : false, - context: this.dataset.get_context() + context: instance.web.pyeval.eval( + 'context', this.dataset.get_context()) }).done(this.on_loaded); }, /** @@ -227,8 +228,9 @@ instance.web.TreeView = instance.web.View.extend(/** @lends instance.web.TreeVie return this.rpc('/web/treeview/action', { id: id, model: this.dataset.model, - context: new instance.web.CompoundContext( - this.dataset.get_context(), local_context) + context: instance.web.pyeval.eval( + 'context', new instance.web.CompoundContext( + this.dataset.get_context(), local_context)) }).then(function (actions) { if (!actions.length) { return; } var action = actions[0][2]; diff --git a/addons/web/static/src/js/views.js b/addons/web/static/src/js/views.js index efd5f890544..9fad16a58b0 100644 --- a/addons/web/static/src/js/views.js +++ b/addons/web/static/src/js/views.js @@ -265,6 +265,17 @@ instance.web.ActionManager = instance.web.Widget.extend({ return self.do_action(result, options); }); } + + // Ensure context & domain are evaluated and can be manipulated/used + if (action.context) { + action.context = instance.web.pyeval.eval( + 'context', action.context); + } + if (action.domain) { + action.domain = instance.web.pyeval.eval( + 'domain', action.domain); + } + if (!action.type) { console.error("No type for action", action); return $.Deferred().reject(); @@ -1081,7 +1092,8 @@ instance.web.Sidebar = instance.web.Widget.extend({ context: instance.web.pyeval.eval( 'context', additional_context) }).done(function(result) { - result.context = _.extend(result.context || {}, + result.context = new instance.web.CompoundContext( + result.context, additional_context); result.flags = result.flags || {}; result.flags.new_window = true; diff --git a/addons/web/static/src/xml/base.xml b/addons/web/static/src/xml/base.xml index 1b7a5cea53a..723f6707cce 100644 --- a/addons/web/static/src/xml/base.xml +++ b/addons/web/static/src/xml/base.xml @@ -905,11 +905,11 @@
  • Context: - +
  • Domain: - +
  • Modifiers: -- cgit v1.2.3 From f243fd7c46234691ce5ff6416a214676386c4de0 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Mon, 26 Nov 2012 17:13:43 +0100 Subject: [FIX] disable sorting (column-click) in an editable listview being edited To do so, extract sort handling to its own method (bound using the events hash) and override-and-disable in editable. bzr revid: xmo@openerp.com-20121126161343-r5pymdtkiltij9cu --- addons/web/static/src/js/view_list.js | 31 +++++++++++++------------- addons/web/static/src/js/view_list_editable.js | 6 +++++ 2 files changed, 22 insertions(+), 15 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/view_list.js b/addons/web/static/src/js/view_list.js index df74674a343..43d7ac6423e 100644 --- a/addons/web/static/src/js/view_list.js +++ b/addons/web/static/src/js/view_list.js @@ -23,6 +23,9 @@ instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListVi 'action_buttons': true, }, view_type: 'tree', + events: { + 'click thead th.oe_sortable[data-id]': 'sort_by_column' + }, /** * Core class for list-type displays. * @@ -262,21 +265,6 @@ instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListVi 'selected', [selection.ids, selection.records]); }); - // Sorting columns - this.$el.find('thead').delegate('th.oe_sortable[data-id]', 'click', function (e) { - e.stopPropagation(); - var $this = $(this); - self.dataset.sort($this.data('id')); - if($this.hasClass("sortdown") || $this.hasClass("sortup")) { - $this.toggleClass("sortdown").toggleClass("sortup"); - } else { - $this.toggleClass("sortdown"); - } - $this.siblings('.oe_sortable').removeClass("sortup sortdown"); - - self.reload_content(); - }); - // Add button if (!this.$buttons) { this.$buttons = $(QWeb.render("ListView.buttons", {'widget':self})); @@ -358,6 +346,19 @@ instance.web.ListView = instance.web.View.extend( /** @lends instance.web.ListVi } this.trigger('list_view_loaded', data, this.grouped); }, + sort_by_column: function (e) { + e.stopPropagation(); + var $column = $(e.currentTarget); + this.dataset.sort($column.data('id')); + if($column.hasClass("sortdown") || $column.hasClass("sortup")) { + $column.toggleClass("sortup sortdown"); + } else { + $column.addClass("sortdown"); + } + $column.siblings('.oe_sortable').removeClass("sortup sortdown"); + + this.reload_content(); + }, /** * Configures the ListView pager based on the provided dataset's information * diff --git a/addons/web/static/src/js/view_list_editable.js b/addons/web/static/src/js/view_list_editable.js index ec0bf2774fe..281e49c7fa2 100644 --- a/addons/web/static/src/js/view_list_editable.js +++ b/addons/web/static/src/js/view_list_editable.js @@ -63,6 +63,12 @@ openerp.web.list_editable = function (instance) { } this._super(); }, + sort_by_column: function (e) { + e.stopPropagation(); + if (!this.editor.is_editing()) { + this._super.apply(this, arguments); + } + }, /** * Handles the activation of a record in editable mode (making a record * editable), called *after* the record has become editable. -- cgit v1.2.3 From 908c986ce8f96d7ec595005256793f34bb8034da Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Tue, 27 Nov 2012 14:34:35 +0100 Subject: [FIX] onchange for client-side evaluation: use regular method calls bzr revid: xmo@openerp.com-20121127133435-ss3g97sm43mrtbla --- addons/web/static/src/js/view_form.js | 36 +++++++++++++++-------------------- 1 file changed, 15 insertions(+), 21 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/view_form.js b/addons/web/static/src/js/view_form.js index a2768e196c7..5d94cdb5d89 100644 --- a/addons/web/static/src/js/view_form.js +++ b/addons/web/static/src/js/view_form.js @@ -437,26 +437,26 @@ instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerM var method = call[1]; if (!_.str.trim(call[2])) { - return {method: method, args: [], context_index: null} + return {method: method, args: []} } var argument_replacement = { 'False': function () {return false;}, 'True': function () {return true;}, 'None': function () {return null;}, - 'context': function (i) { - context_index = i; - var ctx = new instance.web.CompoundContext(self.dataset.get_context(), widget.build_context() ? widget.build_context() : {}); - return ctx; + 'context': function () { + return new instance.web.CompoundContext( + self.dataset.get_context(), + widget.build_context() ? widget.build_context() : {}); } }; - var parent_fields = null, context_index = null; + var parent_fields = null; var args = _.map(call[2].split(','), function (a, i) { var field = _.str.trim(a); // literal constant or context if (field in argument_replacement) { - return argument_replacement[field](i); + return argument_replacement[field](); } // literal number if (/^-?\d+(\.\d+)?$/.test(field)) { @@ -491,8 +491,7 @@ instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerM return { method: method, - args: args, - context_index: context_index + args: args }; }, do_onchange: function(widget, processed) { @@ -511,18 +510,15 @@ instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerM var on_change = widget.node.attrs.on_change; if (on_change) { var change_spec = self.parse_on_change(on_change, widget); - def = self.rpc('/web/dataset/onchange', { - model: self.dataset.model, - method: change_spec.method, - args: [(self.datarecord.id == null ? [] : [self.datarecord.id])].concat(change_spec.args), - context_id: change_spec.context_index == undefined ? null : change_spec.context_index + 1 - }); + var id = [self.datarecord.id == null ? [] : [self.datarecord.id]]; + def = new instance.web.Model(self.dataset.model).call( + change_spec.method, id.concat(change_spec.args)); } else { def = $.when({}); } return def.then(function(response) { if (widget.field['change_default']) { - var fieldname = widget.name + var fieldname = widget.name; var value_; if (response.value && (fieldname in response.value)) { // Use value from onchange if onchange executed @@ -534,11 +530,9 @@ instance.web.FormView = instance.web.View.extend(instance.web.form.FieldManagerM var condition = fieldname + '=' + value_; if (value_) { - return self.rpc('/web/dataset/call', { - model: 'ir.values', - method: 'get_defaults', - args: [self.model, condition] - }).then(function (results) { + return new instance.web.Model('ir.values').call( + 'get_defaults', [self.model, condition] + ).then(function (results) { if (!results.length) { return response; } -- cgit v1.2.3 From cc4d5a79ecb11a403c2fb777c4190cf8d8396cc2 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Tue, 27 Nov 2012 15:39:17 +0100 Subject: [FIX] group_by using old code bzr revid: xmo@openerp.com-20121127143917-pk4un6zi1v96niyr --- addons/web/static/src/js/data.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/data.js b/addons/web/static/src/js/data.js index 59889628151..e823e6f3057 100644 --- a/addons/web/static/src/js/data.js +++ b/addons/web/static/src/js/data.js @@ -123,9 +123,8 @@ instance.web.Query = instance.web.Class.extend({ var self = this; - // FIXME: when pyeval is merged - var ctx = instance.session.test_eval_contexts( - [this._model.context(this._context)]); + var ctx = instance.web.pyeval.eval( + 'context', this._model.context(this._context)); return this._model.call('read_group', { groupby: grouping, fields: _.uniq(grouping.concat(this._fields || [])), -- cgit v1.2.3 From 6d27327d1417022170c951812adc24146cf449ed Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Tue, 27 Nov 2012 16:40:37 +0100 Subject: [FIX] parsing of long integers, as some openerp domains output them bzr revid: xmo@openerp.com-20121127154037-fiu6vsfdvix3zlmz --- addons/web/static/lib/py.js/lib/py.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'addons/web/static') diff --git a/addons/web/static/lib/py.js/lib/py.js b/addons/web/static/lib/py.js/lib/py.js index 3af06a8eb99..59878b9aee5 100644 --- a/addons/web/static/lib/py.js/lib/py.js +++ b/addons/web/static/lib/py.js/lib/py.js @@ -261,7 +261,7 @@ var py = {}; var Name = '[a-zA-Z_]\\w*'; - var DecNumber = '\\d+'; + var DecNumber = '\\d+(L|l)?'; var IntNumber = DecNumber; var PointFloat = group('\\d+\\.\\d*', '\\.\\d+'); var FloatNumber = PointFloat; -- cgit v1.2.3 From 5aa800ef42154dc9d749922836c9d17e511d99a8 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Tue, 27 Nov 2012 16:41:21 +0100 Subject: [IMP] simplify action handlers: no need to eval_domains_and_contexts as do_action will evaluate them if and when needed bzr revid: xmo@openerp.com-20121127154121-rsr4hxgmwmdrpdt7 --- addons/web/static/src/js/views.js | 25 ++++++++----------------- 1 file changed, 8 insertions(+), 17 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/views.js b/addons/web/static/src/js/views.js index 9fad16a58b0..8b71989cad9 100644 --- a/addons/web/static/src/js/views.js +++ b/addons/web/static/src/js/views.js @@ -1232,8 +1232,7 @@ instance.web.View = instance.web.Widget.extend({ }; var context = new instance.web.CompoundContext(dataset.get_context(), action_data.context || {}); - var handler = function (r) { - var action = r; + var handler = function (action) { if (action && action.constructor == Object) { var ncontext = new instance.web.CompoundContext(context); if (record_id) { @@ -1244,18 +1243,10 @@ instance.web.View = instance.web.Widget.extend({ }); } ncontext.add(action.context || {}); - return instance.web.pyeval.eval_domains_and_contexts({ - contexts: [ncontext], - domains: [] - }).then(function (results) { - action.context = results.context; - /* niv: previously we were overriding once more with action_data.context, - * I assumed this was not a correct behavior and removed it - */ - return self.do_action(action, { - on_close: result_handler, - }); - }, null); + action.context = ncontext; + return self.do_action(action, { + on_close: result_handler, + }); } else { self.do_action({"type":"ir.actions.act_window_close"}); return result_handler(); @@ -1277,15 +1268,15 @@ instance.web.View = instance.web.Widget.extend({ } } args.push(context); - return dataset.call_button(action_data.name, args).done(handler); + return dataset.call_button(action_data.name, args).then(handler); } else if (action_data.type=="action") { return this.rpc('/web/action/load', { action_id: action_data.name, context: instance.web.pyeval.eval('context', context), do_not_eval: true - }).done(handler); + }).then(handler); } else { - return dataset.exec_workflow(record_id, action_data.name).done(handler); + return dataset.exec_workflow(record_id, action_data.name).then(handler); } }, /** -- cgit v1.2.3 From 89d9cd5910cd72009e5eff32214a1568f5acede6 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Wed, 28 Nov 2012 12:05:42 +0100 Subject: [FIX] use py.js 0.7 API bzr revid: xmo@openerp.com-20121128110542-nplg9o3e5jpxmqic --- addons/web/static/src/js/pyeval.js | 49 +++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 25 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/pyeval.js b/addons/web/static/src/js/pyeval.js index 4a77eead90f..265449f9f64 100644 --- a/addons/web/static/src/js/pyeval.js +++ b/addons/web/static/src/js/pyeval.js @@ -288,7 +288,7 @@ openerp.web.pyeval = function (instance) { return py.str.fromJSON(s); }, __eq__: function (other) { - if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + if (!py.PY_isInstance(other, datetime.timedelta)) { return py.False; } return (this.days === other.days @@ -297,7 +297,7 @@ openerp.web.pyeval = function (instance) { ? py.True : py.False; }, __add__: function (other) { - if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + if (!py.PY_isInstance(other, datetime.timedelta)) { return py.NotImplemented; } return py.PY_call(datetime.timedelta, [ @@ -308,7 +308,7 @@ openerp.web.pyeval = function (instance) { }, __radd__: function (other) { return this.__add__(other); }, __sub__: function (other) { - if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + if (!py.PY_isInstance(other, datetime.timedelta)) { return py.NotImplemented; } return py.PY_call(datetime.timedelta, [ @@ -318,7 +318,7 @@ openerp.web.pyeval = function (instance) { ]); }, __rsub__: function (other) { - if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + if (!py.PY_isInstance(other, datetime.timedelta)) { return py.NotImplemented; } return this.__neg__().__add__(other); @@ -332,7 +332,7 @@ openerp.web.pyeval = function (instance) { }, __pos__: function () { return this; }, __mul__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } var n = other.toJSON(); @@ -344,7 +344,7 @@ openerp.web.pyeval = function (instance) { }, __rmul__: function (other) { return this.__mul__(other); }, __div__: function (other) { - if (py.PY_call(py.isinstance, [other, py.float]) !== py.True) { + if (!py.PY_isInstance(other, py.float)) { return py.NotImplemented; } var usec = ((this.days * 24 * 3600) + this.seconds) * 1000000 @@ -410,13 +410,12 @@ openerp.web.pyeval = function (instance) { combine: py.classmethod.fromJSON(function () { var args = py.PY_parseArgs(arguments, 'date time'); return py.PY_call(datetime.datetime, [ - // FIXME: should use getattr - args.date.year, - args.date.month, - args.date.day, - args.time.hour, - args.time.minute, - args.time.second + py.PY_getAttr(args.date, 'year'), + py.PY_getAttr(args.date, 'month'), + py.PY_getAttr(args.date, 'day'), + py.PY_getAttr(args.time, 'hour'), + py.PY_getAttr(args.time, 'minute'), + py.PY_getAttr(args.time, 'second') ]); }) }); @@ -452,7 +451,7 @@ openerp.web.pyeval = function (instance) { ? py.True : py.False; }, __add__: function (other) { - if (py.PY_call(py.isinstance, [other, datetime.timedelta]) !== py.True) { + if (!py.PY_isInstance(other, datetime.timedelta)) { return py.NotImplemented; } var s = tmxxx(this.year, this.month, this.day + other.days); @@ -460,13 +459,15 @@ openerp.web.pyeval = function (instance) { }, __radd__: function (other) { return this.__add__(other); }, __sub__: function (other) { - if (py.PY_call(py.isinstance, [other, datetime.timedelta]) === py.True) { + if (py.PY_isInstance(other, datetime.timedelta)) { return this.__add__(other.__neg__()); } - if (py.PY_call(py.isinstance, [other, datetime.date]) === py.True) { + if (py.PY_isInstance(other, datetime.date)) { // FIXME: getattr and sub API methods return py.PY_call(datetime.timedelta, [ - this.toordinal().__sub__(other.toordinal()) + py.PY_subtract( + py.PY_call(py.PY_getAttr(this, 'toordinal')), + py.PY_call(py.PY_getAttr(other, 'toordinal'))) ]); } return py.NotImplemented; @@ -494,12 +495,10 @@ openerp.web.pyeval = function (instance) { }); var time = py.PY_call(py.object); time.strftime = py.PY_def.fromJSON(function () { - // FIXME: needs PY_getattr - var d = py.PY_call(datetime.__getattribute__('datetime') - .__getattribute__('now')); - var args = [].slice.call(arguments); - return py.PY_call.apply( - null, [d.__getattribute__('strftime')].concat(args)); + var args = py.PY_parseArgs(arguments, 'format'); + var dt_class = py.PY_getAttr(datetime, 'datetime'); + var d = py.PY_call(py.PY_getAttr(dt_class, 'now')); + return py.PY_call(py.PY_getAttr(d, 'strftime'), [args.format]); }); var relativedelta = py.type('relativedelta', null, { @@ -510,7 +509,7 @@ openerp.web.pyeval = function (instance) { + 'weekday leakdays yearday nlyearday'); }, __add__: function (other) { - if (py.PY_call(py.isinstance, [other, datetime.date]) !== py.True) { + if (!py.PY_isInstance(other, datetime.date)) { return py.NotImplemented; } // TODO: test this whole mess @@ -555,7 +554,7 @@ openerp.web.pyeval = function (instance) { }, __sub__: function (other) { - if (py.PY_call(py.isinstance, [other, datetime.date]) !== py.True) { + if (!py.PY_isInstance(other, datetime.date)) { return py.NotImplemented; } // TODO: test this whole mess -- cgit v1.2.3 From fef6ed2f9390de21b54eb77f081f2ebb25a17967 Mon Sep 17 00:00:00 2001 From: Christophe Matthieu Date: Wed, 28 Nov 2012 12:17:41 +0100 Subject: [FIX] When the avatar of 'change my preferences' is mousehover, the scrollbar appears, and after a color bar appears. Set oe_form_field_image_controls on overflow hidden for fixing. bzr revid: chm@openerp.com-20121128111741-pm6fy7z01se90oxd --- addons/web/static/src/css/base.css | 1 + addons/web/static/src/css/base.sass | 1 + 2 files changed, 2 insertions(+) (limited to 'addons/web/static') diff --git a/addons/web/static/src/css/base.css b/addons/web/static/src/css/base.css index ee81492b8ad..6a351fc9971 100644 --- a/addons/web/static/src/css/base.css +++ b/addons/web/static/src/css/base.css @@ -2353,6 +2353,7 @@ display: none; text-align: center; color: #eeeeee; + overflow: hidden; background: rgba(37, 37, 37, 0.9); -moz-border-radius: 3px 3px 0 0; -webkit-border-radius: 3px 3px 0 0; diff --git a/addons/web/static/src/css/base.sass b/addons/web/static/src/css/base.sass index 3923fcaf2ff..18d0c52c66b 100644 --- a/addons/web/static/src/css/base.sass +++ b/addons/web/static/src/css/base.sass @@ -1885,6 +1885,7 @@ $sheet-padding: 16px display: none text-align: center color: #eee + overflow: hidden background: rgba(37,37,37,0.9) @include radius(3px 3px 0 0) @include box-sizing(border) -- cgit v1.2.3 From 48b0d70fc217ce28d1b72e8440e864d8c1cc83c1 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Wed, 28 Nov 2012 16:10:44 +0100 Subject: [FIX] context evaluation in kanban resequencing bzr revid: xmo@openerp.com-20121128151044-i58uwcdem2cgyyrv --- addons/web/static/src/js/data.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/data.js b/addons/web/static/src/js/data.js index e823e6f3057..bbff633c687 100644 --- a/addons/web/static/src/js/data.js +++ b/addons/web/static/src/js/data.js @@ -610,7 +610,8 @@ instance.web.DataSet = instance.web.Class.extend(instance.web.PropertiesMixin, return instance.session.rpc('/web/dataset/resequence', { model: this.model, ids: ids, - context: this.get_context(options.context), + context: instance.web.pyeval.eval( + 'context', this.get_context(options.context)), }).then(function (results) { return results; }); -- cgit v1.2.3 From 628ed49fff4efcb39020d5992eb75f2ca93708ae Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Wed, 28 Nov 2012 16:25:24 +0100 Subject: [FIX] correctly return deferreds from all action type handlers bzr revid: xmo@openerp.com-20121128152524-xrh6zqty0huqb732 --- addons/web/static/src/js/views.js | 34 +++++++++++++++++++++------------- 1 file changed, 21 insertions(+), 13 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/views.js b/addons/web/static/src/js/views.js index 8b71989cad9..0e691ab901e 100644 --- a/addons/web/static/src/js/views.js +++ b/addons/web/static/src/js/views.js @@ -394,6 +394,7 @@ instance.web.ActionManager = instance.web.Widget.extend({ options.on_close(); } this.dialog_stop(); + return $.when(); }, ir_actions_server: function (action, options) { var self = this; @@ -407,29 +408,36 @@ instance.web.ActionManager = instance.web.Widget.extend({ ir_actions_report_xml: function(action, options) { var self = this; instance.web.blockUI(); - instance.web.pyeval.eval_domains_and_contexts({ + return instance.web.pyeval.eval_domains_and_contexts({ contexts: [action.context], domains: [] - }).done(function(res) { + }).then(function(res) { action = _.clone(action); action.context = res.context; var c = instance.webclient.crashmanager; - self.session.get_file({ - url: '/web/report', - data: {action: JSON.stringify(action)}, - complete: instance.web.unblockUI, - success: function(){ - if (!self.dialog) { - options.on_close(); + return $.Deferred(function (d) { + self.session.get_file({ + url: '/web/report', + data: {action: JSON.stringify(action)}, + complete: instance.web.unblockUI, + success: function(){ + if (!self.dialog) { + options.on_close(); + } + self.dialog_stop(); + d.resolve(); + }, + error: function () { + c.rpc_error.apply(c, arguments); + d.reject(); } - self.dialog_stop(); - }, - error: c.rpc_error.bind(c) - }) + }) + }); }); }, ir_actions_act_url: function (action) { window.open(action.url, action.target === 'self' ? '_self' : '_blank'); + return $.when(); }, }); -- cgit v1.2.3 From 83d5c4f94c4da42bdac00c798f4581c9b194adf7 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Wed, 28 Nov 2012 16:54:48 +0100 Subject: [IMP] update py.js to correctly tokenize unicode literals also various style improvements in the lib bzr revid: xmo@openerp.com-20121128155448-1tv62wyv3zy2asr5 --- addons/web/static/lib/py.js/.hg_archival.txt | 4 +-- addons/web/static/lib/py.js/lib/py.js | 41 ++++++++++++++++------------ 2 files changed, 26 insertions(+), 19 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/lib/py.js/.hg_archival.txt b/addons/web/static/lib/py.js/.hg_archival.txt index 3da757d145d..33dcdd88830 100644 --- a/addons/web/static/lib/py.js/.hg_archival.txt +++ b/addons/web/static/lib/py.js/.hg_archival.txt @@ -1,5 +1,5 @@ repo: 076b192d0d8ab2b92d1dbcfa3da055382f30eaea -node: 7c9ac450ae180524cfdf69e0e03439caef4a43ac +node: ccf62e5d0291f66a39f4049f3e880004e59c3654 branch: default latesttag: 0.7 -latesttagdistance: 1 +latesttagdistance: 4 diff --git a/addons/web/static/lib/py.js/lib/py.js b/addons/web/static/lib/py.js/lib/py.js index 59878b9aee5..854232a0d80 100644 --- a/addons/web/static/lib/py.js/lib/py.js +++ b/addons/web/static/lib/py.js/lib/py.js @@ -148,14 +148,14 @@ var py = {}; comparator('>'); comparator('>='); comparator('<>'); comparator('!='); comparator('=='); - infix('|', 70); infix('^', 80), infix('&', 90); + infix('|', 70); infix('^', 80); infix('&', 90); infix('<<', 100); infix('>>', 100); infix('+', 110); infix('-', 110); infix('*', 120); infix('/', 120); - infix('//', 120), infix('%', 120); + infix('//', 120); infix('%', 120); prefix('-', 130); prefix('+', 130); prefix('~', 130); @@ -273,12 +273,16 @@ var py = {}; var Special = '[:;.,`@]'; var Funny = group(Operator, Bracket, Special); - var ContStr = group("'[^']*'", '"[^"]*"'); + var ContStr = group("[uU]?'([^']*)'", '[uU]?"([^"]*)"'); var PseudoToken = Whitespace + group(Number, Funny, ContStr, Name); + var number_pattern = new RegExp('^' + Number + '$'); + var string_pattern = new RegExp('^' + ContStr + '$'); + var name_pattern = new RegExp('^' + Name + '$'); + var strip = new RegExp('^' + Whitespace); return function tokenize(s) { - var max=s.length, tokens = []; + var max=s.length, tokens = [], start, end = undefined; // /g flag makes repeated exec() have memory var pseudoprog = new RegExp(PseudoToken, 'g'); @@ -294,18 +298,20 @@ var py = {}; + '; parsed so far: ' + tokens); } - var start = pseudomatch.index, end = pseudoprog.lastIndex; + start = pseudomatch.index; + end = pseudoprog.lastIndex; // strip leading space caught by Whitespace - var token = s.slice(start, end).replace(new RegExp('^' + Whitespace), ''); + var token = s.slice(start, end).replace(strip, ''); var initial = token[0]; - if (/\d/.test(initial) || (initial === '.' && token !== '.')) { + if (number_pattern.test(token)) { tokens.push(create(symbols['(number)'], { value: parseFloat(token) })); - } else if (/'|"/.test(initial)) { + } else if (string_pattern.test(token)) { + var m = string_pattern.exec(token); tokens.push(create(symbols['(string)'], { - value: token.slice(1, -1) + value: m[2] || m[3] })); } else if (token in symbols) { var symbol; @@ -320,7 +326,7 @@ var py = {}; symbol = symbols[token]; } tokens.push(create(symbol)); - } else if (/[_a-zA-Z]/.test(initial)) { + } else if (name_pattern.test(token)) { tokens.push(create(symbols['(name)'], { value: token })); @@ -369,7 +375,7 @@ var py = {}; return py.False; } - var fn = function () {} + var fn = function () {}; fn.prototype = py.object; if (py.PY_isInstance(val, py.object) || py.PY_isSubclass(val, py.object)) { @@ -413,6 +419,7 @@ var py = {}; var args = argument[0]; var kwargs = {}; for (var k in argument[1]) { + if (!argument[1].hasOwnProperty(k)) { continue; } kwargs[k] = argument[1][k]; } if (typeof format === 'string') { @@ -428,9 +435,10 @@ var py = {}; "TypeError: unknown format specification " + JSON.stringify(spec)); }; + var spec; // TODO: ensure all format arg names are actual names? for(var i=0; i Date: Wed, 28 Nov 2012 17:13:11 +0100 Subject: [FIX] sidebar activation: put original context before action context in eval sequence bzr revid: xmo@openerp.com-20121128161311-u3e3oqhutt043mzq --- addons/web/static/src/js/views.js | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/views.js b/addons/web/static/src/js/views.js index 0e691ab901e..7a854150129 100644 --- a/addons/web/static/src/js/views.js +++ b/addons/web/static/src/js/views.js @@ -1090,19 +1090,18 @@ instance.web.Sidebar = instance.web.Widget.extend({ instance.web.dialog($("
    ").text(_t("You must choose at least one record.")), { title: _t("Warning"), modal: true }); return false; } - var additional_context = _.extend({ - active_id: ids[0], - active_ids: ids, - active_model: self.getParent().dataset.model - }, context); + var c = instance.web.pyeval.eval('context', + new instance.web.CompoundContext({ + active_id: ids[0], + active_ids: ids, + active_model: self.getParent().dataset.model + }, context)); self.rpc("/web/action/load", { action_id: item.action.id, - context: instance.web.pyeval.eval( - 'context', additional_context) + context: c }).done(function(result) { result.context = new instance.web.CompoundContext( - result.context, - additional_context); + c, result.context); result.flags = result.flags || {}; result.flags.new_window = true; self.do_action(result, { -- cgit v1.2.3 From 66e13eb9bf9c2d1b44abd22555dcd0374a8521b8 Mon Sep 17 00:00:00 2001 From: Christophe Matthieu Date: Thu, 29 Nov 2012 09:33:14 +0100 Subject: [IMP] web avatar preference: change overflow hidden into padding: 4px 0 bzr revid: chm@openerp.com-20121129083314-gbhblm0vi4nw08sb --- addons/web/static/src/css/base.css | 3 +-- addons/web/static/src/css/base.sass | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/css/base.css b/addons/web/static/src/css/base.css index 6a351fc9971..24a035a3050 100644 --- a/addons/web/static/src/css/base.css +++ b/addons/web/static/src/css/base.css @@ -2348,12 +2348,11 @@ .openerp .oe_form .oe_form_field_image .oe_form_field_image_controls { position: absolute; top: 1px; - padding: 4px; + padding: 4px 0; width: 100%; display: none; text-align: center; color: #eeeeee; - overflow: hidden; background: rgba(37, 37, 37, 0.9); -moz-border-radius: 3px 3px 0 0; -webkit-border-radius: 3px 3px 0 0; diff --git a/addons/web/static/src/css/base.sass b/addons/web/static/src/css/base.sass index 18d0c52c66b..6d167709692 100644 --- a/addons/web/static/src/css/base.sass +++ b/addons/web/static/src/css/base.sass @@ -1880,12 +1880,11 @@ $sheet-padding: 16px .oe_form_field_image_controls position: absolute top: 1px - padding: 4px + padding: 4px 0 width: 100% display: none text-align: center color: #eee - overflow: hidden background: rgba(37,37,37,0.9) @include radius(3px 3px 0 0) @include box-sizing(border) -- cgit v1.2.3 From bf29cecca3d412add5d764137835a5028de44c95 Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Thu, 29 Nov 2012 11:11:37 +0100 Subject: [FIX] if an action descriptor is precisely ``false``, treat it as an ir_action_close ~/projects/tiny/web/current Can be seen in e.g. Quotations > [More sidebar] > Sale: Mark Unread: it's a server action which just returns ``False``, the handler resulted in a noop but also produced an error message in the browser console ("No type for action false"). Convert ``false`` (identity-tested) into an ir_action_close in do_action, before actually mucking into the action descriptor. bzr revid: xmo@openerp.com-20121129101137-g01nd49hnlg2odfs --- addons/web/static/src/js/views.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/views.js b/addons/web/static/src/js/views.js index def265db0bb..7b58818bec0 100644 --- a/addons/web/static/src/js/views.js +++ b/addons/web/static/src/js/views.js @@ -256,7 +256,9 @@ instance.web.ActionManager = instance.web.Widget.extend({ on_close: function() {}, action_menu_id: null, }); - if (_.isString(action) && instance.web.client_actions.contains(action)) { + if (action === false) { + action = { type: 'ir.actions.act_window_close' }; + } else if (_.isString(action) && instance.web.client_actions.contains(action)) { var action_client = { type: "ir.actions.client", tag: action, params: {} }; return this.do_action(action_client, options); } else if (_.isNumber(action) || _.isString(action)) { -- cgit v1.2.3 From c7772fdd82105ddf60cbec2517753bf927ce19ed Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Thu, 29 Nov 2012 11:38:41 +0100 Subject: [FIX] server-sourced fields_get has no indirection to the model's fields previous searchview-controller wrapper method did. Remove leftover indirection deref bzr revid: xmo@openerp.com-20121129103841-6qcl4sctekqmrt2q --- addons/web/static/src/js/search.js | 2 +- addons/web/static/test/search.js | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) (limited to 'addons/web/static') diff --git a/addons/web/static/src/js/search.js b/addons/web/static/src/js/search.js index 29fa71b5a97..5b59c7d6912 100644 --- a/addons/web/static/src/js/search.js +++ b/addons/web/static/src/js/search.js @@ -1708,7 +1708,7 @@ instance.web.search.Advanced = instance.web.search.Input.extend({ new instance.web.Model(this.view.model).call('fields_get').done(function(data) { self.fields = _.extend({ id: { string: 'ID', type: 'id' } - }, data.fields); + }, data); })).done(function () { self.append_proposition(); }); diff --git a/addons/web/static/test/search.js b/addons/web/static/test/search.js index 870ce241d15..45f6d2c715b 100644 --- a/addons/web/static/test/search.js +++ b/addons/web/static/test/search.js @@ -178,9 +178,9 @@ var makeSearchView = function (instance, dummy_widget_attributes, defaults) { return []; }; instance.session.responses['dummy.model:fields_get'] = function () { - return {fields: { + return { dummy: {type: 'char', string: 'Dummy'} - }}; + }; }; var dataset = {model: 'dummy.model', get_context: function () { return {}; }}; -- cgit v1.2.3