Ejemplo n.º 1
0
 def _handle(self, req):
     module_names = self._reload_modules(req)
     content = lcg.coerce((
         lcg.p(_("The following modules were successfully reloaded:")),
         lcg.p(", ".join(module_names)),
     ))
     return wiking.Document(_("Reload"), lcg.coerce(content))
Ejemplo n.º 2
0
 def handle(self, req):
     req.wmi = False # Will be set to True by `WikingManagementInterface' if needed.
     preview_mode_param = req.param(self._PREVIEW_MODE_PARAM)
     if preview_mode_param is not None:
         req.set_cookie(self._PREVIEW_MODE_COOKIE, preview_mode_param == '1' and '1' or None)
     wiking.module.CachedTables.reload_info(req)
     wiking.module.Config.configure(req)
     modname = self._resolve_modname(req)
     if modname:
         return req.forward(wiking.module(modname))
     else:
         try:
             return super(Application, self).handle(req)
         except wiking.Forbidden:
             # The parent method raises Forbidden when there are no menu items to redirect to.
             if req.check_roles(Roles.CONTENT_ADMIN):
                 # Give the administrator some hints on a fresh install.
                 if wiking.module.Pages.empty(req):
                     return wiking.Document(
                         title=_("Welcome to Wiking CMS"),
                         content=lcg.Container((lcg.p("There are currently no pages."),
                                                lcg.p(lcg.link("/?action=insert",
                                                               _("Create a new page"))))),
                     )
                 elif not self.preview_mode(req):
                     req.message(_("There are no published pages. "
                                   "You need to switch to the Preview mode "
                                   "to be able to access the unpublished pages."),
                                 req.WARNING)
             raise
Ejemplo n.º 3
0
 def handle(self, req):
     req.wmi = False  # Will be set to True by `WikingManagementInterface' if needed.
     preview_mode_param = req.param(self._PREVIEW_MODE_PARAM)
     if preview_mode_param is not None:
         req.set_cookie(self._PREVIEW_MODE_COOKIE, preview_mode_param == '1' and '1' or None)
     wiking.module.CachedTables.reload_info(req)
     wiking.module.Config.configure(req)
     modname = self._resolve_modname(req)
     if modname:
         return req.forward(wiking.module(modname))
     else:
         try:
             return super(Application, self).handle(req)
         except wiking.Forbidden:
             # The parent method raises Forbidden when there are no menu items to redirect to.
             if req.check_roles(Roles.CONTENT_ADMIN):
                 # Give the administrator some hints on a fresh install.
                 if wiking.module.Pages.empty(req):
                     return wiking.Document(
                         title=_("Welcome to Wiking CMS"),
                         content=lcg.Container((lcg.p("There are currently no pages."),
                                                lcg.p(lcg.link("/?action=insert",
                                                               _("Create a new page"))))),
                     )
                 elif not self.preview_mode(req):
                     req.message(_("There are no published pages. "
                                   "You need to switch to the Preview mode "
                                   "to be able to access the unpublished pages."),
                                 req.WARNING)
             raise
Ejemplo n.º 4
0
 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
Ejemplo n.º 5
0
 def authoring(cls):
     content = [lcg.p(p) for p in cls._HELP_INTRO]
     if cls._SOURCE_FORMATTING:
         content.append(lcg.Section(title=_("Exercise Definition"),
                                    content=[lcg.p(p) for p in cls._SOURCE_FORMATTING]))
     if cls._SOURCE_EXAMPLE:
         content.append(lcg.Section(title=_("Definition Example"),
                                    content=lcg.pre(cls._SOURCE_EXAMPLE.strip())))
     return lcg.Section(title=cls.name(), content=content)
