Esempio n. 1
0
def session_resume():
    cherrypy.log.error('Resume Session', 'DIAGRAM', logging.DEBUG)
    actions =list()
    if cherrypy.session.has_key('display'):
        display = cherrypy.session['display']
    else:
        display = {'symbol': True, 'value':False} # default
        cherrypy.session['display'] = display
    if cherrypy.session.has_key('circuit'):
        equation = cherrypy.session['equation']
        latex = cherrypy.session['circuit'].latex
        actions.append(new_action('actCircuitTikzSet', 'Circuit', latex = latex))
        actions.append(new_action('actCircuitTikzDisplayUpdate', 'Circuit', value = display['value'],  symbol = display['symbol']))
        if tab_search('Solver'):
            actions.append(new_action('actEquationHeadingUpdate', 'Solver', display = cherrypy.session.get('display'), circuit_id = cherrypy.session['circuit'].id)) 
        try:
            respDict = render_circuitikz(latex)
            if respDict.has_key('actions'):
                actions += respDict['actions']
                return {'actions':actions}
            elif respDict.has_key('dialog'):
                return {'dialog':dialog} 
        except Exception as err:
            msg = 'Problem encounter, %s'%str(err.message)
            cherrypy.log(msg)
            dialog = new_dialog('Latex Error', msg)
            return {'dialog':dialog} 
            dialog = respDict['dialog']
    else:
        latex = ''
    return {'actions':actions}
Esempio n. 2
0
def mech_options_set(idx, option, value):
    print 'Mechanical.mech_options_set, entry, %s, %s' % (option, value)
    actions = list()
    if cherrypy.session['mechOptions'][idx][option] != value:
        print 'set option %s' % value
        cherrypy.session['mechOptions'][idx][option] = value
        if option in ('checkOptions', 'ratio', 'size', 'unit'):
            actions.append(new_action('actRefresh', 'Drawing', idx=idx))
    else:
        actions.append(new_action('actPass', 'Drawing', idx=idx))
    return {'actions': actions}
Esempio n. 3
0
def tab_select(tabId):
    logger.debug('tab_select - user selected tabId - %d' % tabId)
    actions = list()
    if tabId == 2:  # primary key for solver
        print 'Mechanical: Clicked Solver '
    elif tabId == 5:  # primary key for mechanical
        actions.append(new_action('actRefresh', 'Drawing'))
        return {'actions': actions}
