Пример #1
0
    def convert_content(self, req, input_type, text, output_type):
        page_name = req.args.get('page', 'WikiStart')
        wikipage = WikiPage(self.env, page_name)

        wikiprint = WikiPrint(self.env)

        page = wikiprint.wikipage_to_html(text, page_name, req)

        #Get page title from first header in outline
        out = StringIO.StringIO()
        context = Context(Resource('wiki', page_name), req.abs_href, req.perm)
        context.req = req

        outline = OutlineFormatter(self.env, context)
        outline.format(text, out, 1, 1)

        title = wikipage.name
        for depth, anchor, text in outline.outline:
            if depth == 1:
                title = text
                break

        out = wikiprint.html_to_pdf(req, [page],
                                    book=(output_type == 'pdfbook'),
                                    title=title,
                                    subject="%s - %s" %
                                    (self.env.project_name, page_name),
                                    version=str(wikipage.version),
                                    date=format_datetime(to_datetime(None)))
        return (out, 'application/pdf')
Пример #2
0
    def expand_macro(self, formatter, name, content):
        min_depth, max_depth = 1, 6
        title = None
        inline = 0
        if content:
            argv = [arg.strip() for arg in content.split(',')]
            if len(argv) > 0:
                depth = argv[0]
                if '-' in depth:
                    min_depth, max_depth = [int(d)
                                            for d in depth.split('-', 1)]
                else:
                    min_depth = max_depth = int(depth)
                if len(argv) > 1:
                    title = argv[1].strip()
                    if len(argv) > 2:
                        inline = argv[2].strip().lower() == 'inline'

        # TODO: - integrate the rest of the OutlineFormatter directly here
        #       - use formatter.wikidom instead of formatter.source
        out = StringIO()
        oformatter = OutlineFormatter(self.env, formatter.context)
        oformatter.format(formatter.source, out, max_depth, min_depth,
                          shorten=not inline)
        outline = Markup(out.getvalue())

        if title:
            outline = tag.h4(title) + outline
        if not inline:
            outline = tag.div(outline, class_='wiki-toc')
        return outline
Пример #3
0
    def convert_content(self, req, input_type, text, output_type):
        page_name = req.args.get('page', 'WikiStart')
        wikipage = WikiPage(self.env, page_name)
        
        wikiprint = WikiPrint(self.env)
        
        page = wikiprint.wikipage_to_html(text, page_name, req)
        
        #Get page title from first header in outline
        out = StringIO.StringIO()
        context = Context(Resource('wiki', page_name), req.abs_href, req.perm)
        context.req = req

        outline = OutlineFormatter(self.env, context)
        outline.format(text, out, 1, 1)
        
        title = wikipage.name
        for depth, anchor, text in outline.outline:
            if depth == 1:
                title = text
                break
        
        out = wikiprint.html_to_pdf(req, [page], book = (output_type == 'pdfbook'),
            title=title,
            subject="%s - %s" % (self.env.project_name, page_name),
            version=str(wikipage.version),
            date=format_datetime(to_datetime(None)))
        return (out, 'application/pdf')
Пример #4
0
 class Outliner(object):
     flavor = 'outliner'
     def __init__(self, env, context, input):
         self.outliner = OutlineFormatter(env, context)
         self.input = input
     def generate(self):
         out = StringIO()
         self.outliner.format(self.input, out)
         return out.getvalue()
Пример #5
0
 class Outliner(object):
     flavor = 'outliner'
     def __init__(self, env, context, input):
         self.outliner = OutlineFormatter(env, context)
         self.input = input
     def generate(self):
         out = StringIO()
         self.outliner.format(self.input, out)
         return out.getvalue()
Пример #6
0
 def _render_page_outline(self, formatter, ol, page_resource, active, params):
     page = params.get('root', '') + page_resource.id
     page_text, page_exists = self.get_page_text(formatter, page_resource)
     if page_exists:
         ctx = formatter.context(page_resource)
         fmt = OutlineFormatter(self.env, ctx)
         fmt.format(page_text, NullOut())
         outline_tree(self.env, ol, fmt.outline, ctx,
                 active and page_resource.id == formatter.context.resource.id,
                 params['min_depth'], params['max_depth'])
     else:
         ol.append(system_message('Error: Page %s does not exist' %
                                  page_resource.id))
