Beispiel #1
0
 def key_press_event(self, ev, which=0):
     code = ev.key()
     if self.capture == 0 or code in (
         0,
         Qt.Key_unknown,
         Qt.Key_Shift,
         Qt.Key_Control,
         Qt.Key_Alt,
         Qt.Key_Meta,
         Qt.Key_AltGr,
         Qt.Key_CapsLock,
         Qt.Key_NumLock,
         Qt.Key_ScrollLock,
     ):
         return QWidget.keyPressEvent(self, ev)
     button = getattr(self, "button%d" % which)
     font = QFont()
     button.setFont(font)
     sequence = QKeySequence(code | (int(ev.modifiers()) & ~Qt.KeypadModifier))
     button.setText(sequence.toString(QKeySequence.NativeText))
     self.capture = 0
     setattr(self, "shortcut%d" % which, sequence)
     dup_desc = self.dup_check(sequence, self.key)
     if dup_desc is not None:
         error_dialog(
             self,
             _("Already assigned"),
             unicode(sequence.toString(QKeySequence.NativeText)) + " " + _("already assigned to") + " " + dup_desc,
             show=True,
         )
         self.clear_clicked(which=which)
Beispiel #2
0
 def key_press_event(self, ev, which=0):
     code = ev.key()
     if self.capture == 0 or code in (0, Qt.Key_unknown,
             Qt.Key_Shift, Qt.Key_Control, Qt.Key_Alt, Qt.Key_Meta,
             Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock, Qt.Key_ScrollLock):
         return QWidget.keyPressEvent(self, ev)
     button = getattr(self, 'button%d'%which)
     button.setStyleSheet('QPushButton { font-weight: normal}')
     mods = int(ev.modifiers()) & ~Qt.KeypadModifier
     # for some reason qt sometimes produces ascii control codes in text,
     # for example ctrl+shift+u will give text == '\x15' on linux
     txt = clean_ascii_chars(ev.text())
     if txt and txt.lower() == txt.upper():
         # We have a symbol like ! or > etc. In this case the value of code
         # already includes Shift, so remove it
         mods &= ~Qt.ShiftModifier
     sequence = QKeySequence(code|mods)
     button.setText(sequence.toString(QKeySequence.NativeText))
     self.capture = 0
     dup_desc = self.dup_check(sequence)
     if dup_desc is not None:
         error_dialog(self, _('Already assigned'),
                 unicode(sequence.toString(QKeySequence.NativeText)) + ' ' +
                 _('already assigned to') + ' ' + dup_desc, show=True)
         self.clear_clicked(which=which)
Beispiel #3
0
 def get_match(self, event_or_sequence, ignore=tuple()):
     q = event_or_sequence
     if isinstance(q, QKeyEvent):
         q = QKeySequence(q.key() | (int(q.modifiers()) & ~Qt.KeypadModifier))
     for key in self.order:
         if key not in ignore:
             for seq in self.get_sequences(key):
                 if seq.matches(q) == QKeySequence.ExactMatch:
                     return key
     return None
Beispiel #4
0
def keysequence_from_event(ev):  # {{{
    k, mods = ev.key(), int(ev.modifiers())
    if k in (
            0, Qt.Key_unknown, Qt.Key_Shift, Qt.Key_Control, Qt.Key_Alt,
            Qt.Key_Meta, Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock,
            Qt.Key_ScrollLock):
        return
    letter = QKeySequence(k).toString(QKeySequence.PortableText)
    if mods & Qt.SHIFT and letter.lower() == letter.upper():
        # Something like Shift+* or Shift+> we have to remove the shift,
        # since it is included in keycode.
        mods = mods & ~Qt.SHIFT
    return QKeySequence(k | mods)
Beispiel #5
0
 def custom_keys(self):
     if self.use_default.isChecked():
         return None
     ans = []
     for which in (1, 2):
         button = getattr(self, 'button%d'%which)
         t = unicode(button.text())
         if t == _('None'):
             continue
         ks = QKeySequence(t, QKeySequence.NativeText)
         if not ks.isEmpty():
             ans.append(ks)
     return tuple(ans)
Beispiel #6
0
 def key_press_event(self, ev, which=0):
     code = ev.key()
     if self.capture == 0 or code in (0, Qt.Key_unknown,
             Qt.Key_Shift, Qt.Key_Control, Qt.Key_Alt, Qt.Key_Meta,
             Qt.Key_AltGr, Qt.Key_CapsLock, Qt.Key_NumLock, Qt.Key_ScrollLock):
         return QWidget.keyPressEvent(self, ev)
     sequence = QKeySequence(code|(int(ev.modifiers())&~Qt.KeypadModifier))
     setattr(self, 'shortcut%d'%which, sequence)
     self.clear_button(which)
     self.capture = 0
     dup_desc = self.dup_check(sequence, self.key)
     if dup_desc is not None:
         error_dialog(self, _('Already assigned'),
                 unicode_type(sequence.toString(QKeySequence.NativeText)) + ' ' +
                 _('already assigned to') + ' ' + dup_desc, show=True)
         self.clear_clicked(which=which)
Beispiel #7
0
 def setEditorData(self, editor, index):
     defs = index.data(DEFAULTS)
     defs = _(" or ").join([unicode(x.toString(x.NativeText)) for x in defs])
     editor.key = unicode(index.data(KEY))
     editor.default_shortcuts.setText(_("&Default") + ": %s" % defs)
     editor.default_shortcuts.setChecked(True)
     editor.header.setText("<b>%s: %s</b>" % (_("Customize shortcuts for"), unicode(index.data(DESCRIPTION))))
     custom = index.data(CUSTOM)
     if custom:
         editor.custom.setChecked(True)
         for x in (0, 1):
             button = getattr(editor, "button%d" % (x + 1))
             if len(custom) > x:
                 seq = QKeySequence(custom[x])
                 button.setText(seq.toString(seq.NativeText))
                 setattr(editor, "shortcut%d" % (x + 1), seq)
Beispiel #8
0
    def init_search_box_mixin(self):
        self.search.initialize('main_search_history', colorize=True,
                help_text=_('Search (For Advanced Search click the button to the left)'))
        self.search.cleared.connect(self.search_box_cleared)
        # Queued so that search.current_text will be correct
        self.search.changed.connect(self.search_box_changed,
                type=Qt.QueuedConnection)
        self.search.focus_to_library.connect(self.focus_to_library)
        self.clear_button.clicked.connect(self.search.clear_clicked)
        self.advanced_search_button.clicked[bool].connect(self.do_advanced_search)

        self.search.clear()
        self.search.setMaximumWidth(self.width()-150)
        self.action_focus_search = QAction(self)
        shortcuts = list(
                map(lambda x:unicode(x.toString(QKeySequence.PortableText)),
                QKeySequence.keyBindings(QKeySequence.Find)))
        shortcuts += ['/', 'Alt+S']
        self.keyboard.register_shortcut('start search', _('Start search'),
                default_keys=shortcuts, action=self.action_focus_search)
        self.action_focus_search.triggered.connect(self.focus_search_box)
        self.addAction(self.action_focus_search)
        self.search.setStatusTip(re.sub(r'<\w+>', ' ',
            unicode(self.search.toolTip())))
        self.advanced_search_button.setStatusTip(self.advanced_search_button.toolTip())
        self.clear_button.setStatusTip(self.clear_button.toolTip())
        self.set_highlight_only_button_icon()
        self.highlight_only_button.clicked.connect(self.highlight_only_clicked)
        tt = _('Enable or disable search highlighting.') + '<br><br>'
        tt += config.help('highlight_search_matches')
        self.highlight_only_button.setToolTip(tt)