Esempio n. 4
0
def mech_design_get(idxMech=None):
    actions = list()
    user = cherrypy.session['user']
    mechDesign = cherrypy.session['mechDesign']
    equation = cherrypy.session['equation']
    solution = equation.solution_get('S')
    ds = Geometric.DraftSpace(backend='Agg')
    ds.clear()
    ds.showGrid = False
    ds.showTick = False
    ds.showAnchor = False
    mechPath = os.path.join(get_server_setting('imagesdir'),
                            cherrypy.session.id)
    ds.path = mechPath
    ds.authorOrigin = equation.instance.owner.firstName + ' ' + equation.instance.owner.lastName
    ds.authorModify = user.firstName + ' ' + user.lastName
    ds.dateOrigin = equation.instance.timestamp.strftime("%m-%d-%Y")
    ds.title = equation.instance.title
    if not os.path.exists(mechPath):
        os.mkdir(mechPath)
    idxList = list()
    if idxMech != None:
        idxList.append(idxMech)
    else:
        for drawing in mechDesign.drawings:
            idxList.append(drawing.id)
    storage = FileStorage.FileStorage(
        os.path.join(get_server_setting('cachedir'), 'cache.fs'))
    db = DB(storage)
    connection = db.open()
    root = connection.root()
    for idxMech in idxList:
        for drawing in mechDesign.drawings:  #search for drawing
            if drawing.id == idxMech:
                break
        mechOptions = cherrypy.session['mechOptions'][idxMech]
        ds.ratio = mechOptions['ratio']
        ds.perspective = drawing.perspective.capitalize()
        ds.name = 'Mechanical-Drawing' + drawing.perspective.capitalize(
        ) + time.strftime('%y%m%d%H%M%S')
        imgUrl = 'api/image?app=Mechanical&tab=Drawing&id1=%d&id2=%d' % (
            mechDesign.id, drawing.id) + '&image=' + ds.name + '.' + DRAWMODE
        values = dict()
        symbols = dict()
        baseUnit = equation.unumDict[int(mechOptions['unit'])]
        for variableSol in solution.variables:
            for variableMech in drawing.variables:
                desig = variableMech.desig.longhand + str(variableMech.number)
                if variableMech.id == variableSol.variable.id:
                    symbols[desig] = variableMech.desig.latex.replace(
                        '#', str(variableMech.number))
                    if variableSol.variable.desig.name == 'Length':
                        unumSelected = equation.variable_get_unit(
                            variableSol, 'selected-unum')
                        unumValue = variableSol.value * unumSelected
                        unumValue = unumValue.asUnit(baseUnit)
                        value = unumValue._value
                    else:
                        value = variableSol.value

                    values[desig] = value

        key = '%s\n%s\n%s\n%s\n%s' % (
            mechOptions['size'], mechOptions['checkOptions'],
            mechOptions['ratio'], mechOptions['unit'],
            ds.get_cmd(drawing.drawing, values))
        cache = root.cache_image.get(key, None)
        imgFileLoc = os.path.join(ds.path, ds.name + '.' + DRAWMODE)
        if cache:
            fId = open(imgFileLoc, 'wb+')
            fId.write(cache.image)
            cache.update()  # update timestamp
            root.cache_image[key] = cache
            transaction.commit()
        else:
            cherrypy.log.error('Draw %s, %s' % (drawing, values), 'MECHANICAL',
                               logging.DEBUG)
            ds.load(drawing.drawing, values)
            cherrypy.log.error('Set background.', 'MECHANICAL', logging.DEBUG)
            ds.draw_background(mechOptions['size'])
            ds.save(fmt=DRAWMODE)
            root.cache_image[key] = ModelCore.CacheImage(imgFileLoc)
            transaction.commit()
        ds.clear()
        actions.append(
            new_action('actDrawingAdd',
                       'Drawing',
                       idx=idxMech,
                       image=imgUrl,
                       variables=None,
                       code=drawing.drawing,
                       perspective=drawing.perspective))
        actions.append(
            new_action('actRatioChange',
                       'Drawing',
                       idx=idxMech,
                       ratio=mechOptions['ratio']))
        actions.append(
            new_action('actSizeFill',
                       'Drawing',
                       idx=idxMech,
                       options=Geometric.options,
                       value=mechOptions['size']))
        actions.append(
            new_action('actUnitFill',
                       'Drawing',
                       idx=idxMech,
                       options={
                           100000: 'm',
                           302800: 'ft',
                           300103: 'cm',
                           302700: 'in',
                           300102: 'mm',
                           302900: 'mil'
                       },
                       value=int(mechOptions['unit'])))
    connection.close()  #close cache
    db.close()
    storage.close()
    return {'actions': actions}
Esempio n. 5
0
def render_circuitikz(latex, dest = None, equation = None, display = None):
    actions = list()
    if dest:
        filePath, fileName = os.path.split(dest)
        imageSessPath = filePath
        imagePath = os.path.join(imageSessPath, fileName + '.png')
    else:
        equation = cherrypy.session['equation']
        display = cherrypy.session['display']
        fileName = 'Diagram-Circuit%s'%time.strftime('%y%m%d%H%M%S')
        imageSessPath = os.path.join(get_server_setting('imagesdir'), cherrypy.session.id)
        actions.append(new_action('actCircuitTikzSubmit', 'Circuit', id =cherrypy.session['circuit'].id))      
        actions.append(new_action('actCircuitTikzSubmit', 'Solver', id =cherrypy.session['circuit'].id))
    imagePath = os.path.join(imageSessPath, fileName + '.png')
    if not os.path.isdir(imageSessPath):
        os.mkdir(imageSessPath)
        cherrypy.log.error('Making directory %s'%imageSessPath, 'DIAGRAM', logging.DEBUG)
    if latex == '':
        return {'actions':actions}
    else:
        # look in cache for existing results
        storage = FileStorage.FileStorage(os.path.join(get_server_setting('cachedir'), 'cache.fs'))
        db = DB(storage)
        connection = db.open()
        root = connection.root()
        cache = root.cache_image.get(latex, None)
        if cache:
            imgFile = open(imagePath, 'wb+')
            imgFile.write(cache.image)
            cache.update() # update timestamp
            root.cache_image[latex] = cache
            transaction.commit()
        else:            
            head =  \
