Ejemplo n.º 1
0
def removeShortcut(action, key):
    """Removes matching QKeySequence from the list of the action."""
    key = QKeySequence(key)
    shortcuts = action.shortcuts()
    for s in action.shortcuts():
        if key.matches(s) or s.matches(key):
            shortcuts.remove(s)
    action.setShortcuts(shortcuts)
Ejemplo n.º 2
0
 def test_load_default_shortcuts(self):
     shorts_count = self.shortcuts_manager.result_widget.topLevelItemCount()
     item = self.shortcuts_manager.result_widget.topLevelItem(0)
     shortcut_keys = item.text(1)
     # Expected data
     expected_key = QKeySequence(Qt.CTRL + Qt.Key_N)
     expected_key_str = expected_key.toString(QKeySequence.NativeText)
     # Just one shortcut should be loaded
     self.assertEqual(shorts_count, 1)
     # The key should be the same as the expected
     self.assertEqual(shortcut_keys, expected_key_str)
Ejemplo n.º 3
0
def keySequenceClicks(widget, keySequence, extraModifiers=Qt.NoModifier):
    """Use QTest.keyClick to send a QKeySequence to a widget."""

    # This is based on a simplified version of http://stackoverflow.com/questions/14034209/convert-string-representation-of-keycode-to-qtkey-or-any-int-and-back. I added code to handle the case in which the resulting key contains a modifier (for example, Shift+Home). When I execute QTest.keyClick(widget, keyWithModifier), I get the error "ASSERT: "false" in file .\qasciikey.cpp, line 495". To fix this, the following code splits the key into a key and its modifier.
    # Bitmask for all modifier keys.
    modifierMask = int(Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier |
                       Qt.MetaModifier |  Qt.KeypadModifier)
    ks = QKeySequence(keySequence)
    # For now, we don't handle a QKeySequence("Ctrl") or any other modified by itself.
    assert ks.count() > 0
    for _, key in enumerate(ks):
        modifiers = Qt.KeyboardModifiers((key & modifierMask) | extraModifiers)
        key = key & ~modifierMask
        QTest.keyClick(widget, key, modifiers)
Ejemplo n.º 4
0
 def _add_global_shortcut_listener(self, keyseq):
     # Create a shortcut for this new key sequence
     # Note: We associate the shortcut with the ENTIRE WINDOW.
     #       We intercept the shortcut and decide which widget to direct it to.
     #       (We don't rely on Qt to do this for us.)
     # Note: This class assumes that all widgets using shortcuts belong to the SAME main window.
     assert keyseq not in self._global_shortcuts
     keyseq = QKeySequence(keyseq)
     keytext = str(keyseq.toString())
     self._global_shortcuts[keytext] = QShortcut(
         QKeySequence(keyseq),
         getMainWindow(),
         member=partial(self._handle_shortcut_pressed, keytext),
         context=Qt.ApplicationShortcut,
     )
Ejemplo n.º 5
0
def importShortcut(filename, widget, schemeWidget):
    """Loads shortcuts from a file"""
    try:
        d = ET.parse(filename)
        root = d.getroot()
        if root.tag != 'frescobaldi-shortcut':
            raise ValueError(_("No shortcuts found."))
    except Exception as e:
        QMessageBox.critical(widget, app.caption(_("Error")),
        _("Can't read from source:\n\n{url}\n\n{error}").format(
            url=filename, error=e))
        return

    schemeWidget.scheme.blockSignals(True)
    scheme = schemeWidget.addScheme(root.get('name'))
    schemeWidget.scheme.blockSignals(False)

    for col in root.findall('collection'):
        for name in col.findall('name'):
            shortcuts = [QKeySequence.fromString(shortcut.text) for shortcut in name.findall('shortcut')]
            item = widget.item(col.attrib['name'], name.attrib['name'])
            if item:
                item.setShortcuts(shortcuts, scheme)

    schemeWidget.disableDefault(False)
    schemeWidget.currentChanged.emit()
    schemeWidget.changed.emit()
Ejemplo n.º 6
0
    def create_context_menu(self):
        menu = QMenu()
        menu.setToolTipsVisible(True)
        self._add_zoom_actions_to_menu(menu)

        if self.something_is_selected:
            filter_bw = Filter.read_configured_filter_bw()
            text = self.tr("Apply bandpass filter (filter bw={0:n})".format(filter_bw))
            create_from_frequency_selection = menu.addAction(text)
            create_from_frequency_selection.triggered.connect(self.on_create_from_frequency_selection_triggered)
            create_from_frequency_selection.setIcon(QIcon.fromTheme("view-filter"))

            try:
                cancel_button = " or ".join(k.toString() for k in QKeySequence.keyBindings(QKeySequence.Cancel))
            except Exception as e:
                logger.debug("Error reading cancel button: " + str(e))
                cancel_button = "Esc"

            create_from_frequency_selection.setToolTip("You can abort filtering with <b>{}</b>.".format(cancel_button))

        configure_filter_bw = menu.addAction(self.tr("Configure filter bandwidth..."))
        configure_filter_bw.triggered.connect(self.on_configure_filter_bw_triggered)
        configure_filter_bw.setIcon(QIcon.fromTheme("configure"))

        menu.addSeparator()

        export_fta_action = menu.addAction("Export spectrogram...")
        export_fta_action.triggered.connect(self.on_export_fta_action_triggered)

        return menu
Ejemplo n.º 7
0
 def startRecording(self):
     self.setFocus(True) # because of QTBUG 17810
     self.setDown(True)
     self.setStyleSheet("text-align: left;")
     self._isrecording = True
     self._recseq = QKeySequence()
     self._modifiers = int(QApplication.keyboardModifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
     self.grabKeyboard()
     self.updateDisplay()
Ejemplo n.º 8
0
    def change_keyseq(self, group, name, old_keyseq, keyseq):
        """
        Customize a shortcut's activating key sequence.
        """
        if old_keyseq:
            old_keyseq = QKeySequence(old_keyseq)
            old_keytext = str(old_keyseq.toString())
            self._keyseq_target_actions[old_keytext].remove((group, name))
        try:
            keyseq = QKeySequence(keyseq)
            keytext = str(keyseq.toString())
            target_name_set = self._keyseq_target_actions[keytext]
        except KeyError:
            target_name_set = self._keyseq_target_actions[keytext] = set()
            self._add_global_shortcut_listener(keyseq)

        target_name_set.add((group, name))
        self._update_tooltip(group, name, keyseq)
Ejemplo n.º 9
0
 def __init__(self, parent=None):
     super(KeySequenceButton, self).__init__(parent)
     self.setIcon(icons.get("configure"))
     self._modifierlessAllowed = False
     self._seq = QKeySequence()
     self._timer = QTimer()
     self._timer.setSingleShot(True)
     self._isrecording = False
     self.clicked.connect(self.startRecording)
     self._timer.timeout.connect(self.doneRecording)
Ejemplo n.º 10
0
    def on_new_shortcut(self):
        new_shortcut = str(QKeySequence.toString(self.new_shortcut.keySequence()))
        self.controller.update_hotkey(self.selected_option, new_shortcut)

        # Regenerate list
        self.ui.listWidget_hotkey.clear()
        self.generate_hotkey_list()

        # Update inputs
        self.ui.lineEdit_current_shortcut.setText(new_shortcut)
        self.new_shortcut.clear()
Ejemplo n.º 11
0
 def setShortcut(self, identifier, shortcut: QtGui.QKeySequence):
     """Set a shortcut for the action named `identifier`."""
     action = self.actions[identifier]
     action.shortcut = shortcut
     if action.shortcut == action.defaultShortcut:
         # remove from storage, if it's there (we only store non-defaults)
         if identifier in config.storage.gui.shortcuts:
             del config.storage.gui.shortcuts[identifier]
     else:
         config.storage.gui.shortcuts[identifier] = shortcut.toString()
     self.shortcutChanged.emit(identifier, shortcut)
Ejemplo n.º 12
0
    def text(self):
        """Get the text which would be displayed when pressing this key."""
        control = {
            Qt.Key_Space: ' ',
            Qt.Key_Tab: '\t',
            Qt.Key_Backspace: '\b',
            Qt.Key_Return: '\r',
            Qt.Key_Enter: '\r',
            Qt.Key_Escape: '\x1b',
        }

        if self.key in control:
            return control[self.key]
        elif not _is_printable(self.key):
            return ''

        text = QKeySequence(self.key).toString()
        if not self.modifiers & Qt.ShiftModifier:
            text = text.lower()
        return text
Ejemplo n.º 13
0
class HotkeyLineEdit(QLineEdit):
    key_sequence = None

    def __init__(self, parent=None):
        super(HotkeyLineEdit, self).__init__(parent)
        self.clearKeySequence()

    def clearKeySequence(self):
        self.key_sequence = QKeySequence()
        self.updateText()

    def setKeySequence(self, keyseq):
        if not isinstance(keyseq, QKeySequence): raise RuntimeError
        self.key_sequence = keyseq
        self.updateText()

    def updateText(self):
        self.setText(self.key_sequence.toString(QKeySequence.NativeText))

    def mousePressEvent(self, event):
        log.info("Mouse press")
        # TODO: construct a data structure to hold mouse presses that can be used as shortcuts

    def keyPressEvent(self, event):
        log.info("Key Press")
        key = event.key(); 
        key = Qt.Key(key); 

        # Ignore unknown keys
        # and if modifier keys come alone
        if key == Qt.Key_unknown or key in (Qt.Key_Control, Qt.Key_Alt, Qt.Key_AltGr, Qt.Key_Shift):
            return

        # Pressing Backspace will clear the content
        if key == Qt.Key_Backspace:
            self.setText(None)
            self.clearKeySequence()
            return
        
        # Checking for key combinations
        modifiers = event.modifiers();

        if(modifiers & Qt.NoModifier):
            return
        if(modifiers & Qt.ShiftModifier):
            key += Qt.SHIFT
        if(modifiers & Qt.ControlModifier):
            key += Qt.CTRL 
        if(modifiers & Qt.AltModifier):
            key += Qt.ALT 

        self.setKeySequence(QKeySequence(key))
Ejemplo n.º 14
0
    def handleKeyEvent(self, e):
        nextKey = e.key()
        if (nextKey == Qt.Key_Control or nextKey == Qt.Key_Shift or
                nextKey == Qt.Key_Meta or nextKey == Qt.Key_Alt or
                nextKey == Qt.Key_Super_L or nextKey == Qt.Key_AltGr):
            return

        nextKey |= self.translateModifiers(e.modifiers(), e.text())
        k0 = 0
        k1 = 0
        k2 = 0
        k3 = 0
        l = len(self.m_keySequence)
        if l==1:
            k0 = self.m_keySequence[0]
        elif l==2:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
        elif l==3:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
        elif l==4:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
            k3 = self.m_keySequence[3]
        if self.m_num==0:
            k0 = nextKey
            k1 = 0
            k2 = 0
            k3 = 0
        elif self.m_num==1:
            k1 = nextKey
            k2 = 0
            k3 = 0
        elif self.m_num==2:
            k2 = nextKey
            k3 = 0
        elif self.m_num==3:
            k3 = nextKey
        else:
            pass

        self.m_num += 1
        if (self.m_num > 3):
            self.m_num = 0
        self.m_keySequence = QKeySequence(k0, k1, k2, k3)
        self.m_lineEdit.setText(self.m_keySequence.toString(QKeySequence.NativeText))
        e.accept()
        self.keySequenceChangedSignal.emit(self.m_keySequence)
Ejemplo n.º 15
0
    def __init__(self,parent=None):
        super(QtKeySequenceEdit, self).__init__(parent)

        self.m_keySequence = QKeySequence()
        self.m_num = 0
        self.m_lineEdit = QLineEdit(self)
        layout = QHBoxLayout(self)
        layout.addWidget(self.m_lineEdit)
        layout.setContentsMargins(0, 0, 0, 0)
        self.m_lineEdit.installEventFilter(self)
        self.m_lineEdit.setReadOnly(True)
        self.m_lineEdit.setFocusProxy(self)
        self.setFocusPolicy(self.m_lineEdit.focusPolicy())
        self.setAttribute(Qt.WA_InputMethodEnabled)
Ejemplo n.º 16
0
    def test_save_shortcuts(self):
        data = []

        def called():
            data.append(True)

        actions = gui.FakeActions()
        setattr(actions, 'update_shortcuts', called)
        self.patch(shortcut_manager.actions, 'Actions', lambda: actions)
        self.shortcuts_manager.result_widget.clear()
        key = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_N)
        key_str = key.toString(QKeySequence.NativeText)
        tree_data = ["New File", key_str, "New-File"]
        item = QTreeWidgetItem(self.shortcuts_manager.result_widget, tree_data)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        # Before save there is nothing in QSettings
        self.assertEqual(self.settings.value("New-File", None), None)
        # Save
        self.shortcuts_manager.save()
        # After save there is a value for New-File QSettings
        self.assertEqual(self.settings.values["New-File"], key_str)
        # After save check if NINJA call the update_shortcuts in actios.Actions
        self.assertEqual(data, [True])
