Exemplo n.º 1
0
    def simulationStart(self):
        """

        :return:
        """
        if hasattr(self.solver.analysis, "running"):
            if not self.solver.analysis.running:
                self._data_timer.start(1000)

                self.job_info_time_started = time.clock()
                self.solver.analysis.running = True
                self.solver.analysis.stopped = False
                self.solver.analysis.finished = False

        self.ui.simulationStartButton.setEnabled(False)
        self.ui.simulationResetButton.setEnabled(False)
        self.ui.simulationStopButton.setEnabled(True)

        #   set simulation start time to display it in a widget
        self.solver.analysis.start_time_simulation_info = QtCore.QDateTime.currentDateTime()
        self.ui.simulationStartTime_dateTimeEdit.setDateTime(self.solver.analysis.start_time_simulation_info)

        #   start simulation timer
        self.elapsed_time = QtCore.QElapsedTimer()
        self.elapsed_time.start()
Exemplo n.º 2
0
 def getWidget(self, splash):
     t = QtCore.QElapsedTimer()
     t.start()
     while (t.elapsed() < 800):
         str = QtCore.QString("times = ") + QtCore.QString.number(t.elapsed())
         splash.showMessage(str)
         QtCore.QCoreApplication.processEvents()
Exemplo n.º 3
0
    def _parseAvailableMessages(self):
        while self._client.messagesAvailable() > 0:
            msg = self._client.readMessage()
            if msg.isNull():
                continue
            res = self._parse(msg)

            # key tuple: (isReply, snr, source)
            # reply tuple: (t, Ack, Reply)
            # command tuple: (t, Command)
            isReply = msg.isReply()
            snr = int(msg.snr)
            source = bytes(msg.source)
            key = (isReply, snr, source)
            t = QtCore.QElapsedTimer()
            t.start()

            if isReply:
                entry = self._inQueue.get(key)
                if entry == None:
                    entry = (None, None, None)
                if isinstance(res, dcp.parser.Ack):
                    entry = (t, res, entry[2])
                elif isinstance(res, dcp.parser.Reply):
                    entry = (t, entry[1], res)
                else:
                    entry = (t, entry[1], msg)
            else:
                if isinstance(res, dcp.parser.Command):
                    entry = (t, res)
                else:
                    entry = (t, msg)
            self._inQueue[key] = entry
Exemplo n.º 4
0
 def getWidget(self, splash):
     t = QtCore.QElapsedTimer()
     t.start()
     while (t.elapsed() < 800):
         showing = "times = " + str(t.elapsed())
         splash.showMessage(showing)
         QtCore.QCoreApplication.processEvents()
Exemplo n.º 5
0
    def __init__(self):
        super(MainEditor, self).__init__()
        self.setWindowTitle('Lex Talionis Level Editor v' + GC.version)
        self.installEventFilter(self)

        # Data
        self.init_data()

        self.view = MainView(self.tile_data, self.tile_info, self.unit_data,
                             self)
        self.setCentralWidget(self.view)

        self.status_bar = self.statusBar()
        self.status_bar.showMessage('Ready')

        self.directory = None
        self.current_level_name = None
        self.image = None

        self.create_actions()
        self.create_menus()
        self.create_dock_windows()

        # Whether anything has changed since the last save
        self.modified = False

        # === Timing ===
        self.main_timer = QtCore.QTimer()
        self.main_timer.timeout.connect(self.tick)
        self.main_timer.start(33)  # 30 FPS
        self.elapsed_timer = QtCore.QElapsedTimer()
        self.elapsed_timer.start()

        # === Auto-open ===
        self.auto_open()