Beispiel #9
0
def finalize(shortcuts, custom_keys_map={}):  # {{{
    '''
    Resolve conflicts and assign keys to every action in shortcuts, which must
    be a OrderedDict. User specified mappings of unique names to keys (as a
    list of strings) should be passed in in custom_keys_map. Return a mapping
    of unique names to resolved keys. Also sets the set_to_default member
    correctly for each shortcut.
    '''
    seen, keys_map = {}, {}
    for unique_name, shortcut in shortcuts.iteritems():
        ac = shortcut['action']
        if ac is None or sip.isdeleted(ac):
            if ac is not None and DEBUG:
                prints('Shortcut %r has a deleted action' % unique_name)
            continue
        custom_keys = custom_keys_map.get(unique_name, None)
        if custom_keys is None:
            candidates = shortcut['default_keys']
            shortcut['set_to_default'] = True
        else:
            candidates = custom_keys
            shortcut['set_to_default'] = False
        keys = []
        for x in candidates:
            ks = QKeySequence(x, QKeySequence.PortableText)
            x = unicode(ks.toString(QKeySequence.PortableText))
            if x in seen:
                if DEBUG:
                    prints('Key %r for shortcut %s is already used by'
                            ' %s, ignoring'%(x, shortcut['name'], seen[x]['name']))
                keys_map[unique_name] = ()
                continue
            seen[x] = shortcut
            keys.append(ks)
        keys = tuple(keys)

        keys_map[unique_name] = keys
        ac.setShortcuts(list(keys))

    return keys_map
Beispiel #10
0
def finalize(shortcuts, custom_keys_map={}):  # {{{
    '''
    Resolve conflicts and assign keys to every action in shorcuts, which must
    be a OrderedDict. User specified mappings of unique names to keys (as a
    list of strings) should be passed in in custom_keys_map. Return a mapping
    of unique names to resolved keys. Also sets the set_to_default member
    correctly for each shortcut.
    '''
    seen, keys_map = {}, {}
    for unique_name, shortcut in shortcuts.iteritems():
        custom_keys = custom_keys_map.get(unique_name, None)
        if custom_keys is None:
            candidates = shortcut['default_keys']
            shortcut['set_to_default'] = True
        else:
            candidates = custom_keys
            shortcut['set_to_default'] = False
        keys = []
        for x in candidates:
            ks = QKeySequence(x, QKeySequence.PortableText)
            x = unicode(ks.toString(QKeySequence.PortableText))
            if x in seen:
                if DEBUG:
                    prints('Key %r for shortcut %s is already used by'
                           ' %s, ignoring' %
                           (x, shortcut['name'], seen[x]['name']))
                keys_map[unique_name] = ()
                continue
            seen[x] = shortcut
            keys.append(ks)
        keys = tuple(keys)
        #print (111111, unique_name, candidates, keys)

        keys_map[unique_name] = keys
        ac = shortcut['action']
        if ac is not None:
            ac.setShortcuts(list(keys))

    return keys_map
Beispiel #11
0
 def key_press_event(self, ev, which=0):
     code = ev.key()
     if self.capture == 0 or code in (0, Qt.Key_unknown, Qt.Key_Shift,
                                      Qt.Key_Control, Qt.Key_Alt,
                                      Qt.Key_Meta, Qt.Key_AltGr,
                                      Qt.Key_CapsLock, Qt.Key_NumLock,
                                      Qt.Key_ScrollLock):
         return QWidget.keyPressEvent(self, ev)
     sequence = QKeySequence(code
                             | (int(ev.modifiers()) & (~Qt.KeypadModifier)))
     setattr(self, 'shortcut%d' % which, sequence)
     self.clear_button(which)
     self.capture = 0
     dup_desc = self.dup_check(sequence, self.key)
     if dup_desc is not None:
         error_dialog(
             self,
             _('Already assigned'),
             unicode_type(sequence.toString(QKeySequence.NativeText)) +
             ' ' + _('already assigned to') + ' ' + dup_desc,
             show=True)
         self.clear_clicked(which=which)
Beispiel #12
0
 def setEditorData(self, editor, index):
     defs = index.data(DEFAULTS)
     defs = _(' or ').join([
         unicode_type(x.toString(QKeySequence.SequenceFormat.NativeText))
         for x in defs
     ])
     editor.key = unicode_type(index.data(KEY))
     editor.default_shortcuts.setText(_('&Default') + ': %s' % defs)
     editor.default_shortcuts.setChecked(True)
     editor.header.setText('<b>%s: %s</b>' %
                           (_('Customize shortcuts for'),
                            unicode_type(index.data(DESCRIPTION))))
     custom = index.data(CUSTOM)
     if custom:
         editor.custom.setChecked(True)
         for x in (0, 1):
             button = getattr(editor, 'button%d' % (x + 1))
             if len(custom) > x:
                 seq = QKeySequence(custom[x])
                 button.setText(
                     seq.toString(QKeySequence.SequenceFormat.NativeText))
                 setattr(editor, 'shortcut%d' % (x + 1), seq)
Beispiel #13
0
    def __init__(self, parent, cover_flow):
        QDialog.__init__(self, parent)
        self._layout = QStackedLayout()
        self.setLayout(self._layout)
        self.setWindowTitle(_('Browse by covers'))
        self.layout().addWidget(cover_flow)

        geom = gprefs.get('cover_browser_dialog_geometry', None)
        if not geom or not QApplication.instance().safe_restore_geometry(
                self, geom):
            h, w = available_height() - 60, int(available_width() / 1.5)
            self.resize(w, h)
        self.action_fs_toggle = a = QAction(self)
        self.addAction(a)
        a.setShortcuts([
            QKeySequence('F11', QKeySequence.PortableText),
            QKeySequence('Ctrl+Shift+F', QKeySequence.PortableText)
        ])
        a.triggered.connect(self.toggle_fullscreen)
        self.action_esc_fs = a = QAction(self)
        a.triggered.connect(self.show_normal)
        self.addAction(a)
        a.setShortcuts([QKeySequence('Esc', QKeySequence.PortableText)])

        self.pre_fs_geom = None
        cover_flow.setFocus(Qt.OtherFocusReason)
        self.view_action = a = QAction(self)
        iactions = parent.iactions
        self.addAction(a)
        a.setShortcuts(
            list(iactions['View'].menuless_qaction.shortcuts()) +
            [QKeySequence(Qt.Key_Space)])
        a.triggered.connect(iactions['View'].menuless_qaction.trigger)
        self.sd_action = a = QAction(self)
        self.addAction(a)
        a.setShortcuts(
            list(iactions['Send To Device'].menuless_qaction.shortcuts()))
        a.triggered.connect(
            iactions['Send To Device'].menuless_qaction.trigger)
