Example #1
0
class RelationBox(component.CtxComponent):
    """ Helper view class to display a relation rset in a sidebox.
    """
    __select__ = nonempty_rset() & match_kwargs("title", "rql")
    __regid__ = "relationbox"
    cw_property_defs = {}
    context = "incontext"

    @property
    def domid(self):
        return (super(RelationBox, self).domid + unicode(abs(id(self))) +
                unicode(abs(id(self.cw_rset))))

    def render_title(self, w):
        w(self.cw_extra_kwargs["title"])

    def render_body(self, w):
        defaultlimit = self._cw.property_value("navigation.related-limit")
        if not isinstance(self.cw_rset, list):
            rset = list(self.cw_rset.entities())
        else:
            rset = self.cw_rset
        for entity in rset[:(defaultlimit - 1)]:
            w(u"<div>&bull; " + entity.view(self.context) + u"</div>")
        # if len(rset) == defaultlimit:
        rql = self.cw_extra_kwargs["rql"]
        href = self._cw.build_url(rql=rql)
        w(u"<br/><div><a href='{0}'>&#8634; see more</a></div>".format(href))
Example #2
0
class CellView(EntityView, metaclass=class_deprecated):
    __deprecation_warning__ = '[3.14] %(cls)s is deprecated'
    __regid__ = 'cell'
    __select__ = nonempty_rset()

    def cell_call(self, row, col, cellvid=None):
        """
        :param row, col: indexes locating the cell value in view's result set
        :param cellvid: cell view (defaults to 'outofcontext')
        """
        etype, val = self.cw_rset.description[row][col], self.cw_rset[row][col]
        if etype is None or not self._cw.vreg.schema.eschema(etype).final:
            if val is None:
                # This is usually caused by a left outer join and in that case,
                # regular views will most certainly fail if they don't have
                # a real eid
                # XXX if cellvid is e.g. reledit, we may wanna call it anyway
                self.w(u'&#160;')
            else:
                self.wview(cellvid or 'outofcontext',
                           self.cw_rset,
                           row=row,
                           col=col)
        else:
            # XXX why do we need a fallback view here?
            self.wview(cellvid or 'final',
                       self.cw_rset,
                       'null',
                       row=row,
                       col=col)
Example #3
0
class AnyRsetView(View):
    """base class for views applying on any non empty result sets"""
    __select__ = nonempty_rset()

    category = _('anyrsetview')

    def columns_labels(self, mainindex=0, tr=True):
        """compute the label of the rset colums

        The logic is based on :meth:`~rql.stmts.Union.get_description`.

        :param mainindex: The index of the main variable. This is an hint to get
                          more accurate label for various situation
        :type mainindex:  int

        :param tr: Should the label be translated ?
        :type tr: boolean
        """
        if tr:
            translate = partial(display_name, self._cw)
        else:
            translate = lambda val, *args, **kwargs: val
        # XXX [0] because of missing Union support
        rql_syntax_tree = self.cw_rset.syntax_tree()
        rqlstdescr = rql_syntax_tree.get_description(mainindex, translate)[0]
        labels = []
        for colidx, label in enumerate(rqlstdescr):
            labels.append(self.column_label(colidx, label, translate))
        return labels

    def column_label(self, colidx, default, translate_func=None):
        """return the label of a specified columns index

        Overwrite me if you need to compute specific label.

        :param colidx: The index of the column the call computes a label for.
        :type colidx:  int

        :param default: Default value. If ``"Any"`` the default value will be
                        recomputed as coma separated list for all possible
                        etypes name.
        :type colidx:  string

        :param translate_func: A function used to translate name.
        :type colidx:  function
        """
        label = default
        if label == 'Any':
            etypes = self.cw_rset.column_types(colidx)
            if translate_func is not None:
                etypes = map(translate_func, etypes)
            label = u','.join(etypes)
        return label
Example #4
0
class SelectAction(action.Action):
    """base class for link search actions. By default apply on
    any size entity result search it the current state is 'linksearch'
    if accept match.
    """
    __regid__ = 'select'
    __select__ = (match_search_state('linksearch') & nonempty_rset()
                  & match_searched_etype())

    title = _('select')
    category = 'mainactions'
    order = 0

    def url(self):
        return linksearch_select_url(self._cw, self.cw_rset)
Example #5
0
class RsetBox(component.CtxComponent):
    """helper view class to display an rset in a sidebox"""
    __select__ = nonempty_rset() & match_kwargs('title', 'vid')
    __regid__ = 'rsetbox'
    cw_property_defs = {}
    context = 'incontext'

    @property
    def domid(self):
        return super(RsetBox, self).domid + str(abs(id(self))) + str(abs(id(self.cw_rset)))

    def render_title(self, w):
        w(self.cw_extra_kwargs['title'])

    def render_body(self, w):
        if 'dispctrl' in self.cw_extra_kwargs:
            # XXX do not modify dispctrl!
            self.cw_extra_kwargs['dispctrl'].setdefault('subvid', 'outofcontext')
            self.cw_extra_kwargs['dispctrl'].setdefault('use_list_limit', 1)
        self._cw.view(self.cw_extra_kwargs['vid'], self.cw_rset, w=w,
                      initargs=self.cw_extra_kwargs)