Exemplo n.º 6
0
    def __init__(self, serial=None, *args, **kwargs):
        """

        :param source:
        :param dst:
        :param fps:
        :param size:
        :param serial:
        """
        self.log = logging.getLogger(__name__)
        self.log.info(str(multiprocessing.cpu_count()) + ' CPUs found')

        #try:
        #    import zmq  # ZeroMQ python bindings
        #except ImportError:
        #    zmq = None

        # Setup frame grabber object, fills frame buffer
        self.log.debug('Instantiating grabber...')
        self.grabber = grabber.Grabber(*args, **kwargs)

        # Writer writes frames from buffer to video file in a separate process.
        self.log.debug('Instantiating writer...')
        self.writer_queue = multiprocessing.Queue(16)
        self.writer_pipe, child_pipe = multiprocessing.Pipe()

        self.writer = multiprocessing.Process(target=writer.Writer,
                                              args=(
                                                  self.grabber.fps,
                                                  self.grabber.size,
                                                  self.writer_queue,
                                                  child_pipe,
                                              ))
        self.log.debug('Starting writer...')
        self.writer.start()
        self.log.debug('Instantiating data logger...')
        self.dlogger = datalog.DataLogger()

        # tracker object finds LEDs in frames
        self.log.debug('Instantiating tracker...')
        self.tracker = tracker.Tracker(adaptive_tracking=True)

        # chatter handles serial communication
        self.log.debug('Instantiating chatter...')
        self.chatter = chatter.Chatter(serial, auto=True)

        # self.timer2 = QtCore.QTimer()
        # self.timer2.timeout.connect(self.update)
        # SPOTTER_REFRESH_INTERVAL = int(1000.0 / self.grabber.capture.get(5))
        # self.timer2.start(SPOTTER_REFRESH_INTERVAL)
        self.stopwatch = QtCore.QElapsedTimer()
        self.stopwatch.start()
        p = self.chatter.pins('digital')
        if p is not None and len(p) > 0:
            self.fpstest = self.tracker.trackFPS(p[-1])
        else:
            self.fpstest = None
Exemplo n.º 7
0
    def __init__(self,
                 protocol_xml_path="default_config.xml",
                 command_xml_path="default_config.xml",
                 verbose=False):
        super(KilroyProtocols, self).__init__()

        # Initialize internal attributes
        self.verbose = verbose
        self.protocol_xml_path = protocol_xml_path
        self.command_xml_path = command_xml_path
        self.protocol_names = []
        self.protocol_commands = []  # [Instrument Type, command_info]
        self.protocol_durations = []
        self.num_protocols = 0
        self.status = [-1, -1]  # Protocol ID, command ID within protocol
        self.issued_command = []
        self.received_message = None

        print "----------------------------------------------------------------------"

        # Create instance of ValveCommands class
        self.valveCommands = ValveCommands(xml_file_path=self.command_xml_path,
                                           verbose=self.verbose)

        # Connect valve command issue signal
        self.valveCommands.change_command_signal.connect(
            self.issueValveCommand)

        # Create instance of PumpCommands class
        self.pumpCommands = PumpCommands(xml_file_path=self.command_xml_path,
                                         verbose=self.verbose)

        # Connect pump commands issue signal
        self.pumpCommands.change_command_signal.connect(self.issuePumpCommand)

        # Create GUI
        self.createGUI()

        # Load configurations
        self.loadProtocols(xml_file_path=self.protocol_xml_path)

        # Create protocol timer--controls when commands are issued
        self.protocol_timer = QtCore.QTimer()
        self.protocol_timer.setSingleShot(True)
        self.protocol_timer.timeout.connect(self.advanceProtocol)

        # Create elapsed time timer--determines time between command calls
        self.elapsed_timer = QtCore.QElapsedTimer()
        self.poll_elapsed_time_timer = QtCore.QTimer()
        self.poll_elapsed_time_timer.setInterval(1000)
        self.poll_elapsed_time_timer.timeout.connect(self.updateElapsedTime)
Exemplo n.º 8
0
    def filter_handler(self):
        """ Filter handler is invoked by start cleaning button """
        self.timer = QtCore.QElapsedTimer()
        self.timer.start()

        ignore_str = self.ui.ignore_ext_lineEdit.text().split(",")
        ignore_list = [x.replace(".", "").strip() for x in ignore_str]
        self.filter_thread = FilteringThread(self.file_path, ignore_list)
        logging.info("Filter thread created")
        self.filter_thread.started.connect(self.filter_started)
        self.filter_thread.total_count_signal.connect(self.set_total_count)
        self.filter_thread.update_progress_signal.connect(self.update_progress)
        self.filter_thread.finished.connect(self.filter_completed)
        self.filter_thread.start()