Beispiel #14
0
        def __init__(self, parent=None):
            super().__init__(parent)
            self.start_offset = None  # will be set by parent
            self.itemDoubleClicked.connect(
                    lambda item: self.popup_event_editor(self.row(item))
                    )

            self.setSelectionMode(self.ContiguousSelection)

            style = self.style()
            self.move_up = QAction(style.standardIcon(QStyle.SP_ArrowUp), 'Move Up', self)
            self.move_up.setShortcut(QKeySequence(Qt.Key_Minus))
            self.move_up.triggered.connect(lambda: self.shift(-1))
            self.addAction(self.move_up)

            self.move_down = QAction(style.standardIcon(QStyle.SP_ArrowDown), 'Move Down', self)
            self.move_down.setShortcut(QKeySequence(Qt.Key_Plus))
            self.move_down.triggered.connect(lambda: self.shift(+1))
            self.addAction(self.move_down)

            copy = QAction(self)
            copy.setShortcut(QKeySequence.Copy)
            copy.triggered.connect(self.copy)
            self.addAction(copy)

            paste = QAction(self)
            paste.setShortcut(QKeySequence.Paste)
            paste.triggered.connect(self.paste)
            self.addAction(paste)

            self.delete = QAction(style.standardIcon(QStyle.SP_TrashIcon), 'Delete', self)
            self.delete.setShortcut(QKeySequence.Delete)
            self.delete.triggered.connect(self.delete_selected)
            self.addAction(self.delete)

            self.new = QAction(style.standardIcon(QStyle.SP_FileIcon), 'Insert Event', self)
            self.new.triggered.connect(lambda: self.insert_event(self.currentRow(), self.NOP.copy()))
            self.addAction(self.new)
Beispiel #15
0
def test():
    setup_for_cli_run()
    app = QApplication([])
    bus = dbus.SessionBus()
    dbus_name = BusName('com.calibre-ebook.TestDBusMenu',
                        bus=bus,
                        do_not_queue=True)
    m = QMenu()
    ac = m.addAction(QIcon(I('window-close.png')), 'Quit', app.quit)
    ac.setShortcut(QKeySequence('Ctrl+Q'))
    menu = DBusMenu('/Menu', bus=bus)
    menu.publish_new_menu(m)
    app.exec_()
    del dbus_name
    def contextMenuEvent(self, event):
        '''
        @param: event QContextMenuEvent
        '''
        if not (self.textInteractionFlags() & Qt.TextSelectableByMouse) and \
                not (self.textInteractionFlags() & Qt.TextSelectableByKeyboard):
            event.ignore()
            return

        menu = QMenu()
        act = menu.addAction(_('Copy'), self._copy)
        act.setShortcut(QKeySequence('Ctrl+C'))
        act.setEnabled(self.hasSelectedText())

        menu.exec_(event.globalPos())
Beispiel #17
0
def key_sequence_to_dbus_shortcut(qks):
    for key in qks:
        if key == -1 or key == Qt.Key_unknown:
            continue
        items = []
        for mod, name in iteritems({Qt.META:'Super', Qt.CTRL:'Control', Qt.ALT:'Alt', Qt.SHIFT:'Shift'}):
            if key & mod == mod:
                items.append(name)
        key &= int(~(Qt.ShiftModifier | Qt.ControlModifier | Qt.AltModifier | Qt.MetaModifier | Qt.KeypadModifier))
        text = QKeySequence(key).toString()
        if text:
            text = {'+':'plus', '-':'minus'}.get(text, text)
            items.append(text)
        if items:
            yield items
Beispiel #18
0
    def __init__(self):
        super().__init__()

        self.initUI()

        self.installEventFilter(self.EventFilter(self))

        self.setFocusPolicy(Qt.WheelFocus)
        self.setTabOrder(self.CmpTable, self.Inspector)
        self.setTabOrder(self.Inspector, self.Selector)
        self.setTabOrder(self.Selector, self.FieldInspector)
        #self.setTabOrder(self.FieldInspector, self.CmpTable)

        #----------------------------------------------------
        #
        #   Application Hotkeys
        #
        self.shortcutLeft = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Left), self)
        self.shortcutRight = QShortcut(QKeySequence(Qt.ALT + Qt.Key_Right),
                                       self)
        self.shortcutLeft.setContext(Qt.ApplicationShortcut)
        self.shortcutRight.setContext(Qt.ApplicationShortcut)
        self.shortcutLeft.activated.connect(self.scroll_left)
        self.shortcutRight.activated.connect(self.scroll_right)
    def __init__(self, view, parent=None):
        '''
        @param: view WebView
        @param: parent QWidget
        '''
        super().__init__(parent)
        self._ui = uic.loadUi('mc/webtab/SearchToolBar.ui', self)
        self._view = view  # WebView
        self._findFlags = QWebEnginePage.FindCaseSensitively  # QWebEnginePage.FindFlags
        self._searchRequests = 0

        self._ui.closeButton.clicked.connect(self.close)
        self._ui.lineEdit.textEdited.connect(self.findNext)
        self._ui.next.clicked.connect(self.findNext)
        self._ui.previous.clicked.connect(self.findPrevious)
        self._ui.caseSensitive.clicked.connect(self.caseSensitivityChanged)

        findNextAction = QShortcut(QKeySequence('F3'), self)
        findNextAction.activated.connect(self.findNext)

        findPreviousAction = QShortcut(QKeySequence('Shift+F3'), self)
        findPreviousAction.activated.connect(self.findPrevious)

        parent.installEventFilter(self)
Beispiel #20
0
    def __init__(self, shortcuts, config_file_base_name, parent=None):
        QAbstractListModel.__init__(self, parent)

        self.descriptions = {}
        for k, v in shortcuts.items():
            self.descriptions[k] = v[-1]
        self.keys = {}
        for k, v in shortcuts.items():
            self.keys[k] = v[0]
        self.order = list(shortcuts)
        self.order.sort(key=lambda x: sort_key(self.descriptions[x]))
        self.sequences = {}
        for k, v in self.keys.items():
            self.sequences[k] = [QKeySequence(x) for x in v]

        self.custom = XMLConfig(config_file_base_name)
Beispiel #21
0
def quickmarks():
    global _quickmarks
    if _quickmarks is None:
        from .utils import parse_url
        _quickmarks = {}
        try:
            with open(os.path.join(config_dir, 'quickmarks'), 'rb') as f:
                for line in f.read().decode('utf-8').splitlines():
                    line = line.strip()
                    if line and not line.startswith('#'):
                        key, url = line.partition(' ')[::2]
                        key = QKeySequence.fromString(key)[0]
                        url = parse_url(url)
                        _quickmarks[key] = url
        except FileNotFoundError:
            pass
    return _quickmarks
Beispiel #22
0
def quickmarks():
    global _quickmarks
    if _quickmarks is None:
        from .utils import parse_url
        _quickmarks = {}
        try:
            with open(os.path.join(config_dir, 'quickmarks'), 'rb') as f:
                for line in f.read().decode('utf-8').splitlines():
                    line = line.strip()
                    if line and not line.startswith('#'):
                        key, url = line.partition(' ')[::2]
                        key = QKeySequence.fromString(key)[0]
                        url = parse_url(url)
                        _quickmarks[key] = url
        except FileNotFoundError:
            pass
    return _quickmarks
Beispiel #23
0
 def contextMenuEvent(self, ev):
     menu = self.createStandardContextMenu()
     for action in menu.actions():
         parts = action.text().split('\t')
         if len(parts) == 2 and QKeySequence(QKeySequence.Paste).toString(QKeySequence.NativeText) in parts[-1]:
             menu.insertAction(action, self.action_paste_and_match_style)
             break
     else:
         menu.addAction(self.action_paste_and_match_style)
     st = self.text()
     if st and st.strip():
         self.create_change_case_menu(menu)
     parent = self._parent()
     if hasattr(parent, 'toolbars_visible'):
         vis = parent.toolbars_visible
         menu.addAction(_('%s toolbars') % (_('Hide') if vis else _('Show')), parent.toggle_toolbars)
     menu.exec_(ev.globalPos())