Ejemplo n.º 17
0
    def keyPressEvent(self, ev):
        if not self._isrecording:
            return super(KeySequenceButton, self).keyPressEvent(ev)
        if ev.isAutoRepeat():
            return
        modifiers = int(ev.modifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        ev.accept()
        
        key = ev.key()
        # check if key is a modifier or a character key without modifier (and if that is allowed)
        if (
            # don't append the key if the key is -1 (garbage) or a modifier ...
            key not in (-1, Qt.Key_AltGr, Qt.Key_Shift, Qt.Key_Control,
                            Qt.Key_Alt, Qt.Key_Meta, Qt.Key_Menu)
            # or if this is the first key and without modifier and modifierless keys are not allowed
            and (self._modifierlessAllowed
                 or self._recseq.count() > 0
                 or modifiers & ~Qt.SHIFT
                 or not ev.text()
                 or (modifiers & Qt.SHIFT
                     and key in (Qt.Key_Return, Qt.Key_Space, Qt.Key_Tab, Qt.Key_Backtab,
                                 Qt.Key_Backspace, Qt.Key_Delete, Qt.Key_Escape)))):
            # change Shift+Backtab into Shift+Tab
            if key == Qt.Key_Backtab and modifiers & Qt.SHIFT:
                key = Qt.Key_Tab | modifiers
            # remove the Shift modifier if it doesn't make sense
#            elif (Qt.Key_Exclam <= key <= Qt.Key_At
#                  or Qt.Key_Z < key <= 0x0ff):
#                key = key | (modifiers & ~Qt.SHIFT)
            else:
                key = key | modifiers
            
            # append max. 4 keystrokes
            if self._recseq.count() < 4:
                l = list(self._recseq)
                l.append(key)
                self._recseq = QKeySequence(*l)
        
        self._modifiers = modifiers
        self.controlTimer()
        self.updateDisplay()
Ejemplo n.º 18
0
    def __init__(self, parent):
        self.parent = parent

        # load application settings (fixed location)
        self.appsettings = QSettings(COMPANY, APPLICATION)
        config = self.appsettings.value("settings")
        if config:
            # merge settings
            self.settings = dict(list(self.settings.items()) + list(config.items()))

        self.setupDefaultShortcuts()
        shortcuts = self.appsettings.value("shortcuts")
        if shortcuts:
            # unserialize keysequences and assign them to their corresponding shortcuts!
            for key, value in shortcuts.items():
                keysequence = QKeySequence.fromString(value, QKeySequence.NativeText)

                # skip shortcuts that don't exist
                if key not in self.shortcuts:
                    continue

                self.shortcuts[key].setKey(keysequence)

        self.refreshMangaSettings()
Ejemplo n.º 19
0
class QtKeySequenceEdit(QWidget):
    keySequenceChangedSignal = pyqtSignal(QKeySequence)
    def __init__(self,parent=None):
        super(QtKeySequenceEdit, self).__init__(parent)

        self.m_keySequence = QKeySequence()
        self.m_num = 0
        self.m_lineEdit = QLineEdit(self)
        layout = QHBoxLayout(self)
        layout.addWidget(self.m_lineEdit)
        layout.setContentsMargins(0, 0, 0, 0)
        self.m_lineEdit.installEventFilter(self)
        self.m_lineEdit.setReadOnly(True)
        self.m_lineEdit.setFocusProxy(self)
        self.setFocusPolicy(self.m_lineEdit.focusPolicy())
        self.setAttribute(Qt.WA_InputMethodEnabled)

    def eventFilter(self, o, e):
        if o == self.m_lineEdit and e.type() == QEvent.ContextMenu:
            c = e
            menu = self.m_lineEdit.createStandardContextMenu()
            actions = menu.actions()
            for action in actions:
                action.setShortcut(QKeySequence())
                actionString = action.text()
                pos = actionString.rfind('\t')
                if (pos > 0):
                    actionString = actionString[:pos]
                action.setText(actionString)

            actionBefore = None
            if (len(actions) > 0):
                actionBefore = actions[0]
            clearAction = QAction(self.tr("Clear Shortcut"), menu)
            menu.insertAction(actionBefore, clearAction)
            menu.insertSeparator(actionBefore)
            clearAction.setEnabled(not len(self.m_keySequence)<=0)
            clearAction.triggered.connect(self.slotClearShortcut)
            menu.exec(c.globalPos())
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).eventFilter(o, e)

    def slotClearShortcut(self):
        if len(self.m_keySequence) <= 0:
            return
        self.setKeySequence(QKeySequence())
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def handleKeyEvent(self, e):
        nextKey = e.key()
        if (nextKey == Qt.Key_Control or nextKey == Qt.Key_Shift or
                nextKey == Qt.Key_Meta or nextKey == Qt.Key_Alt or
                nextKey == Qt.Key_Super_L or nextKey == Qt.Key_AltGr):
            return

        nextKey |= self.translateModifiers(e.modifiers(), e.text())
        k0 = 0
        k1 = 0
        k2 = 0
        k3 = 0
        l = len(self.m_keySequence)
        if l==1:
            k0 = self.m_keySequence[0]
        elif l==2:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
        elif l==3:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
        elif l==4:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
            k3 = self.m_keySequence[3]
        if self.m_num==0:
            k0 = nextKey
            k1 = 0
            k2 = 0
            k3 = 0
        elif self.m_num==1:
            k1 = nextKey
            k2 = 0
            k3 = 0
        elif self.m_num==2:
            k2 = nextKey
            k3 = 0
        elif self.m_num==3:
            k3 = nextKey
        else:
            pass

        self.m_num += 1
        if (self.m_num > 3):
            self.m_num = 0
        self.m_keySequence = QKeySequence(k0, k1, k2, k3)
        self.m_lineEdit.setText(self.m_keySequence.toString(QKeySequence.NativeText))
        e.accept()
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def setKeySequence(self, sequence):
        if (sequence == self.m_keySequence):
            return
        self.m_num = 0
        self.m_keySequence = sequence
        self.m_lineEdit.setText(self.m_keySequence.toString(QKeySequence.NativeText))

    def keySequence(self):
        return self.m_keySequence

    def translateModifiers(self, state, text):
        result = 0
        if ((state & Qt.ShiftModifier) and (len(text) == 0 or not text[0].isprintable() or text[0].isalpha() or text[0].isspace())):
            result |= Qt.SHIFT
        if (state & Qt.ControlModifier):
            result |= Qt.CTRL
        if (state & Qt.MetaModifier):
            result |= Qt.META
        if (state & Qt.AltModifier):
            result |= Qt.ALT
        return result

    def focusInEvent(self, e):
        self.m_lineEdit.event(e)
        self.m_lineEdit.selectAll()
        super(QtKeySequenceEdit, self).focusInEvent(e)

    def focusOutEvent(self, e):
        self.m_num = 0
        self.m_lineEdit.event(e)
        super(QtKeySequenceEdit, self).focusOutEvent(e)

    def keyPressEvent(self, e):
        self.handleKeyEvent(e)
        e.accept()

    def keyReleaseEvent(self, e):
        self.m_lineEdit.event(e)

    def paintEvent(self, ptQPaintEvent):
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self)

    def event(self,e):
        if (e.type() == QEvent.Shortcut or
                e.type() == QEvent.ShortcutOverride  or
                e.type() == QEvent.KeyRelease):
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).event(e)
    def __init__(self, parent=None):
        super(Tree, self).__init__(parent)

        self.model = myStandardItemModel()
        self.setModel(self.model)

        # DATA
        # sampleTable = np.array([["S12345", "11", "12", "13", "14"],
        #                         ["S2", "21", "22", "23", "24"],
        #                         ["S3", "31", "32", "33", "34"], ])

        sampleTable = [["S1", "100", "1", "1", "1", "1", "1", "1", "1"],
                       ["S2", "200", "2", "2", "2", "2", "2", "2", "2"],
                       ["S3", "300", "3", "3", "3", "3", "3", "3", "3"],
                       ["S4", "400", "4", "4", "4", "4", "4", "4", "4"],
                       ["", "", " ", " ", " ", " ", " ", " ", " "],
                       ["", "", " ", " ", " ", " ", " ", " ", " "],
                       ["", "", " ", " ", " ", " ", " ", " ", " "]]

        self.headerLabels_sampTable = ["Sample/Title", "Trans", "Height", "Phi Offset",\
                                       "Psi", "Footprint", "Resolution", "Coarse_noMirror", "Switch"]
        self.tableModel = TableModel(self, sampleTable,
                                     self.headerLabels_sampTable)

        self.delegate = ComboBoxDelegate(self, sampleTable)
        self.setItemDelegateForColumn(1, self.delegate)
        self.tableModel.dataChanged.connect(self.delegate.updateCombo)
        self.tableModel.dataChanged.connect(self.updateSummary)
        self.model.dataChanged.connect(self.updateRuntime)

        #self.setEditTriggers(QtWidgets.QAbstractItemView.AllEditTriggers)#CurrentChanged)
        self.setDragDropMode(QtWidgets.QAbstractItemView.InternalMove
                             | QtWidgets.QAbstractItemView.DragDrop)
        self.setDragEnabled(True)
        self.setAcceptDrops(True)

        self.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
        self.resizeColumnToContents(0)
        self.setAlternatingRowColors(True)
        font = QtGui.QFont("Verdana", 10.5)
        font.setWeight(QtGui.QFont.Bold)
        self.header().setFont(font)
        # self.resize(self.sizeHint().height(), self.minimumHeight())

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.openMenu)

        self.collapsed.connect(self.showSummary)
        self.expanded.connect(self.removeSummary)

        self.shortcut = QShortcut(QKeySequence("Del"), self)
        self.shortcut.activated.connect(self.del_action)

        self.updateSummary()

        # define shortcuts
        self.menu = QtWidgets.QMenu()
        self.sub_menu = QtWidgets.QMenu("Insert Action")
        self.menu.addMenu(self.sub_menu)
        actions = NRActions.actions
        for name in actions:
            shortcut = "Ctrl+" + name[0].lower()
            action = self.sub_menu.addAction(name)
            #action.setShortcut(QtGui.QKeySequence(shortcut))
            short = QtWidgets.QShortcut(QtGui.QKeySequence(shortcut), self)
            short.activated.connect(partial(self.menu_action, action))
            action.triggered.connect(partial(self.menu_action, action))
Ejemplo n.º 21
0
    def setupUI(self):
        # setting window
        self.showMaximized()
        self.setMouseTracking(True)

        scroll = QScrollArea(self)
        centWidget = QWidget(self)
        paintWidget = PaintWidget(self, self)

        # setup layout with image on  the center
        vbox = QHBoxLayout()
        vbox.addStretch(1)

        if self.defaultPix:
            paintWidget.setFixedSize(self.defaultPix.size())
        else:
            paintWidget.setFixedSize(self.size())

        vbox.addWidget(paintWidget)
        vbox.addStretch(1)

        centWidget.setLayout(vbox)
        scroll.setWidget(paintWidget)

        self.setCentralWidget(scroll)
        self.setWindowTitle('Paint')

        # create menu
        menu = self.menuBar()
        fileMenu = menu.addMenu('File')

        commandsGroup = QActionGroup(self)

        self.saveAction = QAction('Save', self)
        self.saveAction.setShortcut('Ctrl+S')
        fileMenu.addAction(self.saveAction)

        self.saveBufferAction = QAction('Save to buffer', self)
        self.saveBufferAction.setShortcut('Ctrl+Shift+S')
        fileMenu.addAction(self.saveBufferAction)

        self.saveServerAction = QAction('Save on server', self)
        self.saveServerAction.setShortcut('Ctrl+Alt+S')
        fileMenu.addAction(self.saveServerAction)

        self.clearAction = QAction('Clear', self)
        self.clearAction.setShortcut('Ctrl+F')
        fileMenu.addAction(self.clearAction)

        self.unExecuteAction = QAction('Unexecute', self)
        self.unExecuteAction.setShortcut('Ctrl+Z')
        fileMenu.addAction(self.unExecuteAction)

        self.quitAction = QAction('Quit', self)
        self.quitAction.setShortcut('Ctrl+Q')
        fileMenu.addAction(self.quitAction)

        self.LineAction = QAction('Line', self)
        self.LineAction.setIcon(QIcon('./Images/line.png'))
        self.LineAction.setCheckable(True)
        self.LineAction.setChecked(True)
        commandsGroup.addAction(self.LineAction)

        self.RectAction = QAction('Rect', self)
        self.RectAction.setIcon(QIcon('./Images/rect.png'))
        self.RectAction.setCheckable(True)
        commandsGroup.addAction(self.RectAction)

        self.CircleAction = QAction('Ellipse', self)
        self.CircleAction.setIcon(QIcon('./Images/ellipse.png'))
        self.CircleAction.setCheckable(True)
        commandsGroup.addAction(self.CircleAction)

        self.ArrowAction = QAction('Arrow', self)
        self.ArrowAction.setCheckable(True)
        self.ArrowAction.setIcon(QIcon('./Images/arrow.png'))
        commandsGroup.addAction(self.ArrowAction)

        self.PenAction = QAction('Pen', self)
        self.PenAction.setIcon(QIcon('./Images/poly.png'))
        self.PenAction.setCheckable(True)
        commandsGroup.addAction(self.PenAction)

        self.PencilAction = QAction('Pencil', self)
        self.PencilAction.setCheckable(True)
        self.PencilAction.setIcon(QIcon('./Images/pencil.png'))
        commandsGroup.addAction(self.PencilAction)

        self.ImageAction = QAction('Image', self)
        self.ImageAction.setCheckable(True)
        self.ImageAction.setIcon(QIcon('./Images/image.png'))
        commandsGroup.addAction(self.ImageAction)

        self.TextAction = QAction('Text', self)
        self.TextAction.setCheckable(True)
        self.TextAction.setIcon(QIcon('./Images/text.png'))
        commandsGroup.addAction(self.TextAction)

        self.EditAction = QAction('Edit', self)
        self.EditAction.setCheckable(True)
        self.EditAction.setIcon(QIcon('./Images/move.png'))
        commandsGroup.addAction(self.EditAction)

        self.deleteAction = QAction('Delete', self)
        self.deleteAction.setDisabled(True)
        self.deleteAction.setShortcut('Delete')

        self.copyAction = QAction('Copy', self)
        self.copyAction.setDisabled(True)
        self.copyAction.setShortcut(QKeySequence('Ctrl+C'))

        self.pasteAction = QAction('Paste', self)
        self.pasteAction.setShortcut(QKeySequence('Ctrl+V'))

        menu.addAction(self.deleteAction)
        menu.addAction(self.copyAction)
        menu.addAction(self.pasteAction)

        self.commandsToolbar = QToolBar('Commands')
        self.commandsToolbar.setMovable(False)
        self.commandsToolbar.addActions(commandsGroup.actions())

        self.setToolbar(NoneToolbar('Context'))
        self.contextToolbar.setMovable(False)
        self.contextToolbar.destroy()

        self.addToolBar(Qt.LeftToolBarArea, self.commandsToolbar)
        self.addToolBar(Qt.TopToolBarArea, self.contextToolbar)
Ejemplo n.º 22
0
    def __init__(self, cue_model, **kwargs):
        super().__init__(cue_model=cue_model, **kwargs)
        self.setLayout(QGridLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)

        self._model_adapter = CueListModel(self._cue_model)
        self._model_adapter.item_added.connect(self.__cue_added)
        self._model_adapter.item_removed.connect(self.__cue_removed)

        self._playing_model = RunningCueModel(self._cue_model)
        self._context_item = None
        self._next_cue_index = 0

        self._show_dbmeter = config['ListLayout'].getboolean('ShowDbMeters')
        self._seek_visible = config['ListLayout'].getboolean('ShowSeek')
        self._accurate_time = config['ListLayout'].getboolean('ShowAccurate')
        self._auto_continue = config['ListLayout'].getboolean('AutoContinue')
        self._show_playing = config['ListLayout'].getboolean('ShowPlaying')
        self._go_key = config['ListLayout']['GoKey']
        self._go_key_sequence = QKeySequence(self._go_key,
                                             QKeySequence.NativeText)

        try:
            self._end_list = EndListBehavior(config['ListLayout']['EndList'])
        except ValueError:
            self._end_list = EndListBehavior.Stop

        # Add layout-specific menus
        self.showPlayingAction = QAction(self)
        self.showPlayingAction.setCheckable(True)
        self.showPlayingAction.setChecked(self._show_playing)
        self.showPlayingAction.triggered.connect(self.set_playing_visible)

        self.showDbMeterAction = QAction(self)
        self.showDbMeterAction.setCheckable(True)
        self.showDbMeterAction.setChecked(self._show_dbmeter)
        self.showDbMeterAction.triggered.connect(self.set_dbmeter_visible)

        self.showSeekAction = QAction(self)
        self.showSeekAction.setCheckable(True)
        self.showSeekAction.setChecked(self._seek_visible)
        self.showSeekAction.triggered.connect(self.set_seek_visible)

        self.accurateTimingAction = QAction(self)
        self.accurateTimingAction.setCheckable(True)
        self.accurateTimingAction.setChecked(self._accurate_time)
        self.accurateTimingAction.triggered.connect(self.set_accurate_time)

        self.autoNextAction = QAction(self)
        self.autoNextAction.setCheckable(True)
        self.autoNextAction.setChecked(self._auto_continue)
        self.autoNextAction.triggered.connect(self.set_auto_next)

        MainWindow().menuLayout.addAction(self.showPlayingAction)
        MainWindow().menuLayout.addAction(self.showDbMeterAction)
        MainWindow().menuLayout.addAction(self.showSeekAction)
        MainWindow().menuLayout.addAction(self.accurateTimingAction)
        MainWindow().menuLayout.addAction(self.autoNextAction)

        # GO-BUTTON (top-left)
        self.goButton = QPushButton('GO', self)
        self.goButton.setFocusPolicy(Qt.NoFocus)
        self.goButton.setFixedWidth(120)
        self.goButton.setFixedHeight(100)
        self.goButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.goButton.setStyleSheet('font-size: 48pt;')
        self.goButton.clicked.connect(self.__go_slot)
        self.layout().addWidget(self.goButton, 0, 0)

        # INFO PANEL (top center)
        self.infoPanel = InfoPanel()
        self.infoPanel.setFixedHeight(100)
        self.layout().addWidget(self.infoPanel, 0, 1)

        # CONTROL-BUTTONS (top-right)
        self.controlButtons = ShowControlButtons(parent=self)
        self.controlButtons.setFixedHeight(100)
        self.controlButtons.stopButton.clicked.connect(self.stop_all)
        self.controlButtons.pauseButton.clicked.connect(self.pause_all)
        self.controlButtons.fadeInButton.clicked.connect(self.fadein_all)
        self.controlButtons.fadeOutButton.clicked.connect(self.fadeout_all)
        self.controlButtons.restartButton.clicked.connect(self.restart_all)
        self.controlButtons.interruptButton.clicked.connect(self.interrupt_all)
        self.layout().addWidget(self.controlButtons, 0, 2)

        # CUE VIEW (center left)
        self.listView = CueListView(self._model_adapter, self)
        self.listView.itemDoubleClicked.connect(self.double_clicked)
        self.listView.currentItemChanged.connect(self.__current_changed)
        self.listView.context_event.connect(self.context_event)
        self.listView.key_event.connect(self.onKeyPressEvent)
        self.listView.select_cue_event.connect(self.select_event)
        self.layout().addWidget(self.listView, 1, 0, 1, 2)

        # PLAYING VIEW (center right)
        self.playView = RunningCuesListWidget(self._playing_model, parent=self)
        self.playView.dbmeter_visible = self._show_dbmeter
        self.playView.accurate_time = self._accurate_time
        self.playView.seek_visible = self._seek_visible
        self.playView.setMinimumWidth(300)
        self.playView.setMaximumWidth(300)
        self.layout().addWidget(self.playView, 1, 2)

        self.set_playing_visible(self._show_playing)

        # TODO: maybe can be moved outside the layout
        # Add cue preferences widgets
        CueSettingsRegistry().add_item(CueGeneralSettings, Cue)
        CueSettingsRegistry().add_item(MediaCueSettings, MediaCue)
        CueSettingsRegistry().add_item(Appearance)

        # Context menu actions
        self.edit_action = QAction(self)
        self.edit_action.triggered.connect(self.edit_context_cue)

        self.remove_action = QAction(self)
        self.remove_action.triggered.connect(self.remove_context_cue)

        self.select_action = QAction(self)
        self.select_action.triggered.connect(self.select_context_cue)

        self.cm_registry.add_item(self.edit_action)
        self.sep1 = self.cm_registry.add_separator()
        self.cm_registry.add_item(self.remove_action)
        self.cm_registry.add_item(self.select_action)

        self.retranslateUi()
