Пример #1
0
    def wrapper(func):
        sig = inspect.signature(func)
        # default values in func definition
        interactives = {
            k: v.default
            for k, v in sig.parameters.items()
            if isinstance(v.default, Interactive)
        }

        if name is None:
            sh_name = func.__name__
        else:
            sh_name = name

        if interactives:

            @wraps(func)
            def arg_func():
                kwds = {
                    k: get_minibuffer_input(v.message, v.completer())
                    for k, v in interactives.items()
                }
                func(**kwds)

            registry('gearbox/shortcuts').append(
                (domain, shortcut, arg_func, sh_name))
        else:
            registry('gearbox/shortcuts').append(
                (domain, shortcut, func, sh_name))
Пример #2
0
    def run_model(self, script_fn):
        artifacts_dir = registry('sim/artifacts_dir')
        if not artifacts_dir:
            artifacts_dir = os.path.join(os.path.dirname(script_fn), 'build')
            bind('sim/artifacts_dir', artifacts_dir)
            print(f"Artifacts dir: {artifacts_dir}")

        os.makedirs(artifacts_dir, exist_ok=True)
        sys.path.append(os.path.dirname(script_fn))
        # config['trace/ignore'].append(os.path.dirname(__file__))
        config['trace/ignore'].append(runpy.__file__)
        compilation_log_fn = os.path.join(artifacts_dir, 'compilation.log')
        bind('gearbox/compilation_log_fn', compilation_log_fn)
        bind('svgen/debug_intfs', ['*'])

        os.system(f'rm -rf {compilation_log_fn}')

        # import pdb; pdb.set_trace()
        old_handlers = {}
        for name in registry('logger'):
            if name in logging.root.manager.loggerDict:
                logger = logging.getLogger(name)
                old_handlers[name] = logger.handlers.copy()
                logger.handlers.clear()
                logger.addHandler(
                    logger.get_logger_handler(
                        logging.FileHandler(compilation_log_fn)))

        bind('gearbox/model_script_name', script_fn)
        self.script_loading_started.emit()

        self.err = None
        self.cur_model_issue_id = None
        try:
            runpy.run_path(script_fn)
        except Exception as e:
            self.err = e

        self.script_loaded.emit()

        if not self.err:
            root = registry('gear/hier_root')
            if not root.child:
                self.err = EmptyHierarchy('No PyGears model created')
                exc_info = fake_exc_info((EmptyHierarchy, self.err, None),
                                         script_fn, 0)
                self.err = self.err.with_traceback(exc_info[2])

        if self.err is not None:
            pygears_excepthook(type(self.err), self.err,
                               self.err.__traceback__)

        if self.err is None:
            self.invoke_method('run_sim')
Пример #3
0
    def __init__(self,
                 view,
                 name,
                 plugins=None,
                 main=Inject('gearbox/main/inst'),
                 layout=Inject('gearbox/layout')):

        super().__init__()

        view.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
        menu = main.get_submenu(main.menuBar(), self.domain.title())
        if menu:
            view.customContextMenuRequested.connect(
                lambda pos: menu.popup(view.mapToGlobal(pos)))

        self.view = view
        self.name = name
        layout.add(self)

        if plugins is None:
            try:
                plugins = registry(f'gearbox/plugins/{self.domain}')
            except KeyError:
                plugins = {}

        self.plugins = {}
        for name, cls in plugins.items():
            self.add_plugin(name, cls(self))
Пример #4
0
    def create_menus(self,
                     prefixes=Inject('gearbox/prefixes'),
                     shortcuts=Inject('gearbox/shortcuts')):
        for domain, key, callback, name in registry('gearbox/shortcuts'):
            if not isinstance(key, tuple):
                key = (key, )

            current_menu = self.menuBar()
            start_skip = 1
            if (domain is None):
                if (key[0] != QtCore.Qt.Key_Space):
                    Shortcut(domain, key, callback, name)

                start_skip = 2

            else:
                submenu = self.get_or_create_submenu(current_menu,
                                                     domain.title())
                action = self.get_subaction(current_menu, domain.title())
                action.setVisible(False)
                current_menu = submenu

            for i in range(start_skip, len(key) + 1):
                if i < len(key):
                    menu_name = prefixes.get((domain, key[:i]),
                                             'group').title()
                    current_menu = self.get_or_create_submenu(
                        current_menu, menu_name)
                else:
                    action = Action(domain, key, callback, name)
                    self.addAction(action)
                    current_menu.addAction(action)
Пример #5
0
    def update_pipes(self, pipes):
        ts = timestep()
        if ts is None:
            ts = 0

        signal_names = [(pipe, self.vcd_map.pipe_data_signal_stem(pipe)[:-4])
                        for pipe in pipes if pipe.status[0] != ts]

        for i in range(0, len(signal_names), 20):

            cur_slice = slice(i, min(len(signal_names), i + 20))
            cur_names = signal_names[cur_slice]

            ret = self.gtkwave_intf.command(
                f'get_values {ts*10} [list {" ".join(s[1] for s in cur_names)}]'
            )
            rtl_status = ret.split('\n')

            # assert len(rtl_status) == (cur_slice.stop - cur_slice.start)
            if len(rtl_status) != (cur_slice.stop - cur_slice.start):
                continue

            for wave_status, (pipe, _) in zip(rtl_status, cur_names):
                self.update_rtl_intf(pipe, wave_status.strip())

        NodeActivityVisitor().visit(registry('gearbox/graph_model'))