Пример #7
0
 def _render_page_outline(self, formatter, ol, page_resource, active,
                          params):
     page = params.get('root', '') + page_resource.id
     page_text, page_exists = self.get_page_text(formatter, page_resource)
     if page_exists:
         ctx = formatter.context(page_resource)
         fmt = OutlineFormatter(self.env, ctx)
         fmt.format(page_text, NullOut())
         outline_tree(
             self.env, ol, fmt.outline, ctx, active
             and page_resource.id == formatter.context.resource.id,
             params['min_depth'], params['max_depth'])
     else:
         ol.append(
             system_message('Error: Page %s does not exist' %
                            page_resource.id))
Пример #8
0
 def _render_title_index(self, formatter, ol, page_resource, active, show_title):
     page_text, page_exists = self.get_page_text(formatter, page_resource)
     if not page_exists:
         ol.append(system_message('Error: No page matching %s found' %
                                  page_resource.id))
         return
     ctx = formatter.context(page_resource)
     fmt = OutlineFormatter(self.env, ctx)
     fmt.format(page_text, NullOut())
     title = ''
     if show_title and fmt.outline:
         title = ': ' + fmt.outline[0][2]
     ol.append((tag.li(tag.a(page_resource.id,
                   href=get_resource_url(self.env, page_resource, ctx.href)),
                   Markup(title),
                   class_= active and 'active' or None)))
Пример #9
0
    def expand_macro(self, formatter, name, content):
        min_depth, max_depth = 1, 6
        title = None
        inline = False
        numbered = True
        if content:
            argv = [arg.strip() for arg in content.split(',')]
            if len(argv) > 0:
                depth = argv[0]
                if '-' in depth:
                    min_depth, max_depth = \
                        [_arg_as_int(d, min=min_depth, max=max_depth)
                         for d in depth.split('-', 1)]
                else:
                    min_depth = max_depth = \
                        _arg_as_int(depth, min=min_depth, max=max_depth)
                if len(argv) > 1:
                    title = argv[1].strip()
                    for arg in argv[2:]:
                        arg = arg.strip().lower()
                        if arg == 'inline':
                            inline = True
                        elif arg == 'unnumbered':
                            numbered = False

        # TODO: - integrate the rest of the OutlineFormatter directly here
        #       - use formatter.wikidom instead of formatter.source
        out = io.StringIO()
        oformatter = OutlineFormatter(self.env, formatter.context)
        oformatter.format(formatter.source,
                          out,
                          max_depth,
                          min_depth,
                          shorten=not inline)
        outline = Markup(out.getvalue())

        if title:
            outline = tag.h4(title) + outline
        if not inline:
            outline = tag.div(outline, class_='wiki-toc')
        elif not numbered:
            outline = tag.div(outline, class_='wiki-toc-un')
        return outline
Пример #10
0
 def _render_title_index(self, formatter, ol, page_resource, active,
                         show_title):
     page_text, page_exists = self.get_page_text(formatter, page_resource)
     if not page_exists:
         ol.append(
             system_message('Error: No page matching %s found' %
                            page_resource.id))
         return
     ctx = formatter.context(page_resource)
     fmt = OutlineFormatter(self.env, ctx)
     fmt.format(page_text, NullOut())
     title = ''
     if show_title and fmt.outline:
         title = ': ' + fmt.outline[0][2]
     ol.append((tag.li(tag.a(page_resource.id,
                             href=get_resource_url(self.env, page_resource,
                                                   ctx.href)),
                       Markup(title),
                       class_=active and 'active' or None)))
Пример #11
0
 def __init__(self, env, context, input):
     self.outliner = OutlineFormatter(env, context)
     self.input = input