Exemplo n.º 9
0
    def wait(self, msgs=None, timeout=None):
        if timeout == None:
            timeout = self._timeout
        else:
            timeout = int(round(timeout * 1000.0))
        if msgs != None:
            if isinstance(msgs, collections.Iterable):
                keys = []
                for m in msgs:
                    keys.append((True, int(m.snr), bytes(m.destination)))
            else:
                keys = [(True, int(msgs.snr), bytes(msgs.destination))]

        timeLeft = 0
        t = QtCore.QElapsedTimer()
        t.start()
        while (timeLeft >= 0):
            self._client.waitForReadyRead(timeLeft)
            self._parseAvailableMessages()

            if msgs == None:
                m = self._nextCompletedMessage()
                if m != None:
                    return m
            else:
                completed = self._messagesCompleted(keys)
                if all(completed):
                    res = []
                    for k in keys:
                        v = self._inQueue.pop(k)
                        assert len(v) == 3
                        ack, reply = v[1], v[2]
                        if reply != None:
                            res.append(reply)
                        elif ack != None:
                            res.append(ack)
                        else:
                            res.append(None)

                    if len(res) == 1 and (not isinstance(
                            msgs, collections.Iterable)):
                        return res[0]
                    else:
                        return res

            timeLeft = timeout - t.elapsed()
Exemplo n.º 10
0
    def tokenization_handler(self):
        """
        Tokenization handler is invoked by the start tokenization button
        """
        msg = "Please wait. Tokenization in progress."
        self.ui.status_lineEdit.setText(msg)

        self.timer = QtCore.QElapsedTimer()
        self.timer.start()
        f_type = int(self.ui.log_format_comboBox.currentIndex())
        self.init_database()

        self.file_path = self.ui.file_path_textEdit.text()
        try:
            self.thread = TokenizationThread(self.file_path, f_type)
            logging.info("Tokenization Thread created")
        except (OSError, IOError) as e:
            msg = "Unable to open file"
            QtGui.QMessageBox.critical(self.ui.centralwidget, "YAST - Error",
                                       msg + ": " + str(e))
            self.ui.token_frame.setEnabled(False)
            logging.exception("Failed to open file %s" % self.file_path)
            return
        except TypeError:
            msg = "Selected log file doesn't match with the selected log "\
                "format ({}). Please verify file format."
            msg = msg.format(self.ui.log_format_comboBox.currentText())
            self.ui.status_lineEdit.setText(msg)
            QtGui.QMessageBox.critical(self.ui.centralwidget, "YAST - Error",
                                       msg)
            self.ui.token_frame.setEnabled(False)
            logging.exception("Incorrect file format selected")
            return
        except ValueError as e:
            self.ui.status_lineEdit.setText(str(e))
            QtGui.QMessageBox.critical(self.ui.centralwidget, "YAST - Error",
                                       str(e))
            self.ui.token_frame.setEnabled(False)
            logging.exception("Unsupported file format")
            return

        self.thread.update_progress_signal.connect(self.update_progress)
        self.thread.total_count_signal.connect(self.set_total_count)
        self.thread.finished.connect(self.tokenization_completed)
        self.thread.started.connect(self.tokenization_started)
        self.thread.start()
Exemplo n.º 11
0
    def sessionization_handler(self):
        """ Invoked by start sessionization button """

        session_timer = self.ui.time_spinBox.value()
        self.timer = QtCore.QElapsedTimer()
        self.timer.start()

        self.session_thread = SessionThread(self.file_path, session_timer)
        logging.info("Sessionization thread created")
        self.session_thread.started.connect(self.sessionization_started)
        self.session_thread.update_progress_signal.connect(
            self.update_progress)
        self.session_thread.total_count_signal.connect(self.set_total_count)
        self.session_thread.number_of_sessions_signal.connect(
            self.total_sessions_count)
        self.session_thread.step_completed_signal.connect(self.step_completed)
        self.session_thread.finished.connect(self.sessionization_completed)
        self.session_thread.start()