Beispiel #24
0
    def __init__(self, parent, title, path):
        #super().__init__(parent, Qt.WA_DeleteOnClose )
        super().__init__(parent, Qt.Window)

        self.text_browser = QTextBrowser(self)
        #self.text_browser  = QWebEngineView(self)
        self.back_button = QPushButton('Back', self)
        self.forward_button = QPushButton('Forward', self)
        self.close_button = QPushButton('Close', self)

        self.layout = QVBoxLayout(self)
        self.btn_widget = QWidget(self)
        self.btn_layout = QHBoxLayout(self.btn_widget)
        self.btn_layout.addWidget(self.back_button)
        self.btn_layout.addWidget(self.forward_button)
        self.btn_layout.addStretch(1)
        self.btn_layout.addWidget(self.close_button)

        self.shortcutEscape = QShortcut(QKeySequence(Qt.Key_Escape), self)
        self.shortcutEscape.activated.connect(self.close)

        self.layout.addWidget(self.btn_widget)
        self.layout.addWidget(self.text_browser)

        self.back_button.clicked.connect(self.text_browser.backward)
        self.forward_button.clicked.connect(self.text_browser.forward)
        self.close_button.clicked.connect(self.close)

        self.text_browser.setSearchPaths([os.path.join(resources_path, 'doc')])
        self.text_browser.setSource(QUrl(path))
        #       f = QFont()
        #       f.setPointSize(14)
        #       self.text_browser.setFont(f)

        Settings = QSettings('kicad-tools', 'Schematic Component Manager')

        if Settings.contains('help-window'):
            self.restoreGeometry(Settings.value('help-window'))
            #pos_x, pos_y, width, height = Settings.value('help-window')
        else:
            pos_x, pos_y, width, height = 0, 0, 640, 640
            self.setGeometry(pos_x, pos_y, width, height)

        self.window().setWindowTitle(title)
        self.show()
Beispiel #25
0
    def _setupMenu(self):
        if const.OS_MACOS:
            macMainMenu = None
            if not macMainMenu:
                macMainMenu = MainMenu(self, 0)
                macMainMenu.initMenuBar(QMenuBar(0))
                gVar.app.activeWindowChanged.connect(macMainMenu.setWindow)
            else:
                macMainMenu.setWindow(self)
        else:
            self.setMenuBar(MenuBar(self))
            self._mainMenu = MainMenu(self, self)
            self._mainMenu.initMenuBar(self.menuBar())

        self._mainMenu.initSuperMenu(self._superMenu)

        # Setup other shortcuts
        reloadBypassCacheAction = QShortcut(QKeySequence('Ctrl+F5'), self)
        reloadBypassCacheAction2 = QShortcut(QKeySequence('Ctrl+Shift+R'),
                                             self)
        reloadBypassCacheAction.activated.connect(self.reloadBypassCache)
        reloadBypassCacheAction2.activated.connect(self.reloadBypassCache)

        closeTabAction = QShortcut(QKeySequence('Ctrl+W'), self)
        closeTabAction2 = QShortcut(QKeySequence('Ctrl+F4'), self)

        closeTabAction.activated.connect(self._closeTab)
        closeTabAction2.activated.connect(self._closeTab)

        reloadAction = QShortcut(QKeySequence('Ctrl+R'), self)
        reloadAction.activated.connect(self.reload)

        openLocationAction = QShortcut(QKeySequence('Alt+D'), self)
        openLocationAction.activated.connect(self._openLocation)

        inspectorAction = QShortcut(QKeySequence('F12'), self)
        inspectorAction.activated.connect(self.toggleWebInspector)

        restoreClosedWindow = QShortcut(QKeySequence('Ctrl+Shift+N'), self)
        restoreClosedWindow.activated.connect(
            gVar.app.closedWindowsManager().restoreClosedWindow)
Beispiel #26
0
    def init_search_box_mixin(self):
        self.search.initialize(
            'main_search_history',
            colorize=True,
            help_text=_(
                'Search (For advanced search click the button to the left)'))
        self.search.cleared.connect(self.search_box_cleared)
        # Queued so that search.current_text will be correct
        self.search.changed.connect(self.search_box_changed,
                                    type=Qt.QueuedConnection)
        self.search.focus_to_library.connect(self.focus_to_library)
        self.clear_button.clicked.connect(self.search.clear_clicked)
        self.advanced_search_button.clicked[bool].connect(
            self.do_advanced_search)

        self.search.clear()
        self.search.setMaximumWidth(self.width() - 150)
        self.action_focus_search = QAction(self)
        shortcuts = list(
            map(lambda x: unicode(x.toString(QKeySequence.PortableText)),
                QKeySequence.keyBindings(QKeySequence.Find)))
        shortcuts += ['/', 'Alt+S']
        self.keyboard.register_shortcut('start search',
                                        _('Start search'),
                                        default_keys=shortcuts,
                                        action=self.action_focus_search)
        self.action_focus_search.triggered.connect(self.focus_search_box)
        self.addAction(self.action_focus_search)
        self.search.setStatusTip(
            re.sub(r'<\w+>', ' ', unicode(self.search.toolTip())))
        self.advanced_search_button.setStatusTip(
            self.advanced_search_button.toolTip())
        self.clear_button.setStatusTip(self.clear_button.toolTip())
        self.set_highlight_only_button_icon()
        self.highlight_only_button.clicked.connect(self.highlight_only_clicked)
        tt = _('Enable or disable search highlighting.') + '<br><br>'
        tt += config.help('highlight_search_matches')
        self.highlight_only_button.setToolTip(tt)
        self.highlight_only_action = ac = QAction(self)
        self.addAction(ac), ac.triggered.connect(self.highlight_only_clicked)
        self.keyboard.register_shortcut('highlight search results',
                                        _('Highlight search results'),
                                        action=self.highlight_only_action)
Beispiel #27
0
    def __init__(self, parent):

        #---------------------------------------------------
        super().__init__(parent)
        self.Parent = parent
        #---------------------------------------------------
        Settings = QSettings('kicad-tools', 'Schematic Component Manager')
        if Settings.contains('component-view'):
            CmpViewDict = Settings.value('component-view')
        else:
            CmpViewDict = {
                'C': '$Value, $Footprint',
                'D': '$LibRef',
                'R': '$Value, $Footprint'
            }

        if Settings.contains('component-ignore'):
            IgnoreCmpRefsList = Settings.value('component-ignore')
        else:
            IgnoreCmpRefsList = []

        #---------------------------------------------------
        self.CmpViewTable = self.TCmpViewTable(self, CmpViewDict)
        self.IgnoreCmpList = self.TIgnoreCmpList(self, IgnoreCmpRefsList)
        #---------------------------------------------------
        self.Tabs = QTabWidget(self)
        self.Tabs.addTab(self.CmpViewTable, 'Component View')
        self.Tabs.addTab(self.IgnoreCmpList, 'Ignore Component List')
        #---------------------------------------------------
        self.ButtonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.ButtonBox.accepted.connect(self.save_settings)
        self.ButtonBox.rejected.connect(self.cancel)
        #---------------------------------------------------
        self.Layout = QVBoxLayout(self)
        self.Layout.addWidget(self.Tabs)
        self.Layout.addWidget(self.ButtonBox)
        #---------------------------------------------------
        self.setWindowTitle('Settings')
        self.setModal(True)
        #---------------------------------------------------
        self.shortcutHelp = QShortcut(QKeySequence(Qt.Key_F1), self)
        self.shortcutHelp.activated.connect(self.show_help)
