def create_menu(self, position: QPoint):
        org_idx: QModelIndex = self.indexAt(position)
        idx = self.proxy.mapToSource(org_idx)
        if not idx.isValid():
            # can happen e.g. before list is populated for the first time
            return
        tx_item = self.hm.transactions.value_from_pos(idx.row())
        column = idx.column()
        if column == HistoryColumns.STATUS_ICON:
            column_title = _('Transaction ID')
            column_data = tx_item['txid']
        else:
            column_title = self.hm.headerData(column, Qt.Horizontal,
                                              Qt.DisplayRole)
            column_data = self.hm.data(idx, Qt.DisplayRole).value()
        tx_hash = tx_item['txid']
        tx = self.wallet.db.get_transaction(tx_hash)
        if not tx:
            return
        tx_URL = block_explorer_URL(self.config, 'tx', tx_hash)
        height = self.wallet.get_tx_height(tx_hash).height
        is_relevant, is_mine, v, fee = self.wallet.get_wallet_delta(tx)
        is_unconfirmed = height <= 0
        pr_key = self.wallet.invoices.paid.get(tx_hash)
        menu = QMenu()
        if height == TX_HEIGHT_LOCAL:
            menu.addAction(_("Remove"), lambda: self.remove_local_tx(tx_hash))

        amount_columns = [
            HistoryColumns.COIN_VALUE, HistoryColumns.RUNNING_COIN_BALANCE,
            HistoryColumns.FIAT_VALUE, HistoryColumns.FIAT_ACQ_PRICE,
            HistoryColumns.FIAT_CAP_GAINS
        ]
        if column in amount_columns:
            column_data = column_data.strip()
        menu.addAction(
            _("Copy {}").format(column_title),
            lambda: self.parent.app.clipboard().setText(column_data))

        for c in self.editable_columns:
            if self.isColumnHidden(c): continue
            label = self.hm.headerData(c, Qt.Horizontal, Qt.DisplayRole)
            # TODO use siblingAtColumn when min Qt version is >=5.11
            persistent = QPersistentModelIndex(
                org_idx.sibling(org_idx.row(), c))
            menu.addAction(_("Edit {}").format(label),
                           lambda p=persistent: self.edit(QModelIndex(p)))
        menu.addAction(_("Details"), lambda: self.show_transaction(tx_hash))
        if is_unconfirmed and tx:
            # note: the current implementation of RBF *needs* the old tx fee
            rbf = is_mine and not tx.is_final() and fee is not None
            if rbf:
                menu.addAction(_("Increase fee"),
                               lambda: self.parent.bump_fee_dialog(tx))
            else:
                child_tx = self.wallet.cpfp(tx, 0)
                if child_tx:
                    menu.addAction(_("Child pays for parent"),
                                   lambda: self.parent.cpfp(tx, child_tx))
        if pr_key:
            menu.addAction(read_QIcon("seal"), _("View invoice"),
                           lambda: self.parent.show_invoice(pr_key))
        if tx_URL:
            menu.addAction(_("View on block explorer"),
                           lambda: webopen(tx_URL))
        menu.exec_(self.viewport().mapToGlobal(position))
 def task_list_widget_context_menu(self):
     menu = QMenu()
     menu.addAction(
         'Remove Task', lambda: self.remove_task(
             self.scheduled_downloads_list_widget.currentRow()))
     menu.exec_(QCursor.pos())
示例#3
0
    def get_context_menu(self, qpoint):
        """ override this method to customize the context menu """
        menu = QMenu(self)
        index = self.view.indexAt(qpoint)

        def add_action(menu, text, handler, icon=None):
            a = None
            if icon is None:
                a = QAction(text, self)
            else:
                a = QAction(icon, text, self)
            a.triggered.connect(handler)
            menu.addAction(a)

        add_action(menu, "Color selection", self._handle_color_selection)

        # duplication here with vstructui
        color_menu = menu.addMenu("Color selection...")

        # need to escape the closure capture on the color loop variable below
        # hint from: http://stackoverflow.com/a/6035865/87207
        def make_color_selection_handler(color):
            return lambda: self._handle_color_selection(color=color)

        for color in QT_COLORS:
            add_action(color_menu, "{:s}".format(color.name),
                       make_color_selection_handler(color.qcolor),
                       make_color_icon(color.qcolor))

        start = self._hsm.start
        end = self._hsm.end
        cm = self.getColorModel()
        if (start == end
                and cm.is_index_colored(start)) or cm.is_region_colored(
                    start, end):

            def make_remove_color_handler(r):
                return lambda: self._handle_remove_color_range(r)

            remove_color_menu = menu.addMenu("Remove color...")
            for cr in cm.get_region_colors(start, end):
                pixmap = QPixmap(10, 10)
                pixmap.fill(cr.color)
                icon = QIcon(pixmap)
                add_action(
                    remove_color_menu,
                    "Remove color [{:s}, {:s}], len: {:s}".format(
                        h(cr.begin), h(cr.end), h(cr.end - cr.begin)),
                    make_remove_color_handler(cr), make_color_icon(cr.color))

        menu.addSeparator(
        )  # -----------------------------------------------------------------

        add_action(menu, "Copy selection (binary)", self._handle_copy_binary)
        copy_menu = menu.addMenu("Copy...")
        add_action(copy_menu, "Copy selection (binary)",
                   self._handle_copy_binary)
        add_action(copy_menu, "Copy selection (text)", self._handle_copy_text)
        add_action(copy_menu, "Copy selection (hex)", self._handle_copy_hex)
        add_action(copy_menu, "Copy selection (hexdump)",
                   self._handle_copy_hexdump)
        add_action(copy_menu, "Copy selection (base64)",
                   self._handle_copy_base64)

        menu.addSeparator(
        )  # -----------------------------------------------------------------

        add_action(menu, "Add origin", lambda: self._handle_add_origin(index))
        return menu
示例#4
0
    def _event_create_menu(self, position):
        menu = QMenu()

        # What the user clicked on.
        menu_index = self.indexAt(position)
        menu_source_index = get_source_index(menu_index, _ItemModel)

        if menu_source_index.row() != -1:
            menu_line = self._data[menu_source_index.row()]
            menu_column = menu_source_index.column()
            column_title = self._headers[menu_column]
            if menu_column == 0:
                copy_text = hash_to_hex_str(menu_line.hash)
            else:
                copy_text = str(menu_source_index.model().data(
                    menu_source_index, Qt.DisplayRole)).strip()
            menu.addAction(
                _("Copy {}").format(column_title),
                lambda: self._main_window.app.clipboard().setText(copy_text))

        # The row selection.
        selected_indexes = self.selectedIndexes()
        if len(selected_indexes):
            # This is an index on the sort/filter model, translate it to the base model.
            selected = []
            for selected_index in selected_indexes:
                base_index = get_source_index(selected_index, _ItemModel)

                row = base_index.row()
                column = base_index.column()
                line = self._data[row]
                selected.append(
                    (row, column, line, selected_index, base_index))

            rows = set(v[0] for v in selected)
            multi_select = len(rows) > 1

            if not multi_select:
                row, column, line, selected_index, base_index = selected[0]
                menu.addAction(
                    _('Details'), lambda: self._main_window.show_transaction(
                        self._account, self._account.get_transaction(line.hash)
                    ))
                line_URL = web.BE_URL(self._main_window.config, 'tx',
                                      hash_to_hex_str(line.hash))
                if line_URL:
                    menu.addAction(_("View on block explorer"),
                                   lambda: webbrowser.open(line_URL))
                menu.addSeparator()
                if column == LABEL_COLUMN:
                    menu.addAction(
                        _("Edit {}").format(column_title),
                        lambda: self.edit(selected_index))
                entry = self._account.get_transaction_entry(line.hash)
                if entry.flags & TxFlags.STATE_UNCLEARED_MASK != 0:
                    menu.addAction(
                        _("Broadcast"),
                        lambda: self._broadcast_transaction(line.hash))
                    menu.addSeparator()
                    menu.addAction(
                        _("Remove from account"),
                        lambda: self._account.delete_transaction(line.hash))

        menu.exec_(self.viewport().mapToGlobal(position))
示例#5
0
文件: main.py 项目: eday1990/elmocut
    def __init__(self):
        super().__init__()
        self.version = '1.0.3'
        self.icon = self.processIcon(app_icon)

        # Add window icon
        self.setWindowIcon(self.icon)
        self.setupUi(self)
        self.setStyleSheet(load_stylesheet())
        
        # Main Props
        self.scanner = Scanner()
        self.killer = Killer()

        # Settings props
        self.minimize = True
        self.remember = False
        self.autoupdate = True

        self.from_tray = False

        # Threading
        self.scan_thread = ScanThread()
        self.scan_thread.thread_finished.connect(self.ScanThread_Reciever)
        self.scan_thread.progress.connect(self.pgbar.setValue)

        self.update_thread = UpdateThread()
        self.update_thread.thread_finished.connect(self.UpdateThread_Reciever)
        
        # We send elmocut to the settings window
        self.settings_window = Settings(self, self.icon)
        self.about_window = About(self, self.icon)

        self.applySettings()

        # Connect buttons
        self.buttons = [
            (self.btnScanEasy,  self.scanEasy,     scan_easy_icon, 'Arping Scan'),
            (self.btnScanHard,  self.scanHard,     scan_hard_icon, 'Pinging Scan'),
            (self.btnKill,      self.kill,         kill_icon,      'Kill selected device'),
            (self.btnUnkill,    self.unkill,       unkill_icon,    'Un-kill selected device'),
            (self.btnKillAll,   self.killAll,      killall_icon,   'Kill all devices'),
            (self.btnUnkillAll, self.unkillAll,    unkillall_icon, 'Un-kill all devices'),
            (self.btnSettings,  self.openSettings, settings_icon,  'View elmoCut settings'),
            (self.btnAbout,     self.openAbout,    about_icon,     'About elmoCut')
            ]
        
        for btn, btn_func, btn_icon, btn_tip in self.buttons:
            btn.setToolTip(btn_tip)
            btn.clicked.connect(btn_func)
            btn.setIcon(self.processIcon(btn_icon))

        self.pgbar.setVisible(False)

        # Table Widget
        self.tableScan.itemClicked.connect(self.deviceClicked)
        self.tableScan.cellClicked.connect(self.cellClicked)
        self.tableScan.setColumnCount(4)
        self.tableScan.verticalHeader().setVisible(False)
        self.tableScan.setHorizontalHeaderLabels(['IP Address','MAC Address','Vendor','Type'])

        '''
           System tray icon and it's tray menu
        '''
        show_option = QAction('Show', self)
        hide_option = QAction('Hide', self)
        quit_option = QAction('Quit', self)
        kill_option = QAction(self.processIcon(kill_icon), '&Kill All', self)
        unkill_option = QAction(self.processIcon(unkill_icon),'&Unkill All', self)
        
        show_option.triggered.connect(self.show)
        hide_option.triggered.connect(self.hide_all)
        quit_option.triggered.connect(self.quit_all)
        kill_option.triggered.connect(self.killAll)
        unkill_option.triggered.connect(self.unkillAll)
        
        tray_menu = QMenu()
        tray_menu.addAction(show_option)
        tray_menu.addAction(hide_option)
        tray_menu.addSeparator()
        tray_menu.addAction(kill_option)
        tray_menu.addAction(unkill_option)
        tray_menu.addSeparator()
        tray_menu.addAction(quit_option)
        
        self.tray_icon = QSystemTrayIcon(self)
        self.tray_icon.setIcon(self.icon)
        self.tray_icon.setToolTip('elmoCut')
        self.tray_icon.setContextMenu(tray_menu)
        self.tray_icon.show()
        self.tray_icon.activated.connect(self.tray_clicked)
示例#6
0
    def createActions(self):

        self.newProjectAct = QAction(QIcon(values.newProjectImage),
                                     values.newProjectActText, self.mainWindow)
        self.newProjectAct.setShortcut(QKeySequence.New)
        self.newProjectAct.setStatusTip(values.newProjectActTip)

        self.openProjectAct = QAction(QIcon(values.openProjectImage),
                                      values.openProjectActText,
                                      self.mainWindow)
        self.openProjectAct.setShortcut(QKeySequence.Open)
        self.openProjectAct.setStatusTip(values.openProjectActTip)

        self.openRecentAct = QAction(values.openRecentActText, self.mainWindow)
        self.openRecentAct.setMenu(QMenu())

        self.saveProjectAct = QAction(QIcon(values.saveProjectImage),
                                      values.saveProjectActText,
                                      self.mainWindow)
        self.saveProjectAct.setShortcut(QKeySequence.Save)
        self.saveProjectAct.setStatusTip(values.saveProjectActTip)

        self.setSettingsAct = QAction(QIcon(values.settingsImage),
                                      values.settingsActText, self.mainWindow)
        self.setSettingsAct.setStatusTip(values.settingsActTip)

        self.buildCropMapsAct = QAction(QIcon(values.analyzeCropImage),
                                        values.analyzeCropActText,
                                        self.mainWindow)
        self.buildCropMapsAct.setStatusTip(values.analyzeCropActTip)

        self.selectRoiPolyAct = QAction(QIcon(values.setRoiImage),
                                        values.setRoiActText, self.mainWindow)
        self.selectRoiPolyAct.setStatusTip(values.setRoiActTip)

        self.setCropRowsDirAct = QAction(QIcon(values.setRowsDirImage),
                                         values.setRowsDirActText,
                                         self.mainWindow)
        self.setCropRowsDirAct.setStatusTip(values.setRowsDirActTip)

        self.imageInfoToolAct = QAction(QIcon(values.infoToolImage),
                                        values.infoToolActText,
                                        self.mainWindow)
        self.imageInfoToolAct.setStatusTip(values.infoToolActTip)
        self.imageInfoToolAct.setCheckable(True)
        self.imageInfoToolAct.setChecked(False)

        self.shownShapesAct = QAction(QIcon(values.shownShapesImage),
                                      values.showShapesActText,
                                      self.mainWindow)
        self.shownShapesAct.setStatusTip(values.showShapesActTip)
        self.shownShapesAct.setMenu(QMenu())

        self.zoomInAct = QAction(QIcon(values.zoomInImage),
                                 values.zoomInActText, self.mainWindow)
        self.zoomInAct.setShortcut("Ctrl++")
        self.zoomInAct.setStatusTip(values.zoomInActTip)

        self.zoomOutAct = QAction(QIcon(values.zoomOutImage),
                                  values.zoomOutActText, self.mainWindow)
        self.zoomOutAct.setShortcut("Ctrl+-")
        self.zoomOutAct.setStatusTip(values.zoomOutActTip)

        self.exitAct = QAction(values.exitActText, self.mainWindow)
        self.exitAct.setShortcut("Ctrl+Q")

        self.aboutAct = QAction(values.aboutActText, self.mainWindow)

        action = self.imageListDockWidget.toggleViewAction()
        action.setIcon(QIcon(values.panelViewImage))
        action.setText(values.togglePanelViewActText)
        action.setStatusTip(values.togglePanelViewActTip)
        self.toggleImageListViewAct = action
