Beispiel #1
0
def autorun_get_latex_interactive_session(cmds, **kargs):
    ct = conf.color_theme
    to_latex = lambda s: tex_escape(s).replace("@[@","{").replace("@]@","}").replace("@`@","\\")
    try:
        try:
            conf.color_theme = LatexTheme2()
            s,res = autorun_get_interactive_session(cmds, **kargs)
        except StopAutorun,e:
            e.code_run = to_latex(e.code_run)
            raise
    finally:
        conf.color_theme = ct
    return to_latex(s),res
Beispiel #2
0
def autorun_get_latex_interactive_session(cmds, **kargs):
    ct = conf.color_theme
    to_latex = lambda s: tex_escape(s).replace("@[@","{").replace("@]@","}").replace("@`@","\\")
    try:
        try:
            conf.color_theme = LatexTheme2()
            s,res = autorun_get_interactive_session(cmds, **kargs)
        except StopAutorun,e:
            e.code_run = to_latex(e.code_run)
            raise
    finally:
        conf.color_theme = ct
    return to_latex(s),res
Beispiel #3
0
    def canvas_dump(self, layer_shift=0, rebuild=1):
        canvas = pyx.canvas.canvas()
        if rebuild:
            p, t = self.__class__(str(self)).build_ps()
        else:
            p, t = self.build_ps()
        YTXT = len(t)
        for n, l in t:
            YTXT += len(l)
        YTXT = float(YTXT)
        YDUMP = YTXT

        XSTART = 1
        XDSTART = 10
        y = 0.0
        yd = 0.0
        xd = 0
        XMUL = 0.55
        YMUL = 0.4

        backcolor = colgen(0.6, 0.8, 1.0, trans=pyx.color.rgb)
        forecolor = colgen(0.2, 0.5, 0.8, trans=pyx.color.rgb)

        #        backcolor=makecol(0.376, 0.729, 0.525, 1.0)

        def hexstr(x):
            s = []
            for c in x:
                s.append("%02x" % ord(c))
            return " ".join(s)

        def make_dump_txt(x, y, txt):
            return pyx.text.text(XDSTART + x * XMUL, (YDUMP - y) * YMUL,
                                 r"\tt{%s}" % hexstr(txt),
                                 [pyx.text.size.Large])

        def make_box(o):
            return pyx.box.rect(o.left(),
                                o.bottom(),
                                o.width(),
                                o.height(),
                                relcenter=(0.5, 0.5))

        def make_frame(lst):
            if len(lst) == 1:
                b = lst[0].bbox()
                b.enlarge(pyx.unit.u_pt)
                return b.path()
            else:
                fb = lst[0].bbox()
                fb.enlarge(pyx.unit.u_pt)
                lb = lst[-1].bbox()
                lb.enlarge(pyx.unit.u_pt)
                if len(lst) == 2 and fb.left() > lb.right():
                    return pyx.path.path(
                        pyx.path.moveto(fb.right(), fb.top()),
                        pyx.path.lineto(fb.left(), fb.top()),
                        pyx.path.lineto(fb.left(), fb.bottom()),
                        pyx.path.lineto(fb.right(), fb.bottom()),
                        pyx.path.moveto(lb.left(), lb.top()),
                        pyx.path.lineto(lb.right(), lb.top()),
                        pyx.path.lineto(lb.right(), lb.bottom()),
                        pyx.path.lineto(lb.left(), lb.bottom()))
                else:
                    # XXX
                    gb = lst[1].bbox()
                    if gb != lb:
                        gb.enlarge(pyx.unit.u_pt)
                    kb = lst[-2].bbox()
                    if kb != gb and kb != lb:
                        kb.enlarge(pyx.unit.u_pt)
                    return pyx.path.path(
                        pyx.path.moveto(fb.left(), fb.top()),
                        pyx.path.lineto(fb.right(), fb.top()),
                        pyx.path.lineto(fb.right(), kb.bottom()),
                        pyx.path.lineto(lb.right(), kb.bottom()),
                        pyx.path.lineto(lb.right(), lb.bottom()),
                        pyx.path.lineto(lb.left(), lb.bottom()),
                        pyx.path.lineto(lb.left(), gb.top()),
                        pyx.path.lineto(fb.left(), gb.top()),
                        pyx.path.closepath(),
                    )

        def make_dump(s, shift=0, y=0, col=None, bkcol=None, larg=16):
            c = pyx.canvas.canvas()
            tlist = []
            while s:
                dmp, s = s[:larg - shift], s[larg - shift:]
                txt = make_dump_txt(shift, y, dmp)
                tlist.append(txt)
                shift += len(dmp)
                if shift >= 16:
                    shift = 0
                    y += 1
            if col is None:
                col = pyx.color.rgb.red
            if bkcol is None:
                col = pyx.color.rgb.white
            c.stroke(
                make_frame(tlist),
                [col, pyx.deco.filled([bkcol]), pyx.style.linewidth.Thick])
            for txt in tlist:
                c.insert(txt)
            return c, tlist[-1].bbox(), shift, y

        last_shift, last_y = 0, 0.0
        while t:
            bkcol = backcolor.next()
            proto, fields = t.pop()
            y += 0.5
            pt = pyx.text.text(
                XSTART, (YTXT - y) * YMUL,
                r"\font\cmssfont=cmss10\cmssfont{%s}" % proto.name,
                [pyx.text.size.Large])
            y += 1
            ptbb = pt.bbox()
            ptbb.enlarge(pyx.unit.u_pt * 2)
            canvas.stroke(ptbb.path(),
                          [pyx.color.rgb.black,
                           pyx.deco.filled([bkcol])])
            canvas.insert(pt)
            for fname, fval, fdump in fields:
                col = forecolor.next()
                ft = pyx.text.text(
                    XSTART, (YTXT - y) * YMUL,
                    r"\font\cmssfont=cmss10\cmssfont{%s}" %
                    tex_escape(fname.name))
                if isinstance(fval, str):
                    if len(fval) > 18:
                        fval = fval[:18] + "[...]"
                else:
                    fval = ""
                vt = pyx.text.text(
                    XSTART + 3, (YTXT - y) * YMUL,
                    r"\font\cmssfont=cmss10\cmssfont{%s}" % tex_escape(fval))
                y += 1.0
                if fdump:
                    dt, target, last_shift, last_y = make_dump(
                        fdump, last_shift, last_y, col, bkcol)

                    dtb = dt.bbox()
                    dtb = target
                    vtb = vt.bbox()
                    bxvt = make_box(vtb)
                    bxdt = make_box(dtb)
                    dtb.enlarge(pyx.unit.u_pt)
                    try:
                        if yd < 0:
                            cnx = pyx.connector.curve(bxvt,
                                                      bxdt,
                                                      absangle1=0,
                                                      absangle2=-90)
                        else:
                            cnx = pyx.connector.curve(bxvt,
                                                      bxdt,
                                                      absangle1=0,
                                                      absangle2=90)
                    except:
                        pass
                    else:
                        canvas.stroke(cnx, [
                            pyx.style.linewidth.thin, pyx.deco.earrow.small,
                            col
                        ])

                    canvas.insert(dt)

                canvas.insert(ft)
                canvas.insert(vt)
            last_y += layer_shift

        return canvas