Ejemplo n.º 6
0
 def authoring(cls):
     content = [lcg.p(p) for p in cls._HELP_INTRO]
     if cls._SOURCE_FORMATTING:
         content.append(
             lcg.Section(title=_("Exercise Definition"),
                         content=[lcg.p(p)
                                  for p in cls._SOURCE_FORMATTING]))
     if cls._SOURCE_EXAMPLE:
         content.append(
             lcg.Section(title=_("Definition Example"),
                         content=lcg.pre(cls._SOURCE_EXAMPLE.strip())))
     return lcg.Section(title=cls.name(), content=content)
Ejemplo n.º 7
0
 def _help_panel(cls):
     if cls._BUTTONS:
         return (lcg.p(_("The control panel below the exercise contains the following "
                         "buttons:")),
                 lcg.dl([(label, hlp) for label, t, name, hlp in cls._BUTTONS]))
     else:
         return None
Ejemplo n.º 8
0
 def _pytis_help(self, resource_dirs):
     image_dir = os.path.join(config.help_dir, 'img')
     resource_provider = lcg.ResourceProvider(dirs=[image_dir] + resource_dirs)
     def clone(node, node_id):
         # Clone the content node, but force `id' to help URI and `foldable' to True.
         return lcg.ContentNode(node_id, title=node.title(), descr=node.descr(),
                                content=node.content(), hidden=node.hidden(),
                                children=[clone(n, 'help:pytis/'+n.id()) for n in node.children()],
                                resource_provider=resource_provider,
                                foldable=True)
     try:
         node = self._pytis_help_root_node
     except AttributeError:
         directory = os.path.join(config.help_dir, 'src')
         reader = lcg.reader(directory, 'pytis', ext='txt', resource_provider=resource_provider)
         try:
             node = self._pytis_help_root_node = reader.build()
         except IOError as e:
             log(OPERATIONAL, "Unable to read Pytis help files from '%s':" % directory, e)
             node = lcg.ContentNode('pytis:', title=_("Pytis User Guide"),
                                    content=lcg.p(_("Help files not found!")),
                                    hidden=True, resource_provider=resource_provider)
     # We need to clone on every request because set_parent() is called on
     # the result when added to the help tree and set_parent may not be
     # called multiple times.
     return clone(node, 'help:pytis')
Ejemplo n.º 9
0
 def _pytis_help_nodes(self):
     def clone(node, id):
         return self.ContentNode(
             id=id,
             title=node.title(),
             descr=node.descr(),
             content=node.content(),
             hidden=node.hidden(),
             children=[clone(n, 'help:pytis/' + n.id()) for n in node.children()],
             resource_provider=self._resource_provider,
             foldable=True,
         )
     directory = os.path.join(pytis.config.help_dir, 'src')
     reader = lcg.reader(directory, 'pytis', ext='txt',
                         resource_provider=self._resource_provider)
     try:
         node = reader.build()
     except IOError as e:
         log(OPERATIONAL, "Unable to read Pytis help files from '%s':" % directory, e)
         node = self.ContentNode('help:pytis', title=_("Pytis User Guide"),
                                 content=lcg.p(_("Help files not found!")),
                                 hidden=True, resource_provider=self._resource_provider)
     else:
         node = clone(node, 'help:pytis')
     return node
Ejemplo n.º 10
0
 def _access_rights(self, spec_name, view_spec):
     access_rights = pytis.config.resolver.get(spec_name, 'access_spec')
     if not access_rights:
         return None
     permissions = (
         (_("View"), pd.Permission.VIEW),
         (_("Insert"), pd.Permission.INSERT),
         (_("Update"), pd.Permission.UPDATE),
         (_("Delete"), pd.Permission.DELETE),
         (_("Call"), pd.Permission.CALL),
         (_("Export"), pd.Permission.EXPORT),
         (_("Print"), pd.Permission.PRINT),
     )
     result = []
     for label, permission in permissions:
         groups = tuple(access_rights.permitted_groups(permission, None))
         if groups:
             content = [', '.join(groups)]
             field_access = {}
             for field in view_spec.fields():
                 if not field.virtual():
                     field_groups = tuple(access_rights.permitted_groups(permission, field.id()))
                     if field_groups != groups:
                         field_access.setdefault(field_groups, []).append(field)
             if field_access:
                 content.extend((
                     lcg.p(_("Column restrictions:")),
                     lcg.ul((
                         lcg.strong(', '.join(f.label() or f.id() for f in fields)), lcg.br(),
                         ', '.join(groups) or lcg.em(_("no access"))
                     ) for groups, fields in field_access.items()),
                 ))
             result.append((label, content))
     return result