def get_view_artifact(request, dbp, obj, resource):
    require_permission(request.req, resource, dbp.env)

    artifact_url = request.req.href.customartifacts('artifact/{0}'.format(obj.get_id()))
    spec_name, spec_url, values = _get_artifact_details(obj, request.req)

    # Getting wiki pages that refer the artifact
    related_pages = []
    from trac.wiki.formatter import OutlineFormatter
    from trac.web.chrome import web_context

    class NullOut(object):
        def write(self, *args): pass

    for pagename, page_version_id, ref_count in dbp.get_wiki_page_ref_counts(obj):
        page = WikiPage(dbp.env, pagename)

        fmt = OutlineFormatter(dbp.env, web_context(request.req))
        fmt.format(page.text, NullOut())
        title = ''
        text = page.text
        if fmt.outline:
            title = fmt.outline[0][2]
            text = re.sub('[=]+[ ]+' + title + '[ ]+[=]+\s?','', text)

        related_pages.append(
            {'href': get_resource_url(dbp.env, page.resource, request.req.href),
             'title': title if title else pagename,
             'date': user_time(request.req, format_datetime, page.time),
             'author': page.author,
             'excerpt': shorten_result(text)})

    # Getting artifacts that this artifact refers to
    referred_artifacts = []
    from AdaptiveArtifacts import get_artifact_id_names_from_text
    for attribute_name, value in obj.get_values():
        for related_artifact_id,related_artifact_text in get_artifact_id_names_from_text(unicode(value)):
            if dbp.pool.get_item(related_artifact_id) is None:
                dbp.load_artifact(related_artifact_id)
            referred_artifacts.append((dbp.pool.get_item(related_artifact_id),  "%s (%s)" % (related_artifact_text, attribute_name)))

    # Getting artifacts whose attribute values refer this artifact
    referring_artifacts = []
    for related_artifact_id, related_artifact_version_id, ref_count in dbp.get_related_artifact_ref_counts(obj):
        if dbp.pool.get_item(related_artifact_id) is None:
            dbp.load_artifact(related_artifact_id)
        artifact = dbp.pool.get_item(related_artifact_id)

        url = request.req.href.customartifacts('artifact/%d' % (artifact.get_id(),), action='view')
        rel_spec_name = artifact.__class__.get_name() if not artifact.__class__ is Instance else None
        rel_spec_url = request.req.href.customartifacts('spec', artifact.__class__.get_id(), action='view'),
        id_version, time, author, ipnr, comment, readonly = dbp.get_latest_version_details(artifact.get_id())
        referring_artifacts.append(
            {'href': url,
             'spec_name': rel_spec_name,
             'spec_url': rel_spec_url,
             'author': author,
             'date': user_time(request.req, format_datetime, time),
             'artifact': artifact}
        )

    # Build yuml url
    class YUMLDiagram(object):
        def __init__(self):
            self.classes = []
            self.base_url = "http://yuml.me/diagram/plain/class/"
            self._diagram = ""
            self.is_incomplete = False

        def add_class(self, header, body, associations):
            self.classes.append({'header': header, 'body': body, 'associations': associations})

        def serialize(self):
            for yuml_class in self.classes:
                yuml_fragment = "[" + yuml_class['header']
                if yuml_class['body']:
                    yuml_fragment += "|" + ";".join(yuml_class['body'])
                yuml_fragment += "],"
                self._diagram += yuml_fragment

                if yuml_class['associations']:
                    for association_target,association_label, in yuml_class['associations']:
                        yuml_fragment = "[%s]-%s>[%s]," % (yuml_class['header'], association_label, association_target)
                        self._diagram += yuml_fragment

        def get_dsl_text(self):
            return self._diagram.encode('utf8').replace(" ", " ")

        def get_url(self):
            #Could be used for GET requests, as long as it doesn't exceed the maximum URL size
            #return self.base_url + quote(self.get_dsl_text(), "[],;:->=")
            from urllib2 import Request, urlopen
            from urllib import urlencode
            try:
                image_filename = urlopen(Request(yuml.base_url, data=urlencode({'dsl_text': yuml.get_dsl_text()}))).read()
            except HTTPError:
                return ""
            return self.base_url + image_filename

    yuml = YUMLDiagram()

    def artifact_to_yuml_class(rel_artifact, include_values=True):
        def sanitize(value):
            if type(value) == list:
                value = ",".join(value)
            for i, j in {"[": "(",
                         "]": ")",
                         ",": ".",
                         ";": ".",
                         "->": "-",
                         "|": "\\",
                         }.iteritems():
                value = value.replace(i, j)
            return value if len(value) < 128 else "..."

        rel_artifact_title = unicode(rel_artifact)
        rel_spec_name = (u" : " + rel_artifact.__class__.get_name()) if not rel_artifact.__class__ is Instance else u""
        header = rel_artifact_title + rel_spec_name
        body = []
        if include_values:
            for attribute_name, value in rel_artifact.get_values():
                body.append("%s = %s" % (sanitize(attribute_name), sanitize(value)))
        return {'header': sanitize(header), 'body': body, 'associations': []}

    yuml_class = artifact_to_yuml_class(obj)
    yuml_class['body'].append('{bg:orange}') # color the main artifact differently
    yuml_class['associations'] = [(artifact_to_yuml_class(rel_artifact, False)['header'], rel_artifact_text) for rel_artifact, rel_artifact_text in referred_artifacts]
    yuml.add_class(**yuml_class)

    for rel_artifact in referring_artifacts:
        rel_yuml_class = artifact_to_yuml_class(rel_artifact['artifact'])
        rel_yuml_class['associations'] = [(artifact_to_yuml_class(obj, False)['header'], "")]
        yuml.add_class(**rel_yuml_class)

    yuml.serialize()

    # track access
    dbp.track_it("artifact", obj.get_id(), "view", request.req.authname, str(datetime.now()))

    data = {
        'context': Context.from_request(request.req, resource),
        'spec_name': spec_name,
        'spec_url': spec_url,
        'artifact': obj,
        'artifact_url': artifact_url,
        'artifacts_values': values,
        'related_pages': related_pages,
        'related_artifacts': referring_artifacts,
        'show_diagram': dbp.env.config.getbool('asa', 'show_diagram', default=True),
        'yuml_url': yuml.get_url(),
    }
    return 'view_artifact_%s.html' % (request.get_format(),), data, None