示例#7
0
    def createContextMenu(self, table, index, obj):
        menu = QMenu(table)
        K, zone = self.filter.zoneAt(index.row())

        if index.row() == zone.src_start:
            prev_index = zone.prev.src_start if zone.prev is not None else None

        else:
            prev_index = zone.src_start

        next_index = zone.next.src_start if zone.next is not None else None

        move_to_prev = QAction(f"Move to &previous {self.zonestring}",
                               table,
                               triggered=partial(table.goto, row=prev_index))
        menu.addAction(move_to_prev)
        if prev_index is None:
            move_to_prev.setDisabled(True)

        move_to_next = QAction(f"Move to &next {self.zonestring}",
                               table,
                               triggered=partial(table.goto, row=next_index))
        menu.addAction(move_to_next)
        if next_index is None:
            move_to_next.setDisabled(True)

        menu.addSeparator()

        n = index.row()
        J, zone = self.filter.zoneAt(n)

        zones = set(self.filter.zone_indices)
        thiszone = set(range(zone.src_start, zone.src_end))

        filterzones = QAction(f"&Show {self.zonestring} cuts",
                              table,
                              triggered=partial(self.setFilter,
                                                table=table,
                                                filter=zones))
        menu.addAction(filterzones)

        filterzones = QAction(f"&Show this {self.zonestring}",
                              table,
                              triggered=partial(self.setFilter,
                                                table=table,
                                                filter=thiszone))
        menu.addAction(filterzones)

        showall = QAction("Show &all rows",
                          table,
                          triggered=partial(self.showAll, table=table))
        menu.addAction(showall)

        menu.addSeparator()

        checkallselected = QAction("&Check all selected",
                                   table,
                                   triggered=partial(self.checkSelected,
                                                     table=table,
                                                     check=True))
        uncheckallselected = QAction("&Uncheck all selected",
                                     table,
                                     triggered=partial(self.checkSelected,
                                                       table=table,
                                                       check=False))

        menu.addAction(checkallselected)
        menu.addAction(uncheckallselected)

        return menu
示例#8
0
    def __init__(self, parent):
        super().__init__()

        self.parent = parent

        icons = ':/' + \
            str(self.parent.persepolis_setting.value('settings/icons')) + '/'

        # add support for other languages
        locale = str(self.parent.persepolis_setting.value('settings/locale'))
        QLocale.setDefault(QLocale(locale))
        self.translator = QTranslator()
        if self.translator.load(':/translations/locales/ui_' + locale, 'ts'):
            QCoreApplication.installTranslator(self.translator)

        # set ui direction
        ui_direction = self.parent.persepolis_setting.value('ui_direction')

        if ui_direction == 'rtl':
            self.setLayoutDirection(Qt.RightToLeft)

        elif ui_direction in 'ltr':
            self.setLayoutDirection(Qt.LeftToRight)

        # creating context menu
        self.menubar = QMenu(self)
        self.setMenu(self.menubar)
        self.setIcon(QIcon(icons + 'menu'))

        fileMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'File'))
        editMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'Edit'))
        viewMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'View'))
        downloadMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'Download'))
        queueMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'Queue'))
        videoFinderMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'Video Finder'))
        helpMenu = self.menubar.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'Help'))

        sortMenu = viewMenu.addMenu(
            QCoreApplication.translate("mainwindow_ui_tr", 'Sort by'))

        videoFinderMenu.addAction(self.parent.youtubeAddLinkAction)

        downloadMenu.addAction(self.parent.stopAllAction)

        sortMenu.addAction(self.parent.sort_file_name_Action)

        sortMenu.addAction(self.parent.sort_file_size_Action)

        sortMenu.addAction(self.parent.sort_first_try_date_Action)

        sortMenu.addAction(self.parent.sort_last_try_date_Action)

        sortMenu.addAction(self.parent.sort_download_status_Action)

        viewMenu.addAction(self.parent.trayAction)

        viewMenu.addAction(self.parent.showMenuBarAction)

        viewMenu.addAction(self.parent.showSidePanelAction)

        viewMenu.addAction(self.parent.minimizeAction)

        fileMenu.addAction(self.parent.addlinkAction)

        fileMenu.addAction(self.parent.addtextfileAction)

        downloadMenu.addAction(self.parent.resumeAction)

        downloadMenu.addAction(self.parent.pauseAction)

        downloadMenu.addAction(self.parent.stopAction)

        downloadMenu.addAction(self.parent.propertiesAction)

        downloadMenu.addAction(self.parent.progressAction)

        fileMenu.addAction(self.parent.openFileAction)

        fileMenu.addAction(self.parent.openDownloadFolderAction)

        fileMenu.addAction(self.parent.openDefaultDownloadFolderAction)

        fileMenu.addAction(self.parent.exitAction)

        editMenu.addAction(self.parent.clearAction)

        editMenu.addAction(self.parent.removeSelectedAction)

        editMenu.addAction(self.parent.deleteSelectedAction)

        queueMenu.addAction(self.parent.createQueueAction)

        queueMenu.addAction(self.parent.removeQueueAction)

        queueMenu.addAction(self.parent.startQueueAction)

        queueMenu.addAction(self.parent.stopQueueAction)

        queueMenu.addAction(self.parent.moveUpSelectedAction)

        queueMenu.addAction(self.parent.moveDownSelectedAction)

        editMenu.addAction(self.parent.preferencesAction)

        helpMenu.addAction(self.parent.aboutAction)

        helpMenu.addAction(self.parent.issueAction)

        helpMenu.addAction(self.parent.updateAction)

        helpMenu.addAction(self.parent.logAction)

        helpMenu.addAction(self.parent.helpAction)
示例#9
0
    def _initViewMenu(self):
        self._viewMenu = QMenu("View", parent=self)
        self._viewMenu.setObjectName("view_menu")
        self._debugActions = []

        ActionInfo = ShortcutManager.ActionInfo

        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionFitToScreen = self._viewMenu.addAction(
            "&Zoom to &fit")
        self._viewMenu.actionFitToScreen.triggered.connect(self._fitToScreen)

        def toggleHud():
            hide = not self.editor.imageViews[0]._hud.isVisible()
            for v in self.editor.imageViews:
                v.setHudVisible(hide)

        # This action is saved as a member so it can be triggered from tests
        self._viewMenu.actionToggleAllHuds = self._viewMenu.addAction(
            "Toggle huds")
        self._viewMenu.actionToggleAllHuds.triggered.connect(toggleHud)

        def resetAllAxes():
            for s in self.editor.imageScenes:
                s.resetAxes()

        self._viewMenu.addAction("Reset all axes").triggered.connect(
            resetAllAxes)

        def centerAllImages():
            for v in self.editor.imageViews:
                v.centerImage()

        self._viewMenu.addAction("Center images").triggered.connect(
            centerAllImages)

        def toggleDebugPatches(show):
            self.editor.showDebugPatches = show

        actionShowTiling = self._viewMenu.addAction("Show Tiling")
        actionShowTiling.setCheckable(True)
        actionShowTiling.toggled.connect(toggleDebugPatches)
        ShortcutManager().register(
            "Ctrl+D",
            ActionInfo("Navigation", "Show tiling", "Show tiling",
                       actionShowTiling.toggle, self, None))
        self._debugActions.append(actionShowTiling)

        def setCacheSize(cache_size):
            dlg = QDialog(self)
            layout = QHBoxLayout()
            layout.addWidget(QLabel("Cached Slices Per View:"))

            spinBox = QSpinBox(parent=dlg)
            spinBox.setRange(0, 1000)
            spinBox.setValue(self.editor.cacheSize)
            layout.addWidget(spinBox)
            okButton = QPushButton("OK", parent=dlg)
            okButton.clicked.connect(dlg.accept)
            layout.addWidget(okButton)
            dlg.setLayout(layout)
            dlg.setModal(True)
            if dlg.exec_() == QDialog.Accepted:
                self.editor.cacheSize = spinBox.value()

        self._viewMenu.addAction("Set layer cache size").triggered.connect(
            setCacheSize)

        def enablePrefetching(enable):
            # Enable for Z view only
            self.editor.imageScenes[2].setPrefetchingEnabled(enable)

        #             for scene in self.editor.imageScenes:
        #                 scene.setPrefetchingEnabled( enable )
        actionUsePrefetching = self._viewMenu.addAction("Use prefetching")
        actionUsePrefetching.setCheckable(True)
        actionUsePrefetching.toggled.connect(enablePrefetching)

        def blockGuiForRendering():
            for v in self.editor.imageViews:
                v.scene().joinRenderingAllTiles()
                v.repaint()
            QApplication.processEvents()

        actionBlockGui = self._viewMenu.addAction("Block for rendering")
        actionBlockGui.triggered.connect(blockGuiForRendering)
        ShortcutManager().register(
            "Ctrl+B",
            ActionInfo("Navigation", "Block gui for rendering",
                       "Block gui for rendering", actionBlockGui.trigger, self,
                       None),
        )
        self._debugActions.append(actionBlockGui)

        def changeTileWidth():
            """Change tile width (tile block size) and reset image-scene"""
            dlg = QDialog(self)
            dlg.setWindowTitle("Viewer Tile Width")
            dlg.setModal(True)

            spinBox = QSpinBox(parent=dlg)
            spinBox.setRange(128, 10 * 1024)
            spinBox.setValue(self.editor.imageScenes[0].tileWidth())

            ctrl_layout = QHBoxLayout()
            ctrl_layout.addSpacerItem(QSpacerItem(10, 0,
                                                  QSizePolicy.Expanding))
            ctrl_layout.addWidget(QLabel("Tile Width:"))
            ctrl_layout.addWidget(spinBox)

            button_box = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel,
                                          parent=dlg)
            button_box.accepted.connect(dlg.accept)
            button_box.rejected.connect(dlg.reject)

            dlg_layout = QVBoxLayout()
            dlg_layout.addLayout(ctrl_layout)
            dlg_layout.addWidget(
                QLabel("Setting will apply current view immediately,\n"
                       "and all other views upon restart."))
            dlg_layout.addWidget(button_box)

            dlg.setLayout(dlg_layout)

            if dlg.exec_() == QDialog.Accepted:
                for s in self.editor.imageScenes:
                    if s.tileWidth != spinBox.value():
                        s.setTileWidth(spinBox.value())
                        s.reset()

        self._viewMenu.addAction("Set Tile Width...").triggered.connect(
            changeTileWidth)

        # ------ Separator ------
        self._viewMenu.addAction("").setSeparator(True)

        # Text only
        actionOnlyForSelectedView = self._viewMenu.addAction(
            "Only for selected view")
        actionOnlyForSelectedView.setIconVisibleInMenu(True)
        font = actionOnlyForSelectedView.font()
        font.setItalic(True)
        font.setBold(True)
        actionOnlyForSelectedView.setFont(font)

        def setCurrentAxisIcon():
            """Update the icon that shows the currently selected axis."""
            actionOnlyForSelectedView.setIcon(
                QIcon(self.editor.imageViews[
                    self.editor._lastImageViewFocus]._hud.axisLabel.pixmap()))

        self.editor.newImageView2DFocus.connect(setCurrentAxisIcon)
        setCurrentAxisIcon()

        actionFitImage = self._viewMenu.addAction("Fit image")
        actionFitImage.triggered.connect(self._fitImage)
        ShortcutManager().register(
            "K",
            ActionInfo("Navigation", "Fit image on screen",
                       "Fit image on screen", actionFitImage.trigger, self,
                       None),
        )

        def toggleSelectedHud():
            self.editor.imageViews[self.editor._lastImageViewFocus].toggleHud()

        actionToggleSelectedHud = self._viewMenu.addAction("Toggle hud")
        actionToggleSelectedHud.triggered.connect(toggleSelectedHud)

        def resetAxes():
            self.editor.imageScenes[
                self.editor._lastImageViewFocus].resetAxes()

        self._viewMenu.addAction("Reset axes").triggered.connect(resetAxes)

        def centerImage():
            self.editor.imageViews[
                self.editor._lastImageViewFocus].centerImage()

        actionCenterImage = self._viewMenu.addAction("Center image")
        actionCenterImage.triggered.connect(centerImage)
        ShortcutManager().register(
            "C",
            ActionInfo("Navigation", "Center image", "Center image",
                       actionCenterImage.trigger, self, None))

        def restoreImageToOriginalSize():
            self.editor.imageViews[self.editor._lastImageViewFocus].doScaleTo()

        actionResetZoom = self._viewMenu.addAction("Reset zoom")
        actionResetZoom.triggered.connect(restoreImageToOriginalSize)
        ShortcutManager().register(
            "W",
            ActionInfo("Navigation", "Reset zoom", "Reset zoom",
                       actionResetZoom.trigger, self, None))

        def updateHudActions():
            dataShape = self.editor.dataShape
            # if the image is 2D, do not show the HUD action (issue #190)
            is2D = numpy.sum(numpy.asarray(dataShape[1:4]) == 1) == 1
            actionToggleSelectedHud.setVisible(not is2D)
            self._viewMenu.actionToggleAllHuds.setVisible(not is2D)

        self.editor.shapeChanged.connect(updateHudActions)