Ejemplo n.º 11
0
 def _help_panel(cls):
     if cls._BUTTONS:
         return (lcg.p(_("The control panel below the exercise contains the following "
                         "buttons:")),
                 lcg.dl([(label, hlp) for label, t, name, hlp in cls._BUTTONS]))
     else:
         return None
Ejemplo n.º 12
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.º 13
0
 def _result_item(self, item):
     sample = item.sample()
     link = lcg.link(item.uri(), label=item.title(), descr=sample,)
     if sample is None:
         result_item = lcg.p((link,))
     else:
         result_item = lcg.dl(((link, sample),))
     return result_item
Ejemplo n.º 14
0
 def _application_help_page_content(self, node, uri):
     globs = node.globals()
     command, args = globs['command'], globs['args']
     if command in (pytis.form.Application.COMMAND_RUN_FORM,
                    pytis.form.Application.COMMAND_NEW_RECORD):
         content = self._spec_help_content(args['name'])[1]
         if not content:
             if command == pytis.form.Application.COMMAND_RUN_FORM:
                 text = _("Opens the %s on specification", args['form_class'].descr())
             else:
                 text = _("Inserts a new record into")
             content = lcg.p(text, ' ', self._spec_link(args['name']), '.')
         return content
     return lcg.Container((
         lcg.p(_("Runs the command %s with the following arguments:", command.id())),
         lcg.fieldset([(k, unistr(v)) for k, v in args.items()])
     ))
Ejemplo n.º 15
0
    def parse(self, exercise_type, src, **kwargs):
        """Convert textual exercise specification into an Exercise instance.

        Returns 'lcg.Exercise' instance on success or 'lcg.Container' instance
        with error information if the exercise specification is invalid.

        """
        try:
            try:
                read_task = {
                    MultipleChoiceQuestions: self._read_multiple_choice_task,
                    GapFilling: self._read_gap_filling_task,
                    Selections: self._read_selections_task,
                    TrueFalseStatements: self._read_true_false_statements_task,
                    HiddenAnswers: self._read_hidden_answers_task,
                    WrittenAnswers: self._read_written_answers_task,
                    VocabExercise: self._read_vocab_exercise_task,
                    NumberedCloze: self._read_numbered_cloze_task,
                    Cloze: self._read_cloze_task,
                    ModelCloze: self._read_cloze_task,
                }[exercise_type]
            except KeyError:
                self._error(_("Unknown exercise type: %s", exercise_type))
            tasks = []
            try:
                if src:
                    assert 'template' not in kwargs
                    if issubclass(exercise_type, Cloze):
                        pieces = (src,)
                    else:
                        pieces = self._split(src)
                    i = 0
                    while i < len(pieces):
                        t = pieces[i]
                        if i + 1 < len(pieces) and pieces[i + 1].startswith('.. '):
                            comment = pieces[i + 1][3:]
                            i += 2
                        else:
                            comment = None
                            i += 1
                        tasks.append(read_task(t, comment))
                elif 'template' in kwargs:
                    def maketask(match):
                        tasks.append(read_task(match.group(1), None))
                        return "%s"
                    m = self._TEMPLATE_TASK_MATCHER
                    kwargs['template'] = m.sub(maketask, kwargs['template'].replace('%', '%%'))
            except self.ExerciseParserError as e:
                self._error(e.message(), task_number=len(tasks) + 1)
        except self.ExerciseParserError as e:
            if e.task_number() is not None:
                message = _("Error in task %d: %s", e.task_number(), e.message())
            else:
                message = _("Error: %s", e.message())
            return lcg.Container((lcg.p(message, name='error-message'),
                                  lcg.PreformattedText(src)),
                                 name='exercise-specification-error')
        return exercise_type(tasks, **kwargs)