Exemplo n.º 12
0
    def __init__(self, *args,
                 **kwargs):  # , source, destination, fps, size, gui, serial
        self.log = logging.getLogger(__name__)
        QtGui.QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Spotter main class, handles Grabber, Writer, Tracker, Chatter
        self.__spotter_ref = Spotter(*args, **kwargs)

        # Status Bar
        self.status_bar = StatusBar(self)
        self.statusBar().addWidget(self.status_bar)

        # Side bar widget
        self.side_bar = SideBar.SideBar(self)
        self.ui.frame_parameters.addWidget(self.side_bar)

        # Exit Signals
        self.ui.actionE_xit.setShortcut('Ctrl+Q')
        self.ui.actionE_xit.setStatusTip('Exit Spotter')
        self.connect(self.ui.actionE_xit, QtCore.SIGNAL('triggered()'),
                     QtCore.SLOT('close()'))

        # About window
        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'),
                     self.about)

        # Menu Bar items
        #   File
        self.connect(self.ui.actionFile, QtCore.SIGNAL('triggered()'),
                     self.file_open_video)
        self.connect(self.ui.actionCamera, QtCore.SIGNAL('triggered()'),
                     self.file_open_device)
        #   Configuration
        self.connect(self.ui.actionLoadConfig, QtCore.SIGNAL('triggered()'),
                     self.load_config)
        self.connect(self.ui.actionSaveConfig, QtCore.SIGNAL('triggered()'),
                     self.save_config)
        self.connect(self.ui.actionRemoveTemplate,
                     QtCore.SIGNAL('triggered()'),
                     self.side_bar.remove_all_tabs)

        # Toolbar items
        self.connect(self.ui.actionRecord, QtCore.SIGNAL('toggled(bool)'),
                     self.record_video)
        self.connect(self.ui.actionSourceProperties,
                     QtCore.SIGNAL('triggered()'),
                     self.spotter.grabber.get_capture_properties)
        # Serial/Arduino Connection status indicator
        self.arduino_indicator = SerialIndicator(self.spotter.chatter)
        self.ui.toolBar.addWidget(self.arduino_indicator)

        # OpenGL frame
        self.gl_frame = GLFrame(AA=True)
        self.ui.frame_video.addWidget(self.gl_frame)
        self.gl_frame.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                    QtGui.QSizePolicy.Expanding)

        # handling mouse events by the tabs for selection of regions etc.
        self.gl_frame.sig_event.connect(self.mouse_event_to_tab)

        # Loading template list in folder
        default_path = os.path.join(os.path.abspath(DIR_CONFIG),
                                    DEFAULT_TEMPLATE)
        self.template_default = self.parse_config(default_path, True)
        #list_of_files = [f for f in os.listdir(DIR_TEMPLATES) if f.lower().endswith('ini')]

        # Main Window states
        self.center_window()
        self.connect(self.ui.actionOnTop, QtCore.SIGNAL('toggled(bool)'),
                     self.toggle_window_on_top)

        # Starts main frame grabber loop
        self.timer = QtCore.QTimer(self)
        self.timer.timeout.connect(self.refresh)
        self.timer.start(GUI_REFRESH_INTERVAL)

        self.stopwatch = QtCore.QElapsedTimer()
        self.stopwatch.start()
Exemplo n.º 13
0
#!/usr/bin/env python
#https://github.com/KubaO/stackoverflown/tree/master/questions/interval-timer-38036583
# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui

if __name__ == "__main__":
    running = False
    app = QtGui.QApplication(sys.argv)
    w = QtGui.QWidget()
    layout = QtGui.QVBoxLayout(w)
    label = QtGui.QLabel()
    button = QtGui.QPushButton('Start')
    timer = QtCore.QElapsedTimer()
    updateTimer = QtCore.QTimer()

    layout.addWidget(label)
    layout.addWidget(button)

    def onTimeout():
        label.setText('Elapsed: {0}ms'.format(timer.elapsed()))

    def onClicked():
        global running
        if running:
            onTimeout()
            updateTimer.stop()
            button.setText('Start')
        else:
            timer.start()
            updateTimer.start()