Ejemplo n.º 23
0
    def welcome_dialog(self):
        """
        Show a modal welcome dialog for OASYS.

        Reimplemented from `CanvasMainWindow`.
        """

        dialog = welcomedialog.WelcomeDialog(self)
        dialog.setWindowTitle(self.tr("Welcome to OASYS"))

        def new_scheme():
            if self.new_scheme() == QDialog.Accepted:
                dialog.accept()

        def open_scheme():
            if self.open_scheme() == QDialog.Accepted:
                dialog.accept()

        def open_recent():
            if self.recent_scheme() == QDialog.Accepted:
                dialog.accept()

        def tutorial():
            import webbrowser
            webbrowser.open("https://github.com/srio/ShadowOui-Tutorial")
            #if self.tutorial_scheme() == QDialog.Accepted:
            #    dialog.accept()

        new_action = \
            QAction(self.tr("New"), dialog,
                    toolTip=self.tr("Open a new workflow."),
                    triggered=new_scheme,
                    shortcut=QKeySequence.New,
                    icon=canvasmain.canvas_icons("New.svg")
                    )

        open_action = \
            QAction(self.tr("Open"), dialog,
                    objectName="welcome-action-open",
                    toolTip=self.tr("Open a workflow."),
                    triggered=open_scheme,
                    shortcut=QKeySequence.Open,
                    icon=canvasmain.canvas_icons("Open.svg")
                    )

        recent_action = \
            QAction(self.tr("Recent"), dialog,
                    objectName="welcome-recent-action",
                    toolTip=self.tr("Browse and open a recent workflow."),
                    triggered=open_recent,
                    shortcut=QKeySequence(Qt.ControlModifier | \
                                          (Qt.ShiftModifier | Qt.Key_R)),
                    icon=canvasmain.canvas_icons("Recent.svg")
                    )

        tutorials_action = \
            QAction(self.tr("Tutorial"), dialog,
                    objectName="welcome-tutorial-action",
                    toolTip=self.tr("Browse tutorial workflows."),
                    triggered=tutorial,
                    icon=canvasmain.canvas_icons("Tutorials.svg")
                    )

        icon = resource_path("icons/Install.svg")

        addons_action = \
            QAction(self.tr("Add-ons"), dialog,
                    objectName="welcome-addons-action",
                    toolTip=self.tr("Install add-ons"),
                    triggered=self.open_addons,
                    icon=QIcon(icon),
                    )

        if self.__updatable:
            addons_action.setText("Update Now")
            addons_action.setToolTip("Update or install new add-ons")
            addons_action.setIcon(QIcon(resource_path("icons/Update.svg")))

            mbox = QMessageBox(
                dialog,
                icon=QMessageBox.Information,
                text="{} add-on{} {} a newer version.\n"
                "Would you like to update now?".format(
                    "One" if self.__updatable == 1 else self.__updatable,
                    "s" if self.__updatable > 1 else "",
                    "has" if self.__updatable == 1 else "have"),
                standardButtons=QMessageBox.Ok | QMessageBox.No,
            )
            mbox.setWindowFlags(Qt.Sheet | Qt.MSWindowsFixedSizeDialogHint)
            mbox.setModal(True)
            dialog.show()
            mbox.show()
            mbox.finished.connect(lambda r: self.open_addons()
                                  if r == QMessageBox.Ok else None)

        bottom_row = [
            self.get_started_action, tutorials_action,
            self.documentation_action, addons_action
        ]

        self.new_action.triggered.connect(dialog.accept)
        top_row = [new_action, open_action, recent_action]

        dialog.addRow(top_row, background="light-grass")
        dialog.addRow(bottom_row, background="light-orange")

        # Find and hide the welcome dialogs bottom bar. It contains the
        # Show at startup" check box and we ALWAYS want the Welcome Dialog
        # to show.
        bottombar = dialog.findChild(QWidget, name='bottom-bar')
        if bottombar is not None:
            bottombar.hide()

        status = dialog.exec_()

        dialog.deleteLater()

        return status
Ejemplo n.º 24
0
 def slotClearShortcut(self):
     if len(self.m_keySequence) <= 0:
         return
     self.setKeySequence(QKeySequence())
     self.keySequenceChangedSignal.emit(self.m_keySequence)
Ejemplo n.º 25
0
 def init_interface(self):
     self.setAttribute(QtCore.Qt.WA_DeleteOnClose)
     self.setWindowTitle("Pystripe illumination correction")
     self.file_menu = QMenu("&File", self)
     self.file_menu.addAction("&Save", self.fileSave)
     self.save_shortcut = QShortcut(QKeySequence("Ctrl+S"), self)
     self.save_shortcut.activated.connect(self.fileSave)
     self.file_menu.addAction("&Quit", self.fileQuit,
                              QtCore.Qt.CTRL + QtCore.Qt.Key_Q)
     self.menuBar().addMenu(self.file_menu)
     self.main_widget = QWidget(self)
     #
     # The layout:
     #  |---------------------------splitter--------------|
     #  | ---------- vbox ------------ |                  |
     #  | |  Z: z-chooser & dark     | |                  |
     #  | | ---------grid----------- | |                  |
     #  | | | 1, 1    |    2, 1    | | |   canvas         |
     #  | | ---------- ------------- | |                  |
     #  | | | 1, 2    |    2, 2    | | |                  |
     #  | | ------------------------ | |                  |
     #  |------------------------------|------------------|
     imgdir = list(self.image_directories.values())[0]
     stackfiles = list(imgdir.values())[0]
     x = get_x_coords(imgdir)
     y = get_y_coords(imgdir)
     splitter = QSplitter(QtCore.Qt.Horizontal)
     top_layout = QHBoxLayout()
     top_layout.addWidget(splitter)
     self.main_widget.setLayout(top_layout)
     vwidget = QWidget()
     vbox = QVBoxLayout(self.main_widget)
     vwidget.setLayout(vbox)
     splitter.addWidget(vwidget)
     zchooser_group_box = QGroupBox("Z plane to display / Dark field value")
     vbox.addWidget(zchooser_group_box)
     chooser_layout = QHBoxLayout()
     zchooser_group_box.setLayout(chooser_layout)
     grid_group_box = QGroupBox("Y offsets and flat files")
     vbox.addWidget(grid_group_box)
     grid = QGridLayout()
     grid.setColumnStretch(1, len(x))
     grid.setColumnStretch(2, len(y))
     grid_group_box.setLayout(grid)
     #
     # -- the Z chooser --
     #
     choices = [_.split(".")[0] for _ in stackfiles]
     if len(choices) > 40:
         # Limit to 20 or so Z
         spacing = len(choices) // 20
         choices = choices[::spacing]
     z_chooser_label = QLabel("Z:")
     chooser_layout.addWidget(z_chooser_label)
     self.z_chooser = QComboBox()
     chooser_layout.addWidget(self.z_chooser)
     for choice in choices:
         self.z_chooser.addItem(os.path.split(choice)[-1])
     self.z_chooser.currentTextChanged.connect(self.onZChange)
     dark_label = QLabel("Dark")
     chooser_layout.addWidget(dark_label)
     self.dark_input = QLineEdit()
     self.dark_input.setText("100")
     chooser_layout.addWidget(self.dark_input)
     self.dark_slider = QSlider(QtCore.Qt.Horizontal)
     self.dark_slider.setMinimum(0)
     self.dark_slider.setMaximum(250)
     self.dark_slider.setValue(100)
     chooser_layout.addWidget(self.dark_slider)
     self.hookSliderAndInput(self.dark_slider, self.dark_input)
     #
     # --- the grid of controls ---
     #
     self.stack_label = {}
     self.stack_flat_file_widget = {}
     self.stack_y_offset_box_widget = {}
     self.stack_y_offset_slider_widget = {}
     for xi in range(len(x)):
         for yi in range(len(y)):
             key = (x[xi], y[yi])
             if key not in imgdir:
                 continue # skip non-existent directory
             stack_group = QGroupBox("%d,%d" % key)
             grid.addWidget(stack_group, yi, xi)
             stack_layout = QVBoxLayout()
             stack_group.setLayout(stack_layout)
             y_layout = QHBoxLayout()
             stack_layout.addLayout(y_layout)
             self.stack_label[key] = QLabel("Y:")
             y_layout.addWidget(self.stack_label[key])
             y_input = QLineEdit()
             y_layout.addWidget(y_input)
             y_input.setText("0")
             y_slider = QSlider(QtCore.Qt.Horizontal)
             y_layout.addWidget(y_slider)
             y_slider.setMinimum(-200)
             y_slider.setMaximum(200)
             self.hookSliderAndInput(y_slider, y_input)
             self.stack_y_offset_box_widget[key] = y_input
             self.stack_y_offset_slider_widget[key] = y_slider
             flat_choices = QComboBox()
             self.stack_flat_file_widget[key] = flat_choices
             stack_layout.addWidget(flat_choices)
             for choice in self.flat_files:
                 filename = os.path.split(choice)[1]
                 flat_choices.addItem(filename)
             flat_choices.currentTextChanged.connect(self.updateDisplay)
     #
     # The display box
     #
     self.canvas = MPLCanvas(self.main_widget)
     self.addToolBar(NavigationToolbar(self.canvas, self))
     splitter.addWidget(self.canvas)
     #
     # Set up main window
     #
     self.main_widget.setFocus()
     self.setCentralWidget(self.main_widget)
     self.onZChange()
Ejemplo n.º 26
0
 def save_shortcut(self):
     self.hide()
     shortcut = QKeySequence(self.line_edit.text())
     self.emit(SIGNAL('shortcutChanged'), shortcut)
Ejemplo n.º 27
0
class QtKeySequenceEdit(QWidget):
    keySequenceChangedSignal = pyqtSignal(QKeySequence)
    def __init__(self,parent=None):
        super(QtKeySequenceEdit, self).__init__(parent)

        self.m_keySequence = QKeySequence()
        self.m_num = 0
        self.m_lineEdit = QLineEdit(self)
        layout = QHBoxLayout(self)
        layout.addWidget(self.m_lineEdit)
        layout.setContentsMargins(0, 0, 0, 0)
        self.m_lineEdit.installEventFilter(self)
        self.m_lineEdit.setReadOnly(True)
        self.m_lineEdit.setFocusProxy(self)
        self.setFocusPolicy(self.m_lineEdit.focusPolicy())
        self.setAttribute(Qt.WA_InputMethodEnabled)

    def eventFilter(self, o, e):
        if o == self.m_lineEdit and e.type() == QEvent.ContextMenu:
            c = e
            menu = self.m_lineEdit.createStandardContextMenu()
            actions = menu.actions()
            for action in actions:
                action.setShortcut(QKeySequence())
                actionString = action.text()
                pos = actionString.rfind('\t')
                if (pos > 0):
                    actionString = actionString[:pos]
                action.setText(actionString)

            actionBefore = None
            if (len(actions) > 0):
                actionBefore = actions[0]
            clearAction = QAction(self.tr("Clear Shortcut"), menu)
            menu.insertAction(actionBefore, clearAction)
            menu.insertSeparator(actionBefore)
            clearAction.setEnabled(not len(self.m_keySequence)<=0)
            clearAction.triggered.connect(self.slotClearShortcut)
            menu.exec(c.globalPos())
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).eventFilter(o, e)

    def slotClearShortcut(self):
        if len(self.m_keySequence) <= 0:
            return
        self.setKeySequence(QKeySequence())
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def handleKeyEvent(self, e):
        nextKey = e.key()
        if (nextKey == Qt.Key_Control or nextKey == Qt.Key_Shift or
                nextKey == Qt.Key_Meta or nextKey == Qt.Key_Alt or
                nextKey == Qt.Key_Super_L or nextKey == Qt.Key_AltGr):
            return

        nextKey |= self.translateModifiers(e.modifiers(), e.text())
        k0 = 0
        k1 = 0
        k2 = 0
        k3 = 0
        l = len(self.m_keySequence)
        if l==1:
            k0 = self.m_keySequence[0]
        elif l==2:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
        elif l==3:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
        elif l==4:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
            k3 = self.m_keySequence[3]
        if self.m_num==0:
            k0 = nextKey
            k1 = 0
            k2 = 0
            k3 = 0
        elif self.m_num==1:
            k1 = nextKey
            k2 = 0
            k3 = 0
        elif self.m_num==2:
            k2 = nextKey
            k3 = 0
        elif self.m_num==3:
            k3 = nextKey
        else:
            pass

        self.m_num += 1
        if (self.m_num > 3):
            self.m_num = 0
        self.m_keySequence = QKeySequence(k0, k1, k2, k3)
        self.m_lineEdit.setText(self.m_keySequence.toString(QKeySequence.NativeText))
        e.accept()
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def setKeySequence(self, sequence):
        if (sequence == self.m_keySequence):
            return
        self.m_num = 0
        self.m_keySequence = sequence
        self.m_lineEdit.setText(self.m_keySequence.toString(QKeySequence.NativeText))

    def keySequence(self):
        return self.m_keySequence

    def translateModifiers(self, state, text):
        result = 0
        if ((state & Qt.ShiftModifier) and (len(text) == 0 or not text[0].isprintable() or text[0].isalpha() or text[0].isspace())):
            result |= Qt.SHIFT
        if (state & Qt.ControlModifier):
            result |= Qt.CTRL
        if (state & Qt.MetaModifier):
            result |= Qt.META
        if (state & Qt.AltModifier):
            result |= Qt.ALT
        return result

    def focusInEvent(self, e):
        self.m_lineEdit.event(e)
        self.m_lineEdit.selectAll()
        super(QtKeySequenceEdit, self).focusInEvent(e)

    def focusOutEvent(self, e):
        self.m_num = 0
        self.m_lineEdit.event(e)
        super(QtKeySequenceEdit, self).focusOutEvent(e)

    def keyPressEvent(self, e):
        self.handleKeyEvent(e)
        e.accept()

    def keyReleaseEvent(self, e):
        self.m_lineEdit.event(e)

    def paintEvent(self, ptQPaintEvent):
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self)

    def event(self,e):
        if (e.type() == QEvent.Shortcut or
                e.type() == QEvent.ShortcutOverride  or
                e.type() == QEvent.KeyRelease):
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).event(e)
Ejemplo n.º 28
0
    def retranslateUi(self, Form):
        _translate = QtCore.QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "Q-Stream Player"))
        self.Player_name.setText(_translate("Form", "Q-Stream Player"))
        self.time_status.setText(_translate("Form", "00:00:00"))
        self.backslash.setText(_translate("Form", "/"))
        self.duration_status.setText(_translate("Form", "00:00:00"))
        # self.enter_url_label.setText(_translate("Form", statusList[4]))

        # Set intial Volume
        self.volumeslider.setRange(0, 100)
        self.volumeslider.setValue(75)
        self.mediaPlayer.setVolume(75)
        self.position_slider.setRange(0, 100)

        # connecting buttons
        self.miniplayer_button.clicked.connect(self.setupMiniPlayer)
        self.position_slider.sliderMoved.connect(self.setPosition)
        self.position_slider.sliderMoved.connect(self.handleLabel)
        self.volume_button.clicked.connect(self.mute)
        self.volumeslider.valueChanged.connect(self.setVolume)
        self.screenshot_button.clicked.connect(self.screenshot)
        self.playback_button.clicked.connect(self.stopplayback)
        self.always_on_top_button.clicked.connect(self.checkOnTop)
        self.play_button.clicked.connect(self.play)
        self.open_File_button.clicked.connect(self.openFile)
        # self.video_setting_button.clicked.connect(self.handleQuality)
        self.setting_button.clicked.connect(self.handleSetting)
        self.Quality_box.currentTextChanged.connect(self.handleQuality)
        self.cross_button.clicked.connect(self.exit)
        self.maximize_button.clicked.connect(self.max)
        self.minimize_button.clicked.connect(self.min)

        # Shortcuts
        shortcut = QShortcut(QKeySequence('Esc'), self.video_playback)
        shortcut.activated.connect(self.EscFun)
        shortcut = QShortcut(QKeySequence('Space'), self.video_playback)
        shortcut.activated.connect(self.play)
        shortcut = QShortcut(QKeySequence('f'), self.video_playback)
        shortcut.activated.connect(self.fullscreen_video)
        shortcut = QShortcut(QKeySequence('c'), self.video_playback)
        shortcut.activated.connect(self.setupMiniPlayer)
        shortcut = QShortcut(QKeySequence('o'), self.video_playback)
        shortcut.activated.connect(self.openFile)
        shortcut = QShortcut(QKeySequence('a'), self.video_playback)
        shortcut.activated.connect(self.checkOnTop)
        shortcut = QShortcut(QKeySequence("Return"), self.video_playback)
        shortcut.activated.connect(self.playOnline)
        shortcut = QShortcut(QKeySequence('m'), self.video_playback)
        shortcut.activated.connect(self.mute)
        shortcut = QShortcut(QKeySequence(Qt.Key_Right), self.video_playback)
        shortcut.activated.connect(self.forwardSlider)
        shortcut = QShortcut(QKeySequence(Qt.Key_Left), self.video_playback)
        shortcut.activated.connect(self.backSlider)
        self.volupshortcut = QShortcut(QKeySequence(Qt.Key_Up),
                                       self.video_playback)
        self.volupshortcut.activated.connect(self.volumeUp)
        self.voldownshortcut = QShortcut(QKeySequence(Qt.Key_Down),
                                         self.video_playback)
        self.voldownshortcut.activated.connect(self.volumeDown)
        shortcut = QShortcut(QKeySequence(Qt.ControlModifier + Qt.Key_Right),
                             self.video_playback)
        shortcut.activated.connect(self.forwardSlider10)
        shortcut = QShortcut(QKeySequence(Qt.ControlModifier + Qt.Key_Left),
                             self.video_playback)
        shortcut.activated.connect(self.backSlider10)
        shortcut = QShortcut(QKeySequence(Qt.AltModifier + Qt.Key_Left),
                             self.video_playback)
        shortcut.activated.connect(self.backSlider5)
        shortcut = QShortcut(QKeySequence(Qt.AltModifier + Qt.Key_Right),
                             self.video_playback)
        shortcut.activated.connect(self.forwardSlider5)

        # loading history to Url Box
        items = self.load()
        self.url_box.addItems(items)
        self.url_box.setCurrentIndex(-1)

        # icon size
        # iconSize = QSize(5,5)
        # self.play_button.setIconSize(iconSize)
        # self.playback_button.setIconSize(iconSize)
        # self.screenshot_button.setIconSize(iconSize)
        # self.always_on_top_button.setIconSize(iconSize)
        # self.miniplayer_button.setIconSize(iconSize)
        # self.setting_button.setIconSize(iconSize)
        # self.volume_button.setIconSize(iconSize)

        # button size
        btnSize = QSize(22, 22)
        self.play_button.setMaximumSize(btnSize)
        self.playback_button.setMaximumSize(btnSize)
        self.screenshot_button.setMaximumSize(btnSize)
        self.always_on_top_button.setMaximumSize(btnSize)
        self.miniplayer_button.setMaximumSize(btnSize)
        # self.video_setting_button.setMaximumSize(btnSize)
        self.setting_button.setMaximumSize(btnSize)
        self.volume_button.setMaximumSize(btnSize)

        # set margin
        self.horizontalLayout.setContentsMargins(10, 5, 9, 0)
        self.horizontalLayout_4.setContentsMargins(9, 0, 9, 0)
        self.horizontalLayout_4.setSpacing(4)
        self.horizontalLayout_5.setContentsMargins(0, 5, 5, 5)
        self.horizontalLayout_6.setContentsMargins(9, 0, 9, 0)

        # Media player settings
        self.mediaPlayer.setVideoOutput(self.video_playback)
        self.mediaPlayer.stateChanged.connect(self.mediaStateChanged)
        self.mediaPlayer.positionChanged.connect(self.positionChanged)
        self.mediaPlayer.positionChanged.connect(self.handleLabel)
        self.mediaPlayer.durationChanged.connect(self.durationChanged)