Ejemplo n.º 16
0
    def footer_content(self, req):
        """Return the content displayed in page footer as 'lcg.Content' element(s).

        Any content acceptable by 'lcg.coerce()' may be returned.

        """
        return lcg.p(_("Contact:"), ' ',
                     lcg.link("mailto:" + wiking.cfg.webmaster_address,
                              wiking.cfg.webmaster_address))
Ejemplo n.º 17
0
    def footer_content(self, req):
        """Return the content displayed in page footer as 'lcg.Content' element(s).

        Any content acceptable by 'lcg.coerce()' may be returned.

        """
        return lcg.p(_("Contact:"), ' ',
                     lcg.link("mailto:" + wiking.cfg.webmaster_address,
                              wiking.cfg.webmaster_address))
Ejemplo n.º 18
0
 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
Ejemplo n.º 19
0
 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
Ejemplo n.º 20
0
 def _result_item(self, item):
     sample = item.sample()
     link = lcg.link(
         item.uri(),
         label=item.title(),
         descr=sample,
     )
     if sample is None:
         result_item = lcg.p((link, ))
     else:
         result_item = lcg.dl(((link, sample), ))
     return result_item
Ejemplo n.º 21
0
Archivo: appl.py Proyecto: dusek/wiking
 def handle(self, req):
     req.wmi = False # Will be set to True by `WikingManagementInterface' if needed.
     preview_mode_param = req.param(self._PREVIEW_MODE_PARAM)
     if preview_mode_param is not None:
         req.set_cookie(self._PREVIEW_MODE_COOKIE, preview_mode_param == '1' and '1' or None)
     wiking.module.CachedTables.reload_info(req)
     wiking.module.Config.configure(req)
     if req.unresolved_path:
         try:
             modname = self._mapping[req.unresolved_path[0]]
         except KeyError:
             modname = 'Pages'
         else:
             # Consume the unresolved path if it was in static mapping or
             # leave it for further resolution when passing to Pages.
             del req.unresolved_path[0]
     elif req.param('action'):
         if req.param('_manage_cms_panels') == '1':
             modname = 'Panels'
         else:
             modname = 'Pages'
     else:
         try:
             return super(Application, self).handle(req)
         except wiking.Forbidden:
             # The parent method raises Forbidden when there are no menu items to redirect to.
             if req.check_roles(Roles.CONTENT_ADMIN):
                 # Give the administrator some hints on a fresh install.
                 if wiking.module.Pages.empty(req):
                     raise wiking.Abort(_("Welcome to Wiking CMS"),
                                        lcg.Container((lcg.p("There are currently no pages."),
                                                       lcg.p(lcg.link("/?action=insert",
                                                                      _("Create a new page"))))))
                 elif not self.preview_mode(req):
                     req.message(_("There are no published pages. "
                                   "You need to switch to the Preview mode "
                                   "to be able to access the unpublished pages."),
                                 req.WARNING)
             raise
     return req.forward(wiking.module(modname))
Ejemplo n.º 22
0
 def _handle_maintenance_mode(self, req):
     import httplib
     # Translators: Meaning that the system (webpage) does not work now
     # because we are updating/fixing something but will work again after
     # the maintaince is finished.
     node = lcg.ContentNode(req.uri().encode('utf-8'), title=_("Maintenance Mode"),
                            content=lcg.p(_("The system is temporarily down for maintenance.")))
     exporter = wiking.MinimalExporter(translations=wiking.cfg.translation_path)
     try:
         lang = req.preferred_language()
     except:
         lang = wiking.cfg.default_language_by_domain.get(req.server_hostname(),
                                                          wiking.cfg.default_language) or 'en'
     context = exporter.context(node, lang=lang)
     exported = exporter.export(context)
     return req.send_response(context.localize(exported),
                              status_code=httplib.SERVICE_UNAVAILABLE)