示例#10
0
文件: Devices.py 项目: peterwup/tdm
    def __init__(self, parent, *args, **kwargs):
        super(ListWidget, self).__init__(*args, **kwargs)
        self.setWindowTitle("Devices list")
        self.setWindowState(Qt.WindowMaximized)
        self.setLayout(VLayout(margin=0, spacing=0))

        self.mqtt = parent.mqtt
        self.env = parent.env

        self.device = None
        self.idx = None

        self.nam = QNetworkAccessManager()
        self.backup = bytes()

        self.settings = QSettings("{}/TDM/tdm.cfg".format(QDir.homePath()),
                                  QSettings.IniFormat)
        views_order = self.settings.value("views_order", [])

        self.views = {}
        self.settings.beginGroup("Views")
        views = self.settings.childKeys()
        if views and views_order:
            for view in views_order.split(";"):
                view_list = self.settings.value(view).split(";")
                self.views[view] = base_view + view_list
        else:
            self.views = default_views
        self.settings.endGroup()

        self.tb = Toolbar(Qt.Horizontal, 24, Qt.ToolButtonTextBesideIcon)
        self.tb_relays = Toolbar(Qt.Horizontal, 24, Qt.ToolButtonIconOnly)
        # self.tb_filter = Toolbar(Qt.Horizontal, 24, Qt.ToolButtonTextBesideIcon)
        self.tb_views = Toolbar(Qt.Horizontal, 24, Qt.ToolButtonTextBesideIcon)

        self.pwm_sliders = []

        self.layout().addWidget(self.tb)
        self.layout().addWidget(self.tb_relays)
        # self.layout().addWidget(self.tb_filter)

        self.device_list = TableView()
        self.device_list.setIconSize(QSize(24, 24))
        self.model = parent.device_model
        self.model.setupColumns(self.views["Home"])

        self.sorted_device_model = QSortFilterProxyModel()
        self.sorted_device_model.setFilterCaseSensitivity(Qt.CaseInsensitive)
        self.sorted_device_model.setSourceModel(parent.device_model)
        self.sorted_device_model.setSortRole(Qt.InitialSortOrderRole)
        self.sorted_device_model.setSortLocaleAware(True)
        self.sorted_device_model.setFilterKeyColumn(-1)

        self.device_list.setModel(self.sorted_device_model)
        self.device_list.setupView(self.views["Home"])
        self.device_list.setSortingEnabled(True)
        self.device_list.setWordWrap(True)
        self.device_list.setItemDelegate(DeviceDelegate())
        self.device_list.sortByColumn(self.model.columnIndex("Device"),
                                      Qt.AscendingOrder)
        self.device_list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.device_list.verticalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)
        self.layout().addWidget(self.device_list)

        self.layout().addWidget(self.tb_views)

        self.device_list.clicked.connect(self.select_device)
        self.device_list.customContextMenuRequested.connect(
            self.show_list_ctx_menu)

        self.ctx_menu = QMenu()

        self.create_actions()
        self.create_view_buttons()
        # self.create_view_filter()

        self.device_list.doubleClicked.connect(lambda: self.openConsole.emit())
示例#11
0
 def from_list_menu(self, position) -> None:
     item = self._from_list.itemAt(position)
     menu = QMenu()
     menu.addAction(_("Remove"),
                    lambda: self._on_from_list_menu_remove(item))
     menu.exec_(self._from_list.viewport().mapToGlobal(position))
示例#12
0
文件: Devices.py 项目: peterwup/tdm
    def create_actions(self):
        actConsole = self.tb.addAction(QIcon(":/console.png"), "Console",
                                       self.openConsole.emit)
        actConsole.setShortcut("Ctrl+E")

        actRules = self.tb.addAction(QIcon(":/rules.png"), "Rules",
                                     self.openRulesEditor.emit)
        actRules.setShortcut("Ctrl+R")

        actTimers = self.tb.addAction(QIcon(":/timers.png"), "Timers",
                                      self.configureTimers)

        actButtons = self.tb.addAction(QIcon(":/buttons.png"), "Buttons",
                                       self.configureButtons)
        actButtons.setShortcut("Ctrl+B")

        actSwitches = self.tb.addAction(QIcon(":/switches.png"), "Switches",
                                        self.configureSwitches)
        actSwitches.setShortcut("Ctrl+S")

        actPower = self.tb.addAction(QIcon(":/power.png"), "Power",
                                     self.configurePower)
        actPower.setShortcut("Ctrl+P")

        # setopts = self.tb.addAction(QIcon(":/setoptions.png"), "SetOptions", self.configureSO)
        # setopts.setShortcut("Ctrl+S")

        self.tb.addSpacer()

        actTelemetry = self.tb.addAction(QIcon(":/telemetry.png"), "Telemetry",
                                         self.openTelemetry.emit)
        actTelemetry.setShortcut("Ctrl+T")

        actWebui = self.tb.addAction(QIcon(":/web.png"), "WebUI",
                                     self.openWebUI.emit)
        actWebui.setShortcut("Ctrl+U")

        self.ctx_menu.addActions([
            actRules, actTimers, actButtons, actSwitches, actPower,
            actTelemetry, actWebui
        ])
        self.ctx_menu.addSeparator()

        self.ctx_menu_cfg = QMenu("Configure")
        self.ctx_menu_cfg.setIcon(QIcon(":/settings.png"))
        self.ctx_menu_cfg.addAction("Module", self.configureModule)
        self.ctx_menu_cfg.addAction("GPIO", self.configureGPIO)
        self.ctx_menu_cfg.addAction("Template", self.configureTemplate)
        # self.ctx_menu_cfg.addAction("Wifi", self.ctx_menu_teleperiod)
        # self.ctx_menu_cfg.addAction("Time", self.cfgTime.emit)
        # self.ctx_menu_cfg.addAction("MQTT", self.ctx_menu_teleperiod)

        # self.ctx_menu_cfg.addAction("Logging", self.ctx_menu_teleperiod)

        self.ctx_menu.addMenu(self.ctx_menu_cfg)
        self.ctx_menu.addSeparator()

        self.ctx_menu.addAction(QIcon(":/refresh.png"), "Refresh",
                                self.ctx_menu_refresh)

        self.ctx_menu.addSeparator()
        self.ctx_menu.addAction(QIcon(":/clear.png"), "Clear retained",
                                self.ctx_menu_clear_retained)
        self.ctx_menu.addAction("Clear Backlog", self.ctx_menu_clear_backlog)
        self.ctx_menu.addSeparator()
        self.ctx_menu.addAction(QIcon(":/copy.png"), "Copy",
                                self.ctx_menu_copy)
        self.ctx_menu.addSeparator()
        self.ctx_menu.addAction(QIcon(":/restart.png"), "Restart",
                                self.ctx_menu_restart)
        self.ctx_menu.addAction(QIcon(), "Reset", self.ctx_menu_reset)
        self.ctx_menu.addSeparator()
        self.ctx_menu.addAction(QIcon(":/delete.png"), "Delete",
                                self.ctx_menu_delete_device)

        # self.tb.addAction(QIcon(), "Multi Command", self.ctx_menu_webui)

        self.agAllPower = QActionGroup(self)
        self.agAllPower.addAction(QIcon(":/P_ON.png"), "All ON")
        self.agAllPower.addAction(QIcon(":/P_OFF.png"), "All OFF")
        self.agAllPower.setEnabled(False)
        self.agAllPower.setExclusive(False)
        self.agAllPower.triggered.connect(self.toggle_power_all)
        self.tb_relays.addActions(self.agAllPower.actions())

        self.agRelays = QActionGroup(self)
        self.agRelays.setVisible(False)
        self.agRelays.setExclusive(False)

        for a in range(1, 9):
            act = QAction(QIcon(":/P{}_OFF.png".format(a)), "")
            act.setShortcut("F{}".format(a))
            self.agRelays.addAction(act)

        self.agRelays.triggered.connect(self.toggle_power)
        self.tb_relays.addActions(self.agRelays.actions())

        self.tb_relays.addSeparator()
        self.actColor = self.tb_relays.addAction(QIcon(":/color.png"), "Color",
                                                 self.set_color)
        self.actColor.setEnabled(False)

        self.actChannels = self.tb_relays.addAction(QIcon(":/sliders.png"),
                                                    "Channels")
        self.actChannels.setEnabled(False)
        self.mChannels = QMenu()
        self.actChannels.setMenu(self.mChannels)
        self.tb_relays.widgetForAction(self.actChannels).setPopupMode(
            QToolButton.InstantPopup)
示例#13
0
	def create_widgets(self):
		"""Create widgets"""
		self.USER_PRESETS_PATH = os.path.join(paths.APP_FOLDER, "presets")
		if not os.path.exists(self.USER_PRESETS_PATH):
			os.mkdir(self.USER_PRESETS_PATH)
		self.settings = QSettings(paths.CONFIG_PATH, QSettings.IniFormat)
		
		#EQUALIZER
		self.eq = vlc.AudioEqualizer()
		
