Example #1
0
    def setIcon(self, iconpath=None):
        self.img = QtGui.QImage()
        if iconpath:
            self.icon = iconpath
        if self.icon is None:  # not set
            return
        elif self.icon.lower().endswith(
                '.svg'):  # new style (path from libroot)
            svgfilepath = self.icon
            # make relative to the directory of the block
            if not os.path.isabs(svgfilepath):
                svgfilepath = os.path.join(libraries.libpath(self.libname),
                                           svgfilepath)
        else:  # old style
            svgfilepath = os.path.join(respath, 'blocks', self.icon + '.svg')

        self.icon = svgfilepath
        #==============================================================================
        #         hack png
        #==============================================================================
        ret = svg2png(svgfilepath)
        if ret:
            self.png, self.pngmirr = ret

        if self.flip and self.pngmirr and os.path.isfile(self.pngmirr):
            self.img.load(self.pngmirr)
        elif self.png and os.path.isfile(self.png):
            self.img.load(self.png)

            self.update()
Example #2
0
    def changeIcon(self, actComp=None):
        libname, blockname, fname, blk = self.getnames(actComp)
        path = libraries.libpath(libname)
        filename = QtWidgets.QFileDialog.getOpenFileName(self,
                                                         'Open',
                                                         path,
                                                         filter='*.svg')
        if filename:
            # strip absolute path if in same dir as block itself
            actComp.setIcon(filename)

            if os.path.dirname(filename) == libraries.libpath(libname):
                filename = os.path.basename(filename)

            actComp.setView('icon', filename)

            self.refresh()
Example #3
0
    def setView(self, viewname, viewvalue):
        '''add a view and update disk'''
        views = copy(self.getViews())
        if 'textSource' in views:
            del views['textSource']
        # make relative paths
        dirname = libraries.libpath(self.libname)
        viewvalue = os.path.relpath(viewvalue, dirname)

        views[viewname] = viewvalue
        vv = self.getViews.copy()
        if 'textSource' in vv:
            del vv['textSource']
        self.updateOnDisk(dd=dict(views=vv))
Example #4
0
def rmBlock(libname, blockname):
    # first remove views (one of them is the file itself)
    blk = block_modules[libname + '/' + blockname]
    for type, filename in blk.views.items():
        if filename:
            fn1 = os.path.join(libraries.libpath(libname), filename)
            fn2 = os.path.join(os.getcwd(), filename)
            if os.path.isfile(fn1):
                os.remove(fn1)
            elif os.path.isfile(fn2):
                os.remove(fn2)
            elif os.path.isfile(filename):
                os.remove(filename)
    libraries.rmBlock(libname, blockname)
Example #5
0
    def addLibrary(self):
        dialog = textLineDialog('Name: ', 'Add library')
        ret = dialog.getLabel()
        if ret:
            try:
                # create path
                fp = libraries.libpath(ret)
                os.mkdir(fp)
                # create __init__.py
                f = open(os.path.join(fp, '__init__.py'), 'wb')
                f.close()

                self.refresh()

            except Exception as e:
                error('Library error' + str(e))
Example #6
0
def toBlk(filename, libname):
    res = []
    for name, inp, outp, properties, doc in get_defs(filename):
        if doc.strip():
            fmt = templates['block'].splitlines()
            fmt.insert(3, 'tooltip = """{tooltip}"""\n')
            fmt = '\n'.join(fmt)
        else:
            fmt = templates['block']
        wi = max([len(i) for i in inp])
        wo = max([len(o) for o in outp])
        w2 = (wi + wo + 1) // 2 * 10
        inputs, outputs = [], []

        for ix, i in enumerate(inp):
            inputs.append((i, -w2, ix * PD))
        for ix, o in enumerate(outp):
            outputs.append((o, w2, ix * PD))

        p = libraries.libpath(libname)

        # copy diagram
        ed, ext = viewTypes['myhdl']
        fndgm = os.path.join(p, name + ext)
        views = dict(myhdl=name + ext)
        with open(filename) as f:
            t = f.read()
        with open(fndgm, 'wb') as f:
            f.write(t)

        fnblk = os.path.join(p, name + '.py')
        # write block
        with open(fnblk, 'wb') as f:
            f.write(
                fmt.format(name=name,
                           libname=libname,
                           inp=inputs,
                           outp=outputs,
                           io=[],
                           bbox=None,
                           tooltip=doc,
                           parameters={},
                           properties=properties,
                           views=views))
        res.append((libname, name))
    return res  # return list of imported blocks