Ejemplo n.º 23
0
 def _handle_maintenance_mode(self, req):
     import http.client
     # Translators: Meaning that the system (webpage) does not work now
     # because we are updating/fixing something but will work again after
     # the maintaince is finished.
     node = lcg.ContentNode(req.uri().encode('utf-8'), title=_("Maintenance Mode"),
                            content=lcg.p(_("The system is temporarily down for maintenance.")))
     exporter = wiking.MinimalExporter(translations=wiking.cfg.translation_path)
     try:
         lang = req.preferred_language()
     except Exception:
         lang = wiking.cfg.default_language_by_domain.get(req.server_hostname(),
                                                          wiking.cfg.default_language) or 'en'
     context = exporter.context(node, lang=lang)
     exported = exporter.export(context)
     return req.send_response(context.localize(exported),
                              status_code=http.client.SERVICE_UNAVAILABLE)
Ejemplo n.º 24
0
    def help_page(self, uri):
        """Return the complete help structure of LCG nodes with content for given uri.

        The returned value is an 'lcg.ContentNode' instance, which is a part of
        the complete menu structure (it refers to other 'lcg.ContentNode'
        instances through the parent/child relationships).  Only the returned
        node, however, actually has content (page to be displayed in the help
        browser).  Other nodes have empty content as they are only important as
        navigation menu items.

        """
        root = self._root()
        if uri.startswith('help:spec/'):
            # Separate specification descriptions are not part of the
            # static node structure generated by _root().
            title, content = self._spec_help_content(uri[10:])
            if content:
                node = self.ContentNode(
                    uri,
                    title=title,
                    hidden=True,
                    content=content,
                    resource_provider=self._resource_provider,
                )
                root.append_child(node)
            else:
                node = None
        else:
            # Try to find the node in the statically
            node = root.find_node(uri)
            if node and isinstance(node.content(), self.EmptyContent):
                node.update(self._application_help_page_content(node, uri))
        if not node:
            node = root.find_node('NotFound')
            if not node:
                node = self.ContentNode('NotFound', title=_("Not Found"), hidden=True,
                                        content=(), resource_provider=self._resource_provider)
                root.append_child(node)
            node.update(lcg.p(_("The requested help page not found: %s", uri)))
        return node
Ejemplo n.º 25
0
 def _help_keys(cls):
     return (lcg.p(_("In all the exercises where you fill in the text into a text box "
                     "you can use the two shortcut keys described below.")),
             lcg.dl(((_("Enter"),
                      _("Use this key within the text field to evaluate the current answer. "
                        "You hear a sound response and in case of an error, the cursor is "
                        "moved to the position of the first incorrect character within the "
                        "text.  This way you can locate the error, fix it and evaluate again. "
                        u"When you don't know how to fix an error, you can use the ‘hint’ "
                        "key described below.")),
                     (_("Ctrl-Space"),
                      _(u"This function is called a ‘hint’.  It helps you in case you don't "
                        "know the answer or you don't know how to fix an error in your answer. "
                        "Just press the key combination (holding the Ctrl key, press the "
                        "spacebar) and one letter of the correct answer will be filled in "
                        "automatically.  If you have already entered some text, the cursor "
                        "will be moved to after the last correct character and next one will "
                        "be inserted.  This also means that if there is some text after the "
                        "cursor, there is at least one error in it.  Try to locate this error "
                        "and correct it.  Then you can evaluate your answer using the "
                        u"‘Enter’ key (see above) or use ‘hint’ again, until you find the "
                        "complete answer.")))),)
Ejemplo n.º 26
0
 def _help_keys(cls):
     return (lcg.p(_("In all the exercises where you fill in the text into a text-box "
                     "you can use the two shortcut keys described below.")),
             lcg.dl(((_("Enter"),
                      _("Use this key within the text-field to evaluate the current answer. "
                        "You hear a sound response and in case of an error, the cursor is "
                        "moved to the position of the first incorrect character within the "
                        "text.  This way you can locate the error, fix it and evaluate again. "
                        u"When you don't know how to fix an error, you can use the ‘hint’ "
                        "key described below.")),
                     (_("Ctrl-Space"),
                      _(u"This function is called a ‘hint’.  It helps you in case you don't "
                        "know the answer or you don't know how to fix an error in your answer. "
                        "Just press the key combination (holding the Ctrl key, press the "
                        "spacebar) and one letter of the correct answer will be filled in "
                        "automatically.  If you have already entered some text, the cursor "
                        "will be moved to after the last correct character and next one will "
                        "be inserted.  This also means that if there is some text after the "
                        "cursor, there is at least one error in it.  Try to locate this error "
                        "and correct it.  Then you can evaluate your answer using the "
                        u"‘Enter’ key (see above) or use ‘hint’ again, until you find the "
                        "complete answer.")))),)
Ejemplo n.º 27
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.º 28
0
    def parse(self, exercise_type, src, **kwargs):
        """Convert textual exercise specification into an Exercise instance.

        Returns 'lcg.Exercise' instance on success or 'lcg.Container' instance
        with error information if the exercise specification is invalid.

        """
        try:
            try:
                read_task = {
                    MultipleChoiceQuestions: self._read_multiple_choice_task,
                    GapFilling: self._read_gap_filling_task,
                    Selections: self._read_selections_task,
                    TrueFalseStatements: self._read_true_false_statements_task,
                    HiddenAnswers: self._read_hidden_answers_task,
                    WrittenAnswers: self._read_written_answers_task,
                    VocabExercise: self._read_vocab_exercise_task,
                    NumberedCloze: self._read_numbered_cloze_task,
                    Cloze: self._read_cloze_task,
                    ModelCloze: self._read_cloze_task,
                }[exercise_type]
            except KeyError:
                self._error(_("Unknown exercise type: %s", exercise_type))
            tasks = []
            try:
                if src:
                    assert 'template' not in kwargs
                    if issubclass(exercise_type, Cloze):
                        pieces = (src, )
                    else:
                        pieces = self._split(src)
                    i = 0
                    while i < len(pieces):
                        t = pieces[i]
                        if i + 1 < len(pieces) and pieces[i +
                                                          1].startswith('.. '):
                            comment = pieces[i + 1][3:]
                            i += 2
                        else:
                            comment = None
                            i += 1
                        tasks.append(read_task(t, comment))
                elif 'template' in kwargs:

                    def maketask(match):
                        tasks.append(read_task(match.group(1), None))
                        return "%s"

                    m = self._TEMPLATE_TASK_MATCHER
                    kwargs['template'] = m.sub(
                        maketask, kwargs['template'].replace('%', '%%'))
            except self.ExerciseParserError as e:
                self._error(e.message(), task_number=len(tasks) + 1)
        except self.ExerciseParserError as e:
            if e.task_number() is not None:
                message = _("Error in task %d: %s", e.task_number(),
                            e.message())
            else:
                message = _("Error: %s", e.message())
            return lcg.Container((lcg.p(
                message, name='error-message'), lcg.PreformattedText(src)),
                                 name='exercise-specification-error')
        return exercise_type(tasks, **kwargs)
Ejemplo n.º 29
0
 def help_page(self, topic):
     """Return the help page for given topic as lcg.ContentNode instance."""
     resource_dirs = [d[:-3]+'resources' for d in sys.path
                      if d.endswith('/pytis/lib') or d.endswith('/lcg/lib')]
     resource_provider = lcg.ResourceProvider(dirs=resource_dirs)
     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(), ())])
     #data = pytis.data.dbtable('ev_pytis_user_help',
     #                          ('help_id', 'fullname', 'spec_name', 'page_id', 'position',
     #                           'title', 'description', 'menu_help', 'content', 'language',),
     #                          config.dbconnection)
     #data.select(condition=pytis.data.EQ('language', pytis.data.sval(current_language())),
     #            sort=(('position', pytis.data.ASCENDENT),))
     data = pytis.data.dbtable('ev_pytis_user_help',
                               ('help_id', 'fullname', 'spec_name', 'page_id', 'position',
                                'title', 'description', 'menu_help', 'content',),
                               config.dbconnection)
     data.select(sort=(('position', pytis.data.ASCENDENT),))
     children = {}
     while True:
         row = data.fetchone()
         if not row:
             break
         parent = '.'.join(row['position'].value().split('.')[:-1])
         children.setdefault(parent, []).append(row)
     data.close()
     nodes = [lcg.ContentNode('help:application',
                              title=_("%s application help") % config.application_name,
                              content=lcg.NodeIndex(), resource_provider=resource_provider,
                              children=[make_node(r, children) for r in children['']]),
              self._pytis_help(resource_dirs),
              lcg.ContentNode('NotFound', title=_("Not Found"), hidden=True,
                              content=lcg.p(_("The requested help page not found: %s",
                                              topic)),
                              resource_provider=resource_provider)]
     if topic.startswith('spec/'):
         # Separate specification descriptions are not in the menu generated
         # from ev_pytis_help.  If specification description page is
         # requested, we generate one and add it to the menu here.
         spec_name = topic[5:]
         title, content = self._spec_help_content(spec_name)
         if title and content:
             content = lcg.Container((lcg.TableOfContents(title=_("Contents")), content))
             node = lcg.ContentNode('help:'+topic, title=title, hidden=True, content=content,
                                    resource_provider=resource_provider)
             nodes.append(node)
     root = lcg.ContentNode('help:', content=lcg.Content(), hidden=True, children=nodes)
     return root.find_node('help:'+topic) or root.find_node('NotFound')
Ejemplo n.º 30
0
 def _empty_result_page(self):
     return lcg.p(_("Nothing found."))
Ejemplo n.º 31
0
 def _help_indicators(cls):
     if cls._INDICATORS:
         return (lcg.p(_("The indicator panel below the exercise shows the following values:")),
                 lcg.dl([(label, help) for name, label, help in cls._INDICATORS]))
     else:
         return None
Ejemplo n.º 32
0
 def _search_form(self, req, message=None):
     content = []
     if message is not None:
         content.append(lcg.p(message))
     content = [self.SearchForm(req)]
     return wiking.Document(self._SEARCH_TITLE, lcg.Container(content))
Ejemplo n.º 33
0
 def _help_indicators(cls):
     if cls._INDICATORS:
         return (lcg.p(_("The indicator panel below the exercise shows the following values:")),
                 lcg.dl([(label, help) for name, label, help in cls._INDICATORS]))
     else:
         return None
Ejemplo n.º 34
0
 def _search_form(self, req, message=None):
     content = []
     if message is not None:
         content.append(lcg.p(message))
     content = [self.SearchForm(req)]
     return wiking.Document(self._SEARCH_TITLE, lcg.Container(content))
Ejemplo n.º 35
0
 def help(cls):
     return lcg.Container([lcg.p(p) for p in cls._HELP_INTRO])
Ejemplo n.º 36
0
 def help(cls):
     return lcg.Container([lcg.p(p) for p in cls._HELP_INTRO])
Ejemplo n.º 37
0
 def _empty_result_page(self):
     return lcg.p(_("Nothing found."))
Ejemplo n.º 38
0
 def _handle(self, req):
     module_names = self._reload_modules(req)
     content = lcg.coerce((lcg.p(_("The following modules were successfully reloaded:")),
                           lcg.p(", ".join(module_names)),))
     return wiking.Document(_("Reload"), lcg.coerce(content))