Beispiel #4
0
    def canvas_dump(self, layer_shift=0, rebuild=1):
        canvas = pyx.canvas.canvas()
        if rebuild:
            p,t = self.__class__(str(self)).build_ps()
        else:
            p,t = self.build_ps()
        YTXT=len(t)
        for n,l in t:
            YTXT += len(l)
        YTXT = float(YTXT)
        YDUMP=YTXT

        XSTART = 1
        XDSTART = 10
        y = 0.0
        yd = 0.0
        xd = 0 
        XMUL= 0.55
        YMUL = 0.4
    
        backcolor=colgen(0.6, 0.8, 1.0, trans=pyx.color.rgb)
        forecolor=colgen(0.2, 0.5, 0.8, trans=pyx.color.rgb)
#        backcolor=makecol(0.376, 0.729, 0.525, 1.0)
        
        
        def hexstr(x):
            s = []
            for c in x:
                s.append("%02x" % ord(c))
            return " ".join(s)

                
        def make_dump_txt(x,y,txt):
            return pyx.text.text(XDSTART+x*XMUL, (YDUMP-y)*YMUL, r"\tt{%s}"%hexstr(txt), [pyx.text.size.Large])

        def make_box(o):
            return pyx.box.rect(o.left(), o.bottom(), o.width(), o.height(), relcenter=(0.5,0.5))

        def make_frame(lst):
            if len(lst) == 1:
                b = lst[0].bbox()
                b.enlarge(pyx.unit.u_pt)
                return b.path()
            else:
                fb = lst[0].bbox()
                fb.enlarge(pyx.unit.u_pt)
                lb = lst[-1].bbox()
                lb.enlarge(pyx.unit.u_pt)
                if len(lst) == 2 and fb.left() > lb.right():
                    return pyx.path.path(pyx.path.moveto(fb.right(), fb.top()),
                                         pyx.path.lineto(fb.left(), fb.top()),
                                         pyx.path.lineto(fb.left(), fb.bottom()),
                                         pyx.path.lineto(fb.right(), fb.bottom()),
                                         pyx.path.moveto(lb.left(), lb.top()),
                                         pyx.path.lineto(lb.right(), lb.top()),
                                         pyx.path.lineto(lb.right(), lb.bottom()),
                                         pyx.path.lineto(lb.left(), lb.bottom()))
                else:
                    # XXX
                    gb = lst[1].bbox()
                    if gb != lb:
                        gb.enlarge(pyx.unit.u_pt)
                    kb = lst[-2].bbox()
                    if kb != gb and kb != lb:
                        kb.enlarge(pyx.unit.u_pt)
                    return pyx.path.path(pyx.path.moveto(fb.left(), fb.top()),
                                         pyx.path.lineto(fb.right(), fb.top()),
                                         pyx.path.lineto(fb.right(), kb.bottom()),
                                         pyx.path.lineto(lb.right(), kb.bottom()),
                                         pyx.path.lineto(lb.right(), lb.bottom()),
                                         pyx.path.lineto(lb.left(), lb.bottom()),
                                         pyx.path.lineto(lb.left(), gb.top()),
                                         pyx.path.lineto(fb.left(), gb.top()),
                                         pyx.path.closepath(),)
                                         

        def make_dump(s, shift=0, y=0, col=None, bkcol=None, larg=16):
            c = pyx.canvas.canvas()
            tlist = []
            while s:
                dmp,s = s[:larg-shift],s[larg-shift:]
                txt = make_dump_txt(shift, y, dmp)
                tlist.append(txt)
                shift += len(dmp)
                if shift >= 16:
                    shift = 0
                    y += 1
            if col is None:
                col = pyx.color.rgb.red
            if bkcol is None:
                col = pyx.color.rgb.white
            c.stroke(make_frame(tlist),[col,pyx.deco.filled([bkcol]),pyx.style.linewidth.Thick])
            for txt in tlist:
                c.insert(txt)
            return c, tlist[-1].bbox(), shift, y
                            

        last_shift,last_y=0,0.0
        while t:
            bkcol = backcolor.next()
            proto,fields = t.pop()
            y += 0.5
            pt = pyx.text.text(XSTART, (YTXT-y)*YMUL, r"\font\cmssfont=cmss10\cmssfont{%s}" % proto.name, [ pyx.text.size.Large])
            y += 1
            ptbb=pt.bbox()
            ptbb.enlarge(pyx.unit.u_pt*2)
            canvas.stroke(ptbb.path(),[pyx.color.rgb.black, pyx.deco.filled([bkcol])])
            canvas.insert(pt)
            for fname, fval, fdump in fields:
                col = forecolor.next()
                ft = pyx.text.text(XSTART, (YTXT-y)*YMUL, r"\font\cmssfont=cmss10\cmssfont{%s}" % tex_escape(fname.name))
                if isinstance(fval, str):
                    if len(fval) > 18:
                        fval = fval[:18]+"[...]"
                else:
                    fval=""
                vt = pyx.text.text(XSTART+3, (YTXT-y)*YMUL, r"\font\cmssfont=cmss10\cmssfont{%s}" % tex_escape(fval))
                y += 1.0
                if fdump:
                    dt,target,last_shift,last_y = make_dump(fdump, last_shift, last_y, col, bkcol)

                    dtb = dt.bbox()
                    dtb=target
                    vtb = vt.bbox()
                    bxvt = make_box(vtb)
                    bxdt = make_box(dtb)
                    dtb.enlarge(pyx.unit.u_pt)
                    try:
                        if yd < 0:
                            cnx = pyx.connector.curve(bxvt,bxdt,absangle1=0, absangle2=-90)
                        else:
                            cnx = pyx.connector.curve(bxvt,bxdt,absangle1=0, absangle2=90)
                    except:
                        pass
                    else:
                        canvas.stroke(cnx,[pyx.style.linewidth.thin,pyx.deco.earrow.small,col])
                        
                    canvas.insert(dt)
                
                canvas.insert(ft)
                canvas.insert(vt)
            last_y += layer_shift
    
        return canvas
