def __init__(self, vertical, parent=None): QWebView.__init__(self, parent) s = self.settings() s.setAttribute(s.JavascriptEnabled, False) self.vertical = vertical self.page().setLinkDelegationPolicy(self.page().DelegateAllLinks) self.linkClicked.connect(self.link_activated) self._link_clicked = False self.setAttribute(Qt.WA_OpaquePaintEvent, False) palette = self.palette() self.setAcceptDrops(False) palette.setBrush(QPalette.Base, Qt.transparent) self.page().setPalette(palette) self.css = P('templates/book_details.css', data=True).decode('utf-8') for x, icon in [('remove_format', 'trash.png'), ('save_format', 'save.png'), ('restore_format', 'edit-undo.png'), ('copy_link', 'edit-copy.png'), ('manage_author', 'user_profile.png'), ('compare_format', 'diff.png')]: ac = QAction(QIcon(I(icon)), '', self) ac.current_fmt = None ac.current_url = None ac.triggered.connect(getattr(self, '%s_triggerred' % x)) setattr(self, '%s_action' % x, ac)
def __init__(self, horizontal=False, size=48, parent=None): QFrame.__init__(self, parent) if horizontal: size = 24 self.pi = ProgressIndicator(self, size) self._jobs = QLabel('<b>' + _('Jobs:') + ' 0') self._jobs.mouseReleaseEvent = self.mouseReleaseEvent self.shortcut = _('Shift+Alt+J') if horizontal: self.setLayout(QHBoxLayout()) self.layout().setDirection(self.layout().RightToLeft) else: self.setLayout(QVBoxLayout()) self._jobs.setAlignment(Qt.AlignHCenter | Qt.AlignBottom) self.layout().addWidget(self.pi) self.layout().addWidget(self._jobs) if not horizontal: self.layout().setAlignment(self._jobs, Qt.AlignHCenter) self._jobs.setMargin(0) self.layout().setMargin(0) self._jobs.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.setCursor(Qt.PointingHandCursor) b = _('Click to see list of jobs') self.setToolTip(b + u' (%s)' % self.shortcut) self.action_toggle = QAction(b, parent) parent.addAction(self.action_toggle) self.action_toggle.setShortcut(self.shortcut) self.action_toggle.triggered.connect(self.toggle)
def __init__(self, vertical, parent=None): QWebView.__init__(self, parent) s = self.settings() s.setAttribute(s.JavascriptEnabled, False) self.vertical = vertical self.page().setLinkDelegationPolicy(self.page().DelegateAllLinks) self.linkClicked.connect(self.link_activated) self._link_clicked = False self.setAttribute(Qt.WA_OpaquePaintEvent, False) palette = self.palette() self.setAcceptDrops(False) palette.setBrush(QPalette.Base, Qt.transparent) self.page().setPalette(palette) self.css = P("templates/book_details.css", data=True).decode("utf-8") for x, icon in [ ("remove_format", "trash.png"), ("save_format", "save.png"), ("restore_format", "edit-undo.png"), ("copy_link", "edit-copy.png"), ("manage_author", "user_profile.png"), ("compare_format", "diff.png"), ]: ac = QAction(QIcon(I(icon)), "", self) ac.current_fmt = None ac.current_url = None ac.triggered.connect(getattr(self, "%s_triggerred" % x)) setattr(self, "%s_action" % x, ac)
def reg(icon, text, target, sid, keys, description, toolbar_allowed=False): if not isinstance(icon, QIcon): icon = QIcon(I(icon)) ac = actions[sid] = QAction(icon, text, self) if icon else QAction( text, self) ac.setObjectName('action-' + sid) if toolbar_allowed: toolbar_actions[sid] = ac if target is not None: ac.triggered.connect(target) if isinstance(keys, type('')): keys = (keys, ) self.keyboard.register_shortcut(sid, unicode(ac.text()).replace( '&', ''), default_keys=keys, description=description, action=ac, group=group) self.addAction(ac) return ac
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 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 showContextMenu(self, position): SuggestionContextMenu = self.ui.textEdit.createStandardContextMenu() cursor = self.ui.textEdit.textCursor() cursor.select(QTextCursor.WordUnderCursor) self.ui.textEdit.setTextCursor(cursor) if self.ui.textEdit.textCursor().hasSelection(): a = self.ui.textEdit.textCursor().selectedText() if a[-1] == u'।': a = a.remove(u'।') cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor) self.ui.textEdit.setTextCursor(cursor) text = unicode(a).encode('utf-8') if not self.checker.spell(text): ignoreAction = QAction('Ignore', SuggestionContextMenu) ignoreAction.triggered.connect(self.ignoreSelection) addAction = QAction('Add to Dictionary', SuggestionContextMenu) addAction.triggered.connect(self.addWord) SuggestionContextMenu.insertSeparator( SuggestionContextMenu.actions()[0]) SuggestionContextMenu.insertAction( SuggestionContextMenu.actions()[0], addAction) SuggestionContextMenu.insertAction( SuggestionContextMenu.actions()[0], ignoreAction) SuggestionMenu = QMenu('Spelling Suggestions') for word in self.checker.suggest(text): word = word.decode('utf-8') action = SuggestAction(word, SuggestionMenu) action.correct.connect(self.replaceCorrect) SuggestionMenu.addAction(action) if len(SuggestionMenu.actions()) != 0: SuggestionContextMenu.insertMenu( SuggestionContextMenu.actions()[0], SuggestionMenu) cursor.clearSelection() SuggestionContextMenu.exec_(self.ui.textEdit.mapToGlobal(position)) self.ui.textEdit.setTextCursor(cursor)
def __init__(self, name, label, icon, initial_show=True, initial_side_size=120, connect_button=True, orientation=Qt.Horizontal, side_index=0, parent=None, shortcut=None): QSplitter.__init__(self, parent) self.resize_timer = QTimer(self) self.resize_timer.setSingleShot(True) self.desired_side_size = initial_side_size self.desired_show = initial_show self.resize_timer.setInterval(5) self.resize_timer.timeout.connect(self.do_resize) self.setOrientation(orientation) self.side_index = side_index self._name = name self.label = label self.initial_side_size = initial_side_size self.initial_show = initial_show self.splitterMoved.connect(self.splitter_moved, type=Qt.QueuedConnection) self.button = LayoutButton(icon, label, self, shortcut=shortcut) if connect_button: self.button.clicked.connect(self.double_clicked) if shortcut is not None: self.action_toggle = QAction(QIcon(icon), _('Toggle') + ' ' + label, self) self.action_toggle.triggered.connect(self.toggle_triggered) if parent is not None: parent.addAction(self.action_toggle) if hasattr(parent, 'keyboard'): parent.keyboard.register_shortcut('splitter %s %s'%(name, label), unicode(self.action_toggle.text()), default_keys=(shortcut,), action=self.action_toggle) else: self.action_toggle.setShortcut(shortcut) else: self.action_toggle.setShortcut(shortcut)
def __init__(self): self.search.initialize( 'main_search_history', colorize=True, help_text=_( 'Search (For Advanced Search click the button to the left)')) self.search.cleared.connect(self.search_box_cleared) # Queued so that search.current_text will be correct self.search.changed.connect(self.search_box_changed, type=Qt.QueuedConnection) self.search.focus_to_library.connect(self.focus_to_library) self.clear_button.clicked.connect(self.search.clear_clicked) self.advanced_search_button.clicked[bool].connect( self.do_advanced_search) self.search.clear() self.search.setMaximumWidth(self.width() - 150) self.action_focus_search = QAction(self) shortcuts = QKeySequence.keyBindings(QKeySequence.Find) shortcuts = list(shortcuts) + [ QKeySequence('/'), QKeySequence('Alt+S') ] self.action_focus_search.setShortcuts(shortcuts) self.action_focus_search.triggered.connect(self.focus_search_box) self.addAction(self.action_focus_search) self.search.setStatusTip( re.sub(r'<\w+>', ' ', unicode(self.search.toolTip()))) self.advanced_search_button.setStatusTip( self.advanced_search_button.toolTip()) self.clear_button.setStatusTip(self.clear_button.toolTip()) self.search_highlight_only.stateChanged.connect( self.highlight_only_changed) self.search_highlight_only.setChecked( dynamic.get('search_highlight_only', False))
def addColumnCategory(self, name, columns, visible=True): qa = QAction(name, self) qa.setCheckable(True) qa.setChecked(visible) if not visible: self._showColumnCategory(columns, False) QObject.connect(qa, SIGNAL("toggled(bool)"), self._currier.curry(self._showColumnCategory, columns)) self._column_views.append((name, qa, columns))
def reg(icon, text, target, sid, keys, description): ac = QAction(QIcon(I(icon)), text, self) ac.triggered.connect(target) if isinstance(keys, type('')): keys = (keys,) self.keyboard.register_shortcut( sid, unicode(ac.text()), default_keys=keys, description=description, action=ac, group=group) self.addAction(ac) return ac
class MainWindow(QDialog): def __init__(self, default_status_msg=_('Welcome to') + ' ' + __appname__+' console', parent=None): QDialog.__init__(self, parent) self.restart_requested = False self.l = QVBoxLayout() self.setLayout(self.l) self.resize(800, 600) geom = dynamic.get('console_window_geometry', None) if geom is not None: self.restoreGeometry(geom) # Setup tool bar {{{ self.tool_bar = QToolBar(self) self.tool_bar.setToolButtonStyle(Qt.ToolButtonTextOnly) self.l.addWidget(self.tool_bar) # }}} # Setup status bar {{{ self.status_bar = QStatusBar(self) self.status_bar.defmsg = QLabel(__appname__ + _(' console ') + __version__) self.status_bar._font = QFont() self.status_bar._font.setBold(True) self.status_bar.defmsg.setFont(self.status_bar._font) self.status_bar.addWidget(self.status_bar.defmsg) # }}} self.console = Console(parent=self) self.console.running.connect(partial(self.status_bar.showMessage, _('Code is running'))) self.console.running_done.connect(self.status_bar.clearMessage) self.l.addWidget(self.console) self.l.addWidget(self.status_bar) self.setWindowTitle(__appname__ + ' console') self.setWindowIcon(QIcon(I('console.png'))) self.restart_action = QAction(_('Restart console'), self) self.restart_action.setShortcut(_('Ctrl+R')) self.addAction(self.restart_action) self.restart_action.triggered.connect(self.restart) self.console.context_menu.addAction(self.restart_action) def restart(self): self.restart_requested = True self.reject() def closeEvent(self, *args): dynamic.set('console_window_geometry', bytearray(self.saveGeometry())) self.console.shutdown() return QDialog.closeEvent(self, *args)
def __init__(self, wac, icon, text, checkable, view): QAction.__init__(self, QIcon(I(icon+'.png')), text, view) self._page_action = getattr(QWebPage, wac) self.setCheckable(checkable) self.triggered.connect(self.trigger_page_action) view.selectionChanged.connect(self.update_state, type=Qt.QueuedConnection) self.page_action.changed.connect(self.update_state, type=Qt.QueuedConnection) self.update_state()
def __init__(self, gui): sc = 'Shift+Alt+G' LayoutButton.__init__(self, I('grid.png'), _('Cover Grid'), parent=gui, shortcut=sc) self.set_state_to_show() self.action_toggle = QAction(self.icon(), _('Toggle') + ' ' + self.label, self) gui.addAction(self.action_toggle) gui.keyboard.register_shortcut('grid view toggle' + self.label, unicode(self.action_toggle.text()), default_keys=(sc,), action=self.action_toggle) self.action_toggle.triggered.connect(self.toggle) self.toggled.connect(self.update_state)
def __init__(self, wac, icon, text, checkable, view): QAction.__init__(self, QIcon(I(icon + '.png')), text, view) self._page_action = getattr(QWebPage, wac) self.setCheckable(checkable) self.triggered.connect(self.trigger_page_action) view.selectionChanged.connect(self.update_state, type=Qt.QueuedConnection) self.page_action.changed.connect(self.update_state, type=Qt.QueuedConnection) self.update_state()
def addActionToList(self, txtMenu, whichList, fctnCalled, status="", shortkey=""): """ add an action to 'whichList' """ theAction = QAction(txtMenu, self.parent) theAction.setStatusTip(status) theAction.setShortcut(shortkey) self.connect(theAction, SIGNAL("triggered()"), fctnCalled) whichList.append(theAction)
def __init__(self, nextep, parent=None): """ initialisation """ super(Actions, self).__init__() self.parent = parent self.nextep = nextep self.listActions = [] self.listActionsFile = [] self.listActions.append(("&File", self.listActionsFile)) self.listActionsPref = [] self.listActions.append(("&Options", self.listActionsPref)) self.listActionsMT = [] self.listActions.append(("&Manage TvShow", self.listActionsMT)) separator = QAction(self.parent) separator.setSeparator(True) # Define actions # Options self.addActionToList("&Settings", self.listActionsPref, self.setApp, "Open settings window.", QKeySequence.Preferences) self.addActionToList("Site O&rder", self.listActionsPref, self.sortApp, "Define which site to download from first") self.addActionToList("&Dict bug", self.listActionsPref, self.dictApp, "Dictbug") self.listActionsPref.append(separator) self.addActionToList("&Interactive", self.listActionsPref, self.intApp, "If checked, user is asked some things") self.listActionsPref[len(self.listActionsPref) - 1].setCheckable(True) # Manage TvShow self.addActionToList("&Add a show", self.listActionsMT, self.addApp, "To track a new show.") self.addActionToList("&Remove a show", self.listActionsMT, self.delApp, "Remove a show from watching list.") self.addActionToList("&Track a show", self.listActionsMT, self.trackS, "To track a show.") self.addActionToList("&Untrack", self.listActionsMT, self.untrackS, "To Untrack a show.") # File self.addActionToList("&Update", self.listActionsFile, self.refreshApp, "Update from nextep.", QKeySequence.Refresh) self.listActionsFile.append(separator) self.addActionToList("&Quit", self.listActionsFile, self.quitApp, "Quit the app.", QKeySequence.Quit)
class MenuBar(QMenuBar): # {{{ def __init__(self, location_manager, parent): QMenuBar.__init__(self, parent) self.gui = parent self.setNativeMenuBar(True) self.location_manager = location_manager self.added_actions = [] self.donate_action = QAction(_('Donate'), self) self.donate_menu = QMenu() self.donate_menu.addAction(self.gui.donate_action) self.donate_action.setMenu(self.donate_menu) def update_lm_actions(self): for ac in self.added_actions: clone = getattr(ac, 'clone', None) if clone is not None and clone in self.location_manager.all_actions: ac.setVisible(clone in self.location_manager.available_actions) def init_bar(self, actions): for ac in self.added_actions: m = ac.menu() if m is not None: m.setVisible(False) self.clear() self.added_actions = [] for what in actions: if what is None: continue elif what == 'Location Manager': for ac in self.location_manager.all_actions: ac = self.build_menu(ac) self.addAction(ac) self.added_actions.append(ac) ac.setVisible(False) elif what == 'Donate': self.addAction(self.donate_action) elif what in self.gui.iactions: action = self.gui.iactions[what] ac = self.build_menu(action.qaction) self.addAction(ac) self.added_actions.append(ac) def build_menu(self, action): m = action.menu() ac = MenuAction(action, self) if m is None: m = QMenu() m.addAction(action) ac.setMenu(m) return ac
def _setupEffectsMenu(self): """ Populate the Effects menu. """ availableEffects = Phonon.BackendCapabilities.availableAudioEffects() for e in availableEffects: effectName = e.name() self.effectsDict[effectName] = e action = QAction(effectName, self._dialog.menuAudioEffects) action.setCheckable(True) self._dialog.menuAudioEffects.addAction(action)
def create_action(self, spec=None, attr='qaction', shortcut_name=None): if spec is None: spec = self.action_spec text, icon, tooltip, shortcut = spec if icon is not None: action = QAction(QIcon(I(icon)), text, self.gui) else: action = QAction(text, self.gui) if attr == 'qaction': mt = (action.text() if self.action_menu_clone_qaction is True else unicode(self.action_menu_clone_qaction)) self.menuless_qaction = ma = QAction(action.icon(), mt, self.gui) ma.triggered.connect(action.trigger) for a in ((action, ma) if attr == 'qaction' else (action, )): a.setAutoRepeat(self.auto_repeat) text = tooltip if tooltip else text a.setToolTip(text) a.setStatusTip(text) a.setWhatsThis(text) shortcut_action = action desc = tooltip if tooltip else None if attr == 'qaction': shortcut_action = ma if shortcut is not None: keys = ((shortcut, ) if isinstance(shortcut, basestring) else tuple(shortcut)) if shortcut_name is None and spec[0]: shortcut_name = unicode(spec[0]) if shortcut_name and self.action_spec[0] and not ( attr == 'qaction' and self.popup_type == QToolButton.InstantPopup): try: self.gui.keyboard.register_shortcut( self.unique_name + ' - ' + attr, shortcut_name, default_keys=keys, action=shortcut_action, description=desc, group=self.action_spec[0]) except NameConflict as e: try: prints(unicode(e)) except: pass shortcut_action.setShortcuts([ QKeySequence(key, QKeySequence.PortableText) for key in keys ]) if attr is not None: setattr(self, attr, action) if attr == 'qaction' and self.action_add_menu: menu = QMenu() action.setMenu(menu) if self.action_menu_clone_qaction: menu.addAction(self.menuless_qaction) return action
def __init__(self, location_manager, parent): QMenuBar.__init__(self, parent) self.gui = parent self.setNativeMenuBar(True) self.location_manager = location_manager self.added_actions = [] self.donate_action = QAction(_('Donate'), self) self.donate_menu = QMenu() self.donate_menu.addAction(self.gui.donate_action) self.donate_action.setMenu(self.donate_menu)
def get_menubar_actions(cls): preferences_action = QAction(QIcon(I('config.png')), _('&Preferences'), None) quit_action = QAction(QIcon(I('window-close.png')), _('&Quit'), None) preferences_action.setMenuRole(QAction.PreferencesRole) quit_action.setMenuRole(QAction.QuitRole) return preferences_action, quit_action
def getFlyoutActionList(self): #Ninad 20070618 """ Returns custom actionlist that will be used in a specific mode or editing a feature etc Example: while in movie mode, the _createFlyoutToolBar method calls this. """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList = [] self.exitMovieAction = NE1_QWidgetAction(self.w, win=self.w) self.exitMovieAction.setText("Exit Movie") self.exitMovieAction.setWhatsThis("Exits Movie Mode") self.exitMovieAction.setCheckable(True) self.exitMovieAction.setChecked(True) self.exitMovieAction.setIcon( geticon("ui/actions/Toolbars/Smart/Exit.png")) subControlAreaActionList.append(self.exitMovieAction) separator = QAction(self.w) separator.setSeparator(True) subControlAreaActionList.append(separator) subControlAreaActionList.append(self.w.simPlotToolAction) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params
def _setFindOptionsToolButtonMenu(self): """ Sets the menu for the findOptionstoolbutton that appears a small menu button next to the findLineEdit. """ self.findOptionsMenu = QMenu(self.findOptionsToolButton) self.caseSensitiveFindAction = QAction(self.findOptionsToolButton) self.caseSensitiveFindAction.setText('Match Case') self.caseSensitiveFindAction.setCheckable(True) self.caseSensitiveFindAction.setChecked(False) self.findOptionsMenu.addAction(self.caseSensitiveFindAction) self.findOptionsMenu.addSeparator() self.findOptionsToolButton.setMenu(self.findOptionsMenu) return
def getFlyoutActionList(self): #Ninad 20070618 """ Returns custom actionlist that will be used in a specific mode or editing a feature etc Example: while in movie mode, the _createFlyoutToolBar method calls this. """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList =[] self.exitMovieAction = NE1_QWidgetAction(self.w, win = self.w) self.exitMovieAction.setText("Exit Movie") self.exitMovieAction.setWhatsThis("Exits Movie Mode") self.exitMovieAction.setCheckable(True) self.exitMovieAction.setChecked(True) self.exitMovieAction.setIcon( geticon("ui/actions/Toolbars/Smart/Exit.png")) subControlAreaActionList.append(self.exitMovieAction) separator = QAction(self.w) separator.setSeparator(True) subControlAreaActionList.append(separator) subControlAreaActionList.append(self.w.simPlotToolAction) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params
def __init__(self, parent): QMenuBar.__init__(self, parent) # Menu items self._fileM = QMenu(self.tr("File")) self._editM = QMenu(self.tr("Edit")) self._viewM = QMenu(self.tr("View")) self._optionM = QMenu(self.tr("Options")) self.addMenu(self._fileM) self.addMenu(self._editM) self.addMenu(self._viewM) self.addMenu(self._optionM) # Actions self._connectDatabaseA = QAction(self.tr("Connect a PostGIS database"), self.parent()) self._connectDatabaseA.setShortcut(QKeySequence("Ctrl+Shift+C")) self.parent().connect(self._connectDatabaseA, SIGNAL("triggered()"), self.parent().dialConnectDatabase) self._importDatabaseDataA = QAction( self.tr("Import data from database"), self.parent()) self._importDatabaseDataA.setShortcut(QKeySequence("Ctrl+Shift+I")) self.parent().connect(self._importDatabaseDataA, SIGNAL("triggered()"), self.parent().dialImportDatabaseData) self._importVectorFileDataA = QAction( self.tr("Import vector from file"), self.parent()) self._importVectorFileDataA.setShortcut(QKeySequence("Ctrl+Shift+V")) self.parent().connect(self._importVectorFileDataA, SIGNAL("triggered()"), self.parent().dialImportVectorFileData) self._importRasterFileDataA = QAction( self.tr("Import raster data from file"), self.parent()) self._importRasterFileDataA.setShortcut(QKeySequence("Ctrl+Shift+R")) self.parent().connect(self._importRasterFileDataA, SIGNAL("triggered()"), self.parent().dialImportRasterFileData) self._colorLayerA = QAction(self.tr("Select layer color"), self.parent()) self.parent().connect(self._colorLayerA, SIGNAL("triggered()"), self.parent().dialSelectLayerColor) # Add actions to menu self._fileM.addAction(self._importVectorFileDataA) self._fileM.addAction(self._importRasterFileDataA) self._fileM.addSeparator() self._fileM.addAction(self._connectDatabaseA) self._fileM.addAction(self._importDatabaseDataA) self._viewM.addAction(self._colorLayerA)
def getFlyoutActionList(self): #Ninad 20070618 """ Returns a tuple that contains mode spcific actionlists in the added in the flyout toolbar of the mode. CommandToolbar._createFlyoutToolBar method calls this @return: params: A tuple that contains 3 lists: (subControlAreaActionList, commandActionLists, allActionsList) """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode, there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList =[] self.exitFuseAction = NE1_QWidgetAction(self.w, win = self.w) self.exitFuseAction.setText("Exit Fuse") self.exitFuseAction.setCheckable(True) self.exitFuseAction.setChecked(True) self.exitFuseAction.setIcon( geticon("ui/actions/Toolbars/Smart/Exit.png")) subControlAreaActionList.append(self.exitFuseAction) separator = QAction(self.w) separator.setSeparator(True) subControlAreaActionList.append(separator) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params
class GridViewButton(LayoutButton): # {{{ def __init__(self, gui): sc = _('Shift+Alt+G') LayoutButton.__init__(self, I('grid.png'), _('Cover Grid'), parent=gui, shortcut=sc) if tweaks.get('use_new_db', False): self.set_state_to_show() self.action_toggle = QAction(self.icon(), _('Toggle') + ' ' + self.label, self) gui.addAction(self.action_toggle) gui.keyboard.register_shortcut('grid view toggle' + self.label, unicode(self.action_toggle.text()), default_keys=(sc,), action=self.action_toggle) self.action_toggle.triggered.connect(self.toggle) self.toggled.connect(self.update_state) self.grid_enabled = True else: self.setVisible(False) self.grid_enabled = False def update_state(self, checked): if checked: self.set_state_to_hide() else: self.set_state_to_show() def save_state(self): if self.grid_enabled: gprefs['grid view visible'] = bool(self.isChecked()) def restore_state(self): if self.grid_enabled and gprefs.get('grid view visible', False): self.toggle()
def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) self.setLayout(l) l.setContentsMargins(0, 0, 0, 0) self.view = QTreeWidget(self) self.delegate = Delegate(self.view) self.view.setItemDelegate(self.delegate) self.view.setHeaderHidden(True) self.view.setAnimated(True) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect(self.show_context_menu, type=Qt.QueuedConnection) self.view.itemActivated.connect(self.emit_navigate) self.view.itemPressed.connect(self.item_pressed) pi = plugins['progress_indicator'][0] if hasattr(pi, 'set_no_activate_on_click'): pi.set_no_activate_on_click(self.view) self.view.itemDoubleClicked.connect(self.emit_navigate) l.addWidget(self.view) self.refresh_action = QAction(QIcon(I('view-refresh.png')), _('&Refresh'), self) self.refresh_action.triggered.connect(self.refresh) self.refresh_timer = t = QTimer(self) t.setInterval(1000), t.setSingleShot(True) t.timeout.connect(self.auto_refresh) self.toc_name = None self.currently_editing = None
class GridViewButton(LayoutButton): # {{{ def __init__(self, gui): sc = 'Shift+Alt+G' LayoutButton.__init__(self, I('grid.png'), _('Cover Grid'), parent=gui, shortcut=sc) self.set_state_to_show() self.action_toggle = QAction(self.icon(), _('Toggle') + ' ' + self.label, self) gui.addAction(self.action_toggle) gui.keyboard.register_shortcut('grid view toggle' + self.label, unicode(self.action_toggle.text()), default_keys=(sc, ), action=self.action_toggle) self.action_toggle.triggered.connect(self.toggle) self.toggled.connect(self.update_state) def update_state(self, checked): if checked: self.set_state_to_hide() else: self.set_state_to_show() def save_state(self): gprefs['grid view visible'] = bool(self.isChecked()) def restore_state(self): if gprefs.get('grid view visible', False): self.toggle()
def __init__(self, parent=None): QWidget.__init__(self, parent) self.l = l = QGridLayout(self) self.setLayout(l) l.setContentsMargins(0, 0, 0, 0) self.is_visible = False self.view = QTreeWidget(self) self.delegate = Delegate(self.view) self.view.setItemDelegate(self.delegate) self.view.setHeaderHidden(True) self.view.setAnimated(True) self.view.setContextMenuPolicy(Qt.CustomContextMenu) self.view.customContextMenuRequested.connect(self.show_context_menu, type=Qt.QueuedConnection) self.view.itemActivated.connect(self.emit_navigate) self.view.itemPressed.connect(self.item_pressed) pi = plugins['progress_indicator'][0] if hasattr(pi, 'set_no_activate_on_click'): pi.set_no_activate_on_click(self.view) self.view.itemDoubleClicked.connect(self.emit_navigate) l.addWidget(self.view) self.refresh_action = QAction(QIcon(I('view-refresh.png')), _('&Refresh'), self) self.refresh_action.triggered.connect(self.build)
def __init__(self): self.checked = QIcon(I('ok.png')) self.empty = QIcon(I('blank.png')) self.current_search_action = QAction(self.empty, _('*current search'), self) self.current_search_action.triggered.connect(partial(self.apply_virtual_library, library='*')) self.addAction(self.current_search_action) self.keyboard.register_shortcut( 'vl-from-current-search', _('Virtual library from current search'), description=_( 'Create a temporary Virtual library from the current search'), group=_('Miscellaneous'), default_keys=('Ctrl+*',), action=self.current_search_action) self.search_based_vl_name = None self.search_based_vl = None self.virtual_library_menu = QMenu() self.virtual_library.clicked.connect(self.virtual_library_clicked) self.clear_vl.clicked.connect(lambda x: (self.apply_virtual_library(), self.clear_additional_restriction())) self.virtual_library_tooltip = \ _('Use a "virtual library" to show only a subset of the books present in this library') self.virtual_library.setToolTip(self.virtual_library_tooltip) self.search_restriction = ComboBoxWithHelp(self) self.search_restriction.setVisible(False) self.search_count.setText(_("(all books)")) self.ar_menu = QMenu(_('Additional restriction')) self.edit_menu = QMenu(_('Edit Virtual Library')) self.rm_menu = QMenu(_('Remove Virtual Library'))
def __init__(self, horizontal=False, size=48, parent=None): QFrame.__init__(self, parent) if horizontal: size = 24 self.pi = ProgressIndicator(self, size) self._jobs = QLabel('<b>'+_('Jobs:')+' 0') self._jobs.mouseReleaseEvent = self.mouseReleaseEvent self.shortcut = _('Shift+Alt+J') if horizontal: self.setLayout(QHBoxLayout()) self.layout().setDirection(self.layout().RightToLeft) else: self.setLayout(QVBoxLayout()) self._jobs.setAlignment(Qt.AlignHCenter|Qt.AlignBottom) self.layout().addWidget(self.pi) self.layout().addWidget(self._jobs) if not horizontal: self.layout().setAlignment(self._jobs, Qt.AlignHCenter) self._jobs.setMargin(0) self.layout().setMargin(0) self._jobs.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum) self.setCursor(Qt.PointingHandCursor) b = _('Click to see list of jobs') self.setToolTip(b + u' (%s)'%self.shortcut) self.action_toggle = QAction(b, parent) parent.addAction(self.action_toggle) self.action_toggle.setShortcut(self.shortcut) self.action_toggle.triggered.connect(self.toggle)
def __init__(self, vertical, parent=None): QWebView.__init__(self, parent) self.vertical = vertical self.page().setLinkDelegationPolicy(self.page().DelegateAllLinks) self.linkClicked.connect(self.link_activated) self._link_clicked = False self.setAttribute(Qt.WA_OpaquePaintEvent, False) palette = self.palette() self.setAcceptDrops(False) palette.setBrush(QPalette.Base, Qt.transparent) self.page().setPalette(palette) self.css = P('templates/book_details.css', data=True).decode('utf-8') for x, icon in [('remove', 'trash.png'), ('save', 'save.png')]: ac = QAction(QIcon(I(icon)), '', self) ac.current_fmt = None ac.triggered.connect(getattr(self, '%s_format_triggerred'%x)) setattr(self, '%s_format_action'%x, ac)
def getFlyoutActionList(self): #Ninad 20070618 """ Returns a tuple that contains mode spcific actionlists in the added in the flyout toolbar of the mode. CommandToolbar._createFlyoutToolBar method calls this @return: params: A tuple that contains 3 lists: (subControlAreaActionList, commandActionLists, allActionsList) """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode, there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList =[] subControlAreaActionList.append(self.exitModeAction) separator = QAction(self.win) separator.setSeparator(True) subControlAreaActionList.append(separator) subControlAreaActionList.append(self.win.toolsMoveMoleculeAction) subControlAreaActionList.append(self.win.rotateComponentsAction) subControlAreaActionList.append(self.win.modifyAlignCommonAxisAction) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params
def getFlyoutActionList(self): #Ninad 20070618 """ Returns a tuple that contains mode spcific actionlists in the added in the flyout toolbar of the mode. CommandToolbar._createFlyoutToolBar method calls this @return: params: A tuple that contains 3 lists: (subControlAreaActionList, commandActionLists, allActionsList) """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode, there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList = [] subControlAreaActionList.append(self.exitModeAction) separator = QAction(self.win) separator.setSeparator(True) subControlAreaActionList.append(separator) subControlAreaActionList.append(self.win.toolsMoveMoleculeAction) subControlAreaActionList.append(self.win.rotateComponentsAction) subControlAreaActionList.append(self.win.modifyAlignCommonAxisAction) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params
def __init__(self, type_, title, msg, det_msg='', q_icon=None, show_copy_button=True, parent=None, default_yes=True): QDialog.__init__(self, parent) if q_icon is None: icon = { self.ERROR : 'error', self.WARNING: 'warning', self.INFO: 'information', self.QUESTION: 'question', }[type_] icon = 'dialog_%s.png'%icon self.icon = QIcon(I(icon)) else: self.icon = q_icon self.setupUi(self) self.setWindowTitle(title) self.setWindowIcon(self.icon) self.icon_label.setPixmap(self.icon.pixmap(128, 128)) self.msg.setText(msg) self.det_msg.setPlainText(det_msg) self.det_msg.setVisible(False) self.toggle_checkbox.setVisible(False) if show_copy_button: self.ctc_button = self.bb.addButton(_('&Copy to clipboard'), self.bb.ActionRole) self.ctc_button.clicked.connect(self.copy_to_clipboard) self.show_det_msg = _('Show &details') self.hide_det_msg = _('Hide &details') self.det_msg_toggle = self.bb.addButton(self.show_det_msg, self.bb.ActionRole) self.det_msg_toggle.clicked.connect(self.toggle_det_msg) self.det_msg_toggle.setToolTip( _('Show detailed information about this error')) self.copy_action = QAction(self) self.addAction(self.copy_action) self.copy_action.setShortcuts(QKeySequence.Copy) self.copy_action.triggered.connect(self.copy_to_clipboard) self.is_question = type_ == self.QUESTION if self.is_question: self.bb.setStandardButtons(self.bb.Yes|self.bb.No) self.bb.button(self.bb.Yes if default_yes else self.bb.No ).setDefault(True) self.default_yes = default_yes else: self.bb.button(self.bb.Ok).setDefault(True) if not det_msg: self.det_msg_toggle.setVisible(False) self.do_resize()
def getFlyoutActionList(self): """ returns custom actionlist that will be used in a specific mode or editing a feature etc Example: while in movie mode, the _createFlyoutToolBar method calls this """ #'allActionsList' returns all actions in the flyout toolbar #including the subcontrolArea actions allActionsList = [] #Action List for subcontrol Area buttons. #In this mode there is really no subcontrol area. #We will treat subcontrol area same as 'command area' #(subcontrol area buttons will have an empty list as their command area #list). We will set the Comamnd Area palette background color to the #subcontrol area. subControlAreaActionList =[] self.exitEditCommandAction.setChecked(True) subControlAreaActionList.append(self.exitEditCommandAction) separator = QAction(self.w) separator.setSeparator(True) subControlAreaActionList.append(separator) allActionsList.extend(subControlAreaActionList) #Empty actionlist for the 'Command Area' commandActionLists = [] #Append empty 'lists' in 'commandActionLists equal to the #number of actions in subControlArea for i in range(len(subControlAreaActionList)): lst = [] commandActionLists.append(lst) params = (subControlAreaActionList, commandActionLists, allActionsList) return params
def contextMenuEvent(self, event): menu = QMenu(self) pos = event.pos() index = self.indexAt(pos) if index.isValid(): item = self.indexAt(pos).internalPointer() node = self.item_to_node_dict[item] nodeset = [node] # ? ? ? ? optflag = False # ? ? ? ? cmenu_spec = self.ne1model.make_cmenuspec_for_set(nodeset, optflag) for x in cmenu_spec: if x is not None: str, thunk = x[:2] act = QAction(str, self) act.setEnabled("disabled" not in x[2:]) self.connect(act, SIGNAL("triggered()"), thunk) menu.addAction(act) else: menu.addSeparator() menu.exec_(event.globalPos())
def contextMenuEvent(self, event): menu = QMenu(self) pos = event.pos() index = self.indexAt(pos) if index.isValid(): item = self.indexAt(pos).internalPointer() node = self.item_to_node_dict[item] nodeset = [ node ] # ? ? ? ? optflag = False # ? ? ? ? cmenu_spec = self.treemodel.make_cmenuspec_for_set(nodeset, optflag) for x in cmenu_spec: if x is not None: str, thunk = x[:2] act = QAction(str, self) act.setEnabled("disabled" not in x[2:]) self.connect(act, SIGNAL("triggered()"), thunk) menu.addAction(act) else: menu.addSeparator() menu.exec_(event.globalPos())
def __init__(self, gui): sc = _('Shift+Alt+G') LayoutButton.__init__(self, I('grid.png'), _('Cover Grid'), parent=gui, shortcut=sc) if tweaks.get('use_new_db', False): self.set_state_to_show() self.action_toggle = QAction(self.icon(), _('Toggle') + ' ' + self.label, self) gui.addAction(self.action_toggle) gui.keyboard.register_shortcut('grid view toggle' + self.label, unicode(self.action_toggle.text()), default_keys=(sc, ), action=self.action_toggle) self.action_toggle.triggered.connect(self.toggle) self.toggled.connect(self.update_state) self.grid_enabled = True else: self.setVisible(False) self.grid_enabled = False
def __init__(self, parent, cover_flow): QDialog.__init__(self, parent) self._layout = QStackedLayout() self.setLayout(self._layout) self.setWindowTitle(_('Browse by covers')) self.layout().addWidget(cover_flow) geom = gprefs.get('cover_browser_dialog_geometry', bytearray('')) geom = QByteArray(geom) if not self.restoreGeometry(geom): h, w = available_height() - 60, int(available_width() / 1.5) self.resize(w, h) self.action_fs_toggle = a = QAction(self) self.addAction(a) a.setShortcuts([ QKeySequence('F11', QKeySequence.PortableText), QKeySequence('Ctrl+Shift+F', QKeySequence.PortableText) ]) a.triggered.connect(self.toggle_fullscreen) self.action_esc_fs = a = QAction(self) a.triggered.connect(self.show_normal) self.addAction(a) a.setShortcuts([QKeySequence('Esc', QKeySequence.PortableText)]) self.pre_fs_geom = None cover_flow.setFocus(Qt.OtherFocusReason) self.view_action = a = QAction(self) iactions = parent.iactions self.addAction(a) a.setShortcuts( list(iactions['View'].menuless_qaction.shortcuts()) + [QKeySequence(Qt.Key_Space)]) a.triggered.connect(iactions['View'].menuless_qaction.trigger) self.sd_action = a = QAction(self) self.addAction(a) a.setShortcuts( list(iactions['Send To Device'].menuless_qaction.shortcuts())) a.triggered.connect( iactions['Send To Device'].menuless_qaction.trigger)
def __init__(self, parent, unique_pref_name, stays_on_top=False): if stays_on_top: QDialog.__init__(self, parent.opts.gui, Qt.WindowStaysOnTopHint) else: QDialog.__init__(self, parent.opts.gui) self.unique_pref_name = unique_pref_name self.prefs = parent.opts.prefs self.geom = self.prefs.get(unique_pref_name, None) self.finished.connect(self.dialog_closing) # Hook ESC key self.esc_action = a = QAction(self) self.addAction(a) a.triggered.connect(self.esc) a.setShortcuts([QKeySequence('Esc', QKeySequence.PortableText)])
def __init__(self, gui): sc = _('Shift+Alt+G') LayoutButton.__init__(self, I('grid.png'), _('Cover Grid'), parent=gui, shortcut=sc) if tweaks.get('use_new_db', False): self.set_state_to_show() self.action_toggle = QAction(self.icon(), _('Toggle') + ' ' + self.label, self) gui.addAction(self.action_toggle) gui.keyboard.register_shortcut('grid view toggle' + self.label, unicode(self.action_toggle.text()), default_keys=(sc,), action=self.action_toggle) self.action_toggle.triggered.connect(self.toggle) self.toggled.connect(self.update_state) self.grid_enabled = True else: self.setVisible(False) self.grid_enabled = False
def create_action(self, spec=None, attr='qaction', shortcut_name=None): if spec is None: spec = self.action_spec text, icon, tooltip, shortcut = spec if icon is not None: action = QAction(QIcon(I(icon)), text, self.gui) else: action = QAction(text, self.gui) if attr == 'qaction': mt = (action.text() if self.action_menu_clone_qaction is True else unicode(self.action_menu_clone_qaction)) self.menuless_qaction = ma = QAction(action.icon(), mt, self.gui) ma.triggered.connect(action.trigger) for a in ((action, ma) if attr == 'qaction' else (action,)): a.setAutoRepeat(self.auto_repeat) text = tooltip if tooltip else text a.setToolTip(text) a.setStatusTip(text) a.setWhatsThis(text) shortcut_action = action desc = tooltip if tooltip else None if attr == 'qaction': shortcut_action = ma if shortcut is not None: keys = ((shortcut,) if isinstance(shortcut, basestring) else tuple(shortcut)) if shortcut_name is None and spec[0]: shortcut_name = unicode(spec[0]) if shortcut_name and self.action_spec[0] and not ( attr == 'qaction' and self.popup_type == QToolButton.InstantPopup): try: self.gui.keyboard.register_shortcut(self.unique_name + ' - ' + attr, shortcut_name, default_keys=keys, action=shortcut_action, description=desc, group=self.action_spec[0]) except NameConflict as e: try: prints(unicode(e)) except: pass shortcut_action.setShortcuts([QKeySequence(key, QKeySequence.PortableText) for key in keys]) if attr is not None: setattr(self, attr, action) if attr == 'qaction' and self.action_add_menu: menu = QMenu() action.setMenu(menu) if self.action_menu_clone_qaction: menu.addAction(self.menuless_qaction) return action
def __init__(self): self.search.initialize( 'main_search_history', colorize=True, help_text=_( 'Search (For Advanced Search click the button to the left)')) self.search.cleared.connect(self.search_box_cleared) # Queued so that search.current_text will be correct self.search.changed.connect(self.search_box_changed, type=Qt.QueuedConnection) self.search.focus_to_library.connect(self.focus_to_library) self.clear_button.clicked.connect(self.search.clear_clicked) self.advanced_search_button.clicked[bool].connect( self.do_advanced_search) self.search.clear() self.search.setMaximumWidth(self.width() - 150) self.action_focus_search = QAction(self) shortcuts = list( map(lambda x: unicode(x.toString()), QKeySequence.keyBindings(QKeySequence.Find))) shortcuts += ['/', 'Alt+S'] self.keyboard.register_shortcut('start search', _('Start search'), default_keys=shortcuts, action=self.action_focus_search) self.action_focus_search.triggered.connect(self.focus_search_box) self.addAction(self.action_focus_search) self.search.setStatusTip( re.sub(r'<\w+>', ' ', unicode(self.search.toolTip()))) self.advanced_search_button.setStatusTip( self.advanced_search_button.toolTip()) self.clear_button.setStatusTip(self.clear_button.toolTip()) self.set_highlight_only_button_icon() self.highlight_only_button.clicked.connect(self.highlight_only_clicked) tt = _('Enable or disable search highlighting.') + '<br><br>' tt += config.help('highlight_search_matches') self.highlight_only_button.setToolTip(tt)
def initialize_view(self, debug_javascript=False): self.setRenderHints(QPainter.Antialiasing|QPainter.TextAntialiasing|QPainter.SmoothPixmapTransform) self.flipper = SlideFlip(self) self.is_auto_repeat_event = False self.debug_javascript = debug_javascript self.shortcuts = Shortcuts(SHORTCUTS, 'shortcuts/viewer') self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self._size_hint = QSize(510, 680) self.initial_pos = 0.0 self.to_bottom = False self.document = Document(self.shortcuts, parent=self, debug_javascript=debug_javascript) self.setPage(self.document) self.inspector = WebInspector(self, self.document) self.manager = None self._reference_mode = False self._ignore_scrollbar_signals = False self.loading_url = None self.loadFinished.connect(self.load_finished) self.connect(self.document, SIGNAL('linkClicked(QUrl)'), self.link_clicked) self.connect(self.document, SIGNAL('linkHovered(QString,QString,QString)'), self.link_hovered) self.connect(self.document, SIGNAL('selectionChanged()'), self.selection_changed) self.connect(self.document, SIGNAL('animated_scroll_done()'), self.animated_scroll_done, Qt.QueuedConnection) self.document.page_turn.connect(self.page_turn_requested) copy_action = self.pageAction(self.document.Copy) copy_action.setIcon(QIcon(I('convert.png'))) d = self.document self.unimplemented_actions = list(map(self.pageAction, [d.DownloadImageToDisk, d.OpenLinkInNewWindow, d.DownloadLinkToDisk, d.OpenImageInNewWindow, d.OpenLink, d.Reload, d.InspectElement])) self.search_online_action = QAction(QIcon(I('search.png')), '', self) self.search_online_action.triggered.connect(self.search_online) self.addAction(self.search_online_action) self.dictionary_action = QAction(QIcon(I('dictionary.png')), _('&Lookup in dictionary'), self) self.dictionary_action.triggered.connect(self.lookup) self.addAction(self.dictionary_action) self.image_popup = ImagePopup(self) self.table_popup = TablePopup(self) self.view_image_action = QAction(QIcon(I('view-image.png')), _('View &image...'), self) self.view_image_action.triggered.connect(self.image_popup) self.view_table_action = QAction(QIcon(I('view.png')), _('View &table...'), self) self.view_table_action.triggered.connect(self.popup_table) self.search_action = QAction(QIcon(I('dictionary.png')), _('&Search for next occurrence'), self) self.search_action.triggered.connect(self.search_next) self.addAction(self.search_action) self.goto_location_action = QAction(_('Go to...'), self) self.goto_location_menu = m = QMenu(self) self.goto_location_actions = a = { 'Next Page': self.next_page, 'Previous Page': self.previous_page, 'Section Top' : partial(self.scroll_to, 0), 'Document Top': self.goto_document_start, 'Section Bottom':partial(self.scroll_to, 1), 'Document Bottom': self.goto_document_end, 'Next Section': self.goto_next_section, 'Previous Section': self.goto_previous_section, } for name, key in [(_('Next Section'), 'Next Section'), (_('Previous Section'), 'Previous Section'), (None, None), (_('Document Start'), 'Document Top'), (_('Document End'), 'Document Bottom'), (None, None), (_('Section Start'), 'Section Top'), (_('Section End'), 'Section Bottom'), (None, None), (_('Next Page'), 'Next Page'), (_('Previous Page'), 'Previous Page')]: if key is None: m.addSeparator() else: m.addAction(name, a[key], self.shortcuts.get_sequences(key)[0]) self.goto_location_action.setMenu(self.goto_location_menu) self.grabGesture(Qt.SwipeGesture) self.restore_fonts_action = QAction(_('Default font size'), self) self.restore_fonts_action.setCheckable(True) self.restore_fonts_action.triggered.connect(self.restore_font_size)
class DocumentView(QWebView): # {{{ magnification_changed = pyqtSignal(object) DISABLED_BRUSH = QBrush(Qt.lightGray, Qt.Dense5Pattern) def initialize_view(self, debug_javascript=False): self.setRenderHints(QPainter.Antialiasing|QPainter.TextAntialiasing|QPainter.SmoothPixmapTransform) self.flipper = SlideFlip(self) self.is_auto_repeat_event = False self.debug_javascript = debug_javascript self.shortcuts = Shortcuts(SHORTCUTS, 'shortcuts/viewer') self.setSizePolicy(QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)) self._size_hint = QSize(510, 680) self.initial_pos = 0.0 self.to_bottom = False self.document = Document(self.shortcuts, parent=self, debug_javascript=debug_javascript) self.setPage(self.document) self.inspector = WebInspector(self, self.document) self.manager = None self._reference_mode = False self._ignore_scrollbar_signals = False self.loading_url = None self.loadFinished.connect(self.load_finished) self.connect(self.document, SIGNAL('linkClicked(QUrl)'), self.link_clicked) self.connect(self.document, SIGNAL('linkHovered(QString,QString,QString)'), self.link_hovered) self.connect(self.document, SIGNAL('selectionChanged()'), self.selection_changed) self.connect(self.document, SIGNAL('animated_scroll_done()'), self.animated_scroll_done, Qt.QueuedConnection) self.document.page_turn.connect(self.page_turn_requested) copy_action = self.pageAction(self.document.Copy) copy_action.setIcon(QIcon(I('convert.png'))) d = self.document self.unimplemented_actions = list(map(self.pageAction, [d.DownloadImageToDisk, d.OpenLinkInNewWindow, d.DownloadLinkToDisk, d.OpenImageInNewWindow, d.OpenLink, d.Reload, d.InspectElement])) self.search_online_action = QAction(QIcon(I('search.png')), '', self) self.search_online_action.triggered.connect(self.search_online) self.addAction(self.search_online_action) self.dictionary_action = QAction(QIcon(I('dictionary.png')), _('&Lookup in dictionary'), self) self.dictionary_action.triggered.connect(self.lookup) self.addAction(self.dictionary_action) self.image_popup = ImagePopup(self) self.table_popup = TablePopup(self) self.view_image_action = QAction(QIcon(I('view-image.png')), _('View &image...'), self) self.view_image_action.triggered.connect(self.image_popup) self.view_table_action = QAction(QIcon(I('view.png')), _('View &table...'), self) self.view_table_action.triggered.connect(self.popup_table) self.search_action = QAction(QIcon(I('dictionary.png')), _('&Search for next occurrence'), self) self.search_action.triggered.connect(self.search_next) self.addAction(self.search_action) self.goto_location_action = QAction(_('Go to...'), self) self.goto_location_menu = m = QMenu(self) self.goto_location_actions = a = { 'Next Page': self.next_page, 'Previous Page': self.previous_page, 'Section Top' : partial(self.scroll_to, 0), 'Document Top': self.goto_document_start, 'Section Bottom':partial(self.scroll_to, 1), 'Document Bottom': self.goto_document_end, 'Next Section': self.goto_next_section, 'Previous Section': self.goto_previous_section, } for name, key in [(_('Next Section'), 'Next Section'), (_('Previous Section'), 'Previous Section'), (None, None), (_('Document Start'), 'Document Top'), (_('Document End'), 'Document Bottom'), (None, None), (_('Section Start'), 'Section Top'), (_('Section End'), 'Section Bottom'), (None, None), (_('Next Page'), 'Next Page'), (_('Previous Page'), 'Previous Page')]: if key is None: m.addSeparator() else: m.addAction(name, a[key], self.shortcuts.get_sequences(key)[0]) self.goto_location_action.setMenu(self.goto_location_menu) self.grabGesture(Qt.SwipeGesture) self.restore_fonts_action = QAction(_('Default font size'), self) self.restore_fonts_action.setCheckable(True) self.restore_fonts_action.triggered.connect(self.restore_font_size) def goto_next_section(self, *args): if self.manager is not None: self.manager.goto_next_section() def goto_previous_section(self, *args): if self.manager is not None: self.manager.goto_previous_section() def goto_document_start(self, *args): if self.manager is not None: self.manager.goto_start() def goto_document_end(self, *args): if self.manager is not None: self.manager.goto_end() @property def copy_action(self): return self.pageAction(self.document.Copy) def animated_scroll_done(self): if self.manager is not None: self.manager.scrolled(self.document.scroll_fraction) def reference_mode(self, enable): self._reference_mode = enable self.document.reference_mode(enable) def goto(self, ref): self.document.goto(ref) def goto_bookmark(self, bm): self.document.goto_bookmark(bm) def config(self, parent=None): self.document.do_config(parent) if self.document.in_fullscreen_mode: self.document.switch_to_fullscreen_mode() self.setFocus(Qt.OtherFocusReason) def load_theme(self, theme_id): themes = load_themes() theme = themes[theme_id] opts = config(theme).parse() self.document.apply_settings(opts) if self.document.in_fullscreen_mode: self.document.switch_to_fullscreen_mode() self.setFocus(Qt.OtherFocusReason) def bookmark(self): return self.document.bookmark() def selection_changed(self): if self.manager is not None: self.manager.selection_changed(unicode(self.document.selectedText())) def _selectedText(self): t = unicode(self.selectedText()).strip() if not t: return u'' if len(t) > 40: t = t[:40] + u'...' t = t.replace(u'&', u'&&') return _("S&earch Google for '%s'")%t def popup_table(self): html = self.document.extract_node() self.table_popup(html, QUrl.fromLocalFile(self.last_loaded_path), self.document.font_magnification_step) def contextMenuEvent(self, ev): mf = self.document.mainFrame() r = mf.hitTestContent(ev.pos()) img = r.pixmap() elem = r.element() if elem.isNull(): elem = r.enclosingBlockElement() table = None parent = elem while not parent.isNull(): if (unicode(parent.tagName()) == u'table' or unicode(parent.localName()) == u'table'): table = parent break parent = parent.parent() self.image_popup.current_img = img self.image_popup.current_url = r.imageUrl() menu = self.document.createStandardContextMenu() for action in self.unimplemented_actions: menu.removeAction(action) if not img.isNull(): menu.addAction(self.view_image_action) if table is not None: self.document.mark_element.emit(table) menu.addAction(self.view_table_action) text = self._selectedText() if text and img.isNull(): self.search_online_action.setText(text) for x, sc in (('search_online', 'Search online'), ('dictionary', 'Lookup word'), ('search', 'Next occurrence')): ac = getattr(self, '%s_action' % x) menu.addAction(ac.icon(), '%s [%s]' % (unicode(ac.text()), ','.join(self.shortcuts.get_shortcuts(sc))), ac.trigger) if not text and img.isNull(): menu.addSeparator() if self.manager.action_back.isEnabled(): menu.addAction(self.manager.action_back) if self.manager.action_forward.isEnabled(): menu.addAction(self.manager.action_forward) menu.addAction(self.goto_location_action) if self.manager is not None: menu.addSeparator() menu.addAction(self.manager.action_table_of_contents) menu.addSeparator() menu.addAction(self.manager.action_font_size_larger) self.restore_fonts_action.setChecked(self.multiplier == 1) menu.addAction(self.restore_fonts_action) menu.addAction(self.manager.action_font_size_smaller) menu.addSeparator() menu.addAction(_('Inspect'), self.inspect) if not text and img.isNull() and self.manager is not None: menu.addSeparator() if (not self.document.show_controls or self.document.in_fullscreen_mode) and self.manager is not None: menu.addAction(self.manager.toggle_toolbar_action) menu.addAction(self.manager.action_full_screen) menu.addSeparator() menu.addAction(self.manager.action_quit) menu.exec_(ev.globalPos()) def inspect(self): self.inspector.show() self.inspector.raise_() self.pageAction(self.document.InspectElement).trigger() def lookup(self, *args): if self.manager is not None: t = unicode(self.selectedText()).strip() if t: self.manager.lookup(t.split()[0]) def search_next(self): if self.manager is not None: t = unicode(self.selectedText()).strip() if t: self.manager.search.set_search_string(t) def search_online(self): t = unicode(self.selectedText()).strip() if t: url = 'https://www.google.com/search?q=' + QUrl().toPercentEncoding(t) open_url(QUrl.fromEncoded(url)) def set_manager(self, manager): self.manager = manager self.scrollbar = manager.horizontal_scrollbar self.connect(self.scrollbar, SIGNAL('valueChanged(int)'), self.scroll_horizontally) def scroll_horizontally(self, amount): self.document.scroll_to(y=self.document.ypos, x=amount) @property def scroll_pos(self): return (self.document.ypos, self.document.ypos + self.document.window_height) @property def viewport_rect(self): # (left, top, right, bottom) of the viewport in document co-ordinates # When in paged mode, left and right are the numbers of the columns # at the left edge and *after* the right edge of the viewport d = self.document if d.in_paged_mode: try: l, r = d.column_boundaries except ValueError: l, r = (0, 1) else: l, r = d.xpos, d.xpos + d.window_width return (l, d.ypos, r, d.ypos + d.window_height) def link_hovered(self, link, text, context): link, text = unicode(link), unicode(text) if link: self.setCursor(Qt.PointingHandCursor) else: self.unsetCursor() def link_clicked(self, url): if self.manager is not None: self.manager.link_clicked(url) def sizeHint(self): return self._size_hint @dynamic_property def scroll_fraction(self): def fget(self): return self.document.scroll_fraction def fset(self, val): self.document.scroll_fraction = float(val) return property(fget=fget, fset=fset) @property def hscroll_fraction(self): return self.document.hscroll_fraction @property def content_size(self): return self.document.width, self.document.height @dynamic_property def current_language(self): def fget(self): return self.document.current_language def fset(self, val): self.document.current_language = val return property(fget=fget, fset=fset) def search(self, text, backwards=False): flags = self.document.FindBackward if backwards else self.document.FindFlags(0) found = self.document.findText(text, flags) if found and self.document.in_paged_mode: self.document.javascript('paged_display.snap_to_selection()') return found def path(self): return os.path.abspath(unicode(self.url().toLocalFile())) def load_path(self, path, pos=0.0): self.initial_pos = pos self.last_loaded_path = path def callback(lu): self.loading_url = lu if self.manager is not None: self.manager.load_started() load_html(path, self, codec=getattr(path, 'encoding', 'utf-8'), mime_type=getattr(path, 'mime_type', 'text/html'), pre_load_callback=callback) entries = set() for ie in getattr(path, 'index_entries', []): if ie.start_anchor: entries.add(ie.start_anchor) if ie.end_anchor: entries.add(ie.end_anchor) self.document.index_anchors = entries def initialize_scrollbar(self): if getattr(self, 'scrollbar', None) is not None: if self.document.in_paged_mode: self.scrollbar.setVisible(False) return delta = self.document.width - self.size().width() if delta > 0: self._ignore_scrollbar_signals = True self.scrollbar.blockSignals(True) self.scrollbar.setRange(0, delta) self.scrollbar.setValue(0) self.scrollbar.setSingleStep(1) self.scrollbar.setPageStep(int(delta/10.)) self.scrollbar.setVisible(delta > 0) self.scrollbar.blockSignals(False) self._ignore_scrollbar_signals = False def load_finished(self, ok): if self.loading_url is None: # An <iframe> finished loading return self.loading_url = None self.document.load_javascript_libraries() self.document.after_load(self.last_loaded_path) self._size_hint = self.document.mainFrame().contentsSize() scrolled = False if self.to_bottom: self.to_bottom = False self.initial_pos = 1.0 if self.initial_pos > 0.0: scrolled = True self.scroll_to(self.initial_pos, notify=False) self.initial_pos = 0.0 self.update() self.initialize_scrollbar() self.document.reference_mode(self._reference_mode) if self.manager is not None: spine_index = self.manager.load_finished(bool(ok)) if spine_index > -1: self.document.set_reference_prefix('%d.'%(spine_index+1)) if scrolled: self.manager.scrolled(self.document.scroll_fraction, onload=True) if self.flipper.isVisible(): if self.flipper.running: self.flipper.setVisible(False) else: self.flipper(self.current_page_image(), duration=self.document.page_flip_duration) @classmethod def test_line(cls, img, y): 'Test if line contains pixels of exactly the same color' start = img.pixel(0, y) for i in range(1, img.width()): if img.pixel(i, y) != start: return False return True def current_page_image(self, overlap=-1): if overlap < 0: overlap = self.height() img = QImage(self.width(), overlap, QImage.Format_ARGB32_Premultiplied) painter = QPainter(img) painter.setRenderHints(self.renderHints()) self.document.mainFrame().render(painter, QRegion(0, 0, self.width(), overlap)) painter.end() return img def find_next_blank_line(self, overlap): img = self.current_page_image(overlap) for i in range(overlap-1, -1, -1): if self.test_line(img, i): self.scroll_by(y=i, notify=False) return self.scroll_by(y=overlap) def previous_page(self): if self.flipper.running and not self.is_auto_repeat_event: return if self.loading_url is not None: return epf = self.document.enable_page_flip and not self.is_auto_repeat_event if self.document.in_paged_mode: loc = self.document.javascript( 'paged_display.previous_screen_location()', typ='int') if loc < 0: if self.manager is not None: if epf: self.flipper.initialize(self.current_page_image(), forwards=False) self.manager.previous_document() else: if epf: self.flipper.initialize(self.current_page_image(), forwards=False) self.document.scroll_to(x=loc, y=0) if epf: self.flipper(self.current_page_image(), duration=self.document.page_flip_duration) if self.manager is not None: self.manager.scrolled(self.scroll_fraction) return delta_y = self.document.window_height - 25 if self.document.at_top: if self.manager is not None: self.to_bottom = True if epf: self.flipper.initialize(self.current_page_image(), False) self.manager.previous_document() else: opos = self.document.ypos upper_limit = opos - delta_y if upper_limit < 0: upper_limit = 0 if upper_limit < opos: if epf: self.flipper.initialize(self.current_page_image(), forwards=False) self.document.scroll_to(self.document.xpos, upper_limit) if epf: self.flipper(self.current_page_image(), duration=self.document.page_flip_duration) if self.manager is not None: self.manager.scrolled(self.scroll_fraction) def next_page(self): if self.flipper.running and not self.is_auto_repeat_event: return if self.loading_url is not None: return epf = self.document.enable_page_flip and not self.is_auto_repeat_event if self.document.in_paged_mode: loc = self.document.javascript( 'paged_display.next_screen_location()', typ='int') if loc < 0: if self.manager is not None: if epf: self.flipper.initialize(self.current_page_image()) self.manager.next_document() else: if epf: self.flipper.initialize(self.current_page_image()) self.document.scroll_to(x=loc, y=0) if epf: self.flipper(self.current_page_image(), duration=self.document.page_flip_duration) if self.manager is not None: self.manager.scrolled(self.scroll_fraction) return window_height = self.document.window_height document_height = self.document.height ddelta = document_height - window_height # print '\nWindow height:', window_height # print 'Document height:', self.document.height delta_y = window_height - 25 if self.document.at_bottom or ddelta <= 0: if self.manager is not None: if epf: self.flipper.initialize(self.current_page_image()) self.manager.next_document() elif ddelta < 25: self.scroll_by(y=ddelta) return else: oopos = self.document.ypos # print 'Original position:', oopos self.document.set_bottom_padding(0) opos = self.document.ypos # print 'After set padding=0:', self.document.ypos if opos < oopos: if self.manager is not None: if epf: self.flipper.initialize(self.current_page_image()) self.manager.next_document() return # oheight = self.document.height lower_limit = opos + delta_y # Max value of top y co-ord after scrolling max_y = self.document.height - window_height # The maximum possible top y co-ord if max_y < lower_limit: padding = lower_limit - max_y if padding == window_height: if self.manager is not None: if epf: self.flipper.initialize(self.current_page_image()) self.manager.next_document() return # print 'Setting padding to:', lower_limit - max_y self.document.set_bottom_padding(lower_limit - max_y) if epf: self.flipper.initialize(self.current_page_image()) # print 'Document height:', self.document.height # print 'Height change:', (self.document.height - oheight) max_y = self.document.height - window_height lower_limit = min(max_y, lower_limit) # print 'Scroll to:', lower_limit if lower_limit > opos: self.document.scroll_to(self.document.xpos, lower_limit) actually_scrolled = self.document.ypos - opos # print 'After scroll pos:', self.document.ypos # print 'Scrolled by:', self.document.ypos - opos self.find_next_blank_line(window_height - actually_scrolled) # print 'After blank line pos:', self.document.ypos if epf: self.flipper(self.current_page_image(), duration=self.document.page_flip_duration) if self.manager is not None: self.manager.scrolled(self.scroll_fraction) # print 'After all:', self.document.ypos def page_turn_requested(self, backwards): if backwards: self.previous_page() else: self.next_page() def scroll_by(self, x=0, y=0, notify=True): old_pos = (self.document.xpos if self.document.in_paged_mode else self.document.ypos) self.document.scroll_by(x, y) new_pos = (self.document.xpos if self.document.in_paged_mode else self.document.ypos) if notify and self.manager is not None and new_pos != old_pos: self.manager.scrolled(self.scroll_fraction) def scroll_to(self, pos, notify=True): if self._ignore_scrollbar_signals: return old_pos = (self.document.xpos if self.document.in_paged_mode else self.document.ypos) if self.document.in_paged_mode: if isinstance(pos, basestring): self.document.jump_to_anchor(pos) else: self.document.scroll_fraction = pos else: if isinstance(pos, basestring): self.document.jump_to_anchor(pos) else: if pos >= 1: self.document.scroll_to(0, self.document.height) else: y = int(math.ceil( pos*(self.document.height-self.document.window_height))) self.document.scroll_to(0, y) new_pos = (self.document.xpos if self.document.in_paged_mode else self.document.ypos) if notify and self.manager is not None and new_pos != old_pos: self.manager.scrolled(self.scroll_fraction) @dynamic_property def multiplier(self): def fget(self): return self.zoomFactor() def fset(self, val): self.setZoomFactor(val) self.magnification_changed.emit(val) return property(fget=fget, fset=fset) def magnify_fonts(self, amount=None): if amount is None: amount = self.document.font_magnification_step with self.document.page_position: self.multiplier += amount return self.document.scroll_fraction def shrink_fonts(self, amount=None): if amount is None: amount = self.document.font_magnification_step if self.multiplier >= amount: with self.document.page_position: self.multiplier -= amount return self.document.scroll_fraction def restore_font_size(self): with self.document.page_position: self.multiplier = 1 return self.document.scroll_fraction def changeEvent(self, event): if event.type() == event.EnabledChange: self.update() return QWebView.changeEvent(self, event) def paintEvent(self, event): painter = QPainter(self) painter.setRenderHints(self.renderHints()) self.document.mainFrame().render(painter, event.region()) if not self.isEnabled(): painter.fillRect(event.region().boundingRect(), self.DISABLED_BRUSH) painter.end() def wheelEvent(self, event): mods = event.modifiers() if mods & Qt.CTRL: if self.manager is not None and event.delta() != 0: (self.manager.font_size_larger if event.delta() > 0 else self.manager.font_size_smaller)() return if self.document.in_paged_mode: if abs(event.delta()) < 15: return typ = 'screen' if self.document.wheel_flips_pages else 'col' direction = 'next' if event.delta() < 0 else 'previous' loc = self.document.javascript('paged_display.%s_%s_location()'%( direction, typ), typ='int') if loc > -1: self.document.scroll_to(x=loc, y=0) if self.manager is not None: self.manager.scrolled(self.scroll_fraction) event.accept() elif self.manager is not None: if direction == 'next': self.manager.next_document() else: self.manager.previous_document() event.accept() return if event.delta() < -14: if self.document.wheel_flips_pages: self.next_page() event.accept() return if self.document.at_bottom: self.scroll_by(y=15) # at_bottom can lie on windows if self.manager is not None: self.manager.next_document() event.accept() return elif event.delta() > 14: if self.document.wheel_flips_pages: self.previous_page() event.accept() return if self.document.at_top: if self.manager is not None: self.manager.previous_document() event.accept() return ret = QWebView.wheelEvent(self, event) scroll_amount = (event.delta() / 120.0) * .2 * -1 if event.orientation() == Qt.Vertical: self.scroll_by(0, self.document.viewportSize().height() * scroll_amount) else: self.scroll_by(self.document.viewportSize().width() * scroll_amount, 0) if self.manager is not None: self.manager.scrolled(self.scroll_fraction) return ret def keyPressEvent(self, event): if not self.handle_key_press(event): return QWebView.keyPressEvent(self, event) def paged_col_scroll(self, forward=True, scroll_past_end=True): dir = 'next' if forward else 'previous' loc = self.document.javascript( 'paged_display.%s_col_location()'%dir, typ='int') if loc > -1: self.document.scroll_to(x=loc, y=0) self.manager.scrolled(self.document.scroll_fraction) elif scroll_past_end: (self.manager.next_document() if forward else self.manager.previous_document()) def handle_key_press(self, event): handled = True key = self.shortcuts.get_match(event) func = self.goto_location_actions.get(key, None) if func is not None: self.is_auto_repeat_event = event.isAutoRepeat() try: func() finally: self.is_auto_repeat_event = False elif key == 'Down': if self.document.in_paged_mode: self.paged_col_scroll(scroll_past_end=not self.document.line_scrolling_stops_on_pagebreaks) else: if (not self.document.line_scrolling_stops_on_pagebreaks and self.document.at_bottom): self.manager.next_document() else: self.scroll_by(y=15) elif key == 'Up': if self.document.in_paged_mode: self.paged_col_scroll(forward=False, scroll_past_end=not self.document.line_scrolling_stops_on_pagebreaks) else: if (not self.document.line_scrolling_stops_on_pagebreaks and self.document.at_top): self.manager.previous_document() else: self.scroll_by(y=-15) elif key == 'Left': if self.document.in_paged_mode: self.paged_col_scroll(forward=False) else: self.scroll_by(x=-15) elif key == 'Right': if self.document.in_paged_mode: self.paged_col_scroll() else: self.scroll_by(x=15) elif key == 'Back': if self.manager is not None: self.manager.back(None) elif key == 'Forward': if self.manager is not None: self.manager.forward(None) else: handled = False return handled def resizeEvent(self, event): if self.manager is not None: self.manager.viewport_resize_started(event) return QWebView.resizeEvent(self, event) def event(self, ev): if ev.type() == ev.Gesture: swipe = ev.gesture(Qt.SwipeGesture) if swipe is not None: self.handle_swipe(swipe) return True return QWebView.event(self, ev) def handle_swipe(self, swipe): if swipe.state() == Qt.GestureFinished: if swipe.horizontalDirection() == QSwipeGesture.Left: self.previous_page() elif swipe.horizontalDirection() == QSwipeGesture.Right: self.next_page() elif swipe.verticalDirection() == QSwipeGesture.Up: self.goto_previous_section() elif swipe.horizontalDirection() == QSwipeGesture.Down: self.goto_next_section() def mouseReleaseEvent(self, ev): opos = self.document.ypos ret = QWebView.mouseReleaseEvent(self, ev) if self.manager is not None and opos != self.document.ypos: self.manager.internal_link_clicked(opos) self.manager.scrolled(self.scroll_fraction) return ret
def __init__(self, *args): QAction.__init__(self, *args) self.triggered.connect(lambda x: self.correct.emit( unicode(self.text())))
def initialize(self, parent, content, book_id, installed_book, marvin_db_path, use_qwv=True): ''' __init__ is called on SizePersistedDialog() ''' self.setupUi(self) self.book_id = book_id self.connected_device = parent.opts.gui.device_manager.device self.installed_book = installed_book self.marvin_db_path = marvin_db_path self.opts = parent.opts self.parent = parent self.stored_command = None self.verbose = parent.verbose self._log_location(installed_book.title) # Subscribe to Marvin driver change events self.connected_device.marvin_device_signals.reader_app_status_changed.connect( self.marvin_status_changed) # Set the icon self.setWindowIcon(self.parent.icon) # Set or hide the header if content['header']: self.header.setText(content['header']) else: self.header.setVisible(False) # Set the titles self.setWindowTitle(content['title']) self.html_gb.setTitle(content['group_box_title']) if content['toolTip']: self.html_gb.setToolTip(content['toolTip']) # Set the bg color of the content to the dialog bg color bgcolor = self.palette().color(QPalette.Background) palette = QPalette() palette.setColor(QPalette.Base, bgcolor) #self._log(repr(content['html_content'])) # Initialize the window content if use_qwv: # Add a QWebView to layout self.html_wv = QWebView() self.html_wv.setHtml(content['html_content']) self.html_wv.sizeHint = self.wv_sizeHint self.html_wv.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.html_wv.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) self.html_wv.linkClicked.connect(self.link_clicked) self.html_gb_vl.addWidget(self.html_wv) self.html_tb.setVisible(False) else: # Initialize the contents of the TextBrowser self.html_tb.setText(content['html_content']) #self.html_tb.setPalette(palette) # Set or hide the footer if content['footer']: self.footer.setText(content['footer']) else: self.footer.setVisible(False) # Add Copy to Clipboard button self.ctc_button = self.bb.addButton('&Copy to clipboard', self.bb.ActionRole) self.ctc_button.clicked.connect(self.copy_to_clipboard) self.ctc_button.setIcon(QIcon(I('edit-copy.png'))) self.ctc_button.setObjectName('copy_to_clipboard_button') self.ctc_button.setToolTip('<p>Copy plain text to clipboard, <b>Alt/Option-click</b> for HTML</p>') self.copy_action = QAction(self) self.addAction(self.copy_action) self.copy_action.setShortcuts(QKeySequence.Copy) self.copy_action.triggered.connect(self.copy_to_clipboard) # Add Refresh button if enabled if content['refresh']: self.refresh_method = content['refresh']['method'] self.refresh_button = self.bb.addButton("Refresh '%s'" % content['refresh']['name'], self.bb.ActionRole) self.refresh_button.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_marvin.png'))) self.refresh_button.setObjectName('refresh_button') self.refresh_button.setEnabled(bool(self.installed_book.cid)) # Hook the button events self.bb.clicked.connect(self.dispatch_button_click) # Restore position self.resize_dialog()
class HTMLViewerDialog(SizePersistedDialog, Ui_Dialog, Logger): marvin_device_status_changed = pyqtSignal(dict) def accept(self): self._log_location() super(HTMLViewerDialog, self).accept() def close(self): self._log_location() super(HTMLViewerDialog, self).close() def copy_to_clipboard(self, *args): ''' Store window contents to system clipboard ''' modifiers = Application.keyboardModifiers() if bool(modifiers & Qt.AltModifier): contents = self.html_wv.page().currentFrame().toHtml() #contents = BeautifulSoup(str(contents)).prettify() QApplication.clipboard().setText(contents) else: contents = self.html_wv.page().currentFrame().toPlainText() QApplication.clipboard().setText(unicode(contents)) if hasattr(self, 'ctc_button'): self.ctc_button.setText('Copied') self.ctc_button.setIcon(QIcon(I('ok.png'))) def dispatch_button_click(self, button): ''' BUTTON_ROLES = ['AcceptRole', 'RejectRole', 'DestructiveRole', 'ActionRole', 'HelpRole', 'YesRole', 'NoRole', 'ApplyRole', 'ResetRole'] ''' self._log_location() if self.bb.buttonRole(button) == QDialogButtonBox.AcceptRole: # Save content self.accept() elif self.bb.buttonRole(button) == QDialogButtonBox.ActionRole: if button.objectName() == 'refresh_button': self.refresh_custom_column() elif button.objectName() == 'copy_to_clipboard_button': self.copy_to_clipboard() elif self.bb.buttonRole(button) == QDialogButtonBox.RejectRole: # Cancelled self.close() def esc(self, *args): self.close() def initialize(self, parent, content, book_id, installed_book, marvin_db_path, use_qwv=True): ''' __init__ is called on SizePersistedDialog() ''' self.setupUi(self) self.book_id = book_id self.connected_device = parent.opts.gui.device_manager.device self.installed_book = installed_book self.marvin_db_path = marvin_db_path self.opts = parent.opts self.parent = parent self.stored_command = None self.verbose = parent.verbose self._log_location(installed_book.title) # Subscribe to Marvin driver change events self.connected_device.marvin_device_signals.reader_app_status_changed.connect( self.marvin_status_changed) # Set the icon self.setWindowIcon(self.parent.icon) # Set or hide the header if content['header']: self.header.setText(content['header']) else: self.header.setVisible(False) # Set the titles self.setWindowTitle(content['title']) self.html_gb.setTitle(content['group_box_title']) if content['toolTip']: self.html_gb.setToolTip(content['toolTip']) # Set the bg color of the content to the dialog bg color bgcolor = self.palette().color(QPalette.Background) palette = QPalette() palette.setColor(QPalette.Base, bgcolor) #self._log(repr(content['html_content'])) # Initialize the window content if use_qwv: # Add a QWebView to layout self.html_wv = QWebView() self.html_wv.setHtml(content['html_content']) self.html_wv.sizeHint = self.wv_sizeHint self.html_wv.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) self.html_wv.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks) self.html_wv.linkClicked.connect(self.link_clicked) self.html_gb_vl.addWidget(self.html_wv) self.html_tb.setVisible(False) else: # Initialize the contents of the TextBrowser self.html_tb.setText(content['html_content']) #self.html_tb.setPalette(palette) # Set or hide the footer if content['footer']: self.footer.setText(content['footer']) else: self.footer.setVisible(False) # Add Copy to Clipboard button self.ctc_button = self.bb.addButton('&Copy to clipboard', self.bb.ActionRole) self.ctc_button.clicked.connect(self.copy_to_clipboard) self.ctc_button.setIcon(QIcon(I('edit-copy.png'))) self.ctc_button.setObjectName('copy_to_clipboard_button') self.ctc_button.setToolTip('<p>Copy plain text to clipboard, <b>Alt/Option-click</b> for HTML</p>') self.copy_action = QAction(self) self.addAction(self.copy_action) self.copy_action.setShortcuts(QKeySequence.Copy) self.copy_action.triggered.connect(self.copy_to_clipboard) # Add Refresh button if enabled if content['refresh']: self.refresh_method = content['refresh']['method'] self.refresh_button = self.bb.addButton("Refresh '%s'" % content['refresh']['name'], self.bb.ActionRole) self.refresh_button.setIcon(QIcon(os.path.join(self.parent.opts.resources_path, 'icons', 'from_marvin.png'))) self.refresh_button.setObjectName('refresh_button') self.refresh_button.setEnabled(bool(self.installed_book.cid)) # Hook the button events self.bb.clicked.connect(self.dispatch_button_click) # Restore position self.resize_dialog() def link_clicked(self, url): ''' Open clicked link in regular browser ''' open_url(url) def marvin_status_changed(self, cmd_dict): ''' ''' self.marvin_device_status_changed.emit(cmd_dict) command = cmd_dict['cmd'] self._log_location(command) if command in ['disconnected', 'yanked']: self._log("closing dialog: %s" % command) self.close() def refresh_custom_column(self): ''' If enabled, pass window content to custom column ''' refresh = getattr(self.parent, self.refresh_method, None) if refresh is not None: refresh() self.refresh_button.setText('Refreshed') self.refresh_button.setIcon(QIcon(I('ok.png'))) else: self._log_location("ERROR: Can't execute '%s'" % self.refresh_method) def store_command(self, command): ''' ''' self._log_location(command) self.stored_command = command self.close() def wv_sizeHint(self): ''' QWebVew apparently has a default size of 800, 600 ''' return QSize(400,200)
def __init__(self, fmt, parent): self.fmt = fmt.replace('ORIGINAL_', '') QAction.__init__(self, _('Restore %s from the original')%self.fmt, parent) self.triggered.connect(self._triggered)