Exemplo n.º 14
0
    def __init__(self, *args,
                 **kwargs):  # , source, destination, fps, size, gui, serial
        self.log = logging.getLogger(__name__)
        QtGui.QMainWindow.__init__(self)

        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)

        # Spotter main class, handles Grabber, Writer, Tracker, Chatter
        #  self.spotter_queue= multiprocessing.Queue(16)
        self.__spotter_ref = Spotter(*args, **kwargs)

        # Status Bar
        self.status_bar = StatusBar(self)
        self.statusBar().addWidget(self.status_bar)

        # Side bar widget
        self.side_bar = SideBar.SideBar(self)
        self.ui.frame_parameters.addWidget(self.side_bar)

        # Exit Signals
        #self.ui.actionE_xit.setShortcut('Ctrl+Q')
        #self.ui.actionE_xit.setStatusTip('Exit Spotter')
        #self.connect(self.ui.actionE_xit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))

        # About window
        self.connect(self.ui.actionAbout, QtCore.SIGNAL('triggered()'),
                     self.about)

        #  Open File
        self.connect(self.ui.actionFile, QtCore.SIGNAL('toggled(bool)'),
                     self.file_open_video)
        # Open Video
        self.connect(self.ui.actionCamera, QtCore.SIGNAL('toggled(bool)'),
                     self.file_open_device)
        #   Configuration
        # Load template
        self.connect(self.ui.actionLoadConfig, QtCore.SIGNAL('triggered()'),
                     self.load_config)
        # Save template
        self.connect(self.ui.actionSaveConfig, QtCore.SIGNAL('triggered()'),
                     self.save_config)
        #remove all templates
        self.connect(self.ui.actionRemoveTemplate,
                     QtCore.SIGNAL('triggered()'),
                     self.side_bar.remove_all_tabs)
        #turns GUI on/off --> stabilizes framerate
        self.connect(self.ui.actionGUI_on_off, QtCore.SIGNAL('toggled(bool)'),
                     self.GUI_timers)

        # Toolbar items
        #record video
        self.connect(self.ui.actionRecord, QtCore.SIGNAL('toggled(bool)'),
                     self.record_video)
        #record data log
        self.connect(self.ui.actionLogger, QtCore.SIGNAL('toggled(bool)'),
                     self.start_log)
        #outputs the results for each object to a separate figure
        self.connect(self.ui.actionReset, QtCore.SIGNAL('triggered()'),
                     self.reset_hist)
        #clears output history, and resets filters
        self.connect(self.ui.actionGraph, QtCore.SIGNAL('triggered()'),
                     self.output_graph)
        #show action properties
        #self.connect(self.ui.actionSourceProperties, QtCore.SIGNAL('triggered()'),self.props)
        # Serial/Arduino Connection status indicator
        self.arduino_indicator = SerialIndicator(self.spotter.chatter)
        self.ui.toolBar.addWidget(self.arduino_indicator)

        # OpenGL frame
        self.gl_frame = GLFrame(AA=True)
        self.ui.frame_video.addWidget(self.gl_frame)
        self.gl_frame.setSizePolicy(QtGui.QSizePolicy.Expanding,
                                    QtGui.QSizePolicy.Expanding)

        # handling mouse events by the tabs for selection of regions etc.
        self.gl_frame.sig_event.connect(self.mouse_event_to_tab)

        # Loading template list in folder
        default_path = os.path.join(os.path.abspath(DIR_CONFIG),
                                    DEFAULT_TEMPLATE)

        self.template_default = self.parse_config(default_path, True)
        #list_of_files = [f for f in os.listdir(DIR_TEMPLATES) if f.lower().endswith('ini')]

        # Main Window states
        self.center_window()
        self.connect(self.ui.actionOnTop, QtCore.SIGNAL('toggled(bool)'),
                     self.toggle_window_on_top)
        #Outputs FPS signal
        self.connect(self.ui.actionFPS_test, QtCore.SIGNAL('toggled(bool)'),
                     self.trackFPS)

        #asynchronously updates GUI
        self.connect(self.ui.actionSpeed_up, QtCore.SIGNAL('toggled(bool)'),
                     self.speedUp)

        # Starts main frame grabber loop
        self.timerGL = QtCore.QTimer(self)
        self.timerGL.timeout.connect(self.refresh)

        self.timerSide = QtCore.QTimer(self)
        self.timerSide.timeout.connect(self.side_bar.update_current_page)

        #
        self.stopwatch = QtCore.QElapsedTimer()
        self.stopwatch.start()
        #Main timer for updating Spotter
        self.timer2 = QtCore.QTimer(self)
        self.timer2.timeout.connect(self.spotterUpdate)
        #SPOTTER_REFRESH_INTERVAL=int(1000.0/self.spotter.grabber.capture.get(5))
        self.timer2.start(SPOTTER_REFRESH_INTERVAL)

        self.ui.actionSpeed_up.setChecked(True)
        self.ui.actionFPS_test.setChecked(True)