#vbox_main
		self.vbox_main = QVBoxLayout()
		self.vbox_main.setContentsMargins(1, 1, 1, 1)
		self.vbox_main.setSpacing(3)
		self.setLayout(self.vbox_main)

	#add hbox turn and presets
		self.hbox_presets = QHBoxLayout()
		self.vbox_main.addLayout(self.hbox_presets)
		#turn
		self.turn_eq = QCheckBox(self.tr("Eq on/off"))
		self.turn_eq.stateChanged.connect(self.on_off_eq)
		self.hbox_presets.addWidget(self.turn_eq)
		#combo presets
		self.combo_presets = QComboBox()
		self.combo_presets.setFixedHeight(32)
		self.hbox_presets.addWidget(self.combo_presets)
		default_path_presets = os.path.join(os.getcwd(), "presets")
		list_presets = os.listdir(default_path_presets)
		list_presets.sort()
		self.combo_presets.addItem(self.tr("Choose:"))
		for item in list_presets:
			self.combo_presets.addItem(item)
		user_presets_list = os.listdir(self.USER_PRESETS_PATH)
		user_presets_list.sort()
		for item in user_presets_list:
			self.combo_presets.addItem(item)
		self.combo_presets.activated.connect(self.choose_preset)
		#button_menu
		self.button_menu = QPushButton()
		self.button_menu.setFixedSize(32, 32)
		self.button_menu.setIconSize(QSize(28, 28))
		self.button_menu.setIcon(QIcon(':/more_icon.png'))
		self.button_menu.setStyleSheet(styles.get_button_style())
		self.button_menu.setCursor(Qt.PointingHandCursor)
		self.hbox_presets.addWidget(self.button_menu)
		self.menu_tools = QMenu()
		self.menu_tools.addAction(QIcon(':/accept_icon.png'), self.tr("Accept"), self.press_accept)
		self.menu_tools.addAction(QIcon(':/save_icon.png'), self.tr("Save"), self.open_widget_save)
		self.menu_tools.addAction(QIcon(':/reset_icon.png'), self.tr("Reset"), self.press_reset)
		self.button_menu.setMenu(self.menu_tools)
		
	#widget_preset_save
		self.widget_preset_save = Widget_save(self)
		self.widget_preset_save.hide()
		self.vbox_main.addWidget(self.widget_preset_save)

	#add scroll slider
		self.scroll_sliders = QScrollArea()
		self.scroll_sliders.setWidgetResizable(True)
		self.vbox_main.addWidget(self.scroll_sliders)
		#add sliders vbox
		self.widget_sliders = QWidget()
		self.scroll_sliders.setWidget(self.widget_sliders)
		self.vbox_sliders = QVBoxLayout()
		self.widget_sliders.setLayout(self.vbox_sliders)
		
		#list_sliders
		self.list_sliders = []
		
		#list_sliders_names
		self.list_slider_names = [
								"Preamp:", "31 Hz:", "62 Hz:",
								"125 Hz:", "250 Hz:", "500 Hz:",
								"1 KHz:", "2 KHz", "4 KHz:",
								"8 KHz:", "16 KHz:",
							]
		for item in self.list_slider_names:
			index = self.list_slider_names.index(item)
			self.hbox = QHBoxLayout()
			self.vbox_sliders.addLayout(self.hbox)
			self.label_name = QLabel(item + '\t')
			self.hbox.addWidget(self.label_name)
			self.slider = Slider_band()
			self.list_sliders.append(self.slider)
			self.slider.BAND_NUM = index
			self.slider.valueChanged.connect(self.change_slider_num)
			self.hbox.addWidget(self.slider)
			self.label_value = QLabel()
			self.hbox.addWidget(self.label_value)
			
		#AUTORUN
		self.check_sliders()
    def __init__(self, parent=None, external=False):
        """
        Constructor
        
        @param parent parent of this dialog (QWidget)
        @param external flag indicating an instatiation as a main
            window (boolean)
        """
        super(PluginRepositoryWidget, self).__init__(parent)
        self.setupUi(self)

        self.__updateButton = self.buttonBox.addButton(
            self.tr("Update"), QDialogButtonBox.ActionRole)
        self.__downloadButton = self.buttonBox.addButton(
            self.tr("Download"), QDialogButtonBox.ActionRole)
        self.__downloadButton.setEnabled(False)
        self.__downloadInstallButton = self.buttonBox.addButton(
            self.tr("Download && Install"), QDialogButtonBox.ActionRole)
        self.__downloadInstallButton.setEnabled(False)
        self.__downloadCancelButton = self.buttonBox.addButton(
            self.tr("Cancel"), QDialogButtonBox.ActionRole)
        self.__installButton = \
            self.buttonBox.addButton(self.tr("Close && Install"),
                                     QDialogButtonBox.ActionRole)
        self.__downloadCancelButton.setEnabled(False)
        self.__installButton.setEnabled(False)

        self.repositoryUrlEdit.setText(
            Preferences.getUI("PluginRepositoryUrl6"))

        self.repositoryList.headerItem().setText(
            self.repositoryList.columnCount(), "")
        self.repositoryList.header().setSortIndicator(0, Qt.AscendingOrder)

        self.__pluginContextMenu = QMenu(self)
        self.__hideAct = self.__pluginContextMenu.addAction(
            self.tr("Hide"), self.__hidePlugin)
        self.__hideSelectedAct = self.__pluginContextMenu.addAction(
            self.tr("Hide Selected"), self.__hideSelectedPlugins)
        self.__pluginContextMenu.addSeparator()
        self.__showAllAct = self.__pluginContextMenu.addAction(
            self.tr("Show All"), self.__showAllPlugins)
        self.__pluginContextMenu.addSeparator()
        self.__pluginContextMenu.addAction(self.tr("Cleanup Downloads"),
                                           self.__cleanupDownloads)

        self.pluginRepositoryFile = \
            os.path.join(Utilities.getConfigDir(), "PluginRepository")

        self.__external = external

        # attributes for the network objects
        self.__networkManager = QNetworkAccessManager(self)
        self.__networkManager.proxyAuthenticationRequired.connect(
            proxyAuthenticationRequired)
        if SSL_AVAILABLE:
            self.__sslErrorHandler = E5SslErrorHandler(self)
            self.__networkManager.sslErrors.connect(self.__sslErrors)
        self.__replies = []

        self.__doneMethod = None
        self.__inDownload = False
        self.__pluginsToDownload = []
        self.__pluginsDownloaded = []
        self.__isDownloadInstall = False
        self.__allDownloadedOk = False

        self.__hiddenPlugins = Preferences.getPluginManager("HiddenPlugins")

        self.__populateList()
    def generate_menu(self, pos):
        row_num = -1
        for i in self.tableWidget.selectionModel().selection().indexes():
            row_num = i.row()
        if row_num == -1:
            return
        if self.user_role == '普通用户':
            menu = QMenu()
            return_action = QAction(u'还书')
            return_action.setIcon(QIcon(RETURN))
            menu.addAction(return_action)

            delay_borrow_action = QAction(u'续借')
            delay_borrow_action.setIcon(QIcon(DELAY_TIME))
            menu.addAction(delay_borrow_action)

            # 如果当前条目为已还则菜单栏为不可点击状态
            if self.return_flag[row_num] == 1:
                return_action.setEnabled(False)
                delay_borrow_action.setEnabled(False)
            action = menu.exec_(self.tableWidget.mapToGlobal(pos))

            if action == return_action:
                if accept_box(self, '提示', '确实归还当前书本吗?') == QMessageBox.Yes:
                    th = Thread(target=self.return_book,
                                args=(self.borrow_info_id[row_num], ))
                    th.start()

            if action == delay_borrow_action:
                self.renew_win = RenewWindow(
                    borrow_id=self.borrow_info_id[row_num])
                self.renew_win.show()
        else:
            menu = QMenu()
            del_record_action = QAction(u'删除记录')
            del_record_action.setIcon(QIcon(DELETE_ICON))
            menu.addAction(del_record_action)

            ask_return_action = QAction(u'催还')
            ask_return_action.setIcon(QIcon(PUSH_RETURN))
            menu.addAction(ask_return_action)

            # 根据是否已经归还来判断菜单是否为可点击状态
            if self.return_flag[row_num] == 1:
                ask_return_action.setEnabled(False)
            else:
                del_record_action.setEnabled(False)

            action = menu.exec_(self.tableWidget.mapToGlobal(pos))

            if action == del_record_action:
                rep = accept_box(self, '警告', '确定删除该条记录吗?')
                if rep == QMessageBox.Yes:
                    pass

            if action == ask_return_action:
                index = self.tableWidget.currentRow()
                borrow_id = self.borrow_info_id[index]
                borrow_user = self.tableWidget.item(index, 0).text()
                self.ask_win = AskReturnWindow(
                    data=[borrow_user, borrow_id, 0,
                          get_current_time()])
                self.ask_win.show()
示例#16
0
    def setup(self):

        TogOff = self.icon + 'Toggle_Off.png'
        TogOn = self.icon + 'Toggle_On.png'
        TogOff = pathlib.Path(TogOff)
        TogOff = pathlib.PurePosixPath(TogOff)
        TogOn = pathlib.Path(TogOn)
        TogOn = pathlib.PurePosixPath(TogOn)

        self.setStyleSheet("QCheckBox::indicator{width: 30px;height: 30px;}"
                           "QCheckBox::indicator:unchecked { image : url(%s);}"
                           "QCheckBox::indicator:checked { image:  url(%s);}"
                           "QCheckBox{font :10pt;}" % (TogOff, TogOn))

        vbox1 = QVBoxLayout()

        hbox2 = QHBoxLayout()
        self.openButton = QPushButton('Open', self)
        self.openButton.setIcon(QtGui.QIcon(self.icon + "Open.png"))
        self.openButton.setIconSize(QtCore.QSize(50, 50))
        self.openButton.setMaximumWidth(200)
        self.openButton.setMaximumHeight(100)
        self.openButton.setShortcut(QtGui.QKeySequence("Ctrl+O"))
        hbox2.addWidget(self.openButton)
        self.openButtonhbox4 = QHBoxLayout()
        self.openButton.setStyleSheet(
            "background-color: transparent ;border-color: transparent")

        self.saveButton = QPushButton('Save', self)
        self.saveButton.setMaximumWidth(100)
        self.saveButton.setMinimumHeight(100)
        self.saveButton.setIconSize(QtCore.QSize(50, 50))
        hbox2.addWidget(self.saveButton)
        self.saveButton.setIcon(QtGui.QIcon(self.icon + "Saving.png"))
        self.saveButton.setStyleSheet(
            "background-color: transparent ;border-color: transparent")
        vbox1.addLayout(hbox2)

        hbox3 = QHBoxLayout()
        grid_layout0 = QGridLayout()
        self.checkBoxAutoSave = QCheckBox('AutoSave', self)
        self.checkBoxAutoSave.setChecked(False)
        grid_layout0.addWidget(self.checkBoxAutoSave, 0, 0)
        self.checkBoxBg = QCheckBox('Bg substraction', self)
        self.checkBoxBg.setChecked(False)
        grid_layout0.addWidget(self.checkBoxBg, 1, 0)
        self.optionAutoSave = QPushButton('Options', self)
        hbox3.addLayout(grid_layout0)
        self.optionAutoSave.setIcon(QtGui.QIcon(self.icon + "Settings.png"))
        #self.optionAutoSave.setIconSize(QtCore.QSize(20,20))
        hbox3.addWidget(self.optionAutoSave)
        vbox1.addLayout(hbox3)

        hbox8 = QHBoxLayout()

        hbox4 = QHBoxLayout()
        self.labelFileName = QLabel("File :")
        self.labelFileName.setStyleSheet("font:15pt;")
        self.labelFileName.setMinimumHeight(30)
        self.labelFileName.setMaximumWidth(40)
        hbox4.addWidget(self.labelFileName)
        hbox42 = QHBoxLayout()

        self.fileName = QLabel()
        self.fileName.setStyleSheet("font:10pt")
        self.fileName.setMaximumHeight(30)
        self.fileName.setMaximumWidth(150)
        hbox42.addWidget(self.fileName)
        vbox1.addLayout(hbox4)
        vbox1.addLayout(hbox42)

        hbox5 = QHBoxLayout()
        self.checkBoxPlot = QCheckBox('CROSS', self)
        self.checkBoxPlot.setChecked(False)

        hbox5.addWidget(self.checkBoxPlot)
        hbox6 = QHBoxLayout()
        self.label_Cross = QLabel()
        #self.label_Cross.setMaximumHeight(20)
        self.label_Cross.setMaximumWidth(150)
        self.label_Cross.setStyleSheet("font:10pt")
        hbox6.addWidget(self.label_Cross)
        #hbox6.setSpacing(1)
        vbox1.addLayout(hbox5)
        vbox1.addLayout(hbox6)

        self.ZoomLabel = QLabel('Zoom')
        vbox1.addWidget(self.ZoomLabel)
        self.checkBoxZoom = QSlider(Qt.Horizontal)
        self.checkBoxZoom.setMaximumWidth(200)
        self.checkBoxZoom.setMinimum(-5)
        self.checkBoxZoom.setMaximum(100)
        self.checkBoxZoom.setValue(-20)
        vbox1.addWidget(self.checkBoxZoom)

        self.checkBoxScale = QCheckBox('Auto Scale', self)
        self.checkBoxScale.setChecked(True)
        self.checkBoxScale.setMaximumWidth(100)

        self.checkBoxColor = QCheckBox('Color', self)
        self.checkBoxColor.setChecked(True)

        self.checkBoxHist = QCheckBox('Hist', self)
        self.checkBoxHist.setChecked(False)
        self.maxGraphBox = QCheckBox('Max', self)
        grid_layout = QGridLayout()
        grid_layout.setVerticalSpacing(0)
        grid_layout.setHorizontalSpacing(10)
        grid_layout.addWidget(self.checkBoxScale, 0, 0)
        grid_layout.addWidget(self.checkBoxColor, 1, 0)
        grid_layout.addWidget(self.checkBoxHist, 0, 1)
        #grid_layout.addWidget(self.checkBoxZoom, 1, 0)
        grid_layout.addWidget(self.maxGraphBox, 1, 1)

        hbox8.addLayout(grid_layout)

        vbox1.addLayout(hbox8)

        hbox9 = QHBoxLayout()
        self.energyBox = QPushButton('&Encercled', self)
        hbox9.addWidget(self.energyBox)
        self.filtreBox = QPushButton('&Filters', self)
        menu = QMenu()
        menu.addAction('&Gaussian', self.Gauss)
        menu.addAction('&Median', self.Median)
        menu.addAction('&Origin', self.Orig)
        self.filtreBox.setMenu(menu)
        hbox9.addWidget(self.filtreBox)
        vbox1.addLayout(hbox9)

        hbox11 = QHBoxLayout()
        self.PlotButton = QPushButton('Plot')
        hbox11.addWidget(self.PlotButton)
        self.MeasButton = QPushButton('Meas.')
        hbox11.addWidget(self.MeasButton)

        hbox10 = QHBoxLayout()
        self.ligneButton = QPushButton('Line')
        self.ligneButton.setIcon(QtGui.QIcon(self.icon + "ligne.jpeg"))

        hbox10.addWidget(self.ligneButton)

        self.rectangleButton = QPushButton('Rect')
        self.rectangleButton.setIcon(QtGui.QIcon(self.icon + "rectangle.png"))
        hbox10.addWidget(self.rectangleButton)

        self.circleButton = QPushButton('Circle')
        self.circleButton.setIcon(QtGui.QIcon(self.icon + "Red_circle.png"))
        hbox10.addWidget(self.circleButton)

        vbox1.addLayout(hbox11)
        vbox1.addLayout(hbox10)
        vbox1.addStretch(1)

        self.winImage = pg.GraphicsLayoutWidget()
        self.winImage.setContentsMargins(0, 0, 0, 0)
        self.winImage.setAspectLocked(True)
        self.winImage.setSizePolicy(QSizePolicy.Expanding,
                                    QSizePolicy.Expanding)
        self.winImage.ci.setContentsMargins(0, 0, 0, 0)

        vbox2 = QVBoxLayout()
        vbox2.addWidget(self.winImage)
        vbox2.setContentsMargins(0, 0, 0, 0)

        self.p1 = self.winImage.addPlot()
        self.imh = pg.ImageItem()
        self.p1.addItem(self.imh)
        self.p1.setMouseEnabled(x=False, y=False)
        self.p1.setContentsMargins(0, 0, 0, 0)

        self.p1.setAspectLocked(True, ratio=1)
        self.p1.showAxis('right', show=False)
        self.p1.showAxis('top', show=False)
        self.p1.showAxis('left', show=False)
        self.p1.showAxis('bottom', show=False)

        self.vLine = pg.InfiniteLine(angle=90, movable=False, pen='y')
        self.hLine = pg.InfiniteLine(angle=0, movable=False, pen='y')

        self.xc = 10
        self.yc = 10
        self.rx = 50
        self.ry = 50
        self.vLine.setPos(self.xc)
        self.hLine.setPos(self.yc)

        self.ro1 = pg.EllipseROI([self.xc, self.yc], [self.rx, self.ry],
                                 pen='y',
                                 movable=False,
                                 maxBounds=QtCore.QRectF(
                                     0, 0, self.rx, self.ry))
        self.ro1.setPos([self.xc - (self.rx / 2), self.yc - (self.ry / 2)])

        # text for fwhm on p1
        self.textX = pg.TextItem(angle=-90)
        self.textY = pg.TextItem()

        #histogram
        self.hist = pg.HistogramLUTItem()
        self.hist.setImageItem(self.imh)
        self.hist.autoHistogramRange()
        self.hist.gradient.loadPreset('flame')

        ##  XY  graph
        self.curve2 = pg.PlotCurveItem()
        self.curve3 = pg.PlotCurveItem()

        ## main layout
        hMainLayout = QHBoxLayout()
        hMainLayout.addLayout(vbox2)
        hMainLayout.addLayout(vbox1)
        hMainLayout.setContentsMargins(1, 1, 1, 1)
        hMainLayout.setSpacing(1)
        hMainLayout.setStretch(10, 1)

        self.setLayout(hMainLayout)
        self.setContentsMargins(1, 1, 1, 1)
        #self.plotLine=pg.LineSegmentROI(positions=((self.dimx/2-100,self.dimy/2),(self.dimx/2+100,self.dimy/2)), movable=True,angle=0,pen='b')
        self.plotLine = pg.LineSegmentROI(positions=((0, 200), (200, 200)),
                                          movable=True,
                                          angle=0,
                                          pen='w')
        #self.plotLine=pg.PolyLineROI(positions=((0,200),(200,200),(300,200)), movable=True,angle=0,pen='w')
        self.plotRect = pg.RectROI([self.xc, self.yc], [4 * self.rx, self.ry],
                                   pen='g')
        self.plotCercle = pg.CircleROI([self.xc, self.yc], [80, 80], pen='g')
