Ejemplo n.º 1
0
    def _spec_help_content(self, spec_name):
        if not pytis.form.has_access(spec_name):
            return (_("Access Denied"),
                    lcg.p(_("You don't have permissions for specification „%s“.") % spec_name))
        resolver = pytis.util.resolver()
        try:
            view_spec = resolver.get(spec_name, 'view_spec')
        except pytis.util.ResolverError:
            return None, None

        def field_label(f):
            label = f.column_label()
            if not label:
                label = f.label() or f.id()
            elif f.label() and f.label() != label:
                label += ' (' + f.label() + ')'
            return label

        def field_description(f):
            result = self._description('field', spec_name, f.id(), f.descr())
            related_specnames = [name for name in
                                 [f.codebook()] + [link.name() for link in f.links()] if name]
            if related_specnames:
                pytis.util.remove_duplicates(related_specnames)
                result = (result,
                          lcg.p(_("Related views:")),
                          lcg.ul([self._spec_link(name) for name in related_specnames]))
            return result

        parser = lcg.Parser()
        content = lcg.Container(
            [lcg.TableOfContents(title=_("Contents"))] + [
                lcg.Section(title=title, content=func(content)) for title, func, content in (
                    (_("Overview"), lcg.p,
                     self._description('description', spec_name, None, view_spec.description())),
                    (_("Description"), parser.parse,
                     self._description('help', spec_name, None, view_spec.help())),
                    (_("Form fields"), lcg.dl,
                     sorted([(field_label(f), field_description(f)) for f in view_spec.fields()],
                            key=lambda x: x[0])),
                    (_("Profiles"), lcg.dl,
                     [(p.title(), self._description('profile', spec_name, p.id(), p.descr()))
                      for p in view_spec.profiles().unnest()]),
                    (_("Context menu actions"), lcg.dl,
                     [(a.title(), (self._description('action', spec_name, a.id(), a.descr()),
                                   (' ', _("Access Rights"), ': ', ', '.join(a.access_groups()))
                                   if a.access_groups() else ''))
                      for a in view_spec.actions(unnest=True)]),
                    (_("Side forms"), lcg.dl,
                     [(self._spec_link(b.name(), b.title()),
                       self._description('binding', spec_name, b.id(), b.descr()))
                      for b in view_spec.bindings() if b.name()]),
                    (_("Access Rights"), lcg.dl,
                     self._access_rights(spec_name, view_spec)),
                ) if content
            ],
            resources=self._spec_help_resources(spec_name)
        )
        return view_spec.title(), content
Ejemplo n.º 2
0
 def export_task(task):
     text = task.text().replace('[', r'\[')
     if text:
         content = lcg.Parser().parse_inline_markup(text)
         html = context.localize(content.export(context))
     else:
         html = ''
     return g.noescape(task.substitute_fields(html, make_field))
Ejemplo n.º 3
0
 def _lcg(self):
     parser = lcg.Parser()
     parameters = {}
     result = lcg.Container(parser.parse(self._text, parameters))
     self._parameters = {}
     for k, v in parameters.items():
         self._parameters[k] = v
     if 'first_page_header' not in self._parameters and 'page_header' in self._parameters:
         self._parameters['first_page_header'] = self._parameters['page_header']
     return result