Beispiel #28
0
    def _initializeActions(self):
        for type_, text, shortcut, useCtx, theme in [
            (QWebEnginePage.Undo, _('&Undo'), 'Ctrl+Z', True, 'edit-undo'),
            (QWebEnginePage.Redo, _('&Redo'), 'Ctrl+Shift+Z', True, 'edit-redo'),
            (QWebEnginePage.Cut, _('&Cut'), 'Ctrl+X', True, 'edit-cut'),
            (QWebEnginePage.Copy, _('&Copy'), 'Ctrl+C', True, 'edit-copy'),
            (QWebEnginePage.Paste, _('&Paste'), 'Ctrl+V', True, 'edit-paste'),
            (QWebEnginePage.SelectAll, _('Select All'), 'Ctrl+A', True, 'edit-select-all'),

            (QWebEnginePage.Reload, _('&Reload'), '', False, 'view-refresh'),
            (QWebEnginePage.Stop, _('S&top'), '', False, 'process-stop'),
        ]:
            act = self.pageAction(type_)
            act.setText(text)
            if shortcut:
                act.setShortcut(QKeySequence(shortcut))
            if useCtx:
                act.setShortcutContext(Qt.WidgetWithChildrenShortcut)
            if not useCtx:
                self.addAction(act)
            act.setIcon(QIcon.fromTheme(theme))
Beispiel #29
0
    def __init__(self, logger, opts, parent=None):
        MainWindow.__init__(self, opts, parent)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose)
        self.setWindowTitle(__appname__ + _(' - LRF Viewer'))

        self.logger = logger
        self.opts = opts
        self.create_document()
        self.spin_box_action = self.spin_box = QSpinBox()
        self.tool_bar.addWidget(self.spin_box)
        self.tool_bar.addSeparator()
        self.slider_action = self.slider = QSlider(Qt.Orientation.Horizontal)
        self.tool_bar.addWidget(self.slider)
        self.tool_bar.addSeparator()
        self.search = SearchBox2(self)
        self.search.initialize('lrf_viewer_search_history')
        self.search_action = self.tool_bar.addWidget(self.search)
        self.search.search.connect(self.find)

        self.action_next_page.setShortcuts([QKeySequence.StandardKey.MoveToNextPage, QKeySequence(Qt.Key.Key_Space)])
        self.action_previous_page.setShortcuts([QKeySequence.StandardKey.MoveToPreviousPage, QKeySequence(Qt.Key.Key_Backspace)])
        self.action_next_match.setShortcuts(QKeySequence.StandardKey.FindNext)
        self.addAction(self.action_next_match)
        self.action_next_page.triggered[(bool)].connect(self.next)
        self.action_previous_page.triggered[(bool)].connect(self.previous)
        self.action_back.triggered[(bool)].connect(self.back)
        self.action_forward.triggered[(bool)].connect(self.forward)
        self.action_next_match.triggered[(bool)].connect(self.next_match)
        self.action_open_ebook.triggered[(bool)].connect(self.open_ebook)
        self.action_configure.triggered[(bool)].connect(self.configure)
        self.spin_box.valueChanged[(int)].connect(self.go_to_page)
        self.slider.valueChanged[(int)].connect(self.go_to_page)

        self.graphics_view.setRenderHint(QPainter.RenderHint.Antialiasing, True)
        self.graphics_view.setRenderHint(QPainter.RenderHint.TextAntialiasing, True)
        self.graphics_view.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform, True)

        self.closed = False
Beispiel #30
0
    def init_search_box_mixin(self):
        self.search.initialize(
            "main_search_history",
            colorize=True,
            help_text=_("Search (For Advanced Search click the button to the left)"),
        )
        self.search.cleared.connect(self.search_box_cleared)
        # Queued so that search.current_text will be correct
        self.search.changed.connect(self.search_box_changed, type=Qt.QueuedConnection)
        self.search.focus_to_library.connect(self.focus_to_library)
        self.clear_button.clicked.connect(self.search.clear_clicked)
        self.advanced_search_button.clicked[bool].connect(self.do_advanced_search)

        self.search.clear()
        self.search.setMaximumWidth(self.width() - 150)
        self.action_focus_search = QAction(self)
        shortcuts = list(
            map(lambda x: unicode(x.toString(QKeySequence.PortableText)), QKeySequence.keyBindings(QKeySequence.Find))
        )
        shortcuts += ["/", "Alt+S"]
        self.keyboard.register_shortcut(
            "start search", _("Start search"), default_keys=shortcuts, action=self.action_focus_search
        )
        self.action_focus_search.triggered.connect(self.focus_search_box)
        self.addAction(self.action_focus_search)
        self.search.setStatusTip(re.sub(r"<\w+>", " ", unicode(self.search.toolTip())))
        self.advanced_search_button.setStatusTip(self.advanced_search_button.toolTip())
        self.clear_button.setStatusTip(self.clear_button.toolTip())
        self.set_highlight_only_button_icon()
        self.highlight_only_button.clicked.connect(self.highlight_only_clicked)
        tt = _("Enable or disable search highlighting.") + "<br><br>"
        tt += config.help("highlight_search_matches")
        self.highlight_only_button.setToolTip(tt)
        self.highlight_only_action = ac = QAction(self)
        self.addAction(ac), ac.triggered.connect(self.highlight_only_clicked)
        self.keyboard.register_shortcut(
            "highlight search results", _("Highlight search results"), action=self.highlight_only_action
        )
Beispiel #31
0
 def setZ(self, z, top=False, depthlabel=None, can_raise=True):
     self.image.setZ(z)
     if self._z_markers is None:
         for i, elem in enumerate(self._all_markers):
             elem.setZ(z + i + i)
     # set the depth label, if any
     label = "%s: %s" % (chr(ord('a') + self._number), self.name)
     # label = "%s %s"%(depthlabel,self.name) if depthlabel else self.name
     if top:
         label = "%s: <B>%s</B>" % (chr(ord('a') + self._number), self.name)
     self._wlabel.setText(label)
     # set hotkey
     self._qa_show_rc.setShortcut(Qt.Key_F9 if top else QKeySequence())
     # set raise control
     self._can_raise = can_raise
     self._qa_raise.setVisible(can_raise)
     self._wlock.setVisible(can_raise)
     if can_raise:
         self._wraise.setToolTip(
             "<P>Click here to raise this image to the top. Click on the down-arrow to access the image menu.</P>"
         )
     else:
         self._wraise.setToolTip("<P>Click to access the image menu.</P>")
    def __init__(self, parent=None):
        super().__init__(parent)
        self.ui = None  # Ui::DownloadManager
        self._timer = QBasicTimer()

        self._lastDownloadPath = ''
        self._downloadPath = ''
        self._useNativeDialog = False
        self._isClosing = False
        self._closeOnFinish = False
        self._activeDownloadsCount = 0

        self._useExternalManager = False
        self._externalExecutable = ''
        self._externalArguments = ''

        self._lastDownloadOption = self.NoOption  # DownloadOption

        self._taskbarButton = None  # QPointer<QWinTaskbarButton>

        self._ui = uic.loadUi('mc/downloads/DownloadManager.ui', self)
        self.setWindowFlags(self.windowFlags() ^ Qt.WindowMaximizeButtonHint)
        if const.OS_WIN:
            if QtWin.isCompositionEnabled():  # TODO: ?
                QtWin.extendFrameIntoClientArea(self, -1, -1, -1, -1)
        self._ui.clearButton.setIcon(QIcon.fromTheme('edit-clear'))
        gVar.appTools.centerWidgetOnScreen(self)

        self._ui.clearButton.clicked.connect(self._clearList)

        clearShortcut = QShortcut(QKeySequence('CTRL+L'), self)
        clearShortcut.activated.connect(self._clearList)

        self.loadSettings()

        gVar.appTools.setWmClass('Download Manager', self)