Example #7
0
def _addBlockModuleDefaults(libname, blockname):
    '''add default settings to a loaded block_module'''
    blk = block_modules[libname + '/' + blockname]
    blk.name = blockname
    blk.libname = libname
    blk.textSource = libraries.blockpath(libname, blockname)
    try:
        if not 'icon' in blk.views:
            blk.views['icon'] = None
        if not hasattr(blk, 'bbox'):
            blk.bbox = None
        for pp in ['properties', 'parameters']:
            if not hasattr(blk, pp):
                setattr(blk, pp, dict())
    except Exception as e:
        raise Exception('Block {}.{} raised error {}'.format(
            libname, blockname, str(e)))

    p = libraries.libpath(libname)
    for viewname, (ed, ext) in viewTypes.items():
        fn = os.path.join(p, blockname + ext)
        if os.path.isfile(fn):
            blk.views[viewname] = fn
Example #8
0
        with open(fndgm, 'wb') as f:
            f.write(t)

        fnblk = os.path.join(p, name + '.py')
        # write block
        with open(fnblk, 'wb') as f:
            f.write(
                fmt.format(name=name,
                           libname=libname,
                           inp=inputs,
                           outp=outputs,
                           io=[],
                           bbox=None,
                           tooltip=doc,
                           parameters={},
                           properties=properties,
                           views=views))
        res.append((libname, name))
    return res  # return list of imported blocks


if __name__ == '__main__':
    # Usage:
    #     python myhdl_to_blk.py libname, myhdlfilename
    # libname is without prefix
    libname = sys.argv[1]
    p = libraries.libpath(libname)
    if not os.path.isdir(p):
        os.mkdir(p)
    for filename in sys.argv[2:]:
        toBlk(filename, libname)
Example #9
0
def netlist(filename,
            properties=dict(),
            lang='myhdl',
            netlist_dir=const.netlist_dir,
            netlists=None):
    '''netlist a file in netlist_dir
    netlists contains a set of already netlisted blocks'''
    if debug:
        print('debug netlist')
        print('      filename   ', filename)
        print('      properties ', properties)
        print('      lang       ', lang)