Ejemplo n.º 4
0
Archivo: web.py Proyecto: cerha/pytis
 def action_view(self, req, record):
     text = record['content'].value()
     modname = record['modname'].value()
     globals = self.globals(req)
     storage = self._attachment_storage(record)
     if storage:
         resources = storage.resources()
     else:
         resources = ()
     if text:
         text = lcg.MacroParser(globals=globals).parse(text)
         parser = lcg.Parser()
         if self._SEPARATOR.search(text):
             pre, post = [parser.parse(part)
                          for part in self._SEPARATOR.split(text, maxsplit=2)]
         else:
             pre, post = parser.parse(text), []
     else:
         pre, post = [], []
     if modname is not None:
         binding = self._embed_binding(modname)
         result = req.forward(wiking.module(modname), binding=binding, record=record,
                              title=record['title'].value())
         if isinstance(result, wiking.Document):
             # Embed the resulting document into the current menu item content.
             content = result.content()
             if isinstance(content, (tuple, list)):
                 content = list(content)
             else:
                 content = [content]
             document = result.clone(title=self._document_title(req, record), subtitle=None,
                                     content=lcg.Container(pre + content + post,
                                                           resources=resources),
                                     globals=globals)
         else:
             # A wiking.Response instance has been returned by the embedded module.
             return result
     elif text is None and record['parent'].value() is None:
         # Redirect to the first subitem from empty top level items.
         rows = self._data.get_rows(parent=record['menu_item_id'].value(), published=True,
                                    sorting=self._sorting)
         # TODO: Use only items, which are visible to the current user (access rights).
         if rows:
             raise wiking.Redirect('/' + self._menu_item_identifier(rows[0]))
         else:
             document = self._document(req, lcg.Container([], resources=resources),
                                       record, globals=globals)
     else:
         document = self._document(req, lcg.Container(pre + post, resources=resources),
                                   record, globals=globals)
     if modname is None:
         # Module access is logged in EmbeddablePytisModule._handle().
         wiking.module.AccessLog.log(req, None, None)
     return document
Ejemplo n.º 5
0
 def _content(self, path, lang):
     filename = '.'.join((path, lang, 'txt'))
     f = codecs.open(filename, encoding='utf-8')
     text = "".join(f.readlines())
     f.close()
     content = lcg.Parser().parse(text)
     if len(content) == 1 and isinstance(content[0], lcg.Section):
         title = content[0].title()
         content = content[0].content()
     else:
         title = None
     return title, lcg.Container(content)
Ejemplo n.º 6
0
 def _application_help_page_content(self, node, uri):
     self._data.select(condition=pd.EQ('help_id', pd.sval(uri[5:])))
     row = self._data.fetchone()
     self._data.close()
     if row:
         if row['page_id'].value():
             storage = pytis.presentation.DbAttachmentStorage(
                 'e_pytis_help_pages_attachments', 'page_id', row['page_id'].value(),
             )
             return lcg.Container(lcg.Parser().parse(row['content'].value() or ''),
                                  resources=storage.resources())
         if row['menu_help'].value():
             return lcg.Parser().parse(row['menu_help'].value())
         else:
             spec_name = row['spec_name'].value()
             # TODO: Use the default descriptions from HelpUpdater.
             if spec_name:
                 content = self._spec_help_content(spec_name)[1]
                 if content:
                     return content
     return lcg.Content()
Ejemplo n.º 7
0
Archivo: misc.py Proyecto: cerha/pytis
 def _content(self, record):
     par = os.path.pardir
     return pytis.util.lcg_node(
         (
             lcg.fieldset((
                 (_("Price"), record['price'].export()),
                 (_("Available since"), lcg.LocalizableDateTime(record['since'].value())),
             )),
             lcg.sec(_("Notes"), lcg.Parser().parse(record['notes'].value()), name='notes')
             if record['notes'].value() else lcg.Content(),
         ),
         title=record['product'].value(),
         resource_path=(os.path.normpath(os.path.join(__file__, par, par, par, par, 'css')),),
         resources=('pytis-demo-product.css',),
     )
Ejemplo n.º 8
0
    def _export_task_text(self, context, exercise, exercise_id, task):
        g = context.generator()

        def make_field(answer, label, word_start, word_end):
            field, field_id = self._make_field(context, exercise, exercise_id, task, answer)
            if word_start or word_end:
                return g.span(g.noescape(word_start + field + word_end), cls='nowrap')
            else:
                return field
        text = task.text().replace('[', r'\[')
        if text:
            content = lcg.Parser().parse_inline_markup(text)
            html = context.localize(content.export(context))
        else:
            html = ''
        return g.noescape(task.substitute_fields(html, make_field))