示例#17
0
    def createMenu(self, position, tpe, elem, prop, par, item):
        # global
        undoAction = QAction('Undo', self.treeView)
        undoAction.setEnabled(not self.flow.isEnd())
        redoAction = QAction('Redo', self.treeView)
        redoAction.setEnabled(not self.flow.isFirst())
        copyAsXML = QAction('Copy as XML', self.treeView)
        pasteAsXML = QAction('Paste as XML', self.treeView)
        clearAll = QAction('Clear table', self.treeView)

        # delete
        copyTextAction = QAction('Copy text', self.treeView)
        pasteTextAction = QAction("Paste text", self.treeView)
        deleteTagAction = QAction('Delete tag', self.treeView)
        deletePropertyAction = QAction('Delete property', self.treeView)

        # duplicate
        duplicateAction = QAction('Duplicate', self.treeView)

        # add
        addMenu = QMenu("Add..")
        Utilities.Style.applyStyle(addMenu)

        # add child
        addChildAction = QAction('Add Child', self.treeView)

        # add property
        addPropertyAction = QAction('Add Property', self.treeView)

        # new
        newDocument = QAction('New document', self.treeView)

        addMenu.addAction(addChildAction)
        addMenu.addAction(addPropertyAction)

        menu = QMenu()
        Utilities.Style.applyStyle(menu)
        if self.treeView.editable:
            menu.addAction(undoAction)
            menu.addAction(redoAction)
            menu.addSeparator()
        menu.addAction(copyAsXML)
        if self.treeView.editable:
            menu.addAction(pasteAsXML)
            menu.addAction(clearAll)
            menu.addSeparator()

        if self.treeView.editable:
            if tpe == 0:  # tag
                menu.addAction(copyTextAction)
                menu.addAction(pasteTextAction)
                menu.addAction(duplicateAction)
                menu.addMenu(addMenu)
                menu.addAction(deleteTagAction)
            elif tpe == 1:  # property
                menu.addAction(copyTextAction)
                menu.addAction(pasteTextAction)
                menu.addAction(addPropertyAction)
                if prop is not None:
                    menu.addAction(deletePropertyAction)
            else:  # root
                if self.xmlData is None:
                    menu.addAction(newDocument)
                else:
                    menu.addAction(addChildAction)
                    menu.addAction(addPropertyAction)
        else:
            if tpe == 0 or tpe == 1:
                menu.addAction(copyTextAction)
        action = menu.exec_(self.treeView.viewport().mapToGlobal(position))

        if action == undoAction:
            self.flowAction(1)
        elif action == redoAction:
            self.flowAction(0)
        elif action == copyAsXML:
            self.actionCopyAsXML()
        elif action == pasteAsXML:
            self.actionPasteAsXML()
        elif action == clearAll:
            self.actionClearAll()
        elif action == copyTextAction:
            self.actionCopyText(item)
        elif action == pasteTextAction:
            self.actionPasteText(item)
        elif action == duplicateAction:
            self.actionDuplicate(elem, par)
        elif action == deleteTagAction:
            self.actionDeleteTag(elem, par)
        elif action == deletePropertyAction:
            self.actionDeleteProperty(elem, prop)
        elif action == addChildAction:
            self.actionAddChild(elem)
        elif action == addPropertyAction:
            self.actionAddProperty(elem)
        elif action == newDocument:
            self.actionNewDocument()
示例#18
0
def build_xlt_menu( mainwindow, slot ):

    # Create the submenu but assume it will be empty.
    submenu = QMenu(
        _TR( 'Name of Translators submenu', 'Translators...' ) )
    submenu.setToolTip(
        _TR( 'Translators submenu tooltip',
             'Available Translators in extras/Translators folder' ) )
    submenu.setEnabled( False )

    # Form the path to extras/Translators and try to get a list
    # of all files in it. If it doesn't exist or isn't a dir,
    # we get an error.
    xlt_dir = os.path.join( paths.get_extras_path(), 'Translators' )
    try :
        xlt_files = os.listdir( xlt_dir )
    except Exception as E:
        # this error is logged but not displayed to the user as its
        # only effect is an empty, disabled submenu.
        xlt_logger.error( 'Unable to load any Translator modules')
        xlt_logger.error( str(E) )
        xlt_files = []

    # Check every file in extras/Translators as a possible Translator
    for candidate in xlt_files :

        # Form the full path
        candidate_path = os.path.join( xlt_dir, candidate )

        # Is it readable?
        if not os.access( candidate_path, os.R_OK ) : continue

        # Is it a python source? (Not supporting .pyc just now)
        if not candidate.endswith('.py') : continue

        # Create a loader object - this throws no exceptions
        xlt_logger.info( 'Loading translator module '+candidate )
        xlt_loader = importlib.machinery.SourceFileLoader(
            os.path.splitext( candidate )[0], candidate_path )

        # Try the actual load, which executes the code and can throw
        # exceptions either directly from the loader, or uncaught exceptions
        # thrown by the loaded code. If any exceptions, skip it.
        xlt_logger.info( 'Executing translator into namespace '+candidate )
        try:
            xlt_namespace = xlt_loader.load_module()
        except Exception as E :
            # This error is only logged. It is of interest only to the
            # coder of a Translator wondering why it doesn't appear.
            xlt_logger.error( 'Error loading or executing Translator {}:'.format(candidate) )
            xlt_logger.error( str(E) )
            continue

        # The loaded module should have a MENU_NAME which is a string
        xlt_name = getattr( xlt_namespace, 'MENU_NAME', False )
        if not isinstance(xlt_name, str) :
            xlt_logger.error('Translator {} has no MENU_NAME string'.format(candidate) )
            continue

        # The MENU_NAME should be of reasonable length for a menu item
        if ( len( xlt_name ) > 16 ) or ( len( xlt_name ) < 3 ) :
            xlt_logger.error('Translator {} MENU_NAME too long or too short'.format(candidate) )
            continue

        # The loaded module should offer global functions initialize() and
        # translate(). If not, log an error.

        xlt_fun = getattr( xlt_namespace, 'initialize', False )
        if not isinstance( xlt_fun, types.FunctionType ):
            xlt_logger.error('Translator {} lacks initialize() member'.format(candidate) )
            continue
        xlt_fun = getattr( xlt_namespace, 'translate', False )
        if not isinstance( xlt_fun, types.FunctionType ) :
            xlt_logger.error('Translator {} lacks translate() member'.format(candidate) )
            continue
        xlt_fun = getattr( xlt_namespace, 'finalize', False )
        if not isinstance( xlt_fun, types.FunctionType ) :
            xlt_logger.error('Translator {} lacks finalize() member'.format(candidate) )
            continue
        # OK, we are going to trust it. Save the namespace for use later.
        xlt_index = len( _XLT_NAMESPACES )
        _XLT_NAMESPACES.append( xlt_namespace )

        # Build the menu action with the given name and an optional tooltip.
        action = submenu.addAction( xlt_namespace.MENU_NAME )
        action.setToolTip( getattr( xlt_namespace, 'TOOLTIP', '' ) )

        # Save the index to the namespace as the menu action's data()
        action.setData( xlt_index )

        # Connect the action to the slot provided
        action.triggered.connect( slot )

        # The menu is not going to be empty, so make it enabled
        submenu.setEnabled( True )

    # end for candidate in xlt_files
    return submenu
示例#19
0
 def create_popup_menu(self, parent=None):
     self.popup_menu = QMenu()
     self.popup_menu.addAction("Yeni", self.new_cluster)
     self.popup_menu.addAction("Sil", self.delete_cluster)
示例#20
0
    def create_menu(self, position):
        is_multisig = isinstance(self.wallet, Multisig_Wallet)
        can_delete = self.wallet.can_delete_address()
        selected = self.selectedItems()
        multi_select = len(selected) > 1
        addrs = [item.data(0, Qt.UserRole) for item in selected]
        if not addrs:
            return
        addrs = [addr for addr in addrs if isinstance(addr, Address)]

        menu = QMenu()

        if not multi_select:
            item = self.itemAt(position)
            col = self.currentColumn()
            if not item:
                return
            if not addrs:
                item.setExpanded(not item.isExpanded())
                return
            addr = addrs[0]

            column_title = self.headerItem().text(col)
            if col == 0:
                copy_text = addr.to_string()
            else:
                copy_text = item.text(col)
            menu.addAction(
                _("Copy {}").format(column_title),
                lambda: self.parent.app.clipboard().setText(copy_text))
            menu.addAction(_('Details'),
                           lambda: self.parent.show_address(addr))
            if col in self.editable_columns:
                menu.addAction(
                    _("Edit {}").format(column_title),
                    lambda: self.editItem(item, col))
            menu.addAction(_("Request payment"),
                           lambda: self.parent.receive_at(addr))
            if self.wallet.can_export():
                menu.addAction(_("Private key"),
                               lambda: self.parent.show_private_key(addr))
            if not is_multisig and not self.wallet.is_watching_only():
                menu.addAction(_("Sign/verify message"),
                               lambda: self.parent.sign_verify_message(addr))
                menu.addAction(_("Encrypt/decrypt message"),
                               lambda: self.encrypt_message(addr))
            if can_delete:
                menu.addAction(_("Remove from wallet"),
                               lambda: self.parent.remove_address(addr))
            addr_URL = web.BE_URL(self.config, 'addr', addr)
            if addr_URL:
                menu.addAction(_("View on block explorer"),
                               lambda: webbrowser.open(addr_URL))

            keystore = self.wallet.get_keystore()
            if self.wallet.wallet_type == 'standard' and isinstance(
                    keystore, Hardware_KeyStore):

                def show_address():
                    self.parent.run_in_thread(keystore.plugin.show_address,
                                              self.wallet, addr)

                menu.addAction(
                    _("Show on {}").format(keystore.plugin.device),
                    show_address)

        freeze = self.parent.set_frozen_state
        if any(self.wallet.is_frozen_address(addr) for addr in addrs):
            menu.addAction(_("Unfreeze"), partial(freeze, addrs, False))
        if not all(self.wallet.is_frozen_address(addr) for addr in addrs):
            menu.addAction(_("Freeze"), partial(freeze, addrs, True))

        coins = self.wallet.get_spendable_coins(domain=addrs,
                                                config=self.config)
        if coins:
            menu.addAction(_("Spend from"),
                           partial(self.parent.spend_coins, coins))

        menu.exec_(self.viewport().mapToGlobal(position))