Ejemplo n.º 29
0
 def setKey(self, key_string):
     self.key_string = key_string
     qkeyseq = QKeySequence(key_string, QKeySequence.PortableText)
     native_key_string = qkeyseq.toString(format=QKeySequence.NativeText)
     self.setText(native_key_string)
Ejemplo n.º 30
0
    def _menubar(self):
        """Set up the menu bar."""
        menubar = self.menuBar()

        # applications menu
        menu_appl = menubar.addMenu('&Aplicación')

        icon = self.style().standardIcon(QStyle.SP_BrowserReload)
        action_reload = QAction(icon, '&Refrescar', self)
        action_reload.setShortcut('Ctrl+R')
        action_reload.setToolTip('Recarga la lista de programas')
        action_reload.triggered.connect(self.refresh_episodes)
        menu_appl.addAction(action_reload)

        icon = self.style().standardIcon(QStyle.SP_FileDialogDetailedView)
        action_preferences = QAction(icon, '&Preferencias', self)
        action_preferences.triggered.connect(self.open_preferences)
        action_preferences.setToolTip(
            'Configurar distintos parámetros del programa')
        menu_appl.addAction(action_preferences)

        menu_appl.addSeparator()

        icon = self.style().standardIcon(QStyle.SP_MessageBoxInformation)
        _act = QAction(icon, '&Acerca de', self)
        _act.triggered.connect(self.open_about_dialog)
        _act.setToolTip('Muestra información de la aplicación')
        menu_appl.addAction(_act)

        icon = self.style().standardIcon(QStyle.SP_DialogCloseButton)
        _act = QAction(icon, '&Salir', self)
        _act.setShortcut('Ctrl+Q')
        _act.setToolTip('Sale de la aplicación')
        _act.triggered.connect(self.on_close)
        menu_appl.addAction(_act)

        # program menu
        menu_prog = menubar.addMenu('&Programa')

        icon = self.style().standardIcon(QStyle.SP_ArrowDown)
        self.action_download = QAction(icon, '&Descargar', self)
        self.action_download.setShortcut('Ctrl+D')
        self.action_download.setEnabled(False)
        self.action_download.setToolTip(TTIP_DOWNLOAD_D)
        self.action_download.triggered.connect(self.download_episode)
        menu_prog.addAction(self.action_download)

        icon = self.style().standardIcon(QStyle.SP_MediaPlay)
        self.action_play = QAction(icon, '&Reproducir', self)
        self.action_play.setEnabled(False)
        self.action_play.setToolTip(TTIP_PLAY_D)
        self.action_play.triggered.connect(self.on_play_action)
        menu_prog.addAction(self.action_play)

        # toolbar for buttons and filters
        toolbar = self.addToolBar('main')
        toolbar.layout().setSpacing(10)

        # basic buttons
        toolbar.addAction(self.action_download)
        toolbar.addAction(self.action_play)
        toolbar.addSeparator()
        toolbar.addAction(action_reload)
        toolbar.addAction(action_preferences)

        # spacer to move all filters to the right
        spacer = QWidget()
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        toolbar.addWidget(spacer)

        # channel selection combobox
        toolbar.addWidget(QLabel("Canal: "))
        self.filter_chan = QComboBox()
        for c in self.episode_channels:
            self.filter_chan.addItem(c)
        self.filter_chan.activated.connect(self.on_filter_changed)
        toolbar.addWidget(self.filter_chan)

        # filter text and button
        toolbar.addWidget(QLabel("Filtro: "))
        self.filter_line = QLineEdit()
        self.filter_line.setMaximumWidth(150)
        self.filter_line.textChanged.connect(self.on_filter_changed)
        toolbar.addWidget(self.filter_line)
        self.filter_cbox = QCheckBox("Sólo descargados")
        self.filter_cbox.stateChanged.connect(self.on_filter_changed)
        toolbar.addWidget(self.filter_cbox)
        QShortcut(QKeySequence("Ctrl+F"), self, self.filter_line.setFocus)

        # if needed, a warning that stuff needs to be configured
        icon = self.style().standardIcon(QStyle.SP_MessageBoxWarning)
        m = "Necesita configurar algo; haga click aquí para abrir el wizard"
        self.needsomething_alert = QAction(icon, m, self)
        self.needsomething_alert.triggered.connect(self._start_wizard)
        toolbar.addAction(self.needsomething_alert)
        if not config.get('nowizard'):
            self._start_wizard()
        self._review_need_something_indicator()
Ejemplo n.º 31
0
 def checkKeySequenceEqual(self, modifier, key, targetKeySequence):
     return QKeySequence(modifier + key) == QKeySequence(targetKeySequence)
Ejemplo n.º 32
0
 def createAct(self):
     ###########################
     # create act
     ###########################
     self.openAct = QAction(QIcon('icons\\open.png'), '打开', self)
     self.openAct.setShortcut('Ctrl+O')
     self.openAct.setStatusTip('Open Document')
     self.openAct.triggered.connect(self.act_open)
     ## exit
     self.exitAct = QAction(QIcon('icons\\close_.png'), '终了', self)
     self.exitAct.setShortcut('Ctrl+Q')
     self.exitAct.setStatusTip('Exit application')
     self.exitAct.triggered.connect(self.close)
     ## exit
     self.saveAct = QAction(QIcon('icons\\save.png'), '保存', self)
     self.saveAct.setShortcut('Ctrl+S')
     self.saveAct.setStatusTip('Save Document')
     self.saveAct.triggered.connect(self.act_save)
     ## select
     self.selectAct = QAction(QIcon('icons\\select.png'), '选择', self)
     self.selectAct.setShortcut('Ctrl+E')
     self.selectAct.setStatusTip('Select Project Member')
     self.selectAct.triggered.connect(self.act_select)
     ## delete
     self.deleteAct = QAction(QIcon('icons\\delete.png'), '选择', self)
     self.deleteAct.setShortcut('Ctrl+D')
     self.deleteAct.setStatusTip('Delete Document')
     self.deleteAct.triggered.connect(self.act_delete)
     ## extract
     self.extractAct = QAction(QIcon('icons\\extract.png'), '提取', self)
     self.extractAct.setShortcut(QKeySequence('Ctrl+Shit+E'))
     self.extractAct.setStatusTip('Extract Format Pages')
     self.extractAct.triggered.connect(self.act_extract)
     ## split
     self.splitAct = QAction(QIcon('icons\\split.png'), '分离', self)
     self.splitAct.setShortcut('Ctrl+Shit+S')
     self.splitAct.setStatusTip('Split Document')
     self.splitAct.triggered.connect(self.act_split)
     ## fill
     self.fillAct = QAction(QIcon('icons\\fillin.png'), '填写', self)
     self.fillAct.setShortcut('Ctrl+Shit+F')
     self.fillAct.setStatusTip('Fill in Blank')
     self.fillAct.triggered.connect(self.act_fillin)
     ## auto
     self.autoAct = QAction(QIcon('icons\\auto.png'), '完全自动', self)
     self.autoAct.setShortcut('Ctrl+Shit+A')
     self.autoAct.setStatusTip('Do Automatically')
     self.autoAct.triggered.connect(self.act_auto)
     ## merge
     self.mergeAct = QAction(QIcon('icons\\merge.png'), '合并', self)
     self.mergeAct.setShortcut('Ctrl+Shit+M')
     self.mergeAct.setStatusTip('Merge Documents')
     self.mergeAct.triggered.connect(self.act_merge)
     ## check
     self.todocxAct = QAction(QIcon('icons\\doc.png'), '检查', self)
     self.todocxAct.setShortcut('Ctrl+Shit+')
     self.todocxAct.setStatusTip('Check Document')
     self.todocxAct.triggered.connect(self.act_2docx)
     ## 2xml
     self.toxmlAct = QAction(QIcon('icons\\xml.png'), '变换到XML', self)
     self.toxmlAct.setShortcut('Ctrl+Shit+X')
     self.toxmlAct.setStatusTip('Convert Docx to Xml')
     self.toxmlAct.triggered.connect(self.act_2xml)
     ## 2html
     self.tohtmlAct = QAction(QIcon('icons\\html.png'), '变换到HTML', self)
     self.tohtmlAct.setShortcut('Ctrl+Shit+H')
     self.tohtmlAct.setStatusTip('Convert docx to HTML')
     self.tohtmlAct.triggered.connect(self.act_2html)
     ## setting
     self.settingAct = QAction(QIcon('icons\\setting_.png'), '设置', self)
     self.settingAct.setShortcut('Ctrl+Shit+T')
     self.settingAct.setStatusTip('Setting')
     self.settingAct.triggered.connect(self.act_setting)
     ## help
     self.aboutAct = QAction(QIcon('icons\\help.png'), '关于', self)
     self.aboutAct.setShortcut('Ctrl+H')
     self.aboutAct.setStatusTip('About Program')
     self.aboutAct.triggered.connect(self.act_about)
Ejemplo n.º 33
0
    def __init__(self, app):
        self._app = app
        self._layout = QVBoxLayout(app)
        self._top_separator = Separator(parent=app)
        self._bottom_separator = Separator(parent=app)
        self._splitter = QSplitter(app)
        if use_mac_theme():
            self._splitter.setHandleWidth(0)

        # NOTE: 以位置命名的部件应该只用来组织界面布局,不要
        # 给其添加任何功能性的函数
        self.top_panel = TopPanel(app, app)
        self.bottom_panel = BottomPanel(app, app)
        self._left_panel_container = QScrollArea(app)
        self._left_panel_container.setWidgetResizable(True)
        self._left_panel_container.setFrameShape(QFrame.NoFrame)
        self.left_panel = LeftPanel(self._app, self._left_panel_container)
        self._left_panel_container.setWidget(self.left_panel)
        self.right_panel = RightPanel(self._app, self._splitter)
        self.mpv_widget = MpvOpenGLWidget(self._app)
        self.mpv_widget.hide()

        # alias
        self.magicbox = self.bottom_panel.magicbox
        self.pc_panel = self.top_panel.pc_panel
        self.table_container = self.right_panel.table_container
        self.back_btn = self.bottom_panel.back_btn
        self.forward_btn = self.bottom_panel.forward_btn
        self.toggle_video_btn = self.pc_panel.toggle_video_btn

        # 对部件进行一些 UI 层面的初始化
        self._splitter.addWidget(self._left_panel_container)
        self._splitter.addWidget(self.right_panel)

        self.right_panel.setMinimumWidth(780)
        self._left_panel_container.setSizePolicy(QSizePolicy.Minimum,
                                                 QSizePolicy.Expanding)
        self.right_panel.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)

        self._layout.addWidget(self.bottom_panel)
        self._layout.addWidget(self._bottom_separator)
        self._layout.addWidget(self._splitter)
        self._layout.addWidget(self.mpv_widget)
        self._layout.addWidget(self._top_separator)
        self._layout.addWidget(self.top_panel)

        self._layout.setSpacing(0)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self.top_panel.layout().setSpacing(0)
        self.top_panel.layout().setContentsMargins(0, 0, 0, 0)

        self.pc_panel.playlist_btn.clicked.connect(self.show_player_playlist)
        self.pc_panel.mv_btn.clicked.connect(self._play_mv)
        self.toggle_video_btn.clicked.connect(self._toggle_video_widget)
        self._app.player.video_format_changed.connect(
            self.on_video_format_changed)

        self._app.hotkey_mgr.registe(
            [QKeySequence('Ctrl+F'),
             QKeySequence(':'),
             QKeySequence('Alt+x')], self.magicbox.setFocus)
Ejemplo n.º 34
0
 def checkKeySequenceEqual(self, modifier, key, targetKeySequence):
     keySequence = QKeySequence(modifier + key).toString()
     return keySequence == targetKeySequence
Ejemplo n.º 35
0
    def create_connects(self):
        self.ui.actionFullscreen_mode.setShortcut(QKeySequence.FullScreen)
        self.ui.actionOpen.setShortcut(QKeySequence(QKeySequence.Open))
        self.ui.actionOpen_directory.setShortcut(QKeySequence("Ctrl+Shift+O"))

        self.ui.menuEdit.aboutToShow.connect(self.on_edit_menu_about_to_show)

        self.ui.actionNew_Project.triggered.connect(
            self.on_new_project_action_triggered)
        self.ui.actionNew_Project.setShortcut(QKeySequence.New)
        self.ui.actionProject_settings.triggered.connect(
            self.on_project_settings_action_triggered)
        self.ui.actionSave_project.triggered.connect(
            self.project_manager.save_project)

        self.ui.actionAbout_AutomaticHacker.triggered.connect(
            self.on_show_about_clicked)
        self.ui.actionRecord.triggered.connect(
            self.on_show_record_dialog_action_triggered)

        self.ui.actionFullscreen_mode.triggered.connect(
            self.on_fullscreen_action_triggered)
        self.ui.actionSaveAllSignals.triggered.connect(
            self.signal_tab_controller.save_all)
        self.ui.actionClose_all.triggered.connect(
            self.on_close_all_action_triggered)
        self.ui.actionOpen.triggered.connect(
            self.on_open_file_action_triggered)
        self.ui.actionOpen_directory.triggered.connect(
            self.on_open_directory_action_triggered)
        self.ui.actionDecoding.triggered.connect(
            self.on_show_decoding_dialog_triggered)
        self.ui.actionSpectrum_Analyzer.triggered.connect(
            self.on_show_spectrum_dialog_action_triggered)
        self.ui.actionOptions.triggered.connect(
            self.show_options_dialog_action_triggered)
        self.ui.actionSniff_protocol.triggered.connect(
            self.show_proto_sniff_dialog)
        self.ui.actionAbout_Qt.triggered.connect(
            QApplication.instance().aboutQt)

        self.ui.btnFileTreeGoUp.clicked.connect(
            self.on_btn_file_tree_go_up_clicked)
        self.ui.fileTree.directory_open_wanted.connect(
            self.project_manager.set_project_folder)

        self.signal_tab_controller.frame_closed.connect(
            self.close_signal_frame)
        self.signal_tab_controller.signal_created.connect(
            self.on_signal_created)
        self.signal_tab_controller.ui.scrollArea.files_dropped.connect(
            self.on_files_dropped)
        self.signal_tab_controller.files_dropped.connect(self.on_files_dropped)
        self.signal_tab_controller.frame_was_dropped.connect(
            self.set_frame_numbers)

        self.compare_frame_controller.show_interpretation_clicked.connect(
            self.show_protocol_selection_in_interpretation)
        self.compare_frame_controller.files_dropped.connect(
            self.on_files_dropped)
        self.compare_frame_controller.show_decoding_clicked.connect(
            self.on_show_decoding_dialog_triggered)
        self.compare_frame_controller.ui.treeViewProtocols.files_dropped_on_group.connect(
            self.on_files_dropped_on_group)
        self.compare_frame_controller.participant_changed.connect(
            self.signal_tab_controller.on_participant_changed)
        self.compare_frame_controller.ui.treeViewProtocols.close_wanted.connect(
            self.on_cfc_close_wanted)
        self.compare_frame_controller.show_config_field_types_triggered.connect(
            self.on_show_field_types_config_action_triggered)

        self.ui.lnEdtTreeFilter.textChanged.connect(
            self.on_file_tree_filter_text_changed)

        self.ui.tabWidget.currentChanged.connect(self.on_selected_tab_changed)
        self.project_save_timer.timeout.connect(
            self.project_manager.save_project)

        self.ui.actionConvert_Folder_to_Project.triggered.connect(
            self.project_manager.convert_folder_to_project)
        self.project_manager.project_loaded_status_changed.connect(
            self.ui.actionProject_settings.setVisible)
        self.project_manager.project_loaded_status_changed.connect(
            self.ui.actionSave_project.setVisible)
        self.project_manager.project_loaded_status_changed.connect(
            self.ui.actionConvert_Folder_to_Project.setDisabled)
        self.project_manager.project_updated.connect(self.on_project_updated)

        self.ui.textEditProjectDescription.textChanged.connect(
            self.on_text_edit_project_description_text_changed)
        self.ui.tabWidget_Project.tabBarDoubleClicked.connect(
            self.on_project_tab_bar_double_clicked)

        self.ui.listViewParticipants.doubleClicked.connect(
            self.on_project_settings_action_triggered)

        self.ui.actionShowFileTree.triggered.connect(
            self.on_action_show_filetree_triggered)
        self.ui.actionShowFileTree.setShortcut(QKeySequence("F10"))

        self.ui.menuFile.addSeparator()
        for i in range(constants.MAX_RECENT_FILE_NR):
            recent_file_action = QAction(self)
            recent_file_action.setVisible(False)
            recent_file_action.triggered.connect(
                self.on_open_recent_action_triggered)
            self.recentFileActionList.append(recent_file_action)
            self.ui.menuFile.addAction(self.recentFileActionList[i])