#    print ('      netlist_dir', netlist_dir)
#    print ('      netlists   ', netlists)
    if netlists is None:
        netlists = set()
    # check if already netlisted
    if filename in netlists:
        #        print('skip')
        return

    toplevel = len(netlists) == 0
    netlists.add(filename)

    ed, ext_diagram = const.viewTypes['diagram']
    ed, ext_lang = const.viewTypes[lang]

    #    d, module_name  = os.path.split(filename)

    libname, blockname = libraries.pathToLibnameBlockname(
        filename)  # removes extension
    ext = '.py' if lang == 'myhdl' else ext_lang  # .mhdl.py -> .py etc.

    # note: libdir is empty when outside library i.e. toplevel
    if toplevel:
        subdir = ''
    else:
        subdir = libraries.libprefix + libname if libname else libname
        if not os.path.isdir(os.path.join(netlist_dir, subdir)):
            os.makedirs(os.path.join(netlist_dir, subdir))
            if lang == 'myhdl':
                with open(os.path.join(netlist_dir, subdir, '__init__.py'),
                          'wb') as f:
                    f.write('# import blocks in name-space\n\n')

    outfile = os.path.join(netlist_dir, subdir, blockname + ext)

    if lang == 'myhdl':
        template = const.templates['myhdl'].lstrip()
        tbfooter = const.templates['myhdl_tbfooter']
        convert = toMyhdl
        codegen_stmt = 'toMyhdlInstance'
        if toplevel:
            include = const.templates['myhdl_toplevel_include']
        else:
            include = const.templates['myhdl_include']
    elif lang == 'systemverilog':
        template = const.templates['systemverilog'].lstrip()
        tbfooter = const.templates['systemverilog_tbfooter']
        convert = toSystemverilog
        codegen_stmt = 'toSytemverilogInstance'
        if toplevel:
            include = const.templates['systemverilog_toplevel_include']
        else:
            include = const.templates['systemverilog_include']
    else:
        raise Exception('todo: language support for ' + lang)

    if filename.endswith(ext_lang):  # other view (myhdl verilog etc.)
        # copy file to netlist location (if newer than existing netlist)
        if outfile in netlists or dest_newer_than_source(dest=outfile,
                                                         source=filename):
            # print('{} module already present in {}'.format(lang, outfile))
            return  # do nothing if outfile newer than infile

        with open(filename, 'rb') as fi:
            body = fi.read()

        txt = fillTemplate(template, blockname, body, include)
        with open(outfile, 'wb') as fo:
            fo.write(txt)
        print('{} module written to {}'.format(lang, outfile))

    else:  # diagram

        # resolve connections
        blocks, internal_nets, external_nets = resolve_connectivity(
            filename, properties=dict())
        body = convert(blockname, blocks, internal_nets, external_nets,
                       netlist_dir)

        txt = fillTemplate(template + tbfooter, blockname, body, include)

        if not os.path.isdir(netlist_dir):
            os.makedirs(netlist_dir)

        if not dest_newer_than_source(dest=outfile, source=filename):
            with open(outfile, 'wb') as fo:
                fo.write(
                    '# diagram netlist generated from {}\n\n'.format(filename))
                fo.write(txt)
            print('diagram netlist written to', outfile)

        # also netlist blocks in the diagram
        for name, block in blocks.items():
            libname, blockname = block['libname'], block['blockname']
            #            print ('subblock', libname, blockname)
            k = libname + '/' + blockname
            libpath = libraries.libpath(libname)
            fname = os.path.join(libpath, blockname)
            #                netlist_subdir = os.path.join(netlist_dir, libraries.libprefix+libname)

            # block module contains code genration (no need to netlist)
            if k in blkModuleCache and hasattr(blkModuleCache[k],
                                               codegen_stmt):
                continue

            # inst has a netlist view
            elif os.path.exists(fname + ext_lang):
                netlist(fname + ext_lang, properties, lang, netlist_dir,
                        netlists)

            # inst has diagram (that can be netlisted)
            elif os.path.exists(fname + ext_diagram):
                netlist(fname + ext_diagram, properties, lang, netlist_dir,
                        netlists)

            else:
                print('Warning: {}.{} is missing a {} view or diagram'.format(
                    libname, blockname, lang))

            if lang != 'myhdl':
                continue

            # add __init__ files as needed
            # and add 'from library import block'
            # this allows the instantiation to look like:
            #     library.block(pin1=net1, pin2=net2)
            # otherwise instantiation would look like:
            #     library.block.block(pin1=net1, pin2=net2)
            libdir = libraries.libprefix + libname if libname else libname
            initname = os.path.join(netlist_dir, libdir, '__init__.py')
            modname = os.path.join(netlist_dir, libdir, blockname + '.py')
            imp_statement = 'from {p}{l}.{b} import {b}\n'.format(
                p=libraries.libprefix, l=libname, b=blockname)

            if os.path.isfile(modname):
                if os.path.isfile(initname):
                    with open(initname, 'rb') as f:
                        t = f.read()
                    if not imp_statement in t:
                        t += imp_statement
                else:
                    t = '# import blocks in name-space\n\n'
                    t += imp_statement

                with open(initname, 'wb') as f:
                    f.write(t)