Пример #6
0
def gktwave_delete(timekeep=Inject('gearbox/timekeep')):
    print('Gtkwave deleted')
    gtkwave = registry('gearbox/gtkwave/inst')
    timekeep.timestep_changed.disconnect(gtkwave.update)
    for b in gtkwave.buffers:
        b.delete()

    bind('gearbox/gtkwave/inst', None)
Пример #7
0
def open_file_interact(
        sim_bridge=Inject('gearbox/sim_bridge'),
        prev_script_fn=Inject('gearbox/model_script_name'),
):
    ret = QtWidgets.QFileDialog.getOpenFileName(
        caption='Open file',
        dir=os.getcwd(),
        filter="PyGears script (*.py);;All files (*)")

    script_fn = ret[0]

    if script_fn:
        if prev_script_fn:
            bind('gearbox/main/new_model_script_fn', script_fn)
            close_file()
        else:
            registry('gearbox/sim_bridge').invoke_method('run_model',
                                                         script_fn=script_fn)
Пример #8
0
def graph(layout=Inject('gearbox/layout')):

    for b in layout.buffers:
        if b.name == 'graph':
            buff = b
    else:
        buff = registry('gearbox/graph_model_ctrl').graph_create()

    layout.show_buffer(buff)
Пример #9
0
    def change_domain(self, domain):

        current_menu = self.menuBar()
        prev_domain = registry('gearbox/domain')

        if prev_domain:
            action = self.get_subaction(current_menu,
                                        registry('gearbox/domain').title())
            if action:
                action.setVisible(False)

        bind('gearbox/domain', domain)

        if domain:
            action = self.get_subaction(current_menu, domain.title())
            if action:
                action.setVisible(True)

        self.domain_changed.emit(domain)
Пример #10
0
    def __init__(self,
                 parent=None,
                 buff=None,
                 layout=Inject('gearbox/layout')):
        super().__init__()
        self.parent = parent
        self.buff = None

        self.setSpacing(0)
        self.setMargin(0)
        self.setContentsMargins(0, 0, 0, 0)

        self.modeline = Modeline(self)

        local_dir = os.path.abspath(os.path.dirname(__file__))

        pixmap = QtGui.QPixmap(os.path.join(local_dir, 'logo.png'))

        self.tab_change_lock = False
        self.tab_bar = QtWidgets.QTabBar()
        self.tab_bar.addTab('**')
        self.tab_bar.currentChanged.connect(self.switch_tab)
        for b in layout.buffers:
            self.new_buffer(b)

        layout.new_buffer.connect(self.new_buffer)
        layout.buffer_removed.connect(self.buffer_removed)

        self.placeholder = QtWidgets.QLabel()
        self.placeholder.setPixmap(pixmap)
        self.placeholder.setFocusPolicy(QtCore.Qt.FocusPolicy.ClickFocus)
        self.placeholder.setSizePolicy(QtWidgets.QSizePolicy.Ignored,
                                       QtWidgets.QSizePolicy.Ignored)
        # self.placeholder.setStyleSheet(themify(STYLE_MINIBUFFER))
        self.placeholder.setAlignment(QtCore.Qt.AlignHCenter
                                      | QtCore.Qt.AlignVCenter)

        self.buf_layout_pos = 1
        self.layout_full_size = 4
        self.addWidget(self.tab_bar)
        self.addWidget(self.placeholder, 1)
        self.addWidget(self.modeline)

        if not registry('gearbox/main/tabbar'):
            self.tab_bar.hide()

        if buff is not None:
            self.placeholder.hide()
            self.insertWidget(self.buf_layout_pos, buff.view, stretch=1)
            self.buff = buff
            self.buff.show()
Пример #11
0
    def handle_event(self, name):
        if name == 'after_cleanup':
            sim_exception = registry('sim/exception')
            if sim_exception:
                log_exception(sim_exception)
                # layout = registry('gearbox/layout')
                # layout.current_window.place_buffer(
                #     layout.get_buffer_by_name('compilation'))

            self.simulating = False

        if name == 'exception':
            self.model_loaded.emit()
        else:
            getattr(self, name).emit()