示例#21
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.calc = CalcCore()
        self.setWindowTitle('rpCalc')
        modPath = os.path.abspath(sys.path[0])
        if modPath.endswith('.zip') or modPath.endswith('.exe'):
            modPath = os.path.dirname(modPath)  # for py2exe/cx_freeze
        iconPathList = [
            iconPath,
            os.path.join(modPath, 'icons/'),
            os.path.join(modPath, '../icons')
        ]
        self.icons = icondict.IconDict()
        self.icons.addIconPath(filter(None, iconPathList))
        self.icons.addIconPath([path for path in iconPathList if path])
        try:
            QApplication.setWindowIcon(self.icons['calc_lg'])
        except KeyError:
            pass
        if self.calc.option.boolData('KeepOnTop'):
            self.setWindowFlags(Qt.Window | Qt.WindowStaysOnTopHint)
        else:
            self.setWindowFlags(Qt.Window)
        self.setFocusPolicy(Qt.StrongFocus)
        self.helpView = None
        self.extraView = None
        self.altBaseView = None
        self.optDlg = None
        self.popupMenu = QMenu(self)
        self.popupMenu.addAction('Registers on &LCD', self.toggleReg)
        self.popupMenu.addSeparator()
        self.popupMenu.addAction('Show &Register List', self.viewReg)
        self.popupMenu.addAction('Show &History List', self.viewHist)
        self.popupMenu.addAction('Show &Memory List', self.viewMem)
        self.popupMenu.addSeparator()
        self.popupMenu.addAction('Show Other &Bases', self.viewAltBases)
        self.popupMenu.addSeparator()
        self.popupMenu.addAction('Show Help &File', self.help)
        self.popupMenu.addAction('&About rpCalc', self.about)
        self.popupMenu.addSeparator()
        self.popupMenu.addAction('&Quit', self.close)
        topLay = QVBoxLayout(self)
        self.setLayout(topLay)
        topLay.setSpacing(4)
        topLay.setContentsMargins(6, 6, 6, 6)
        lcdBox = LcdBox()
        topLay.addWidget(lcdBox)
        lcdLay = QGridLayout(lcdBox)
        lcdLay.setColumnStretch(1, 1)
        lcdLay.setRowStretch(3, 1)
        self.extraLabels = [QLabel(' T:', ), QLabel(' Z:', ), QLabel(' Y:', )]
        for i in range(3):
            lcdLay.addWidget(self.extraLabels[i], i, 0, Qt.AlignLeft)
        self.extraLcds = [Lcd(1.5, 13), Lcd(1.5, 13), Lcd(1.5, 13)]
        lcdLay.addWidget(self.extraLcds[2], 0, 1, Qt.AlignRight)
        lcdLay.addWidget(self.extraLcds[1], 1, 1, Qt.AlignRight)
        lcdLay.addWidget(self.extraLcds[0], 2, 1, Qt.AlignRight)
        if not self.calc.option.boolData('ViewRegisters'):
            for w in self.extraLabels + self.extraLcds:
                w.hide()
        self.lcd = Lcd(2.0, 13)
        lcdLay.addWidget(self.lcd, 3, 0, 1, 2, Qt.AlignRight)
        self.setLcdHighlight()
        self.updateLcd()
        self.updateColors()

        self.cmdLay = QGridLayout()
        topLay.addLayout(self.cmdLay)
        self.cmdDict = {}
        self.addCmdButton('x^2', 0, 0)
        self.addCmdButton('sqRT', 0, 1)
        self.addCmdButton('y^X', 0, 2)
        self.addCmdButton('xRT', 0, 3)
        self.addCmdButton('RCIP', 0, 4)
        self.addCmdButton('SIN', 1, 0)
        self.addCmdButton('COS', 1, 1)
        self.addCmdButton('TAN', 1, 2)
        self.addCmdButton('LN', 1, 3)
        self.addCmdButton('e^X', 1, 4)
        self.addCmdButton('ASIN', 2, 0)
        self.addCmdButton('ACOS', 2, 1)
        self.addCmdButton('ATAN', 2, 2)
        self.addCmdButton('LOG', 2, 3)
        self.addCmdButton('tn^X', 2, 4)
        self.addCmdButton('STO', 3, 0)
        self.addCmdButton('RCL', 3, 1)
        self.addCmdButton('R<', 3, 2)
        self.addCmdButton('R>', 3, 3)
        self.addCmdButton('x<>y', 3, 4)
        self.addCmdButton('SHOW', 4, 0)
        self.addCmdButton('CLR', 4, 1)
        self.addCmdButton('PLCS', 4, 2)
        self.addCmdButton('SCI', 4, 3)
        self.addCmdButton('DEG', 4, 4)
        self.addCmdButton('EXIT', 5, 0)
        self.addCmdButton('Pi', 5, 1)
        self.addCmdButton('EXP', 5, 2)
        self.addCmdButton('CHS', 5, 3)
        self.addCmdButton('<-', 5, 4)

        self.mainLay = QGridLayout()
        topLay.addLayout(self.mainLay)
        self.mainDict = {}
        self.addMainButton(0, 'OPT', 0, 0)
        self.addMainButton(Qt.Key_Slash, '/', 0, 1)
        self.addMainButton(Qt.Key_Asterisk, '*', 0, 2)
        self.addMainButton(Qt.Key_Minus, '-', 0, 3)
        self.addMainButton(Qt.Key_7, '7', 1, 0)
        self.addMainButton(Qt.Key_8, '8', 1, 1)
        self.addMainButton(Qt.Key_9, '9', 1, 2)
        self.addMainButton(Qt.Key_Plus, '+', 1, 3, 1, 0)
        self.addMainButton(Qt.Key_4, '4', 2, 0)
        self.addMainButton(Qt.Key_5, '5', 2, 1)
        self.addMainButton(Qt.Key_6, '6', 2, 2)
        self.addMainButton(Qt.Key_1, '1', 3, 0)
        self.addMainButton(Qt.Key_2, '2', 3, 1)
        self.addMainButton(Qt.Key_3, '3', 3, 2)
        self.addMainButton(Qt.Key_Enter, 'ENT', 3, 3, 1, 0)
        self.addMainButton(Qt.Key_0, '0', 4, 0, 0, 1)
        self.addMainButton(Qt.Key_Period, '.', 4, 2)

        self.mainDict[Qt.Key_Return] = \
                     self.mainDict[Qt.Key_Enter]
        # added for european keyboards:
        self.mainDict[Qt.Key_Comma] = \
                     self.mainDict[Qt.Key_Period]
        self.cmdDict['ENT'] = self.mainDict[Qt.Key_Enter]
        self.cmdDict['OPT'] = self.mainDict[0]

        self.entryStr = ''
        self.showMode = False

        statusBox = QFrame()
        statusBox.setFrameStyle(QFrame.Panel | QFrame.Sunken)
        statusBox.setSizePolicy(
            QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))
        topLay.addWidget(statusBox)
        statusLay = QHBoxLayout(statusBox)
        self.entryLabel = QLabel(statusBox)
        statusLay.addWidget(self.entryLabel)
        statusLay.setContentsMargins(1, 1, 1, 1)
        self.statusLabel = QLabel(statusBox)
        self.statusLabel.setAlignment(Qt.AlignRight)
        statusLay.addWidget(self.statusLabel)

        if self.calc.option.boolData('ExtraViewStartup'):
            self.viewReg()
        if self.calc.option.boolData('AltBaseStartup'):
            self.viewAltBases()

        rect = QRect(self.calc.option.intData('MainDlgXPos', 0, 10000),
                     self.calc.option.intData('MainDlgYPos', 0, 10000),
                     self.calc.option.intData('MainDlgXSize', 0, 10000),
                     self.calc.option.intData('MainDlgYSize', 0, 10000))
        if rect.isValid():
            availRect = (
                QApplication.primaryScreen().availableVirtualGeometry())
            topMargin = self.calc.option.intData('MainDlgTopMargin', 0, 1000)
            otherMargin = self.calc.option.intData('MainDlgOtherMargin', 0,
                                                   1000)
            # remove frame space from available rect
            availRect.adjust(otherMargin, topMargin, -otherMargin,
                             -otherMargin)
            finalRect = rect.intersected(availRect)
            if finalRect.isEmpty():
                rect.moveTo(0, 0)
                finalRect = rect.intersected(availRect)
            if finalRect.isValid():
                self.setGeometry(finalRect)

        self.updateEntryLabel('rpCalc Version {0}'.format(__version__))
        QTimer.singleShot(5000, self.updateEntryLabel)
示例#22
0
def disable_noise_suppression(disable_menu, enable_menu):
    unload_modules()
    disable_menu.setEnabled(False)
    enable_menu.setEnabled(True)


if __name__ == '__main__':
    appctxt = ApplicationContext()
    ico_file = appctxt.get_resource('icon.png')
    icon = QIcon(ico_file)

    tray = QSystemTrayIcon()
    tray.setIcon(icon)
    tray.setVisible(True)

    main_menu = QMenu()
    disable_suppression_menu = QAction("Disable Noise Suppression")
    disable_suppression_menu.setEnabled(False)

    enable_suppression_menu = QMenu("Enable Noise Suppression")
    for src in pulse.source_list():
        enable_suppression_menu.addAction(
            AudioMenuItem(src.description, enable_suppression_menu,
                          disable_suppression_menu, src.name, appctxt))

    disable_suppression_menu.triggered.connect(
        lambda: disable_noise_suppression(disable_suppression_menu,
                                          enable_suppression_menu))

    main_menu.addMenu(enable_suppression_menu)
    main_menu.addAction(disable_suppression_menu)
示例#23
0
    def __init__(self):
        super(PaletteDocker, self).__init__()
        # make base-widget and layout
        widget = QWidget()
        layout = QVBoxLayout()
        buttonLayout = QHBoxLayout()
        widget.setLayout(layout)
        self.setWindowTitle(i18n("Python Palette Docker"))

        # Make a combobox and add palettes
        self.cmb_palettes = QComboBox()
        allPalettes = Application.resources("palette")
        for palette_name in allPalettes:
            self.cmb_palettes.addItem(palette_name)
            self.cmb_palettes.model().sort(0)

        if len(allPalettes.keys()) > 0:
            self.currentPalette = Palette(list(allPalettes.values())[0])
        else:
            self.currentPalette = None

        self.cmb_palettes.currentTextChanged.connect(self.slot_paletteChanged)
        layout.addWidget(self.cmb_palettes)  # add combobox to the layout
        self.paletteView = PaletteView()
        self.paletteView.setPalette(self.currentPalette)
        layout.addWidget(self.paletteView)
        self.paletteView.entrySelectedForeGround.connect(
            self.slot_swatchSelected)

        self.colorComboBox = QComboBox()
        self.colorList = list()
        buttonLayout.addWidget(self.colorComboBox)
        self.bnSetColor = QToolButton()
        self.bnSetColor.setText(i18n("Set"))
        self.bnSetColor.clicked.connect(self.slot_get_color_from_combobox)
        buttonLayout.addWidget(self.bnSetColor)

        self.addEntry = QAction(self)
        self.addEntry.setIconText(i18n("+"))
        self.addEntry.triggered.connect(self.slot_add_entry)
        self.addGroup = QAction(self)
        self.addGroup.triggered.connect(self.slot_add_group)
        self.addGroup.setText(
            i18nc("Group as Color Group in a Palette", "Add Group"))
        self.addGroup.setIconText(str("\U0001F4C2"))
        self.removeEntry = QAction(self)
        self.removeEntry.setText(i18n("Remove Entry"))
        self.removeEntry.setIconText("-")
        self.removeEntry.triggered.connect(self.slot_remove_entry)
        addEntryButton = QToolButton()
        addEntryButton.setDefaultAction(self.addEntry)
        buttonLayout.addWidget(addEntryButton)
        addGroupButton = QToolButton()
        addGroupButton.setDefaultAction(self.addGroup)
        buttonLayout.addWidget(addGroupButton)
        removeEntryButton = QToolButton()
        removeEntryButton.setDefaultAction(self.removeEntry)
        buttonLayout.addWidget(removeEntryButton)

        # QActions
        self.extra = QToolButton()
        self.editPaletteData = QAction(self)
        self.editPaletteData.setText(i18n("Edit Palette Settings"))
        self.editPaletteData.triggered.connect(self.slot_edit_palette_data)
        self.extra.setDefaultAction(self.editPaletteData)
        buttonLayout.addWidget(self.extra)
        self.actionMenu = QMenu()
        self.exportToGimp = QAction(self)
        self.exportToGimp.setText(i18n("Export as GIMP Palette File"))
        self.exportToGimp.triggered.connect(self.slot_export_to_gimp_palette)
        self.exportToInkscape = QAction(self)
        self.exportToInkscape.setText(
            i18n("Export as Inkscape SVG with Swatches"))
        self.exportToInkscape.triggered.connect(
            self.slot_export_to_inkscape_svg)
        self.sortColors = QAction(self)
        self.sortColors.setText(i18n("Sort Colors"))
        self.sortColors.triggered.connect(self.slot_sort_colors)
        self.actionMenu.addAction(self.editPaletteData)
        self.actionMenu.addAction(self.exportToGimp)
        self.actionMenu.addAction(self.exportToInkscape)
        # self.actionMenu.addAction(self.sortColors)

        self.extra.setMenu(self.actionMenu)

        layout.addLayout(buttonLayout)
        self.slot_fill_combobox()
        self.setWidget(widget)  # add widget to the docker
