Commit a0f4a389 authored by Adrien Di Mascio's avatar Adrien Di Mascio
Browse files

[api] work in progress, use __regid__, cw_*, etc.

parent 495862266785
......@@ -38,7 +38,7 @@ class TreeMixIn(object):
entities=entities)
if entities:
return [e for e in res if e.e_schema != self.e_schema]
return res.filtered_rset(lambda x: x.e_schema != self.e_schema, self.col)
return res.filtered_rset(lambda x: x.e_schema != self.e_schema, self.cw_col)
def same_type_children(self, entities=True):
"""return children entities of the same type as this entity.
......@@ -50,7 +50,7 @@ class TreeMixIn(object):
entities=entities)
if entities:
return [e for e in res if e.e_schema == self.e_schema]
return res.filtered_rset(lambda x: x.e_schema == self.e_schema, self.col)
return res.filtered_rset(lambda x: x.e_schema == self.e_schema, self.cw_col)
def iterchildren(self, _done=None):
if _done is None:
......@@ -249,7 +249,7 @@ class TreeViewMixIn(object):
class TreePathMixIn(object):
"""a recursive path view"""
id = 'path'
__regid__ = 'path'
item_vid = 'oneline'
separator = u' > '
......
......@@ -210,7 +210,7 @@ class ActionsRegistry(CWRegistry):
def possible_actions(self, req, rset=None, **kwargs):
if rset is None:
actions = self.possible_vobjects(req, rset=rset, **kwargs)
actions = self.poss_visible_objects(req, rset=rset, **kwargs)
else:
actions = rset.possible_actions(**kwargs) # cached implementation
result = {}
......
......@@ -82,7 +82,7 @@ class AnyEntity(Entity):
def dc_date(self, date_format=None):# XXX default to ISO 8601 ?
"""return latest modification date of this entity"""
return self.format_date(self.modification_date, date_format=date_format)
return self._cw.format_date(self.modification_date, date_format=date_format)
def dc_type(self, form=''):
"""return the display name for the type of this entity (translated)"""
......@@ -95,7 +95,7 @@ class AnyEntity(Entity):
for rschema, attrschema in self.e_schema.attribute_definitions():
if rschema.rproperty(self.e_schema, attrschema,
'internationalizable'):
return self._cw._(self.req.user.property_value('ui.language'))
return self._cw._(self._cw.user.property_value('ui.language'))
return self._cw._(self._cw.vreg.property_value('ui.language'))
@property
......@@ -125,7 +125,7 @@ class AnyEntity(Entity):
if 'vtitle' in self._cw.form:
# embeding for instance
path.append( self._cw.form['vtitle'] )
elif view.id != 'primary' and hasattr(view, 'title'):
elif view.__regid__ != 'primary' and hasattr(view, 'title'):
path.append( self._cw._(view.title) )
return path
......
......@@ -51,7 +51,7 @@ class EmailAddress(AnyEntity):
if not ('sender' in subjrels and 'recipients' in subjrels):
return
rql = 'DISTINCT Any X, S, D ORDERBY D DESC WHERE X sender Y or X recipients Y, X subject S, X date D, Y eid %(y)s'
rset = self.req.execute(rql, {'y': self.eid}, 'y')
rset = self._cw.execute(rql, {'y': self.eid}, 'y')
if skipeids is None:
skipeids = set()
for i in xrange(len(rset)):
......@@ -88,13 +88,13 @@ class Bookmark(AnyEntity):
fetch_attrs, fetch_order = fetch_config(['title', 'path'])
def actual_url(self):
url = self.req.build_url(self.path)
url = self._cw.build_url(self.path)
if self.title:
urlparts = list(urlsplit(url))
if urlparts[3]:
urlparts[3] += '&vtitle=%s' % self.req.url_quote(self.title)
urlparts[3] += '&vtitle=%s' % self._cw.url_quote(self.title)
else:
urlparts[3] = 'vtitle=%s' % self.req.url_quote(self.title)
urlparts[3] = 'vtitle=%s' % self._cw.url_quote(self.title)
url = urlunsplit(urlparts)
return url
......@@ -113,7 +113,7 @@ class CWProperty(AnyEntity):
def dc_description(self, format='text/plain'):
try:
return self.req._(self.vreg.property_info(self.pkey)['help'])
return self._cw._(self.vreg.property_info(self.pkey)['help'])
except UnknownProperty:
return u''
......@@ -130,7 +130,7 @@ class CWCache(AnyEntity):
fetch_attrs, fetch_order = fetch_config(['name'])
def touch(self):
self.req.execute('SET X timestamp %(t)s WHERE X eid %(x)s',
self._cw.execute('SET X timestamp %(t)s WHERE X eid %(x)s',
{'t': datetime.now(), 'x': self.eid}, 'x')
def valid(self, date):
......
......@@ -142,7 +142,7 @@ class SpecializedEntityClassesTC(CubicWebTC):
self.assertEquals(eclass.__bases__[0].__bases__, (Foo,))
# check Division eclass is still selected for plain Division entities
eclass = self.select_eclass('Division')
self.assertEquals(eclass.id, 'Division')
self.assertEquals(eclass.__regid__, 'Division')
if __name__ == '__main__':
unittest_main()
......@@ -408,11 +408,11 @@ class WorkflowableMixIn(object):
return wfrset.get_entity(0, 0)
if len(wfrset) > 1:
for wf in wfrset.entities():
if wf.is_default_workflow_of(self.id):
if wf.is_default_workflow_of(self.__regid__):
return wf
self.warning("can't find default workflow for %s", self.id)
self.warning("can't find default workflow for %s", self.__regid__)
else:
self.warning("can't find any workflow for %s", self.id)
self.warning("can't find any workflow for %s", self.__regid__)
return None
def possible_transitions(self):
......@@ -452,7 +452,7 @@ class WorkflowableMixIn(object):
"""
assert self.current_workflow
tr = self.current_workflow.transition_by_name(trname)
assert tr is not None, 'not a %s transition: %s' % (self.id, trname)
assert tr is not None, 'not a %s transition: %s' % (self.__regid__, trname)
return self._add_trinfo(comment, commentformat, tr.eid)
def change_state(self, statename, comment=None, commentformat=None, tr=None):
......@@ -471,7 +471,7 @@ class WorkflowableMixIn(object):
else:
state = self.current_workflow.state_by_name(statename)
if state is None:
raise WorkflowException('not a %s state: %s' % (self.id,
raise WorkflowException('not a %s state: %s' % (self.__regid__,
statename))
stateeid = state.eid
# XXX try to find matching transition?
......
......@@ -106,7 +106,7 @@ class View(AppObject):
@property
def content_type(self):
return self.req.html_content_type()
return self._cw.html_content_type()
def set_stream(self, w=None):
if self.w is not None:
......@@ -155,8 +155,8 @@ class View(AppObject):
"""
from cubicweb.ext.tal import CubicWebContext
context = CubicWebContext()
context.update({'self': self, 'rset': self.rset, '_' : self.req._,
'req': self.req, 'user': self.req.user})
context.update({'self': self, 'rset': self.cw_rset, '_' : self._cw._,
'req': self._cw, 'user': self._cw.user})
context.update(variables)
output = UStringIO()
template.expand(context, output)
......@@ -175,14 +175,14 @@ class View(AppObject):
Views applicable on None result sets have to override this method
"""
rset = self.rset
rset = self.cw_rset
if rset is None:
raise NotImplementedError, self
wrap = self.templatable and len(rset) > 1 and self.add_div_section
for i in xrange(len(rset)):
if wrap:
self.w(u'<div class="section">')
self.wview(self.id, rset, row=i, **kwargs)
self.wview(self.__regid__, rset, row=i, **kwargs)
if wrap:
self.w(u"</div>")
......@@ -200,23 +200,23 @@ class View(AppObject):
return True
def is_primary(self):
return self.id == 'primary'
return self.__regid__ == 'primary'
def url(self):
"""return the url associated with this view. Should not be
necessary for non linkable views, but a default implementation
is provided anyway.
"""
rset = self.rset
rset = self.cw_rset
if rset is None:
return self.build_url('view', vid=self.id)
return self._cw.build_url('view', vid=self.__regid__)
coltypes = rset.column_types(0)
if len(coltypes) == 1:
etype = iter(coltypes).next()
if not self.schema.eschema(etype).is_final():
if not self._cw.schema.eschema(etype).is_final():
if len(rset) == 1:
entity = rset.get_entity(0, 0)
return entity.absolute_url(vid=self.id)
return entity.absolute_url(vid=self.__regid__)
# don't want to generate /<etype> url if there is some restriction
# on something else than the entity type
restr = rset.syntax_tree().children[0].where
......@@ -226,25 +226,25 @@ class View(AppObject):
norestriction = (isinstance(restr, nodes.Relation) and
restr.is_types_restriction())
if norestriction:
return self.build_url(etype.lower(), vid=self.id)
return self.build_url('view', rql=rset.printable_rql(), vid=self.id)
return self._cw.build_url(etype.lower(), vid=self.__regid__)
return self._cw.build_url('view', rql=rset.printable_rql(), vid=self.__regid__)
def set_request_content_type(self):
"""set the content type returned by this view"""
self.req.set_content_type(self.content_type)
self._cw.set_content_type(self.content_type)
# view utilities ##########################################################
def wview(self, __vid, rset=None, __fallback_vid=None, **kwargs):
"""shortcut to self.view method automatically passing self.w as argument
"""
self.view(__vid, rset, __fallback_vid, w=self.w, **kwargs)
self._cw.view(__vid, rset, __fallback_vid, w=self.w, **kwargs)
# XXX Template bw compat
template = deprecated('[3.4] .template is deprecated, use .view')(wview)
def whead(self, data):
self.req.html_headers.write(data)
self._cw.html_headers.write(data)
def wdata(self, data):
"""simple helper that escapes `data` and writes into `self.w`"""
......@@ -262,34 +262,34 @@ class View(AppObject):
"""returns a title according to the result set - used for the
title in the HTML header
"""
vtitle = self.req.form.get('vtitle')
vtitle = self._cw.form.get('vtitle')
if vtitle:
return self.req._(vtitle)
return self._cw._(vtitle)
# class defined title will only be used if the resulting title doesn't
# seem clear enough
vtitle = getattr(self, 'title', None) or u''
if vtitle:
vtitle = self.req._(vtitle)
rset = self.rset
vtitle = self._cw._(vtitle)
rset = self.cw_rset
if rset and rset.rowcount:
if rset.rowcount == 1:
try:
entity = self.complete_entity(0)
entity = rset.complete_entity(0, 0)
# use long_title to get context information if any
clabel = entity.dc_long_title()
except NotAnEntity:
clabel = display_name(self.req, rset.description[0][0])
clabel = display_name(self._cw, rset.description[0][0])
clabel = u'%s (%s)' % (clabel, vtitle)
else :
etypes = rset.column_types(0)
if len(etypes) == 1:
etype = iter(etypes).next()
clabel = display_name(self.req, etype, 'plural')
clabel = display_name(self._cw, etype, 'plural')
else :
clabel = u'#[*] (%s)' % vtitle
else:
clabel = vtitle
return u'%s (%s)' % (clabel, self.req.property_value('ui.site-title'))
return u'%s (%s)' % (clabel, self._cw.property_value('ui.site-title'))
def output_url_builder( self, name, url, args ):
self.w(u'<script language="JavaScript"><!--\n' \
......@@ -305,7 +305,7 @@ class View(AppObject):
def create_url(self, etype, **kwargs):
""" return the url of the entity creation form for a given entity type"""
return self.req.build_url('add/%s'%etype, **kwargs)
return self._cw.build_url('add/%s'%etype, **kwargs)
def field(self, label, value, row=True, show_label=True, w=None, tr=True):
""" read-only field """
......@@ -315,7 +315,7 @@ class View(AppObject):
w(u'<div class="row">')
if show_label and label:
if tr:
label = display_name(self.req, label)
label = display_name(self._cw, label)
w(u'<span class="label">%s</span>' % label)
w(u'<div class="field">%s</div>' % value)
if row:
......@@ -370,11 +370,11 @@ class EntityStartupView(EntityView):
"""override call to execute rql returned by the .startup_rql method if
necessary
"""
if self.rset is None:
self.rset = self.req.execute(self.startup_rql())
rset = self.rset
rset = self.cw_rset
if rset is None:
rset = self.cw_rset = self._cw.execute(self.startup_rql())
for i in xrange(len(rset)):
self.wview(self.id, rset, row=i, **kwargs)
self.wview(self.__regid__, rset, row=i, **kwargs)
class AnyRsetView(View):
......@@ -385,18 +385,18 @@ class AnyRsetView(View):
def columns_labels(self, mainindex=0, tr=True):
if tr:
translate = lambda val, req=self.req: display_name(req, val)
translate = lambda val, req=self._cw: display_name(req, val)
else:
translate = lambda val: val
# XXX [0] because of missing Union support
rqlstdescr = self.rset.syntax_tree().get_description(mainindex,
translate)[0]
rqlstdescr = self.cw_rset.syntax_tree().get_description(mainindex,
translate)[0]
labels = []
for colindex, label in enumerate(rqlstdescr):
# compute column header
if label == 'Any': # find a better label
label = ','.join(translate(et)
for et in self.rset.column_types(colindex))
for et in self.cw_rset.column_types(colindex))
labels.append(label)
return labels
......@@ -411,7 +411,7 @@ class MainTemplate(View):
@property
def doctype(self):
if self.req.xhtml_browser():
if self._cw.xhtml_browser():
return STRICT_DOCTYPE
return STRICT_DOCTYPE_NOEXT
......@@ -422,7 +422,7 @@ class MainTemplate(View):
if self.binary:
self._stream = stream = StringIO()
else:
self._stream = stream = HTMLStream(self.req)
self._stream = stream = HTMLStream(self._cw)
w = stream.write
else:
stream = None
......@@ -447,18 +447,18 @@ class ReloadableMixIn(object):
"""register the given user callback and return an url to call it ready to be
inserted in html
"""
self.req.add_js('cubicweb.ajax.js')
self._cw.add_js('cubicweb.ajax.js')
if nonify:
_cb = cb
def cb(*args):
_cb(*args)
cbname = self.req.register_onetime_callback(cb, *args)
cbname = self._cw.register_onetime_callback(cb, *args)
return self.build_js(cbname, xml_escape(msg or ''))
def build_update_js_call(self, cbname, msg):
rql = xml_escape(self.rset.printable_rql())
rql = xml_escape(self.cw_rset.printable_rql())
return "javascript:userCallbackThenUpdateUI('%s', '%s', '%s', '%s', '%s', '%s')" % (
cbname, self.id, rql, msg, self.__registry__, self.div_id())
cbname, self.__regid__, rql, msg, self.__registry__, self.div_id())
def build_reload_js_call(self, cbname, msg):
return "javascript:userCallbackThenReloadPage('%s', '%s')" % (cbname, msg)
......@@ -477,8 +477,8 @@ class Component(ReloadableMixIn, View):
# XXX huummm, much probably useless
htmlclass = 'mainRelated'
def div_class(self):
return '%s %s' % (self.htmlclass, self.id)
return '%s %s' % (self.htmlclass, self.__regid__)
# XXX a generic '%s%s' % (self.id, self.__registry__.capitalize()) would probably be nicer
# XXX a generic '%s%s' % (self.__regid__, self.__registry__.capitalize()) would probably be nicer
def div_id(self):
return '%sComponent' % self.id
return '%sComponent' % self.__regid__
......@@ -49,13 +49,13 @@ class Action(AppObject):
raise NotImplementedError
def html_class(self):
if self.req.selected(self.url()):
if self._cw.selected(self.url()):
return 'selected'
if self.category:
return 'box' + self.category.capitalize()
def build_action(self, title, path, **kwargs):
return UnregisteredAction(self.req, self.rset, title, path, **kwargs)
return UnregisteredAction(self._cw, self.cw_rset, title, path, **kwargs)
class UnregisteredAction(Action):
......@@ -89,9 +89,9 @@ class LinkToEntityAction(Action):
submenu = 'addrelated'
def url(self):
current_entity = self.rset.get_entity(self.row or 0, self.col or 0)
current_entity = self.cw_rset.get_entity(self.cw_row or 0, self.cw_col or 0)
linkto = '%s:%s:%s' % (self.rtype, current_entity.eid, target(self))
return self.build_url('add/%s' % self.etype, __linkto=linkto,
__redirectpath=current_entity.rest_path(), # should not be url quoted!
__redirectvid=self.req.form.get('__redirectvid', ''))
__redirectvid=self._cw.form.get('__redirectvid', ''))
......@@ -77,18 +77,18 @@ class BoxTemplate(View):
return self.box_action(self._action(title, path, **kwargs))
def _action(self, title, path, **kwargs):
return UnregisteredAction(self.req, self.rset, title, path, **kwargs)
return UnregisteredAction(self._cw, self.cw_rset, title, path, **kwargs)
# formating callbacks
def boxitem_link_tooltip(self, action):
if action.id:
return u'keyword: %s' % action.id
if action.__regid__:
return u'keyword: %s' % action.__regid__
return u''
def box_action(self, action):
cls = getattr(action, 'html_class', lambda: None)() or self.htmlitemclass
return BoxLink(action.url(), self.req._(action.title),
return BoxLink(action.url(), self._cw._(action.title),
cls, self.boxitem_link_tooltip(action))
......@@ -105,18 +105,18 @@ class RQLBoxTemplate(BoxTemplate):
rql = None
def to_display_rql(self):
assert self.rql is not None, self.id
assert self.rql is not None, self.__regid__
return (self.rql,)
def call(self, **kwargs):
try:
rset = self.req.execute(*self.to_display_rql())
rset = self._cw.execute(*self.to_display_rql())
except Unauthorized:
# can't access to something in the query, forget this box
return
if len(rset) == 0:
return
box = BoxWidget(self.req._(self.title), self.id)
box = BoxWidget(self._cw._(self.title), self.__regid__)
for i, (teid, tname) in enumerate(rset):
entity = rset.get_entity(i, 0)
box.append(self.mk_action(tname, entity.absolute_url()))
......@@ -129,8 +129,8 @@ class UserRQLBoxTemplate(RQLBoxTemplate):
"""
def to_display_rql(self):
assert self.rql is not None, self.id
return (self.rql, {'x': self.req.user.eid}, 'x')
assert self.rql is not None, self.__regid__
return (self.rql, {'x': self._cw.user.eid}, 'x')
class EntityBoxTemplate(BoxTemplate):
......@@ -147,12 +147,12 @@ class RelatedEntityBoxTemplate(EntityBoxTemplate):
__select__ = EntityBoxTemplate.__select__ & partial_has_related_entities()
def cell_call(self, row, col, **kwargs):
entity = self.rset.get_entity(row, col)
limit = self.req.property_value('navigation.related-limit') + 1
entity = self.cw_rset.get_entity(row, col)
limit = self._cw.property_value('navigation.related-limit') + 1
role = get_role(self)
self.w(u'<div class="sideBox">')
self.wview('sidebox', entity.related(self.rtype, role, limit=limit),
title=display_name(self.req, self.rtype, role))
title=display_name(self._cw, self.rtype, role))
self.w(u'</div>')
......@@ -165,9 +165,9 @@ class EditRelationBoxTemplate(ReloadableMixIn, EntityBoxTemplate):
"""
def cell_call(self, row, col, view=None, **kwargs):
self.req.add_js('cubicweb.ajax.js')
entity = self.rset.get_entity(row, col)
box = SideBoxWidget(display_name(self.req, self.rtype), self.id)
self._cw.add_js('cubicweb.ajax.js')
entity = self.cw_rset.get_entity(row, col)
box = SideBoxWidget(display_name(self._cw, self.rtype), self.__regid__)
related = self.related_boxitems(entity)
unrelated = self.unrelated_boxitems(entity)
box.extend(related)
......@@ -177,7 +177,7 @@ class EditRelationBoxTemplate(ReloadableMixIn, EntityBoxTemplate):
box.render(self.w)
def div_id(self):
return self.id
return self.__regid__
def box_item(self, entity, etarget, rql, label):
"""builds HTML link to edit relation between `entity` and `etarget`
......@@ -218,12 +218,12 @@ class EditRelationBoxTemplate(ReloadableMixIn, EntityBoxTemplate):
return entity.unrelated(self.rtype, self.etype, get_role(self)).entities()
# in other cases, use vocabulary functions
entities = []
form = self.vreg['forms'].select('edition', self.req, rset=self.rset,
row=self.row or 0)
form = self.vreg['forms'].select('edition', self._cw, rset=self.cw_rset,
row=self.cw_row or 0)
field = form.field_by_name(self.rtype, get_role(self), entity.e_schema)
for _, eid in form.form_field_vocabulary(field):
if eid is not None:
rset = self.req.eid_rset(eid)
rset = self._cw.eid_rset(eid)
entities.append(rset.get_entity(0, 0))
return entities
......@@ -86,10 +86,10 @@ class NavigationComponent(Component):
except AttributeError:
page_size = self.extra_kwargs.get('page_size')
if page_size is None:
if 'page_size' in self.req.form:
page_size = int(self.req.form['page_size'])
if 'page_size' in self._cw.form:
page_size = int(self._cw.form['page_size'])
else:
page_size = self.req.property_value(self.page_size_property)
page_size = self._cw.property_value(self.page_size_property)
self._page_size = page_size
return page_size
......@@ -100,8 +100,8 @@ class NavigationComponent(Component):
def page_boundaries(self):
try:
stop = int(self.req.form[self.stop_param]) + 1
start = int(self.req.form[self.start_param])
stop = int(self._cw.form[self.stop_param]) + 1
start = int(self._cw.form[self.start_param])
except KeyError:
start, stop = 0, self.page_size
self.starting_from = start
......@@ -117,7 +117,7 @@ class NavigationComponent(Component):
params = merge_dicts(params, {self.start_param : start,
self.stop_param : stop,})
if path == 'json':
rql = params.pop('rql', self.rset.printable_rql())
rql = params.pop('rql', self.cw_rset.printable_rql())
# latest 'true' used for 'swap' mode
url = 'javascript: replacePageChunk(%s, %s, %s, %s, true)' % (
dumps(params.get('divid', 'paginated-content')),
......@@ -163,15 +163,15 @@ class RelatedObjectsVComponent(EntityVComponent):
def cell_call(self, row, col, view=None):
rql = self.rql()
if rql is None:
entity = self.rset.get_entity(row, col)
entity = self.cw_rset.get_entity(row, col)
rset = entity.related(self.rtype, role(self))
else:
eid = self.rset[row][col]
rset = self.req.execute(self.rql(), {'x': eid}, 'x')
eid = self.cw_rset[row][col]
rset = self._cw.execute(self.rql(), {'x': eid}, 'x')
if not rset.rowcount:
return
self.w(u'<div class="%s">' % self.div_class())
self.wview(self.vid, rset, title=self.req._(self.title).capitalize())
self.wview(self.vid, rset, title=self._cw._(self.title).capitalize())
self.w(u'</div>')
......
......@@ -282,7 +282,7 @@ class AbstractFacet(AppObject):
self.filtered_variable = filtered_variable
def init_from_rset(self):
self.rqlst = self.rset.syntax_tree().children[0]
self.rqlst = self.cw_rset.syntax_tree().children[0]
def init_from_form(self, rqlst):
self.rqlst = rqlst
......@@ -290,7 +290,7 @@ class AbstractFacet(AppObject):
@property
def operator(self):
# OR between selected values by default
return self.req.form.get(self.id + '_andor', 'OR')
return self._cw.form.get(self.__regid__ + '_andor', 'OR')
def get_widget(self):
"""return the widget instance to use to display this facet
......@@ -315,12 +315,12 @@ class VocabularyFacet(AbstractFacet):
if len(vocab) <= 1: