def store_passwd(ok, during_shutdown): if ok == 'never': exclude = gprefs.get('never-store-password-for', {}) exclude[key] = True password_exclusions.set(key, True) elif ok and not during_shutdown: QApplication.instance().store_password(url, username, password)
def eventFilter(self, obj, ev): if ev.type() == ev.MouseMove: if self.cursor_hidden: self.cursor_hidden = False QApplication.instance().restoreOverrideCursor() self.hide_cursor_timer.start() return False
def show_splash_screen(self): self.splash_pixmap = QPixmap() self.splash_pixmap.load(I('library.png')) self.splash_screen = QSplashScreen(self.splash_pixmap) self.splash_screen.showMessage(_('Starting %s: Loading books...') % __appname__) self.splash_screen.show() QApplication.instance().processEvents()
def run_wizard(self, *args): if self.confirm_quit(): self.run_wizard_b4_shutdown = True self.restart_after_quit = True try: self.shutdown(write_settings=False) except: pass QApplication.instance().quit()
def quit(self, checked=True, restart=False, debug_on_restart=False, confirm_quit=True): if confirm_quit and not self.confirm_quit(): return try: self.shutdown() except: pass self.restart_after_quit = restart self.debug_on_restart = debug_on_restart QApplication.instance().quit()
def __init__(self, opts, parent=None, gui_debug=None): MainWindow.__init__(self, opts, parent=parent, disable_automatic_gc=True) self.setWindowIcon(QApplication.instance().windowIcon()) self.jobs_pointer = Pointer(self) self.proceed_requested.connect(self.do_proceed, type=Qt.QueuedConnection) self.proceed_question = ProceedQuestion(self) self.job_error_dialog = JobError(self) self.keyboard = Manager(self) get_gui.ans = self self.opts = opts self.device_connected = None self.gui_debug = gui_debug self.iactions = OrderedDict() # Actions for action in interface_actions(): if opts.ignore_plugins and action.plugin_path is not None: continue try: ac = self.init_iaction(action) except: # Ignore errors in loading user supplied plugins import traceback traceback.print_exc() if action.plugin_path is None: raise continue ac.plugin_path = action.plugin_path ac.interface_action_base_plugin = action self.add_iaction(ac) self.load_store_plugins()
def css(): global _css if _css is None: _css = P('templates/book_details.css', data=True).decode('utf-8') col = QApplication.instance().palette().color(QPalette.Link).name() _css = _css.replace('LINK_COLOR', col) return _css
def ensure_app(headless=True): global _store_app with _ea_lock: if _store_app is None and QApplication.instance() is None: args = sys.argv[:1] if headless and (islinux or isbsd): args += ['-platformpluginpath', sys.extensions_location, '-platform', 'headless'] _store_app = QApplication(args) if headless and (islinux or isbsd): _store_app.headless = True import traceback # This is needed because as of PyQt 5.4 if sys.execpthook == # sys.__excepthook__ PyQt will abort the application on an # unhandled python exception in a slot or virtual method. Since ensure_app() # is used in worker processes for background work like rendering html # or running a headless browser, we circumvent this as I really # dont feel like going through all the code and making sure no # unhandled exceptions ever occur. All the actual GUI apps already # override sys.except_hook with a proper error handler. def eh(t, v, tb): try: traceback.print_exception(t, v, tb, file=sys.stderr) except: pass sys.excepthook = eh
def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, QModelIndex()) theme = index.data(Qt.UserRole) if not theme: return painter.save() pixmap = index.data(Qt.DecorationRole) if pixmap and not pixmap.isNull(): rect = option.rect.adjusted(0, self.SPACING, COVER_SIZE[0] - option.rect.width(), - self.SPACING) painter.drawPixmap(rect, pixmap) if option.state & QStyle.State_Selected: painter.setPen(QPen(QApplication.instance().palette().highlightedText().color())) bottom = option.rect.bottom() - 2 painter.drawLine(0, bottom, option.rect.right(), bottom) if 'static-text' not in theme: theme['static-text'] = QStaticText(_( ''' <h1>{title}</h1> <p>by <i>{author}</i> with <b>{number}</b> icons [{size}]</p> <p>{description}</p> <p>Version: {version} Number of users: {usage}</p> '''.format(title=theme.get('title', _('Unknown')), author=theme.get('author', _('Unknown')), number=theme.get('number', 0), description=theme.get('description', ''), size=human_readable(theme.get('compressed-size', 0)), version=theme.get('version', 1), usage=theme.get('usage', 0), ))) painter.drawStaticText(COVER_SIZE[0] + self.SPACING, option.rect.top() + self.SPACING, theme['static-text']) painter.restore()
def contextMenuEvent(self, ev): from calibre.gui2.open_with import populate_menu, edit_programs cm = QMenu(self) paste = cm.addAction(_('Paste cover')) copy = cm.addAction(_('Copy cover')) remove = cm.addAction(_('Remove cover')) gc = cm.addAction(_('Generate cover from metadata')) cm.addSeparator() if not QApplication.instance().clipboard().mimeData().hasImage(): paste.setEnabled(False) copy.triggered.connect(self.copy_to_clipboard) paste.triggered.connect(self.paste_from_clipboard) remove.triggered.connect(self.remove_cover) gc.triggered.connect(self.generate_cover) m = QMenu(_('Open cover with...')) populate_menu(m, self.open_with, 'cover_image') if len(m.actions()) == 0: cm.addAction(_('Open cover with...'), self.choose_open_with) else: m.addSeparator() m.addAction(_('Add another application to open cover...'), self.choose_open_with) m.addAction(_('Edit Open with applications...'), partial(edit_programs, 'cover_image', self)) cm.ocw = m cm.addMenu(m) cm.si = m = create_search_internet_menu(self.search_internet.emit) cm.addMenu(m) cm.exec_(ev.globalPos())
def ensure_app(): global _store_app if _store_app is None and QApplication.instance() is None: args = sys.argv[:1] if islinux or isbsd: args += ['-platformpluginpath', sys.extensions_location, '-platform', 'headless'] _store_app = QApplication(args)
def __init__(self, name, plugins, gui_name, parent=None): QWidget.__init__(self, parent) self._layout = QVBoxLayout() self.setLayout(self._layout) self.label = QLabel(gui_name) self.sep = QFrame(self) self.bf = QFont() self.bf.setBold(True) self.label.setFont(self.bf) self.sep.setFrameShape(QFrame.HLine) self._layout.addWidget(self.label) self._layout.addWidget(self.sep) self.plugins = plugins self.bar = QToolBar(self) self.bar.setStyleSheet("QToolBar { border: none; background: none }") lh = QApplication.instance().line_height self.bar.setIconSize(QSize(2 * lh, 2 * lh)) self.bar.setMovable(False) self.bar.setFloatable(False) self.bar.setToolButtonStyle(Qt.ToolButtonTextUnderIcon) self._layout.addWidget(self.bar) self.actions = [] for p in plugins: target = partial(self.triggered, p) ac = self.bar.addAction(QIcon(p.icon), p.gui_name, target) ac.setToolTip(textwrap.fill(p.description)) ac.setWhatsThis(textwrap.fill(p.description)) ac.setStatusTip(p.description) self.actions.append(ac) w = self.bar.widgetForAction(ac) w.setCursor(Qt.PointingHandCursor) w.setAutoRaise(True) w.setMinimumWidth(100)
def context_menu_requested(self, widget, ev): if isinstance(widget, Heading): start = widget else: found = False for w in reversed(self.widgets): if w is widget: found = True elif found and isinstance(w, Heading): start = w break else: return found = False lines = [] for w in self.widgets: if found and isinstance(w, Heading): break if w is start: found = True if found: lines += w.lines_for_copy if not lines: return block = '\n'.join(lines).replace('\xa0', ' ') heading = lines[0] m = QMenu(self) m.addAction(QIcon(I('edit-copy.png')), _('Copy') + ' ' + heading.replace('\xa0', ' '), lambda : QApplication.instance().clipboard().setText(block)) all_lines = [] for w in self.widgets: all_lines += w.lines_for_copy all_text = '\n'.join(all_lines).replace('\xa0', ' ') m.addAction(QIcon(I('edit-copy.png')), _('Copy everything'), lambda : QApplication.instance().clipboard().setText(all_text)) m.exec_(ev.globalPos())
def quit(self, checked=True, restart=False, debug_on_restart=False, confirm_quit=True): if self.shutting_down: return if confirm_quit and not self.confirm_quit(): return try: self.shutdown() except: pass self.restart_after_quit = restart self.debug_on_restart = debug_on_restart if self.system_tray_icon is not None and self.restart_after_quit: # Needed on windows to prevent multiple systray icons self.system_tray_icon.setVisible(False) QApplication.instance().quit()
def mousePressEvent(self, ev): if ev.button() == Qt.LeftButton: from .actions import show_downloads app = QApplication.instance() w = app.activeWindow() if hasattr(w, 'get_tab_for_load'): show_downloads(w)
def contextMenuEvent(self, ev): from calibre.gui2.open_with import populate_menu, edit_programs cm = QMenu(self) paste = cm.addAction(_("Paste Cover")) copy = cm.addAction(_("Copy Cover")) remove = cm.addAction(_("Remove Cover")) gc = cm.addAction(_("Generate Cover from metadata")) if not QApplication.instance().clipboard().mimeData().hasImage(): paste.setEnabled(False) copy.triggered.connect(self.copy_to_clipboard) paste.triggered.connect(self.paste_from_clipboard) remove.triggered.connect(self.remove_cover) gc.triggered.connect(self.generate_cover) m = QMenu(_("Open cover with...")) populate_menu(m, self.open_with, "cover_image") if len(m.actions()) == 0: cm.addAction(_("Open cover with..."), self.choose_open_with) else: m.addSeparator() m.addAction(_("Add another application to open cover..."), self.choose_open_with) m.addAction(_("Edit Open With applications..."), partial(edit_programs, "cover_image", self)) cm.addMenu(m) cm.exec_(ev.globalPos())
def __init__(self, develop=False): self.drawn_once = False self.develop = develop self.title_font = f = QFont() f.setPointSize(self.TITLE_SIZE) f.setBold(True) self.title_height = QFontMetrics(f).lineSpacing() + 2 self.body_font = f = QFont() f.setPointSize(self.BODY_SIZE) self.line_height = QFontMetrics(f).lineSpacing() self.total_height = max(self.LOGO_SIZE, self.title_height + 3 * self.line_height) self.num_font = f = QFont() f.setPixelSize(self.total_height) f.setItalic(True), f.setBold(True) f = QFontMetrics(f) self.num_ch = str(max(3, numeric_version[0])) self.footer_font = f = QFont() f.setPointSize(self.FOOTER_SIZE) f.setItalic(True) self.dpr = QApplication.instance().devicePixelRatio() self.pmap = QPixmap(I('library.png', allow_user_override=False)) self.pmap.setDevicePixelRatio(self.dpr) self.pmap = self.pmap.scaled(int(self.dpr * self.LOGO_SIZE), int(self.dpr * self.LOGO_SIZE), transformMode=Qt.SmoothTransformation) self.light_brush = QBrush(QColor('#F6F3E9')) self.dark_brush = QBrush(QColor('#39322B')) pmap = QPixmap(int(self.WIDTH * self.dpr), int(self.WIDTH * self.dpr)) pmap.setDevicePixelRatio(self.dpr) pmap.fill(Qt.transparent) QSplashScreen.__init__(self, pmap) self.setWindowTitle(__appname__)
def handle_tap(self, tp): self.scroller.stop() last_tap_at, self.last_tap_at = self.last_tap_at, monotonic() if self.close_open_menu(): return interval = QApplication.instance().doubleClickInterval() / 1000 double_tap = self.last_tap_at - last_tap_at < interval send_click(self.parent(), tp.start_position, double_click=double_tap)
def paste_from_clipboard(self, pmap=None): if not isinstance(pmap, QPixmap): cb = QApplication.instance().clipboard() pmap = cb.pixmap() if pmap.isNull() and cb.supportsSelection(): pmap = cb.pixmap(cb.Selection) if not pmap.isNull(): self.update_cover(pmap)
def _paste_url(text): text = text or '' text = text.partition(' ')[2].strip() w = QApplication.instance().activeWindow() w.setFocus(Qt.MouseFocusReason) # For some reason calling setFocus directly on the tab does not work t = getattr(w, 'current_tab', None) if t is not None: python_to_js(t, 'insert_text', text)
def paste(self, *args): app = QApplication.instance() c = app.clipboard() txt = unicode(c.text()).strip() if txt: old = unicode(self.isbn_box.toPlainText()).strip() new = old + '\n' + txt self.isbn_box.setPlainText(new)
def css(): global _css if _css is None: val = P('templates/book_details.css', data=True).decode('utf-8') col = QApplication.instance().palette().color(QPalette.Link).name() val = val.replace('LINK_COLOR', col) _css = re.sub(ur'/\*.*?\*/', '', val, flags=re.DOTALL) return _css
def get_login_credentials(self, url): if not QApplication.instance().ask_for_master_password(self): return if password_db.join(): key = key_from_url(url) accounts = password_db.get_accounts(key) if accounts: return accounts[0]
def paint(self, painter, option, index): QStyledItemDelegate.paint(self, painter, option, self._m.index(1)) painter.save() parent = self.parent() or QApplication.instance() style = parent.style() try: index.data(Qt.UserRole).draw_item(painter, style, option) finally: painter.restore()
def build_context_menu(self): cm = QMenu(self) paste = cm.addAction(_('Paste cover')) copy = cm.addAction(_('Copy cover')) if not QApplication.instance().clipboard().mimeData().hasImage(): paste.setEnabled(False) copy.triggered.connect(self.copy_to_clipboard) paste.triggered.connect(self.paste_from_clipboard) return cm
def paste_from_clipboard(self): cb = QApplication.instance().clipboard() pmap = cb.pixmap() if pmap.isNull() and cb.supportsSelection(): pmap = cb.pixmap(cb.Selection) if not pmap.isNull(): self.set_pixmap(pmap) self.cover_changed.emit( pixmap_to_data(pmap, format='PNG'))
def has_active_downloads(self, val): val = bool(val) changed = val != self._has_active_downloads self._has_active_downloads = val if changed: app = QApplication.instance() for w in app.windows: di = w.downloads_indicator (di.start if val else di.stop)()
def __init__(self, parent=None): QWebView.__init__(self, parent) self.inspector = QWebInspector(self) w = QApplication.instance().desktop().availableGeometry(self).width() self._size_hint = QSize(int(w/3), int(w/2)) self._page = WebPage(self) self.setPage(self._page) self.inspector.setPage(self._page) self.clear()
def data(self, index, role): row, col = index.row(), index.column() if row >= len(self.matches): return None result = self.matches[row] if role == Qt.DisplayRole: if col == 1: t = result.title if result.title else _('Unknown') a = result.author if result.author else '' return ('<b>%s</b><br><i>%s</i>' % (t, a)) elif col == 2: return (result.price) elif col == 4: return ('<span>%s<br>%s</span>' % (result.store_name, result.formats)) return None elif role == Qt.DecorationRole: if col == 0 and result.cover_data: p = QPixmap() p.loadFromData(result.cover_data) p.setDevicePixelRatio(QApplication.instance().devicePixelRatio()) return p if col == 3: if result.drm == SearchResult.DRM_LOCKED: return (self.DRM_LOCKED_ICON) elif result.drm == SearchResult.DRM_UNLOCKED: return (self.DRM_UNLOCKED_ICON) elif result.drm == SearchResult.DRM_UNKNOWN: return (self.DRM_UNKNOWN_ICON) if col == 5: if result.downloads: return (self.DOWNLOAD_ICON) if col == 6: if result.affiliate: return (self.DONATE_ICON) elif role == Qt.ToolTipRole: if col == 1: return ('<p>%s</p>' % result.title) elif col == 2: return ('<p>' + _('Detected price as: %s. Check with the store before making a purchase to verify this price is correct. This price often does not include promotions the store may be running.') % result.price + '</p>') # noqa elif col == 3: if result.drm == SearchResult.DRM_LOCKED: return ('<p>' + _('This book as been detected as having DRM restrictions. This book may not work with your reader and you will have limitations placed upon you as to what you can do with this book. Check with the store before making any purchases to ensure you can actually read this book.') + '</p>') # noqa elif result.drm == SearchResult.DRM_UNLOCKED: return ('<p>' + _('This book has been detected as being DRM Free. You should be able to use this book on any device provided it is in a format calibre supports for conversion. However, before making a purchase double check the DRM status with the store. The store may not be disclosing the use of DRM.') + '</p>') # noqa else: return ('<p>' + _('The DRM status of this book could not be determined. There is a very high likelihood that this book is actually DRM restricted.') + '</p>') # noqa elif col == 4: return ('<p>%s</p>' % result.formats) elif col == 5: if result.downloads: return ('<p>' + _('The following formats can be downloaded directly: %s.') % ', '.join(result.downloads.keys()) + '</p>') elif col == 6: if result.affiliate: return ('<p>' + _('Buying from this store supports the calibre developer: %s.') % result.plugin_author + '</p>') elif role == Qt.SizeHintRole: return QSize(64, 64) return None
def create_window_menubar(self, parent): if not QApplication.instance().testAttribute(Qt.AA_DontUseNativeMenuBar) and self.has_global_menu: ans = ExportedMenuBar(parent, self.menu_registrar, self.bus) self.prune_dead_refs() self.window_menus.append(weakref.ref(ans)) return ans ans = QMenuBar(parent) parent.setMenuBar(ans) ans.is_native_menubar = False return ans
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 = Cover(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.open_with_requested.connect(self.open_with) self.cover.choose_open_with_requested.connect(self.choose_open_with) 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.path_to_book = None 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: QApplication.instance().safe_restore_geometry( self, saved_layout[0]) self.splitter.restoreState(saved_layout[1]) except Exception: pass from calibre.gui2.ui import get_gui ema = get_gui().iactions['Edit Metadata'].menuless_qaction a = self.ema = QAction('edit metadata', self) a.setShortcut(ema.shortcut()) self.addAction(a) a.triggered.connect(ema.trigger)
def sizeHint(self): geom = QApplication.instance().desktop().availableGeometry(self) return QSize(int(0.9 * geom.width()), int(0.8 * geom.height()))
def viewlog(self): self.browser.setText('\n'.join(self.log)) self.browser.moveCursor(QTextCursor.End) QApplication.instance().processEvents()
self._plot_control.remove(self._plot_widget_item) if __name__ == '__main__': from PyQt5.Qt import QApplication from PyQt5.QtWidgets import QHBoxLayout, QMainWindow import numpy as np x = np.linspace(0, 6 * np.pi, 1000) y = np.cos(x) app = QApplication([]) main = QMainWindow() layout = QHBoxLayout() content = QFrame() content.setLayout(layout) main.setCentralWidget(content) plot = PlotWidget(main) plot_handler = PlotConfig(plot) layout.addWidget(plot) layout.addWidget(plot_handler) plot_handler.plot(x, y, 'r--', name='cosine') plot_handler.plot(x, np.sin(x)) main.show() QApplication.instance().exec_()
def copy_to_clipboard(self): QApplication.instance().clipboard().setText(self.plain_text)
def signal_received(self, read_fd): try: os.read(read_fd, 1024) except EnvironmentError: return QApplication.instance().exit(KILL_SIGNAL)
def __init__(self, parent=None): self._host_widget = None self.callback_id_counter = count() self.callback_map = {} self.current_cfi = self.current_content_file = None RestartingWebEngineView.__init__(self, parent) self.tts = TTS(self) self.tts.event_received.connect(self.tts_event_received) self.dead_renderer_error_shown = False self.render_process_failed.connect(self.render_process_died) w = QApplication.instance().desktop().availableGeometry(self).width() QApplication.instance().palette_changed.connect(self.palette_changed) self.show_home_page_on_ready = True self._size_hint = QSize(int(w/3), int(w/2)) self._page = WebPage(self) self.view_is_ready = False self.bridge.bridge_ready.connect(self.on_bridge_ready) self.bridge.view_created.connect(self.on_view_created) self.bridge.content_file_changed.connect(self.on_content_file_changed) self.bridge.set_session_data.connect(self.set_session_data) self.bridge.set_local_storage.connect(self.set_local_storage) self.bridge.reload_book.connect(self.reload_book) self.bridge.toggle_toc.connect(self.toggle_toc) self.bridge.show_search.connect(self.show_search) self.bridge.search_result_not_found.connect(self.search_result_not_found) self.bridge.find_next.connect(self.find_next) self.bridge.toggle_bookmarks.connect(self.toggle_bookmarks) self.bridge.toggle_highlights.connect(self.toggle_highlights) self.bridge.new_bookmark.connect(self.new_bookmark) self.bridge.toggle_inspector.connect(self.toggle_inspector) self.bridge.toggle_lookup.connect(self.toggle_lookup) self.bridge.quit.connect(self.quit) self.bridge.update_current_toc_nodes.connect(self.update_current_toc_nodes) self.bridge.toggle_full_screen.connect(self.toggle_full_screen) self.bridge.ask_for_open.connect(self.ask_for_open) self.bridge.selection_changed.connect(self.selection_changed) self.bridge.autoscroll_state_changed.connect(self.autoscroll_state_changed) self.bridge.view_image.connect(self.view_image) self.bridge.copy_image.connect(self.copy_image) self.bridge.overlay_visibility_changed.connect(self.overlay_visibility_changed) self.bridge.reference_mode_changed.connect(self.reference_mode_changed) self.bridge.show_loading_message.connect(self.show_loading_message) self.bridge.show_error.connect(self.show_error) self.bridge.print_book.connect(self.print_book) self.bridge.clear_history.connect(self.clear_history) self.bridge.reset_interface.connect(self.reset_interface) self.bridge.quit.connect(self.quit) self.bridge.customize_toolbar.connect(self.customize_toolbar) self.bridge.scrollbar_context_menu.connect(self.scrollbar_context_menu) self.bridge.close_prep_finished.connect(self.close_prep_finished) self.bridge.highlights_changed.connect(self.highlights_changed) self.bridge.open_url.connect(safe_open_url) self.bridge.speak_simple_text.connect(self.tts.speak_simple_text) self.bridge.tts.connect(self.tts.action) self.bridge.export_shortcut_map.connect(self.set_shortcut_map) self.shortcut_map = {} self.bridge.report_cfi.connect(self.call_callback) self.bridge.change_background_image.connect(self.change_background_image) self.pending_bridge_ready_actions = {} self.setPage(self._page) self.setAcceptDrops(False) self.setUrl(QUrl('{}://{}/'.format(FAKE_PROTOCOL, FAKE_HOST))) self.urlChanged.connect(self.url_changed) if parent is not None: self.inspector = Inspector(parent.inspector_dock.toggleViewAction(), self) parent.inspector_dock.setWidget(self.inspector)
def doit(): QApplication.instance().clipboard().setText(url)
def load_ebook(self, pathtoebook, open_at=None): if self.iterator is not None: self.save_current_position() self.iterator.__exit__() self.iterator = EbookIterator(pathtoebook) self.open_progress_indicator(_('Loading ebook...')) worker = Worker( target=partial(self.iterator.__enter__, view_kepub=True)) worker.start() while worker.isAlive(): worker.join(0.1) QApplication.processEvents() if worker.exception is not None: if isinstance(worker.exception, DRMError): from calibre.gui2.dialogs.drm_error import DRMErrorMessage DRMErrorMessage(self).exec_() else: r = getattr(worker.exception, 'reason', worker.exception) error_dialog(self, _('Could not open ebook'), as_unicode(r) or _('Unknown error'), det_msg=worker.traceback, show=True) self.close_progress_indicator() else: self.metadata.show_opf(self.iterator.opf, self.iterator.book_format) self.view.current_language = self.iterator.language title = self.iterator.opf.title if not title: title = os.path.splitext(os.path.basename(pathtoebook))[0] if self.iterator.toc: self.toc_model = TOC(self.iterator.spine, self.iterator.toc) self.toc.setModel(self.toc_model) if self.show_toc_on_open: self.action_table_of_contents.setChecked(True) else: self.toc_model = TOC(self.iterator.spine) self.toc.setModel(self.toc_model) self.action_table_of_contents.setChecked(False) if isbytestring(pathtoebook): pathtoebook = force_unicode(pathtoebook, filesystem_encoding) vh = vprefs.get('viewer_open_history', []) try: vh.remove(pathtoebook) except: pass vh.insert(0, pathtoebook) vprefs.set('viewer_open_history', vh[:50]) self.build_recent_menu() self.action_table_of_contents.setDisabled(not self.iterator.toc) self.current_book_has_toc = bool(self.iterator.toc) self.current_title = title self.setWindowTitle(title + ' [%s]' % self.iterator.book_format + ' - ' + self.base_window_title) self.pos.setMaximum(sum(self.iterator.pages)) self.pos.setSuffix(' / %d' % sum(self.iterator.pages)) self.vertical_scrollbar.setMinimum(100) self.vertical_scrollbar.setMaximum(100 * sum(self.iterator.pages)) self.vertical_scrollbar.setSingleStep(10) self.vertical_scrollbar.setPageStep(100) self.set_vscrollbar_value(1) self.current_index = -1 QApplication.instance().alert(self, 5000) previous = self.set_bookmarks(self.iterator.bookmarks) if open_at is None and previous is not None: self.goto_bookmark(previous) else: if open_at is None: self.next_document() else: if open_at > self.pos.maximum(): open_at = self.pos.maximum() if open_at < self.pos.minimum(): open_at = self.pos.minimum() self.goto_page(open_at, loaded_check=False)
def __init__(self, parent, db, id_to_select, select_sort, select_link, find_aut_func, is_first_letter=False): QDialog.__init__(self, parent) Ui_EditAuthorsDialog.__init__(self) self.setupUi(self) # Remove help icon on title bar icon = self.windowIcon() self.setWindowFlags(self.windowFlags() & (~Qt.WindowContextHelpButtonHint)) self.setWindowIcon(icon) try: self.table_column_widths = \ gprefs.get('manage_authors_table_widths', None) geom = gprefs.get('manage_authors_dialog_geometry', None) if geom: QApplication.instance().safe_restore_geometry( self, QByteArray(geom)) except Exception: pass self.buttonBox.button(QDialogButtonBox.Ok).setText(_('&OK')) self.buttonBox.button(QDialogButtonBox.Cancel).setText(_('&Cancel')) self.buttonBox.accepted.connect(self.accepted) self.apply_vl_checkbox.stateChanged.connect(self.use_vl_changed) # Set up the heading for sorting self.table.setSelectionMode(QAbstractItemView.SingleSelection) self.find_aut_func = find_aut_func self.table.resizeColumnsToContents() if self.table.columnWidth(2) < 200: self.table.setColumnWidth(2, 200) # set up the cellChanged signal only after the table is filled self.table.cellChanged.connect(self.cell_changed) self.recalc_author_sort.clicked.connect(self.do_recalc_author_sort) self.auth_sort_to_author.clicked.connect(self.do_auth_sort_to_author) # Capture clicks on the horizontal header to sort the table columns hh = self.table.horizontalHeader() hh.sectionResized.connect(self.table_column_resized) hh.setSectionsClickable(True) hh.sectionClicked.connect(self.do_sort) hh.setSortIndicatorShown(True) # set up the search & filter boxes self.find_box.initialize('manage_authors_search') le = self.find_box.lineEdit() ac = le.findChild(QAction, QT_HIDDEN_CLEAR_ACTION) if ac is not None: ac.triggered.connect(self.clear_find) le.returnPressed.connect(self.do_find) self.find_box.editTextChanged.connect(self.find_text_changed) self.find_button.clicked.connect(self.do_find) self.find_button.setDefault(True) self.filter_box.initialize('manage_authors_filter') le = self.filter_box.lineEdit() ac = le.findChild(QAction, QT_HIDDEN_CLEAR_ACTION) if ac is not None: ac.triggered.connect(self.clear_filter) self.filter_box.lineEdit().returnPressed.connect(self.do_filter) self.filter_button.clicked.connect(self.do_filter) self.not_found_label = l = QLabel(self.table) l.setFrameStyle(QFrame.StyledPanel) l.setAutoFillBackground(True) l.setText(_('No matches found')) l.setAlignment(Qt.AlignVCenter) l.resize(l.sizeHint()) l.move(10, 2) l.setVisible(False) self.not_found_label_timer = QTimer() self.not_found_label_timer.setSingleShot(True) self.not_found_label_timer.timeout.connect( self.not_found_label_timer_event, type=Qt.QueuedConnection) self.table.setContextMenuPolicy(Qt.CustomContextMenu) self.table.customContextMenuRequested.connect(self.show_context_menu) # Fetch the data self.authors = {} self.original_authors = {} auts = db.new_api.author_data() self.completion_data = [] for id_, v in auts.items(): name = v['name'] name = name.replace('|', ',') self.completion_data.append(name) self.authors[id_] = { 'name': name, 'sort': v['sort'], 'link': v['link'] } self.original_authors[id_] = { 'name': name, 'sort': v['sort'], 'link': v['link'] } self.edited_icon = QIcon(I('modified.png')) self.empty_icon = QIcon() if prefs['use_primary_find_in_search']: self.string_contains = primary_contains else: self.string_contains = contains self.last_sorted_by = 'sort' self.author_order = 1 self.author_sort_order = 0 self.link_order = 1 self.show_table(id_to_select, select_sort, select_link, is_first_letter)
def copy_to_clipboard(self): QApplication.instance().clipboard().setPixmap(self.pixmap)
def hide_cursor(self): if get_session_pref('auto_hide_mouse', True): self.cursor_hidden = True QApplication.instance().setOverrideCursor(Qt.BlankCursor)
def auto_height(widget): return max(185, QApplication.instance().desktop().availableGeometry(widget).height() / 5.0)
def load_pixmap(self, data): pmap = QPixmap() pmap.loadFromData(data) pmap.setDevicePixelRatio(QApplication.instance().devicePixelRatio()) return pmap
def evaljs_callback(self, result): self.evaljs_result = result QApplication.instance().exit(0)
def show_context_menu(self, point): item = self.itemAt(point) if item is None or item in set(self.categories.itervalues()): return m = QMenu(self) sel = self.selectedItems() num = len(sel) container = current_container() ci = self.currentItem() if ci is not None: cn = unicode(ci.data(0, NAME_ROLE) or '') mt = unicode(ci.data(0, MIME_ROLE) or '') cat = unicode(ci.data(0, CATEGORY_ROLE) or '') n = elided_text(cn.rpartition('/')[-1]) m.addAction(QIcon(I('save.png')), _('Export %s') % n, partial(self.export, cn)) if cn not in container.names_that_must_not_be_changed and cn not in container.names_that_must_not_be_removed and mt not in OEB_FONTS: m.addAction(_('Replace %s with file...') % n, partial(self.replace, cn)) if num > 1: m.addAction(QIcon(I('save.png')), _('Export all %d selected files') % num, self.export_selected) m.addSeparator() m.addAction(QIcon(I('modified.png')), _('&Rename %s') % n, self.edit_current_item) if is_raster_image(mt): m.addAction(QIcon(I('default_cover.png')), _('Mark %s as cover image') % n, partial(self.mark_as_cover, cn)) elif current_container().SUPPORTS_TITLEPAGES and mt in OEB_DOCS and cat == 'text': m.addAction(QIcon(I('default_cover.png')), _('Mark %s as cover page') % n, partial(self.mark_as_titlepage, cn)) m.addSeparator() if num > 0: m.addSeparator() if num > 1: m.addAction(QIcon(I('modified.png')), _('&Bulk rename the selected files'), self.request_bulk_rename) m.addAction(QIcon(I('modified.png')), _('Change the file extension for the selected files'), self.request_change_ext) m.addAction(QIcon(I('trash.png')), ngettext( '&Delete the selected file', '&Delete the {} selected files', num).format(num), self.request_delete) m.addAction(QIcon(I('edit-copy.png')), ngettext( '&Copy the selected file to another editor instance', '&Copy the {} selected files to another editor instance', num).format(num), self.copy_selected_files) m.addSeparator() md = QApplication.instance().clipboard().mimeData() if md.hasUrls() and md.hasFormat(FILE_COPY_MIME): m.addAction(_('Paste files from other editor instance'), self.paste_from_other_instance) selected_map = defaultdict(list) for item in sel: selected_map[unicode(item.data(0, CATEGORY_ROLE) or '')].append(unicode(item.data(0, NAME_ROLE) or '')) for items in selected_map.itervalues(): items.sort(key=self.index_of_name) if selected_map['text']: m.addAction(QIcon(I('format-text-color.png')), _('Link &stylesheets...'), partial(self.link_stylesheets, selected_map['text'])) if len(selected_map['text']) > 1: m.addAction(QIcon(I('merge.png')), _('&Merge selected text files'), partial(self.start_merge, 'text', selected_map['text'])) if len(selected_map['styles']) > 1: m.addAction(QIcon(I('merge.png')), _('&Merge selected style files'), partial(self.start_merge, 'styles', selected_map['styles'])) if len(list(m.actions())) > 0: m.popup(self.mapToGlobal(point))
def icon_to_clipboard(self): app = QApplication.instance() c = app.clipboard() c.setText(str(self.icon_files.currentText()))
def spin_loop(self): QApplication.instance().processEvents( QEventLoop.ExcludeUserInputEvents)
def color_to_clipboard(self): app = QApplication.instance() c = app.clipboard() c.setText(str(self.color_name.color))
def copy_report(): text = re.sub(r'</.+?>', '\n', report) text = re.sub(r'<.+?>', '', text) cp = QApplication.instance().clipboard() cp.setText(text)
def add_copy_action(name): menu.addAction( QIcon(I('edit-copy.png')), _('Copy {} to clipboard').format(name), lambda: QApplication.instance().clipboard().setText(name))
def data(self, index, role): row, col = index.row(), index.column() if row >= len(self.matches): return None result = self.matches[row] if role == Qt.DisplayRole: if col == 1: t = result.title if result.title else _('Unknown') a = result.author if result.author else '' return ('<b>%s</b><br><i>%s</i>' % (t, a)) elif col == 2: return (result.price) elif col == 4: return ('<span>%s<br>%s</span>' % (result.store_name, result.formats)) return None elif role == Qt.DecorationRole: if col == 0 and result.cover_data: p = QPixmap() p.loadFromData(result.cover_data) p.setDevicePixelRatio( QApplication.instance().devicePixelRatio()) return p if col == 3: if result.drm == SearchResult.DRM_LOCKED: return (self.DRM_LOCKED_ICON) elif result.drm == SearchResult.DRM_UNLOCKED: return (self.DRM_UNLOCKED_ICON) elif result.drm == SearchResult.DRM_UNKNOWN: return (self.DRM_UNKNOWN_ICON) if col == 5: if result.downloads: return (self.DOWNLOAD_ICON) if col == 6: if result.affiliate: return (self.DONATE_ICON) elif role == Qt.ToolTipRole: if col == 1: return ('<p>%s</p>' % result.title) elif col == 2: if result.price: return ('<p>' + _( 'Detected price as: %s. Check with the store before making a purchase' ' to verify this price is correct. This price often does not include' ' promotions the store may be running.') % result.price + '</p>') return '<p>' + _('No price was found') elif col == 3: if result.drm == SearchResult.DRM_LOCKED: return ('<p>' + _( 'This book as been detected as having DRM restrictions. This book may not work with your reader and you will have limitations placed upon you as to what you can do with this book. Check with the store before making any purchases to ensure you can actually read this book.' ) + '</p>') # noqa elif result.drm == SearchResult.DRM_UNLOCKED: return ('<p>' + _( 'This book has been detected as being DRM Free. You should be able to use this book on any device provided it is in a format calibre supports for conversion. However, before making a purchase double check the DRM status with the store. The store may not be disclosing the use of DRM.' ) + '</p>') # noqa else: return ('<p>' + _( 'The DRM status of this book could not be determined. There is a very high likelihood that this book is actually DRM restricted.' ) + '</p>') # noqa elif col == 4: return ('<p>%s</p>' % result.formats) elif col == 5: if result.downloads: return ('<p>' + _( 'The following formats can be downloaded directly: %s.' ) % ', '.join(result.downloads.keys()) + '</p>') elif col == 6: if result.affiliate: return ('<p>' + _( 'Buying from this store supports the calibre developer: %s.' ) % result.plugin_author + '</p>') elif role == Qt.SizeHintRole: return QSize(64, 64) return None
def quit(self): if self.shutdown(): QApplication.instance().quit()
def sizeHint(self): g = QApplication.instance().desktop().availableGeometry(self.parent() or self) return QSize(min(1500, g.width() - 25), 650)
def spin_loop(self): while self.working: QApplication.instance().processEvents( QEventLoop.ExcludeUserInputEvents) return self.result
def default_theme(): global _default_theme if _default_theme is None: isdark = QApplication.instance().palette().color(QPalette.WindowText).lightness() > 128 _default_theme = 'wombat-dark' if isdark else 'pyte-light' return _default_theme
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 = self.bb.addButton( _('Run Welcome &wizard'), QDialogButtonBox.ButtonRole.ActionRole) self.wizard_button.setIcon(QIcon(I('wizard.png'))) 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), l.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 do_paste_and_match_style(self): text = QApplication.instance().clipboard().text() if text: self.setText(text)
def initialize(self, library_path, db, listener, actions, show_gui=True): opts = self.opts self.preferences_action, self.quit_action = actions self.library_path = library_path self.library_broker = GuiLibraryBroker(db) self.content_server = None self.server_change_notification_timer = t = QTimer(self) self.server_changes = Queue() t.setInterval(1000), t.timeout.connect(self.handle_changes_from_server_debounced), t.setSingleShot(True) self._spare_pool = None self.must_restart_before_config = False self.listener = Listener(listener) self.check_messages_timer = QTimer() self.check_messages_timer.timeout.connect(self.another_instance_wants_to_talk) self.check_messages_timer.start(1000) for ac in list(self.iactions.values()): try: ac.do_genesis() except Exception: # Ignore errors in third party plugins import traceback traceback.print_exc() if getattr(ac, 'plugin_path', None) is None: raise self.donate_action = QAction(QIcon(I('donate.png')), _('&Donate to support calibre'), self) for st in list(self.istores.values()): st.do_genesis() MainWindowMixin.init_main_window_mixin(self, db) # Jobs Button {{{ self.job_manager = JobManager() self.jobs_dialog = JobsDialog(self, self.job_manager) self.jobs_button = JobsButton(parent=self) self.jobs_button.initialize(self.jobs_dialog, self.job_manager) # }}} LayoutMixin.init_layout_mixin(self) DeviceMixin.init_device_mixin(self) self.progress_indicator = ProgressIndicator(self) self.progress_indicator.pos = (0, 20) self.verbose = opts.verbose self.get_metadata = GetMetadata() self.upload_memory = {} self.metadata_dialogs = [] self.default_thumbnail = None self.tb_wrapper = textwrap.TextWrapper(width=40) self.viewers = collections.deque() self.system_tray_icon = None if config['systray_icon']: self.system_tray_icon = factory(app_id='com.calibre-ebook.gui').create_system_tray_icon(parent=self, title='calibre') if self.system_tray_icon is not None: self.system_tray_icon.setIcon(QIcon(I('lt.png', allow_user_override=False))) if not (iswindows or isosx): self.system_tray_icon.setIcon(QIcon.fromTheme('calibre-gui', self.system_tray_icon.icon())) self.system_tray_icon.setToolTip(self.jobs_button.tray_tooltip()) self.system_tray_icon.setVisible(True) self.jobs_button.tray_tooltip_updated.connect(self.system_tray_icon.setToolTip) elif config['systray_icon']: prints('Failed to create system tray icon, your desktop environment probably does not support the StatusNotifier spec') self.system_tray_menu = QMenu(self) self.toggle_to_tray_action = self.system_tray_menu.addAction(QIcon(I('page.png')), '') self.toggle_to_tray_action.triggered.connect(self.system_tray_icon_activated) self.system_tray_menu.addAction(self.donate_action) self.eject_action = self.system_tray_menu.addAction( QIcon(I('eject.png')), _('&Eject connected device')) self.eject_action.setEnabled(False) self.addAction(self.quit_action) self.system_tray_menu.addAction(self.quit_action) self.keyboard.register_shortcut('quit calibre', _('Quit calibre'), default_keys=('Ctrl+Q',), action=self.quit_action) if self.system_tray_icon is not None: self.system_tray_icon.setContextMenu(self.system_tray_menu) self.system_tray_icon.activated.connect(self.system_tray_icon_activated) self.quit_action.triggered[bool].connect(self.quit) self.donate_action.triggered[bool].connect(self.donate) self.minimize_action = QAction(_('Minimize the calibre window'), self) self.addAction(self.minimize_action) self.keyboard.register_shortcut('minimize calibre', self.minimize_action.text(), default_keys=(), action=self.minimize_action) self.minimize_action.triggered.connect(self.showMinimized) self.esc_action = QAction(self) self.addAction(self.esc_action) self.keyboard.register_shortcut('clear current search', _('Clear the current search'), default_keys=('Esc',), action=self.esc_action) self.esc_action.triggered.connect(self.esc) self.shift_esc_action = QAction(self) self.addAction(self.shift_esc_action) self.keyboard.register_shortcut('focus book list', _('Focus the book list'), default_keys=('Shift+Esc',), action=self.shift_esc_action) self.shift_esc_action.triggered.connect(self.shift_esc) self.ctrl_esc_action = QAction(self) self.addAction(self.ctrl_esc_action) self.keyboard.register_shortcut('clear virtual library', _('Clear the virtual library'), default_keys=('Ctrl+Esc',), action=self.ctrl_esc_action) self.ctrl_esc_action.triggered.connect(self.ctrl_esc) self.alt_esc_action = QAction(self) self.addAction(self.alt_esc_action) self.keyboard.register_shortcut('clear additional restriction', _('Clear the additional restriction'), default_keys=('Alt+Esc',), action=self.alt_esc_action) self.alt_esc_action.triggered.connect(self.clear_additional_restriction) # ###################### Start spare job server ######################## QTimer.singleShot(1000, self.create_spare_pool) # ###################### Location Manager ######################## self.location_manager.location_selected.connect(self.location_selected) self.location_manager.unmount_device.connect(self.device_manager.umount_device) self.location_manager.configure_device.connect(self.configure_connected_device) self.location_manager.update_device_metadata.connect(self.update_metadata_on_device) self.eject_action.triggered.connect(self.device_manager.umount_device) # ################### Update notification ################### UpdateMixin.init_update_mixin(self, opts) # ###################### Search boxes ######################## SearchRestrictionMixin.init_search_restriction_mixin(self) SavedSearchBoxMixin.init_saved_seach_box_mixin(self) # ###################### Library view ######################## LibraryViewMixin.init_library_view_mixin(self, db) SearchBoxMixin.init_search_box_mixin(self) # Requires current_db self.library_view.model().count_changed_signal.connect( self.iactions['Choose Library'].count_changed) if not gprefs.get('quick_start_guide_added', False): try: add_quick_start_guide(self.library_view) except: import traceback traceback.print_exc() for view in ('library', 'memory', 'card_a', 'card_b'): v = getattr(self, '%s_view' % view) v.selectionModel().selectionChanged.connect(self.update_status_bar) v.model().count_changed_signal.connect(self.update_status_bar) self.library_view.model().count_changed() self.bars_manager.database_changed(self.library_view.model().db) self.library_view.model().database_changed.connect(self.bars_manager.database_changed, type=Qt.QueuedConnection) # ########################## Tags Browser ############################## TagBrowserMixin.init_tag_browser_mixin(self, db) self.library_view.model().database_changed.connect(self.populate_tb_manage_menu, type=Qt.QueuedConnection) # ######################## Search Restriction ########################## if db.prefs['virtual_lib_on_startup']: self.apply_virtual_library(db.prefs['virtual_lib_on_startup']) self.rebuild_vl_tabs() # ########################## Cover Flow ################################ CoverFlowMixin.init_cover_flow_mixin(self) self._calculated_available_height = min(max_available_height()-15, self.height()) self.resize(self.width(), self._calculated_available_height) self.build_context_menus() for ac in list(self.iactions.values()): try: ac.gui_layout_complete() except: import traceback traceback.print_exc() if ac.plugin_path is None: raise if config['autolaunch_server']: self.start_content_server() self.read_settings() self.finalize_layout() self.bars_manager.start_animation() self.set_window_title() for ac in list(self.iactions.values()): try: ac.initialization_complete() except: import traceback traceback.print_exc() if ac.plugin_path is None: raise self.set_current_library_information(current_library_name(), db.library_id, db.field_metadata) register_keyboard_shortcuts() self.keyboard.finalize() if show_gui: # Note this has to come after restoreGeometry() because of # https://bugreports.qt.io/browse/QTBUG-56831 self.show() if self.system_tray_icon is not None and self.system_tray_icon.isVisible() and opts.start_in_tray: self.hide_windows() self.auto_adder = AutoAdder(gprefs['auto_add_path'], self) self.save_layout_state() # Collect cycles now gc.collect() QApplication.instance().shutdown_signal_received.connect(self.quit) if show_gui and self.gui_debug is not None: QTimer.singleShot(10, self.show_gui_debug_msg) self.iactions['Connect Share'].check_smartdevice_menus() QTimer.singleShot(1, self.start_smartdevice) QTimer.singleShot(100, self.update_toggle_to_tray_action)
def sizeHint(self): desktop = QApplication.instance().desktop() h = desktop.availableGeometry(self).height() return QSize(900, h - 75)