示例#24
0
    def __init__(self, novelView):
        QTreeWidget.__init__(self, novelView)

        logger.debug("Initialising GuiNovelToolBar ...")

        self.mainConf = novelwriter.CONFIG
        self.novelView = novelView
        self.theProject = novelView.mainGui.theProject
        self.mainTheme = novelView.mainGui.mainTheme

        iPx = self.mainTheme.baseIconSize
        mPx = self.mainConf.pxInt(3)

        self.setContentsMargins(0, 0, 0, 0)
        self.setAutoFillBackground(True)

        qPalette = self.palette()
        qPalette.setBrush(QPalette.Window, qPalette.base())
        self.setPalette(qPalette)

        fadeCol = qPalette.text().color()
        buttonStyle = (
            "QToolButton {{padding: {0}px; border: none; background: transparent;}} "
            "QToolButton:hover {{border: none; background: rgba({1},{2},{3},0.2);}}"
        ).format(mPx, fadeCol.red(), fadeCol.green(), fadeCol.blue())

        # Widget Label
        self.viewLabel = QLabel("<b>%s</b>" % self.tr("Novel Outline"))
        self.viewLabel.setContentsMargins(0, 0, 0, 0)
        self.viewLabel.setSizePolicy(QSizePolicy.Expanding,
                                     QSizePolicy.Expanding)

        # Refresh Button
        self.tbRefresh = QToolButton(self)
        self.tbRefresh.setToolTip(self.tr("Refresh"))
        self.tbRefresh.setIcon(self.mainTheme.getIcon("refresh"))
        self.tbRefresh.setIconSize(QSize(iPx, iPx))
        self.tbRefresh.setStyleSheet(buttonStyle)
        self.tbRefresh.clicked.connect(self._refreshNovelTree)

        # Novel Root Menu
        self.mRoot = QMenu()
        self.gRoot = QActionGroup(self.mRoot)
        self.aRoot = {}

        self.tbRoot = QToolButton(self)
        self.tbRoot.setToolTip(self.tr("Novel Root"))
        self.tbRoot.setIcon(
            self.mainTheme.getIcon(nwLabels.CLASS_ICON[nwItemClass.NOVEL]))
        self.tbRoot.setIconSize(QSize(iPx, iPx))
        self.tbRoot.setStyleSheet(buttonStyle)
        self.tbRoot.setMenu(self.mRoot)
        self.tbRoot.setPopupMode(QToolButton.InstantPopup)

        # More Options Menu
        self.mMore = QMenu()

        self.mLastCol = self.mMore.addMenu(self.tr("Last Column"))
        self.gLastCol = QActionGroup(self.mMore)
        self.aLastCol = {}
        self._addLastColAction(NovelTreeColumn.HIDDEN, self.tr("Hidden"))
        self._addLastColAction(NovelTreeColumn.POV,
                               self.tr("Point of View Character"))
        self._addLastColAction(NovelTreeColumn.FOCUS,
                               self.tr("Focus Character"))
        self._addLastColAction(NovelTreeColumn.PLOT, self.tr("Novel Plot"))

        self.tbMore = QToolButton(self)
        self.tbMore.setToolTip(self.tr("More Options"))
        self.tbMore.setIcon(self.mainTheme.getIcon("menu"))
        self.tbMore.setIconSize(QSize(iPx, iPx))
        self.tbMore.setStyleSheet(buttonStyle)
        self.tbMore.setMenu(self.mMore)
        self.tbMore.setPopupMode(QToolButton.InstantPopup)

        # Assemble
        self.outerBox = QHBoxLayout()
        self.outerBox.addWidget(self.viewLabel)
        self.outerBox.addWidget(self.tbRefresh)
        self.outerBox.addWidget(self.tbRoot)
        self.outerBox.addWidget(self.tbMore)
        self.outerBox.setContentsMargins(mPx, mPx, 0, mPx)
        self.outerBox.setSpacing(0)

        self.setLayout(self.outerBox)

        logger.debug("GuiNovelToolBar initialisation complete")

        return
示例#25
0
    def __init__(self):
        super(QMainWindow, self).__init__()
        # Set up the user interface from Designer.
        self.setupUi(self)
        
        self.setAccessibleName("Hive Desktop")
        self.redrawLock = Lock()
        self.updateLock = Lock()
        
        self.optionsDialog = dialogs.Options(self)
        self.aboutDialog = dialogs.About(self,
            copyright='holger80',
            programName='Hive Desktop',
            version=VERSION,
            website='https://github.com/holgern/hivedesktop',
            websiteLabel='Github',
            comments='"Welcome to Hive desktop!\n This is the first release for testing qt5.\n Please vote for holger80 as witness, if you like this :).',
            licenseName='GPL-3.0',
            # licenseUrl=helpers.joinpath_to_cwd('LICENSE').as_uri(),
            authors=('holger80',),
            # dependencies=[l.strip() for l in requirements.readlines()],
        )		
        self.mdrenderer = MDRenderer(str(helpers.joinpath_to_cwd('themes')))

        # tmpfile = helpers.mktemp(prefix='hivedesktop', suffix='.html')
        
        self.post = {"body": "##test", "authorperm": "@test/test"}
        self.thread = threads.MDThread(self)
        
        
        # self.webview.url = tmpfile.as_uri()
        
        
        self.feedListWidget.currentRowChanged.connect(self.change_displayed_post, Qt.QueuedConnection)
        
        self.timer = QTimer()
        self.timer.timeout.connect(self.refresh_account_thread)
        
        self.timer2 = QTimer()
        self.timer2.timeout.connect(self.update_account_hist_thread)

        self.timer3 = QTimer()
        self.timer3.timeout.connect(self.update_account_feed_thread)
        
        self.cache_path = QStandardPaths.writableLocation(QStandardPaths.CacheLocation)
        self.db_type = "shelve"
        self.db_type = "sqlite"
        self.feed = []
        self.post = None
        # Get settings
        settings = QSettings()
        # Get checkbox state with speciying type of checkbox:
        # type=bool is a replacement of toBool() in PyQt5
        check_state = settings.value(SETTINGS_TRAY, True, type=bool)
        hist_info_check_state = settings.value(SETTINGS_HIST_INFO, True, type=bool)
        account_state = settings.value(SETTINGS_ACCOUNT, "", type=str)
        self.resize(settings.value(SETTINGS_SIZE, QSize(1053, 800)))
        self.move(settings.value(SETTINGS_POS, QPoint(50, 50)))
        
        #self.accountHistTableWidget.setColumnCount(5)
        #self.accountHistTableWidget.setHorizontalHeaderLabels(["type", "1", "2", "3", "timestamp"])
        
        self.update_account_refreshtime = 5000
        
        # Set state
        self.accountHistNotificationCheckBox.setChecked(hist_info_check_state)
        self.autoRefreshCheckBox.setChecked(check_state)
        if check_state:
            self.timer.start(self.update_account_refreshtime)
            self.timer2.start(15000)
            self.timer3.start(60000)
        self.accountLineEdit.setText(account_state)
        # connect the slot to the signal by clicking the checkbox to save the state settings
        self.autoRefreshCheckBox.clicked.connect(self.save_check_box_settings)   
        self.accountHistNotificationCheckBox.clicked.connect(self.save_check_box_settings)  
        self.accountLineEdit.editingFinished.connect(self.save_account_settings)
        self.actionAbout.triggered.connect(self.about)
        self.actionOptions.triggered.connect(self.options)
        self.threadpool = QThreadPool()
        
        self.minimizeAction = QAction("Mi&nimize", self, triggered=self.hide)
        self.maximizeAction = QAction("Ma&ximize", self,
                triggered=self.showMaximized)
        self.restoreAction = QAction("&Restore", self,
                triggered=self.showNormal)        
        
        menu = QMenu()
        menu.addAction(self.minimizeAction)
        menu.addAction(self.maximizeAction)
        menu.addAction(self.restoreAction)
        menu.addSeparator()        
        # aboutAction = menu.addAction("about")
        # aboutAction.triggered.connect(self.about)
        exitAction = menu.addAction("Exit")
        exitAction.triggered.connect(self.closeApp)
        
        self.tray = QSystemTrayIcon(QIcon(':/icons/icon.ico'))
        
        self.tray.setContextMenu(menu)
        self.tray.activated.connect(self.trayAction)
        
        self.tray.setToolTip("Hive Desktop!")
        self.tray.setObjectName("Hive Desktop")
        self.setWindowTitle("Hive Desktop")
        self.tray.show()
        
        splash_pix = QPixmap(':/icons/splash.png')
        splash = QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
        splash.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)
        splash.setEnabled(False)
        
        #splash.show()
        #splash.showMessage("<h1><font color='green'>starting...</font></h1>", Qt.AlignTop | Qt.AlignCenter, Qt.black)        
        
        account = account_state
        nodelist = NodeList()
        nodelist.update_nodes()
        self.stm = Steem(node=nodelist.get_nodes(hive=True))
        set_shared_blockchain_instance(self.stm)
        if account != "":
            try:
                self.hist_account = Account(account, steem_instance=self.stm)
            except:
                self.hist_account = None
        else:
            self.hist_account = None
            
        self.refreshPushButton.clicked.connect(self.refresh_account)
        self.refreshPushButton.clicked.connect(self.update_account_hist_thread)
        self.accountLineEdit.editingFinished.connect(self.update_account_info)        
        if self.hasFocus is not None:
            self.init_new_account()
            self.init_new_blocks()
        splash.deleteLater()
示例#26
0
    def create_menu(self, position):
        menu = QMenu()
        menu.setSeparatorsCollapsible(
            True)  # consecutive separators are merged together
        selected = self.selected_in_column(self.Columns.NODE_ALIAS)
        if not selected:
            menu.addAction(
                _("Import channel backup"),
                lambda: self.parent.do_process_from_text_channel_backup())
            menu.exec_(self.viewport().mapToGlobal(position))
            return
        multi_select = len(selected) > 1
        if multi_select:
            return
        idx = self.indexAt(position)
        if not idx.isValid():
            return
        item = self.model().itemFromIndex(idx)
        if not item:
            return
        channel_id = idx.sibling(idx.row(),
                                 self.Columns.NODE_ALIAS).data(ROLE_CHANNEL_ID)
        chan = self.lnworker.channel_backups.get(channel_id)
        if chan:
            funding_tx = self.parent.wallet.db.get_transaction(
                chan.funding_outpoint.txid)
            menu.addAction(_("View funding transaction"),
                           lambda: self.parent.show_transaction(funding_tx))
            if chan.get_state() == ChannelState.FUNDED:
                menu.addAction(_("Request force-close"),
                               lambda: self.request_force_close(channel_id))
            if chan.can_be_deleted():
                menu.addAction(_("Delete"),
                               lambda: self.remove_channel_backup(channel_id))
            menu.exec_(self.viewport().mapToGlobal(position))
            return
        chan = self.lnworker.channels[channel_id]
        menu.addAction(_("Details..."),
                       lambda: self.parent.show_channel(channel_id))
        cc = self.add_copy_menu(menu, idx)
        cc.addAction(
            _("Node ID"),
            lambda: self.place_text_on_clipboard(chan.node_id.hex(),
                                                 title=_("Node ID")))
        cc.addAction(
            _("Long Channel ID"),
            lambda: self.place_text_on_clipboard(channel_id.hex(),
                                                 title=_("Long Channel ID")))
        if not chan.is_closed():
            if not chan.is_frozen_for_sending():
                menu.addAction(
                    _("Freeze (for sending)"),
                    lambda: self.freeze_channel_for_sending(chan, True))
            else:
                menu.addAction(
                    _("Unfreeze (for sending)"),
                    lambda: self.freeze_channel_for_sending(chan, False))
            if not chan.is_frozen_for_receiving():
                menu.addAction(_("Freeze (for receiving)"),
                               lambda: chan.set_frozen_for_receiving(True))
            else:
                menu.addAction(_("Unfreeze (for receiving)"),
                               lambda: chan.set_frozen_for_receiving(False))

        funding_tx = self.parent.wallet.db.get_transaction(
            chan.funding_outpoint.txid)
        if funding_tx:
            menu.addAction(_("View funding transaction"),
                           lambda: self.parent.show_transaction(funding_tx))
        if not chan.is_closed():
            menu.addSeparator()
            if chan.peer_state == PeerState.GOOD:
                menu.addAction(_("Close channel"),
                               lambda: self.close_channel(channel_id))
            menu.addAction(_("Force-close channel"),
                           lambda: self.force_close(channel_id))
        else:
            item = chan.get_closing_height()
            if item:
                txid, height, timestamp = item
                closing_tx = self.lnworker.lnwatcher.db.get_transaction(txid)
                if closing_tx:
                    menu.addAction(
                        _("View closing transaction"),
                        lambda: self.parent.show_transaction(closing_tx))
        menu.addSeparator()
        menu.addAction(_("Export backup"),
                       lambda: self.export_channel_backup(channel_id))
        if chan.can_be_deleted():
            menu.addSeparator()
            menu.addAction(_("Delete"),
                           lambda: self.remove_channel(channel_id))
        menu.exec_(self.viewport().mapToGlobal(position))