Ejemplo n.º 9
0
 def _content(self, lang):
     from wiking import Application
     parser = lcg.Parser()
     # modules = [(k, v) for k, v in wiking.application.__dict__.items()
     #            if type(v) == type(Module) and issubclass(v, Module) \
     #            and v.__module__ == 'wiking.application']
     # modules.sort()
     content = parser.parse(Application.__doc__) + \
         [lcg.TableOfContents(title="Application methods:", depth=1)]
     for name, method in sorted(Application.__dict__.items()):
         if name.startswith('_') or name.startswith('action_') \
                 or not isinstance(method, collections.Callable) or not method.__doc__:
             continue
         args, varargs, varkw, defaults = inspect.getargspec(method)
         title = name + inspect.formatargspec(args[1:], varargs, varkw,
                                              defaults)
         doc = self._ARG_REGEX.sub(lambda m: ":" + m.group(1) + ": ",
                                   inspect.getdoc(method))
         content.append(
             lcg.Section(title=title, content=parser.parse(doc), id=name))
     return dict(content=content)
Ejemplo n.º 10
0
    def _content(self, lang):
        import wiking
        import wiking.cms

        def descr(option):
            content = [lcg.em(option.description())]
            doc = option.documentation()
            if doc:
                content.append(lcg.p(doc))
            content.append(lcg.p("*Default value:*", formatted=True))
            content.append(lcg.PreformattedText(option.default_string()))
            return content

        import lcg
        # Initial text is taken from configuration module docstring.
        intro = lcg.Parser().parse(lcg.unindent_docstring(wiking.cfg.__doc__))
        # Construct sections according to module and subsections with the config options
        sections = [
            lcg.Section(title=title,
                        content=[
                            lcg.Section(title="Option '%s'" % o.name(),
                                        id=o.name(),
                                        descr=o.description(),
                                        content=descr(o))
                            for o in cfg.options(sort=True) if o.visible()
                        ])
            for title, cfg in (("Wiking Configuration Options", wiking.cfg),
                               ("Wiking CMS Configuration Options",
                                wiking.cms.cfg))
        ]
        overview = [
            lcg.Section(title=section.title() + " Overview",
                        content=lcg.ul(
                            lcg.coerce((lcg.link(s, s.id()), ": ", s.descr()))
                            for s in section.sections()))
            for section in sections
        ]
        return dict(content=intro + overview + sections)
Ejemplo n.º 11
0
 def make_node(row, children):
     if row['help_id'].value() == topic:
         # If this is the currently displayed node, create the content.
         # Other nodes are only generated for their presence in the
         # menu.
         parser = lcg.Parser()
         if row['page_id'].value():
             storage = pytis.presentation.DbAttachmentStorage(
                 'e_pytis_help_pages_attachments', 'page_id', row['page_id'].value())
             content = lcg.Container(parser.parse(row['content'].value()),
                                     resources=storage.resources())
         else:
             content = [lcg.TableOfContents(title=_("Contents"))]
             fullname, spec_name = row['fullname'].value(), row['spec_name'].value()
             if row['menu_help'].value():
                 content.extend(parser.parse(row['menu_help'].value()))
             if fullname and fullname.startswith('handle/'):
                 pass
             elif fullname and fullname.startswith('proc/'):
                 pass
             elif spec_name == 'export':
                 pass
             elif spec_name == 'ui':
                 pass
             elif spec_name:
                 spec_help_content = self._spec_help_content(spec_name)[1]
                 if spec_help_content:
                     content.append(spec_help_content)
     else:
         content = ()
     return lcg.ContentNode('help:'+row['help_id'].value(), title=row['title'].value(),
                            descr=row['description'].value(), foldable=True,
                            content=lcg.Container(content),
                            resource_provider=resource_provider,
                            children=[make_node(r, children) for r in
                                      children.get(row['position'].value(), ())])
Ejemplo n.º 12
0
Archivo: read.py Proyecto: cerha/lcg
 def __init__(self, *args, **kwargs):
     self._parser = lcg.Parser()
     self._titles = {}
     super(StructuredTextReader, self).__init__(*args, **kwargs)
Ejemplo n.º 13
0
 def __init__(self, *args, **kwargs):
     self._parser = lcg.Parser()
     super(StructuredTextField, self).__init__(*args, **kwargs)
Ejemplo n.º 14
0
 def _spec_help_content(self, spec_name):
     from pytis.form import has_access
     if not has_access(spec_name):
         return (_("Access denied"),
                 lcg.p(_("You don't have permissions for specification „%s“.") % spec_name))
     resolver = pytis.util.resolver()
     def spec_link(spec_name, title=None):
         if title is None:
             try:
                 view_spec = resolver.get(spec_name, 'view_spec')
             except pytis.util.ResolverError as e:
                 title = spec_name
             else:
                 title = view_spec.title()
         return lcg.link('help:spec/%s' % spec_name, title)
     descriptions = self._spec_items_descriptions(spec_name)
     def description(kind, identifier, default):
         return descriptions[kind].get(identifier, default or _("Description not available."))
     def field_label(f):
         label = f.column_label()
         if not label:
             label = f.label() or f.id()
         elif f.label() and f.label() != label:
             label += ' ('+ f.label()+')'
         return label
     def field_description(f):
         result = description('field', f.id(), f.descr())
         related_specnames = [name for name in
                              [f.codebook()] + [link.name() for link in f.links()] if name]
         if related_specnames:
             pytis.util.remove_duplicates(related_specnames)
             result = (result,
                       lcg.p(_("Related views:")),
                       lcg.ul([spec_link(name) for name in related_specnames]))
         return result
     try:
         view_spec = resolver.get(spec_name, 'view_spec')
     except pytis.util.ResolverError as e:
         return None, None
     data = pytis.data.dbtable('e_pytis_help_spec', ('spec_name', 'description', 'help'),
                               config.dbconnection)
     row = data.row((pytis.data.Value(data.find_column('spec_name').type(), spec_name),))
     if row:
         spec_description = row['description'].value()
         spec_help = row['help'].value()
     else:
         spec_description = view_spec.description()
         spec_help = view_spec.help()
     parser = lcg.Parser()
     sections = [
         lcg.Section(title=title, content=f(content))
         for title, f, content in (
             (_("Overview"), lcg.p, spec_description),
             (_("Description"), parser.parse, spec_help),
             (_("Form fields"), lcg.dl,
              sorted([(field_label(f), field_description(f)) for f in view_spec.fields()],
                     key=lambda x: x[0])),
             (_("Profiles"), lcg.dl,
              [(p.title(), description('profile', p.id(), p.descr()))
               for p in view_spec.profiles().unnest()]),
             (_("Context menu actions"), lcg.dl,
              [(a.title(), description('action', a.id(), a.descr()))
               for a in view_spec.actions(unnest=True)]),
             (_("Side forms"), lcg.dl,
              [(spec_link(b.name(), b.title()), description('binding', b.id(), b.descr()))
               for b in view_spec.bindings() if b.name()]),
             )
         if content]
     #data_spec = resolver.get(specname, 'data_spec')
     #rights = data_spec.access_rights()
     #if rights:
     #    content += "\n\n== %s ==\n\n" % _(u"Přístupová práva")
     #    for perm in (pd.Permission.VIEW,
     #                 pd.Permission.INSERT,
     #                 pd.Permission.UPDATE,
     #                 pd.Permission.DELETE,
     #                 pd.Permission.EXPORT):
     #        groups = [g for g in rights.permitted_groups(perm, None) if g]
     #        content += ":%s:: %s\n" % (perm, ', '.join(map(str, groups)) or _(u"Nedefinováno"))
     storage = pytis.presentation.DbAttachmentStorage('e_pytis_help_spec_attachments',
                                                      'spec_name', spec_name)
     return view_spec.title(), lcg.Container(sections, resources=storage.resources())
Ejemplo n.º 15
0
 def __init__(self):
     self._parser = lcg.Parser()