Beispiel #33
0
 def setup_ui(self):
     self.resize(678, 430)
     self.setWindowTitle(_("Add books by ISBN"))
     self.setWindowIcon(QIcon(I('add_book.png')))
     self.l = l = QVBoxLayout(self)
     self.h = h = QHBoxLayout()
     l.addLayout(h)
     self.bb = bb = QDialogButtonBox(
         QDialogButtonBox.Ok | QDialogButtonBox.Cancel, self)
     bb.button(bb.Ok).setShortcut(QKeySequence(Qt.Key_O | Qt.ALT))
     l.addWidget(bb), bb.accepted.connect(self.accept), bb.rejected.connect(
         self.reject)
     self.ll = l = QVBoxLayout()
     h.addLayout(l)
     self.isbn_box = i = QPlainTextEdit(self)
     l.addWidget(i)
     self.paste_button = b = QPushButton(_("&Paste from clipboard"), self)
     l.addWidget(b), b.clicked.connect(self.paste)
     self.lll = l = QVBoxLayout()
     h.addLayout(l)
     self.label = la = QLabel(
         _("<p>Enter a list of ISBNs in the box to the left, one per line. calibre will automatically"
           " create entries for books based on the ISBN and download metadata and covers for them.</p>\n"
           "<p>Any invalid ISBNs in the list will be ignored.</p>\n"
           "<p>You can also specify a file that will be added with each ISBN. To do this enter the full"
           " path to the file after a <code>>></code>.  For example:</p>\n"
           "<p><code>9788842915232 >> %s</code></p>"), self)
     l.addWidget(la), la.setWordWrap(True)
     l.addSpacing(20)
     self.la2 = la = QLabel(_("&Tags to set on created book entries:"),
                            self)
     l.addWidget(la)
     self.add_tags = le = QLineEdit(self)
     la.setBuddy(le)
     l.addWidget(le)
     l.addStretch(10)
Beispiel #34
0
    def initialize(self, shortcut, all_shortcuts):
        self.header.setText('<b>%s: %s</b>' %
                            (_('Customize'), shortcut['name']))
        self.all_shortcuts = all_shortcuts
        self.shortcut = shortcut

        self.default_keys = [
            QKeySequence(k, QKeySequence.SequenceFormat.PortableText)
            for k in shortcut['default_keys']
        ]
        self.current_keys = list(shortcut['keys'])
        default = ', '.join([
            unicode_type(k.toString(QKeySequence.SequenceFormat.NativeText))
            for k in self.default_keys
        ])
        if not default:
            default = _('None')
        current = ', '.join([
            unicode_type(k.toString(QKeySequence.SequenceFormat.NativeText))
            for k in self.current_keys
        ])
        if not current:
            current = _('None')

        self.use_default.setText(
            _('&Default: %(deflt)s [Currently not conflicting: %(curr)s]') %
            dict(deflt=default, curr=current))

        if shortcut['set_to_default']:
            self.use_default.setChecked(True)
        else:
            self.use_custom.setChecked(True)
            for key, which in zip(self.current_keys, [1, 2]):
                button = getattr(self, 'button%d' % which)
                button.setText(
                    key.toString(QKeySequence.SequenceFormat.NativeText))
Beispiel #35
0
    def __init__(self, parent=None):
        QWebView.__init__(self, parent)
        self.base_url = None
        self._parent = weakref.ref(parent)
        self.readonly = False

        self.comments_pat = re.compile(r'<!--.*?-->', re.DOTALL)

        extra_shortcuts = {
            'ToggleBold': 'Bold',
            'ToggleItalic': 'Italic',
            'ToggleUnderline': 'Underline',
        }

        for wac, name, icon, text, checkable in [
            ('ToggleBold', 'bold', 'format-text-bold', _('Bold'), True),
            ('ToggleItalic', 'italic', 'format-text-italic', _('Italic'),
             True),
            ('ToggleUnderline', 'underline', 'format-text-underline',
             _('Underline'), True),
            ('ToggleStrikethrough', 'strikethrough',
             'format-text-strikethrough', _('Strikethrough'), True),
            ('ToggleSuperscript', 'superscript', 'format-text-superscript',
             _('Superscript'), True),
            ('ToggleSubscript', 'subscript', 'format-text-subscript',
             _('Subscript'), True),
            ('InsertOrderedList', 'ordered_list', 'format-list-ordered',
             _('Ordered list'), True),
            ('InsertUnorderedList', 'unordered_list', 'format-list-unordered',
             _('Unordered list'), True),
            ('AlignLeft', 'align_left', 'format-justify-left', _('Align left'),
             False),
            ('AlignCenter', 'align_center', 'format-justify-center',
             _('Align center'), False),
            ('AlignRight', 'align_right', 'format-justify-right',
             _('Align right'), False),
            ('AlignJustified', 'align_justified', 'format-justify-fill',
             _('Align justified'), False),
            ('Undo', 'undo', 'edit-undo', _('Undo'), False),
            ('Redo', 'redo', 'edit-redo', _('Redo'), False),
            ('RemoveFormat', 'remove_format', 'edit-clear',
             _('Remove formatting'), False),
            ('Copy', 'copy', 'edit-copy', _('Copy'), False),
            ('Paste', 'paste', 'edit-paste', _('Paste'), False),
            ('Cut', 'cut', 'edit-cut', _('Cut'), False),
            ('Indent', 'indent', 'format-indent-more',
             _('Increase indentation'), False),
            ('Outdent', 'outdent', 'format-indent-less',
             _('Decrease indentation'), False),
            ('SelectAll', 'select_all', 'edit-select-all', _('Select all'),
             False),
        ]:
            ac = PageAction(wac, icon, text, checkable, self)
            setattr(self, 'action_' + name, ac)
            ss = extra_shortcuts.get(wac, None)
            if ss:
                ac.setShortcut(QKeySequence(getattr(QKeySequence, ss)))
            if wac == 'RemoveFormat':
                ac.triggered.connect(self.remove_format_cleanup,
                                     type=Qt.QueuedConnection)

        self.action_color = QAction(QIcon(I('format-text-color.png')),
                                    _('Foreground color'), self)
        self.action_color.triggered.connect(self.foreground_color)

        self.action_background = QAction(QIcon(I('format-fill-color.png')),
                                         _('Background color'), self)
        self.action_background.triggered.connect(self.background_color)

        self.action_block_style = QAction(QIcon(I('format-text-heading.png')),
                                          _('Style text block'), self)
        self.action_block_style.setToolTip(_('Style the selected text block'))
        self.block_style_menu = QMenu(self)
        self.action_block_style.setMenu(self.block_style_menu)
        self.block_style_actions = []
        for text, name in [
            (_('Normal'), 'p'),
            (_('Heading') + ' 1', 'h1'),
            (_('Heading') + ' 2', 'h2'),
            (_('Heading') + ' 3', 'h3'),
            (_('Heading') + ' 4', 'h4'),
            (_('Heading') + ' 5', 'h5'),
            (_('Heading') + ' 6', 'h6'),
            (_('Pre-formatted'), 'pre'),
            (_('Blockquote'), 'blockquote'),
            (_('Address'), 'address'),
        ]:
            ac = BlockStyleAction(text, name, self)
            self.block_style_menu.addAction(ac)
            self.block_style_actions.append(ac)

        self.action_insert_link = QAction(QIcon(I('insert-link.png')),
                                          _('Insert link or image'), self)
        self.action_insert_hr = QAction(QIcon(I('format-text-hr.png')),
                                        _('Insert separator'), self)
        self.action_insert_link.triggered.connect(self.insert_link)
        self.action_insert_hr.triggered.connect(self.insert_hr)
        self.pageAction(QWebPage.ToggleBold).changed.connect(
            self.update_link_action)
        self.action_insert_link.setEnabled(False)
        self.action_insert_hr.setEnabled(False)
        self.action_clear = QAction(QIcon(I('trash.png')), _('Clear'), self)
        self.action_clear.triggered.connect(self.clear_text)

        self.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.page().linkClicked.connect(self.link_clicked)
        secure_web_page(self.page().settings())

        self.setHtml('')
        self.set_readonly(False)
        self.page().contentsChanged.connect(self.data_changed)