示例#27
0
    def __init__(self,
                 *,
                 parent: 'ElectrumWindow',
                 desc,
                 prompt_if_unsaved,
                 finalized: bool,
                 external_keypairs=None):
        '''Transactions in the wallet will show their description.
        Pass desc to give a description for txs not yet in the wallet.
        '''
        # We want to be a top-level window
        QDialog.__init__(self, parent=None)
        self.tx = None  # type: Optional[Transaction]
        self.external_keypairs = external_keypairs
        self.finalized = finalized
        self.main_window = parent
        self.config = parent.config
        self.wallet = parent.wallet
        self.prompt_if_unsaved = prompt_if_unsaved
        self.saved = False
        self.desc = desc
        self.setMinimumWidth(950)
        self.set_title()

        self.psbt_only_widgets = []  # type: List[QWidget]

        vbox = QVBoxLayout()
        self.setLayout(vbox)

        self.txid_lb = QLabel(_('Transaction ID:'))
        vbox.addWidget(self.txid_lb)
        self.tx_hash_e = ButtonsLineEdit()
        qr_show = lambda: parent.show_qrcode(
            str(self.tx_hash_e.text()), 'Transaction ID', parent=self)
        qr_icon = "qrcode.png"
        self.tx_hash_e.addButton(qr_icon, qr_show, _("Show as QR code"))
        self.tx_hash_e.setReadOnly(True)
        vbox.addWidget(self.tx_hash_e)

        self.add_tx_stats(vbox)

        vbox.addSpacing(10)

        self.inputs_header = QLabel()
        vbox.addWidget(self.inputs_header)
        self.inputs_textedit = QTextEditWithDefaultSize()
        vbox.addWidget(self.inputs_textedit)
        self.outputs_header = QLabel()
        vbox.addWidget(self.outputs_header)
        self.outputs_textedit = QTextEditWithDefaultSize()
        vbox.addWidget(self.outputs_textedit)

        self.extra_pld_lb = QLabel('Extra payload:')
        self.extra_pld_lb.hide()
        vbox.addWidget(self.extra_pld_lb)
        self.extra_pld = ExtraPayloadWidget()
        self.extra_pld.hide()
        vbox.addWidget(self.extra_pld)

        self.sign_button = b = QPushButton(_("Sign"))
        b.clicked.connect(self.sign)

        self.broadcast_button = b = QPushButton(_("Broadcast"))
        b.clicked.connect(self.do_broadcast)

        self.save_button = b = QPushButton(_("Save"))
        b.clicked.connect(self.save)

        self.cancel_button = b = QPushButton(_("Close"))
        b.clicked.connect(self.close)
        b.setDefault(True)

        self.export_actions_menu = export_actions_menu = QMenu()
        self.add_export_actions_to_menu(export_actions_menu)
        export_actions_menu.addSeparator()
        export_submenu = export_actions_menu.addMenu(
            _("For CoinJoin; strip privates"))
        self.add_export_actions_to_menu(export_submenu,
                                        gettx=self._gettx_for_coinjoin)
        self.psbt_only_widgets.append(export_submenu)
        export_submenu = export_actions_menu.addMenu(
            _("For hardware device; include xpubs"))
        self.add_export_actions_to_menu(export_submenu,
                                        gettx=self._gettx_for_hardware_device)
        self.psbt_only_widgets.append(export_submenu)

        self.export_actions_button = QToolButton()
        self.export_actions_button.setObjectName("blue_toolbutton")
        self.export_actions_button.setText(_("Export"))
        self.export_actions_button.setMenu(export_actions_menu)
        self.export_actions_button.setPopupMode(QToolButton.InstantPopup)

        self.finalize_button = QPushButton(_('Finalize'))
        self.finalize_button.clicked.connect(self.on_finalize)

        partial_tx_actions_menu = QMenu()
        ptx_merge_sigs_action = QAction(_("Merge signatures from"), self)
        ptx_merge_sigs_action.triggered.connect(self.merge_sigs)
        partial_tx_actions_menu.addAction(ptx_merge_sigs_action)
        self.partial_tx_actions_button = QToolButton()
        self.partial_tx_actions_button.setObjectName("blue_toolbutton")
        self.partial_tx_actions_button.setText(_("Combine"))
        self.partial_tx_actions_button.setMenu(partial_tx_actions_menu)
        self.partial_tx_actions_button.setPopupMode(QToolButton.InstantPopup)
        self.psbt_only_widgets.append(self.partial_tx_actions_button)

        # Action buttons
        self.buttons = [
            self.partial_tx_actions_button, self.sign_button,
            self.broadcast_button, self.cancel_button
        ]
        # Transaction sharing buttons
        self.sharing_buttons = [
            self.finalize_button, self.export_actions_button, self.save_button
        ]
        run_hook('transaction_dialog', self)
        if not self.finalized:
            self.create_fee_controls()
            vbox.addWidget(self.feecontrol_fields)
        self.hbox = hbox = QHBoxLayout()
        hbox.addLayout(Buttons(*self.sharing_buttons))
        hbox.addStretch(1)
        hbox.addLayout(Buttons(*self.buttons))
        vbox.addLayout(hbox)
        self.set_buttons_visibility()

        dialogs.append(self)
示例#28
0
 def func(position):
     menu: QMenu = QMenu(self)
     related_tables_action: QAction = menu.addAction('Show related tables')
     related_tables_action.triggered.connect(self.show_related_tables(view, reverse_target))
     menu.exec_(view.viewport().mapToGlobal(position))
示例#29
0
    def create_menu(self, position):
        from electrum_mona.wallet import Multisig_Wallet
        is_multisig = isinstance(self.wallet, Multisig_Wallet)
        can_delete = self.wallet.can_delete_address()
        selected = self.selected_in_column(self.Columns.ADDRESS)
        if not selected:
            return
        multi_select = len(selected) > 1
        addrs = [self.model().itemFromIndex(item).text() for item in selected]
        menu = QMenu()
        if not multi_select:
            idx = self.indexAt(position)
            if not idx.isValid():
                return
            item = self.model().itemFromIndex(idx)
            if not item:
                return
            addr = addrs[0]
            addr_column_title = self.model().horizontalHeaderItem(
                self.Columns.LABEL).text()
            addr_idx = idx.sibling(idx.row(), self.Columns.LABEL)
            self.add_copy_menu(menu, idx)
            menu.addAction(_('Details'),
                           lambda: self.parent.show_address(addr))
            persistent = QPersistentModelIndex(addr_idx)
            menu.addAction(_("Edit {}").format(addr_column_title),
                           lambda p=persistent: self.edit(QModelIndex(p)))
            menu.addAction(_("Request payment"),
                           lambda: self.parent.receive_at(addr))
            if self.wallet.can_export():
                menu.addAction(_("Private key"),
                               lambda: self.parent.show_private_key(addr))
            if not is_multisig and not self.wallet.is_watching_only():
                menu.addAction(_("Sign/verify message"),
                               lambda: self.parent.sign_verify_message(addr))
                menu.addAction(_("Encrypt/decrypt message"),
                               lambda: self.parent.encrypt_message(addr))
            if can_delete:
                menu.addAction(_("Remove from wallet"),
                               lambda: self.parent.remove_address(addr))
            addr_URL = block_explorer_URL(self.config, 'addr', addr)
            if addr_URL:
                menu.addAction(_("View on block explorer"),
                               lambda: webopen(addr_URL))

            if not self.wallet.is_frozen_address(addr):
                menu.addAction(
                    _("Freeze"), lambda: self.parent.
                    set_frozen_state_of_addresses([addr], True))
            else:
                menu.addAction(
                    _("Unfreeze"), lambda: self.parent.
                    set_frozen_state_of_addresses([addr], False))

        coins = self.wallet.get_spendable_coins(addrs)
        if coins:
            menu.addAction(_("Spend from"),
                           lambda: self.parent.spend_coins(coins))

        run_hook('receive_menu', menu, addrs, self.wallet)
        menu.exec_(self.viewport().mapToGlobal(position))
    def init_ui(self):
        """Inits UI"""
        uic.loadUi("gui/mainwindow.ui", self)

        self.setWindowTitle(prefs.PACKAGE_NAME)

        # accept file drops
        self.setAcceptDrops(True)

        self.resize(prefs.WINDOW_WIDTH, prefs.WINDOW_HEIGHT)

        # make trace table wider than regs&mem
        self.splitter1.setSizes([1000, 100])
        self.splitter2.setSizes([600, 100])

        # Init trace table
        self.trace_table.itemSelectionChanged.connect(
            self.on_trace_table_row_changed)
        self.trace_table.setColumnCount(len(prefs.TRACE_LABELS))
        self.trace_table.setHorizontalHeaderLabels(prefs.TRACE_LABELS)
        self.trace_table.horizontalHeader().setStretchLastSection(True)
        self.trace_table.bookmarkCreated.connect(self.add_bookmark)
        self.trace_table.commentEdited.connect(self.set_comment)
        self.trace_table.printer = self.print
        self.trace_table.set_row_height(prefs.TRACE_ROW_HEIGHT)

        trace_font = QFont(prefs.TRACE_FONT)
        trace_font.setPointSize(prefs.TRACE_FONT_SIZE)
        self.trace_table.setFont(trace_font)
        self.bookmark_table.setFont(trace_font)
        self.trace_table.setShowGrid(prefs.TRACE_SHOW_GRID)

        if prefs.USE_SYNTAX_HIGHLIGHT_IN_TRACE:
            self.trace_table.init_syntax_highlight()

        # trace pagination
        if prefs.PAGINATION_ENABLED:
            self.trace_pagination = PaginationWidget()
            self.trace_pagination.pageChanged.connect(
                self.trace_table.populate)
            self.horizontalLayout.addWidget(self.trace_pagination)
            self.trace_pagination.set_enabled(True)
            self.trace_pagination.rows_per_page = prefs.PAGINATION_ROWS_PER_PAGE

            self.trace_table.pagination = self.trace_pagination
            self.horizontalLayout.setAlignment(self.trace_pagination,
                                               Qt.AlignLeft)

        # these are used to remember current pages & scroll values for both traces
        self.trace_current_pages = [1, 1]
        self.trace_scroll_values = [0, 0]

        self.reg_table.create_context_menu()
        self.reg_table.setColumnCount(len(prefs.REG_LABELS))
        self.reg_table.setHorizontalHeaderLabels(prefs.REG_LABELS)
        self.reg_table.horizontalHeader().setStretchLastSection(True)
        self.reg_table.regCheckBoxChanged.connect(self.on_reg_checkbox_change)
        self.reg_table.printer = self.print

        if prefs.REG_FILTER_ENABLED:
            self.reg_table.filtered_regs = prefs.REG_FILTER

        if not prefs.USE_DARK_THEME:
            trace_style = (
                "QTableView { selection-background-color: #dddddd; selection-"
                "color: #000000; border: 0px;} QTableWidget::item { padding: 0px; border: 0px}"
            )
            reg_style = (
                "QTableView { selection-background-color: #eee864; selection"
                "-color: #000000;}")
            self.trace_table.setStyleSheet(trace_style)
            self.bookmark_table.setStyleSheet(trace_style)
            self.reg_table.setStyleSheet(reg_style)

        # Init memory table
        self.mem_table.setColumnCount(len(prefs.MEM_LABELS))
        self.mem_table.setHorizontalHeaderLabels(prefs.MEM_LABELS)
        self.mem_table.horizontalHeader().setStretchLastSection(True)

        # Init bookmark table
        self.bookmark_table.setColumnCount(len(prefs.BOOKMARK_LABELS))
        self.bookmark_table.setHorizontalHeaderLabels(prefs.BOOKMARK_LABELS)
        self.bookmark_table.setContextMenuPolicy(Qt.CustomContextMenu)
        self.bookmark_table.customContextMenuRequested.connect(
            self.bookmark_table_context_menu_event)

        self.bookmark_table.delegate = SyntaxHighlightDelegate(self)
        self.bookmark_table.delegate.disasm_columns = prefs.BOOKMARK_HL_DISASM_COLUMNS
        self.bookmark_table.delegate.value_columns = prefs.BOOKMARK_HL_VALUE_COLUMNS
        self.bookmark_table.setItemDelegate(self.bookmark_table.delegate)

        self.bookmark_menu = QMenu(self)

        go_action = QAction("Go to bookmark", self)
        go_action.triggered.connect(self.go_to_bookmark_in_trace)
        self.bookmark_menu.addAction(go_action)

        delete_bookmarks_action = QAction("Delete bookmark(s)", self)
        delete_bookmarks_action.triggered.connect(self.delete_bookmarks)
        self.bookmark_menu.addAction(delete_bookmarks_action)

        # Menu
        exit_action = QAction("&Exit", self)
        exit_action.setShortcut("Ctrl+Q")
        exit_action.setStatusTip("Exit application")
        exit_action.triggered.connect(self.close)

        open_trace_action = QAction("&Open trace..", self)
        open_trace_action.setStatusTip("Open trace")
        open_trace_action.triggered.connect(self.dialog_open_trace)

        self.save_trace_action = QAction("&Save trace", self)
        self.save_trace_action.setStatusTip("Save trace")
        self.save_trace_action.triggered.connect(self.save_trace)
        self.save_trace_action.setEnabled(False)

        save_trace_as_action = QAction("&Save trace as..", self)
        save_trace_as_action.setStatusTip("Save trace as..")
        save_trace_as_action.triggered.connect(self.dialog_save_trace_as)

        save_trace_as_json_action = QAction("&Save trace as JSON..", self)
        save_trace_as_json_action.setStatusTip("Save trace as JSON..")
        save_trace_as_json_action.triggered.connect(
            self.dialog_save_trace_as_json)

        file_menu = self.menu_bar.addMenu("&File")
        file_menu.addAction(open_trace_action)
        file_menu.addAction(self.save_trace_action)
        file_menu.addAction(save_trace_as_action)
        file_menu.addAction(save_trace_as_json_action)
        file_menu.addAction(exit_action)

        self.plugins_topmenu = self.menu_bar.addMenu("&Plugins")

        clear_bookmarks_action = QAction("&Clear bookmarks", self)
        clear_bookmarks_action.setStatusTip("Clear bookmarks")
        clear_bookmarks_action.triggered.connect(self.clear_bookmarks)

        bookmarks_menu = self.menu_bar.addMenu("&Bookmarks")
        bookmarks_menu.addAction(clear_bookmarks_action)

        # Create right click menu for trace table
        self.create_trace_table_menu()
        # Create plugins menu on menu bar
        self.create_plugins_menu()

        about_action = QAction("&About", self)
        about_action.triggered.connect(self.show_about_dialog)

        about_menu = self.menu_bar.addMenu("&About")
        about_menu.addAction(about_action)

        if prefs.USE_SYNTAX_HIGHLIGHT_IN_LOG:
            self.highlight = AsmHighlighter(self.log_text_edit.document())

        # trace select
        self.select_trace_combo_box.addItem("Full trace")
        self.select_trace_combo_box.addItem("Filtered trace")
        self.select_trace_combo_box.currentIndexChanged.connect(
            self.on_trace_combo_box_index_changed)

        self.filter_widget = FilterWidget()
        self.filter_widget.filterBtnClicked.connect(self.on_filter_btn_clicked)
        self.horizontalLayout.addWidget(self.filter_widget)
        if prefs.SHOW_SAMPLE_FILTERS:
            self.filter_widget.set_sample_filters(prefs.SAMPLE_FILTERS)

        self.find_widget = FindWidget()
        self.find_widget.findBtnClicked.connect(self.on_find_btn_clicked)
        self.find_widget.set_fields(prefs.FIND_FIELDS)
        self.horizontalLayout.addWidget(self.find_widget)

        self.show()