Example #6
0
class SaveCWSearchFilterBox(FacetFilterMixIn, component.CtxComponent):
    """ Class that enables us to display a 'Save search' box when the selected
    entities fulfill the '__select__' requirements.

    * This component shows up if the current rset is adaptable.
    * This component is integrated in the CW facet component
    * The global parameters 'RQL_DOWNLOAD_ENTITIES',
      'RQL_DOWNLOAD_EXPORT_ENTITIES' and 'RQL_DOWNLOAD_FSET_ENTITIES' specify
      which entities can be downloaded
      (ie. are adaptable).
    """
    __regid__ = "facet.filterbox"
    __select__ = (nonempty_rset() | contextview_selector())
    context = "left"
    order = 0
    visible = True
    title = _("Filter")

    linkbox_template = u'<div class="cw_search_box">{0}</div>'

    def render(self, w, **kwargs):
        """ Render the facet box only if something has to be displayed.
        """
        # Get the component context
        rset, vid, divid, paginate = self._get_context()

        # Check if some facets are defined for this view
        rql, available_facets = facets(self._cw, rset, self.__regid__)
        nb_facet_widgets = len(available_facets)
        if "eid" in rql:
            nb_facet_widgets = 0

        # Check if the view information can be downloaded
        can_save_search = False
        if rset.rowcount > 0:
            for rowindex in range(len(rset[0])):
                try:
                    entity = rset.get_entity(0, rowindex)
                    entity_name = entity.__class__.__name__
                    if entity_name in RQL_DOWNLOAD_SEARCH_ENTITIES:
                        can_save_search = True
                        break
                except NotAnEntity:
                    pass
                except:
                    raise

        # Can't download if not logged
        can_save_search = (can_save_search
                           and not self._cw.session.anonymous_session)

        # Display the facet if something has to be displayed
        if can_save_search or nb_facet_widgets > 0:
            self.can_save_search = can_save_search
            self.nb_facet_widgets = nb_facet_widgets
            self.layout_render(w, **kwargs)

    def render_body(self, w, **kwargs):
        """ Method that generates the html elements to display the 'Save search'
        box.

        .. note::

            This method only consider the first registered
            'rqldownload-adapters' action to generate the resources associated
            with the current search.

            If the 'eid' attribute is in the RQL do not show the facets.
        """
        # Get the component context
        rset, vid, divid, paginate = self._get_context()

        # Check we have a valid vid
        if vid is None:
            vid = self._cw.form.get("vid")

        # Create the form url
        if self.can_save_search:
            w(self.search_link(rset))
        if self.nb_facet_widgets > 0:
            self.generate_form(w,
                               rset,
                               divid,
                               vid,
                               paginate=paginate,
                               hiddens={},
                               **self.cw_extra_kwargs)

    def search_link(self, rset):
        """ Method that generates the url of the CWSearch form we want to save.
        """
        # Construct the form path
        # > get rql as url parameter
        path = u'rql={0}'.format(self._cw.url_quote(rset.printable_rql()))

        # > get the vid of the view
        if self._cw.form.get("vid"):
            path += u'&vid={0}'.format(self._cw.url_quote(
                self._cw.form["vid"]))

        # > say its a view
        path = u'view?' + path

        # Define the form default tile
        title = self._cw._("--unique title--")

        # Create the url to the CWSearch form
        cls = self._cw.vreg["etypes"].etype_class("CWSearch")
        add_url = cls.cw_create_url(self._cw, path=path, title=title)

        base_url = cls.cw_create_url(self._cw, title=title)
        link = (u'<a class="btn btn-primary" cubicweb:target="{0}" '
                'id="facetBkLink" href="{1}">'.format(xml_escape(base_url),
                                                      xml_escape(add_url)))

        # Create the button
        button = u'<div class="btn-toolbar">'
        button += u'<div class="btn-group-vertical btn-block">'
        button += link
        button += u'<span class="glyphicon glyphicon-save" ' \
                  u'style="width: 25px;"></span>{0}'.format(
                      self._cw._("Add to cart"))
        button += u'</a></div></div><br />'

        return self.linkbox_template.format(button)

    def _get_context(self):
        """ Method to get the in context box information.
        """
        view = self.cw_extra_kwargs.get("view")
        context = getattr(view, "filter_box_context_info", lambda: None)()
        if context:
            rset, vid, divid, paginate = context
        else:
            rset = self.cw_rset
            vid, divid = None, "pageContent"
            paginate = view and view.paginable
        return rset, vid, divid, paginate