Exemplo n.º 15
0
    def __init__(self, window):
        super(UnitView, self).__init__(window)
        self.grid = QtGui.QGridLayout()
        self.window = window
        # window.setLayout(self.grid)
        self.current_unit = None

        # === Unit Face Display ===
        face_grid = QtGui.QGridLayout()

        self.portrait = QtGui.QLabel()
        face_grid.addWidget(self.portrait, 0, 0, 4, 4, QtCore.Qt.AlignCenter)

        self.smile_button = QtGui.QPushButton('Smile')
        self.smile_button.setCheckable(True)
        self.smile_button.clicked.connect(self.smile)
        self.talk_button = QtGui.QPushButton('Talk')
        self.talk_button.setCheckable(True)
        self.talk_button.clicked.connect(self.talk)
        face_grid.addWidget(self.smile_button, 4, 0, 1, 2)
        face_grid.addWidget(self.talk_button, 4, 2, 1, 2)

        blink_label = QtGui.QLabel('Blink Pos. (x, y)')
        mouth_label = QtGui.QLabel('Mouth Pos. (x, y)')
        face_grid.addWidget(blink_label, 5, 0, 1, 2)
        face_grid.addWidget(mouth_label, 5, 2, 1, 2)
        self.portrait_pos_boxes = []
        for num in xrange(4):
            box = QtGui.QSpinBox()
            box.setMinimum(0)
            box.setMaximum(96)
            face_grid.addWidget(box, 6, num)
            self.portrait_pos_boxes.append(box)

        # === Character Data ===
        char_grid = QtGui.QGridLayout()

        # Name
        name_label = QtGui.QLabel('Name:')
        char_grid.addWidget(name_label, 0, 0, 1, 2)
        self.name = QtGui.QLineEdit()
        self.name.setMaxLength(12)
        self.name.setStatusTip("Change name")
        char_grid.addWidget(self.name, 0, 1, 1, 2)
        # Level
        level_label = QtGui.QLabel('Level:')
        char_grid.addWidget(level_label, 1, 0)
        self.level = QtGui.QSpinBox()
        self.level.setMinimum(1)
        char_grid.addWidget(self.level, 1, 1)
        # Gender
        gender_label = QtGui.QLabel('Gender:')
        char_grid.addWidget(gender_label, 1, 2)
        self.gender = QtGui.QSpinBox()
        self.gender.setMinimum(0)
        self.gender.setMaximum(9)
        char_grid.addWidget(self.gender, 1, 3)
        # Class
        klass_label = QtGui.QLabel('Class:')
        char_grid.addWidget(klass_label, 2, 0)
        self.klass = QtGui.QComboBox()
        self.klass.uniformItemSizes = True
        self.klass.setIconSize(QtCore.QSize(48, 32))
        for klass in class_data:
            if 'icon' in klass and klass['icon']:
                self.klass.addItem(klass['icon'], klass['name'])
            else:
                self.klass.addItem(klass['name'])
        char_grid.addWidget(self.klass, 2, 1, 1, 3)

        # Faction
        faction_label = QtGui.QLabel('Faction:')
        char_grid.addWidget(faction_label, 3, 0)
        self.faction = QtGui.QLineEdit()
        char_grid.addWidget(self.faction, 3, 1, 1, 3)
        # Lordbox
        self.lord = QtGui.QCheckBox('Lord?')
        char_grid.addWidget(self.lord, 4, 0, 1, 2)
        # Boss box
        self.boss = QtGui.QCheckBox('Boss?')
        char_grid.addWidget(self.boss, 4, 2, 1, 2)

        # Description
        desc_label = QtGui.QLabel('Desc:')
        char_grid.addWidget(desc_label, 5, 0)
        self.desc = QtGui.QTextEdit()
        char_grid.addWidget(self.desc, 5, 1, 2, 3)

        # === Stats ===
        stat_grid = QtGui.QGridLayout()
        # Names
        stats_label = QtGui.QLabel('Stats:')
        stat_grid.addWidget(stats_label, 0, 0)
        for index, stat_name in enumerate(cf.CONSTANTS['stat_names']):
            stat_label = QtGui.QLabel(stat_name)
            stat_grid.addWidget(stat_label, 0, index + 1)

        bases_label = QtGui.QLabel('Bases:')
        stat_grid.addWidget(bases_label, 1, 0)
        growths_label = QtGui.QLabel('Growths:')
        stat_grid.addWidget(growths_label, 2, 0)

        self.stat_bases = [
            QtGui.QSpinBox() for stat in cf.CONSTANTS['stat_names']
        ]
        self.stat_growths = [
            QtGui.QSpinBox() for stat in cf.CONSTANTS['stat_names']
        ]
        for index, s in enumerate(self.stat_bases):
            s.setMinimum(0)
            s.setMaximum(cf.CONSTANTS['max_stat'])
            stat_grid.addWidget(s, 1, index + 1)
        for index, s in enumerate(self.stat_growths):
            s.setSingleStep(5)
            s.setMaximum(500)
            stat_grid.addWidget(s, 2, index + 1)

        # === Weapon Exp ===
        wexp_grid = QtGui.QGridLayout()
        wexp_label = QtGui.QLabel('Wexp:')
        wexp_grid.addWidget(wexp_label, 0, 0, 2, 1)
        weapon_types = CustomObjects.WEAPON_TRIANGLE.types
        for index, wexp_name in enumerate(weapon_types):
            name_label = QtGui.QLabel(wexp_name)
            icon_label = QtGui.QLabel()
            wexp_icon = CustomObjects.WeaponIcon(idx=index)
            icon_label.setPixmap(
                create_pixmap(wexp_icon.image.convert_alpha(), self.window))
            wexp_grid.addWidget(name_label, 0, (index + 1) * 2 + 1)
            wexp_grid.addWidget(icon_label, 0, (index + 1) * 2)
        self.wexp = [QtGui.QSpinBox() for wexp in weapon_types]
        for index, s in enumerate(self.wexp):
            s.setMinimum(0)
            s.setMaximum(CustomObjects.WEAPON_EXP.sorted_list[-1][1])
            wexp_grid.addWidget(s, 1, (index + 1) * 2, 1, 2)
        # Horizontal line
        line = QtGui.QFrame()
        line.setFrameStyle(QtGui.QFrame.HLine)
        line.setLineWidth(0)
        wexp_grid.addWidget(line, 2, 0, 1, len(self.wexp) * 2 + 2)

        # === Items ===
        item_grid = QtGui.QGridLayout()
        item_label = QtGui.QLabel('Item:')
        drop_label = QtGui.QLabel('Drop?')
        event_label = QtGui.QLabel('Event?')
        self.add_item_button = QtGui.QPushButton('Add Item')
        self.add_item_button.clicked.connect(self.add_item)
        self.remove_item_button = QtGui.QPushButton('Remove Item')
        self.remove_item_button.clicked.connect(self.remove_item)
        self.remove_item_button.setEnabled(False)

        self.items = []
        for num in xrange(cf.CONSTANTS['max_items']):
            self.items.append((self.create_item_combo_box(), QtGui.QCheckBox(),
                               QtGui.QCheckBox()))
        for index, item in enumerate(self.items):
            item_box, drop, event = item
            item_grid.addWidget(item_box, index + 1, 0, 1, 2,
                                QtCore.Qt.AlignTop)
            item_grid.addWidget(drop, index + 1, 2, QtCore.Qt.AlignTop)
            item_grid.addWidget(event, index + 1, 3, QtCore.Qt.AlignTop)

        item_grid.addWidget(item_label, 0, 0, 1, 2, QtCore.Qt.AlignTop)
        item_grid.addWidget(drop_label, 0, 2, QtCore.Qt.AlignTop)
        item_grid.addWidget(event_label, 0, 3, QtCore.Qt.AlignTop)
        item_grid.addWidget(self.add_item_button,
                            cf.CONSTANTS['max_items'] + 2, 0, 1, 2,
                            QtCore.Qt.AlignBottom)
        item_grid.addWidget(self.remove_item_button,
                            cf.CONSTANTS['max_items'] + 2, 2, 1, 2,
                            QtCore.Qt.AlignBottom)
        self.clear_items()

        # === Personal Skills ===
        skill_grid = QtGui.QGridLayout()
        skill_label = QtGui.QLabel('Personal Skill:')
        self.add_skill_button = QtGui.QPushButton('Add Skill')
        self.add_skill_button.clicked.connect(self.add_skill)
        self.remove_skill_button = QtGui.QPushButton('Remove Skill')
        self.remove_skill_button.clicked.connect(self.remove_skill)
        self.remove_skill_button.setEnabled(False)

        self.skills = []
        for num in xrange(cf.CONSTANTS['num_skills']):
            self.skills.append(self.create_skill_combo_box())
        for index, skill_box in enumerate(self.skills):
            skill_grid.addWidget(
                skill_box,
                index + 1,
                0,
                1,
                2,
            )

        skill_grid.addWidget(skill_label, 0, 0, 1, 2, QtCore.Qt.AlignTop)
        skill_grid.addWidget(self.add_skill_button,
                             cf.CONSTANTS['num_skills'] + 2, 0)
        skill_grid.addWidget(self.remove_skill_button,
                             cf.CONSTANTS['num_skills'] + 2, 1)
        self.clear_skills()

        # === Final gridding ===
        self.grid.addLayout(self.stretch(face_grid), 0, 0)
        self.grid.addLayout(self.stretch(char_grid), 0, 1)
        self.grid.addLayout(self.stretch(stat_grid), 1, 0, 1, 2)
        self.grid.addLayout(self.stretch(wexp_grid), 2, 0, 1, 2)
        # item_frame = QtGui.QFrame()
        # item_frame.setFrameStyle(QtGui.QFrame.StyledPanel)
        # item_frame.setLineWidth(0)
        # item_frame.setLayout(self.stretch(item_grid))
        self.grid.addLayout(self.stretch(item_grid), 3, 0)
        self.grid.addLayout(self.stretch(skill_grid), 3, 1)

        # === Timing ===
        self.main_timer = QtCore.QTimer()
        self.main_timer.timeout.connect(self.tick)
        self.main_timer.start(33)  # 30 FPS
        self.elapsed_timer = QtCore.QElapsedTimer()
        self.elapsed_timer.start()
