diff --git a/addons/web/common/http.py b/addons/web/common/http.py index 6b1a28e5803..9c3664c8da0 100644 --- a/addons/web/common/http.py +++ b/addons/web/common/http.py @@ -330,16 +330,32 @@ def httprequest(f): return http_handler #---------------------------------------------------------- -# OpenERP Web werkzeug Session Managment wraped using with +# OpenERP Web Controller registration with a metaclass +#---------------------------------------------------------- +addons_module = {} +addons_manifest = {} +controllers_class = [] +controllers_object = {} +controllers_path = {} + +class ControllerType(type): + def __init__(cls, name, bases, attrs): + super(ControllerType, cls).__init__(name, bases, attrs) + controllers_class.append(("%s.%s" % (cls.__module__, cls.__name__), cls)) + +class Controller(object): + __metaclass__ = ControllerType + +#---------------------------------------------------------- +# OpenERP Web Session context manager #---------------------------------------------------------- STORES = {} @contextlib.contextmanager -def session_context(request, storage_path, session_cookie='sessionid'): +def session_context(request, storage_path, session_cookie='httpsessionid'): session_store, session_lock = STORES.get(storage_path, (None, None)) if not session_store: - session_store = werkzeug.contrib.sessions.FilesystemSessionStore( - storage_path) + session_store = werkzeug.contrib.sessions.FilesystemSessionStore( storage_path) session_lock = threading.Lock() STORES[storage_path] = session_store, session_lock @@ -382,7 +398,7 @@ def session_context(request, storage_path, session_cookie='sessionid'): # note that domains_store and contexts_store are append-only (we # only ever add items to them), so we can just update one with the # other to get the right result, if we want to merge the - # ``context`` dict we'll need something smarter + # ``context`` dict we'll need something smarter in_store = session_store.get(sid) for k, v in request.session.iteritems(): stored = in_store.get(k) @@ -402,22 +418,8 @@ def session_context(request, storage_path, session_cookie='sessionid'): session_store.save(request.session) #---------------------------------------------------------- -# OpenERP Web Module/Controller Loading and URL Routing +# OpenERP Web WSGI Application #---------------------------------------------------------- -addons_module = {} -addons_manifest = {} -controllers_class = [] -controllers_object = {} -controllers_path = {} - -class ControllerType(type): - def __init__(cls, name, bases, attrs): - super(ControllerType, cls).__init__(name, bases, attrs) - controllers_class.append(("%s.%s" % (cls.__module__, cls.__name__), cls)) - -class Controller(object): - __metaclass__ = ControllerType - class DisableCacheMiddleware(object): def __init__(self, app): self.app = app @@ -426,13 +428,18 @@ class DisableCacheMiddleware(object): referer = environ.get('HTTP_REFERER', '') parsed = urlparse.urlparse(referer) debug = parsed.query.count('debug') >= 1 - nh = dict(headers) - if 'Last-Modified' in nh: del nh['Last-Modified'] + + new_headers = [] + unwanted_keys = ['Last-Modified'] if debug: - if 'Expires' in nh: del nh['Expires'] - if 'Etag' in nh: del nh['Etag'] - nh['Cache-Control'] = 'no-cache' - start_response(status, nh.items()) + new_headers = [('Cache-Control', 'no-cache')] + unwanted_keys += ['Expires', 'Etag', 'Cache-Control'] + + for k, v in headers: + if k not in unwanted_keys: + new_headers.append((k, v)) + + start_response(status, new_headers) return self.app(environ, start_wrapped) class Root(object): @@ -459,12 +466,12 @@ class Root(object): if not hasattr(self.config, 'connector'): if self.config.backend == 'local': - self.config.connector = LocalConnector() + self.config.connector = session.LocalConnector() else: self.config.connector = openerplib.get_connector( hostname=self.config.server_host, port=self.config.server_port) - self.session_cookie = 'sessionid' + self.httpsession_cookie = 'httpsessionid' self.addons = {} static_dirs = self._load_addons(openerp_addons_namespace) @@ -499,7 +506,7 @@ class Root(object): if not handler: response = werkzeug.exceptions.NotFound() else: - with session_context(request, self.session_storage, self.session_cookie) as session: + with session_context(request, self.session_storage, self.httpsession_cookie) as session: result = handler( request, self.config) if isinstance(result, basestring): @@ -509,7 +516,7 @@ class Root(object): response = result if hasattr(response, 'set_cookie'): - response.set_cookie(self.session_cookie, session.sid) + response.set_cookie(self.httpsession_cookie, session.sid) return response(environ, start_response) @@ -558,61 +565,13 @@ class Root(object): while ps: c = controllers_path.get(ps) if c: - m = getattr(c, meth) - if getattr(m, 'exposed', False): + m = getattr(c, meth, None) + if m and getattr(m, 'exposed', False): _logger.debug("Dispatching to %s %s %s", ps, c, meth) return m ps, _slash, meth = ps.rpartition('/') + if not ps and meth: + ps = '/' return None -class LibException(Exception): - """ Base of all client lib exceptions """ - def __init__(self,code=None,message=None): - self.code = code - self.message = message - -class ApplicationError(LibException): - """ maps to code: 1, server side: Exception or openerp.exceptions.DeferredException""" - -class Warning(LibException): - """ maps to code: 2, server side: openerp.exceptions.Warning""" - -class AccessError(LibException): - """ maps to code: 3, server side: openerp.exceptions.AccessError""" - -class AccessDenied(LibException): - """ maps to code: 4, server side: openerp.exceptions.AccessDenied""" - - -class LocalConnector(openerplib.Connector): - """ - A type of connector that uses the XMLRPC protocol. - """ - PROTOCOL = 'local' - - def __init__(self): - pass - - def send(self, service_name, method, *args): - import openerp - import traceback - import xmlrpclib - code_string = "warning -- %s\n\n%s" - try: - return openerp.netsvc.dispatch_rpc(service_name, method, args) - except openerp.osv.osv.except_osv, e: - # TODO change the except to raise LibException instead of their emulated xmlrpc fault - raise xmlrpclib.Fault(code_string % (e.name, e.value), '') - except openerp.exceptions.Warning, e: - raise xmlrpclib.Fault(code_string % ("Warning", e), '') - except openerp.exceptions.AccessError, e: - raise xmlrpclib.Fault(code_string % ("AccessError", e), '') - except openerp.exceptions.AccessDenied, e: - raise xmlrpclib.Fault('AccessDenied', str(e)) - except openerp.exceptions.DeferredException, e: - formatted_info = "".join(traceback.format_exception(*e.traceback)) - raise xmlrpclib.Fault(openerp.tools.ustr(e.message), formatted_info) - except Exception, e: - formatted_info = "".join(traceback.format_exception(*(sys.exc_info()))) - raise xmlrpclib.Fault(openerp.tools.exception_to_unicode(e), formatted_info) - +# vim:et:ts=4:sw=4: diff --git a/addons/web/common/session.py b/addons/web/common/session.py index ab486f08e90..5906ee6314e 100644 --- a/addons/web/common/session.py +++ b/addons/web/common/session.py @@ -4,11 +4,67 @@ import babel import dateutil.relativedelta import logging import time +import sys + import openerplib from . import nonliterals _logger = logging.getLogger(__name__) + +#---------------------------------------------------------- +# openerplib local connector +#---------------------------------------------------------- +class LibException(Exception): + """ Base of all client lib exceptions """ + def __init__(self,code=None,message=None): + self.code = code + self.message = message + +class ApplicationError(LibException): + """ maps to code: 1, server side: Exception or openerp.exceptions.DeferredException""" + +class Warning(LibException): + """ maps to code: 2, server side: openerp.exceptions.Warning""" + +class AccessError(LibException): + """ maps to code: 3, server side: openerp.exceptions.AccessError""" + +class AccessDenied(LibException): + """ maps to code: 4, server side: openerp.exceptions.AccessDenied""" + +class LocalConnector(openerplib.Connector): + """ + A type of connector that uses the XMLRPC protocol. + """ + PROTOCOL = 'local' + + def __init__(self): + pass + + def send(self, service_name, method, *args): + import openerp + import traceback + import xmlrpclib + code_string = "warning -- %s\n\n%s" + try: + return openerp.netsvc.dispatch_rpc(service_name, method, args) + except openerp.osv.osv.except_osv, e: + # TODO change the except to raise LibException instead of their emulated xmlrpc fault + raise xmlrpclib.Fault(code_string % (e.name, e.value), '') + except openerp.exceptions.Warning, e: + raise xmlrpclib.Fault(code_string % ("Warning", e), '') + except openerp.exceptions.AccessError, e: + raise xmlrpclib.Fault(code_string % ("AccessError", e), '') + except openerp.exceptions.AccessDenied, e: + raise xmlrpclib.Fault('AccessDenied', str(e)) + except openerp.exceptions.DeferredException, e: + formatted_info = "".join(traceback.format_exception(*e.traceback)) + raise xmlrpclib.Fault(openerp.tools.ustr(e.message), formatted_info) + except Exception, e: + formatted_info = "".join(traceback.format_exception(*(sys.exc_info()))) + raise xmlrpclib.Fault(openerp.tools.exception_to_unicode(e), formatted_info) + #---------------------------------------------------------- # OpenERPSession RPC openerp backend access #---------------------------------------------------------- @@ -68,7 +124,7 @@ class OpenERPSession(object): self._login = login self._password = password - def authenticate(self, db, login, password, env): + def authenticate(self, db, login, password, env=None): # TODO use the openerplib API once it exposes authenticate() uid = self.proxy('common').authenticate(db, login, password, env) self.bind(db, uid, login, password) @@ -216,3 +272,5 @@ class OpenERPSession(object): cdomain = nonliterals.CompoundDomain(domain) cdomain.session = self return cdomain.evaluate(context or {}) + +# vim:et:ts=4:sw=4: diff --git a/addons/web/controllers/main.py b/addons/web/controllers/main.py index 7e79fd9d2ea..c3bf6aff750 100644 --- a/addons/web/controllers/main.py +++ b/addons/web/controllers/main.py @@ -31,87 +31,9 @@ from .. import common openerpweb = common.http #---------------------------------------------------------- -# OpenERP Web web Controllers +# OpenERP Web helpers #---------------------------------------------------------- - -def concat_xml(file_list): - """Concatenate xml files - - :param list(str) file_list: list of files to check - :returns: (concatenation_result, checksum) - :rtype: (str, str) - """ - checksum = hashlib.new('sha1') - if not file_list: - return '', checksum.hexdigest() - - root = None - for fname in file_list: - with open(fname, 'rb') as fp: - contents = fp.read() - checksum.update(contents) - fp.seek(0) - xml = ElementTree.parse(fp).getroot() - - if root is None: - root = ElementTree.Element(xml.tag) - #elif root.tag != xml.tag: - # raise ValueError("Root tags missmatch: %r != %r" % (root.tag, xml.tag)) - - for child in xml.getchildren(): - root.append(child) - return ElementTree.tostring(root, 'utf-8'), checksum.hexdigest() - - -def concat_files(file_list, reader=None, intersperse=""): - """ Concatenates contents of all provided files - - :param list(str) file_list: list of files to check - :param function reader: reading procedure for each file - :param str intersperse: string to intersperse between file contents - :returns: (concatenation_result, checksum) - :rtype: (str, str) - """ - checksum = hashlib.new('sha1') - if not file_list: - return '', checksum.hexdigest() - - if reader is None: - def reader(f): - with open(f, 'rb') as fp: - return fp.read() - - files_content = [] - for fname in file_list: - contents = reader(fname) - checksum.update(contents) - files_content.append(contents) - - files_concat = intersperse.join(files_content) - return files_concat, checksum.hexdigest() - -html_template = """ - - - - - OpenERP - - - %(css)s - %(js)s - - - - -""" - def sass2scss(src): # Validated by diff -u of sass2scss against: # sass-convert -F sass -T scss openerp.sass openerp.scss @@ -163,13 +85,180 @@ def sass2scss(src): return out return write(sass) -def server_wide_modules(req): - addons = [i for i in req.config.server_wide_modules if i in openerpweb.addons_manifest] +def db_list(req): + dbs = [] + proxy = req.session.proxy("db") + dbs = proxy.list() + h = req.httprequest.environ['HTTP_HOST'].split(':')[0] + d = h.split('.')[0] + r = req.config.dbfilter.replace('%h', h).replace('%d', d) + dbs = [i for i in dbs if re.match(r, i)] + return dbs + +def module_topological_sort(modules): + """ Return a list of module names sorted so that their dependencies of the + modules are listed before the module itself + + modules is a dict of {module_name: dependencies} + + :param modules: modules to sort + :type modules: dict + :returns: list(str) + """ + + dependencies = set(itertools.chain.from_iterable(modules.itervalues())) + # incoming edge: dependency on other module (if a depends on b, a has an + # incoming edge from b, aka there's an edge from b to a) + # outgoing edge: other module depending on this one + + # [Tarjan 1976], http://en.wikipedia.org/wiki/Topological_sorting#Algorithms + #L ← Empty list that will contain the sorted nodes + L = [] + #S ← Set of all nodes with no outgoing edges (modules on which no other + # module depends) + S = set(module for module in modules if module not in dependencies) + + visited = set() + #function visit(node n) + def visit(n): + #if n has not been visited yet then + if n not in visited: + #mark n as visited + visited.add(n) + #change: n not web module, can not be resolved, ignore + if n not in modules: return + #for each node m with an edge from m to n do (dependencies of n) + for m in modules[n]: + #visit(m) + visit(m) + #add n to L + L.append(n) + #for each node n in S do + for n in S: + #visit(n) + visit(n) + return L + +def module_installed(req): + # Candidates module the current heuristic is the /static dir + loadable = openerpweb.addons_manifest.keys() + modules = {} + + # Retrieve database installed modules + # TODO The following code should move to ir.module.module.list_installed_modules() + Modules = req.session.model('ir.module.module') + domain = [('state','=','installed'), ('name','in', loadable)] + for module in Modules.search_read(domain, ['name', 'dependencies_id']): + modules[module['name']] = [] + deps = module.get('dependencies_id') + if deps: + deps_read = req.session.model('ir.module.module.dependency').read(deps, ['name']) + dependencies = [i['name'] for i in deps_read] + modules[module['name']] = dependencies + + sorted_modules = module_topological_sort(modules) + return sorted_modules + +def module_installed_bypass_session(dbname): + loadable = openerpweb.addons_manifest.keys() + modules = {} + try: + import openerp.modules.registry + registry = openerp.modules.registry.RegistryManager.get(dbname) + with registry.cursor() as cr: + m = registry.get('ir.module.module') + # TODO The following code should move to ir.module.module.list_installed_modules() + domain = [('state','=','installed'), ('name','in', loadable)] + ids = m.search(cr, 1, [('state','=','installed'), ('name','in', loadable)]) + for module in m.read(cr, 1, ids, ['name', 'dependencies_id']): + modules[module['name']] = [] + deps = module.get('dependencies_id') + if deps: + deps_read = registry.get('ir.module.module.dependency').read(cr, 1, deps, ['name']) + dependencies = [i['name'] for i in deps_read] + modules[module['name']] = dependencies + except Exception,e: + pass + sorted_modules = module_topological_sort(modules) + return sorted_modules + +def module_boot(req): + serverside = [] + dbside = [] + for i in req.config.server_wide_modules: + if i in openerpweb.addons_manifest: + serverside.append(i) + # if only one db load every module at boot + dbs = [] + try: + dbs = db_list(req) + except xmlrpclib.Fault: + # ignore access denied + pass + if len(dbs) == 1: + dbside = module_installed_bypass_session(dbs[0]) + dbside = [i for i in dbside if i not in serverside] + addons = serverside + dbside return addons +def concat_xml(file_list): + """Concatenate xml files + + :param list(str) file_list: list of files to check + :returns: (concatenation_result, checksum) + :rtype: (str, str) + """ + checksum = hashlib.new('sha1') + if not file_list: + return '', checksum.hexdigest() + + root = None + for fname in file_list: + with open(fname, 'rb') as fp: + contents = fp.read() + checksum.update(contents) + fp.seek(0) + xml = ElementTree.parse(fp).getroot() + + if root is None: + root = ElementTree.Element(xml.tag) + #elif root.tag != xml.tag: + # raise ValueError("Root tags missmatch: %r != %r" % (root.tag, xml.tag)) + + for child in xml.getchildren(): + root.append(child) + return ElementTree.tostring(root, 'utf-8'), checksum.hexdigest() + +def concat_files(file_list, reader=None, intersperse=""): + """ Concatenates contents of all provided files + + :param list(str) file_list: list of files to check + :param function reader: reading procedure for each file + :param str intersperse: string to intersperse between file contents + :returns: (concatenation_result, checksum) + :rtype: (str, str) + """ + checksum = hashlib.new('sha1') + if not file_list: + return '', checksum.hexdigest() + + if reader is None: + def reader(f): + with open(f, 'rb') as fp: + return fp.read() + + files_content = [] + for fname in file_list: + contents = reader(fname) + checksum.update(contents) + files_content.append(contents) + + files_concat = intersperse.join(files_content) + return files_concat, checksum.hexdigest() + def manifest_glob(req, addons, key): if addons is None: - addons = server_wide_modules(req) + addons = module_boot(req) else: addons = addons.split(',') r = [] @@ -237,6 +326,189 @@ def make_conditional(req, response, last_modified=None, etag=None): response.set_etag(etag) return response.make_conditional(req.httprequest) +def login_and_redirect(req, db, login, key, redirect_url='/'): + req.session.authenticate(db, login, key, {}) + return set_cookie_and_redirect(req, redirect_url) + +def set_cookie_and_redirect(req, redirect_url): + redirect = werkzeug.utils.redirect(redirect_url, 303) + redirect.autocorrect_location_header = False + cookie_val = urllib2.quote(simplejson.dumps(req.session_id)) + redirect.set_cookie('instance0|session_id', cookie_val) + return redirect + +def eval_context_and_domain(session, context, domain=None): + e_context = session.eval_context(context) + # should we give the evaluated context as an evaluation context to the domain? + e_domain = session.eval_domain(domain or []) + + return e_context, e_domain + +def load_actions_from_ir_values(req, key, key2, models, meta): + context = req.session.eval_context(req.context) + Values = req.session.model('ir.values') + actions = Values.get(key, key2, models, meta, context) + + return [(id, name, clean_action(req, action)) + for id, name, action in actions] + +def clean_action(req, action, do_not_eval=False): + action.setdefault('flags', {}) + + context = req.session.eval_context(req.context) + eval_ctx = req.session.evaluation_context(context) + + if not do_not_eval: + # values come from the server, we can just eval them + if action.get('context') and isinstance(action.get('context'), basestring): + action['context'] = eval( action['context'], eval_ctx ) or {} + + if action.get('domain') and isinstance(action.get('domain'), basestring): + action['domain'] = eval( action['domain'], eval_ctx ) or [] + else: + if 'context' in action: + action['context'] = parse_context(action['context'], req.session) + if 'domain' in action: + action['domain'] = parse_domain(action['domain'], req.session) + + action_type = action.setdefault('type', 'ir.actions.act_window_close') + if action_type == 'ir.actions.act_window': + return fix_view_modes(action) + return action + +# I think generate_views,fix_view_modes should go into js ActionManager +def generate_views(action): + """ + While the server generates a sequence called "views" computing dependencies + between a bunch of stuff for views coming directly from the database + (the ``ir.actions.act_window model``), it's also possible for e.g. buttons + to return custom view dictionaries generated on the fly. + + In that case, there is no ``views`` key available on the action. + + Since the web client relies on ``action['views']``, generate it here from + ``view_mode`` and ``view_id``. + + Currently handles two different cases: + + * no view_id, multiple view_mode + * single view_id, single view_mode + + :param dict action: action descriptor dictionary to generate a views key for + """ + view_id = action.get('view_id') or False + if isinstance(view_id, (list, tuple)): + view_id = view_id[0] + + # providing at least one view mode is a requirement, not an option + view_modes = action['view_mode'].split(',') + + if len(view_modes) > 1: + if view_id: + raise ValueError('Non-db action dictionaries should provide ' + 'either multiple view modes or a single view ' + 'mode and an optional view id.\n\n Got view ' + 'modes %r and view id %r for action %r' % ( + view_modes, view_id, action)) + action['views'] = [(False, mode) for mode in view_modes] + return + action['views'] = [(view_id, view_modes[0])] + +def fix_view_modes(action): + """ For historical reasons, OpenERP has weird dealings in relation to + view_mode and the view_type attribute (on window actions): + + * one of the view modes is ``tree``, which stands for both list views + and tree views + * the choice is made by checking ``view_type``, which is either + ``form`` for a list view or ``tree`` for an actual tree view + + This methods simply folds the view_type into view_mode by adding a + new view mode ``list`` which is the result of the ``tree`` view_mode + in conjunction with the ``form`` view_type. + + TODO: this should go into the doc, some kind of "peculiarities" section + + :param dict action: an action descriptor + :returns: nothing, the action is modified in place + """ + if not action.get('views'): + generate_views(action) + + id_form = None + for index, (id, mode) in enumerate(action['views']): + if mode == 'form': + id_form = id + break + + if action.pop('view_type', 'form') != 'form': + return action + + action['views'] = [ + [id, mode if mode != 'tree' else 'list'] + for id, mode in action['views'] + ] + + return action + +def parse_domain(domain, session): + """ Parses an arbitrary string containing a domain, transforms it + to either a literal domain or a :class:`common.nonliterals.Domain` + + :param domain: the domain to parse, if the domain is not a string it + is assumed to be a literal domain and is returned as-is + :param session: Current OpenERP session + :type session: openerpweb.openerpweb.OpenERPSession + """ + if not isinstance(domain, basestring): + return domain + try: + return ast.literal_eval(domain) + except ValueError: + # not a literal + return common.nonliterals.Domain(session, domain) + +def parse_context(context, session): + """ Parses an arbitrary string containing a context, transforms it + to either a literal context or a :class:`common.nonliterals.Context` + + :param context: the context to parse, if the context is not a string it + is assumed to be a literal domain and is returned as-is + :param session: Current OpenERP session + :type session: openerpweb.openerpweb.OpenERPSession + """ + if not isinstance(context, basestring): + return context + try: + return ast.literal_eval(context) + except ValueError: + return common.nonliterals.Context(session, context) + +#---------------------------------------------------------- +# OpenERP Web web Controllers +#---------------------------------------------------------- + +html_template = """ + + + + + OpenERP + + + %(css)s + %(js)s + + + + +""" + class Home(openerpweb.Controller): _cp_path = '/' @@ -248,21 +520,14 @@ class Home(openerpweb.Controller): r = html_template % { 'js': js, 'css': css, - 'modules': simplejson.dumps(server_wide_modules(req)), + 'modules': simplejson.dumps(module_boot(req)), 'init': 'var wc = new s.web.WebClient();wc.appendTo($(document.body));' } return r @openerpweb.httprequest def login(self, req, db, login, key): - return self._login(req, db, login, key) - - def _login(self, req, db, login, key, redirect_url='/'): - req.session.authenticate(db, login, key, {}) - redirect = werkzeug.utils.redirect(redirect_url, 303) - cookie_val = urllib2.quote(simplejson.dumps(req.session_id)) - redirect.set_cookie('instance0|session_id', cookie_val) - return redirect + return login_and_redirect(req, db, login, key) class WebClient(openerpweb.Controller): _cp_path = "/web/webclient" @@ -412,12 +677,7 @@ class Database(openerpweb.Controller): @openerpweb.jsonrequest def get_list(self, req): - proxy = req.session.proxy("db") - dbs = proxy.list() - h = req.httprequest.environ['HTTP_HOST'].split(':')[0] - d = h.split('.')[0] - r = req.config.dbfilter.replace('%h', h).replace('%d', d) - dbs = [i for i in dbs if re.match(r, i)] + dbs = db_list(req) return {"db_list": dbs} @openerpweb.jsonrequest @@ -486,50 +746,6 @@ class Database(openerpweb.Controller): return {'error': e.faultCode, 'title': 'Change Password'} return {'error': 'Error, password not changed !', 'title': 'Change Password'} -def topological_sort(modules): - """ Return a list of module names sorted so that their dependencies of the - modules are listed before the module itself - - modules is a dict of {module_name: dependencies} - - :param modules: modules to sort - :type modules: dict - :returns: list(str) - """ - - dependencies = set(itertools.chain.from_iterable(modules.itervalues())) - # incoming edge: dependency on other module (if a depends on b, a has an - # incoming edge from b, aka there's an edge from b to a) - # outgoing edge: other module depending on this one - - # [Tarjan 1976], http://en.wikipedia.org/wiki/Topological_sorting#Algorithms - #L ← Empty list that will contain the sorted nodes - L = [] - #S ← Set of all nodes with no outgoing edges (modules on which no other - # module depends) - S = set(module for module in modules if module not in dependencies) - - visited = set() - #function visit(node n) - def visit(n): - #if n has not been visited yet then - if n not in visited: - #mark n as visited - visited.add(n) - #change: n not web module, can not be resolved, ignore - if n not in modules: return - #for each node m with an edge from m to n do (dependencies of n) - for m in modules[n]: - #visit(m) - visit(m) - #add n to L - L.append(n) - #for each node n in S do - for n in S: - #visit(n) - visit(n) - return L - class Session(openerpweb.Controller): _cp_path = "/web/session" @@ -595,34 +811,8 @@ class Session(openerpweb.Controller): @openerpweb.jsonrequest def modules(self, req): - # Compute available candidates module - loadable = openerpweb.addons_manifest - loaded = set(req.config.server_wide_modules) - candidates = [mod for mod in loadable if mod not in loaded] - - # already installed modules have no dependencies - modules = dict.fromkeys(loaded, []) - - # Compute auto_install modules that might be on the web side only - modules.update((name, openerpweb.addons_manifest[name].get('depends', [])) - for name in candidates - if openerpweb.addons_manifest[name].get('auto_install')) - - # Retrieve database installed modules - Modules = req.session.model('ir.module.module') - for module in Modules.search_read( - [('state','=','installed'), ('name','in', candidates)], - ['name', 'dependencies_id']): - deps = module.get('dependencies_id') - if deps: - dependencies = map( - operator.itemgetter('name'), - req.session.model('ir.module.module.dependency').read(deps, ['name'])) - modules[module['name']] = list( - set(modules.get(module['name'], []) + dependencies)) - - sorted_modules = topological_sort(modules) - return [module for module in sorted_modules if module not in loaded] + # return all installed modules. Web client is smart enough to not load a module twice + return module_installed(req) @openerpweb.jsonrequest def eval_domain_and_context(self, req, contexts, domains, @@ -726,120 +916,6 @@ class Session(openerpweb.Controller): def destroy(self, req): req.session._suicide = True -def eval_context_and_domain(session, context, domain=None): - e_context = session.eval_context(context) - # should we give the evaluated context as an evaluation context to the domain? - e_domain = session.eval_domain(domain or []) - - return e_context, e_domain - -def load_actions_from_ir_values(req, key, key2, models, meta): - context = req.session.eval_context(req.context) - Values = req.session.model('ir.values') - actions = Values.get(key, key2, models, meta, context) - - return [(id, name, clean_action(req, action)) - for id, name, action in actions] - -def clean_action(req, action, do_not_eval=False): - action.setdefault('flags', {}) - - context = req.session.eval_context(req.context) - eval_ctx = req.session.evaluation_context(context) - - if not do_not_eval: - # values come from the server, we can just eval them - if action.get('context') and isinstance(action.get('context'), basestring): - action['context'] = eval( action['context'], eval_ctx ) or {} - - if action.get('domain') and isinstance(action.get('domain'), basestring): - action['domain'] = eval( action['domain'], eval_ctx ) or [] - else: - if 'context' in action: - action['context'] = parse_context(action['context'], req.session) - if 'domain' in action: - action['domain'] = parse_domain(action['domain'], req.session) - - action_type = action.setdefault('type', 'ir.actions.act_window_close') - if action_type == 'ir.actions.act_window': - return fix_view_modes(action) - return action - -# I think generate_views,fix_view_modes should go into js ActionManager -def generate_views(action): - """ - While the server generates a sequence called "views" computing dependencies - between a bunch of stuff for views coming directly from the database - (the ``ir.actions.act_window model``), it's also possible for e.g. buttons - to return custom view dictionaries generated on the fly. - - In that case, there is no ``views`` key available on the action. - - Since the web client relies on ``action['views']``, generate it here from - ``view_mode`` and ``view_id``. - - Currently handles two different cases: - - * no view_id, multiple view_mode - * single view_id, single view_mode - - :param dict action: action descriptor dictionary to generate a views key for - """ - view_id = action.get('view_id') or False - if isinstance(view_id, (list, tuple)): - view_id = view_id[0] - - # providing at least one view mode is a requirement, not an option - view_modes = action['view_mode'].split(',') - - if len(view_modes) > 1: - if view_id: - raise ValueError('Non-db action dictionaries should provide ' - 'either multiple view modes or a single view ' - 'mode and an optional view id.\n\n Got view ' - 'modes %r and view id %r for action %r' % ( - view_modes, view_id, action)) - action['views'] = [(False, mode) for mode in view_modes] - return - action['views'] = [(view_id, view_modes[0])] - -def fix_view_modes(action): - """ For historical reasons, OpenERP has weird dealings in relation to - view_mode and the view_type attribute (on window actions): - - * one of the view modes is ``tree``, which stands for both list views - and tree views - * the choice is made by checking ``view_type``, which is either - ``form`` for a list view or ``tree`` for an actual tree view - - This methods simply folds the view_type into view_mode by adding a - new view mode ``list`` which is the result of the ``tree`` view_mode - in conjunction with the ``form`` view_type. - - TODO: this should go into the doc, some kind of "peculiarities" section - - :param dict action: an action descriptor - :returns: nothing, the action is modified in place - """ - if not action.get('views'): - generate_views(action) - - id_form = None - for index, (id, mode) in enumerate(action['views']): - if mode == 'form': - id_form = id - break - - if action.pop('view_type', 'form') != 'form': - return action - - action['views'] = [ - [id, mode if mode != 'tree' else 'list'] - for id, mode in action['views'] - ] - - return action - class Menu(openerpweb.Controller): _cp_path = "/web/menu" @@ -1065,6 +1141,15 @@ class DataSet(openerpweb.Controller): def exec_workflow(self, req, model, id, signal): return req.session.exec_workflow(model, id, signal) + @openerpweb.jsonrequest + def resequence(self, req, model, ids): + m = req.session.model(model) + if not len(m.fields_get(['sequence'])): + return False + for i in range(len(ids)): + m.write([ids[i]], { 'sequence': i }) + return True + class DataGroup(openerpweb.Controller): _cp_path = "/web/group" @openerpweb.jsonrequest @@ -1204,39 +1289,6 @@ class View(openerpweb.Controller): def load(self, req, model, view_id, view_type, toolbar=False): return self.fields_view_get(req, model, view_id, view_type, toolbar=toolbar) -def parse_domain(domain, session): - """ Parses an arbitrary string containing a domain, transforms it - to either a literal domain or a :class:`common.nonliterals.Domain` - - :param domain: the domain to parse, if the domain is not a string it - is assumed to be a literal domain and is returned as-is - :param session: Current OpenERP session - :type session: openerpweb.openerpweb.OpenERPSession - """ - if not isinstance(domain, basestring): - return domain - try: - return ast.literal_eval(domain) - except ValueError: - # not a literal - return common.nonliterals.Domain(session, domain) - -def parse_context(context, session): - """ Parses an arbitrary string containing a context, transforms it - to either a literal context or a :class:`common.nonliterals.Context` - - :param context: the context to parse, if the context is not a string it - is assumed to be a literal domain and is returned as-is - :param session: Current OpenERP session - :type session: openerpweb.openerpweb.OpenERPSession - """ - if not isinstance(context, basestring): - return context - try: - return ast.literal_eval(context) - except ValueError: - return common.nonliterals.Context(session, context) - class ListView(View): _cp_path = "/web/listview" @@ -1310,47 +1362,6 @@ class SearchView(View): del filter['context'] del filter['domain'] return filters - - - @openerpweb.jsonrequest - def add_to_dashboard(self, req, menu_id, action_id, context_to_save, domain, view_mode, name=''): - to_eval = common.nonliterals.CompoundContext(context_to_save) - to_eval.session = req.session - ctx = dict((k, v) for k, v in to_eval.evaluate().iteritems() - if not k.startswith('search_default_')) - ctx['dashboard_merge_domains_contexts'] = False # TODO: replace this 6.1 workaround by attribute on - domain = common.nonliterals.CompoundDomain(domain) - domain.session = req.session - domain = domain.evaluate() - - dashboard_action = load_actions_from_ir_values(req, 'action', 'tree_but_open', - [('ir.ui.menu', menu_id)], False) - if dashboard_action: - action = dashboard_action[0][2] - if action['res_model'] == 'board.board' and action['views'][0][1] == 'form': - # Maybe should check the content instead of model board.board ? - view_id = action['views'][0][0] - board = req.session.model(action['res_model']).fields_view_get(view_id, 'form') - if board and 'arch' in board: - xml = ElementTree.fromstring(board['arch']) - column = xml.find('./board/column') - if column is not None: - new_action = ElementTree.Element('action', { - 'name' : str(action_id), - 'string' : name, - 'view_mode' : view_mode, - 'context' : str(ctx), - 'domain' : str(domain) - }) - column.insert(0, new_action) - arch = ElementTree.tostring(xml, 'utf-8') - return req.session.model('ir.ui.view.custom').create({ - 'user_id': req.session._uid, - 'ref_id': view_id, - 'arch': arch - }, req.session.eval_context(req.context)) - - return False class Binary(openerpweb.Controller): _cp_path = "/web/binary" @@ -1363,11 +1374,14 @@ class Binary(openerpweb.Controller): headers = [('Content-Type', 'image/png')] etag = req.httprequest.headers.get('If-None-Match') hashed_session = hashlib.md5(req.session_id).hexdigest() + id = None if not id else simplejson.loads(id) + if type(id) is list: + id = id[0] # m2o if etag: if not id and hashed_session == etag: return werkzeug.wrappers.Response(status=304) else: - date = Model.read([int(id)], [last_update], context)[0].get(last_update) + date = Model.read([id], [last_update], context)[0].get(last_update) if hashlib.md5(date).hexdigest() == etag: return werkzeug.wrappers.Response(status=304) @@ -1377,11 +1391,6 @@ class Binary(openerpweb.Controller): res = Model.default_get([field], context).get(field) image_data = base64.b64decode(res) else: - try: - id = int(id) - except (ValueError): - # objects might use virtual ids as string - pass res = Model.read([id], [last_update, field], context)[0] retag = hashlib.md5(res.get(last_update)).hexdigest() image_data = base64.b64decode(res.get(field)) @@ -1999,3 +2008,5 @@ class Import(View): message, record) return '' % ( jsonp, simplejson.dumps({'error': {'message':msg}})) + +# vim:expandtab:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/addons/web/i18n/ar.po b/addons/web/i18n/ar.po index 0f36aa1cc4f..498c78516be 100644 --- a/addons/web/i18n/ar.po +++ b/addons/web/i18n/ar.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:44+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/bg.po b/addons/web/i18n/bg.po index c52042a4b59..775314cd39e 100644 --- a/addons/web/i18n/bg.po +++ b/addons/web/i18n/bg.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:44+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/bn.po b/addons/web/i18n/bn.po index ac2d00d9a19..96aff0694c1 100644 --- a/addons/web/i18n/bn.po +++ b/addons/web/i18n/bn.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:44+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/bs.po b/addons/web/i18n/bs.po index ad7bbe2cfab..e2aff2f0b09 100644 --- a/addons/web/i18n/bs.po +++ b/addons/web/i18n/bs.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:44+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/ca.po b/addons/web/i18n/ca.po index 1166c9a76be..6c5cce42b4a 100644 --- a/addons/web/i18n/ca.po +++ b/addons/web/i18n/ca.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/cs.po b/addons/web/i18n/cs.po index 39dcc94e600..e03171f930f 100644 --- a/addons/web/i18n/cs.po +++ b/addons/web/i18n/cs.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" "X-Poedit-Language: Czech\n" #. openerp-web diff --git a/addons/web/i18n/da.po b/addons/web/i18n/da.po index 37cdd447d88..d4a5cc6efad 100644 --- a/addons/web/i18n/da.po +++ b/addons/web/i18n/da.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/de.po b/addons/web/i18n/de.po index cd9870daf8d..bd7f20ec818 100644 --- a/addons/web/i18n/de.po +++ b/addons/web/i18n/de.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/en_AU.po b/addons/web/i18n/en_AU.po index 980e0495a17..6d7490923f6 100644 --- a/addons/web/i18n/en_AU.po +++ b/addons/web/i18n/en_AU.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/en_GB.po b/addons/web/i18n/en_GB.po index e181c7b0f3b..83c3325e793 100644 --- a/addons/web/i18n/en_GB.po +++ b/addons/web/i18n/en_GB.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/es.po b/addons/web/i18n/es.po index 78c51a4b14d..74e77381873 100644 --- a/addons/web/i18n/es.po +++ b/addons/web/i18n/es.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/es_CL.po b/addons/web/i18n/es_CL.po index eafa6347c7d..5e65aad781f 100644 --- a/addons/web/i18n/es_CL.po +++ b/addons/web/i18n/es_CL.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/es_CR.po b/addons/web/i18n/es_CR.po index ce3448df7aa..953aacbfb3d 100644 --- a/addons/web/i18n/es_CR.po +++ b/addons/web/i18n/es_CR.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" "Language: es\n" #. openerp-web diff --git a/addons/web/i18n/es_EC.po b/addons/web/i18n/es_EC.po index 47abace7e8a..7eb680fc806 100644 --- a/addons/web/i18n/es_EC.po +++ b/addons/web/i18n/es_EC.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/et.po b/addons/web/i18n/et.po index adf87a35acf..96c99115ff1 100644 --- a/addons/web/i18n/et.po +++ b/addons/web/i18n/et.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/eu.po b/addons/web/i18n/eu.po index dbe83aaa07e..38dc8244b97 100644 --- a/addons/web/i18n/eu.po +++ b/addons/web/i18n/eu.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:44+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/fi.po b/addons/web/i18n/fi.po index e068de86393..c4d36e63a43 100644 --- a/addons/web/i18n/fi.po +++ b/addons/web/i18n/fi.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/fr.po b/addons/web/i18n/fr.po index f1eb7538abe..9e0a92f76cf 100644 --- a/addons/web/i18n/fr.po +++ b/addons/web/i18n/fr.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/fr_CA.po b/addons/web/i18n/fr_CA.po index 64392521b3a..bfd81ef9938 100644 --- a/addons/web/i18n/fr_CA.po +++ b/addons/web/i18n/fr_CA.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/gl.po b/addons/web/i18n/gl.po index 787600e6530..6471ce44d60 100644 --- a/addons/web/i18n/gl.po +++ b/addons/web/i18n/gl.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/gu.po b/addons/web/i18n/gu.po index 379c920071f..778e78b55b2 100644 --- a/addons/web/i18n/gu.po +++ b/addons/web/i18n/gu.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/hi.po b/addons/web/i18n/hi.po index 4b45f75782c..21c023f5560 100644 --- a/addons/web/i18n/hi.po +++ b/addons/web/i18n/hi.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/hr.po b/addons/web/i18n/hr.po index f0b8e2cf1ba..da768b45e9e 100644 --- a/addons/web/i18n/hr.po +++ b/addons/web/i18n/hr.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/hu.po b/addons/web/i18n/hu.po index 6aa3dda534c..8a3b6507d5d 100644 --- a/addons/web/i18n/hu.po +++ b/addons/web/i18n/hu.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/id.po b/addons/web/i18n/id.po index 61542947099..f1bd452b6bd 100644 --- a/addons/web/i18n/id.po +++ b/addons/web/i18n/id.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/it.po b/addons/web/i18n/it.po index 3b080d51083..ee0f096eda7 100644 --- a/addons/web/i18n/it.po +++ b/addons/web/i18n/it.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/ja.po b/addons/web/i18n/ja.po index d6665f20d48..affb27e9acf 100644 --- a/addons/web/i18n/ja.po +++ b/addons/web/i18n/ja.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/ka.po b/addons/web/i18n/ka.po index 2bba1754dab..f875f727a4f 100644 --- a/addons/web/i18n/ka.po +++ b/addons/web/i18n/ka.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/mk.po b/addons/web/i18n/mk.po index 2a852ec2daf..c1504ec7ae4 100644 --- a/addons/web/i18n/mk.po +++ b/addons/web/i18n/mk.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/mn.po b/addons/web/i18n/mn.po index 856cbb12b37..25bc63906da 100644 --- a/addons/web/i18n/mn.po +++ b/addons/web/i18n/mn.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/nb.po b/addons/web/i18n/nb.po index 0cff88715ef..ca269b242b0 100644 --- a/addons/web/i18n/nb.po +++ b/addons/web/i18n/nb.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/nl.po b/addons/web/i18n/nl.po index ba9d26c5a55..b04df56f3dd 100644 --- a/addons/web/i18n/nl.po +++ b/addons/web/i18n/nl.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/nl_BE.po b/addons/web/i18n/nl_BE.po index 4177344b173..416ef765127 100644 --- a/addons/web/i18n/nl_BE.po +++ b/addons/web/i18n/nl_BE.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/pl.po b/addons/web/i18n/pl.po index 1065dea0625..0110ed205f5 100644 --- a/addons/web/i18n/pl.po +++ b/addons/web/i18n/pl.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/pt.po b/addons/web/i18n/pt.po index 6411ed2e0ef..8166d9e0f22 100644 --- a/addons/web/i18n/pt.po +++ b/addons/web/i18n/pt.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/pt_BR.po b/addons/web/i18n/pt_BR.po index cef8cfbea32..3d0b5dd72ae 100644 --- a/addons/web/i18n/pt_BR.po +++ b/addons/web/i18n/pt_BR.po @@ -9,13 +9,14 @@ msgstr "" "Report-Msgid-Bugs-To: FULL NAME \n" "POT-Creation-Date: 2012-07-02 09:06+0200\n" "PO-Revision-Date: 2012-07-30 00:28+0000\n" -"Last-Translator: Fábio Martinelli \n" +"Last-Translator: Fábio Martinelli - http://zupy.com.br " +"\n" "Language-Team: Brazilian Portuguese \n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/ro.po b/addons/web/i18n/ro.po index 610b10a07ac..7f32fc3db44 100644 --- a/addons/web/i18n/ro.po +++ b/addons/web/i18n/ro.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/ru.po b/addons/web/i18n/ru.po index 013c6d6d103..abc6f64d863 100644 --- a/addons/web/i18n/ru.po +++ b/addons/web/i18n/ru.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/sk.po b/addons/web/i18n/sk.po index 5e811fe09ea..dddf69edd89 100644 --- a/addons/web/i18n/sk.po +++ b/addons/web/i18n/sk.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/sl.po b/addons/web/i18n/sl.po index c19851d0c42..6953dfae170 100644 --- a/addons/web/i18n/sl.po +++ b/addons/web/i18n/sl.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/sq.po b/addons/web/i18n/sq.po index 06bc23a5371..abec3f0edee 100644 --- a/addons/web/i18n/sq.po +++ b/addons/web/i18n/sq.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:44+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/sr@latin.po b/addons/web/i18n/sr@latin.po index 39ff195729e..8ca06c6cdf9 100644 --- a/addons/web/i18n/sr@latin.po +++ b/addons/web/i18n/sr@latin.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/sv.po b/addons/web/i18n/sv.po index a94ae1736a6..31db2f2f6d7 100644 --- a/addons/web/i18n/sv.po +++ b/addons/web/i18n/sv.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/tr.po b/addons/web/i18n/tr.po index f0b6e0285be..5aeb203510d 100644 --- a/addons/web/i18n/tr.po +++ b/addons/web/i18n/tr.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/uk.po b/addons/web/i18n/uk.po index 6b7dd66a729..cb04d046af5 100644 --- a/addons/web/i18n/uk.po +++ b/addons/web/i18n/uk.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:49+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/zh_CN.po b/addons/web/i18n/zh_CN.po index 67dcc2db4a4..4c8b46ec72a 100644 --- a/addons/web/i18n/zh_CN.po +++ b/addons/web/i18n/zh_CN.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/i18n/zh_TW.po b/addons/web/i18n/zh_TW.po index 490eab5317b..8c6a6cb74e9 100644 --- a/addons/web/i18n/zh_TW.po +++ b/addons/web/i18n/zh_TW.po @@ -14,8 +14,8 @@ msgstr "" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"X-Launchpad-Export-Date: 2012-08-08 04:45+0000\n" -"X-Generator: Launchpad (build 15757)\n" +"X-Launchpad-Export-Date: 2012-08-15 04:50+0000\n" +"X-Generator: Launchpad (build 15801)\n" #. openerp-web #: addons/web/static/src/js/chrome.js:176 diff --git a/addons/web/static/lib/backbone/backbone.js b/addons/web/static/lib/backbone/backbone.js index 7c56f42363c..3373c952bfa 100644 --- a/addons/web/static/lib/backbone/backbone.js +++ b/addons/web/static/lib/backbone/backbone.js @@ -1,4 +1,4 @@ -// Backbone.js 0.9.1 +// Backbone.js 0.9.2 // (c) 2010-2012 Jeremy Ashkenas, DocumentCloud Inc. // Backbone may be freely distributed under the MIT license. @@ -32,7 +32,7 @@ } // Current version of the library. Keep in sync with `package.json`. - Backbone.VERSION = '0.9.1'; + Backbone.VERSION = '0.9.2'; // Require Underscore, if we're on the server, and it's not already present. var _ = root._; @@ -71,6 +71,9 @@ // Backbone.Events // ----------------- + // Regular expression used to split event strings + var eventSplitter = /\s+/; + // A module that can be mixed in to *any object* in order to provide it with // custom events. You may bind with `on` or remove with `off` callback functions // to an event; trigger`-ing an event fires all callbacks in succession. @@ -80,89 +83,110 @@ // object.on('expand', function(){ alert('expanded'); }); // object.trigger('expand'); // - Backbone.Events = { + var Events = Backbone.Events = { - // Bind an event, specified by a string name, `ev`, to a `callback` + // Bind one or more space separated events, `events`, to a `callback` // function. Passing `"all"` will bind the callback to all events fired. on: function(events, callback, context) { - var ev; - events = events.split(/\s+/); - var calls = this._callbacks || (this._callbacks = {}); - while (ev = events.shift()) { - // Create an immutable callback list, allowing traversal during - // modification. The tail is an empty object that will always be used - // as the next node. - var list = calls[ev] || (calls[ev] = {}); - var tail = list.tail || (list.tail = list.next = {}); - tail.callback = callback; - tail.context = context; - list.tail = tail.next = {}; + + var calls, event, node, tail, list; + if (!callback) return this; + events = events.split(eventSplitter); + calls = this._callbacks || (this._callbacks = {}); + + // Create an immutable callback list, allowing traversal during + // modification. The tail is an empty object that will always be used + // as the next node. + while (event = events.shift()) { + list = calls[event]; + node = list ? list.tail : {}; + node.next = tail = {}; + node.context = context; + node.callback = callback; + calls[event] = {tail: tail, next: list ? list.next : node}; } + return this; }, // Remove one or many callbacks. If `context` is null, removes all callbacks // with that function. If `callback` is null, removes all callbacks for the - // event. If `ev` is null, removes all bound callbacks for all events. + // event. If `events` is null, removes all bound callbacks for all events. off: function(events, callback, context) { - var ev, calls, node; - if (!events) { + var event, calls, node, tail, cb, ctx; + + // No events, or removing *all* events. + if (!(calls = this._callbacks)) return; + if (!(events || callback || context)) { delete this._callbacks; - } else if (calls = this._callbacks) { - events = events.split(/\s+/); - while (ev = events.shift()) { - node = calls[ev]; - delete calls[ev]; - if (!callback || !node) continue; - // Create a new list, omitting the indicated event/context pairs. - while ((node = node.next) && node.next) { - if (node.callback === callback && - (!context || node.context === context)) continue; - this.on(ev, node.callback, node.context); + return this; + } + + // Loop through the listed events and contexts, splicing them out of the + // linked list of callbacks if appropriate. + events = events ? events.split(eventSplitter) : _.keys(calls); + while (event = events.shift()) { + node = calls[event]; + delete calls[event]; + if (!node || !(callback || context)) continue; + // Create a new list, omitting the indicated callbacks. + tail = node.tail; + while ((node = node.next) !== tail) { + cb = node.callback; + ctx = node.context; + if ((callback && cb !== callback) || (context && ctx !== context)) { + this.on(event, cb, ctx); } } } + return this; }, - // Trigger an event, firing all bound callbacks. Callbacks are passed the - // same arguments as `trigger` is, apart from the event name. - // Listening for `"all"` passes the true event name as the first argument. + // Trigger one or many events, firing all bound callbacks. Callbacks are + // passed the same arguments as `trigger` is, apart from the event name + // (unless you're listening on `"all"`, which will cause your callback to + // receive the true name of the event as the first argument). trigger: function(events) { var event, node, calls, tail, args, all, rest; if (!(calls = this._callbacks)) return this; - all = calls['all']; - (events = events.split(/\s+/)).push(null); - // Save references to the current heads & tails. - while (event = events.shift()) { - if (all) events.push({next: all.next, tail: all.tail, event: event}); - if (!(node = calls[event])) continue; - events.push({next: node.next, tail: node.tail}); - } - // Traverse each list, stopping when the saved tail is reached. + all = calls.all; + events = events.split(eventSplitter); rest = slice.call(arguments, 1); - while (node = events.pop()) { - tail = node.tail; - args = node.event ? [node.event].concat(rest) : rest; - while ((node = node.next) !== tail) { - node.callback.apply(node.context || this, args); + + // For each event, walk through the linked list of callbacks twice, + // first to trigger the event, then to trigger any `"all"` callbacks. + while (event = events.shift()) { + if (node = calls[event]) { + tail = node.tail; + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, rest); + } + } + if (node = all) { + tail = node.tail; + args = [event].concat(rest); + while ((node = node.next) !== tail) { + node.callback.apply(node.context || this, args); + } } } + return this; } }; // Aliases for backwards compatibility. - Backbone.Events.bind = Backbone.Events.on; - Backbone.Events.unbind = Backbone.Events.off; + Events.bind = Events.on; + Events.unbind = Events.off; // Backbone.Model // -------------- // Create a new model, with defined attributes. A client id (`cid`) // is automatically generated and assigned for you. - Backbone.Model = function(attributes, options) { + var Model = Backbone.Model = function(attributes, options) { var defaults; attributes || (attributes = {}); if (options && options.parse) attributes = this.parse(attributes); @@ -173,16 +197,31 @@ this.attributes = {}; this._escapedAttributes = {}; this.cid = _.uniqueId('c'); - if (!this.set(attributes, {silent: true})) { - throw new Error("Can't create an invalid model"); - } - delete this._changed; + this.changed = {}; + this._silent = {}; + this._pending = {}; + this.set(attributes, {silent: true}); + // Reset change tracking. + this.changed = {}; + this._silent = {}; + this._pending = {}; this._previousAttributes = _.clone(this.attributes); this.initialize.apply(this, arguments); }; // Attach all inheritable methods to the Model prototype. - _.extend(Backbone.Model.prototype, Backbone.Events, { + _.extend(Model.prototype, Events, { + + // A hash of attributes whose current and previous value differ. + changed: null, + + // A hash of attributes that have silently changed since the last time + // `change` was called. Will become pending attributes on the next call. + _silent: null, + + // A hash of attributes that have changed since the last `'change'` event + // began. + _pending: null, // The default name for the JSON `id` attribute is `"id"`. MongoDB and // CouchDB users may want to set this to `"_id"`. @@ -193,7 +232,7 @@ initialize: function(){}, // Return a copy of the model's `attributes` object. - toJSON: function() { + toJSON: function(options) { return _.clone(this.attributes); }, @@ -206,20 +245,22 @@ escape: function(attr) { var html; if (html = this._escapedAttributes[attr]) return html; - var val = this.attributes[attr]; + var val = this.get(attr); return this._escapedAttributes[attr] = _.escape(val == null ? '' : '' + val); }, // Returns `true` if the attribute contains a value that is not null // or undefined. has: function(attr) { - return this.attributes[attr] != null; + return this.get(attr) != null; }, // Set a hash of model attributes on the object, firing `"change"` unless // you choose to silence it. set: function(key, value, options) { var attrs, attr, val; + + // Handle both `"key", value` and `{key: value}` -style arguments. if (_.isObject(key) || key == null) { attrs = key; options = value; @@ -231,7 +272,7 @@ // Extract attributes and options. options || (options = {}); if (!attrs) return this; - if (attrs instanceof Backbone.Model) attrs = attrs.attributes; + if (attrs instanceof Model) attrs = attrs.attributes; if (options.unset) for (attr in attrs) attrs[attr] = void 0; // Run validation. @@ -240,33 +281,37 @@ // Check for changes of `id`. if (this.idAttribute in attrs) this.id = attrs[this.idAttribute]; + var changes = options.changes = {}; var now = this.attributes; var escaped = this._escapedAttributes; var prev = this._previousAttributes || {}; - var alreadySetting = this._setting; - this._changed || (this._changed = {}); - this._setting = true; - // Update attributes. + // For each `set` attribute... for (attr in attrs) { val = attrs[attr]; - if (!_.isEqual(now[attr], val)) delete escaped[attr]; - options.unset ? delete now[attr] : now[attr] = val; - if (this._changing && !_.isEqual(this._changed[attr], val)) { - this.trigger('change:' + attr, this, val, options); - this._moreChanges = true; + + // If the new and current value differ, record the change. + if (!_.isEqual(now[attr], val) || (options.unset && _.has(now, attr))) { + delete escaped[attr]; + (options.silent ? this._silent : changes)[attr] = true; } - delete this._changed[attr]; + + // Update or delete the current value. + options.unset ? delete now[attr] : now[attr] = val; + + // If the new and previous value differ, record the change. If not, + // then remove changes for this attribute. if (!_.isEqual(prev[attr], val) || (_.has(now, attr) != _.has(prev, attr))) { - this._changed[attr] = val; + this.changed[attr] = val; + if (!options.silent) this._pending[attr] = true; + } else { + delete this.changed[attr]; + delete this._pending[attr]; } } - // Fire the `"change"` events, if the model has been changed. - if (!alreadySetting) { - if (!options.silent && this.hasChanged()) this.change(options); - this._setting = false; - } + // Fire the `"change"` events. + if (!options.silent) this.change(options); return this; }, @@ -304,6 +349,8 @@ // state will be `set` again. save: function(key, value, options) { var attrs, current; + + // Handle both `("key", value)` and `({key: value})` -style calls. if (_.isObject(key) || key == null) { attrs = key; options = value; @@ -311,18 +358,30 @@ attrs = {}; attrs[key] = value; } - options = options ? _.clone(options) : {}; - if (options.wait) current = _.clone(this.attributes); + + // If we're "wait"-ing to set changed attributes, validate early. + if (options.wait) { + if (!this._validate(attrs, options)) return false; + current = _.clone(this.attributes); + } + + // Regular saves `set` attributes before persisting to the server. var silentOptions = _.extend({}, options, {silent: true}); if (attrs && !this.set(attrs, options.wait ? silentOptions : options)) { return false; } + + // After a successful server-side save, the client is (optionally) + // updated with the server-side state. var model = this; var success = options.success; options.success = function(resp, status, xhr) { var serverAttrs = model.parse(resp, xhr); - if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs); + if (options.wait) { + delete options.wait; + serverAttrs = _.extend(attrs || {}, serverAttrs); + } if (!model.set(serverAttrs, options)) return false; if (success) { success(model, resp); @@ -330,6 +389,8 @@ model.trigger('sync', model, resp, options); } }; + + // Finish configuring and sending the Ajax request. options.error = Backbone.wrapError(options.error, model, options); var method = this.isNew() ? 'create' : 'update'; var xhr = (this.sync || Backbone.sync).call(this, method, this, options); @@ -349,7 +410,11 @@ model.trigger('destroy', model, model.collection, options); }; - if (this.isNew()) return triggerDestroy(); + if (this.isNew()) { + triggerDestroy(); + return false; + } + options.success = function(resp) { if (options.wait) triggerDestroy(); if (success) { @@ -358,6 +423,7 @@ model.trigger('sync', model, resp, options); } }; + options.error = Backbone.wrapError(options.error, model, options); var xhr = (this.sync || Backbone.sync).call(this, 'delete', this, options); if (!options.wait) triggerDestroy(); @@ -368,7 +434,7 @@ // using Backbone's restful methods, override this to change the endpoint // that will be called. url: function() { - var base = getValue(this.collection, 'url') || getValue(this, 'urlRoot') || urlError(); + var base = getValue(this, 'urlRoot') || getValue(this.collection, 'url') || urlError(); if (this.isNew()) return base; return base + (base.charAt(base.length - 1) == '/' ? '' : '/') + encodeURIComponent(this.id); }, @@ -393,18 +459,33 @@ // a `"change:attribute"` event for each changed attribute. // Calling this will cause all objects observing the model to update. change: function(options) { - if (this._changing || !this.hasChanged()) return this; + options || (options = {}); + var changing = this._changing; this._changing = true; - this._moreChanges = true; - for (var attr in this._changed) { - this.trigger('change:' + attr, this, this._changed[attr], options); + + // Silent changes become pending changes. + for (var attr in this._silent) this._pending[attr] = true; + + // Silent changes are triggered. + var changes = _.extend({}, options.changes, this._silent); + this._silent = {}; + for (var attr in changes) { + this.trigger('change:' + attr, this, this.get(attr), options); } - while (this._moreChanges) { - this._moreChanges = false; + if (changing) return this; + + // Continue firing `"change"` events while there are pending changes. + while (!_.isEmpty(this._pending)) { + this._pending = {}; this.trigger('change', this, options); + // Pending and silent changes still remain. + for (var attr in this.changed) { + if (this._pending[attr] || this._silent[attr]) continue; + delete this.changed[attr]; + } + this._previousAttributes = _.clone(this.attributes); } - this._previousAttributes = _.clone(this.attributes); - delete this._changed; + this._changing = false; return this; }, @@ -412,8 +493,8 @@ // Determine if the model has changed since the last `"change"` event. // If you specify an attribute name, determine if that attribute has changed. hasChanged: function(attr) { - if (!arguments.length) return !_.isEmpty(this._changed); - return this._changed && _.has(this._changed, attr); + if (!arguments.length) return !_.isEmpty(this.changed); + return _.has(this.changed, attr); }, // Return an object containing all the attributes that have changed, or @@ -423,7 +504,7 @@ // You can also pass an attributes object to diff against the model, // determining if there *would be* a change. changedAttributes: function(diff) { - if (!diff) return this.hasChanged() ? _.clone(this._changed) : false; + if (!diff) return this.hasChanged() ? _.clone(this.changed) : false; var val, changed = false, old = this._previousAttributes; for (var attr in diff) { if (_.isEqual(old[attr], (val = diff[attr]))) continue; @@ -451,9 +532,9 @@ return !this.validate(this.attributes); }, - // Run validation against a set of incoming attributes, returning `true` - // if all is well. If a specific `error` callback has been passed, - // call that instead of firing the general `"error"` event. + // Run validation against the next complete set of model attributes, + // returning `true` if all is well. If a specific `error` callback has + // been passed, call that instead of firing the general `"error"` event. _validate: function(attrs, options) { if (options.silent || !this.validate) return true; attrs = _.extend({}, this.attributes, attrs); @@ -475,8 +556,9 @@ // Provides a standard collection class for our sets of models, ordered // or unordered. If a `comparator` is specified, the Collection will maintain // its models in sort order, as they're added and removed. - Backbone.Collection = function(models, options) { + var Collection = Backbone.Collection = function(models, options) { options || (options = {}); + if (options.model) this.model = options.model; if (options.comparator) this.comparator = options.comparator; this._reset(); this.initialize.apply(this, arguments); @@ -484,11 +566,11 @@ }; // Define the Collection's inheritable methods. - _.extend(Backbone.Collection.prototype, Backbone.Events, { + _.extend(Collection.prototype, Events, { // The default model for a collection is just a **Backbone.Model**. // This should be overridden in most cases. - model: Backbone.Model, + model: Model, // Initialize is an empty function by default. Override it with your own // initialization logic. @@ -496,14 +578,14 @@ // The JSON representation of a Collection is an array of the // models' attributes. - toJSON: function() { - return this.map(function(model){ return model.toJSON(); }); + toJSON: function(options) { + return this.map(function(model){ return model.toJSON(options); }); }, // Add a model, or list of models to the set. Pass **silent** to avoid // firing the `add` event for every new model. add: function(models, options) { - var i, index, length, model, cid, id, cids = {}, ids = {}; + var i, index, length, model, cid, id, cids = {}, ids = {}, dups = []; options || (options = {}); models = _.isArray(models) ? models.slice() : [models]; @@ -513,16 +595,24 @@ if (!(model = models[i] = this._prepareModel(models[i], options))) { throw new Error("Can't add an invalid model to a collection"); } - if (cids[cid = model.cid] || this._byCid[cid] || - (((id = model.id) != null) && (ids[id] || this._byId[id]))) { - throw new Error("Can't add the same model to a collection twice"); + cid = model.cid; + id = model.id; + if (cids[cid] || this._byCid[cid] || ((id != null) && (ids[id] || this._byId[id]))) { + dups.push(i); + continue; } cids[cid] = ids[id] = model; } + // Remove duplicates. + i = dups.length; + while (i--) { + models.splice(dups[i], 1); + } + // Listen to added models' events, and index models for lookup by // `id` and by `cid`. - for (i = 0; i < length; i++) { + for (i = 0, length = models.length; i < length; i++) { (model = models[i]).on('all', this._onModelEvent, this); this._byCid[model.cid] = model; if (model.id != null) this._byId[model.id] = model; @@ -566,9 +656,37 @@ return this; }, + // Add a model to the end of the collection. + push: function(model, options) { + model = this._prepareModel(model, options); + this.add(model, options); + return model; + }, + + // Remove a model from the end of the collection. + pop: function(options) { + var model = this.at(this.length - 1); + this.remove(model, options); + return model; + }, + + // Add a model to the beginning of the collection. + unshift: function(model, options) { + model = this._prepareModel(model, options); + this.add(model, _.extend({at: 0}, options)); + return model; + }, + + // Remove a model from the beginning of the collection. + shift: function(options) { + var model = this.at(0); + this.remove(model, options); + return model; + }, + // Get a model from the set by id. get: function(id) { - if (id == null) return null; + if (id == null) return void 0; return this._byId[id.id != null ? id.id : id]; }, @@ -582,6 +700,17 @@ return this.models[index]; }, + // Return models with matching attributes. Useful for simple cases of `filter`. + where: function(attrs) { + if (_.isEmpty(attrs)) return []; + return this.filter(function(model) { + for (var key in attrs) { + if (attrs[key] !== model.get(key)) return false; + } + return true; + }); + }, + // Force the collection to re-sort itself. You don't need to call this under // normal circumstances, as the set will maintain sort order as each item // is added. @@ -613,7 +742,7 @@ this._removeReference(this.models[i]); } this._reset(); - this.add(models, {silent: true, parse: options.parse}); + this.add(models, _.extend({silent: true}, options)); if (!options.silent) this.trigger('reset', this, options); return this; }, @@ -679,7 +808,8 @@ // Prepare a model or hash of attributes to be added to this collection. _prepareModel: function(model, options) { - if (!(model instanceof Backbone.Model)) { + options || (options = {}); + if (!(model instanceof Model)) { var attrs = model; options.collection = this; model = new this.model(attrs, options); @@ -702,12 +832,12 @@ // Sets need to update their indexes when models change ids. All other // events simply proxy through. "add" and "remove" events that originate // in other collections are ignored. - _onModelEvent: function(ev, model, collection, options) { - if ((ev == 'add' || ev == 'remove') && collection != this) return; - if (ev == 'destroy') { + _onModelEvent: function(event, model, collection, options) { + if ((event == 'add' || event == 'remove') && collection != this) return; + if (event == 'destroy') { this.remove(model, options); } - if (model && ev === 'change:' + model.idAttribute) { + if (model && event === 'change:' + model.idAttribute) { delete this._byId[model.previous(model.idAttribute)]; this._byId[model.id] = model; } @@ -725,7 +855,7 @@ // Mix in each Underscore method as a proxy to `Collection#models`. _.each(methods, function(method) { - Backbone.Collection.prototype[method] = function() { + Collection.prototype[method] = function() { return _[method].apply(_, [this.models].concat(_.toArray(arguments))); }; }); @@ -735,7 +865,7 @@ // Routers map faux-URLs to actions, and fire events when routes are // matched. Creating a new one sets its `routes` hash, if not set statically. - Backbone.Router = function(options) { + var Router = Backbone.Router = function(options) { options || (options = {}); if (options.routes) this.routes = options.routes; this._bindRoutes(); @@ -749,7 +879,7 @@ var escapeRegExp = /[-[\]{}()+?.,\\^$|#\s]/g; // Set up all inheritable **Backbone.Router** properties and methods. - _.extend(Backbone.Router.prototype, Backbone.Events, { + _.extend(Router.prototype, Events, { // Initialize is an empty function by default. Override it with your own // initialization logic. @@ -762,7 +892,7 @@ // }); // route: function(route, name, callback) { - Backbone.history || (Backbone.history = new Backbone.History); + Backbone.history || (Backbone.history = new History); if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (!callback) callback = this[name]; Backbone.history.route(route, _.bind(function(fragment) { @@ -815,7 +945,7 @@ // Handles cross-browser history management, based on URL fragments. If the // browser does not support `onhashchange`, falls back to polling. - Backbone.History = function() { + var History = Backbone.History = function() { this.handlers = []; _.bindAll(this, 'checkUrl'); }; @@ -827,15 +957,23 @@ var isExplorer = /msie [\w.]+/; // Has the history handling already been started? - var historyStarted = false; + History.started = false; // Set up all inheritable **Backbone.History** properties and methods. - _.extend(Backbone.History.prototype, Backbone.Events, { + _.extend(History.prototype, Events, { // The default interval to poll for hash changes, if necessary, is // twenty times a second. interval: 50, + // Gets the true hash value. Cannot use location.hash directly due to bug + // in Firefox where location.hash will always be decoded. + getHash: function(windowOverride) { + var loc = windowOverride ? windowOverride.location : window.location; + var match = loc.href.match(/#(.*)$/); + return match ? match[1] : ''; + }, + // Get the cross-browser normalized URL fragment, either from the URL, // the hash, or the override. getFragment: function(fragment, forcePushState) { @@ -845,10 +983,9 @@ var search = window.location.search; if (search) fragment += search; } else { - fragment = window.location.hash; + fragment = this.getHash(); } } - fragment = decodeURIComponent(fragment); if (!fragment.indexOf(this.options.root)) fragment = fragment.substr(this.options.root.length); return fragment.replace(routeStripper, ''); }, @@ -856,10 +993,11 @@ // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function(options) { + if (History.started) throw new Error("Backbone.history has already been started"); + History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? - if (historyStarted) throw new Error("Backbone.history has already been started"); this.options = _.extend({}, {root: '/'}, this.options, options); this._wantsHashChange = this.options.hashChange !== false; this._wantsPushState = !!this.options.pushState; @@ -867,6 +1005,7 @@ var fragment = this.getFragment(); var docMode = document.documentMode; var oldIE = (isExplorer.exec(navigator.userAgent.toLowerCase()) && (!docMode || docMode <= 7)); + if (oldIE) { this.iframe = $('