Ejemplo n.º 36
0
def key_to_string(key):
    """Convert a Qt::Key member to a meaningful name.

    Args:
        key: A Qt::Key member.

    Return:
        A name of the key as a string.
    """
    special_names_str = {
        # Some keys handled in a weird way by QKeySequence::toString.
        # See https://bugreports.qt.io/browse/QTBUG-40030
        # Most are unlikely to be ever needed, but you never know ;)
        # For dead/combining keys, we return the corresponding non-combining
        # key, as that's easier to add to the config.
        'Key_Blue': 'Blue',
        'Key_Calendar': 'Calendar',
        'Key_ChannelDown': 'Channel Down',
        'Key_ChannelUp': 'Channel Up',
        'Key_ContrastAdjust': 'Contrast Adjust',
        'Key_Dead_Abovedot': '˙',
        'Key_Dead_Abovering': '˚',
        'Key_Dead_Acute': '´',
        'Key_Dead_Belowdot': 'Belowdot',
        'Key_Dead_Breve': '˘',
        'Key_Dead_Caron': 'ˇ',
        'Key_Dead_Cedilla': '¸',
        'Key_Dead_Circumflex': '^',
        'Key_Dead_Diaeresis': '¨',
        'Key_Dead_Doubleacute': '˝',
        'Key_Dead_Grave': '`',
        'Key_Dead_Hook': 'Hook',
        'Key_Dead_Horn': 'Horn',
        'Key_Dead_Iota': 'Iota',
        'Key_Dead_Macron': '¯',
        'Key_Dead_Ogonek': '˛',
        'Key_Dead_Semivoiced_Sound': 'Semivoiced Sound',
        'Key_Dead_Tilde': '~',
        'Key_Dead_Voiced_Sound': 'Voiced Sound',
        'Key_Exit': 'Exit',
        'Key_Green': 'Green',
        'Key_Guide': 'Guide',
        'Key_Info': 'Info',
        'Key_LaunchG': 'LaunchG',
        'Key_LaunchH': 'LaunchH',
        'Key_MediaLast': 'MediaLast',
        'Key_Memo': 'Memo',
        'Key_MicMute': 'Mic Mute',
        'Key_Mode_switch': 'Mode switch',
        'Key_Multi_key': 'Multi key',
        'Key_PowerDown': 'Power Down',
        'Key_Red': 'Red',
        'Key_Settings': 'Settings',
        'Key_SingleCandidate': 'Single Candidate',
        'Key_ToDoList': 'Todo List',
        'Key_TouchpadOff': 'Touchpad Off',
        'Key_TouchpadOn': 'Touchpad On',
        'Key_TouchpadToggle': 'Touchpad toggle',
        'Key_Yellow': 'Yellow',
        'Key_Alt': 'Alt',
        'Key_AltGr': 'AltGr',
        'Key_Control': 'Control',
        'Key_Direction_L': 'Direction L',
        'Key_Direction_R': 'Direction R',
        'Key_Hyper_L': 'Hyper L',
        'Key_Hyper_R': 'Hyper R',
        'Key_Meta': 'Meta',
        'Key_Shift': 'Shift',
        'Key_Super_L': 'Super L',
        'Key_Super_R': 'Super R',
        'Key_unknown': 'Unknown',
    }
    # We now build our real special_names dict from the string mapping above.
    # The reason we don't do this directly is that certain Qt versions don't
    # have all the keys, so we want to ignore AttributeErrors.
    special_names = {}
    for k, v in special_names_str.items():
        try:
            special_names[getattr(Qt, k)] = v
        except AttributeError:
            pass
    # Now we check if the key is any special one - if not, we use
    # QKeySequence::toString.
    try:
        return special_names[key]
    except KeyError:
        name = QKeySequence(key).toString()
        morphings = {
            'Backtab': 'Tab',
            'Esc': 'Escape',
        }
        if name in morphings:
            return morphings[name]
        else:
            return name