def convertReqifToLatex(reqifFile: str = "input.reqif",
                        latexFile: str = "output.tex",
                        width: str = "15cm",
                        include_images=False):
    reqif = Requirements.TReqz.reqif(reqifFile)
    documentIds = reqif.getAllDocumentIds()
    specTypeIds = reqif.getAllSpecObjectTypeIds()

    target = open(latexFile, 'w')

    documentId = documentIds[0]
    typeId = specTypeIds[0]

    rootReqs = reqif.getAllDocumentRootRequirements(documentId)
    attributes = reqif.getAllAttributeTypeLongNames(typeId)
    chapterExists = False

    allRequirements = reqif.getAllDocumentRequirementIds(documentId)
    reqif.handledReqs = 0

    for attribute in attributes:
        if attribute == 'ReqIF.ChapterName':
            chapterExists = True
            attributes.remove('ReqIF.ChapterName')
            break

    attributes.remove('ReqIF.Text')
    attributes.insert(0, 'ReqIF.Text')

    def htmlToText(text: str):
        newtext = text.replace("<br />", "\n")
        newtext = newtext.replace("</div>", "</div> ")
        newtext = newtext.replace("\n\n", "\n")
        return newtext

    def handleReq(reqif, requirement: str, level='', childId=1):
        reqif.handledReqs += 1
        utils.commandlinePrint(
            utils.fillLeftWithZeros(str(reqif.handledReqs),
                                    len(str(len(allRequirements)))) + "/" +
            str(len(allRequirements)))

        values = reqif.getRequirementValues(requirement)
        res = ""

        results = []
        isChapter = False
        for attribute in attributes:
            value = values.get(attribute)

            if attribute == 'ReqIF.Text':
                if chapterExists and (value == None or value == ''):
                    value = values.get('ReqIF.ChapterName')
                    if value != None and value != '':
                        isChapter = True

            if value != None and value != '':

                if reqif.checkAttributeIsXhtmlByLongName(typeId, attribute):
                    value = htmlToText(value)
                    value = utils.cleanXhtml(value)
                    value = utils.tex_escape(value)
                    value: str = value.strip("\n")
                    value = value.split("\n")
                    newValue = []
                    for v in value:
                        normalizedValue = v.strip()
                        normalizedValue = normalizedValue.strip("\t")
                        if normalizedValue != '' and normalizedValue != "\n":
                            newValue.append(normalizedValue)

                    value = "\n".join(newValue)

                    value: str = value.replace("\n", "\\newline \n")
                    if isChapter:
                        if level == '':
                            level = str(childId)
                        else:
                            level += '.' + str(childId)
                        value = "\\textcolor{red}{\\textbf{" + level + ' ' + value + "}}"
                    value = '\\begin{minipage}{' + width + '}' + value + '\\end{minipage}'
                else:
                    if reqif.checkAttributeIsEnumerationByLongName(
                            typeId, attribute):
                        attributeType = reqif.findAttributeTypeByLongName(
                            typeId, attribute)
                        valueMap = attributeType.getValueMap()
                        newValue = []
                        for v in value:
                            newValue.append(valueMap.get(v))
                        value = newValue
                    else:
                        pass

                if isinstance(value, str):
                    pass
                elif isinstance(value, list):
                    value = ', '.join(value)
                else:
                    raise RuntimeError("unsupported type: " + str(type(value)))

                results.append(value)
            else:
                if reqif.checkAttributeIsEnumerationByLongName(
                        typeId, attribute):
                    elem = reqif.convertEnumerationValuesByLongName(
                        typeId, attribute, value)
                    if elem != []:
                        value = ', '.join(elem)
                        results.append(value)
                    else:
                        results.append(' ')
                else:
                    results.append(' ')

        res += ("&".join(results)) + "\\\\\n\\hline\n"

        childs = reqif.getRequirementChilds(documentId, requirement)

        res = ''.join(x for x in res if x in string.printable)
        target.write(res)

        if childs == None:
            raise RuntimeError

        i = 1
        for child in childs:
            wasChapter = handleReq(reqif, child, level, i)
            if wasChapter:
                i += 1

        if isChapter:
            return True
        return False

    res = "\\documentclass[10pt,a4paper,final,landscape]{scrartcl}\n"
    res += "\\usepackage{longtable}\n"
    res += "\\usepackage{tabu}\n"
    res += "\\usepackage{xcolor}\n"
    res += "\\usepackage[utf8]{inputenc}\n"
    res += "\\usepackage{lmodern}\n"
    res += "\\usepackage[babel, german=guillemets]{csquotes}\n"
    res += "\\usepackage[ngerman]{babel}\n"
    res += "\\usepackage{textcomp}\n"
    res += "\\usepackage[left=1cm,right=1cm, bottom=1cm, top=1cm]{geometry}\n"
    res += "\\begin{document}\n"
    res += "\\setlength{\\tabulinesep}{3pt}\\begin{center}\\begin{longtabu} to \\textwidth {|p{" + width + "}|" + "l|" * (
        len(attributes) - 1) + "}\n"

    attributeNames = []
    for attribute in attributes:
        attributeNames.append(utils.tex_escape(attribute))
    res += " & ".join(attributeNames) + "\\\\\n"
    res += "\\hline\n"
    target.write(res)

    utils.startCommandlinePrint(
        utils.fillLeftWithZeros(str(reqif.handledReqs),
                                len(str(len(allRequirements)))) + "/" +
        str(len(allRequirements)))
    i = 1
    for requirement in rootReqs:
        wasChapter = handleReq(reqif, requirement, '', i)
        if wasChapter:
            i += 1

    res = "\\end{longtabu}\\end{center}\n"
    res += "\\end{document}"
    target.write(res)

    target.close()
    utils.endCommandlinePrint()
    def handleReq(reqif, requirement: str, level='', childId=1):
        reqif.handledReqs += 1
        utils.commandlinePrint(
            utils.fillLeftWithZeros(str(reqif.handledReqs),
                                    len(str(len(allRequirements)))) + "/" +
            str(len(allRequirements)))

        values = reqif.getRequirementValues(requirement)
        res = ""

        results = []
        isChapter = False
        for attribute in attributes:
            value = values.get(attribute)

            if attribute == 'ReqIF.Text':
                if chapterExists and (value == None or value == ''):
                    value = values.get('ReqIF.ChapterName')
                    if value != None and value != '':
                        isChapter = True

            if value != None and value != '':

                if reqif.checkAttributeIsXhtmlByLongName(typeId, attribute):
                    value = htmlToText(value)
                    value = utils.cleanXhtml(value)
                    value = utils.tex_escape(value)
                    value: str = value.strip("\n")
                    value = value.split("\n")
                    newValue = []
                    for v in value:
                        normalizedValue = v.strip()
                        normalizedValue = normalizedValue.strip("\t")
                        if normalizedValue != '' and normalizedValue != "\n":
                            newValue.append(normalizedValue)

                    value = "\n".join(newValue)

                    value: str = value.replace("\n", "\\newline \n")
                    if isChapter:
                        if level == '':
                            level = str(childId)
                        else:
                            level += '.' + str(childId)
                        value = "\\textcolor{red}{\\textbf{" + level + ' ' + value + "}}"
                    value = '\\begin{minipage}{' + width + '}' + value + '\\end{minipage}'
                else:
                    if reqif.checkAttributeIsEnumerationByLongName(
                            typeId, attribute):
                        attributeType = reqif.findAttributeTypeByLongName(
                            typeId, attribute)
                        valueMap = attributeType.getValueMap()
                        newValue = []
                        for v in value:
                            newValue.append(valueMap.get(v))
                        value = newValue
                    else:
                        pass

                if isinstance(value, str):
                    pass
                elif isinstance(value, list):
                    value = ', '.join(value)
                else:
                    raise RuntimeError("unsupported type: " + str(type(value)))

                results.append(value)
            else:
                if reqif.checkAttributeIsEnumerationByLongName(
                        typeId, attribute):
                    elem = reqif.convertEnumerationValuesByLongName(
                        typeId, attribute, value)
                    if elem != []:
                        value = ', '.join(elem)
                        results.append(value)
                    else:
                        results.append(' ')
                else:
                    results.append(' ')

        res += ("&".join(results)) + "\\\\\n\\hline\n"

        childs = reqif.getRequirementChilds(documentId, requirement)

        res = ''.join(x for x in res if x in string.printable)
        target.write(res)

        if childs == None:
            raise RuntimeError

        i = 1
        for child in childs:
            wasChapter = handleReq(reqif, child, level, i)
            if wasChapter:
                i += 1

        if isChapter:
            return True
        return False