"""\\documentclass[border=4pt]{standalone}
\\usepackage{tikz}
\\usepackage{circuitikz}
\\usepackage{siunitx}
\\pagestyle{empty}
\\begin{document}
\\begin{circuitikz}[%s]
\\newcommand*{\\doublelabel}[3][3em]{\\parbox{#1}{\\raggedleft #2 \\\\ #3}}
"""
            head = head%('american')
            tail = \
"""
\\end{circuitikz}
\\end{document}
"""
            latexDoc = head + latex + tail
            latexDoc = execute_latex_controls(latexDoc, equation, display)
            imagePath = os.path.join(imageSessPath, fileName + '.png')
            args = '-interaction=nonstopmode -halt-on-error -jobname %s -output-directory=%s '%(fileName, imageSessPath)
            # string -> txt (\todo: fix, should render as a string
            if texMode == 'file':
                texFileLoc = os.path.join(imageSessPath, fileName + '.tex')
                f = open(texFileLoc, 'w')
                f.write(latexDoc)
                f.close()
                # tex -> pdf processingsa
                cmd = '"%s" %s %s'%(os.path.join(latexPath, latexEngine), args, texFileLoc)
            elif texMode == 'string':
                # string -> pdf processing
                cmd = '"%s" %s "%s"'%(os.path.join(latexPath, latexEngine), args, latexDoc.replace('\n', ' '))
            cherrypy.log.error("Running %s"%cmd, 'DIAGRAM', logging.DEBUG)
            p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
            stdoutdata, stderrdata  = p.communicate()
            if stderrdata:
                cherrypy.log.error('Error: %s'%stderrdata, 'DIAGRAM', logging.ERROR)
            idx = stdoutdata.find('!')
            if idx >0 :
                cherrypy.log.error('Error: %s'%stdoutdata[idx:], 'DIAGRAM', logging.ERROR, True)
                raise Exception('Latex Error ' + stdoutdata[idx:])
            else:
                imgMagicCmd = 'convert -trim -density 128 "%s.pdf" -background none -undercolor none -pointsize 6 label:"               " -gravity SouthEast -append -pointsize 6 label:"(c) OneSolver.com" -gravity SouthEast -append "%s"'
                if not dest:
                    # latex did not have any errors, save to ram
                    if cherrypy.session.has_key('circuit'):
                        dbCircuit = cherrypy.session['circuit']
                    else:
                        session_new()
                    dbCircuit.latex = latex
                    dbCircuit.equation.instance = equation.instance
                    cherrypy.session['circuit'] = dbCircuit
                    # pdf -> png processing (imagemagick)   
                    cmd = imgMagicCmd%(os.path.join(imageSessPath, fileName), imagePath)
                    cherrypy.log.error('Running %s'%cmd, 'DIAGRAM', logging.DEBUG)
                    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                    stdoutdata, stderrdata  = p.communicate()
                    if stdoutdata:
                        cherrypy.log.error('Output: %s'%stdoutdata, 'DIAGRAM', logging.INFO)
                    if stderrdata:
                        cherrypy.log.error('Error: %s'%stderrdata, 'DIAGRAM', logging.ERROR)
                else:
                    cmd = imgMagicCmd%(os.path.join(imageSessPath, fileName), imagePath)
                    p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
                    stdoutdata, stderrdata  = p.communicate()
                    if stdoutdata:
                        cherrypy.log.error('Output: %s'%stdoutdata, 'DIAGRAM', logging.INFO)
                    if stderrdata:
                        cherrypy.log.error('Error: %s'%stderrdata, 'DIAGRAM', logging.ERROR)
                cache = ModelCore.CacheImage(imagePath)
                root.cache_diagram[latex] = cache
                transaction.commit()
        connection.close() #close cache
        db.close()
        storage.close()
        return {'actions':actions}