Example #1
0
class DebugDevice(QDialog):
    def __init__(self, gui, parent=None):
        QDialog.__init__(self, parent)
        self.gui = gui
        self._layout = QVBoxLayout(self)
        self.setLayout(self._layout)
        self.log = QPlainTextEdit(self)
        self._layout.addWidget(self.log)
        self.log.setPlainText(
            _('Getting debug information, please wait') + '...')
        self.copy = QPushButton(_('Copy to &clipboard'))
        self.copy.setDefault(True)
        self.setWindowTitle(_('Debug device detection'))
        self.setWindowIcon(QIcon(I('debug.png')))
        self.copy.clicked.connect(self.copy_to_clipboard)
        self.ok = QPushButton('&OK')
        self.ok.setAutoDefault(False)
        self.ok.clicked.connect(self.accept)
        self.bbox = QDialogButtonBox(self)
        self.bbox.addButton(self.copy, QDialogButtonBox.ButtonRole.ActionRole)
        self.bbox.addButton(self.ok, QDialogButtonBox.ButtonRole.AcceptRole)
        self._layout.addWidget(self.bbox)
        self.resize(750, 500)
        self.bbox.setEnabled(False)
        QTimer.singleShot(1000, self.debug)

    def debug(self):
        if self.gui.device_manager.is_device_connected:
            error_dialog(
                self,
                _('Device already detected'),
                _('A device (%s) is already detected by calibre.'
                  ' If you wish to debug the detection of another device'
                  ', first disconnect this device.') %
                self.gui.device_manager.connected_device.get_gui_name(),
                show=True)
            self.bbox.setEnabled(True)
            return
        self.gui.debug_detection(self)

    def __call__(self, job):
        if not self.isVisible():
            return
        self.bbox.setEnabled(True)
        if job.failed:
            return error_dialog(
                self,
                _('Debugging failed'),
                _('Running debug device detection failed. Click Show '
                  'Details for more information.'),
                det_msg=job.details,
                show=True)
        self.log.setPlainText(job.result)

    def copy_to_clipboard(self):
        QApplication.clipboard().setText(self.log.toPlainText())