Beispiel #36
0
 def debug_event(self, ev):
     from calibre.gui2 import event_type_name
     print('Event:', event_type_name(ev))
     if ev.type() in (ev.KeyPress, ev.ShortcutOverride, ev.KeyRelease):
         print('\tkey:', QKeySequence(ev.key()).toString())
Beispiel #37
0
    def __init__(self, parent, view, row, link_delegate):
        QDialog.__init__(self, parent)
        self.normal_brush = QBrush(Qt.white)
        self.marked_brush = QBrush(Qt.lightGray)
        self.marked = None
        self.gui = parent
        self.splitter = QSplitter(self)
        self._l = l = QVBoxLayout(self)
        self.setLayout(l)
        l.addWidget(self.splitter)

        self.cover = CoverView(self, show_size=gprefs['bd_overlay_cover_size'])
        self.cover.resizeEvent = self.cover_view_resized
        self.cover.cover_changed.connect(self.cover_changed)
        self.cover_pixmap = None
        self.cover.sizeHint = self.details_size_hint
        self.splitter.addWidget(self.cover)

        self.details = Details(parent.book_details.book_info, self)
        self.details.anchor_clicked.connect(self.on_link_clicked)
        self.link_delegate = link_delegate
        self.details.setAttribute(Qt.WA_OpaquePaintEvent, False)
        palette = self.details.palette()
        self.details.setAcceptDrops(False)
        palette.setBrush(QPalette.Base, Qt.transparent)
        self.details.setPalette(palette)

        self.c = QWidget(self)
        self.c.l = l2 = QGridLayout(self.c)
        l2.setContentsMargins(0, 0, 0, 0)
        self.c.setLayout(l2)
        l2.addWidget(self.details, 0, 0, 1, -1)
        self.splitter.addWidget(self.c)

        self.fit_cover = QCheckBox(_('Fit &cover within view'), self)
        self.fit_cover.setChecked(
            gprefs.get('book_info_dialog_fit_cover', True))
        self.hl = hl = QHBoxLayout()
        hl.setContentsMargins(0, 0, 0, 0)
        l2.addLayout(hl, l2.rowCount(), 0, 1, -1)
        hl.addWidget(self.fit_cover), hl.addStretch()
        self.clabel = QLabel(
            '<div style="text-align: right"><a href="calibre:conf" title="{}" style="text-decoration: none">{}</a>'
            .format(_('Configure this view'), _('Configure')))
        self.clabel.linkActivated.connect(self.configure)
        hl.addWidget(self.clabel)
        self.previous_button = QPushButton(QIcon(I('previous.png')),
                                           _('&Previous'), self)
        self.previous_button.clicked.connect(self.previous)
        l2.addWidget(self.previous_button, l2.rowCount(), 0)
        self.next_button = QPushButton(QIcon(I('next.png')), _('&Next'), self)
        self.next_button.clicked.connect(self.next)
        l2.addWidget(self.next_button, l2.rowCount() - 1, 1)

        self.view = view
        self.current_row = None
        self.refresh(row)
        self.view.model().new_bookdisplay_data.connect(self.slave)
        self.fit_cover.stateChanged.connect(self.toggle_cover_fit)
        self.ns = QShortcut(QKeySequence('Alt+Right'), self)
        self.ns.activated.connect(self.next)
        self.ps = QShortcut(QKeySequence('Alt+Left'), self)
        self.ps.activated.connect(self.previous)
        self.next_button.setToolTip(
            _('Next [%s]') %
            unicode_type(self.ns.key().toString(QKeySequence.NativeText)))
        self.previous_button.setToolTip(
            _('Previous [%s]') %
            unicode_type(self.ps.key().toString(QKeySequence.NativeText)))

        geom = QCoreApplication.instance().desktop().availableGeometry(self)
        screen_height = geom.height() - 100
        screen_width = geom.width() - 100
        self.resize(max(int(screen_width / 2), 700), screen_height)
        saved_layout = gprefs.get('book_info_dialog_layout', None)
        if saved_layout is not None:
            try:
                self.restoreGeometry(saved_layout[0])
                self.splitter.restoreState(saved_layout[1])
            except Exception:
                pass
Beispiel #38
0
    def __init__(self):
        QWidget.__init__(self, None)
        # Set pixmaps resource before Main Window initialized
        self._resource = os.path.join(ctx.consts.theme_dir, ctx.flags.theme,
                                      ctx.consts.pixmaps_resource_file)
        if os.path.exists(self._resource):
            resource = QResource()
            resource.registerResource(self._resource)
        else:
            raise yali.Error, _("Pixmaps resources file doesn't exists")

        self.ui = Ui_YaliMain()
        self.ui.setupUi(self)

        self.font = 10
        self.animation_type = None

        self.screens = None
        self.screens_content = None

        self.pds_helper = HelpWidget(self.ui.scrollAreaWidgetContents)

        # shortcut to open help
        self.help_shortcut = QShortcut(QKeySequence(Qt.Key_F1), self)

        # shortcut to open debug window
        #self.debugShortCut = QtWidgets.QShortcut(QtWidgets.QKeySequence(Qt.Key_F2),self)

        # something funny
        self.tetris_shortcut = QShortcut(QKeySequence(Qt.Key_F6), self)
        self.cursor_shortcut = QShortcut(QKeySequence(Qt.Key_F7), self)
        self.theme_shortcut = QShortcut(QKeySequence(Qt.Key_F8), self)

        # shortcut to open a console
        self.console_shortcut = QShortcut(QKeySequence(Qt.Key_F11), self)

        # set style
        self._style = os.path.join(ctx.consts.theme_dir, ctx.flags.theme,
                                   ctx.consts.style_file)
        if os.path.exists(self._style):
            self.updateStyle()
        else:
            raise yali.Error, _("Style file doesn't exists")

        # set screens content
        release_file = os.path.join(ctx.consts.branding_dir,
                                    ctx.flags.branding,
                                    ctx.consts.release_file)
        if os.path.exists(release_file):
            self.screens_content = yali.util.parse_branding_screens(
                release_file)
        else:
            raise yali.Error, _("Release file doesn't exists")

        # move one step at a time
        self.step_increment = 1

        # ToolButton Popup Menu
        self.menu = QMenu()
        self.shutdown = self.menu.addAction(
            QIcon(QPixmap(":/images/system-shutdown.png")),
            _("Turn Off Computer"))
        self.reboot = self.menu.addAction(
            QIcon(QPixmap(":/images/system-reboot.png")),
            _("Restart Computer"))
        self.restart = self.menu.addAction(
            QIcon(QPixmap(":/images/system-yali-reboot.png")),
            _("Restart YALI"))
        #self.menu.setDefaultAction(self.shutdown)
        self.ui.system_menu.setMenu(self.menu)
        self.ui.system_menu.setDefaultAction(self.shutdown)

        # Main Slots
        self.help_shortcut.activated.connect(self.pds_helper.toggleHelp)
        #self.debugShortCut.activated.connect(self.toggleDebug)
        self.console_shortcut.activated.connect(self.toggleConsole)
        self.cursor_shortcut.activated.connect(self.toggleCursor)
        self.theme_shortcut.activated.connect(self.toggleTheme)
        self.tetris_shortcut.activated.connect(self.toggleTetris)
        self.ui.buttonNext.clicked.connect(self.slotNext)
        self.ui.buttonBack.clicked.connect(self.slotBack)
        self.ui.toggleHelp.clicked.connect(self.pds_helper.toggleHelp)
        if not ctx.flags.install_type == ctx.STEP_FIRST_BOOT:
            self.ui.releaseNotes.clicked.connect(self.showReleaseNotes)
        else:
            self.ui.releaseNotes.hide()
        self.menu.triggered[QAction].connect(self.slotMenu)

        self.cmb = _("right")
        self.dont_ask_again = False
        self.terminal = None
        self.tetris = None

        self.ui.helpContentFrame.hide()

        self.effect = QGraphicsOpacityEffect(self)
        self.ui.mainStack.setGraphicsEffect(self.effect)
        self.effect.setOpacity(1.0)

        self.anime = QTimer(self)
        self.anime.timeout.connect(self.animate)
Beispiel #39
0
def access_key(k):
    'Return shortcut text suitable for adding to a menu item'
    if QKeySequence.keyBindings(k):
        return '\t' + QKeySequence(k).toString(QKeySequence.NativeText)
    return ''
Beispiel #40
0
    def __init__(self,
                 ids,
                 get_metadata,
                 field_metadata,
                 parent=None,
                 window_title=None,
                 reject_button_tooltip=None,
                 accept_all_tooltip=None,
                 reject_all_tooltip=None,
                 revert_tooltip=None,
                 intro_msg=None,
                 action_button=None,
                 **kwargs):
        QDialog.__init__(self, parent)
        self.l = l = QVBoxLayout()
        self.setLayout(l)
        self.setWindowIcon(QIcon(I('auto_author_sort.png')))
        self.get_metadata = get_metadata
        self.ids = list(ids)
        self.total = len(self.ids)
        self.accepted = OrderedDict()
        self.rejected_ids = set()
        self.window_title = window_title or _('Compare metadata')

        if intro_msg:
            self.la = la = QLabel(intro_msg)
            la.setWordWrap(True)
            l.addWidget(la)

        self.compare_widget = CompareSingle(field_metadata,
                                            parent=parent,
                                            revert_tooltip=revert_tooltip,
                                            **kwargs)
        self.sa = sa = QScrollArea()
        l.addWidget(sa)
        sa.setWidget(self.compare_widget)
        sa.setWidgetResizable(True)

        self.bb = bb = QDialogButtonBox(QDialogButtonBox.Cancel)
        bb.button(bb.Cancel).setAutoDefault(False)
        bb.rejected.connect(self.reject)
        if self.total > 1:
            self.aarb = b = bb.addButton(_('&Accept all remaining'),
                                         bb.YesRole)
            b.setIcon(QIcon(I('ok.png'))), b.setAutoDefault(False)
            if accept_all_tooltip:
                b.setToolTip(accept_all_tooltip)
            b.clicked.connect(self.accept_all_remaining)
            self.rarb = b = bb.addButton(_('Re&ject all remaining'), bb.NoRole)
            b.setIcon(QIcon(I('minus.png'))), b.setAutoDefault(False)
            if reject_all_tooltip:
                b.setToolTip(reject_all_tooltip)
            b.clicked.connect(self.reject_all_remaining)
            self.sb = b = bb.addButton(_('&Reject'), bb.ActionRole)
            b.clicked.connect(partial(self.next_item, False))
            b.setIcon(QIcon(I('minus.png'))), b.setAutoDefault(False)
            if reject_button_tooltip:
                b.setToolTip(reject_button_tooltip)
            self.next_action = ac = QAction(self)
            ac.setShortcut(QKeySequence(Qt.ALT | Qt.Key_Right))
            self.addAction(ac)
        if action_button is not None:
            self.acb = b = bb.addButton(action_button[0], bb.ActionRole)
            b.setIcon(QIcon(action_button[1]))
            self.action_button_action = action_button[2]
            b.clicked.connect(self.action_button_clicked)
        self.nb = b = bb.addButton(
            _('&Next') if self.total > 1 else _('&OK'), bb.ActionRole)
        if self.total > 1:
            b.setToolTip(
                _('Move to next [%s]') %
                self.next_action.shortcut().toString(QKeySequence.NativeText))
            self.next_action.triggered.connect(b.click)
        b.setIcon(QIcon(I('forward.png' if self.total > 1 else 'ok.png')))
        b.clicked.connect(partial(self.next_item, True))
        b.setDefault(True), b.setAutoDefault(True)
        self.bbh = h = QHBoxLayout()
        h.setContentsMargins(0, 0, 0, 0)
        l.addLayout(h)
        self.markq = m = QCheckBox(_('&Mark rejected books'))
        m.setChecked(gprefs['metadata_diff_mark_rejected'])
        m.stateChanged[int].connect(
            lambda: gprefs.set('metadata_diff_mark_rejected', m.isChecked()))
        m.setToolTip(
            _('Mark rejected books in the book list after this dialog is closed'
              ))
        h.addWidget(m), h.addWidget(bb)

        self.next_item(True)

        desktop = QApplication.instance().desktop()
        geom = desktop.availableGeometry(parent or self)
        width = max(700, min(950, geom.width() - 50))
        height = max(650, min(1000, geom.height() - 100))
        self.resize(QSize(width, height))
        geom = gprefs.get('diff_dialog_geom', None)
        if geom is not None:
            self.restoreGeometry(geom)
        b.setFocus(Qt.OtherFocusReason)
Beispiel #41
0
 def get_keys(x):
     if isinstance(x, str):
         x = [x]
     for k in x:
         if isinstance(k, str):
             yield QKeySequence.fromString(k)[0]
Beispiel #42
0
 def key(k):
     sc = unicode(
         QKeySequence(k | Qt.CTRL).toString(QKeySequence.NativeText))
     return ' [%s]' % sc
Beispiel #43
0
def access_key(k):
    'Return shortcut text suitable for adding to a menu item'
    if QKeySequence.keyBindings(k):
        return '\t' + QKeySequence(k).toString(QKeySequence.NativeText)
    return ''