From fec027e83203e6705f690469cd39101e4eba3b06 Mon Sep 17 00:00:00 2001 From: Christophe Simonis Date: Tue, 15 Jan 2013 11:40:15 +0100 Subject: [PATCH 001/175] [IMP] reorder modules menus bzr revid: chs@openerp.com-20130115104015-5ytx00t0b5230aaf --- openerp/addons/base/module/module_view.xml | 17 +++-------------- 1 file changed, 3 insertions(+), 14 deletions(-) diff --git a/openerp/addons/base/module/module_view.xml b/openerp/addons/base/module/module_view.xml index 3a43a2591ba..3923c9de3bd 100644 --- a/openerp/addons/base/module/module_view.xml +++ b/openerp/addons/base/module/module_view.xml @@ -171,23 +171,18 @@ - - Modules ir.module.module form kanban,tree,form -

No module found!

You should try others search criteria.

- + @@ -195,20 +190,14 @@ Apps apps - - + Updates apps.updates {} - - + From 7e1a76cdd846a8c455d402fcd76d8baa58a9b2f8 Mon Sep 17 00:00:00 2001 From: Christophe Simonis Date: Tue, 15 Jan 2013 11:40:47 +0100 Subject: [PATCH 002/175] [FIX] setup.py: correct windows install bzr revid: chs@openerp.com-20130115104047-6hrl825bn5pkmoo6 --- setup.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/setup.py b/setup.py index b144924d022..e4e6001d302 100755 --- a/setup.py +++ b/setup.py @@ -43,6 +43,12 @@ def data(): base = os.path.join('pytz', root[len(tzdir) + 1:]) r[base] = [os.path.join(root, f) for f in filenames] + import docutils + dudir = os.path.dirname(docutils.__file__) + for root, _, filenames in os.walk(dudir): + base = os.path.join('docutils', root[len(dudir) + 1:]) + r[base] = [os.path.join(root, f) for f in filenames if not f.endswith(('.py', '.pyc', '.pyo'))] + return r.items() def gen_manifest(): From e2639618f666605e385befb578db3f889a8c035f Mon Sep 17 00:00:00 2001 From: Xavier Morel Date: Thu, 17 Jan 2013 10:27:22 +0100 Subject: [PATCH 003/175] [DOC] remove openerpdev intersphinx, add ref to module doc bzr revid: xmo@openerp.com-20130117092722-6rfhkcu4igrgeo06 --- addons/web/doc/conf.py | 1 - addons/web/doc/module.rst | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/addons/web/doc/conf.py b/addons/web/doc/conf.py index 54434190707..7fe38022ab1 100644 --- a/addons/web/doc/conf.py +++ b/addons/web/doc/conf.py @@ -253,6 +253,5 @@ todo_include_todos = True intersphinx_mapping = { 'python': ('http://docs.python.org/', None), 'openerpserver': ('http://doc.openerp.com/trunk/developers/server', None), - 'openerpdev': ('http://doc.openerp.com/trunk/developers', None), 'openerpcommand': ('http://doc.openerp.com/trunk/developers/command', None), } diff --git a/addons/web/doc/module.rst b/addons/web/doc/module.rst index 1bdb7c14799..8306e885f65 100644 --- a/addons/web/doc/module.rst +++ b/addons/web/doc/module.rst @@ -1,3 +1,5 @@ +.. _module: + Building an OpenERP Web module ============================== From 3574038ffdf78e8c63430ecc92a4f2d916207fda Mon Sep 17 00:00:00 2001 From: Christophe Simonis Date: Thu, 17 Jan 2013 14:29:24 +0100 Subject: [PATCH 004/175] [FIX] apps: install_from_url: fix install condition + better logging bzr revid: chs@openerp.com-20130117132924-ejzbkh5przqi6hwf --- openerp/addons/base/module/module.py | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/openerp/addons/base/module/module.py b/openerp/addons/base/module/module.py index 9e8b68451c5..123bf4124ed 100644 --- a/openerp/addons/base/module/module.py +++ b/openerp/addons/base/module/module.py @@ -2,7 +2,7 @@ ############################################################################## # # OpenERP, Open Source Management Solution -# Copyright (C) 2004-2012 OpenERP S.A. (). +# Copyright (C) 2004-2013 OpenERP S.A. (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as @@ -656,6 +656,7 @@ class module(osv.osv): def install_from_urls(self, cr, uid, urls, context=None): OPENERP = 'openerp' tmp = tempfile.mkdtemp() + _logger.debug('Install from url: %r', urls) try: # 1. Download & unzip missing modules for module_name, url in urls.items(): @@ -672,12 +673,13 @@ class module(osv.osv): zipfile.ZipFile(StringIO(content)).extractall(tmp) assert os.path.isdir(os.path.join(tmp, module_name)) - # 2a. Copy/Replace module source in addons path + # 2a. Copy/Replace module source in addons path for module_name, url in urls.items(): if module_name == OPENERP or not url: continue # OPENERP is special case, handled below, and no URL means local module module_path = modules.get_module_path(module_name, downloaded=True, display_warning=False) bck = backup(module_path, False) + _logger.info('Copy downloaded module `%s` to `%s`', module_name, module_path) shutil.move(os.path.join(tmp, module_name), module_path) if bck: shutil.rmtree(bck) @@ -697,15 +699,22 @@ class module(osv.osv): # then replace the server by the new "base" module server_dir = openerp.tools.config['root_path'] # XXX or dirname() bck = backup(server_dir) + _logger.info('Copy downloaded module `openerp` to `%s`', server_dir) shutil.move(os.path.join(tmp, OPENERP), server_dir) #if bck: # shutil.rmtree(bck) self.update_list(cr, uid, context=context) - ids = self.search(cr, uid, [('name', 'in', urls.keys())], context=context) - if self.search_count(cr, uid, [('id', 'in', ids), ('state', '=', 'installed')], context=context): - # if any to update + with_urls = [m for m, u in urls.items() if u] + downloaded_ids = self.search(cr, uid, [('name', 'in', with_urls)], context=context) + already_installed = self.search(cr, uid, [('id', 'in', downloaded_ids), ('state', '=', 'installed')], context=context) + + to_install_ids = self.search(cr, uid, [('name', 'in', urls.keys()), ('state', '=', 'uninstalled')], context=context) + post_install_action = self.button_immediate_install(cr, uid, to_install_ids, context=context) + + if already_installed: + # in this case, force server restart to reload python code... cr.commit() openerp.service.restart_server() return { @@ -713,7 +722,7 @@ class module(osv.osv): 'tag': 'home', 'params': {'wait': True}, } - return self.button_immediate_install(cr, uid, ids, context=context) + return post_install_action finally: shutil.rmtree(tmp) From 4857a8a020d81ebd375122fb478726103c3f2393 Mon Sep 17 00:00:00 2001 From: Christophe Simonis Date: Thu, 17 Jan 2013 14:51:08 +0100 Subject: [PATCH 005/175] [FIX] module loading: call adapt_version() instead of computing it ourself bzr revid: chs@openerp.com-20130117135108-a4wt4wtbtfdwiui3 --- openerp/modules/loading.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/openerp/modules/loading.py b/openerp/modules/loading.py index fb68642f137..638a40c9fa8 100644 --- a/openerp/modules/loading.py +++ b/openerp/modules/loading.py @@ -3,7 +3,7 @@ # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2009 Tiny SPRL (). -# Copyright (C) 2010-2012 OpenERP s.a. (). +# Copyright (C) 2010-2013 OpenERP s.a. (). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as @@ -36,14 +36,12 @@ import openerp.modules.graph import openerp.modules.migration import openerp.osv as osv import openerp.pooler as pooler -import openerp.release as release import openerp.tools as tools from openerp import SUPERUSER_ID -from openerp import SUPERUSER_ID from openerp.tools.translate import _ from openerp.modules.module import initialize_sys_path, \ - load_openerp_module, init_module_models + load_openerp_module, init_module_models, adapt_version _logger = logging.getLogger(__name__) @@ -213,7 +211,7 @@ def load_module_graph(cr, graph, status=None, perform_checks=True, skip_modules= migrations.migrate_module(package, 'post') - ver = release.major_version + '.' + package.data['version'] + ver = adapt_version(package.data['version']) # Set new modules and dependencies modobj.write(cr, SUPERUSER_ID, [module_id], {'state': 'installed', 'latest_version': ver}) # Update translations for all installed languages From 66cadcdb18c9ce0f48a05cf7d13cb98ed2f171e5 Mon Sep 17 00:00:00 2001 From: Anael Closson Date: Fri, 10 May 2013 17:19:34 +0200 Subject: [PATCH 007/175] [FIX] OPW 591344 : internal reports don't show images Cleaner method, and shows images. bzr revid: acl@openerp.com-20130510151934-e2kvwiexdzp3zc12 --- openerp/report/render/rml2pdf/trml2pdf.py | 54 +++++++---------------- 1 file changed, 17 insertions(+), 37 deletions(-) diff --git a/openerp/report/render/rml2pdf/trml2pdf.py b/openerp/report/render/rml2pdf/trml2pdf.py index e8d6375c98e..153eff14b65 100644 --- a/openerp/report/render/rml2pdf/trml2pdf.py +++ b/openerp/report/render/rml2pdf/trml2pdf.py @@ -82,53 +82,33 @@ def _open_image(filename, path=None): pass raise IOError("File %s cannot be found in image path" % filename) + class NumberedCanvas(canvas.Canvas): def __init__(self, *args, **kwargs): canvas.Canvas.__init__(self, *args, **kwargs) - self._codes = [] - self._flag=False - self._pageCount=0 - self._currentPage =0 - self._pageCounter=0 - self.pages={} + self._saved_page_states = [] def showPage(self): - self._currentPage +=1 - if not self._flag: - self._pageCount += 1 - else: - self.pages.update({self._currentPage:self._pageCount}) - self._codes.append({'code': self._code, 'stack': self._codeStack}) + self._saved_page_states.append(dict(self.__dict__)) self._startPage() - self._flag=False - - def pageCount(self): - if self.pages.get(self._pageCounter,False): - self._pageNumber=0 - self._pageCounter +=1 - key=self._pageCounter - if not self.pages.get(key,False): - while not self.pages.get(key,False): - key += 1 - self.setFont("Helvetica", 8) - self.drawRightString((self._pagesize[0]-30), (self._pagesize[1]-40), - " %(this)i / %(total)i" % { - 'this': self._pageNumber+1, - 'total': self.pages.get(key,False), - } - ) def save(self): """add page info to each page (page x of y)""" - # reset page counter - self._pageNumber = 0 - for code in self._codes: - self._code = code['code'] - self._codeStack = code['stack'] - self.pageCount() + num_pages = len(self._saved_page_states) + for state in self._saved_page_states: + self.__dict__.update(state) + self.draw_page_number(num_pages) canvas.Canvas.showPage(self) -# self.restoreState() - self._doc.SaveToFile(self._filename, self) + canvas.Canvas.save(self) + + def draw_page_number(self, page_count): + self.drawRightString((self._pagesize[0]-30), (self._pagesize[1]-40), + " %(this)i / %(total)i" % { + 'this': self._pageNumber, + 'total': page_count, + } + ) + class PageCount(platypus.Flowable): def __init__(self, story_count=0): From 46e89d6dd1427ac5c7fa144f3b36e6ea1779771d Mon Sep 17 00:00:00 2001 From: Mohammed Shekha Date: Thu, 20 Jun 2013 16:16:06 +0530 Subject: [PATCH 008/175] [FIX]Fixed the issue of recurrent rule, there is no need of passing 'Z' after end_date as end_date converted to UNTIL parameter in rrule, and date given in UNTIL is not converted to any other timezone until you specifically passed timezone difference or timezone name like 20130620T121012+3:30 or 20130620T121012TZOFFSET, currently Z creates issue when recurrent rule is created with end_date, TypeError: can't compare offset-naive and offset-aware datetimes. bzr revid: msh@openerp.com-20130620104606-g3dyr1mafzo8fpgg --- addons/base_calendar/base_calendar.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/addons/base_calendar/base_calendar.py b/addons/base_calendar/base_calendar.py index 25bfcac448c..41a142cde68 100644 --- a/addons/base_calendar/base_calendar.py +++ b/addons/base_calendar/base_calendar.py @@ -1269,7 +1269,7 @@ rule or repeating pattern of time to exclude from the recurring rule."), def get_end_date(data): if data.get('end_date'): - data['end_date_new'] = ''.join((re.compile('\d')).findall(data.get('end_date'))) + 'T235959Z' + data['end_date_new'] = ''.join((re.compile('\d')).findall(data.get('end_date'))) + 'T235959' return (data.get('end_type') == 'count' and (';COUNT=' + str(data.get('count'))) or '') +\ ((data.get('end_date_new') and data.get('end_type') == 'end_date' and (';UNTIL=' + data.get('end_date_new'))) or '') From 3276861ff6125d02e08b5c5b12b75925e056c4bc Mon Sep 17 00:00:00 2001 From: "Xavier Fernandez http://www.smile.fr" <> Date: Wed, 28 Aug 2013 17:21:17 +0200 Subject: [PATCH 009/175] [FIX] port Xavier Fernandez's fix for Bug #971412: Translations export has no fixed order lp bug: https://launchpad.net/bugs/971412 fixed bzr revid: ls@numerigraphe.com-20130828152117-e1h0yljgbn538v9o --- openerp/tools/translate.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/openerp/tools/translate.py b/openerp/tools/translate.py index 41113b8ccd9..53762b87970 100644 --- a/openerp/tools/translate.py +++ b/openerp/tools/translate.py @@ -458,7 +458,8 @@ def trans_export(lang, modules, buffer, format, cr): row.setdefault('tnrs', []).append((type, name, res_id)) row.setdefault('comments', set()).update(comments) - for src, row in grouped_rows.items(): + for src in sorted(grouped_rows): + row = grouped_rows[src] if not lang: # translation template, so no translation value row['translation'] = '' From 1f3a482f4fc309262802b980e143234a56b9503d Mon Sep 17 00:00:00 2001 From: Lionel Sausin Date: Thu, 29 Aug 2013 09:50:35 +0200 Subject: [PATCH 010/175] [REF] avoid the lookup in sorted translation export as suggested by Guewen Baconnier @ Camptocamp bzr revid: ls@numerigraphe.com-20130829075035-lml81a7bbn66c8qu --- openerp/tools/translate.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/openerp/tools/translate.py b/openerp/tools/translate.py index 53762b87970..6e9eb50f162 100644 --- a/openerp/tools/translate.py +++ b/openerp/tools/translate.py @@ -458,8 +458,7 @@ def trans_export(lang, modules, buffer, format, cr): row.setdefault('tnrs', []).append((type, name, res_id)) row.setdefault('comments', set()).update(comments) - for src in sorted(grouped_rows): - row = grouped_rows[src] + for src, row in sorted(grouped_rows.items()): if not lang: # translation template, so no translation value row['translation'] = '' From 0dcc62426c3689191798fbe33717eea5d4659a96 Mon Sep 17 00:00:00 2001 From: Yanina Aular Date: Fri, 15 Nov 2013 17:57:17 -0430 Subject: [PATCH 011/175] [FIX] function field with wrong type int instead of integer bzr revid: yanina.aular@vauxoo.com-20131115222717-12bplq7rnv3rorbm --- addons/project/project.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/addons/project/project.py b/addons/project/project.py index 5bd2e604368..c7b394ad376 100644 --- a/addons/project/project.py +++ b/addons/project/project.py @@ -288,7 +288,8 @@ class project(osv.osv): help="The kind of document created when an email is received on this project's email alias"), 'privacy_visibility': fields.selection(_visibility_selection, 'Privacy / Visibility', required=True), 'state': fields.selection([('template', 'Template'),('draft','New'),('open','In Progress'), ('cancelled', 'Cancelled'),('pending','Pending'),('close','Closed')], 'Status', required=True,), - 'doc_count':fields.function(_get_attached_docs, string="Number of documents attached", type='int') + 'doc_count':fields.function(_get_attached_docs, string="Number of documents attached", + type='integer') } def _get_type_common(self, cr, uid, context): From f6349ffb7fd9c075573953be2ac0f0dc20520743 Mon Sep 17 00:00:00 2001 From: Leonardo Pistone Date: Wed, 18 Dec 2013 17:45:26 +0100 Subject: [PATCH 012/175] [merge] [fix] action should return True lp bug: https://launchpad.net/bugs/1262265 fixed bzr revid: leonardo.pistone@camptocamp.com-20131218164526-rgyo6p9hlpk28sxg --- addons/mrp_repair/mrp_repair.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/addons/mrp_repair/mrp_repair.py b/addons/mrp_repair/mrp_repair.py index 9c0ab0e2c18..9335d395714 100644 --- a/addons/mrp_repair/mrp_repair.py +++ b/addons/mrp_repair/mrp_repair.py @@ -350,7 +350,8 @@ class mrp_repair(osv.osv): return self.write(cr,uid,ids,{'state':'cancel'}) def wkf_invoice_create(self, cr, uid, ids, *args): - return self.action_invoice_create(cr, uid, ids) + self.action_invoice_create(cr, uid, ids) + return True def action_invoice_create(self, cr, uid, ids, group=False, context=None): """ Creates invoice(s) for repair order. From 855836e96e42f1be3075eaa87628184f52112b80 Mon Sep 17 00:00:00 2001 From: Stephane Wirtel Date: Thu, 27 Feb 2014 13:56:48 +0100 Subject: [PATCH 013/175] [IMP] Move the netsvc.dispatch_rpc function from netsvc to openerp.http bzr revid: stw@openerp.com-20140227125648-kunaefr22y28honx --- openerp/http.py | 96 +++++++++++++++++++++++++++++++--- openerp/netsvc.py | 86 ------------------------------ openerp/service/wsgi_server.py | 2 +- openerp/tools/__init__.py | 2 +- openerp/tools/debugger.py | 8 +++ 5 files changed, 98 insertions(+), 96 deletions(-) create mode 100644 openerp/tools/debugger.py diff --git a/openerp/http.py b/openerp/http.py index bcd7511d769..ea1e82ed4c6 100644 --- a/openerp/http.py +++ b/openerp/http.py @@ -21,8 +21,10 @@ import time import traceback import urlparse import warnings +from pprint import pformat import babel.core +import psutil import psycopg2 import simplejson import werkzeug.contrib.sessions @@ -34,6 +36,7 @@ import werkzeug.wrappers import werkzeug.wsgi import openerp +import openerp.netsvc from openerp.service import security, model as service_model import openerp.tools @@ -50,6 +53,83 @@ request = _request_stack() A global proxy that always redirect to the current request object. """ +def replace_request_password(args): + # password is always 3rd argument in a request, we replace it in RPC logs + # so it's easier to forward logs for diagnostics/debugging purposes... + if len(args) > 2: + args = list(args) + args[2] = '*' + return tuple(args) + +def log(logger, level, prefix, msg, depth=None): + indent='' + indent_after=' '*len(prefix) + for line in (prefix+pformat(msg, depth=depth)).split('\n'): + logger.log(level, indent+line) + indent=indent_after + +def dispatch_rpc(service_name, method, params): + """ Handle a RPC call. + + This is pure Python code, the actual marshalling (from/to XML-RPC) is done + in a upper layer. + """ + try: + rpc_request = logging.getLogger(__name__ + '.rpc.request') + rpc_response = logging.getLogger(__name__ + '.rpc.response') + rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG) + rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG) + if rpc_request_flag or rpc_response_flag: + start_time = time.time() + start_rss, start_vms = 0, 0 + start_rss, start_vms = psutil.Process(os.getpid()).get_memory_info() + if rpc_request and rpc_response_flag: + log(rpc_request, logging.DEBUG, '%s.%s' % (service_name, method), replace_request_password(params)) + + threading.current_thread().uid = None + threading.current_thread().dbname = None + if service_name == 'common': + dispatch = openerp.service.common.dispatch + elif service_name == 'db': + dispatch = openerp.service.db.dispatch + elif service_name == 'object': + dispatch = openerp.service.model.dispatch + elif service_name == 'report': + dispatch = openerp.service.report.dispatch + else: + dispatch = openerp.service.wsgi_server.rpc_handlers.get(service_name) + result = dispatch(method, params) + + if rpc_request_flag or rpc_response_flag: + end_time = time.time() + end_rss, end_vms = 0, 0 + end_rss, end_vms = psutil.Process(os.getpid()).get_memory_info() + logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (service_name, method, end_time - start_time, start_vms / 1024, end_vms / 1024, (end_vms - start_vms)/1024) + if rpc_response_flag: + log(rpc_response, logging.DEBUG, logline, result) + else: + log(rpc_request, logging.DEBUG, logline, replace_request_password(params), depth=1) + + return result + except openerp.osv.orm.except_orm: + raise + except openerp.exceptions.AccessError: + raise + except openerp.exceptions.AccessDenied: + raise + except openerp.exceptions.Warning: + raise + except openerp.exceptions.RedirectWarning: + raise + except openerp.exceptions.DeferredException, e: + _logger.exception(openerp.tools.exception_to_unicode(e)) + openerp.tools.debugger.post_mortem(openerp.tools.config, e.traceback) + raise + except Exception, e: + _logger.exception(openerp.tools.exception_to_unicode(e)) + openerp.tools.debugger.post_mortem(openerp.tools.config, sys.exc_info()) + raise + def local_redirect(path, query=None, keep_hash=False, forward_debug=True, code=303): url = path if not query: @@ -618,7 +698,7 @@ class SessionExpiredException(Exception): class Service(object): """ .. deprecated:: 8.0 - Use ``openerp.netsvc.dispatch_rpc()`` instead. + Use ``dispatch_rpc()`` instead. """ def __init__(self, session, service_name): self.session = session @@ -626,7 +706,7 @@ class Service(object): def __getattr__(self, method): def proxy_method(*args): - result = openerp.netsvc.dispatch_rpc(self.service_name, method, args) + result = dispatch_rpc(self.service_name, method, args) return result return proxy_method @@ -699,7 +779,7 @@ class OpenERPSession(werkzeug.contrib.sessions.Session): HTTP_HOST=wsgienv['HTTP_HOST'], REMOTE_ADDR=wsgienv['REMOTE_ADDR'], ) - uid = openerp.netsvc.dispatch_rpc('common', 'authenticate', [db, login, password, env]) + uid = dispatch_rpc('common', 'authenticate', [db, login, password, env]) else: security.check(db, uid, password) self.db = db @@ -803,14 +883,14 @@ class OpenERPSession(werkzeug.contrib.sessions.Session): def send(self, service_name, method, *args): """ .. deprecated:: 8.0 - Use ``openerp.netsvc.dispatch_rpc()`` instead. + Use ``dispatch_rpc()`` instead. """ - return openerp.netsvc.dispatch_rpc(service_name, method, args) + return dispatch_rpc(service_name, method, args) def proxy(self, service): """ .. deprecated:: 8.0 - Use ``openerp.netsvc.dispatch_rpc()`` instead. + Use ``dispatch_rpc()`` instead. """ return Service(self, service) @@ -1184,7 +1264,7 @@ class Root(object): return request.registry['ir.http'].routing_map() def db_list(force=False, httprequest=None): - dbs = openerp.netsvc.dispatch_rpc("db", "list", [force]) + dbs = dispatch_rpc("db", "list", [force]) return db_filter(dbs, httprequest=httprequest) def db_filter(dbs, httprequest=None): @@ -1229,7 +1309,7 @@ class CommonController(Controller): @route('/jsonrpc', type='json', auth="none") def jsonrpc(self, service, method, args): """ Method used by client APIs to contact OpenERP. """ - return openerp.netsvc.dispatch_rpc(service, method, args) + return dispatch_rpc(service, method, args) @route('/gen_session_id', type='json', auth="none") def gen_session_id(self): diff --git a/openerp/netsvc.py b/openerp/netsvc.py index 755f6513b25..f19162cde5a 100644 --- a/openerp/netsvc.py +++ b/openerp/netsvc.py @@ -26,10 +26,6 @@ import os import release import sys import threading -import time -import types -from pprint import pformat -import psutil import tools import openerp @@ -188,86 +184,4 @@ def init_alternative_logger(): logger.addHandler(handler) logger.setLevel(logging.ERROR) -def replace_request_password(args): - # password is always 3rd argument in a request, we replace it in RPC logs - # so it's easier to forward logs for diagnostics/debugging purposes... - if len(args) > 2: - args = list(args) - args[2] = '*' - return tuple(args) - -def log(logger, level, prefix, msg, depth=None): - indent='' - indent_after=' '*len(prefix) - for line in (prefix+pformat(msg, depth=depth)).split('\n'): - logger.log(level, indent+line) - indent=indent_after - -def dispatch_rpc(service_name, method, params): - """ Handle a RPC call. - - This is pure Python code, the actual marshalling (from/to XML-RPC) is done - in a upper layer. - """ - try: - rpc_request = logging.getLogger(__name__ + '.rpc.request') - rpc_response = logging.getLogger(__name__ + '.rpc.response') - rpc_request_flag = rpc_request.isEnabledFor(logging.DEBUG) - rpc_response_flag = rpc_response.isEnabledFor(logging.DEBUG) - if rpc_request_flag or rpc_response_flag: - start_time = time.time() - start_rss, start_vms = 0, 0 - start_rss, start_vms = psutil.Process(os.getpid()).get_memory_info() - if rpc_request and rpc_response_flag: - log(rpc_request,logging.DEBUG,'%s.%s'%(service_name,method), replace_request_password(params)) - - threading.current_thread().uid = None - threading.current_thread().dbname = None - if service_name == 'common': - dispatch = openerp.service.common.dispatch - elif service_name == 'db': - dispatch = openerp.service.db.dispatch - elif service_name == 'object': - dispatch = openerp.service.model.dispatch - elif service_name == 'report': - dispatch = openerp.service.report.dispatch - else: - dispatch = openerp.service.wsgi_server.rpc_handlers.get(service_name) - result = dispatch(method, params) - - if rpc_request_flag or rpc_response_flag: - end_time = time.time() - end_rss, end_vms = 0, 0 - end_rss, end_vms = psutil.Process(os.getpid()).get_memory_info() - logline = '%s.%s time:%.3fs mem: %sk -> %sk (diff: %sk)' % (service_name, method, end_time - start_time, start_vms / 1024, end_vms / 1024, (end_vms - start_vms)/1024) - if rpc_response_flag: - log(rpc_response,logging.DEBUG, logline, result) - else: - log(rpc_request,logging.DEBUG, logline, replace_request_password(params), depth=1) - - return result - except openerp.osv.orm.except_orm: - raise - except openerp.exceptions.AccessError: - raise - except openerp.exceptions.AccessDenied: - raise - except openerp.exceptions.Warning: - raise - except openerp.exceptions.RedirectWarning: - raise - except openerp.exceptions.DeferredException, e: - _logger.exception(tools.exception_to_unicode(e)) - post_mortem(e.traceback) - raise - except Exception, e: - _logger.exception(tools.exception_to_unicode(e)) - post_mortem(sys.exc_info()) - raise - -def post_mortem(info): - if tools.config['debug_mode'] and isinstance(info[2], types.TracebackType): - import pdb - pdb.post_mortem(info[2]) - # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/openerp/service/wsgi_server.py b/openerp/service/wsgi_server.py index 506a07d0295..b31736ba998 100644 --- a/openerp/service/wsgi_server.py +++ b/openerp/service/wsgi_server.py @@ -72,7 +72,7 @@ def xmlrpc_return(start_response, service, method, params, string_faultcode=Fals # This also mimics SimpleXMLRPCDispatcher._marshaled_dispatch() for # exception handling. try: - result = openerp.netsvc.dispatch_rpc(service, method, params) + result = openerp.http.dispatch_rpc(service, method, params) response = xmlrpclib.dumps((result,), methodresponse=1, allow_none=False, encoding=None) except Exception, e: if string_faultcode: diff --git a/openerp/tools/__init__.py b/openerp/tools/__init__.py index 18dab088440..6ad2cca4724 100644 --- a/openerp/tools/__init__.py +++ b/openerp/tools/__init__.py @@ -34,7 +34,7 @@ from yaml_import import * from sql import * from float_utils import * from mail import * - +from debugger import * # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/openerp/tools/debugger.py b/openerp/tools/debugger.py new file mode 100644 index 00000000000..293d4052513 --- /dev/null +++ b/openerp/tools/debugger.py @@ -0,0 +1,8 @@ +# -*- coding: utf-8 -*- +# Copyright: 2014 - OpenERP S.A. +import types + +def post_mortem(config, info): + if config['debug_mode'] and isinstance(info[2], types.TracebackType): + import pdb + pdb.post_mortem(info[2]) From 3f779a5cae7bd4ca0399cf06e331f5047ec0e343 Mon Sep 17 00:00:00 2001 From: Stephane Wirtel Date: Fri, 28 Feb 2014 17:10:55 +0100 Subject: [PATCH 014/175] [IMP] Add the ir_logging object where we will store the log messages (exception, error and warning) bzr revid: stw@openerp.com-20140228161055-98897xl1r46mf9mr --- openerp/addons/base/ir/__init__.py | 1 + openerp/addons/base/ir/ir_logging.py | 52 ++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 openerp/addons/base/ir/ir_logging.py diff --git a/openerp/addons/base/ir/__init__.py b/openerp/addons/base/ir/__init__.py index b3df5bcbccb..9aa1e7c42a2 100644 --- a/openerp/addons/base/ir/__init__.py +++ b/openerp/addons/base/ir/__init__.py @@ -39,6 +39,7 @@ import ir_mail_server import ir_fields import ir_qweb import ir_http +import ir_logging # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: diff --git a/openerp/addons/base/ir/ir_logging.py b/openerp/addons/base/ir/ir_logging.py new file mode 100644 index 00000000000..66708aa729a --- /dev/null +++ b/openerp/addons/base/ir/ir_logging.py @@ -0,0 +1,52 @@ +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2014 OpenERP SA () +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## +import logging + +from openerp.osv import osv, fields +from openerp.tools.translate import _ + +class ir_logging(osv.Model): + _name = 'ir.logging' + + EXCEPTIONS_TYPE = [ + ('client', 'Client'), + ('server', 'Server') + ] + + _columns = { + 'name': fields.char('Name', required=True), + 'type': fields.selection(EXCEPTIONS_TYPE, string='Type', required=True, select=True), + 'dbname': fields.char('Database Name'), + 'level': fields.char('Level'), + 'message': fields.text('Message', required=True), + 'exception': fields.text('Exception'), + 'path': fields.char('Path', required=True), + 'func': fields.char('Function', required=True), + 'line': fields.char('Line', required=True), + } + + def call_function(self, cr, uid, ids, context=None): + logger = logging.getLogger() + logger.error("I think there is an error") + try: + raise Exception("I want to kill your process...") + except Exception, ex: + logger.exception("Please log me into the database") + return True \ No newline at end of file From 047d071a48630e3db2922d404d3d7f5395a88245 Mon Sep 17 00:00:00 2001 From: Stephane Wirtel Date: Fri, 28 Feb 2014 17:11:47 +0100 Subject: [PATCH 015/175] [IMP] Add a new Logging Handler, where we will store in the database of OpenERP. this database can be overrided via the --log-pgsql-database bzr revid: stw@openerp.com-20140228161147-s9nnrfq2tc94vq5p --- openerp/http.py | 12 ++--- openerp/loggers/__init__.py | 1 + openerp/loggers/handlers.py | 100 ++++++++++++++++++++++++++++++++++++ openerp/netsvc.py | 51 ++++++++++++++---- openerp/tools/config.py | 24 ++++++--- 5 files changed, 162 insertions(+), 26 deletions(-) create mode 100644 openerp/loggers/__init__.py create mode 100644 openerp/loggers/handlers.py diff --git a/openerp/http.py b/openerp/http.py index ea1e82ed4c6..92fe03a6232 100644 --- a/openerp/http.py +++ b/openerp/http.py @@ -111,15 +111,9 @@ def dispatch_rpc(service_name, method, params): log(rpc_request, logging.DEBUG, logline, replace_request_password(params), depth=1) return result - except openerp.osv.orm.except_orm: - raise - except openerp.exceptions.AccessError: - raise - except openerp.exceptions.AccessDenied: - raise - except openerp.exceptions.Warning: - raise - except openerp.exceptions.RedirectWarning: + except (openerp.osv.orm.except_orm, openerp.exceptions.AccessError, \ + openerp.exceptions.AccessDenied, openerp.exceptions.Warning, \ + openerp.exceptions.RedirectWarning): raise except openerp.exceptions.DeferredException, e: _logger.exception(openerp.tools.exception_to_unicode(e)) diff --git a/openerp/loggers/__init__.py b/openerp/loggers/__init__.py new file mode 100644 index 00000000000..19b76b55b64 --- /dev/null +++ b/openerp/loggers/__init__.py @@ -0,0 +1 @@ +from handlers import PostgreSQLHandler \ No newline at end of file diff --git a/openerp/loggers/handlers.py b/openerp/loggers/handlers.py new file mode 100644 index 00000000000..763aa079195 --- /dev/null +++ b/openerp/loggers/handlers.py @@ -0,0 +1,100 @@ +############################################################################## +# +# OpenERP, Open Source Management Solution +# Copyright (C) 2014 OpenERP SA () +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see . +# +############################################################################## + +import contextlib +import datetime +import logging +import threading + +import psycopg2 + +from openerp import tools + +# The PostgreSQL Handler for the logging module, will be used by OpenERP to store the logs +# in the database, --log-pgsql-database=YOUR_DBNAME +# By default the system will use the current database + +class PostgreSQLHandler(logging.Handler): + @contextlib.contextmanager + def create_connection(self): + db_name = None + + db_name_from_cli = tools.config['log_pgsql_database'] + if not db_name_from_cli: + # If there is no database, and only in this case, we are going to use the database + # from the current thread and create a connection to this database. + + current_thread = threading.current_thread() + + db_name_from_thread = getattr(current_thread, 'dbname', None) + if isinstance(db_name_from_thread, basestring): + db_name = db_name_from_thread + else: + db_name = db_name_from_cli + + if not db_name: + return + + parameters = { + 'user': tools.config['db_user'] or None, + 'password': tools.config['db_password'] or None, + 'host': tools.config['db_host'] or None, + 'port': tools.config['db_port'] or None, + 'database': db_name, + } + try: + connection = psycopg2.connect(**parameters) + + if connection: + yield connection + except Exception, ex: # Use a specific exception + print ex + + def emit(self, record): + # We use a context manager to be tolerant to the errors (error of connections,...) + with self.create_connection() as conn: + exception = False + if record.exc_info: + exception = record.exc_text + + now = datetime.datetime.utcnow() + + current_thread = threading.current_thread() + uid = getattr(current_thread, 'uid', False) + dbname = getattr(current_thread, 'dbname', False) + + parameters = ( + now, uid, now, uid, 'server', dbname, record.name, + logging.getLevelName(record.levelno), record.msg, exception, + record.filename, record.funcName, record.lineno + ) + + with conn.cursor() as cursor: + cursor.execute(""" + INSERT INTO ir_logging( + create_date, create_uid, write_date, write_uid, + type, dbname, name, level, message, exception, path, func, + line + ) + VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) + """, + parameters + ) + conn.commit() diff --git a/openerp/netsvc.py b/openerp/netsvc.py index f19162cde5a..250cd52a1d1 100644 --- a/openerp/netsvc.py +++ b/openerp/netsvc.py @@ -29,6 +29,7 @@ import threading import tools import openerp +import openerp.loggers _logger = logging.getLogger(__name__) @@ -85,6 +86,19 @@ class ColoredFormatter(DBFormatter): record.levelname = COLOR_PATTERN % (30 + fg_color, 40 + bg_color, record.levelname) return DBFormatter.format(self, record) +import platform +def is_posix_operating_system(): + return os.name == 'posix' + +def is_windows_operating_system(): + return os.name == 'nt' + +def is_linux_operating_system(): + return is_posix_operating_system() and platform.system() == 'Linux' + +def is_macosx_operating_system(): + return is_posix_operating_system() and platform.system() == 'Darwin' + def init_logger(): from tools.translate import resetlocale resetlocale() @@ -94,24 +108,32 @@ def init_logger(): if tools.config['syslog']: # SysLog Handler - if os.name == 'nt': + if is_windows_operating_system(): handler = logging.handlers.NTEventLogHandler("%s %s" % (release.description, release.version)) - else: + elif is_linux_operating_system(): handler = logging.handlers.SysLogHandler('/dev/log') - format = '%s %s' % (release.description, release.version) \ - + ':%(dbname)s:%(levelname)s:%(name)s:%(message)s' + elif is_macosx_operating_system(): # There is no /dev/log on OSX + handler = logging.handlers.SysLogHandler('/var/run/log') + else: + raise Exception("There is no syslog handler for this Operating System: %s", platform.system()) + + format = '%s %s' % (release.description, release.version) + ':%(dbname)s:%(levelname)s:%(name)s:%(message)s' elif tools.config['logfile']: # LogFile Handler logf = tools.config['logfile'] try: + # We check we have the right location for the log files dirname = os.path.dirname(logf) if dirname and not os.path.isdir(dirname): os.makedirs(dirname) + if tools.config['logrotate'] is not False: - handler = logging.handlers.TimedRotatingFileHandler(logf,'D',1,30) - elif os.name == 'posix': + handler = logging.handlers.TimedRotatingFileHandler(filename=logf, when='D', interval=1, backupCount=30) + + elif is_posix_operating_system(): handler = logging.handlers.WatchedFileHandler(logf) + else: handler = logging.handlers.FileHandler(logf) except Exception: @@ -125,12 +147,14 @@ def init_logger(): # behind Apache with mod_wsgi, handler.stream will have type mod_wsgi.Log, # which has no fileno() method. (mod_wsgi.Log is what is being bound to # sys.stderr when the logging.StreamHandler is being constructed above.) - if isinstance(handler, logging.StreamHandler) \ - and hasattr(handler.stream, 'fileno') \ - and os.isatty(handler.stream.fileno()): + def has_fileno(stream): + return hasattr(stream, 'fileno') and os.isatty(stream.fileno()) + + if isinstance(handler, logging.StreamHandler) and has_fileno(handler.stream): formatter = ColoredFormatter(format) else: formatter = DBFormatter(format) + handler.setFormatter(formatter) # Configure handlers @@ -141,7 +165,9 @@ def init_logger(): logging_configurations = DEFAULT_LOG_CONFIGURATION + pseudo_config + logconfig for logconfig_item in logging_configurations: loggername, level = logconfig_item.split(':') + level = getattr(logging, level, logging.INFO) + logger = logging.getLogger(loggername) logger.handlers = [] logger.setLevel(level) @@ -149,6 +175,13 @@ def init_logger(): if loggername != '': logger.propagate = False + # magic ;-) + # we manage the connection in the postgresqlhandler + postgresqlHandler = openerp.loggers.handlers.PostgreSQLHandler() + postgresqlHandler.setLevel(logging.WARNING) + logger = logging.getLogger() + logger.addHandler(postgresqlHandler) + for logconfig_item in logging_configurations: _logger.debug('logger level set: "%s"', logconfig_item) diff --git a/openerp/tools/config.py b/openerp/tools/config.py index 07435075f8d..ab1eab8a52a 100644 --- a/openerp/tools/config.py +++ b/openerp/tools/config.py @@ -72,9 +72,10 @@ class configmanager(object): } # Not exposed in the configuration file. - self.blacklist_for_save = set( - ['publisher_warranty_url', 'load_language', 'root_path', - 'init', 'save', 'config', 'update', 'stop_after_init']) + self.blacklist_for_save = set([ + 'publisher_warranty_url', 'load_language', 'root_path', + 'init', 'save', 'config', 'update', 'stop_after_init' + ]) # dictionary mapping option destination (keys in self.options) to MyOptions. self.casts = {} @@ -83,7 +84,10 @@ class configmanager(object): self.config_file = fname self.has_ssl = check_ssl() - self._LOGLEVELS = dict([(getattr(loglevels, 'LOG_%s' % x), getattr(logging, x)) for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET')]) + self._LOGLEVELS = dict([ + (getattr(loglevels, 'LOG_%s' % x), getattr(logging, x)) + for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET') + ]) version = "%s %s" % (release.description, release.version) self.parser = parser = optparse.OptionParser(version=version, option_class=MyOption) @@ -176,12 +180,16 @@ class configmanager(object): group.add_option('--log-response', action="append_const", dest="log_handler", const="openerp.netsvc.rpc.response:DEBUG", help='shortcut for --log-handler=openerp.netsvc.rpc.response:DEBUG') group.add_option('--log-web', action="append_const", dest="log_handler", const="openerp.addons.web.http:DEBUG", help='shortcut for --log-handler=openerp.addons.web.http:DEBUG') group.add_option('--log-sql', action="append_const", dest="log_handler", const="openerp.sql_db:DEBUG", help='shortcut for --log-handler=openerp.sql_db:DEBUG') + group.add_option('--log-pgsql-database', dest='log_pgsql_database', help="database where OpenERP will store the exceptions", my_default=False) # For backward-compatibility, map the old log levels to something # quite close. - levels = ['info', 'debug_rpc', 'warn', 'test', 'critical', - 'debug_sql', 'error', 'debug', 'debug_rpc_answer', 'notset'] - group.add_option('--log-level', dest='log_level', type='choice', choices=levels, - my_default='info', help='specify the level of the logging. Accepted values: ' + str(levels) + ' (deprecated option).') + levels = [ + 'info', 'debug_rpc', 'warn', 'test', 'critical', + 'debug_sql', 'error', 'debug', 'debug_rpc_answer', 'notset' + ] + group.add_option('--log-level', dest='log_level', type='choice', + choices=levels, my_default='info', + help='specify the level of the logging. Accepted values: %s (deprecated option).' % (levels,)) parser.add_option_group(group) From 2569e07191422bbd3535ded11825425de4247dd1 Mon Sep 17 00:00:00 2001 From: Christophe Matthieu Date: Mon, 3 Mar 2014 12:39:46 +0100 Subject: [PATCH 016/175] [IMP] website: snippet don't use snipet id bzr revid: chm@openerp.com-20140303113946-d70yd8nmew1k3z37 --- .../src/js/website.snippets.animation.js | 11 +- .../static/src/js/website.snippets.editor.js | 899 +++++++++--------- .../website/static/src/xml/website.editor.xml | 2 +- addons/website/views/snippets.xml | 178 ++-- 4 files changed, 553 insertions(+), 537 deletions(-) diff --git a/addons/website/static/src/js/website.snippets.animation.js b/addons/website/static/src/js/website.snippets.animation.js index bc2ea064731..01e4c5239cb 100644 --- a/addons/website/static/src/js/website.snippets.animation.js +++ b/addons/website/static/src/js/website.snippets.animation.js @@ -5,13 +5,18 @@ if (!website.snippet) website.snippet = {}; website.snippet.readyAnimation = []; - website.snippet.start_animation = function () { + website.snippet.start_animation = function ($target) { for (var k in website.snippet.animationRegistry) { var Animation = website.snippet.animationRegistry[k]; var selector = "[data-snippet-id='"+k+"']"; if (Animation.prototype.selector) { selector += ", " + Animation.prototype.selector; } + if ($target) { + if ($target.is(selector)) selector = $target; + else continue; + } + $(selector).each(function() { var $snipped_id = $(this); if ( !$snipped_id.parents("#oe_snippets").length && @@ -32,7 +37,7 @@ } }); }; - $(document).ready(website.snippet.start_animation); + $(document).ready(function () {website.snippet.start_animation();}); website.snippet.animationRegistry = {}; @@ -67,7 +72,7 @@ }); website.snippet.animationRegistry.parallax = website.snippet.Animation.extend({ - parallax: ".parallax", + selector: ".parallax", start: function () { var self = this; setTimeout(function () {self.set_values();}); diff --git a/addons/website/static/src/js/website.snippets.editor.js b/addons/website/static/src/js/website.snippets.editor.js index 23c5956ebf4..addd610e47b 100644 --- a/addons/website/static/src/js/website.snippets.editor.js +++ b/addons/website/static/src/js/website.snippets.editor.js @@ -167,6 +167,9 @@ 'snippet-style-id' : style_id, 'selector': $style.data('selector'), '$el': $style, + 'selector-siblings': $style.data('selector-siblings'), + 'selector-children': $style.data('selector-children'), + 'selector-vertical-children': $style.data('selector-vertical-children') }; }); $styles.addClass("hidden"); @@ -219,12 +222,19 @@ return; } snipped_event_flag = true; + var selector = []; + for (var k in website.snippet.styles) { + selector.push(website.snippet.styles[k].selector); + } + selector = selector.join(","); + setTimeout(function () {snipped_event_flag = false;}, 0); var $target = $(event.srcElement); - if (!$target.attr("data-snippet-id")) { - $target = $target.parents("[data-snippet-id]:first"); + + if (!$target.is(selector)) { + $target = $target.parents(selector).first(); } - if (!$target.attr("data-oe-model") && !$target.parents("[data-oe-model]:first").length) { + if (!self.dom_filter($target).length) { $target = false; } if (self.$active_snipped_id && self.$active_snipped_id.is($target)) { @@ -281,8 +291,7 @@ if (typeof $snippet.data("snippet-editor") === 'undefined') { var $targets = this.activate_overlay_zones($snippet); if (!$targets.length) return; - var editor = website.snippet.editorRegistry[$snippet.data("snippet-id")] || website.snippet.editorRegistry.resize; - $snippet.data("snippet-editor", new editor(this, $snippet)); + $snippet.data("snippet-editor", new website.snippet.Editor(this, $snippet)); } this.cover_target($snippet.data('overlay'), $snippet); }, @@ -318,36 +327,50 @@ start: function(){ self.hide(); dropped = false; + // snippet_selectors => to get selector-siblings, selector-children, selector-vertical-children $snippet = $(this); - snipped_id = $snippet.data('snippet-id'); + $toInsert = $snippet.find('.oe_snippet_body').clone(); + $toInsert.removeClass('oe_snippet_body'); + + var selector = []; + var selector_siblings = []; + var selector_children = []; + var selector_vertical_children = []; + for (var k in website.snippet.styles) { + if ($toInsert.is(website.snippet.styles[k].selector)) { + selector.push(website.snippet.styles[k].selector); + if (website.snippet.styles[k]['selector-siblings']) + selector_siblings.push(website.snippet.styles[k]['selector-siblings']); + if (website.snippet.styles[k]['selector-children']) + selector_children.push(website.snippet.styles[k]['selector-children']); + if (website.snippet.styles[k]['selector-vertical-children']) + selector_vertical_children.push(website.snippet.styles[k]['selector-vertical-children']); + } + } + action = $snippet.find('.oe_snippet_body').size() ? 'insert' : 'mutate'; + if( action === 'insert'){ - if (!$snippet.data('selector-siblings') && !$snippet.data('selector-children') && !$snippet.data('selector-vertical-children')) { + if (!selector_siblings.length && !selector_children.length && !selector_vertical_children.length) { console.debug($snippet.data("snippet-id") + " have oe_snippet_body class and have not for insert action"+ "data-selector-siblings, data-selector-children or data-selector-vertical-children tag for mutate action"); return; } + console.log(selector_siblings); + console.log(selector_children); + console.log(selector_vertical_children); self.activate_insertion_zones({ - siblings: $snippet.data('selector-siblings'), - children: $snippet.data('selector-children'), - vertical_children: $snippet.data('selector-vertical-children') + siblings: selector_siblings.join(","), + children: selector_children.join(","), + vertical_children: selector_vertical_children.join(","), }); - $toInsert = $snippet.find('.oe_snippet_body').clone(); - $toInsert.removeClass('oe_snippet_body'); - $toInsert.data('src-snippet-id', snipped_id); - if (!$toInsert.data('snippet-id')) { - $toInsert.attr('data-snippet-id', snipped_id); - } else { - snipped_id = $toInsert.data('snippet-id'); - } - } else if( action === 'mutate' ){ if (!$snippet.data('selector')) { console.debug($snippet.data("snippet-id") + " have not oe_snippet_body class and have not data-selector tag"); return; } - var $targets = self.activate_overlay_zones($snippet.data('selector')); + var $targets = self.activate_overlay_zones(selector_children.join(",")); $targets.each(function(){ var $clone = $(this).data('overlay').clone(); $clone.addClass("oe_drop_zone").data('target', $(this)); @@ -382,56 +405,31 @@ } $('.oe_drop_zone').droppable('destroy').remove(); + if (dropped) { var $target = false; - if(action === 'insert'){ - $target = $toInsert; + $target = $toInsert; - website.snippet.start_animation(); + setTimeout(function () { + $("#oe_snippets").trigger('snippet-dropped', $target); + + // after rte + website.snippet.start_animation($target); self.create_overlay($target); if ($target.data("snippet-editor")) { $target.data("snippet-editor").drop_and_build_snippet($target); } - $target.find("[data-snippet-id]").each(function () { - var $snippet = $(this); - var snippet_id = $snippet.data("data-snippet-id"); - self.create_overlay($snippet); - if ($snippet.data("snippet-editor")) { - $snippet.data("snippet-editor").drop_and_build_snippet($snippet); - } - }); - - } else { - $target = $(this).data('target'); - - self.create_overlay($target); - if (website.snippet.editorRegistry[snipped_id]) { - var snippet = new website.snippet.editorRegistry[snipped_id](self, $target); - snippet.drop_and_build_snippet($target); + for (var k in website.snippet.styles) { + $target.find(website.snippet.styles[k].selector).each(function () { + var $snippet = $(this); + self.create_overlay($snippet); + if ($snippet.data("snippet-editor")) { + $snippet.data("snippet-editor").drop_and_build_snippet($snippet); + } + }); } - } - setTimeout(function () { - $("#oe_snippets").trigger('snippet-dropped', $target); - - // reset snippet for rte - $target.removeData("snippet-editor"); - if ($target.data("overlay")) { - $target.data("overlay").remove(); - $target.removeData("overlay"); - } - self.create_overlay($target); - $target.find("[data-snippet-id]").each(function () { - var $snippet = $(this); - $snippet.removeData("snippet-editor"); - if ($snippet.data("overlay")) { - $snippet.data("overlay").remove(); - $snippet.removeData("overlay"); - } - self.create_overlay($snippet); - }); - // end self.make_active($target); },0); @@ -598,8 +596,8 @@ website.snippet.styleRegistry = {}; website.snippet.StyleEditor = openerp.Class.extend({ // initialisation (don't overwrite) - init: function (parent, $target, snippet_id) { - this.parent = parent; + init: function (BuildingBlock, $target, snippet_id) { + this.BuildingBlock = BuildingBlock; this.$target = $target; var styles = this.$target.data("snippet-style-ids") || {}; styles[snippet_id] = this; @@ -664,6 +662,13 @@ // start is call just after the init start: function () { }, + /* + * drop_and_build_snippet + * This method is called just after that a thumbnail is drag and dropped into a drop zone + * (after the insertion of this.$body, if this.$body exists) + */ + drop_and_build_snippet: function ($target) { + }, /* select * called when a user select an item * variables: np = {$next, $prev} @@ -715,7 +720,6 @@ } }); - website.snippet.styleRegistry.background = website.snippet.StyleEditor.extend({ _get_bg: function () { return this.$target.css("background-image").replace(/url\(['"]*|['"]*\)|^none$/g, ""); @@ -781,217 +785,171 @@ this.$el.find('li:has(li[data-class].active)').addClass("active"); } }); + website.snippet.styleRegistry.slider = website.snippet.StyleEditor.extend({ + drop_and_build_snippet: function() { + var id = $(".carousel").length; + this.id = "myCarousel" + id; + this.$target.attr("id", this.id); + this.$target.find(".carousel-control").attr("href", "#myCarousel" + id); + this.$target.find("[data-target]").attr("data-target", "#myCarousel" + id); - - website.snippet.editorRegistry = {}; - website.snippet.Editor = openerp.Class.extend({ - init: function (parent, dom) { - this.parent = parent; - this.$target = $(dom); - this.$overlay = this.$target.data('overlay'); - this.snippet_id = this.$target.data("snippet-id"); - this._readXMLData(); - this.load_style_options(); - this.get_parent_block(); - this.start(); + this.rebind_event(); }, - - /* - * _readXMLData - * Read data XML and set value into: - * this.$el : - * all xml data - * this.$overlay : - * Dom hover the $target who content options - * this.$editor : - * content of .oe_snippet_options - * Displayed into the overlay options on focus - */ - _readXMLData: function() { + // rebind event to active carousel on edit mode + rebind_event: function () { var self = this; - this.$el = this.parent.$snippets.filter(function () { return $(this).data("snippet-id") == self.snippet_id; }).clone(); - this.$editor = this.$el.find(".oe_snippet_options"); - var $options = this.$overlay.find(".oe_overlay_options"); - this.$editor.prependTo($options.find(".oe_options ul")); - if ($options.find(".oe_options ul li").length) { - $options.find(".oe_options").removeClass("hidden"); - } + this.$target.find('.carousel-indicators [data-target]').off('click').on('click', function () { + self.$target.carousel(+$(this).data('slide-to')); }); + + this.$target.attr('contentEditable', 'false'); + this.$target.find('.oe_structure, .content>.row').attr('contentEditable', 'true'); }, - - - // activate drag and drop for the snippets in the snippet toolbar - _drag_and_drop: function(){ - var self = this; - this.dropped = false; - this.$overlay.draggable({ - greedy: true, - appendTo: 'body', - cursor: "move", - handle: ".oe_snippet_move", - cursorAt: { - left: 18, - top: 14 - }, - helper: function() { - var $clone = $(this).clone().css({width: "24px", height: "24px", border: 0}); - $clone.find(".oe_overlay_options >:not(:contains(.oe_snippet_move)), .oe_handle").remove(); - $clone.find(":not(.glyphicon)").css({position: 'absolute', top: 0, left: 0}); - $clone.appendTo("body").removeClass("hidden"); - return $clone; - }, - start: _.bind(self._drag_and_drop_start, self), - stop: _.bind(self._drag_and_drop_stop, self) - }); - }, - _drag_and_drop_after_insert_dropzone: function (){}, - _drag_and_drop_active_drop_zone: function ($zones){ - var self = this; - $zones.droppable({ - over: function(){ - $(".oe_drop_zone.hide").removeClass("hide"); - $(this).addClass("hide").first().after(self.$target); - self.dropped = true; - }, - out: function(){ - $(this).removeClass("hide"); - self.$target.detach(); - self.dropped = false; - }, - }); - }, - _drag_and_drop_start: function (){ - var self = this; - self.parent.hide(); - self.parent.editor_busy = true; - self.size = { - width: self.$target.width(), - height: self.$target.height() - }; - self.$target.after("