Ejemplo n.º 37
0
    def __init__(self, callback, app, palette):
        super().__init__()
        self.app = app
        self.palette = palette
        self.layout = QHBoxLayout(self)
        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tabs.setStyleSheet("""
           QTabWidget::pane { /* The tab widget frame */
                border-top: 0.5px solid #303030;
            }
            
            QTabWidget::tab-bar {
                
            }
            
            /* Style the tab using the tab sub-control. Note that
                it reads QTabBar _not_ QTabWidget */
            QTabBar::tab {
                background: #434343;
                border-bottom: 2px solid #303030;
                border-bottom-color: #434343;
                min-width: 8ex;
                margin-left: 10px;
                padding-left: 25px;
                padding-right: 20px;
                padding-top: 3px;
                padding-bottom: 3px;
            }
            
            QTabBar::tab:selected, QTabBar::tab:hover {
                background: #434343;
            }
            QToolTip {
                padding: 3px;
                font-family: \"Iosevka\";
                font-size: 14px; 
                color: #FFFFFF;
                background: #303030;
                
            }
            QTabBar::tab:selected {
                border-bottom-color: #FFFFFF; /* same as pane color */
            }
            
            """)
        font = QFont(editor['tabFont'])
        font.setPointSize(
            editor["tabFontSize"])  # This is the tab font and font size
        self.tabs.setFont(font)
        self.status = QStatusBar(self)
        self.dialog = MessageBox()
        self.tabs.usesScrollButtons()
        self.filelist = []

        self.tabSaved = False

        self.Console = Console(
        )  # This is the terminal widget and the SECOND thread
        self.terminal = Terminal()
        self.term = IPythonWidget()
        self.directory = Directory(callback, self.app,
                                   self.palette)  # TODO: This is top left
        self.directory.clearSelection()
        self.tabCounter = []
        # Add tabs
        self.tab_layout = QHBoxLayout(
        )  # Create new layout for original tab layout
        self.tab_layout.addWidget(self.tabs)  # Add tab widget to tab layout
        self.search_layout = QHBoxLayout()

        self.tabs.setTabsClosable(True)
        self.tabs.setMovable(
            editor['tabMovable'])  # Let's you make the tabs movable

        if editor[
                'tabShape'] is True:  # If tab shape is true then they have this rounded look
            self.tabs.setTabShape(1)

        else:
            self.tabs.setTabShape(0)  # If false, it has this boxy look

        self.tabs.tabCloseRequested.connect(self.closeTab)

        # Add Console
        self.console_layout = QHBoxLayout()  # Create console layout
        self.console_layout.addWidget(
            self.term)  # Add console to console layout

        # Build Layout
        self.layout.addLayout(
            self.tab_layout)  # Adds 'TOP' layout : tab + directory
        self.layout.addLayout(self.search_layout)

        # Creating horizontal splitter
        self.splitterH = QSplitter(Qt.Horizontal)

        # Creating vertical splitter
        self.splitterV = QSplitter(Qt.Vertical)
        self.splitterV.addWidget(self.splitterH)
        self.layout.addWidget(self.splitterV)
        self.splitterV.setSizes([300, 10])
        self.setLayout(self.layout)  # Sets layout of QWidget

        self.closeShortcut = QShortcut(
            QKeySequence(editor["closeTabShortcut"]), self)
        self.closeShortcut.activated.connect(self.closeTabShortcut)

        self.getAllOpenTabs = QShortcut(QKeySequence("Ctrl+Shift+W"), self)
        self.getAllOpenTabs.activated.connect(self.getAllOpenTabsFunc)

        currentTab = self.tabs.currentWidget()
        self.hideDirectory()
        """
Ejemplo n.º 38
0
 def languageChanged(self):
     self.setName(self.tr("Insert Ellipse"))
     self.setShortcut(QKeySequence(self.tr("C")))
Ejemplo n.º 39
0
    def initUI(self):

        self.setWindowTitle('SIMPLE_stats_analyzer_v2.1')
        self.move(500, 300)
        self.resize(810, 470)

        self.setFixedSize(810, 470)
        self.setAcceptDrops(True)
        self.statusBar().showMessage('Ready')

        # Icon 설정
        self.setWindowIcon(QIcon('web.png'))

        # 단축키 설정
        self.shortcut = QShortcut(QKeySequence('Ctrl+Q'), self)
        self.shortcut.activated.connect(qApp.quit)

        # QLabel - label_file_path (white box)
        self.label_file_path = QLabel(self)
        self.label_file_path.setFrameShape(QFrame.Panel)
        self.label_file_path.setFrameShadow(QFrame.Sunken)
        self.label_file_path.setStyleSheet("background-color: white")
        self.label_file_path.setLineWidth(1)
        self.label_file_path.setGeometry(30, 40, 650, 250)
        font_helve_plain_small = self.label_file_path.font()
        font_helve_plain_small.setFamily('Helvetica')
        font_helve_plain_small.setPointSize(8)
        self.label_file_path.setFont(font_helve_plain_small)

        # QLabel - Drag & Drop
        self.label_dragdrop = QLabel('Drag & Drop files ↓', self)
        self.label_dragdrop.setFixedSize(200, 20)
        self.label_dragdrop.move(30, 20)
        font_helve_bold = self.label_dragdrop.font()
        font_helve_bold.setFamily('Helvetica')
        font_helve_bold.setPointSize(10)
        font_helve_bold.setBold(True)
        self.label_dragdrop.setFont(font_helve_bold)

        # QPushButton - Find files
        btn_path_finder = QPushButton('Find files', self)
        btn_path_finder.setGeometry(690, 39, 100, 120)
        btn_path_finder.clicked.connect(self.btn_path_finder_Function)

        # QPushButton - Stats analysis
        btn_stats_analysis = QPushButton('Stats analysis', self)
        btn_stats_analysis.setGeometry(690, 170, 100, 120)
        btn_stats_analysis.clicked.connect(self.btn_stats_analysis_Function)

        # QLabel - label_save_path (white box)
        self.label_save_path = QLabel(self)
        self.label_save_path.setFrameShape(QFrame.Panel)
        self.label_save_path.setFrameShadow(QFrame.Sunken)
        self.label_save_path.setStyleSheet("background-color: white")
        self.label_save_path.setLineWidth(1)
        self.label_save_path.setGeometry(30, 400, 650, 30)
        self.label_save_path.setFont(font_helve_plain_small)

        # QGroupBox - options
        GB = QGroupBox("Options", self)
        GB.setGeometry(50, 315, 610, 50)
        GB.setFont(font_helve_bold)

        # QCheckBox - options
        self.CB_Last_stats_summary = QCheckBox('Last_stats_summary', self)
        self.CB_Last_stats_summary.move(80, 336)
        self.CB_Last_stats_summary.setFixedSize(200, 20)
        font_helve_plain = self.CB_Last_stats_summary.font()
        font_helve_plain.setFamily('Helvetica')
        font_helve_plain.setPointSize(9)
        self.CB_Last_stats_summary.setFont(font_helve_plain)
        self.CB_Last_stats_summary.clicked.connect(self.groupboxCheckFunction)

        # QLabel - saved folder
        self.label_saved_folder = QLabel('Saved folder ↓', self)
        self.label_saved_folder.setFixedSize(200, 20)
        self.label_saved_folder.move(30, 380)
        self.label_saved_folder.setFont(font_helve_bold)

        # QPushButton - Open saved folder
        btn_savepath_open = QPushButton('Open folder', self)
        btn_savepath_open.setGeometry(690, 400, 100, 30)
        btn_savepath_open.clicked.connect(self.btn_savepath_open_Function)

        # QPushButton - Reset
        btn_reset = QPushButton('Reset', self)
        btn_reset.setGeometry(690, 323, 100, 40)
        btn_reset.clicked.connect(self.btn_reset_Function)

        # 변수들 초기상태
        self.file_path = ""
        self.file_path_text = ""
        self.file_path_list = []
        self.save_path = ""
        self.summary_onoff = 'off'

        self.show()
Ejemplo n.º 40
0
    def __init__(self, parent=None, email=None, remember_credentials=True):
        super(Login, self).__init__(parent)

        self.login = None
        self.passwd = None
        self.remember = remember_credentials

        self.linkRegister = QLabel(
            '<small><a href="' + config.register_url + '">' +
            QApplication.translate("Plus", "Register", None) + '</a></small>')
        self.linkRegister.setOpenExternalLinks(True)
        self.linkResetPassword = QLabel(
            '<small><a href="' + config.reset_passwd_url + '">' +
            QApplication.translate("Plus", "Reset Password", None) +
            '</a></small>')
        self.linkResetPassword.setOpenExternalLinks(True)

        self.textName = QLineEdit(self)
        self.textName.setPlaceholderText(
            QApplication.translate("Plus", "Email", None))
        if email is not None:
            self.textName.setText(email)
        self.textName.textChanged.connect(self.textChanged)
        self.textPass = QLineEdit(self)
        self.textPass.setEchoMode(QLineEdit.Password)
        self.textPass.setPlaceholderText(
            QApplication.translate("Plus", "Password", None))
        self.textPass.textChanged.connect(self.textChanged)

        self.rememberCheckbox = QCheckBox(
            QApplication.translate("Plus", "Remember", None))
        self.rememberCheckbox.setChecked(self.remember)
        self.rememberCheckbox.stateChanged.connect(self.rememberCheckChanged)

        self.dialogbuttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal)
        aw = config.app_window
        if aw.locale not in aw.qtbase_locales:
            self.dialogbuttons.button(QDialogButtonBox.Ok).setText(
                QApplication.translate("Button", "OK", None))
            self.dialogbuttons.button(QDialogButtonBox.Cancel).setText(
                QApplication.translate("Button", "Cancel", None))
        self.dialogbuttons.accepted.connect(self.setCredentials)
        self.dialogbuttons.rejected.connect(self.reject)
        self.dialogbuttons.button(QDialogButtonBox.Ok).setEnabled(False)
        self.dialogbuttons.button(QDialogButtonBox.Cancel).setDefault(True)
        # add additional CMD-. shortcut to close the dialog
        self.dialogbuttons.button(QDialogButtonBox.Cancel).setShortcut(
            QKeySequence("Ctrl+."))
        # add additional CMD-W shortcut to close this dialog
        cancelAction = QAction(self, triggered=lambda _: self.reject())
        try:
            cancelAction.setShortcut(QKeySequence.Cancel)
        except:
            pass
        self.dialogbuttons.button(QDialogButtonBox.Cancel).addActions(
            [cancelAction])

        credentialsLayout = QVBoxLayout(self)
        credentialsLayout.addWidget(self.textName)
        credentialsLayout.addWidget(self.textPass)
        credentialsLayout.addWidget(self.rememberCheckbox)

        credentialsGroup = QGroupBox()
        credentialsGroup.setLayout(credentialsLayout)

        buttonLayout = QHBoxLayout()
        buttonLayout.addStretch()
        buttonLayout.addWidget(self.dialogbuttons)
        buttonLayout.addStretch()

        linkLayout = QHBoxLayout()
        linkLayout.addStretch()
        linkLayout.addWidget(self.linkRegister)
        linkLayout.addStretch()
        linkLayout.addWidget(self.linkResetPassword)
        linkLayout.addStretch()

        layout = QVBoxLayout(self)
        layout.addWidget(credentialsGroup)
        layout.addLayout(linkLayout)
        layout.addLayout(buttonLayout)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(5)
Ejemplo n.º 41
0
    def __init__(self):
        """Create an instance of the WhatsApp Date Splitter GUI.

        This method takes no arguments and you must call show() after initialising an instance of it.
        """
        super(DateSplitterGUI, self).__init__()

        # A boolean to see if the window exists. Used to close properly
        self._exists = True

        self.setWindowTitle('WhatsApp Date Splitter')
        with open('style_gui.css', 'r') as f:
            self.setStyleSheet(f.read())

        self._instructions_text = '''Steps:\n
1. Select an exported chat\n
2. Select an output directory\n
3. Enter the desired title of the chat\n
4. Click the split button\n
5. Wait until the 'Splitting...' text disappears\n
6. If the zip file is big, this may take some time\n
7. Choose a new zip to split or exit the program'''

        self._selected_chat = ''
        self._selected_output = ''

        self._chat_title = ''

        # ===== Create widgets

        self._instructions_label = QtWidgets.QLabel(self)
        self._instructions_label.setText(self._instructions_text)
        self._instructions_label.setAlignment(QtCore.Qt.AlignCenter)
        self._instructions_label.setProperty('class', 'instructions')

        self._select_chat_button = QtWidgets.QPushButton(self)
        self._select_chat_button.setText('Select an exported chat')
        self._select_chat_button.clicked.connect(self._select_chat_dialog)

        self._selected_chat_label = QtWidgets.QLabel(self)
        self._selected_chat_label.setText('Selected:\n')
        self._selected_chat_label.setAlignment(QtCore.Qt.AlignCenter)

        self._select_output_button = QtWidgets.QPushButton(self)
        self._select_output_button.setText('Select an output directory')
        self._select_output_button.clicked.connect(self._select_output_dialog)

        self._selected_output_label = QtWidgets.QLabel(self)
        self._selected_output_label.setText('Selected:\n')
        self._selected_output_label.setAlignment(QtCore.Qt.AlignCenter)

        self._chat_title_label = QtWidgets.QLabel(self)
        self._chat_title_label.setText('Enter the desired title of the chat:')
        self._chat_title_label.setAlignment(QtCore.Qt.AlignCenter)

        self._chat_title_textbox = QtWidgets.QLineEdit(self)

        self._spacer_label = QtWidgets.QLabel(self)
        self._spacer_label.setText('')

        self._split_chat_button = QtWidgets.QPushButton(self)
        self._split_chat_button.setText('Process all')
        self._split_chat_button.setEnabled(False)
        self._split_chat_button.clicked.connect(self._start_split_chat_thread)

        self._splitting_label = QtWidgets.QLabel(self)
        self._splitting_label.setText('')
        self._splitting_label.setAlignment(QtCore.Qt.AlignCenter)

        self._exit_button = QtWidgets.QPushButton(self)
        self._exit_button.setText('Exit')
        self._exit_button.clicked.connect(self._close_properly)

        # This is a shortcut for the exit button
        self._exit_shortcut = QShortcut(QKeySequence("Ctrl+Q"), self)
        self._exit_shortcut.activated.connect(self._close_properly)

        # ===== Arrange widgets properly

        self._vbox = QVBoxLayout()
        self._hbox = QHBoxLayout()
        self._arrange_widgets()

        self._central_widget = QWidget()
        self._central_widget.setLayout(self._hbox)
        self.setCentralWidget(self._central_widget)

        # ===== Create threads

        self._check_everything_thread = threading.Thread(
            target=self._loop_check_everything)
        self._check_everything_thread.start()
Ejemplo n.º 42
0
    def __init__(self, main_window):
        super(WidgetsToolbar, self).__init__(main_window, "Windows Toolbar")
        self.setWindowTitle("Windows Toolbar")

        self.a_player = self.addAction(
            create_icon("qt_ui/icons/icon_player.png"), "Player")
        self.a_outliner = self.addAction(
            create_icon("qt_ui/icons/icon_outliner.png"), "Outliner")
        self.a_timeline = self.addAction(
            create_icon("qt_ui/icons/icon_timeline.png"), "Timeline")
        self.a_player_controls = self.addAction(
            create_icon("qt_ui/icons/icon_player_controls.png"),
            "Player Controls")
        self.a_inspector = self.addAction(
            create_icon("qt_ui/icons/icon_inspector.png"), "Inspector")

        self.addSeparator()
        self.a_screenshot_manager = self.addAction(
            create_icon("qt_ui/icons/icon_screenshot_manager.png"),
            "Screenshot Manager")
        self.a_colorimetry = self.addAction(
            create_icon("qt_ui/icons/icon_colorimetry.png"), "Colorimetry")
        self.a_analyses = self.addAction(
            create_icon("qt_ui/icons/icon_analyses.png"), "Analyses")
        self.a_classification = self.addAction(
            create_icon("qt_ui/icons/icon_classification.png"),
            "Classification")
        self.a_upload = self.addAction(
            create_icon("qt_ui/icons/icon_upload.png"), "Upload")

        self.addSeparator()
        self.a_setup = self.addAction(
            create_icon("qt_ui/icons/icon_settings_plot.png"), "Setup")
        self.a_vocabulary = self.addAction(
            create_icon("qt_ui/icons/icon_vocabulary.png"), "Vocabulary")
        self.a_corpus = self.addAction(
            create_icon("qt_ui/icons/icon_corpus.png"), "Corpus")
        self.a_query = self.addAction(
            create_icon("qt_ui/icons/icon_query.png"), "Query")

        self.addSeparator()
        self.a_cl_obj = self.addAction(
            create_icon("qt_ui/icons/icon_classification_object.png"),
            "Select Classification Object")

        self.a_outliner.setShortcut(QKeySequence(Qt.Key_Alt + Qt.Key_O))
        self.a_timeline.setShortcut(QKeySequence(Qt.Key_Alt + Qt.Key_T))
        self.a_player_controls.setShortcut(QKeySequence(Qt.Key_Alt + Qt.Key_P))
        self.a_analyses.setShortcut(QKeySequence(Qt.Key_Alt + Qt.Key_A))
        self.a_classification.setShortcut(QKeySequence(Qt.Key_Alt + Qt.Key_C))
        self.a_query.setShortcut(QKeySequence(Qt.Key_Alt + Qt.Key_Q))
        self.a_upload.setShortcut(QKeySequence(Qt.Key_Alt + Qt.Key_U))
        self.a_inspector.setShortcut(QKeySequence(Qt.Key_Alt + Qt.Key_I))

        self.a_vocabulary.triggered.connect(
            self.main_window.create_vocabulary_manager)
        self.a_setup.triggered.connect(
            self.main_window.create_experiment_editor)
        self.a_outliner.triggered.connect(self.main_window.create_outliner)
        self.a_timeline.triggered.connect(self.main_window.create_timeline)
        self.a_player_controls.triggered.connect(
            self.main_window.create_widget_player_controls)
        self.a_analyses.triggered.connect(
            self.main_window.create_analysis_results_widget)
        self.a_classification.triggered.connect(
            self.main_window.create_vocabulary_matrix)
        self.a_query.triggered.connect(
            partial(self.main_window.create_query_widget))
        self.a_upload.triggered.connect(
            self.main_window.create_corpus_client_toolbar)
        self.a_screenshot_manager.triggered.connect(
            self.main_window.create_screenshot_manager_dock_widget)
        self.a_colorimetry.triggered.connect(
            self.main_window.create_colorimetry_live)
        self.a_player.triggered.connect(
            self.main_window.create_widget_video_player)
        self.a_corpus.triggered.connect(self.main_window.create_corpus_widget)
        self.a_inspector.triggered.connect(self.main_window.create_inspector)

        self.a_cl_obj.triggered.connect(self.show_classification_selector)

        self.hook_visibility(self.main_window.player_dock_widget,
                             self.a_player)
        self.hook_visibility(self.main_window.outliner, self.a_outliner)
        self.hook_visibility(self.main_window.timeline, self.a_timeline)
        self.hook_visibility(self.main_window.player_controls,
                             self.a_player_controls)
        self.hook_visibility(self.main_window.screenshots_manager_dock,
                             self.a_screenshot_manager)
        self.hook_visibility(self.main_window.colorimetry_live,
                             self.a_colorimetry)
        self.hook_visibility(self.main_window.analysis_results_widget_dock,
                             self.a_analyses)
        self.hook_visibility(self.main_window.vocabulary_matrix,
                             self.a_classification)
        self.hook_visibility(self.main_window.corpus_client_toolbar,
                             self.a_upload)
        self.hook_visibility(self.main_window.experiment_dock, self.a_setup)
        self.hook_visibility(self.main_window.vocabulary_manager,
                             self.a_vocabulary)
        self.hook_visibility(self.main_window.corpus_widget, self.a_corpus)
        self.hook_visibility(self.main_window.query_widget, self.a_query)
        self.hook_visibility(self.main_window.inspector, self.a_inspector)

        # self.main_window = main_window
        self.main_window.vocabulary_manager.visibilityChanged.connect(
            partial(self.on_visibility_changed,
                    self.main_window.vocabulary_manager, self.a_vocabulary))
        self.show()
Ejemplo n.º 43
0
 def keyEventToQKeySequenceString(self, modifier, key):
     keySequence = QKeySequence(modifier + key).toString()
     return keySequence
Ejemplo n.º 44
0
    def __init__(self):
        # constructor of the base class
        QMainWindow.__init__(self)

        QCoreApplication.setOrganizationName("RST")
        QCoreApplication.setOrganizationDomain("https://tu-dresden.de/rst")
        QCoreApplication.setApplicationVersion(
            pkg_resources.require("PyMoskito")[0].version)
        QCoreApplication.setApplicationName(globals()["__package__"])

        # load settings
        self._settings = QSettings()
        self._read_settings()

        # initialize logger
        self._logger = logging.getLogger(self.__class__.__name__)

        # Create Simulation Backend
        self.guiProgress = None
        self.cmdProgress = None
        self.sim = SimulatorInteractor(self)
        self.runSimulation.connect(self.sim.run_simulation)
        self.stopSimulation.connect(self.sim.stop_simulation)
        self.sim.simulation_finalized.connect(self.new_simulation_data)
        self.currentDataset = None
        self.interpolator = None

        # sim setup viewer
        self.targetView = SimulatorView(self)
        self.targetView.setModel(self.sim.target_model)
        self.targetView.expanded.connect(self.target_view_changed)
        self.targetView.collapsed.connect(self.target_view_changed)

        # sim results viewer
        self.result_view = QTreeView()

        # the docking area allows to rearrange the user interface at runtime
        self.area = pg.dockarea.DockArea()

        # Window properties
        icon_size = QSize(25, 25)
        self.setCentralWidget(self.area)
        self.resize(1000, 700)
        self.setWindowTitle("PyMoskito")
        res_path = get_resource("mosquito.png")
        icon = QIcon(res_path)
        self.setWindowIcon(icon)

        # create docks
        self.propertyDock = pg.dockarea.Dock("Properties")
        self.animationDock = pg.dockarea.Dock("Animation")
        self.regimeDock = pg.dockarea.Dock("Regimes")
        self.dataDock = pg.dockarea.Dock("Data")
        self.logDock = pg.dockarea.Dock("Log")
        self.plotDockPlaceholder = pg.dockarea.Dock("Placeholder")

        # arrange docks
        self.area.addDock(self.animationDock, "right")
        self.area.addDock(self.regimeDock, "left", self.animationDock)
        self.area.addDock(self.propertyDock, "bottom", self.regimeDock)
        self.area.addDock(self.dataDock, "bottom", self.propertyDock)
        self.area.addDock(self.plotDockPlaceholder, "bottom",
                          self.animationDock)
        self.area.addDock(self.logDock, "bottom", self.dataDock)
        self.non_plotting_docks = list(self.area.findAll()[1].keys())

        # add widgets to the docks
        self.propertyDock.addWidget(self.targetView)

        if not vtk_available:
            self._logger.error(
                "loading vtk failed with:{}".format(vtk_error_msg))

        # check if there is a registered visualizer
        available_vis = get_registered_visualizers()
        self._logger.info("found visualizers: {}".format(
            [name for cls, name in available_vis]))
        if available_vis:
            # instantiate the first visualizer
            self._logger.info("loading visualizer '{}'".format(
                available_vis[0][1]))
            self.animationLayout = QVBoxLayout()

            if issubclass(available_vis[0][0], MplVisualizer):
                self.animationWidget = QWidget()
                self.visualizer = available_vis[0][0](self.animationWidget,
                                                      self.animationLayout)
                self.animationDock.addWidget(self.animationWidget)
            elif issubclass(available_vis[0][0], VtkVisualizer):
                if vtk_available:
                    # vtk window
                    self.animationFrame = QFrame()
                    self.vtkWidget = QVTKRenderWindowInteractor(
                        self.animationFrame)
                    self.animationLayout.addWidget(self.vtkWidget)
                    self.animationFrame.setLayout(self.animationLayout)
                    self.animationDock.addWidget(self.animationFrame)
                    self.vtk_renderer = vtkRenderer()
                    self.vtkWidget.GetRenderWindow().AddRenderer(
                        self.vtk_renderer)
                    self.visualizer = available_vis[0][0](self.vtk_renderer)
                    self.vtkWidget.Initialize()
                else:
                    self._logger.warning("visualizer depends on vtk which is "
                                         "not available on this system!")
            elif available_vis:
                raise NotImplementedError
        else:
            self.visualizer = None

        # regime window
        self.regime_list = QListWidget(self)
        self.regime_list.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.regimeDock.addWidget(self.regime_list)
        self.regime_list.itemDoubleClicked.connect(self.regime_dclicked)
        self._regimes = []
        self.regime_file_name = ""

        self.actDeleteRegimes = QAction(self.regime_list)
        self.actDeleteRegimes.setText("&Delete Selected Regimes")
        # TODO shortcut works always, not only with focus on the regime list
        # self.actDeleteRegimes.setShortcutContext(Qt.WindowShortcut)
        self.actDeleteRegimes.setShortcut(QKeySequence(Qt.Key_Delete))
        self.actDeleteRegimes.triggered.connect(self.remove_regime_items)

        self.actSave = QAction(self)
        self.actSave.setText('Save Results As')
        self.actSave.setIcon(QIcon(get_resource("save.png")))
        self.actSave.setDisabled(True)
        self.actSave.setShortcut(QKeySequence.Save)
        self.actSave.triggered.connect(self.export_simulation_data)

        self.actLoadRegimes = QAction(self)
        self.actLoadRegimes.setText("Load Regimes from File")
        self.actLoadRegimes.setIcon(QIcon(get_resource("load.png")))
        self.actLoadRegimes.setDisabled(False)
        self.actLoadRegimes.setShortcut(QKeySequence.Open)
        self.actLoadRegimes.triggered.connect(self.load_regime_dialog)

        self.actExitOnBatchCompletion = QAction(self)
        self.actExitOnBatchCompletion.setText("&Exit On Batch Completion")
        self.actExitOnBatchCompletion.setCheckable(True)
        self.actExitOnBatchCompletion.setChecked(
            self._settings.value("control/exit_on_batch_completion") == "True")
        self.actExitOnBatchCompletion.changed.connect(
            self.update_exit_on_batch_completion_setting)

        # regime management
        self.runningBatch = False
        self._current_regime_index = None
        self._current_regime_name = None
        self._regimes = []

        self.regimeFinished.connect(self.run_next_regime)
        self.finishedRegimeBatch.connect(self.regime_batch_finished)

        # data window
        self.dataList = QListWidget(self)
        self.dataDock.addWidget(self.dataList)
        self.dataList.itemDoubleClicked.connect(self.create_plot)

        # actions for simulation control
        self.actSimulateCurrent = QAction(self)
        self.actSimulateCurrent.setText("&Simulate Current Regime")
        self.actSimulateCurrent.setIcon(QIcon(get_resource("simulate.png")))
        self.actSimulateCurrent.setShortcut(QKeySequence("F5"))
        self.actSimulateCurrent.triggered.connect(self.start_simulation)

        self.actSimulateAll = QAction(self)
        self.actSimulateAll.setText("Simulate &All Regimes")
        self.actSimulateAll.setIcon(QIcon(get_resource("execute_regimes.png")))
        self.actSimulateAll.setShortcut(QKeySequence("F6"))
        self.actSimulateAll.setDisabled(True)
        self.actSimulateAll.triggered.connect(self.start_regime_execution)

        # actions for animation control
        self.actAutoPlay = QAction(self)
        self.actAutoPlay.setText("&Autoplay Simulation")
        self.actAutoPlay.setCheckable(True)
        self.actAutoPlay.setChecked(
            self._settings.value("control/autoplay_animation") == "True")
        self.actAutoPlay.changed.connect(self.update_autoplay_setting)

        self.actPlayPause = QAction(self)
        self.actPlayPause.setText("Play Animation")
        self.actPlayPause.setIcon(QIcon(get_resource("play.png")))
        self.actPlayPause.setDisabled(True)
        self.actPlayPause.setShortcut(QKeySequence(Qt.Key_Space))
        self.actPlayPause.triggered.connect(self.play_animation)

        self.actStop = QAction(self)
        self.actStop.setText("Stop")
        self.actStop.setIcon(QIcon(get_resource("stop.png")))
        self.actStop.setDisabled(True)
        self.actStop.triggered.connect(self.stop_animation)

        self.actSlow = QAction(self)
        self.actSlow.setText("Slowest")
        self.actSlow.setIcon(QIcon(get_resource("slow.png")))
        self.actSlow.setDisabled(False)
        self.actSlow.triggered.connect(self.set_slowest_playback_speed)

        self.actFast = QAction(self)
        self.actFast.setText("Fastest")
        self.actFast.setIcon(QIcon(get_resource("fast.png")))
        self.actFast.setDisabled(False)
        self.actFast.triggered.connect(self.set_fastest_playback_speed)

        self.speedControl = QSlider(Qt.Horizontal, self)
        self.speedControl.setMaximumSize(200, 25)
        self.speedControl.setTickPosition(QSlider.TicksBothSides)
        self.speedControl.setDisabled(False)
        self.speedControl.setMinimum(0)
        self.speedControl.setMaximum(12)
        self.speedControl.setValue(6)
        self.speedControl.setTickInterval(6)
        self.speedControl.setSingleStep(2)
        self.speedControl.setPageStep(3)
        self.speedControl.valueChanged.connect(self.update_playback_speed)

        self.timeSlider = QSlider(Qt.Horizontal, self)
        self.timeSlider.setMinimum(0)
        self.timeSliderRange = 1000
        self.timeSlider.setMaximum(self.timeSliderRange)
        self.timeSlider.setTickInterval(1)
        self.timeSlider.setTracking(True)
        self.timeSlider.setDisabled(True)
        self.timeSlider.valueChanged.connect(self.update_playback_time)

        self.playbackTime = .0
        self.playbackGain = 1
        self.currentStepSize = .0
        self.currentEndTime = .0
        self.playbackTimer = QTimer()
        self.playbackTimer.timeout.connect(self.increment_playback_time)
        self.playbackTimeChanged.connect(self.update_gui)
        self.playbackTimeout = 33  # in [ms] -> 30 fps

        self.actResetCamera = QAction(self)
        self.actResetCamera.setText("Reset Camera")
        self.actResetCamera.setIcon(QIcon(get_resource("reset_camera.png")))
        self.actResetCamera.setDisabled(True)
        if available_vis:
            self.actResetCamera.setEnabled(self.visualizer.can_reset_view)
        self.actResetCamera.triggered.connect(self.reset_camera_clicked)

        # postprocessing
        self.actPostprocessing = QAction(self)
        self.actPostprocessing.setText("Launch Postprocessor")
        self.actPostprocessing.setIcon(QIcon(get_resource("processing.png")))
        self.actPostprocessing.setDisabled(False)
        self.actPostprocessing.triggered.connect(self.postprocessing_clicked)
        self.actPostprocessing.setShortcut(QKeySequence("F7"))

        self.postprocessor = None

        # toolbar
        self.toolbarSim = QToolBar("Simulation")
        self.toolbarSim.setContextMenuPolicy(Qt.PreventContextMenu)
        self.toolbarSim.setMovable(False)
        self.toolbarSim.setIconSize(icon_size)
        self.addToolBar(self.toolbarSim)
        self.toolbarSim.addAction(self.actLoadRegimes)
        self.toolbarSim.addAction(self.actSave)
        self.toolbarSim.addSeparator()
        self.toolbarSim.addAction(self.actSimulateCurrent)
        self.toolbarSim.addAction(self.actSimulateAll)
        self.toolbarSim.addSeparator()
        self.toolbarSim.addAction(self.actPlayPause)
        self.toolbarSim.addAction(self.actStop)
        self.toolbarSim.addWidget(self.timeSlider)
        self.toolbarSim.addSeparator()
        self.toolbarSim.addAction(self.actSlow)
        self.toolbarSim.addWidget(self.speedControl)
        self.toolbarSim.addAction(self.actFast)
        self.toolbarSim.addSeparator()
        self.toolbarSim.addAction(self.actPostprocessing)
        self.toolbarSim.addAction(self.actResetCamera)
        self.postprocessor = None

        # log dock
        self.logBox = QPlainTextEdit(self)
        self.logBox.setReadOnly(True)
        self.logDock.addWidget(self.logBox)

        # init logger for logging box
        self.textLogger = PlainTextLogger(logging.INFO)
        self.textLogger.set_target_cb(self.logBox.appendPlainText)
        logging.getLogger().addHandler(self.textLogger)

        # menu bar
        fileMenu = self.menuBar().addMenu("&File")
        fileMenu.addAction(self.actLoadRegimes)
        fileMenu.addAction(self.actSave)
        fileMenu.addAction("&Quit", self.close)

        editMenu = self.menuBar().addMenu("&Edit")
        editMenu.addAction(self.actDeleteRegimes)

        simMenu = self.menuBar().addMenu("&Simulation")
        simMenu.addAction(self.actSimulateCurrent)
        simMenu.addAction(self.actSimulateAll)
        simMenu.addAction(self.actExitOnBatchCompletion)
        simMenu.addAction(self.actPostprocessing)

        animMenu = self.menuBar().addMenu("&Animation")
        animMenu.addAction(self.actPlayPause)
        animMenu.addAction("&Increase Playback Speed",
                           self.increment_playback_speed,
                           QKeySequence(Qt.CTRL + Qt.Key_Plus))
        animMenu.addAction("&Decrease Playback Speed",
                           self.decrement_playback_speed,
                           QKeySequence(Qt.CTRL + Qt.Key_Minus))
        animMenu.addAction("&Reset Playback Speed", self.reset_playback_speed,
                           QKeySequence(Qt.CTRL + Qt.Key_0))
        animMenu.addAction(self.actAutoPlay)
        animMenu.addAction(self.actResetCamera)

        helpMenu = self.menuBar().addMenu("&Help")
        helpMenu.addAction("&Online Documentation", self.show_online_docs)
        helpMenu.addAction("&About", self.show_info)

        # status bar
        self.status = QStatusBar(self)
        self.setStatusBar(self.status)
        self.statusLabel = QLabel("Ready.")
        self.statusBar().addPermanentWidget(self.statusLabel)
        self.timeLabel = QLabel("current time: 0.0")
        self.statusBar().addPermanentWidget(self.timeLabel)

        self._logger.info("Simulation GUI is up and running.")
Ejemplo n.º 45
0
    def build_ui(self):
        """Set up the user interface for the main window.

        Unlike the constructor, this method is re-run
        whenever the browser is "reset" by the user.
        """

        debug("build_ui")
        inactivity_timeout = self.config.get("timeout")
        quit_button_tooltip = (
            self.config.get("quit_button_mode") == 'close'
            and "Click here to quit the browser."
            or """Click here when you are done.
            It will clear your browsing history"""
            """ and return you to the start page.""")
        qb_mode_callbacks = {'close': self.close, 'reset': self.reset_browser}
        to_mode_callbacks = {'close': self.close,
                             'reset': self.reset_browser,
                             'screensaver': self.screensaver}
        self.screensaver_active = False

        # ##Start GUI configuration## #
        self.browser_window = WcgWebView(self.config)
        self.browser_window.setObjectName("web_content")

        if (
            self.config.get("icon_theme") is not None
            and QT_VERSION_STR > '4.6'
        ):
            QIcon.setThemeName(self.config.get("icon_theme"))
        self.setCentralWidget(self.browser_window)
        debug("loading {}".format(self.config.get("start_url")))
        self.browser_window.setUrl(QUrl(self.config.get("start_url")))
        if self.config.get("fullscreen"):
            self.showFullScreen()
        elif (
            self.config.get("window_size") and
            self.config.get("window_size").lower() == 'max'
        ):
            self.showMaximized()
        elif self.config.get("window_size"):
            size = re.match(r"(\d+)x(\d+)", self.config.get("window_size"))
            if size:
                width, height = size.groups()
                self.setFixedSize(int(width), int(height))
            else:
                debug('Ignoring invalid window size "{}"'.format(
                    self.config.get("window_size")
                ))

        # Set up the top navigation bar if it's configured to exist
        if self.config.get("navigation"):
            self.navigation_bar = QToolBar("Navigation")
            self.navigation_bar.setObjectName("navigation")
            self.addToolBar(Qt.TopToolBarArea, self.navigation_bar)
            self.navigation_bar.setMovable(False)
            self.navigation_bar.setFloatable(False)

            #  Standard navigation tools
            self.nav_items = {}
            self.nav_items["back"] = self.browser_window.pageAction(QWebPage.Back)
            self.nav_items["forward"] = self.browser_window.pageAction(QWebPage.Forward)
            self.nav_items["refresh"] = self.browser_window.pageAction(QWebPage.Reload)
            self.nav_items["stop"] = self.browser_window.pageAction(QWebPage.Stop)
            # The "I'm finished" button.
            self.nav_items["quit"] = self.createAction(
                self.config.get("quit_button_text"),
                qb_mode_callbacks.get(self.config.get("quit_button_mode"), self.reset_browser),
                QKeySequence("Alt+F"),
                None,
                quit_button_tooltip)
            # Zoom buttons
            self.nav_items["zoom_in"] = self.createAction(
                "Zoom In",
                self.zoom_in,
                QKeySequence("Alt++"),
                "zoom-in",
                "Increase the size of the text and images on the page")
            self.nav_items["zoom_out"] = self.createAction(
                "Zoom Out",
                self.zoom_out,
                QKeySequence("Alt+-"),
                "zoom-out",
                "Decrease the size of text and images on the page")
            if self.config.get("allow_printing"):
                self.nav_items["print"] = self.createAction(
                    "Print",
                    self.browser_window.print_webpage,
                    QKeySequence("Ctrl+p"),
                    "document-print",
                    "Print this page")

            # Add all the actions to the navigation bar.
            for item in self.config.get("navigation_layout"):
                if item == "separator":
                    self.navigation_bar.addSeparator()
                elif item == "spacer":
                    # an expanding spacer.
                    spacer = QWidget()
                    spacer.setSizePolicy(
                        QSizePolicy.Expanding, QSizePolicy.Preferred)
                    self.navigation_bar.addWidget(spacer)
                elif item == "bookmarks":
                    # Insert bookmarks buttons here.
                    self.bookmark_buttons = []
                    for bookmark in self.config.get("bookmarks", {}).items():
                        debug("Bookmark:\n" + bookmark.__str__())
                        # bookmark name will use the "name" attribute, if present
                        # or else just the key:
                        bookmark_name = bookmark[1].get("name") or bookmark[0]
                        # Create a button for the bookmark as a QAction,
                        # which we'll add to the toolbar
                        button = self.createAction(
                            bookmark_name,
                            lambda url=bookmark[1].get("url"): self.browser_window.load(QUrl(url)),
                            QKeySequence.mnemonic(bookmark_name),
                            None,
                            bookmark[1].get("description")
                            )
                        self.navigation_bar.addAction(button)
                        self.navigation_bar.widgetForAction(button).setObjectName("navigation_button")
                else:
                    action = self.nav_items.get(item, None)
                    if action:
                        self.navigation_bar.addAction(action)
                        self.navigation_bar.widgetForAction(action).setObjectName("navigation_button")

            # This removes the ability to toggle off the navigation bar:
            self.nav_toggle = self.navigation_bar.toggleViewAction()
            self.nav_toggle.setVisible(False)
            # End "if show_navigation is True" block

        # set hidden quit action
        # For reasons I haven't adequately ascertained,
        # this shortcut fails now and then claiming
        # "Ambiguous shortcut overload".
        # No idea why, as it isn't consistent.
        self.really_quit = self.createAction(
            "", self.close, QKeySequence("Ctrl+Alt+Q"), None, ""
        )
        self.addAction(self.really_quit)

        # Call a reset function after timeout
        if inactivity_timeout != 0:
            self.event_filter = InactivityFilter(inactivity_timeout)
            QCoreApplication.instance().installEventFilter(self.event_filter)
            self.browser_window.page().installEventFilter(self.event_filter)
            self.event_filter.timeout.connect(
                to_mode_callbacks.get(self.config.get("timeout_mode"),
                                      self.reset_browser))
        else:
            self.event_filter = None
Ejemplo n.º 46
0
app = QApplication([])
app.setApplicationName("MINCODING");
text = QPlainTextEdit()
#
window = MainWindow()
#
window.setCentralWidget(text)
menu = window.menuBar().addMenu("File")

open_action = QAction("&Open")
def open_file():
    path = QFileDialog.getOpenFileName(window, "Open File")[0]
    if path:
        text.setPlainText(open(path).read())
open_action.triggered.connect(open_file)
open_action.setShortcut(QKeySequence("Ctrl+O"))
menu.addAction(open_action)

save_as_action = QAction("Save &As...")

#
file_path = None
save_action = QAction("&Save")
def save():
    if file_path is None:
        save_as()
    else:
        with open(file_path, "w") as f:
            f.write(text.toPlainText())
        #
        text.document().setModified(False)
Ejemplo n.º 47
0
 def shortcut(self):
     return QKeySequence.fromString(self.text())
Ejemplo n.º 48
0
 def add_shortcuts(self) -> None:
     self.shortcutCloseQ = QShortcut(QKeySequence("Q"), self)
     self.shortcutCloseQ.activated.connect(self.close)
Ejemplo n.º 49
0
 def __init__(self, engine, use_qt_notifications):
     super(MainWindow, self).__init__()
     self.setupUi(self)
     if hasattr(self, 'setUnifiedTitleAndToolBarOnMac'):
         self.setUnifiedTitleAndToolBarOnMac(True)
     self._engine = engine
     self._active_dialogs = {}
     self._dialog_class = {
         'about'             : AboutDialog,
         'configuration'     : ConfigWindow,
     }
     all_actions = find_menu_actions(self.menubar)
     # Dictionaries.
     self.dictionaries = self.scroll_area.widget()
     self.dictionaries.add_translation.connect(self._add_translation)
     self.dictionaries.setFocus()
     edit_menu = all_actions['menu_Edit'].menu()
     edit_menu.addAction(self.dictionaries.action_Undo)
     edit_menu.addSeparator()
     edit_menu.addMenu(self.dictionaries.menu_AddDictionaries)
     edit_menu.addAction(self.dictionaries.action_EditDictionaries)
     edit_menu.addAction(self.dictionaries.action_RemoveDictionaries)
     edit_menu.addSeparator()
     edit_menu.addAction(self.dictionaries.action_MoveDictionariesUp)
     edit_menu.addAction(self.dictionaries.action_MoveDictionariesDown)
     # Tray icon.
     self._trayicon = TrayIcon()
     self._trayicon.enable()
     self._trayicon.clicked.connect(self._engine.toggle_output)
     if use_qt_notifications:
         handler = NotificationHandler()
         handler.emitSignal.connect(self._trayicon.log)
         log.add_handler(handler)
     popup_menu = QMenu()
     for action_name in (
         'action_ToggleOutput',
         'action_Reconnect',
         '',
         'menu_Tools',
         '',
         'action_Configure',
         '',
         'menu_Help',
         '',
         'action_Show',
         'action_Quit',
     ):
         if action_name:
             popup_menu.addAction(all_actions[action_name])
         else:
             popup_menu.addSeparator()
     self._trayicon.set_menu(popup_menu)
     engine.signal_connect('machine_state_changed', self._trayicon.update_machine_state)
     engine.signal_connect('quit', self.on_quit)
     self.action_Quit.triggered.connect(engine.quit)
     # Populate tools bar/menu.
     tools_menu = all_actions['menu_Tools'].menu()
     # Toolbar popup menu for selecting which tools are shown.
     self.toolbar_menu = QMenu()
     self.toolbar.setContextMenuPolicy(Qt.CustomContextMenu)
     self.toolbar.customContextMenuRequested.connect(
         lambda: self.toolbar_menu.popup(QCursor.pos())
     )
     for tool_plugin in registry.list_plugins('gui.qt.tool'):
         tool = tool_plugin.obj
         action_parameters = []
         if tool.ICON is not None:
             icon = tool.ICON
             # Internal QT resources start with a `:`.
             if not icon.startswith(':'):
                 icon = resource_filename(icon)
             action_parameters.append(QIcon(icon))
         action_parameters.append(tool.TITLE)
         toolbar_action = None
         for parent in (tools_menu, self.toolbar, self.toolbar_menu):
             action = parent.addAction(*action_parameters)
             action.setObjectName(tool_plugin.name)
             if tool.__doc__ is not None:
                 action.setToolTip(tool.__doc__)
             if tool.SHORTCUT is not None:
                 action.setShortcut(QKeySequence.fromString(tool.SHORTCUT))
             if parent == self.toolbar_menu:
                 action.setCheckable(True)
                 action.setChecked(True)
                 assert toolbar_action is not None
                 action.toggled.connect(toolbar_action.setVisible)
             else:
                 if parent == self.toolbar:
                     toolbar_action = action
                 action.triggered.connect(partial(self._activate_dialog,
                                                  tool_plugin.name,
                                                  args=()))
         self._dialog_class[tool_plugin.name] = tool
     engine.signal_connect('output_changed', self.on_output_changed)
     # Machine.
     self.machine_type.addItems(
         _(plugin.name)
         for plugin in registry.list_plugins('machine')
     )
     engine.signal_connect('config_changed', self.on_config_changed)
     engine.signal_connect('machine_state_changed',
         lambda machine, state:
         self.machine_state.setText(_(state.capitalize()))
     )
     self.restore_state()
     # Commands.
     engine.signal_connect('add_translation', partial(self._add_translation, manage_windows=True))
     engine.signal_connect('focus', self._focus)
     engine.signal_connect('configure', partial(self._configure, manage_windows=True))
     engine.signal_connect('lookup', partial(self._activate_dialog, 'lookup',
                                             manage_windows=True))
     # Load the configuration (but do not start the engine yet).
     if not engine.load_config():
         self.on_configure()
     # Apply configuration settings.
     config = self._engine.config
     self.machine_type.setCurrentText(config['machine_type'])
     self._configured = False
     self.dictionaries.on_config_changed(config)
     self.set_visible(not config['start_minimized'])
     # Start the engine.
     engine.start()
Ejemplo n.º 50
0
    def __init__(self, resources, sys_argv):
        """
        Init main window.
        """

        super().__init__()
        self.setupUi(self)

        # load args.
        self._args = Args(resources)

        # load translations.
        self._func_tr_()

        # init qt args.
        app_icon = QIcon()
        app_icon.addPixmap(QPixmap(":/images/images/icon_128.png"),
                           QIcon.Normal, QIcon.Off)
        self.setWindowIcon(app_icon)
        self.setMinimumSize(640, 480)

        self._setup_workarea()
        self._setup_result()
        self._setup_rule()
        self._setup_mode()
        self._setup_operation()
        self._setup_script()
        self._setup_channel()
        self._setup_transformation()
        self._setup_settings()

        self.tabifyDockWidget(self.script_dock_widget,
                              self.operation_dock_widget)
        self.tabifyDockWidget(self.transformation_dock_widget,
                              self.mode_dock_widget)
        self.tabifyDockWidget(self.channel_dock_widget, self.rule_dock_widget)

        self.actionOpen.triggered.connect(self._wget_operation.open_btn.click)
        self.actionSave.triggered.connect(self._wget_operation.save_btn.click)
        self.actionImport.triggered.connect(
            self._wget_operation.import_btn.click)
        self.actionExport.triggered.connect(
            self._wget_operation.export_btn.click)
        self.actionQuit.triggered.connect(self.close)

        self.actionCreate.triggered.connect(
            self._wget_operation.create_btn.click)
        self.actionLocate.triggered.connect(
            self._wget_operation.locate_btn.click)
        self.actionAttach.triggered.connect(
            self._wget_operation.attach_btn.click)
        self.actionSettings.triggered.connect(self._wget_settings.showup)

        self.actionWheel.triggered.connect(lambda x: self._inner_create(False)
                                           (False))
        self.actionImage.triggered.connect(lambda x: self._inner_locate(False)
                                           (False))
        self.actionDepot.triggered.connect(lambda x: self._inner_attach(False)
                                           (False))

        self.actionRule.triggered.connect(
            self._inner_show_or_hide(self.rule_dock_widget))
        self.actionChannel.triggered.connect(
            self._inner_show_or_hide(self.channel_dock_widget))
        self.actionOperation.triggered.connect(
            self._inner_show_or_hide(self.operation_dock_widget))
        self.actionScript.triggered.connect(
            self._inner_show_or_hide(self.script_dock_widget))
        self.actionMode.triggered.connect(
            self._inner_show_or_hide(self.mode_dock_widget))
        self.actionTransformation.triggered.connect(
            self._inner_show_or_hide(self.transformation_dock_widget))
        self.actionResult.triggered.connect(
            self._inner_show_or_hide(self.result_dock_widget))
        self.actionAll.triggered.connect(self._inner_all_show_or_hide)

        self.actionHomepage.triggered.connect(
            lambda x: QDesktopServices.openUrl(QUrl(self._args.info_main_site)
                                               ))
        self.actionUpdate.triggered.connect(lambda x: QDesktopServices.openUrl(
            QUrl(self._args.info_update_site)))
        self.actionAbout.triggered.connect(lambda x: self._show_about())

        self.rule_dock_widget.visibilityChanged.connect(
            lambda x: self.actionRule.setChecked(self.rule_dock_widget.
                                                 isVisible()))
        self.channel_dock_widget.visibilityChanged.connect(
            lambda x: self.actionChannel.setChecked(self.channel_dock_widget.
                                                    isVisible()))
        self.operation_dock_widget.visibilityChanged.connect(
            lambda x: self.actionOperation.setChecked(
                self.operation_dock_widget.isVisible()))
        self.script_dock_widget.visibilityChanged.connect(
            lambda x: self.actionScript.setChecked(self.script_dock_widget.
                                                   isVisible()))
        self.mode_dock_widget.visibilityChanged.connect(
            lambda x: self.actionMode.setChecked(self.mode_dock_widget.
                                                 isVisible()))
        self.transformation_dock_widget.visibilityChanged.connect(
            lambda x: self.actionTransformation.setChecked(
                self.transformation_dock_widget.isVisible()))
        self.result_dock_widget.visibilityChanged.connect(
            lambda x: self.actionResult.setChecked(self.result_dock_widget.
                                                   isVisible()))

        shortcut = QShortcut(QKeySequence("Alt+H"), self)
        shortcut.activated.connect(self.actionHomepage.trigger)
        shortcut = QShortcut(QKeySequence("F1"), self)
        shortcut.activated.connect(self.actionHomepage.trigger)

        shortcut = QShortcut(QKeySequence("Alt+U"), self)
        shortcut.activated.connect(self.actionUpdate.trigger)
        shortcut = QShortcut(QKeySequence("F2"), self)
        shortcut.activated.connect(self.actionUpdate.trigger)

        shortcut = QShortcut(QKeySequence("Alt+B"), self)
        shortcut.activated.connect(self.actionAbout.trigger)
        shortcut = QShortcut(QKeySequence("F3"), self)
        shortcut.activated.connect(self.actionAbout.trigger)

        shortcut = QShortcut(QKeySequence("Alt+O"), self)
        shortcut.activated.connect(self._wget_operation.open_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+O"), self)
        shortcut.activated.connect(self._wget_operation.open_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+S"), self)
        shortcut.activated.connect(self._wget_operation.save_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+S"), self)
        shortcut.activated.connect(self._wget_operation.save_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+I"), self)
        shortcut.activated.connect(self._wget_operation.import_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+I"), self)
        shortcut.activated.connect(self._wget_operation.import_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+E"), self)
        shortcut.activated.connect(self._wget_operation.export_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+E"), self)
        shortcut.activated.connect(self._wget_operation.export_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+Q"), self)
        shortcut.activated.connect(self.close)
        shortcut = QShortcut(QKeySequence("Esc"), self)
        shortcut.activated.connect(self.close)

        shortcut = QShortcut(QKeySequence("Alt+T"), self)
        shortcut.activated.connect(self._wget_settings.showup)
        shortcut = QShortcut(QKeySequence("`"), self)
        shortcut.activated.connect(self._wget_settings.showup)

        shortcut = QShortcut(QKeySequence("Alt+C"), self)
        shortcut.activated.connect(self._wget_operation.create_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+W"), self)
        shortcut.activated.connect(self._wget_operation.create_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+L"), self)
        shortcut.activated.connect(self._wget_operation.locate_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+G"), self)
        shortcut.activated.connect(self._wget_operation.locate_btn.click)

        shortcut = QShortcut(QKeySequence("Alt+A"), self)
        shortcut.activated.connect(self._wget_operation.attach_btn.click)
        shortcut = QShortcut(QKeySequence("Ctrl+D"), self)
        shortcut.activated.connect(self._wget_operation.attach_btn.click)

        # install translator.
        self._tr = QTranslator()
        self._app = QApplication.instance()
        self._install_translator()

        # focus on wheel.
        self._wget_wheel.setFocus()

        if len(sys_argv) > 1:
            try:
                if sys_argv[1].split(".")[-1].lower() in ("png", "bmp", "jpg",
                                                          "jpeg", "tif",
                                                          "tiff"):
                    self._inner_locate(False)(False)
                    self._wget_image.open_image(sys_argv[1])

                else:
                    with open(sys_argv[1], "r", encoding='utf-8') as f:
                        color_dict = json.load(f)

                        if isinstance(color_dict,
                                      dict) and "type" in color_dict:
                            if color_dict["type"] == "depot":
                                self._inner_attach(False)(False)
                                self._wget_operation.dp_open(sys_argv[1])

                            elif color_dict["type"] == "set":
                                self._wget_operation.dp_import(sys_argv[1])

            except Exception as err:
                pass

        # install stylesheet.
        """