Пример #12
0
    def __init__(self, sim_pipe=None, parent=None):
        super().__init__(parent)

        self.setWindowIcon(
            QtGui.QIcon(os.path.join(os.path.dirname(__file__),
                                     'gearbox.png')))

        desktop = QtWidgets.QDesktopWidget()
        desktop_frame = desktop.availableGeometry(self)
        self.resize(desktop_frame.size() * 0.7)
        self.move(desktop_frame.width() - self.width(), self.y())

        self._undo_stack = QtWidgets.QUndoStack(self)
        self.shortcuts = []

        self.vbox = QtWidgets.QVBoxLayout()
        self.vbox.setSpacing(0)
        self.vbox.setMargin(0)
        self.vbox.setContentsMargins(0, 0, 0, 0)

        safe_bind('gearbox/main/inst', self)

        self.buffers = BufferStack(main=self)
        self.vbox.addLayout(self.buffers)

        mainWidget = QtWidgets.QWidget()
        mainWidget.setLayout(self.vbox)
        mainWidget.setContentsMargins(0, 0, 0, 0)

        self.minibuffer = Minibuffer()
        # self.minibuffer.completed.connect(self._minibuffer_completed)
        safe_bind('gearbox/minibuffer', self.minibuffer)
        safe_bind('gearbox/domain', None)

        self.vbox.addLayout(self.minibuffer.view)

        self.setCentralWidget(mainWidget)

        self._init_actions()

        # for domain, key, callback, name in registry('gearbox/shortcuts'):
        #     Shortcut(domain, key, callback, name)

        self.create_menus()

        if not registry('gearbox/main/menus'):
            self.menuBar().hide()
Пример #13
0
    def close_script(self):
        if registry('gearbox/model_script_name'):
            # bind('gearbox/model_script_name', None)
            # if self.queue is not None:
            #     registry('sim/gearbox').done = True
            #     self.closing = True
            #     self.cont()
            # else:

            print("Closing script!")
            if self.pygears_proc:
                self.pygears_proc.done = True
                self.pygears_proc.cont()
                # self.pygears_proc.wait()

            self.model_closed.emit()
            self.script_closed.emit()
Пример #14
0
    def window_up(self, version, pid, window_id,
                  graph=Inject('gearbox/graph')):
        print(f'GtkWave started: {version}, {pid}, {window_id}')
        self.window_id = window_id
        self.gtkwave_win = QtGui.QWindow.fromWinId(window_id)
        self.widget = QtWidgets.QWidget.createWindowContainer(self.gtkwave_win)
        # self.widget.setFocusPolicy(QtCore.Qt.NoFocus)
        self.widget.setWindowFlag(QtCore.Qt.X11BypassWindowManagerHint)
        self.widget.setWindowFlag(QtCore.Qt.BypassGraphicsProxyWidget)
        self.widget.setWindowFlag(QtCore.Qt.BypassWindowManagerHint)

        self.command(f'gtkwave::toggleStripGUI')
        if registry('gearbox/gtkwave/menus'):
            self.command(f'gtkwave::toggleStripGUI')

        self.command(f'gtkwave::setZoomFactor -7')

        self.initialized.emit()
Пример #15
0
def main_loop(script_fn, layers=Inject('gearbox/layers')):
    import faulthandler
    faulthandler.enable(file=open('err.log', 'w'))

    bind('gearbox/main/new_model_script_fn', None)
    sys_args = sys.argv.copy()
    # bind('gearbox/main/argv', sys_args)

    load_rc('.gearbox', os.getcwd())

    # app = QtWidgets.QApplication(sys.argv)
    app = Application(sys_args)
    with open(os.path.join(os.path.dirname(__file__), 'default.css')) as f:
        stylesheet = f.read()

    app.setStyleSheet(themify(stylesheet))

    app.setWindowIcon(QtGui.QIcon('gearbox.png'))
    app.setFont(QtGui.QFont("DejaVu Sans Mono", 10))

    main_window = MainWindow()
    main_window.setWindowTitle(f'Gearbox')

    sim_bridge_inst = sim_bridge()
    sim_bridge_inst.script_loading_started.connect(set_main_win_title)
    sim_bridge_inst.script_loading_started.connect(load)

    for l in layers:
        l()

    if script_fn:
        load_rc('.pygears', os.path.dirname(script_fn))
        sim_bridge_inst.invoke_method('run_model', script_fn=script_fn)

    main_window.show()
    ret = app.exec_()
    script_fn = registry('gearbox/main/new_model_script_fn')
    if script_fn:
        print('Quitting: ', sys_args)
        print(('gearbox', sys_args[0], script_fn))
        os.execl(sys_args[0], 'gearbox', script_fn)
    else:
        sys.exit(ret)
Пример #16
0
    def __init__(self):
        super().__init__()

        timestep_event_register(self.update)

        self.graph_intfs = []
        self.instances = []
        self.buffers = []

        try:
            self.create_gtkwave_instance(registry('VCD'), PyGearsVCDMap)
        except KeyError:
            pass

        for m in find_cosim_modules():
            if not isinstance(m, SimVerilated):
                continue

            if m.trace_fn is not None:
                self.create_gtkwave_instance(m, VerilatorVCDMap)
Пример #17
0
 def bind(cls):
     registry(
         'gearbox/plugins/graph')['TimestepModeline'] = TimestepModeline
     registry(
         'gearbox/plugins/graph')['GraphDescription'] = GraphDescription
Пример #18
0
    def bind(cls):
        registry('gearbox/plugins/graph'
                 )['GraphGtkwaveSelectSync'] = GraphGtkwaveSelectSync

        registry(
            'gearbox/plugins/gtkwave')['TimestepModeline'] = TimestepModeline