Example #2
0
class Preferences(QDialog):

    run_wizard_requested = pyqtSignal()

    def __init__(self, gui, initial_plugin=None, close_after_initial=False):
        QDialog.__init__(self, gui)
        self.gui = gui
        self.must_restart = False
        self.do_restart = False
        self.committed = False
        self.close_after_initial = close_after_initial

        self.resize(930, 720)
        nh, nw = min_available_height() - 25, available_width() - 10
        if nh < 0:
            nh = 800
        if nw < 0:
            nw = 600
        nh = min(self.height(), nh)
        nw = min(self.width(), nw)
        self.resize(nw, nh)

        geom = gprefs.get('preferences dialog geometry', None)
        if geom is not None:
            QApplication.instance().safe_restore_geometry(self, geom)

        # Center
        if islinux:
            self.move(gui.rect().center() - self.rect().center())

        self.setWindowModality(Qt.WindowModality.ApplicationModal)
        self.setWindowTitle(__appname__ + ' — ' + _('Preferences'))
        self.setWindowIcon(QIcon(I('config.png')))
        self.l = l = QVBoxLayout(self)

        self.stack = QStackedWidget(self)
        self.bb = QDialogButtonBox(
            QDialogButtonBox.StandardButton.Close
            | QDialogButtonBox.StandardButton.Apply
            | QDialogButtonBox.StandardButton.Cancel
            | QDialogButtonBox.StandardButton.RestoreDefaults)
        self.bb.button(QDialogButtonBox.StandardButton.Apply).clicked.connect(
            self.accept)
        self.bb.button(
            QDialogButtonBox.StandardButton.RestoreDefaults).setIcon(
                QIcon(I('clear_left.png')))
        self.bb.button(
            QDialogButtonBox.StandardButton.RestoreDefaults).clicked.connect(
                self.restore_defaults)
        self.wizard_button = QPushButton(QIcon(I('wizard.png')),
                                         _('Run Welcome &wizard'))
        self.wizard_button.clicked.connect(
            self.run_wizard, type=Qt.ConnectionType.QueuedConnection)
        self.wizard_button.setAutoDefault(False)
        self.bb.rejected.connect(self.reject)
        self.browser = Browser(self)
        self.browser.show_plugin.connect(self.show_plugin)
        self.stack.addWidget(self.browser)
        self.scroll_area = QScrollArea(self)
        self.stack.addWidget(self.scroll_area)
        self.scroll_area.setWidgetResizable(True)

        self.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu)
        self.title_bar = TitleBar(self)
        for ac, tt in [(QDialogButtonBox.StandardButton.Apply,
                        _('Save changes')),
                       (QDialogButtonBox.StandardButton.Cancel,
                        _('Cancel and return to overview'))]:
            self.bb.button(ac).setToolTip(tt)

        l.addWidget(self.title_bar), l.addWidget(self.stack)
        h = QHBoxLayout()
        l.addLayout(h)
        h.addWidget(self.wizard_button), h.addStretch(10), h.addWidget(self.bb)

        if initial_plugin is not None:
            category, name = initial_plugin[:2]
            plugin = get_plugin(category, name)
            if plugin is not None:
                self.show_plugin(plugin)
                if len(initial_plugin) > 2:
                    w = self.findChild(QWidget, initial_plugin[2])
                    if w is not None:
                        for c in self.showing_widget.children():
                            if isinstance(c, QTabWidget):
                                idx = c.indexOf(w)
                                if idx > -1:
                                    c.setCurrentIndex(idx)
                                    break
        else:
            self.hide_plugin()

    def event(self, ev):
        if isinstance(ev, QStatusTipEvent):
            msg = re.sub(r'</?[a-z1-6]+>', ' ', ev.tip())
            self.title_bar.show_msg(msg)
        return QDialog.event(self, ev)

    def run_wizard(self):
        self.run_wizard_requested.emit()
        self.accept()

    def set_tooltips_for_labels(self):
        def process_child(child):
            for g in child.children():
                if isinstance(g, QLabel):
                    buddy = g.buddy()
                    if buddy is not None and hasattr(buddy, 'toolTip'):
                        htext = str(buddy.toolTip()).strip()
                        etext = str(g.toolTip()).strip()
                        if htext and not etext:
                            g.setToolTip(htext)
                            g.setWhatsThis(htext)
                else:
                    process_child(g)

        process_child(self.showing_widget)

    def show_plugin(self, plugin):
        self.showing_widget = plugin.create_widget(self.scroll_area)
        self.showing_widget.genesis(self.gui)
        try:
            self.showing_widget.initialize()
        except AbortInitialize:
            return
        self.set_tooltips_for_labels()
        self.scroll_area.setWidget(self.showing_widget)
        self.stack.setCurrentIndex(1)
        self.showing_widget.show()
        self.setWindowTitle(__appname__ + ' - ' + _('Preferences') + ' - ' +
                            plugin.gui_name)
        self.showing_widget.restart_now.connect(self.restart_now)
        self.title_bar.show_plugin(plugin)
        self.setWindowIcon(QIcon(plugin.icon))

        self.bb.button(QDialogButtonBox.StandardButton.Close).setVisible(False)
        self.wizard_button.setVisible(False)
        for button in (QDialogButtonBox.StandardButton.Apply,
                       QDialogButtonBox.StandardButton.RestoreDefaults,
                       QDialogButtonBox.StandardButton.Cancel):
            button = self.bb.button(button)
            button.setVisible(True)

        self.bb.button(QDialogButtonBox.StandardButton.Apply).setEnabled(False)
        self.bb.button(QDialogButtonBox.StandardButton.Apply).setDefault(
            False), self.bb.button(
                QDialogButtonBox.StandardButton.Apply).setDefault(True)
        self.bb.button(
            QDialogButtonBox.StandardButton.RestoreDefaults).setEnabled(
                self.showing_widget.supports_restoring_to_defaults)
        self.bb.button(
            QDialogButtonBox.StandardButton.RestoreDefaults).setToolTip(
                self.showing_widget.restore_defaults_desc if self.
                showing_widget.supports_restoring_to_defaults else (
                    _('Restoring to defaults not supported for') + ' ' +
                    plugin.gui_name))
        self.bb.button(
            QDialogButtonBox.StandardButton.RestoreDefaults).setText(
                _('Restore &defaults'))
        self.showing_widget.changed_signal.connect(self.changed_signal)

    def changed_signal(self):
        b = self.bb.button(QDialogButtonBox.StandardButton.Apply)
        b.setEnabled(True)

    def hide_plugin(self):
        for sig in 'changed_signal restart_now'.split():
            try:
                getattr(self.showing_widget,
                        sig).disconnect(getattr(self, sig))
            except Exception:
                pass
        self.showing_widget = QWidget(self.scroll_area)
        self.scroll_area.setWidget(self.showing_widget)
        self.setWindowTitle(__appname__ + ' - ' + _('Preferences'))
        self.stack.setCurrentIndex(0)
        self.title_bar.show_plugin()
        self.setWindowIcon(QIcon(I('config.png')))

        for button in (QDialogButtonBox.StandardButton.Apply,
                       QDialogButtonBox.StandardButton.RestoreDefaults,
                       QDialogButtonBox.StandardButton.Cancel):
            button = self.bb.button(button)
            button.setVisible(False)

        self.bb.button(QDialogButtonBox.StandardButton.Close).setVisible(True)
        self.bb.button(QDialogButtonBox.StandardButton.Close).setDefault(
            False), self.bb.button(
                QDialogButtonBox.StandardButton.Close).setDefault(True)
        self.wizard_button.setVisible(True)

    def restart_now(self):
        try:
            self.showing_widget.commit()
        except AbortCommit:
            return
        self.do_restart = True
        self.hide_plugin()
        self.accept()

    def commit(self, *args):
        must_restart = self.showing_widget.commit()
        rc = self.showing_widget.restart_critical
        self.committed = True
        do_restart = False
        if must_restart:
            self.must_restart = True
            msg = _('Some of the changes you made require a restart.'
                    ' Please restart calibre as soon as possible.')
            if rc:
                msg = _('The changes you have made require calibre be '
                        'restarted immediately. You will not be allowed to '
                        'set any more preferences, until you restart.')

            do_restart = show_restart_warning(msg, parent=self)

        self.showing_widget.refresh_gui(self.gui)
        if do_restart:
            self.do_restart = True
        return self.close_after_initial or (must_restart and rc) or do_restart

    def restore_defaults(self, *args):
        self.showing_widget.restore_defaults()

    def on_shutdown(self):
        gprefs.set('preferences dialog geometry',
                   bytearray(self.saveGeometry()))
        if self.committed:
            self.gui.must_restart_before_config = self.must_restart
            self.gui.tags_view.recount()
            self.gui.create_device_menu()
            self.gui.set_device_menu_items_state(
                bool(self.gui.device_connected))
            self.gui.bars_manager.apply_settings()
            self.gui.bars_manager.update_bars()
            self.gui.build_context_menus()

    def accept(self):
        if self.stack.currentIndex() == 0:
            self.on_shutdown()
            return QDialog.accept(self)
        try:
            close = self.commit()
        except AbortCommit:
            return
        if close:
            self.on_shutdown()
            return QDialog.accept(self)
        self.hide_plugin()

    def reject(self):
        if self.stack.currentIndex() == 0 or self.close_after_initial:
            self.on_shutdown()
            return QDialog.reject(self)
        self.hide_plugin()
Example #3
0
class UserDefinedDevice(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self._layout = QVBoxLayout(self)
        self.setLayout(self._layout)
        self.log = QPlainTextEdit(self)
        self._layout.addWidget(self.log)
        self.log.setPlainText(_('Getting device information') + '...')
        self.copy = QPushButton(_('Copy to &clipboard'))
        self.copy.setDefault(True)
        self.setWindowTitle(_('User-defined device information'))
        self.setWindowIcon(QIcon(I('debug.png')))
        self.copy.clicked.connect(self.copy_to_clipboard)
        self.ok = QPushButton('&OK')
        self.ok.setAutoDefault(False)
        self.ok.clicked.connect(self.accept)
        self.bbox = QDialogButtonBox(self)
        self.bbox.addButton(self.copy, QDialogButtonBox.ButtonRole.ActionRole)
        self.bbox.addButton(self.ok, QDialogButtonBox.ButtonRole.AcceptRole)
        self._layout.addWidget(self.bbox)
        self.resize(750, 500)
        self.bbox.setEnabled(False)
        QTimer.singleShot(1000, self.device_info)

    def device_info(self):
        try:
            from calibre.devices import device_info
            r = step_dialog(
                self.parent(), _('Device Detection'),
                _('Ensure your device is disconnected, then press OK'))
            if r:
                self.close()
                return
            before = device_info()
            r = step_dialog(
                self.parent(), _('Device Detection'),
                _('Ensure your device is connected, then press OK'))
            if r:
                self.close()
                return
            after = device_info()
            new_devices = after['device_set'] - before['device_set']
            res = ''
            if len(new_devices) == 1:

                def fmtid(x):
                    x = x or 0
                    if isinstance(x, numbers.Integral):
                        x = hex(x)
                    if not x.startswith('0x'):
                        x = '0x' + x
                    return x

                for d in new_devices:
                    res =  _('USB Vendor ID (in hex)') + ': ' + \
                            fmtid(after['device_details'][d][0]) + '\n'
                    res += _('USB Product ID (in hex)') + ': ' + \
                            fmtid(after['device_details'][d][1]) + '\n'
                    res += _('USB Revision ID (in hex)') + ': ' + \
                            fmtid(after['device_details'][d][2]) + '\n'
            trailer = _(
                'Copy these values to the clipboard, paste them into an '
                'editor, then enter them into the USER_DEVICE by '
                'customizing the device plugin in Preferences->Advanced->Plugins. '
                'Remember to also enter the folders where you want the books to '
                'be put. You must restart calibre for your changes '
                'to take effect.\n')
            self.log.setPlainText(res + '\n\n' + trailer)
        finally:
            self.bbox.setEnabled(True)

    def copy_to_clipboard(self):
        QApplication.clipboard().setText(self.log.toPlainText())