Ejemplo n.º 51
0
def init_all_shortcuts(ui):
    # c Shortcuts
    ui.s_shortcut = QShortcut(QKeySequence('c'), ui)
    ui.s_shortcut.activated.connect(c_shortcuts)

    # b Shortcuts
    ui.notes_back_shortcut = QShortcut(QKeySequence('b'), ui)
    ui.notes_back_shortcut.activated.connect(b_shortcuts)

    # s Shortcuts
    ui.s_shortcut = QShortcut(QKeySequence('s'), ui)
    ui.s_shortcut.activated.connect(s_shortcuts)

    # p Shortcuts
    ui.s_shortcut = QShortcut(QKeySequence('p'), ui)
    ui.s_shortcut.activated.connect(p_shortcuts)

    # d Shortcuts
    ui.d_shortcuts = QShortcut(QKeySequence('d'), ui)
    ui.d_shortcuts.activated.connect(d_shortcuts)

    # y Shortcuts
    ui.y_shortcuts = QShortcut(QKeySequence('y'), ui)
    ui.y_shortcuts.activated.connect(y_shortcuts)

    # i Shortcuts
    ui.i_shortcuts = QShortcut(QKeySequence('i'), ui)
    ui.i_shortcuts.activated.connect(i_shortcuts)

    # q Shortcuts
    ui.q_shortcuts = QShortcut(QKeySequence('q'), ui)
    ui.q_shortcuts.activated.connect(q_shortcuts)

    # j Shortcuts
    ui.j_shortcuts = QShortcut(QKeySequence('j'), ui)
    ui.j_shortcuts.activated.connect(j_shortcuts)

    # x Shortcuts
    ui.x_shortcuts = QShortcut(QKeySequence('x'), ui)
    ui.x_shortcuts.activated.connect(x_shortcuts)

    # u Shortcuts
    ui.u_shortcuts = QShortcut(QKeySequence('u'), ui)
    ui.u_shortcuts.activated.connect(u_shortcuts)

    # k Shortcuts
    ui.k_shortcuts = QShortcut(QKeySequence('k'), ui)
    ui.k_shortcuts.activated.connect(k_shortcuts)

    # t Shortcuts
    ui.t_shortcuts = QShortcut(QKeySequence('t'), ui)
    ui.t_shortcuts.activated.connect(t_shortcuts)

    # h Shortcuts
    ui.h_shortcuts = QShortcut(QKeySequence('h'), ui)
    ui.h_shortcuts.activated.connect(h_shortcuts)

    # l Shortcuts
    ui.l_shortcuts = QShortcut(QKeySequence('l'), ui)
    ui.l_shortcuts.activated.connect(l_shortcuts)
Ejemplo n.º 52
0
class KeySequenceButton(QPushButton):
    
    def __init__(self, parent=None):
        super(KeySequenceButton, self).__init__(parent)
        self.setIcon(icons.get("configure"))
        self._modifierlessAllowed = False
        self._seq = QKeySequence()
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        self._isrecording = False
        self.clicked.connect(self.startRecording)
        self._timer.timeout.connect(self.doneRecording)

    def setKeySequence(self, seq):
        self._seq = seq
        self.updateDisplay()

    def keySequence(self):
        if self._isrecording:
            self.doneRecording()
        return self._seq
    
    def updateDisplay(self):
        if self._isrecording:
            s = self._recseq.toString(QKeySequence.NativeText).replace('&', '&&')
            if self._modifiers:
                if s: s += ","
                s += QKeySequence(self._modifiers).toString(QKeySequence.NativeText)
            elif self._recseq.isEmpty():
                s = _("Input")
            s += " ..."
        else:
            s = self._seq.toString(QKeySequence.NativeText).replace('&', '&&')
        self.setText(s)

    def isRecording(self):
        return self._isrecording
        
    def event(self, ev):
        if self._isrecording:
            # prevent Qt from special casing Tab and Backtab
            if ev.type() == QEvent.KeyPress:
                self.keyPressEvent(ev)
                return True
        return super(KeySequenceButton, self).event(ev)
        
    def keyPressEvent(self, ev):
        if not self._isrecording:
            return super(KeySequenceButton, self).keyPressEvent(ev)
        if ev.isAutoRepeat():
            return
        modifiers = int(ev.modifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        ev.accept()
        
        key = ev.key()
        # check if key is a modifier or a character key without modifier (and if that is allowed)
        if (
            # don't append the key if the key is -1 (garbage) or a modifier ...
            key not in (-1, Qt.Key_AltGr, Qt.Key_Shift, Qt.Key_Control,
                            Qt.Key_Alt, Qt.Key_Meta, Qt.Key_Menu)
            # or if this is the first key and without modifier and modifierless keys are not allowed
            and (self._modifierlessAllowed
                 or self._recseq.count() > 0
                 or modifiers & ~Qt.SHIFT
                 or not ev.text()
                 or (modifiers & Qt.SHIFT
                     and key in (Qt.Key_Return, Qt.Key_Space, Qt.Key_Tab, Qt.Key_Backtab,
                                 Qt.Key_Backspace, Qt.Key_Delete, Qt.Key_Escape)))):
            # change Shift+Backtab into Shift+Tab
            if key == Qt.Key_Backtab and modifiers & Qt.SHIFT:
                key = Qt.Key_Tab | modifiers
            # remove the Shift modifier if it doesn't make sense
#            elif (Qt.Key_Exclam <= key <= Qt.Key_At
#                  or Qt.Key_Z < key <= 0x0ff):
#                key = key | (modifiers & ~Qt.SHIFT)
            else:
                key = key | modifiers
            
            # append max. 4 keystrokes
            if self._recseq.count() < 4:
                l = list(self._recseq)
                l.append(key)
                self._recseq = QKeySequence(*l)
        
        self._modifiers = modifiers
        self.controlTimer()
        self.updateDisplay()
        
    def keyReleaseEvent(self, ev):
        if not self._isrecording:
            return super(KeySequenceButton, self).keyReleaseEvent(ev)
        modifiers = int(ev.modifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        ev.accept()
        
        self._modifiers = modifiers
        self.controlTimer()
        self.updateDisplay()
    
    def hideEvent(self, ev):
        if self._isrecording:
            self.cancelRecording()
        super(KeySequenceButton, self).hideEvent(ev)
        
    def controlTimer(self):
        if self._modifiers or self._recseq.isEmpty():
            self._timer.stop()
        else:
            self._timer.start(600)
    
    def startRecording(self):
        self.setFocus(True) # because of QTBUG 17810
        self.setDown(True)
        self.setStyleSheet("text-align: left;")
        self._isrecording = True
        self._recseq = QKeySequence()
        self._modifiers = int(QApplication.keyboardModifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        self.grabKeyboard()
        self.updateDisplay()
        
    def doneRecording(self):
        self._seq = self._recseq
        self.cancelRecording()
        self.clearFocus()
        self.parentWidget().keySequenceChanged.emit(self.parentWidget().num())
        
    def cancelRecording(self):
        if not self._isrecording:
            return
        self.setDown(False)
        self.setStyleSheet(None)
        self._isrecording = False
        self.releaseKeyboard()
        self.updateDisplay()
Ejemplo n.º 53
0
    def __init__(self, parent=None):  # pylint: disable=too-many-statements
        super(BreakpointsWidget, self).__init__(parent=parent)

        self._app_window = parent

        if self._app_window.dwarf is None:
            print('BreakpointsWidget created before Dwarf exists')
            return

        # connect to dwarf
        self._app_window.dwarf.onApplyContext.connect(self._on_apply_context)
        self._app_window.dwarf.onAddJavaBreakpoint.connect(self._on_add_breakpoint)
        self._app_window.dwarf.onAddObjCBreakpoint.connect(self._on_add_breakpoint)
        self._app_window.dwarf.onAddNativeBreakpoint.connect(self._on_add_breakpoint)
        self._app_window.dwarf.onAddModuleInitializationBreakpoint.connect(self._on_add_breakpoint)
        self._app_window.dwarf.onAddJavaClassInitializationBreakpoint.connect(self._on_add_breakpoint)
        self._app_window.dwarf.onHitModuleInitializationBreakpoint.connect(
            self._on_hit_module_initialization_breakpoint)
        self._app_window.dwarf.onHitJavaClassInitializationBreakpoint.connect(
            self._on_hit_java_class_initialization_breakpoint)
        self._app_window.dwarf.onDeleteBreakpoint.connect(self._on_breakpoint_deleted)

        self._breakpoints_list = DwarfListView()
        self._breakpoints_list.doubleClicked.connect(self._on_double_clicked)
        self._breakpoints_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self._breakpoints_list.customContextMenuRequested.connect(
            self._on_context_menu)
        self._breakpoints_model = QStandardItemModel(0, 3)

        self._breakpoints_model.setHeaderData(0, Qt.Horizontal, 'Address')
        self._breakpoints_model.setHeaderData(1, Qt.Horizontal, 'T')
        self._breakpoints_model.setHeaderData(1, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole)
        self._breakpoints_model.setHeaderData(2, Qt.Horizontal, '<>')
        self._breakpoints_model.setHeaderData(2, Qt.Horizontal, Qt.AlignCenter, Qt.TextAlignmentRole)

        self._breakpoints_list.setModel(self._breakpoints_model)

        self._breakpoints_list.header().setStretchLastSection(False)
        self._breakpoints_list.header().setSectionResizeMode(
            0, QHeaderView.ResizeToContents | QHeaderView.Interactive)
        self._breakpoints_list.header().setSectionResizeMode(
            1, QHeaderView.ResizeToContents)
        self._breakpoints_list.header().setSectionResizeMode(
            2, QHeaderView.ResizeToContents)

        v_box = QVBoxLayout(self)
        v_box.setContentsMargins(0, 0, 0, 0)
        v_box.addWidget(self._breakpoints_list)

        h_box = QHBoxLayout()
        h_box.setContentsMargins(5, 2, 5, 5)
        self.btn1 = QPushButton(
            QIcon(utils.resource_path('assets/icons/plus.svg')), '')
        self.btn1.setFixedSize(20, 20)
        self.btn1.clicked.connect(self._on_add_item_clicked)
        btn2 = QPushButton(
            QIcon(utils.resource_path('assets/icons/dash.svg')), '')
        btn2.setFixedSize(20, 20)
        btn2.clicked.connect(self.delete_items)
        btn3 = QPushButton(
            QIcon(utils.resource_path('assets/icons/trashcan.svg')), '')
        btn3.setFixedSize(20, 20)
        btn3.clicked.connect(self.clear_list)
        h_box.addWidget(self.btn1)
        h_box.addWidget(btn2)
        h_box.addSpacerItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Preferred))
        h_box.addWidget(btn3)
        # header.setLayout(h_box)
        # header.setFixedHeight(25)
        # v_box.addWidget(header)
        v_box.addLayout(h_box)
        self.setLayout(v_box)

        self._bold_font = QFont(self._breakpoints_list.font())
        self._bold_font.setBold(True)

        shortcut_addnative = QShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_N), self._app_window,
            self._on_add_native_breakpoint)
        shortcut_addnative.setAutoRepeat(False)

        shortcut_addjava = QShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_J), self._app_window,
            self._on_add_java_breakpoint)
        shortcut_addjava.setAutoRepeat(False)

        shortcut_add_native_onload = QShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_O), self._app_window,
            self._on_add_module_initialization_breakpoint)
        shortcut_add_native_onload.setAutoRepeat(False)

        # new menu
        self.new_menu = QMenu('New')
        self.new_menu.addAction('Native', self._on_add_native_breakpoint)
        self.new_menu.addAction('Module initialization', self._on_add_module_initialization_breakpoint)
Ejemplo n.º 54
0
 def clearKeySequence(self):
     self.key_sequence = QKeySequence()
     self.updateText()