def get_view_artifact(request, dbp, obj, resource):
    require_permission(request.req, resource, dbp.env)

    artifact_url = request.req.href.customartifacts('artifact/{0}'.format(
        obj.get_id()))
    spec_name, spec_url, values = _get_artifact_details(obj, request.req)

    # Getting wiki pages that refer the artifact
    related_pages = []
    from trac.wiki.formatter import OutlineFormatter
    from trac.web.chrome import web_context

    class NullOut(object):
        def write(self, *args):
            pass

    for pagename, page_version_id, ref_count in dbp.get_wiki_page_ref_counts(
            obj):
        page = WikiPage(dbp.env, pagename)

        fmt = OutlineFormatter(dbp.env, web_context(request.req))
        fmt.format(page.text, NullOut())
        title = ''
        text = page.text
        if fmt.outline:
            title = fmt.outline[0][2]
            text = re.sub('[=]+[ ]+' + title + '[ ]+[=]+\s?', '', text)

        related_pages.append({
            'href':
            get_resource_url(dbp.env, page.resource, request.req.href),
            'title':
            title if title else pagename,
            'date':
            user_time(request.req, format_datetime, page.time),
            'author':
            page.author,
            'excerpt':
            shorten_result(text)
        })

    # Getting artifacts that this artifact refers to
    referred_artifacts = []
    from AdaptiveArtifacts import get_artifact_id_names_from_text
    for attribute_name, value in obj.get_values():
        for related_artifact_id, related_artifact_text in get_artifact_id_names_from_text(
                unicode(value)):
            if dbp.pool.get_item(related_artifact_id) is None:
                dbp.load_artifact(related_artifact_id)
            referred_artifacts.append(
                (dbp.pool.get_item(related_artifact_id),
                 "%s (%s)" % (related_artifact_text, attribute_name)))

    # Getting artifacts whose attribute values refer this artifact
    referring_artifacts = []
    for related_artifact_id, related_artifact_version_id, ref_count in dbp.get_related_artifact_ref_counts(
            obj):
        if dbp.pool.get_item(related_artifact_id) is None:
            dbp.load_artifact(related_artifact_id)
        artifact = dbp.pool.get_item(related_artifact_id)

        url = request.req.href.customartifacts('artifact/%d' %
                                               (artifact.get_id(), ),
                                               action='view')
        rel_spec_name = artifact.__class__.get_name(
        ) if not artifact.__class__ is Instance else None
        rel_spec_url = request.req.href.customartifacts(
            'spec', artifact.__class__.get_id(), action='view'),
        id_version, time, author, ipnr, comment, readonly = dbp.get_latest_version_details(
            artifact.get_id())
        referring_artifacts.append({
            'href':
            url,
            'spec_name':
            rel_spec_name,
            'spec_url':
            rel_spec_url,
            'author':
            author,
            'date':
            user_time(request.req, format_datetime, time),
            'artifact':
            artifact
        })

    # Build yuml url
    class YUMLDiagram(object):
        def __init__(self):
            self.classes = []
            self.base_url = "http://yuml.me/diagram/plain/class/"
            self._diagram = ""
            self.is_incomplete = False

        def add_class(self, header, body, associations):
            self.classes.append({
                'header': header,
                'body': body,
                'associations': associations
            })

        def serialize(self):
            for yuml_class in self.classes:
                yuml_fragment = "[" + yuml_class['header']
                if yuml_class['body']:
                    yuml_fragment += "|" + ";".join(yuml_class['body'])
                yuml_fragment += "],"
                self._diagram += yuml_fragment

                if yuml_class['associations']:
                    for association_target, association_label, in yuml_class[
                            'associations']:
                        yuml_fragment = "[%s]-%s>[%s]," % (
                            yuml_class['header'], association_label,
                            association_target)
                        self._diagram += yuml_fragment

        def get_dsl_text(self):
            return self._diagram.encode('utf8').replace(" ", "&nbsp;")

        def get_url(self):
            #Could be used for GET requests, as long as it doesn't exceed the maximum URL size
            #return self.base_url + quote(self.get_dsl_text(), "[],;:->=")
            from urllib2 import Request, urlopen
            from urllib import urlencode
            try:
                image_filename = urlopen(
                    Request(yuml.base_url,
                            data=urlencode({'dsl_text':
                                            yuml.get_dsl_text()}))).read()
            except HTTPError:
                return ""
            return self.base_url + image_filename

    yuml = YUMLDiagram()

    def artifact_to_yuml_class(rel_artifact, include_values=True):
        def sanitize(value):
            if type(value) == list:
                value = ",".join(value)
            for i, j in {
                    "[": "(",
                    "]": ")",
                    ",": ".",
                    ";": ".",
                    "->": "-",
                    "|": "\\",
            }.iteritems():
                value = value.replace(i, j)
            return value if len(value) < 128 else "..."

        rel_artifact_title = unicode(rel_artifact)
        rel_spec_name = (u" : " + rel_artifact.__class__.get_name()
                         ) if not rel_artifact.__class__ is Instance else u""
        header = rel_artifact_title + rel_spec_name
        body = []
        if include_values:
            for attribute_name, value in rel_artifact.get_values():
                body.append("%s = %s" %
                            (sanitize(attribute_name), sanitize(value)))
        return {'header': sanitize(header), 'body': body, 'associations': []}

    yuml_class = artifact_to_yuml_class(obj)
    yuml_class['body'].append(
        '{bg:orange}')  # color the main artifact differently
    yuml_class['associations'] = [
        (artifact_to_yuml_class(rel_artifact,
                                False)['header'], rel_artifact_text)
        for rel_artifact, rel_artifact_text in referred_artifacts
    ]
    yuml.add_class(**yuml_class)

    for rel_artifact in referring_artifacts:
        rel_yuml_class = artifact_to_yuml_class(rel_artifact['artifact'])
        rel_yuml_class['associations'] = [
            (artifact_to_yuml_class(obj, False)['header'], "")
        ]
        yuml.add_class(**rel_yuml_class)

    yuml.serialize()

    # track access
    dbp.track_it("artifact", obj.get_id(), "view", request.req.authname,
                 str(datetime.now()))

    data = {
        'context': Context.from_request(request.req, resource),
        'spec_name': spec_name,
        'spec_url': spec_url,
        'artifact': obj,
        'artifact_url': artifact_url,
        'artifacts_values': values,
        'related_pages': related_pages,
        'related_artifacts': referring_artifacts,
        'show_diagram': dbp.env.config.getbool('asa',
                                               'show_diagram',
                                               default=True),
        'yuml_url': yuml.get_url(),
    }
    return 'view_artifact_%s.html' % (request.get_format(), ), data, None
Пример #14
0
 def __init__(self, env, context, input):
     self.outliner = OutlineFormatter(env, context)
     self.input = input