def __init__(self, parent, prefs): QDialog.__init__(self, parent) self.prefs = prefs self.setWindowTitle(_('Create ToC from XPath')) self.l = l = QVBoxLayout() self.setLayout(l) self.la = la = QLabel( _('Specify a series of XPath expressions for the different levels of' ' the Table of Contents. You can use the wizard buttons to help' ' you create XPath expressions.')) la.setWordWrap(True) l.addWidget(la) self.widgets = [] for i in range(5): la = _('Level %s ToC:') % ('&%d' % (i + 1)) xp = XPathEdit(self) xp.set_msg(la) self.widgets.append(xp) l.addWidget(xp) self.bb = bb = QDialogButtonBox( QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel) bb.accepted.connect(self.accept) bb.rejected.connect(self.reject) self.ssb = b = bb.addButton(_('&Save settings'), bb.ActionRole) b.clicked.connect(self.save_settings) self.load_button = b = bb.addButton(_('&Load settings'), bb.ActionRole) self.load_menu = QMenu(b) b.setMenu(self.load_menu) self.setup_load_button() self.remove_duplicates_cb = QCheckBox( _('Do not add duplicate entries at the same level')) self.remove_duplicates_cb.setChecked( self.prefs.get('xpath_toc_remove_duplicates', True)) l.addWidget(self.remove_duplicates_cb) l.addStretch() l.addWidget(bb) self.resize(self.sizeHint() + QSize(50, 75))
def show_context_menu(self, pos): m = QMenu(self) a = m.addAction i = unicode(self.textCursor().selectedText()).rstrip('\0') if i: a(QIcon(I('edit-copy.png')), _('Copy to clipboard'), self.copy).setShortcut(QKeySequence.Copy) if len(self.changes) > 0: a(QIcon(I('arrow-up.png')), _('Previous change'), partial(self.next_change.emit, -1)) a(QIcon(I('arrow-down.png')), _('Next change'), partial(self.next_change.emit, 1)) if self.show_open_in_editor: b = self.cursorForPosition(pos).block() if b.isValid(): a(QIcon(I('tweak.png')), _('Open file in the editor'), partial(self.generate_sync_request, b.blockNumber())) if len(m.actions()) > 0: m.exec_(self.mapToGlobal(pos))
def adapt_for_dialog(self, enter): def ac(text, key, role=QAction.MenuRole.TextHeuristicRole): ans = QAction(text, self) ans.setMenuRole(role) ans.setShortcut(QKeySequence(key)) self.edit_menu.addAction(ans) return ans mb = self.native_menubar if enter: self.clear_bar(mb) self.edit_menu = QMenu() self.edit_action = QAction(_('Edit'), self) self.edit_action.setMenu(self.edit_menu) ac(_('Copy'), QKeySequence.StandardKey.Copy), ac(_('Paste'), QKeySequence.StandardKey.Paste), ac(_('Select all'), QKeySequence.StandardKey.SelectAll), mb.addAction(self.edit_action) self.added_actions = [self.edit_action] else: self.refresh_bar()
def show_context_menu(self, point): item = self.currentItem() def key(k): sc = unicode( QKeySequence(k | Qt.CTRL).toString(QKeySequence.NativeText)) return ' [%s]' % sc if item is not None: m = QMenu() ci = unicode(item.data(0, Qt.DisplayRole) or '') p = item.parent() or self.invisibleRootItem() idx = p.indexOfChild(item) if idx > 0: m.addAction(QIcon(I('arrow-up.png')), (_('Move "%s" up') % ci) + key(Qt.Key_Up), self.move_up) if idx + 1 < p.childCount(): m.addAction(QIcon(I('arrow-down.png')), (_('Move "%s" down') % ci) + key(Qt.Key_Down), self.move_down) m.addAction(QIcon(I('trash.png')), _('Remove all selected items'), self.del_items) if item.parent() is not None: m.addAction(QIcon(I('back.png')), (_('Unindent "%s"') % ci) + key(Qt.Key_Left), self.move_left) if idx > 0: m.addAction(QIcon(I('forward.png')), (_('Indent "%s"') % ci) + key(Qt.Key_Right), self.move_right) m.addAction(QIcon(I('edit_input.png')), _('Change the location this entry points to'), self.edit_item) m.addAction(_('Change all selected items to title case'), self.title_case) m.addAction(QIcon(I('modified.png')), _('Bulk rename all selected items'), self.bulk_rename) m.exec_(QCursor.pos())
def _createEncodingSubMenu(self, name, codecNames, menu): ''' @param: name QString @param: codecName QStringList @param: menu QMenu ''' if not codecNames: return codecNames.sort() subMenu = QMenu(name, menu) activeCodecName = gVar.app.webSettings().defaultTextEncoding() group = QActionGroup(subMenu) for codecName in codecNames: act = self._createEncodingAction(codecName, activeCodecName, subMenu) group.addAction(act) subMenu.addAction(act) menu.addMenu(subMenu)
def __init__(self, window, msg, formats, show_open_with=False): QDialog.__init__(self, window) self.resize(507, 377) self.setWindowIcon(QIcon(I("mimetypes/unknown.png"))) self.setWindowTitle(_('Choose format')) self.l = l = QVBoxLayout(self) self.msg = QLabel(msg) l.addWidget(self.msg) self.formats = QListWidget(self) self.formats.setIconSize(QSize(64, 64)) self.formats.activated[QModelIndex].connect(self.activated_slot) l.addWidget(self.formats) self.h = h = QHBoxLayout() h.setContentsMargins(0, 0, 0, 0) l.addLayout(h) if show_open_with: self.owb = QPushButton(_('&Open with...'), self) self.formats.currentRowChanged.connect( self.update_open_with_button) h.addWidget(self.owb) self.own = QMenu(self.owb.text()) self.owb.setMenu(self.own) self.own.aboutToShow.connect(self.populate_open_with) self.buttonBox = bb = QDialogButtonBox(self) bb.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) bb.accepted.connect(self.accept), bb.rejected.connect(self.reject) h.addStretch(10), h.addWidget(self.buttonBox) for format in formats: self.formats.addItem( QListWidgetItem( file_icon_provider().icon_from_ext(format.lower()), format.upper())) self._formats = formats self.formats.setCurrentRow(0) self._format = self.open_with_format = None if show_open_with: self.populate_open_with() self.update_open_with_button()
def create_toolbars(self): self.action_bar = b = self.addToolBar(_('File actions tool bar')) b.setObjectName('action_bar') # Needed for saveState for x in ('undo', 'redo'): b.addAction(getattr(self.canvas, '%s_action' % x)) self.edit_bar = b = self.addToolBar(_('Edit actions tool bar')) b.setObjectName('edit-actions-bar') for x in ('copy', 'paste'): ac = actions['editor-%s' % x] setattr(self, 'action_' + x, b.addAction(ac.icon(), x, getattr(self, x))) self.update_clipboard_actions() b.addSeparator() self.action_trim = ac = b.addAction(QIcon(I('trim.png')), _('Trim image'), self.canvas.trim_image) self.action_rotate = ac = b.addAction(QIcon(I('rotate-right.png')), _('Rotate image'), self.canvas.rotate_image) self.action_resize = ac = b.addAction(QIcon(I('resize.png')), _('Resize image'), self.resize_image) b.addSeparator() self.action_filters = ac = b.addAction(QIcon(I('filter.png')), _('Image filters')) b.widgetForAction(ac).setPopupMode(QToolButton.InstantPopup) self.filters_menu = m = QMenu() ac.setMenu(m) m.addAction(_('Auto-trim image'), self.canvas.autotrim_image) m.addAction(_('Sharpen image'), self.sharpen_image) m.addAction(_('Blur image'), self.blur_image) m.addAction(_('De-speckle image'), self.canvas.despeckle_image) self.info_bar = b = self.addToolBar(_('Image information bar')) b.setObjectName('image_info_bar') self.fmt_label = QLabel('') b.addWidget(self.fmt_label) b.addSeparator() self.size_label = QLabel('') b.addWidget(self.size_label) self.bars = [self.action_bar, self.edit_bar, self.info_bar] for x in self.bars: x.setFloatable(False) x.topLevelChanged.connect(self.toolbar_floated) x.setIconSize(QSize(tprefs['toolbar_icon_size'], tprefs['toolbar_icon_size'])) self.restore_state()
def __init__(self, parent, db): QObject.__init__(self, parent) self.internet_connection_failed = False self._parent = parent self.no_internet_msg = _( 'Cannot download news as no internet connection ' 'is active') self.no_internet_dialog = d = error_dialog(self._parent, self.no_internet_msg, _('No internet connection'), show_copy_button=False) d.setModal(False) self.recipe_model = RecipeModel() self.db = db self.lock = QMutex(QMutex.Recursive) self.download_queue = set([]) self.news_menu = QMenu() self.news_icon = QIcon(I('news.png')) self.scheduler_action = QAction(QIcon(I('scheduler.png')), _('Schedule news download'), self) self.news_menu.addAction(self.scheduler_action) self.scheduler_action.triggered[bool].connect(self.show_dialog) self.cac = QAction(QIcon(I('user_profile.png')), _('Add or edit a custom news source'), self) self.cac.triggered[bool].connect(self.customize_feeds) self.news_menu.addAction(self.cac) self.news_menu.addSeparator() self.all_action = self.news_menu.addAction( _('Download all scheduled news sources'), self.download_all_scheduled) self.timer = QTimer(self) self.timer.start(int(self.INTERVAL * 60 * 1000)) self.timer.timeout.connect(self.check) self.oldest = gconf['oldest_news'] QTimer.singleShot(5 * 1000, self.oldest_check)
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 init_find_in_grouped_search(menu, field, value, book_info): from calibre.gui2.ui import get_gui db = get_gui().current_db fm = db.field_metadata field_name = fm.get(field, {}).get('name', None) if field_name is None: # I don't think this can ever happen, but ... return gsts = db.prefs.get('grouped_search_terms', {}) gsts_to_show = [] for v in gsts: fk = fm.search_term_to_field_key(v) if field in fk: gsts_to_show.append(v) if gsts_to_show: m = QMenu( (_('Search calibre for %s') + '...') % escape_for_menu(value), menu) m.setIcon(QIcon(I('search.png'))) menu.addMenu(m) m.addAction(QIcon(get_icon_path(field, '')), _('in category %s') % escape_for_menu(field_name), lambda g=field: book_info.search_requested( '{}:"={}"'.format(g, value.replace('"', r'\"')))) for gst in gsts_to_show: icon_path = get_icon_path(gst, '@') m.addAction(QIcon(icon_path), _('in grouped search %s') % gst, lambda g=gst: book_info.search_requested( '{}:"={}"'.format(g, value.replace('"', r'\"')))) else: menu.addAction(QIcon(I('search.png')), _('Search calibre for {val} in category {name}').format( val=escape_for_menu(value), name=escape_for_menu(field_name)), lambda g=field: book_info.search_requested( '{}:"={}"'.format(g, value.replace('"', r'\"'))))
def eventFilter(self, obj, event): base = super(Central, self) if obj is not self.editor_tabs.tabBar() or event.type( ) != QEvent.MouseButtonPress or event.button() not in (Qt.RightButton, Qt.MidButton): return base.eventFilter(obj, event) index = self.editor_tabs.tabBar().tabAt(event.pos()) if index < 0: return base.eventFilter(obj, event) if event.button() == Qt.MidButton: self._close_requested(index) ed = self.editor_tabs.widget(index) if ed is not None: menu = QMenu(self) menu.addAction(actions['close-current-tab'].icon(), _('Close tab'), partial(self.close_requested.emit, ed)) menu.addSeparator() menu.addAction(actions['close-all-but-current-tab'].icon(), _('Close other tabs'), partial(self.close_all_but, ed)) menu.exec_(self.editor_tabs.tabBar().mapToGlobal(event.pos())) return True
def create_action(self, for_toolbar=True): self.plugin_prefs = JSONConfig('plugins/{0}_SpanDivEdit'.format(PLUGIN_SAFE_NAME)) self.plugin_prefs.defaults['parse_current'] = True # Create an action, this will be added to the plugins toolbar and # the plugins menu ac = QAction(get_icon('images/spandivedit_icon.png'), _('Edit Spans && Divs'), self.gui) self.restore_prefs() if not for_toolbar: # Register a keyboard shortcut for this toolbar action. We only # register it for the action created for the menu, not the toolbar, # to avoid a double trigger self.register_shortcut(ac, 'edit-spans-divs', default_keys=('Ctrl+Shift+Alt+E',)) else: menu = QMenu() ac.setMenu(menu) checked_menu_item = menu.addAction(_('Edit current file only'), self.toggle_parse_current) checked_menu_item.setCheckable(True) checked_menu_item.setChecked(self.parse_current) menu.addSeparator() config_menu_item = menu.addAction(_('Customize'), self.show_configuration) ac.triggered.connect(self.dispatcher) return ac
def openTreeContextMenu(self, position): menu = QMenu() menu.addAction("Put to plot (1,1)", lambda: self.plotManagers[0].putGraph()) menu.addAction("Put to plot (1,2)", lambda: self.plotManagers[1].putGraph()) menu.addAction("Put to plot (1,3)", lambda: self.plotManagers[2].putGraph()) menu.addAction("Put to plot (2,1)", lambda: self.plotManagers[3].putGraph()) menu.addAction("Put to plot (2,2)", lambda: self.plotManagers[4].putGraph()) menu.addAction("Put to plot (2,3)", lambda: self.plotManagers[5].putGraph()) menu.addAction("Put to plot (3,1)", lambda: self.plotManagers[6].putGraph()) menu.addAction("Put to plot (3,2)", lambda: self.plotManagers[7].putGraph()) menu.addAction("Put to plot (3,3)", lambda: self.plotManagers[8].putGraph()) menu.addAction("Add to table", lambda: self.tableManager.addParameter()) menu.exec_(self.treeView.viewport().mapToGlobal(position))
def context_menu(self, pos): index = self.indexAt(pos) if index.isValid(): try: char_code = int(self.model().data(index, Qt.UserRole)) except (TypeError, ValueError): pass else: m = QMenu(self) m.addAction( QIcon(I('edit-copy.png')), _('Copy %s to clipboard') % codepoint_to_chr(char_code), partial(self.copy_to_clipboard, char_code)) m.addAction( QIcon(I('rating.png')), (_('Remove %s from favorites') if self.showing_favorites else _('Add %s to favorites')) % codepoint_to_chr(char_code), partial(self.remove_from_favorites, char_code)) if self.showing_favorites: m.addAction(_('Restore favorites to defaults'), self.restore_defaults) m.exec_(self.mapToGlobal(pos))
def clone_changed(self): otext = self.text() self.setText(self.clone.text()) if otext != self.text: self.text_changed.emit() ov = self.isVisible() self.setVisible(self.clone.isVisible()) if ov != self.isVisible(): self.visibility_changed.emit() self.setEnabled(self.clone.isEnabled()) self.setCheckable(self.clone.isCheckable()) self.setChecked(self.clone.isChecked()) self.setIcon(self.clone.icon()) if self.clone_shortcuts: self.setShortcuts(self.clone.shortcuts()) if self.clone.menu() is None: if not self.is_top_level: self.setMenu(None) else: m = QMenu(self.text(), self.parent()) m.aboutToShow.connect(self.about_to_show) self.setMenu(m) self.clone_menu()
def show_context_menu(self, point): index = self.indexAt(point) h = index.data(Qt.ItemDataRole.UserRole) self.context_menu = m = QMenu(self) if h is not None: m.addAction(QIcon(I('edit_input.png')), _('Modify this highlight'), self.edit_requested.emit) m.addAction(QIcon(I('edit_input.png')), _('Edit notes for this highlight'), self.edit_notes_requested.emit) m.addAction( QIcon(I('trash.png')), ngettext('Delete this highlight', 'Delete selected highlights', len(self.selectedItems())), self.delete_requested.emit) if h.get('notes'): m.addAction(QIcon(I('modified.png')), _('Edit notes for this highlight'), self.edit_notes_requested.emit) m.addSeparator() m.addAction(_('Expand all'), self.expandAll) m.addAction(_('Collapse all'), self.collapseAll) self.context_menu.popup(self.mapToGlobal(point)) return True
def contextMenuEvent(self, e): row = self.currentRow() if self.item(row): event = self.item(row).data(Qt.UserRole) menu = QMenu(self) edit_action = menu.addAction( self.style().standardIcon( QStyle.SP_FileDialogDetailedView), 'Edit') edit_action.triggered.connect( lambda: self.popup_event_editor(row)) menu.addAction(self.new) # insert_action = menu.addAction( # self.style().standardIcon(QStyle.SP_FileIcon), # 'Insert Event' # ) # insert_action.triggered.connect( # lambda: self.insert_event(self.currentRow(), self.NOP.copy()) # ) if event.pointers: follow_action = menu.addAction( self.style().standardIcon(QStyle.SP_ArrowForward), 'Follow') follow_action.triggered.connect(lambda: self.follow(row)) menu.exec_(e.globalPos())
def contextMenuEvent(self, ev): menu = QMenu(self) data = self._page.contextMenuData() url = data.linkUrl() url = unicode_type(url.toString(NO_URL_FORMATTING)).strip() text = data.selectedText() if text: ca = self.pageAction(QWebEnginePage.WebAction.Copy) if ca.isEnabled(): menu.addAction(ca) menu.addAction(actions['reload-preview']) menu.addAction(QIcon(I('debug.png')), _('Inspect element'), self.inspect) if url.partition(':')[0].lower() in {'http', 'https'}: menu.addAction(_('Open link'), partial(safe_open_url, data.linkUrl())) if QWebEngineContextMenuData.MediaType.MediaTypeImage <= data.mediaType( ) <= QWebEngineContextMenuData.MediaType.MediaTypeFile: url = data.mediaUrl() if url.scheme() == FAKE_PROTOCOL: href = url.path().lstrip('/') if href: c = current_container() resource_name = c.href_to_name(href) if resource_name and c.exists( resource_name ) and resource_name not in c.names_that_must_not_be_changed: self.add_open_with_actions(menu, resource_name) if data.mediaType( ) == QWebEngineContextMenuData.MediaType.MediaTypeImage: mime = c.mime_map[resource_name] if mime.startswith('image/'): menu.addAction( _('Edit %s') % resource_name, partial(self.edit_image, resource_name)) menu.exec_(ev.globalPos())
def genesis(self): # This method is called once per plugin, do initial setup here # Set the icon for this interface action # The get_icons function is a builtin function defined for all your # plugin code. It loads icons from the plugin zip file. It returns # QIcon objects, if you want the actual data, use the analogous # get_resources builtin function. # # Note that if you are loading more than one icon, for performance, you # should pass a list of names to get_icons. In this case, get_icons # will return a dictionary mapping names to QIcons. Names that # are not found in the zip file will result in null QIcons. self.sync_selected_action = self.create_action( spec=('Sync selected books', None, None, None), attr='Sync selected books') self.sync_selected_action.triggered.connect(self.sync_selected) self.sync_all_action = self.create_action(spec=('Sync all books', None, None, None), attr='Sync all books') self.sync_all_action.triggered.connect(self.sync_all) self.menu = QMenu(self.gui) self.menu.addAction(self.sync_selected_action) self.menu.addAction(self.sync_all_action) self.menu.aboutToShow.connect(self.update_menu) # The qaction is automatically created from the action_spec defined # above #self.qaction.triggered.connect(self.show_dialog) icon = get_icons('images/icon.svg') self.qaction.setMenu(self.menu) self.qaction.setIcon(icon) self.qaction.triggered.connect(self.sync_selected)
def ac(name, text, icon, tooltip): icon = QIcon(I(icon)) ac = self.location_actions.addAction(icon, text) setattr(self, 'location_' + name, ac) ac.setAutoRepeat(False) ac.setCheckable(True) receiver = partial(self._location_selected, name) ac.triggered.connect(receiver) self.tooltips[name] = tooltip m = QMenu(parent) self._mem.append(m) a = m.addAction(icon, tooltip) a.triggered.connect(receiver) if name != 'library': self._mem.append(a) a = m.addAction(QIcon(I('eject.png')), _('Eject this device')) a.triggered.connect(self._eject_requested) self._mem.append(a) a = m.addAction(QIcon(I('config.png')), _('Configure this device')) a.triggered.connect(self._configure_requested) self._mem.append(a) a = m.addAction(QIcon(I('sync.png')), _('Update cached metadata on device')) a.triggered.connect( lambda x: self.update_device_metadata.emit()) self._mem.append(a) else: ac.setToolTip(tooltip) ac.setMenu(m) ac.calibre_name = name self.all_actions.append(ac) return ac
def initUI(self): # 添加打开菜单 openFile = QAction(QIcon('open.png'), 'Open', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Open new File') openFile.triggered.connect(self.openFile) openFile.setIcon(QIcon('import.ico')) menubar = self.menuBar() fileMenu = menubar.addMenu('&File') fileMenu.addAction(openFile) toolBar = self.addToolBar("File") toolBar.addAction(openFile) # 设置PlotWidget self.dataPlot.plotItem.showGrid(True, True, 0.5) self.dataPlotRange.setMouseEnabled(x=False, y=False) # dataPlotRange 不能移动 self.dataPlot.setAutoVisible(y=True) # 设置treeWidget的相关 self.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu) self.treeWidget.customContextMenuRequested.connect( self.showContextMenu) self.treeWidget.treeContextMenu = QMenu(self) self.actionA = self.treeWidget.treeContextMenu.addAction(u'Plot') self.actionA.triggered.connect(lambda: self.chartPlot( self.treeWidget.currentItem(), self.treeWidget.selectedItems())) self.treeWidget.setColumnCount(4) self.treeWidget.setHeaderLabels( ['#', 'File Name', 'Corrective Name', 'Unit']) self.treeWidget.setColumnWidth(0, 30) self.treeWidget.setColumnWidth(1, 100) self.treeWidget.setColumnWidth(2, 200)
def show_context_menu(self, pos): m = QMenu(self) a = m.addAction c = self.editor.cursorForPosition(pos) origc = QTextCursor(c) current_cursor = self.editor.textCursor() r = origr = self.editor.syntax_range_for_cursor(c) if ( r is None or not r.format.property(SPELL_PROPERTY) ) and c.positionInBlock() > 0 and not current_cursor.hasSelection(): c.setPosition(c.position() - 1) r = self.editor.syntax_range_for_cursor(c) if r is not None and r.format.property(SPELL_PROPERTY): word = self.editor.text_for_range(c.block(), r) locale = self.editor.spellcheck_locale_for_cursor(c) orig_pos = c.position() c.setPosition(orig_pos - utf16_length(word)) found = False self.editor.setTextCursor(c) if self.editor.find_spell_word([word], locale.langcode, center_on_cursor=False): found = True fc = self.editor.textCursor() if fc.position() < c.position(): self.editor.find_spell_word([word], locale.langcode, center_on_cursor=False) spell_cursor = self.editor.textCursor() if current_cursor.hasSelection(): # Restore the current cursor so that any selection is preserved # for the change case actions self.editor.setTextCursor(current_cursor) if found: suggestions = dictionaries.suggestions(word, locale)[:7] if suggestions: for suggestion in suggestions: ac = m.addAction( suggestion, partial(self.editor.simple_replace, suggestion, cursor=spell_cursor)) f = ac.font() f.setBold(True), ac.setFont(f) m.addSeparator() m.addAction(actions['spell-next']) m.addAction(_('Ignore this word'), partial(self._nuke_word, None, word, locale)) dics = dictionaries.active_user_dictionaries if len(dics) > 0: if len(dics) == 1: m.addAction( _('Add this word to the dictionary: {0}').format( dics[0].name), partial(self._nuke_word, dics[0].name, word, locale)) else: ac = m.addAction(_('Add this word to the dictionary')) dmenu = QMenu(m) ac.setMenu(dmenu) for dic in dics: dmenu.addAction( dic.name, partial(self._nuke_word, dic.name, word, locale)) m.addSeparator() if origr is not None and origr.format.property(LINK_PROPERTY): href = self.editor.text_for_range(origc.block(), origr) m.addAction( _('Open %s') % href, partial(self.link_clicked.emit, href)) if origr is not None and (origr.format.property(TAG_NAME_PROPERTY) or origr.format.property(CSS_PROPERTY)): word = self.editor.text_for_range(origc.block(), origr) item_type = 'tag_name' if origr.format.property( TAG_NAME_PROPERTY) else 'css_property' url = help_url(word, item_type, self.editor.highlighter.doc_name, extra_data=current_container().opf_version) if url is not None: m.addAction( _('Show help for: %s') % word, partial(open_url, url)) for x in ('undo', 'redo'): ac = actions['editor-%s' % x] if ac.isEnabled(): a(ac) m.addSeparator() for x in ('cut', 'copy', 'paste'): ac = actions['editor-' + x] if ac.isEnabled(): a(ac) m.addSeparator() m.addAction(_('&Select all'), self.editor.select_all) if self.selected_text or self.has_marked_text: update_mark_text_action(self) m.addAction(actions['mark-selected-text']) if self.syntax != 'css' and actions['editor-cut'].isEnabled(): cm = QMenu(_('Change &case'), m) for ac in 'upper lower swap title capitalize'.split(): cm.addAction(actions['transform-case-' + ac]) m.addMenu(cm) if self.syntax == 'html': m.addAction(actions['multisplit']) m.exec_(self.editor.viewport().mapToGlobal(pos))
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.content_server = None 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 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 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(horizontal=True, 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.donate_button.clicked.connect(self.donate_action.trigger) self.donate_button.setToolTip(self.donate_action.text().replace( '&', '')) self.donate_button.setIcon(self.donate_action.icon()) self.donate_button.setStatusTip(self.donate_button.toolTip()) 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 if show_gui: 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.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) # ######################## 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 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() if self.bars_manager.showing_donate: self.donate_button.start_animation() self.set_window_title() for ac in 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() 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 __init__(self, parent): QWidget.__init__(self, parent) self.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Preferred) parent = parent.parent() self.l = l = QHBoxLayout(self) l.setContentsMargins(0, 0, 0, 0) self.alter_tb = parent.alter_tb = b = QToolButton(self) b.setAutoRaise(True) b.setText(_('Configure')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) b.setCursor(Qt.PointingHandCursor) b.setPopupMode(b.InstantPopup) b.setToolTip(textwrap.fill(_( 'Change how the Tag browser works, such as,' ' how it is sorted, what happens when you click' ' items, etc.' ))) b.setIcon(QIcon(I('config.png'))) b.m = QMenu() b.setMenu(b.m) self.item_search = FindBox(parent) self.item_search.setMinimumContentsLength(5) self.item_search.setSizeAdjustPolicy(self.item_search.AdjustToMinimumContentsLengthWithIcon) self.item_search.initialize('tag_browser_search') self.item_search.completer().setCaseSensitivity(Qt.CaseSensitive) self.item_search.setToolTip( '<p>' +_( 'Search for items. If the text begins with equals (=) the search is ' 'exact match, otherwise it is "contains" finding items containing ' 'the text anywhere in the item name. Both exact and contains ' 'searches ignore case. You can limit the search to particular ' 'categories using syntax similar to search. For example, ' 'tags:foo will find foo in any tag, but not in authors etc. Entering ' '*foo will collapse all categories then showing only those categories ' 'with items containing the text "foo"') + '</p') ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser find box', _('Find next match'), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(self.set_focus_to_find_box) self.search_button = QToolButton() self.search_button.setAutoRaise(True) self.search_button.setCursor(Qt.PointingHandCursor) self.search_button.setIcon(QIcon(I('search.png'))) self.search_button.setToolTip(_('Find the first/next matching item')) ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser find button', _('Find in Tag browser'), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(self.search_button.click) self.toggle_search_button = b = QToolButton(self) le = self.item_search.lineEdit() le.addAction(QIcon(I('window-close.png')), le.LeadingPosition).triggered.connect(self.close_find_box) b.setText(_('Find')), b.setToolButtonStyle(Qt.ToolButtonTextBesideIcon) b.setCursor(Qt.PointingHandCursor) b.setIcon(QIcon(I('search.png'))) b.setCheckable(True) b.setChecked(gprefs.get('tag browser search box visible', False)) b.setToolTip(_('Search for items in the Tag browser')) b.setAutoRaise(True) b.toggled.connect(self.update_searchbar_state) self.update_searchbar_state()
def __init__(self, parent): QFrame.__init__(self, parent) self.setFrameStyle(QFrame.NoFrame if gprefs['tag_browser_old_look'] else QFrame.StyledPanel) self._parent = parent self._layout = QVBoxLayout(self) self._layout.setContentsMargins(0,0,0,0) # Set up the find box & button self.tb_bar = tbb = TagBrowserBar(self) tbb.clear_find.connect(self.reset_find) self.alter_tb, self.item_search, self.search_button = tbb.alter_tb, tbb.item_search, tbb.search_button self.toggle_search_button = tbb.toggle_search_button self._layout.addWidget(tbb) self.current_find_position = None self.search_button.clicked.connect(self.find) self.item_search.lineEdit().textEdited.connect(self.find_text_changed) self.item_search.activated[str].connect(self.do_find) # The tags view parent.tags_view = TagsView(parent) self.tags_view = parent.tags_view self._layout.insertWidget(0, parent.tags_view) # Now the floating 'not found' box l = QLabel(self.tags_view) self.not_found_label = l l.setFrameStyle(QFrame.StyledPanel) l.setAutoFillBackground(True) l.setText('<p><b>'+_('No more matches.</b><p> Click Find again to go to first match')) l.setAlignment(Qt.AlignVCenter) l.setWordWrap(True) l.resize(l.sizeHint()) l.move(10,20) 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) # The Alter Tag Browser button l = self.alter_tb self.collapse_all_action = ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser collapse all', _('Collapse all'), default_keys=(), action=ac, group=_('Tag browser')) connect_lambda(ac.triggered, self, lambda self: self.tags_view.collapseAll()) ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser alter', _('Configure Tag browser'), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(l.showMenu) sb = l.m.addAction(_('Sort by')) sb.m = l.sort_menu = QMenu(l.m) sb.setMenu(sb.m) sb.bg = QActionGroup(sb) # Must be in the same order as db2.CATEGORY_SORTS for i, x in enumerate((_('Name'), _('Number of books'), _('Average rating'))): a = sb.m.addAction(x) sb.bg.addAction(a) a.setCheckable(True) if i == 0: a.setChecked(True) sb.setToolTip( _('Set the sort order for entries in the Tag browser')) sb.setStatusTip(sb.toolTip()) ma = l.m.addAction(_('Search type when selecting multiple items')) ma.m = l.match_menu = QMenu(l.m) ma.setMenu(ma.m) ma.ag = QActionGroup(ma) # Must be in the same order as db2.MATCH_TYPE for i, x in enumerate((_('Match any of the items'), _('Match all of the items'))): a = ma.m.addAction(x) ma.ag.addAction(a) a.setCheckable(True) if i == 0: a.setChecked(True) ma.setToolTip( _('When selecting multiple entries in the Tag browser ' 'match any or all of them')) ma.setStatusTip(ma.toolTip()) mt = l.m.addAction(_('Manage authors, tags, etc.')) mt.setToolTip(_('All of these category_managers are available by right-clicking ' 'on items in the Tag browser above')) mt.m = l.manage_menu = QMenu(l.m) mt.setMenu(mt.m) ac = QAction(parent) parent.addAction(ac) parent.keyboard.register_shortcut('tag browser toggle item', _("'Click' found item"), default_keys=(), action=ac, group=_('Tag browser')) ac.triggered.connect(self.toggle_item)
def genesis(self): self.prev_lname = self.last_lname = '' self.count_changed(0) self.action_choose = self.menuless_qaction self.action_exim = ac = QAction(_('Export/import all calibre data'), self.gui) ac.triggered.connect(self.exim_data) self.stats = LibraryUsageStats() self.popup_type = (QToolButton.InstantPopup if len(self.stats.stats) > 1 else QToolButton.MenuButtonPopup) if len(self.stats.stats) > 1: self.action_choose.triggered.connect(self.choose_library) else: self.qaction.triggered.connect(self.choose_library) self.choose_menu = self.qaction.menu() ac = self.create_action(spec=(_('Pick a random book'), 'random.png', None, None), attr='action_pick_random') ac.triggered.connect(self.pick_random) if not os.environ.get('CALIBRE_OVERRIDE_DATABASE_PATH', None): self.choose_menu.addAction(self.action_choose) self.quick_menu = QMenu(_('Quick switch')) self.quick_menu_action = self.choose_menu.addMenu(self.quick_menu) self.rename_menu = QMenu(_('Rename library')) self.rename_menu_action = self.choose_menu.addMenu( self.rename_menu) self.choose_menu.addAction(ac) self.delete_menu = QMenu(_('Remove library')) self.delete_menu_action = self.choose_menu.addMenu( self.delete_menu) self.choose_menu.addAction(self.action_exim) else: self.choose_menu.addAction(ac) self.rename_separator = self.choose_menu.addSeparator() self.switch_actions = [] for i in range(5): ac = self.create_action(spec=('', None, None, None), attr='switch_action%d' % i) ac.setObjectName(unicode_type(i)) self.switch_actions.append(ac) ac.setVisible(False) connect_lambda( ac.triggered, self, lambda self: self.switch_requested(self.qs_locations[int( self.gui.sender().objectName())]), type=Qt.QueuedConnection) self.choose_menu.addAction(ac) self.rename_separator = self.choose_menu.addSeparator() self.maintenance_menu = QMenu(_('Library maintenance')) ac = self.create_action(spec=(_('Library metadata backup status'), 'lt.png', None, None), attr='action_backup_status') ac.triggered.connect(self.backup_status, type=Qt.QueuedConnection) self.maintenance_menu.addAction(ac) ac = self.create_action(spec=(_('Check library'), 'lt.png', None, None), attr='action_check_library') ac.triggered.connect(self.check_library, type=Qt.QueuedConnection) self.maintenance_menu.addAction(ac) ac = self.create_action(spec=(_('Restore database'), 'lt.png', None, None), attr='action_restore_database') ac.triggered.connect(self.restore_database, type=Qt.QueuedConnection) self.maintenance_menu.addAction(ac) self.choose_menu.addMenu(self.maintenance_menu) self.view_state_map = {} self.restore_view_state.connect(self._restore_view_state, type=Qt.QueuedConnection) ac = self.create_action(spec=(_('Switch to previous library'), 'lt.png', None, None), attr='action_previous_library') ac.triggered.connect(self.switch_to_previous_library, type=Qt.QueuedConnection) self.gui.keyboard.register_shortcut(self.unique_name + '-' + 'action_previous_library', ac.text(), action=ac, group=self.action_spec[0], default_keys=('Ctrl+Alt+p', )) self.gui.addAction(ac)
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)
def __init__(self, parent=None): QTextEdit.__init__(self, parent) self.setTabChangesFocus(True) self.document().setDefaultStyleSheet(css()) font = self.font() f = QFontInfo(font) delta = tweaks['change_book_details_font_size_by'] + 1 if delta: font.setPixelSize(f.pixelSize() + delta) self.setFont(font) f = QFontMetrics(self.font()) self.em_size = f.horizontalAdvance('m') self.base_url = None self._parent = weakref.ref(parent) self.comments_pat = re.compile(r'<!--.*?-->', re.DOTALL) extra_shortcuts = { 'bold': 'Bold', 'italic': 'Italic', 'underline': 'Underline', } for rec in ( ('bold', 'format-text-bold', _('Bold'), True), ('italic', 'format-text-italic', _('Italic'), True), ('underline', 'format-text-underline', _('Underline'), True), ('strikethrough', 'format-text-strikethrough', _('Strikethrough'), True), ('superscript', 'format-text-superscript', _('Superscript'), True), ('subscript', 'format-text-subscript', _('Subscript'), True), ('ordered_list', 'format-list-ordered', _('Ordered list'), True), ('unordered_list', 'format-list-unordered', _('Unordered list'), True), ('align_left', 'format-justify-left', _('Align left'), True), ('align_center', 'format-justify-center', _('Align center'), True), ('align_right', 'format-justify-right', _('Align right'), True), ('align_justified', 'format-justify-fill', _('Align justified'), True), ('undo', 'edit-undo', _('Undo'), ), ('redo', 'edit-redo', _('Redo'), ), ('remove_format', 'edit-clear', _('Remove formatting'), ), ('copy', 'edit-copy', _('Copy'), ), ('paste', 'edit-paste', _('Paste'), ), ('paste_and_match_style', 'edit-paste', _('Paste and match style'), ), ('cut', 'edit-cut', _('Cut'), ), ('indent', 'format-indent-more', _('Increase indentation'), ), ('outdent', 'format-indent-less', _('Decrease indentation'), ), ('select_all', 'edit-select-all', _('Select all'), ), ('color', 'format-text-color', _('Foreground color')), ('background', 'format-fill-color', _('Background color')), ('insert_link', 'insert-link', _('Insert link or image'),), ('insert_hr', 'format-text-hr', _('Insert separator'),), ('clear', 'trash', _('Clear')), ): name, icon, text = rec[:3] checkable = len(rec) == 4 ac = QAction(QIcon(I(icon + '.png')), text, self) if checkable: ac.setCheckable(checkable) setattr(self, 'action_'+name, ac) ss = extra_shortcuts.get(name) if ss is not None: ac.setShortcut(QKeySequence(getattr(QKeySequence, ss))) ac.triggered.connect(getattr(self, 'do_' + name)) 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 = [] h = _('Heading {0}') for text, name in ( (_('Normal'), 'p'), (h.format(1), 'h1'), (h.format(2), 'h2'), (h.format(3), 'h3'), (h.format(4), 'h4'), (h.format(5), 'h5'), (h.format(6), 'h6'), (_('Blockquote'), 'blockquote'), ): ac = QAction(text, self) self.block_style_menu.addAction(ac) ac.block_name = name ac.setCheckable(True) self.block_style_actions.append(ac) ac.triggered.connect(self.do_format_block) self.setHtml('') self.copyAvailable.connect(self.update_clipboard_actions) self.update_clipboard_actions(False) self.selectionChanged.connect(self.update_selection_based_actions) self.update_selection_based_actions() connect_lambda(self.undoAvailable, self, lambda self, yes: self.action_undo.setEnabled(yes)) connect_lambda(self.redoAvailable, self, lambda self, yes: self.action_redo.setEnabled(yes)) self.action_undo.setEnabled(False), self.action_redo.setEnabled(False) self.textChanged.connect(self.update_cursor_position_actions) self.cursorPositionChanged.connect(self.update_cursor_position_actions) self.textChanged.connect(self.data_changed) self.update_cursor_position_actions()
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)
def __init__(self, field_metadata, parent=None, revert_tooltip=None, datetime_fmt='MMMM yyyy', blank_as_equal=True, fields=('title', 'authors', 'series', 'tags', 'rating', 'publisher', 'pubdate', 'identifiers', 'languages', 'comments', 'cover'), db=None): QWidget.__init__(self, parent) self.l = l = QGridLayout() l.setContentsMargins(0, 0, 0, 0) self.setLayout(l) revert_tooltip = revert_tooltip or _('Revert %s') self.current_mi = None self.changed_font = QFont(QApplication.font()) self.changed_font.setBold(True) self.changed_font.setItalic(True) self.blank_as_equal = blank_as_equal self.widgets = OrderedDict() row = 0 for field in fields: m = field_metadata[field] dt = m['datatype'] extra = None if 'series' in {field, dt}: cls = SeriesEdit elif field == 'identifiers': cls = IdentifiersEdit elif field == 'languages': cls = LanguagesEdit elif 'comments' in {field, dt}: cls = CommentsEdit elif 'rating' in {field, dt}: cls = RatingsEdit elif dt == 'datetime': extra = datetime_fmt cls = DateEdit elif field == 'cover': cls = CoverView elif dt in {'text', 'enum'}: cls = LineEdit else: continue neww = cls(field, True, self, m, extra) neww.changed.connect(partial(self.changed, field)) if isinstance(neww, EditWithComplete): try: neww.update_items_cache(db.new_api.all_field_names(field)) except ValueError: pass # A one-one field like title if isinstance(neww, SeriesEdit): neww.set_db(db.new_api) oldw = cls(field, False, self, m, extra) newl = QLabel('&%s:' % m['name']) newl.setBuddy(neww) button = RightClickButton(self) button.setIcon(QIcon(I('back.png'))) button.clicked.connect(partial(self.revert, field)) button.setToolTip(revert_tooltip % m['name']) if field == 'identifiers': button.m = m = QMenu(button) button.setMenu(m) button.setPopupMode(QToolButton.DelayedPopup) m.addAction(button.toolTip()).triggered.connect(button.click) m.actions()[0].setIcon(button.icon()) m.addAction(_('Merge identifiers')).triggered.connect( self.merge_identifiers) m.actions()[1].setIcon(QIcon(I('merge.png'))) elif field == 'tags': button.m = m = QMenu(button) button.setMenu(m) button.setPopupMode(QToolButton.DelayedPopup) m.addAction(button.toolTip()).triggered.connect(button.click) m.actions()[0].setIcon(button.icon()) m.addAction(_('Merge tags')).triggered.connect(self.merge_tags) m.actions()[1].setIcon(QIcon(I('merge.png'))) self.widgets[field] = Widgets(neww, oldw, newl, button) for i, w in enumerate((newl, neww, button, oldw)): c = i if i < 2 else i + 1 if w is oldw: c += 1 l.addWidget(w, row, c) row += 1 self.sep = f = QFrame(self) f.setFrameShape(f.VLine) l.addWidget(f, 0, 2, row, 1) self.sep2 = f = QFrame(self) f.setFrameShape(f.VLine) l.addWidget(f, 0, 4, row, 1) if 'comments' in self.widgets and not gprefs.get( 'diff_widget_show_comments_controls', True): self.widgets['comments'].new.hide_toolbars()