Exemplo n.º 16
0
Arquivo: gui.py Projeto: Jonksar/todo
    def __init__(self, fps=60, demo=None):
        super(DesktopDemoWindow, self).__init__()

        # Screen variables
        screen_resolution = app.desktop().screenGeometry()

        def clamp(value, minvalue, maxvalue):
            return max(minvalue, min(value, maxvalue))

        def linear_interp(y0, y1, t):
            t = clamp(t, 0, 1)
            return y0 + t * (y1 - y0)

        self.sc_width = screen_resolution.width()
        self.sc_height = screen_resolution.height()

        # resources
        self.pixmap_unlocked = QPixmap('res/16labDemoUnlocked2.png').scaled(self.sc_width, self.sc_height)
        self.pixmap_locked = QPixmap('res/16labDemoLocked2.png').scaled(self.sc_width, self.sc_height)

        # Updating variables
        self.fps = fps
        self._xmap_unlocked = QPixmap('res/16labDemoUnlocked2.png').scaled(self.sc_width, self.sc_height)
        self._update_time = 1000 / fps

        self.update_timer = QtCore.QTimer()
        self.update_timer.timeout.connect(self._update)
        self.update_timer.start(self._update_time)

        # The higher level control variables
        self.lock_event = Event()
        self.state = Status.locked

        # Widget variables
        self.transition_speed = 500
        self.progress_timer = QtCore.QElapsedTimer()
        self.progress_timer.start()

        self.true_progress = 0
        self.visible_progress = 0

        self.target_progress = self.MAX_OPACITY
        self.started_progess = 0

        # Setting up data input settings
        self.demo = demo
        self.demo.set_event_ref(event_ref=self.lock_event)

        # Demo update
        self.demo_update_timer = QtCore.QTimer()
        self.demo_update_timer.timeout.connect(self.demo.update)
        self.demo_update_timer.start(5)

        # Setting up the window itself
        self.label_unlocked = QLabel(self)
        self.label_unlocked.setPixmap(self.pixmap_unlocked)
        self.label_unlocked.setGraphicsEffect(self.gen_opacity_effect(self.target_progress))

        self.setWindowTitle("16lab laptop demo")
        self.label_locked = QLabel(self)
        self.label_locked.setPixmap(self.pixmap_locked)
        self.label_locked.setGraphicsEffect(self.gen_opacity_effect(self.started_progess))

        self.painter = QPainter()

        self.resize(self.sc_width, self.sc_height)