Example #1
0
    def __init__(self):
        super().__init__()
        self.playerState = QMediaPlayer.StoppedState

        self.playButton = QToolButton(clicked=self.playClicked)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

        self.stopButton = QToolButton(clicked=self.stop)
        self.stopButton.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))

        self.pauseButton = QToolButton(clicked=self.pause)
        self.pauseButton.setIcon(
                self.style().standardIcon(QStyle.SP_MediaPause))

        self.nextButton = QToolButton(clicked=self.next)
        self.nextButton.setIcon(
                self.style().standardIcon(QStyle.SP_MediaSkipForward))

        self.previousButton = QToolButton(clicked=self.previous)
        self.previousButton.setIcon(
                self.style().standardIcon(QStyle.SP_MediaSkipBackward))

        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.stopButton)
        layout.addWidget(self.previousButton)
        layout.addWidget(self.playButton)
        layout.addWidget(self.nextButton)
        layout.addWidget(self.pauseButton)
        self.setLayout(layout)
    def __init__(self, parent=None):
        super(MyController, self).__init__(parent)

        self.theClassNames = QList()
        self.theClassCombo = QComboBox(self)
        self.theControlledObject = None

        button = QToolButton(self)
        self.theController = ObjectController(self)
        buttonBox = QDialogButtonBox(self)

        button.clicked.connect(self.createAndControl)
        buttonBox.rejected.connect(self.reject)

        button.setText(self.tr("Create And Control"))
        buttonBox.setStandardButtons(QDialogButtonBox.Close)

        layout = QVBoxLayout(self)
        internalLayout = QHBoxLayout()
        internalLayout.addWidget(self.theClassCombo)
        internalLayout.addWidget(button)
        layout.addLayout(internalLayout)
        layout.addWidget(self.theController)
        layout.addWidget(buttonBox)

        self.theClassNames.append("QWidget")
        self.theClassNames.append("QPushButton")
        self.theClassNames.append("QDialogButtonBox")
        self.theClassNames.append("QTreeWidget")
        self.theClassNames.append("QCalendarWidget")
        self.theClassNames.append("QAction")
        self.theClassNames.append("QTimeLine")
        self.theClassNames.append("QTextDocument")

        self.theClassCombo.addItems(self.theClassNames)
Example #3
0
    def __init__(self, dockwidget):
        super(Widget, self).__init__(dockwidget)
        self._document = None
        self._fileSelector = QComboBox(editable=True, insertPolicy=QComboBox.NoInsert)
        gadgets.drag.ComboDrag(self._fileSelector).role = Qt.UserRole
        self._fileSelector.lineEdit().setReadOnly(True)
        self._fileSelector.lineEdit().setFocusPolicy(Qt.NoFocus)
        self._stopButton = QToolButton()
        self._playButton = QToolButton()
        self._timeSlider = QSlider(Qt.Horizontal, tracking=False,
            singleStep=500, pageStep=5000, invertedControls=True)
        self._display = Display()
        self._tempoFactor = QSlider(Qt.Vertical, minimum=-50, maximum=50,
            singleStep=1, pageStep=5)

        grid = QGridLayout(spacing=0)
        self.setLayout(grid)

        grid.addWidget(self._fileSelector, 0, 0, 1, 3)
        grid.addWidget(self._stopButton, 1, 0)
        grid.addWidget(self._playButton, 1, 1)
        grid.addWidget(self._timeSlider, 1, 2)
        grid.addWidget(self._display, 2, 0, 1, 3)
        grid.addWidget(self._tempoFactor, 0, 3, 3, 1)

        # size policy of combo
        p = self._fileSelector.sizePolicy()
        p.setHorizontalPolicy(QSizePolicy.Ignored)
        self._fileSelector.setSizePolicy(p)

        # size policy of combo popup
        p = self._fileSelector.view().sizePolicy()
        p.setHorizontalPolicy(QSizePolicy.MinimumExpanding)
        self._fileSelector.view().setSizePolicy(p)

        self._player = player.Player()
        self._outputCloseTimer = QTimer(interval=60000, singleShot=True,
            timeout=self.closeOutput)
        self._timeSliderTicker = QTimer(interval=200, timeout=self.updateTimeSlider)
        self._fileSelector.activated[int].connect(self.slotFileSelected)
        self._tempoFactor.valueChanged.connect(self.slotTempoChanged)
        self._timeSlider.valueChanged.connect(self.slotTimeSliderChanged)
        self._timeSlider.sliderMoved.connect(self.slotTimeSliderMoved)
        self._player.beat.connect(self.updateDisplayBeat)
        self._player.time.connect(self.updateDisplayTime)
        self._player.stateChanged.connect(self.slotPlayerStateChanged)
        self.slotPlayerStateChanged(False)
        dockwidget.mainwindow().currentDocumentChanged.connect(self.loadResults)
        app.documentLoaded.connect(self.slotDocumentLoaded)
        app.jobFinished.connect(self.slotUpdatedFiles)
        app.aboutToQuit.connect(self.stop)
        midihub.aboutToRestart.connect(self.slotAboutToRestart)
        midihub.settingsChanged.connect(self.clearMidiSettings, -100)
        midihub.settingsChanged.connect(self.readMidiSettings)
        app.documentClosed.connect(self.slotDocumentClosed)
        app.translateUI(self)
        self.readMidiSettings()
        d = dockwidget.mainwindow().currentDocument()
        if d:
            self.loadResults(d)
Example #4
0
 def actionButton(self, action):
     if isinstance(action, QAction):
         button = QToolButton(self)
         button.setDefaultAction(action)
         return button
     elif isinstance(action, QAbstractButton):
         return action
Example #5
0
    def __init__(self, parentWidget, markerFmt, editWidget):
        QWidget.__init__(self, parentWidget)

        self.markerFormat = markerFmt
        self.textEdit = editWidget
        self.startPos = 0
        self.endPos = 0
        self.pattern = ''

        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        self.searchPattern = CancelAwareLineEdit(self)
        self.searchPattern.setPlaceholderText('Start typing to find in page')
        self.searchPattern.editingFinished.connect(self.hideWidget)
        self.searchPattern.textEdited.connect(self.doSearch)

        upAction = QAction(QIcon(':/icons/find-up.png'), "Find backwards (Shift-F3)", self)
        upAction.setShortcut(Qt.SHIFT + Qt.Key_F3);
        upAction.triggered.connect(self.findUpwards)
        self.upButton = QToolButton(self)
        self.upButton.setDefaultAction(upAction)

        downAction = QAction(QIcon(':/icons/find-down.png'), "Find next (F3)", self)
        downAction.setShortcut(Qt.Key_F3);
        downAction.triggered.connect(self.findDownwards)
        self.downButton = QToolButton(self)
        self.downButton.setDefaultAction(downAction)

        layout.addWidget(self.searchPattern)
        layout.addWidget(self.upButton)
        layout.addWidget(self.downButton)
Example #6
0
    def initToolBar(self):

        self.toolBar = QToolBar("Tools")
        self.toolBar.setMovable(False)
        self.addToolBar(Qt.LeftToolBarArea, self.toolBar)
        self.toolBar.setIconSize(QSize(20, 20))

        self.techAnButton = QToolButton()
        self.techAnButton.setText("Technical analysis")
        self.techAnButton.setFixedSize(130, 25)
        self.pairTrButton = QToolButton()
        self.pairTrButton.setText("Pair Trading")
        self.pairTrButton.setFixedSize(130, 25)
        self.atoTrdButton = QToolButton()
        self.atoTrdButton.setText("Monitor")
        self.atoTrdButton.setFixedSize(130, 25)
        self.trdPnlButton = QToolButton()
        self.trdPnlButton.setText("PnL Report")
        self.trdPnlButton.setFixedSize(130, 25)
        self.trdHisButton = QToolButton()
        self.trdHisButton.setText("Trade History")
        self.trdHisButton.setFixedSize(130, 25)

        self.techAnButton.clicked.connect(self.techAnPage)
        self.pairTrButton.clicked.connect(self.pairTrPage)
        self.atoTrdButton.clicked.connect(self.atoTrdPage)
        self.trdPnlButton.clicked.connect(self.trdPnlPage)
        self.trdHisButton.clicked.connect(self.trdHisPage)

        self.toolBar.addWidget(self.techAnButton)
        self.toolBar.addWidget(self.pairTrButton)
        self.toolBar.addWidget(self.atoTrdButton)
        self.toolBar.addWidget(self.trdPnlButton)
        self.toolBar.addWidget(self.trdHisButton)
        self.toolButtons = [self.techAnButton, self.pairTrButton, self.atoTrdButton, self.trdPnlButton, self.trdHisButton]
Example #7
0
    def __init__(self, parent):
        super(ScorePartsWidget, self).__init__(parent)
        
        self.typesLabel = QLabel()
        self.typesView = QTreeView(
            selectionMode=QTreeView.ExtendedSelection,
            selectionBehavior=QTreeView.SelectRows,
            animated=True,
            headerHidden=True)
        self.scoreLabel = QLabel()
        self.scoreView = widgets.treewidget.TreeWidget(
            selectionMode=QTreeView.ExtendedSelection,
            selectionBehavior=QTreeView.SelectRows,
            headerHidden=True,
            animated=True,
            dragDropMode=QTreeView.InternalMove)
        self.addButton = QPushButton(icon = icons.get("list-add"))
        self.removeButton = QPushButton(icon = icons.get("list-remove"))
        self.upButton = QToolButton(icon = icons.get("go-up"))
        self.downButton = QToolButton(icon = icons.get("go-down"))
        self.partSettings = QStackedWidget()
        
        w = QWidget()
        self.addWidget(w)
        layout = QVBoxLayout(spacing=0)
        w.setLayout(layout)
        
        layout.addWidget(self.typesLabel)
        layout.addWidget(self.typesView)
        layout.addWidget(self.addButton)
        
        w = QWidget()
        self.addWidget(w)
        layout = QVBoxLayout(spacing=0)
        w.setLayout(layout)
        
        layout.addWidget(self.scoreLabel)
        layout.addWidget(self.scoreView)
        
        box = QHBoxLayout(spacing=0)
        layout.addLayout(box)
        
        box.addWidget(self.removeButton)
        box.addWidget(self.upButton)
        box.addWidget(self.downButton)
        
        self.addWidget(self.partSettings)

        self.typesView.setModel(parts.model())
        app.translateUI(self)
        
        # signal connections
        self.addButton.clicked.connect(self.slotAddButtonClicked)
        self.removeButton.clicked.connect(self.slotRemoveButtonClicked)
        self.typesView.doubleClicked.connect(self.slotDoubleClicked)
        self.scoreView.currentItemChanged.connect(self.slotCurrentItemChanged)
        self.upButton.clicked.connect(self.scoreView.moveSelectedChildrenUp)
        self.downButton.clicked.connect(self.scoreView.moveSelectedChildrenDown)
Example #8
0
class Articulations(tool.Tool):
    """Articulations tool in the quick insert panel toolbox.

    """
    def __init__(self, panel):
        super(Articulations, self).__init__(panel)
        self.shorthands = QCheckBox(self)
        self.shorthands.setChecked(True)
        self.removemenu = QToolButton(self,
            autoRaise=True,
            popupMode=QToolButton.InstantPopup,
            icon=icons.get('edit-clear'))

        mainwindow = panel.parent().mainwindow()
        mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled)
        self.removemenu.setEnabled(mainwindow.hasSelection())

        ac = documentactions.DocumentActions.instance(mainwindow).actionCollection
        self.removemenu.addAction(ac.tools_quick_remove_articulations)
        self.removemenu.addAction(ac.tools_quick_remove_ornaments)
        self.removemenu.addAction(ac.tools_quick_remove_instrument_scripts)

        layout = QHBoxLayout()
        layout.addWidget(self.shorthands)
        layout.addWidget(self.removemenu)
        layout.addStretch(1)

        self.layout().addLayout(layout)
        for cls in (
                ArticulationsGroup,
                OrnamentsGroup,
                SignsGroup,
                OtherGroup,
            ):
            self.layout().addWidget(cls(self))
        self.layout().addStretch(1)
        app.translateUI(self)

    def translateUI(self):
        self.shorthands.setText(_("Allow shorthands"))
        self.shorthands.setToolTip(_(
            "Use short notation for some articulations like staccato."))
        self.removemenu.setToolTip(_(
            "Remove articulations etc."))

    def icon(self):
        """Should return an icon for our tab."""
        return symbols.icon("articulation_prall")

    def title(self):
        """Should return a title for our tab."""
        return _("Articulations")

    def tooltip(self):
        """Returns a tooltip"""
        return _("Different kinds of articulations and other signs.")
Example #9
0
    def __init__(self, colorOrParent, *args):
        if isinstance(colorOrParent, QColor):
            QToolButton.__init__(self, *args)
            self.setColor(colorOrParent)
        else:
            QToolButton.__init__(self, colorOrParent, *args)
            self.setColor(QColor())

        self.clicked.connect(self._onClicked)
        self.setIconSize(QSize(16, 16))
Example #10
0
    def __initUI__(self):  # ==================================================

        # ---- Toolbar ----

        toolbar_widget = QWidget()

        btn_apply = QPushButton('Apply')
        btn_apply.clicked.connect(self.btn_apply_isClicked)
        btn_cancel = QPushButton('Cancel')
        btn_cancel.clicked.connect(self.close)
        btn_OK = QPushButton('OK')
        btn_OK.clicked.connect(self.btn_OK_isClicked)
        btn_reset = QPushButton('Reset Defaults')
        btn_reset.clicked.connect(self.reset_defaults)

        toolbar_layout = QGridLayout()
        toolbar_layout.addWidget(btn_reset, 1, 0, 1, 3)
        toolbar_layout.addWidget(btn_OK, 2, 0)
        toolbar_layout.addWidget(btn_cancel, 2, 1)
        toolbar_layout.addWidget(btn_apply, 2, 2)

        toolbar_layout.setColumnStretch(3, 100)
        toolbar_layout.setRowStretch(0, 100)

        toolbar_widget.setLayout(toolbar_layout)

        # ---- Color Grid ----

        colorsDB = ColorsReader()
        colorsDB.load_colors_db()

        colorGrid_widget = QWidget()

        self.colorGrid_layout = QGridLayout()
        for i, key in enumerate(colorsDB.keys()):
            self.colorGrid_layout.addWidget(
                QLabel('%s :' % colorsDB.labels[key]), i, 0)

            btn = QToolButton()
            btn.setAutoRaise(True)
            btn.setFocusPolicy(Qt.NoFocus)
            btn.clicked.connect(self.pick_color)

            self.colorGrid_layout.addWidget(btn, i, 3)
        self.load_colors()
        self.colorGrid_layout.setColumnStretch(2, 100)

        colorGrid_widget.setLayout(self.colorGrid_layout)

        # ---- Main Layout ----

        main_layout = QGridLayout()
        main_layout.addWidget(colorGrid_widget, 0, 0)
        main_layout.addWidget(toolbar_widget, 1, 0)
        self.setLayout(main_layout)
Example #11
0
    def __init__(self, dockwidget):
        super(SvgView, self).__init__(dockwidget)

        self._document = None
        self._setting_zoom = False

        self.view = view.View(self)

        self.pageLabel = QLabel()
        self.pageCombo = QComboBox(sizeAdjustPolicy=QComboBox.AdjustToContents)

        layout = QVBoxLayout(spacing=0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        hbox = QHBoxLayout(spacing=0)
        hbox.addWidget(self.pageLabel)
        hbox.addWidget(self.pageCombo)

        self.zoomInButton = QToolButton(autoRaise=True)
        self.zoomOutButton = QToolButton(autoRaise=True)
        self.zoomOriginalButton = QToolButton(autoRaise=True)
        self.zoomNumber = QSpinBox(minimum=10, maximum=1000, suffix="%")
        ac = dockwidget.actionCollection
        self.zoomInButton.setDefaultAction(ac.svg_zoom_in)
        self.zoomOutButton.setDefaultAction(ac.svg_zoom_out)
        self.zoomOriginalButton.setDefaultAction(ac.svg_zoom_original)
        hbox.addWidget(self.zoomInButton)
        hbox.addWidget(self.zoomNumber)
        hbox.addWidget(self.zoomOutButton)
        hbox.addWidget(self.zoomOriginalButton)

        self.resetButton = QPushButton("reload", self)
        self.resetButton.clicked.connect(self.reLoadDoc)
        hbox.addWidget(self.resetButton)

        self.saveButton = QPushButton("save edits", self)
        self.saveButton.clicked.connect(self.callSave)
        hbox.addWidget(self.saveButton)

        hbox.addStretch(1)
        layout.addLayout(hbox)
        layout.addWidget(self.view)

        app.jobFinished.connect(self.initSvg)
        app.documentClosed.connect(self.slotDocumentClosed)
        app.documentLoaded.connect(self.initSvg)
        self.pageCombo.currentIndexChanged.connect(self.changePage)
        self.zoomNumber.valueChanged.connect(self.slotZoomNumberChanged)
        self.view.zoomFactorChanged.connect(self.slotViewZoomChanged)
        dockwidget.mainwindow().currentDocumentChanged.connect(self.initSvg)
        self.zoomNumber.setValue(100)
        doc = dockwidget.mainwindow().currentDocument()
        if doc:
            self.initSvg(doc)
        app.translateUI(self)
Example #12
0
    def buildWidget(self):
        layout = QHBoxLayout(self)
        layout.setContentsMargins(0,0,0,0)
        SettingMenu = QMenu()
        exitButton = QAction(QIcon('exit24.png'), 'Set As High', self)
        exitButton.triggered.connect(self.setHigh)
        SettingMenu.addAction(exitButton)
        setlowButton = QAction(QIcon('exit24.png'), 'Set As Low', self)
        setlowButton.triggered.connect(self.setLow)
        SettingMenu.addAction(setlowButton)

        self.tb_down = QToolButton()
        self.tb_down.pressed.connect(self.on_click_down)
        self.tb_down.released.connect(self.on_released)
        self.tb_down.setArrowType(Qt.LeftArrow)

        self.tb_up = QToolButton()
        self.tb_up.pressed.connect(self.on_click_up)
        self.tb_up.released.connect(self.on_released)
        self.tb_up.setArrowType(Qt.RightArrow)

        if self.showToggleButton:
            tb_set = QToolButton()
            tb_set.clicked.connect(self.on_click_set_value)
            tb_set.setText('<>')
            if self.showSettingMenu:
                tb_set.setMenu(SettingMenu)
                tb_set.setPopupMode(QToolButton.DelayedPopup)

        layout.addWidget(self.tb_down)
        layout.addWidget(self.bar)
        layout.addWidget(self.tb_up)
        if self.showToggleButton:
            layout.addWidget(tb_set)
        layout.setSpacing(0)
Example #13
0
 def paintEvent(self, event):
     QToolButton.paintEvent(self, event)
     painter = QPainter(self)
     opt = QStyleOption()
     opt.initFrom(self)
     opt.rect = QRect(6, self.rect().center().y() - 3, 8, 8)
     opt.rect.translate(0, -3)
     style = self.style()
     style.drawPrimitive(QStyle.PE_IndicatorArrowUp, opt, painter, self)
     opt.rect.translate(0, 6)
     style.drawPrimitive(QStyle.PE_IndicatorArrowDown, opt, painter, self)
Example #14
0
 def __init__(self):
     super().__init__()
     self.player = QMediaPlayer()
     self.layout = QHBoxLayout()
     self.playButton = QToolButton(self)
     self.prevButton = QToolButton(self)
     self.nextButton = QToolButton(self)
     self.volumeButton = QToolButton(self)
     self.timeSlider = TimeSlider(Qt.Horizontal)
     self._init_ui()
     self._connect_widgets()
Example #15
0
    def __init__(self, parent):
        QToolButton.__init__(self, parent)
        self.setText(self.tr("Tabs"))
        self.setEnabled(False)

        self.setToolTip(self.tr("Indentation mode. Click to change"))

        self.clicked.connect(self._onClicked)
        core.workspace().currentDocumentChanged.connect(self._onCurrentDocumentChanged)
        core.workspace().indentUseTabsChanged.connect(self._onIndentSettingsChanged)
        core.workspace().indentWidthChanged.connect(self._onIndentSettingsChanged)
Example #16
0
 def __init__(self, replace, vm, parent=None):
     """
     Constructor
     
     @param replace flag indicating a replace widget is called
     @param vm reference to the viewmanager object
     @param parent parent widget of this widget (QWidget)
     """
     super(SearchReplaceSlidingWidget, self).__init__(parent)
     
     self.__searchReplaceWidget = \
         SearchReplaceWidget(replace, vm, self, True)
     srHeight = self.__searchReplaceWidget.height()
     
     self.__layout = QHBoxLayout(self)
     self.setLayout(self.__layout)
     self.__layout.setContentsMargins(0, 0, 0, 0)
     self.__layout.setAlignment(Qt.AlignTop)
     
     self.__leftButton = QToolButton(self)
     self.__leftButton.setArrowType(Qt.LeftArrow)
     self.__leftButton.setSizePolicy(
         QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
     self.__leftButton.setAutoRepeat(True)
     
     self.__scroller = QScrollArea(self)
     self.__scroller.setWidget(self.__searchReplaceWidget)
     self.__scroller.setSizePolicy(
         QSizePolicy.Expanding, QSizePolicy.Minimum)
     self.__scroller.setMaximumHeight(srHeight)
     self.__scroller.setFrameShape(QFrame.NoFrame)
     self.__scroller.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.__scroller.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
     self.__scroller.setWidgetResizable(False)
     
     self.__rightButton = QToolButton(self)
     self.__rightButton.setArrowType(Qt.RightArrow)
     self.__rightButton.setSizePolicy(
         QSizePolicy.Minimum, QSizePolicy.MinimumExpanding)
     self.__rightButton.setAutoRepeat(True)
     
     self.__layout.addWidget(self.__leftButton)
     self.__layout.addWidget(self.__scroller)
     self.__layout.addWidget(self.__rightButton)
     
     self.setMaximumHeight(srHeight)
     
     self.__searchReplaceWidget.searchListChanged.connect(
         self.searchListChanged)
     self.__leftButton.clicked.connect(self.__slideLeft)
     self.__rightButton.clicked.connect(self.__slideRight)
Example #17
0
    def __init__(self, parent):
        QToolButton.__init__(self)
        self.parent = parent
        self.setAutoRaise(True)
        self.mode_normal()

        self.menu = menu = QMenu(self)
        self.setMenu(menu)
        for mode, titre in self.modes:
            nom = 'mode_' + mode
            action = menu.addAction(QIcon(png(nom)), titre)
            action.setIconVisibleInMenu(True)
            action.triggered.connect(getattr(self, nom))
        self.clicked.connect(self.mode_occupe)
Example #18
0
    def __init__(self, parent=None):
        super(WindowTools, self).__init__(parent)
        self.setFixedHeight(25)

        self.CloseWindow = QToolButton(self)
        self.MinWindow = QToolButton(self)
        self.CloseWindow.setFixedSize(12, 12)
        self.MinWindow.setFixedSize(12, 12)

        self.layout_top = QHBoxLayout(self)
        self.layout_top.addStretch()
        self.layout_top.addWidget(self.MinWindow)
        self.layout_top.addWidget(self.CloseWindow)
        self.setLayout(self.layout_top)
Example #19
0
    def __init__(self, parent, sigma):
        QDialog.__init__(self, parent, Qt.FramelessWindowHint)
        
        # init
        # ------------------------------------------------
        self.oldSigma = sigma
        self.sigma = sigma
        self.brushSize = 0
        self.setStyleSheet("background-color:window;")
        # widgets and layouts
        # ------------------------------------------------
        
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        
        labelsLayout =  QHBoxLayout()
        self.labelSigma = QLabel("Sigma: xx")
        self.labelBrushSize = QLabel("BrushSize: xx")
        labelsLayout.addWidget(self.labelSigma)
        labelsLayout.addWidget(self.labelBrushSize)
        self.layout.addLayout(labelsLayout)
        
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(1)
        self.slider.setMaximum(100)
        self.slider.sliderMoved.connect(self.on_sliderMoved)
        self.layout.addWidget(self.slider)
        
        self.buttonsLayout = QHBoxLayout()
        self.cancel = QToolButton()
        self.cancel.setText("cancel")
        self.cancel.clicked.connect(self.on_cancelClicked)
        self.buttonsLayout.addWidget(self.cancel)
        
        
        self.ok = QToolButton()
        self.ok.setText("OK")
        self.ok.clicked.connect(self.on_okClicked)
        self.buttonsLayout.addWidget(self.ok)

        self.layout.addLayout(self.buttonsLayout)
        
        self.layout.setContentsMargins(10, 0, 10, 0)
        labelsLayout.setContentsMargins(0, 0, 0, 0)
        self.buttonsLayout.setContentsMargins(0, 0, 0, 0)
        
        self.setlabelSigma()
        self.setLabelBrushSize()
        self.setSliderPosition()
    def __init__(self, parent=None):
        super(PlayerControls, self).__init__(parent)

        self.playerState = QMediaPlayer.StoppedState
        self.playerMuted = False
        self.playerMuted = False

        self.playButton = QToolButton(clicked=self.playClicked)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

        self.stopButton = QToolButton(clicked=self.stop)
        self.stopButton.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        self.stopButton.setEnabled(False)

        self.nextButton = QToolButton(clicked=self.next)
        self.nextButton.setIcon(
                self.style().standardIcon(QStyle.SP_MediaSkipForward))

        self.previousButton = QToolButton(clicked=self.previous)
        self.previousButton.setIcon(
                self.style().standardIcon(QStyle.SP_MediaSkipBackward))

        self.muteButton = QToolButton(clicked=self.muteClicked)
        self.muteButton.setIcon(
                self.style().standardIcon(QStyle.SP_MediaVolume))

        self.volumeSlider = QSlider(Qt.Horizontal,
                sliderMoved=self.changeVolume)
        self.volumeSlider.setRange(0, 100)

        self.rateBox = QComboBox(activated=self.updateRate)
        self.rateBox.addItem("0.5x", 0.5)
        self.rateBox.addItem("1.0x", 1.0)
        self.rateBox.addItem("2.0x", 2.0)
        self.rateBox.setCurrentIndex(1)

        layout = QHBoxLayout()
        #layout.sizeConstraint = QLayout.SetMinimumSize #<<<<<<<<<<<<
        layout.setContentsMargins(0, 0, -10, 0)
        layout.addWidget(self.stopButton)
        layout.addWidget(self.previousButton)
        layout.addWidget(self.playButton)
        layout.addWidget(self.nextButton)
        layout.addWidget(self.muteButton)
        layout.addWidget(self.volumeSlider)
        layout.addWidget(self.rateBox)


        self.setLayout(layout)
Example #21
0
 def __init__(self, tool):
     super(Widget, self).__init__(tool)
     
     layout = QVBoxLayout(spacing=1)
     self.setLayout(layout)
     
     # manual mode UI elements that need special treatment
     self.CBverbose = QCheckBox(clicked=self.optionsChanged)
     self.CBpointandclick = QCheckBox(clicked=self.optionsChanged)
     self.CBcustomfile = QCheckBox(clicked=self.optionsChanged)
     self.LEcustomfile = QLineEdit(enabled=False)
     
     # run Lily button
     self.engraveButton = QToolButton()
     self.engraveButton.setDefaultAction(
         engrave.engraver(tool.mainwindow()).actionCollection.engrave_debug)
     
     # help button
     self.helpButton = QToolButton(clicked=self.helpButtonClicked)
     self.helpButton.setIcon(icons.get('help-contents'))
     
     # add manual widgets
     hbox = QHBoxLayout()
     hbox.setContentsMargins(0, 0, 0, 0)
     hbox.addWidget(self.engraveButton)
     hbox.addWidget(self.helpButton)
     hbox.addStretch(1)
     layout.addLayout(hbox)
     layout.addWidget(self.CBverbose)
     layout.addWidget(self.CBpointandclick)
     
     # automatically processed modes
     self.checkboxes = {}
     for mode in layoutcontrol.modelist():
         self.checkboxes[mode] = cb = QCheckBox(clicked=self.optionsChanged)
         layout.addWidget(cb)
     
     # add manual widgets
     layout.addWidget(self.CBcustomfile)
     layout.addWidget(self.LEcustomfile)
     layout.addStretch(1)
     
     # connect manual widgets
     self.CBcustomfile.toggled.connect(self.LEcustomfile.setEnabled)
     self.LEcustomfile.textEdited.connect(self.optionsChanged)
     
     app.translateUI(self)
     self.loadSettings()
     tool.mainwindow().aboutToClose.connect(self.saveSettings)
Example #22
0
    def __init__(self, parent):
        QToolButton.__init__(self, parent)
        self.setEnabled(False)
        self.setToolTip(self.tr("Line endings. Click for convert"))
        self.setIconSize(QSize(16, 16))
        self.setIcon(QIcon(':/enkiicons/unixEol.png'))
        self.setPopupMode(QToolButton.InstantPopup)

        menu = QMenu(self)  # menu filled on popup. Performance optimisation for quicker start up
        self.setMenu(menu)
        menu.aboutToShow.connect(self._onMenuAboutToShow)
        menu.triggered.connect(self._onEolActionTriggered)

        core.workspace().currentDocumentChanged.connect(self._onCurrentDocumentChanged)
        core.workspace().eolChanged.connect(self._setEolMode)
Example #23
0
    def __evt_category_view(self):
        """
        view by 
        """
        btn = QToolButton()
        btn.setIcon(QIcon(getPath("iconDir", "yeahdoc/view.png")))

        menu = QMenu(btn)
        menu.addAction(QAction("ListMode", self, \
                               triggered=lambda: self.yeahdoccategorylist.setViewMode(QListView.ListMode)))
        menu.addAction(QAction("IconMode", self, \
                               triggered=lambda: self.yeahdoccategorylist.setViewMode(QListView.IconMode)))

        btn.setMenu(menu)

        return btn
Example #24
0
    def __init__(self, window, seq_id, current_sequence_name=None):
        """Creates and handles widgets for a file selection."""
        super().__init__()
        from PyQt5.QtWidgets import QToolButton

        self.window = window
        self.seq_id = seq_id

        if not current_sequence_name and len(self.window.sequences) >= seq_id:
            sequence = self.window.sequences[seq_id - 1]
            if sequence:
                current_sequence_name = self.window.sequences[seq_id - 1].name

        self.current_sequence_indicator = QLabel(window)
        self.current_sequence_indicator.setText(
            current_sequence_name or 'Not selected'
        )
        self.select_btn = QPushButton('Select sequence %s' % seq_id)
        self.select_btn.clicked.connect(self.callback_file)

        self.more_btn = QToolButton()
        self.more_btn.setArrowType(Qt.DownArrow)
        self.more_btn.clicked.connect(self.callback_more)

        self.btn_box = QHBoxLayout()
        self.btn_box.setContentsMargins(0, 0, 0, 0)
        self.btn_box.setSpacing(0)
        self.btn_box.addWidget(self.select_btn)
        self.btn_box.addWidget(self.more_btn)

        self.addWidget(self.current_sequence_indicator)
        self.addLayout(self.btn_box)
Example #25
0
 def __init__(self, parent: QWidget = None):
     # Constructs a frame widget with frame style NoFrame and a 1-pixel frame width.
     super(CollapsibleFrame, self).__init__(parent)
     # possible values are:
     #   QFrame.NoFrame, QFrame.Box, QFrame.Panel, QFrame.StyledPanel,
     #   QFrame.HLine, QFrame.VLine, QFrame.WinPanel
     self.setFrameShape(QFrame.StyledPanel)
     # possible values are:  QFrame.Plain, QFrame.Raised, QFrame.Sunken
     self.setFrameShadow(QFrame.Plain)
     # layout
     self._layout = QVBoxLayout()
     self._layout.setContentsMargins(0, 0, 0, 0)
     self._layout.setSpacing(0)
     self.setLayout(self._layout)
     # button
     self._button = QToolButton(self)
     self._button.setArrowType(Qt.RightArrow)
     self._button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
     self._button.setAutoRaise(False)
     self._button.setText('CollapsibleFrame')
     self._button.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
     self._layout.addWidget(self._button, 0)
     self._button.setVisible(True)
     # group box
     self._panel = QWidget(self)
     self._layout.addWidget(self._panel)
     self._panel.setVisible(False)
     self._panel_layout = QVBoxLayout()
     self._panel_layout.setContentsMargins(1, 1, 1, 1)
     self._panel_layout.setSpacing(2)
     self._panel.setLayout(self._panel_layout)
     # connect signals
     self._button.clicked.connect(self.on_button_click)
     # private state variables
     self._is_collapsed = True
Example #26
0
    def __init__(self, panel):
        super(Articulations, self).__init__(panel)
        self.shorthands = QCheckBox(self)
        self.shorthands.setChecked(True)
        self.removemenu = QToolButton(
            self, autoRaise=True, popupMode=QToolButton.InstantPopup, icon=icons.get("edit-clear")
        )

        mainwindow = panel.parent().mainwindow()
        mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled)
        self.removemenu.setEnabled(mainwindow.hasSelection())

        ac = documentactions.DocumentActions.instance(mainwindow).actionCollection
        self.removemenu.addAction(ac.tools_quick_remove_articulations)
        self.removemenu.addAction(ac.tools_quick_remove_ornaments)
        self.removemenu.addAction(ac.tools_quick_remove_instrument_scripts)

        layout = QHBoxLayout()
        layout.addWidget(self.shorthands)
        layout.addWidget(self.removemenu)
        layout.addStretch(1)

        self.layout().addLayout(layout)
        for cls in (ArticulationsGroup, OrnamentsGroup, SignsGroup, OtherGroup):
            self.layout().addWidget(cls(self))
        self.layout().addStretch(1)
        app.translateUI(self)
Example #27
0
    def __init__(self, panel):
        super(Spanners, self).__init__(panel)
        self.removemenu = QToolButton(self,
            autoRaise=True,
            popupMode=QToolButton.InstantPopup,
            icon=icons.get('edit-clear'))

        mainwindow = panel.parent().mainwindow()
        mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled)
        self.removemenu.setEnabled(mainwindow.hasSelection())

        ac = documentactions.DocumentActions.instance(mainwindow).actionCollection
        self.removemenu.addAction(ac.tools_quick_remove_slurs)
        self.removemenu.addAction(ac.tools_quick_remove_beams)
        self.removemenu.addAction(ac.tools_quick_remove_ligatures)

        layout = QHBoxLayout()
        layout.addWidget(self.removemenu)
        layout.addStretch(1)

        self.layout().addLayout(layout)
        self.layout().addWidget(ArpeggioGroup(self))
        self.layout().addWidget(GlissandoGroup(self))
        self.layout().addWidget(SpannerGroup(self))
        self.layout().addWidget(GraceGroup(self))
        self.layout().addStretch(1)
Example #28
0
 def setup_ui(self):
     self.setObjectName('searchBox')
     self.searchButton = QToolButton(clicked = self.search_musics)
     self.searchButton.setFocusPolicy(Qt.NoFocus)
     self.searchButton.setIconSize(QSize(21, 21))
     self.searchButton.setIcon(QIcon(IconsHub.Search))
     self.searchButton.setCursor(Qt.ArrowCursor)
     self.searchCombo = QComboBox()
     self.searchCombo.setObjectName('searchCombo')
     musicIcon = QIcon(IconsHub.SearchMusictitle)
     artistIcon = QIcon(IconsHub.SearchArtist)
     albumIcon = QIcon(IconsHub.SearchAlbum)       
     self.searchCombo.setIconSize(QSize(20, 20))
     self.searchCombo.insertItem(0, musicIcon, "歌曲")
     self.searchCombo.insertItem(1, artistIcon, "歌手")
     self.searchCombo.insertItem(2, albumIcon, "专辑")
     self.searchCombo.setFixedSize(90, 26)
     self.searchCombo.setCursor(Qt.ArrowCursor)
     self.searchCombo.setCurrentIndex(0)
     searchLayout = QHBoxLayout(self)
     searchLayout.addWidget(self.searchCombo)
     searchLayout.addStretch()
     searchLayout.addWidget(self.searchButton)
     searchLayout.setSpacing(0)
     searchLayout.setContentsMargins(0, 0, 2, 0)
     self.setTextMargins(95, 0, 25, 0)  
Example #29
0
    def __init__(self, parent):
        QToolButton.__init__(self, parent)
        self.setToolTip(self.tr("Cursor position"))
        self.setEnabled(False)
        self._setCursorPosition(-1, -1)
        minWidth = QFontMetrics(self.font()).width("Line: xxxxx Column: xxx")
        minWidth += 30  # for the button borders
        self.setMinimumWidth(minWidth)  # Avoid flickering when text width changed
        core.workspace().currentDocumentChanged.connect(self._onCurrentDocumentChanged)

        core.workspace().cursorPositionChanged.connect(self._onCursorPositionChanged)

        self._timer = QTimer()
        self._timer.setInterval(200)
        self._timer.setSingleShot(True)
        self._timer.timeout.connect(self._onUpdatePositionTimer)
        self._passedUpdate = False
Example #30
0
 def _createHelpMessage(self):
     if hasattr(self, '_helpWindow'):
         return
     self._helpWindow = QWidget()
     self._helpWindow.setWindowFlags(QtCore.Qt.Window)
     layout = QVBoxLayout()
     self._helpWindow.setLayout(layout)
     self._helpMessageArea = QScrollArea()
     self._helpMessageText = QTextBrowser()
     self._helpMessageText.setOpenExternalLinks(True)
     self._helpMessageArea.setWidget(self._helpMessageText)
     layout.addWidget(self._helpMessageText)
     self._squidGuiPath = os.path.dirname(os.path.abspath(__file__))
     self._helpBaseURL = os.path.join(self._squidGuiPath,'help.html')
     self._helpMessageText.setSource(QtCore.QUrl(self._helpBaseURL))
     self._helpMessageText.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     self._helpMessageArea.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
     self._helpMessageText.setMinimumSize(800, 600)
     self._closeHelpAction = QAction('Close', self)
     self._closeHelpAction.triggered.connect(self._helpWindow.close)        
     # Setting the close event so that the ``Help`` button is
     # unchecked when the help window is closed
     self._helpWindow.closeEvent = lambda event: self._helpAction.setChecked(False)
     self._helpTOCAction = QAction('Help running demo', self)
     self._helpTOCAction.triggered.connect( self._jumpToHelpTOC)                
     # This panel is for putting two buttons using horizontal
     # layout
     panel = QFrame()
     panel.setFrameStyle(QFrame.StyledPanel + QFrame.Raised)
     layout.addWidget(panel)
     layout = QHBoxLayout()
     panel.setLayout(layout)
     self._helpAction = QAction('Help running', self)
     self._helpAction.triggered.connect(self._showRunningHelp)
     self._helpBiophysicsAction = QAction('Help biophysics', self)
     self._helpBiophysicsAction.triggered.connect(self._showBioPhysicsHelp)
     self._helpTOCButton = QToolButton()
     self._helpTOCButton.setDefaultAction(self._helpTOCAction)
     self._helpBiophysicsButton = QToolButton()
     self._helpBiophysicsButton.setDefaultAction(self._helpBiophysicsAction)
     layout.addWidget(self._helpTOCButton)
     layout.addWidget(self._helpBiophysicsButton)
     self._closeHelpButton = QToolButton()
     self._closeHelpButton.setDefaultAction(self._closeHelpAction)
     layout.addWidget(self._closeHelpButton)
Example #31
0
    def __init__(self, parent=None):
        super().__init__(parent)
        self.user_info = []
        self.sutda = Sutda()

        self.log = ""
        self.information = {}
        self.get_paeButton = QToolButton()
        self.get_paeButton.setText("패 받기")
        self.get_paeButton.clicked.connect(self.Get_card)
        self.get_paeButton.setFixedSize(105, 50)
        self.get_paeButton.setEnabled(False)

        left_Layout = QGridLayout()
        left_Layout.addWidget(self.get_paeButton, 2, 0)
        cpuDeck = QGridLayout()
        self.computer_pae1 = QLabel(self)
        self.computer_pae2 = QLabel(self)
        self.default = QPixmap('IMG/back.png')
        self.computer_pae1.setPixmap(self.default)
        self.computer_pae2.setPixmap(self.default)
        cpuDeck.addWidget(self.computer_pae1, 0, 0)
        cpuDeck.addWidget(self.computer_pae2, 0, 1)
        left_Layout.addLayout(cpuDeck, 1, 0)

        cpu = QGridLayout()
        self.cpuLabel = QLabel("CPU")
        font = self.cpuLabel.font()
        font.setPointSize(font.pointSize() + 8)
        font.setBold(True)
        font.setFamily('Courier New')
        self.cpuLabel.setAlignment(Qt.AlignTop)
        self.cpuLabel.setFont(font)
        self.cpuResult = QLineEdit()
        self.cpuResult.setReadOnly(True)
        self.cpuResult.setFixedWidth(100)
        self.cpuResult.setAlignment(Qt.AlignCenter)
        cpu.addWidget(self.cpuLabel, 0, 0)
        cpu.addWidget(self.cpuResult, 1, 0)
        left_Layout.addLayout(cpu, 1, 2)

        userDeck = QGridLayout()
        self.user_pae1 = QLabel(self)
        self.user_pae2 = QLabel(self)
        self.user_pae1.setPixmap(self.default)
        self.user_pae2.setPixmap(self.default)
        userDeck.addWidget(self.user_pae1, 0, 0)
        userDeck.addWidget(self.user_pae2, 0, 1)
        left_Layout.addLayout(userDeck, 3, 0)

        user = QGridLayout()
        self.userLabel = QLabel("Player")
        font = self.userLabel.font()
        font.setPointSize(font.pointSize() + 8)
        font.setBold(True)
        font.setFamily('Courier New')
        self.userLabel.setAlignment(Qt.AlignTop)
        self.userLabel.setFont(font)
        self.userResult = QLineEdit()
        self.userResult.setReadOnly(True)
        self.userResult.setFixedWidth(100)
        self.userResult.setAlignment(Qt.AlignCenter)
        user.addWidget(self.userLabel, 0, 0)
        user.addWidget(self.userResult, 1, 0)
        left_Layout.addLayout(user, 3, 2)

        # left_money
        self.lbLefted = QLabel("보유 금액 :")
        self.lbLefted.setAlignment(Qt.AlignRight)
        self.left_money = QLineEdit()
        self.left_money.setReadOnly(True)
        self.left_money.setAlignment(Qt.AlignRight)
        self.lefted_money = 1000000
        self.left_money.setText(str(self.lefted_money))
        self.left_money.setFixedWidth(105)

        self.name_edit = QLineEdit()

        self.name_edit.setAlignment(Qt.AlignRight)

        left_Layout.addWidget(self.left_money, 0, 2)
        left_Layout.addWidget(self.lbLefted, 0, 0)

        betLayout = QGridLayout()
        self.btn_Betting = QToolButton()
        self.btn_Betting.setText("BETTING")
        self.btn_Betting.setEnabled(False)

        # self.start_btn.clicked.connect()

        self.btn_Die = QToolButton()
        self.btn_Die.setText("DIE")
        self.btn_Die.setEnabled(False)

        # self.btn_Die.clicked.connect()
        betLayout.addWidget(self.btn_Betting, 0, 0)
        betLayout.addWidget(self.btn_Die, 1, 0)
        left_Layout.addLayout(betLayout, 2, 2)

        self.btn_Save = QToolButton()
        self.btn_Save.setText("SAVE")
        self.btn_Save.clicked.connect(self.save)

        self.btn_Login = QToolButton()
        self.btn_Login.setText("Login")
        self.btn_Login.clicked.connect(self.start_game)

        self.btn_Ranking = QToolButton()
        self.btn_Ranking.setText("Rank")
        self.btn_Ranking.clicked.connect(self.ranking)

        self.logBox = QTextEdit()
        self.logBox.setReadOnly(True)
        self.lblog = QLabel("--log--")
        self.lblog.setAlignment(Qt.AlignCenter)

        right_layout = QGridLayout()

        right_layout.addWidget(self.name_edit, 0, 0)
        right_layout.addWidget(self.btn_Save, 0, 2)
        right_layout.addWidget(self.btn_Login, 0, 1)
        right_layout.addWidget(self.btn_Ranking, 0, 3)
        right_layout.addWidget(self.lblog, 1, 0, 1, 4)
        right_layout.addWidget(self.logBox, 2, 0, 3, 4)

        self.rank_Edit = QTextEdit()
        self.rank_Edit.setReadOnly(True)
        self.rank_Rabel = QLabel("--Rank--")
        self.rank_Rabel.setAlignment(Qt.AlignCenter)
        self.rank_Edit.setText(self.ranking())

        rank_layout = QGridLayout()
        rank_layout.addWidget(self.rank_Edit, 1, 0)
        rank_layout.addWidget(self.rank_Rabel, 0, 0)
        self.ranking()
        # Layout placement
        mainLayout = QGridLayout()
        self.setWindowTitle("Sutda")
        # mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        mainLayout.addLayout(left_Layout, 0, 0)
        mainLayout.addLayout(right_layout, 0, 1)
        mainLayout.addLayout(rank_layout, 0, 2)
        self.setLayout(mainLayout)
        self.btn_Die.clicked.connect(self.dieClicked)
        self.btn_Betting.clicked.connect(self.bettingClicked)
        self.ranking()
class HangmanGame(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)

        # Initialize word database        
        self.word = Word('words.txt')

        # Hangman display window
        self.hangmanWindow = QTextEdit()
        self.hangmanWindow.setReadOnly(True)
        self.hangmanWindow.setAlignment(Qt.AlignLeft)
        font = self.hangmanWindow.font()
        font.setFamily('Courier New')
        self.hangmanWindow.setFont(font)

        # Layout
        hangmanLayout = QGridLayout()
        hangmanLayout.addWidget(self.hangmanWindow, 0, 0)

        # Status Layout creation
        statusLayout = QGridLayout()

        # Display widget for current status
        self.currentWord = QLineEdit()
        self.currentWord.setReadOnly(True)
        self.currentWord.setAlignment(Qt.AlignCenter)
# 가로길이를 300까지 크기를 키워주면 13글자 이상도 들어 갈 수 있다.
        self.currentWord.setFixedWidth(300)
        font = self.currentWord.font()
        font.setPointSize(font.pointSize() + 8)
        self.currentWord.setFont(font)
        statusLayout.addWidget(self.currentWord, 0, 0, 1, 2)

        # Display widget for already used characters
        self.guessedChars = QLineEdit()
        self.guessedChars.setReadOnly(True)
        self.guessedChars.setAlignment(Qt.AlignLeft)
        self.guessedChars.setMaxLength(52)
        statusLayout.addWidget(self.guessedChars, 1, 0, 1, 2)

        # Display widget for message output
        self.message = QLineEdit()
        self.message.setReadOnly(True)
        self.message.setAlignment(Qt.AlignLeft)
        self.message.setMaxLength(52)
        statusLayout.addWidget(self.message, 2, 0, 1, 2)

        # Input widget for user selected characters
        self.charInput = QLineEdit()
        self.charInput.setMaxLength(1)
        statusLayout.addWidget(self.charInput, 3, 0)

        # Button for submitting a character
        self.guessButton = QToolButton()
        self.guessButton.setText('Guess!')
        self.guessButton.clicked.connect(self.guessClicked)
        statusLayout.addWidget(self.guessButton, 3, 1)

        # Button for a new game
        self.newGameButton = QToolButton()
        self.newGameButton.setText('New Game')
        self.newGameButton.clicked.connect(self.startGame)
        statusLayout.addWidget(self.newGameButton, 4, 0)

        # Layout placement
        mainLayout = QGridLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        mainLayout.addLayout(hangmanLayout, 0, 0)
        mainLayout.addLayout(statusLayout, 0, 1)

        self.setLayout(mainLayout)

        self.setWindowTitle('Hangman Game')

        # Start a new game on application launch!
        self.startGame()


    def startGame(self):
        self.hangman = Hangman()
        #randFromDB() 괄호 사이에 숫자 입력하여 랜덤 길이 넣어준다. !!
        word = self.word.randFromDB(15)
        
        self.guess = Guess(self.word.randFromDB())
        self.gameOver = False
        self.hangmanWindow.setPlaceholderText(self.hangman.currentShape())
        self.currentWord.setText(self.guess.displayCurrent())
        self.guessedChars.setText(self.guess.displayGuessed())
        self.message.clear()


    def guessClicked(self):
        guessedChar = self.charInput.text()
        self.charInput.clear()
        self.message.clear()

        if self.gameOver == True:
        # 메시지 출력하고 - message.setText() - 리턴
            self.message.setText("Game Over")
        # return 추가
            return "Finished"

        

        if len(guessedChar) != 1:
        # 입력의 길이가 1 인지를 판단하고, 아닌 경우 메시지 출력, 리턴
            self.charInput.setText("1글자만 입력하세요.")
            return "Finished"

        # 먼저 guessedChar를 소문자로 변형
        guessedChar = guessedChar.lower()
        
        if guessedChar in guess.guessedChars:
            self.message.setText("이미 추측한 글자입니다.")
            return "Finished"
        # 이미 사용한 글자인지를 판단하고, 아닌 경우 메시지 출력, 리턴

        success = self.guess.guess(guessedChar)
        
        if success == False:
            # 남아 있는 목숨을 1 만큼 감소
            hangman.decreaseLife()
            # 메시지 출력
            self.message.setText("not " + '"' + guessedChar + '"' + "in the word")


        # hangmanWindow 에 현재 hangman 상태 그림을 출력
        self.hangmanWindow.setPlaceholderText(self.hangman.currentShape())
        # currentWord 에 현재까지 부분적으로 맞추어진 단어 상태를 출력
        self.currentWord.setText(self.guess.displayCurrent())
        # guessedChars 에 지금까지 이용한 글자들의 집합을 출력        
        self.guessedChars.setText(self.guess.displayGuessed())

        if self.guess.finished():
            # 메시지 ("Success!") 출력하고, self.gameOver 는 True 로            
            self.message.setText("Success!")
            self.gmaeOver == True

        elif self.hangman.getRemainingLives() == 0:
            # 메시지 ("Fail!" + 비밀 단어) 출력하고, self.gameOver 는 True 로
            self.message.setText("Fail!" + guess.secretWord)
            self.gameOver == True
class CollapsibleSection(QFrame):
    def __init__(self, header_text, init_collapsed=False, is_top=False):
        super().__init__()

        if not is_top:
            self.setObjectName("CollapsibleSection")
            self.setStyleSheet(
                "#CollapsibleSection{border-top: 1px solid lightgrey;}")

        self._layout = QVBoxLayout(self)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
        self.setLayout(self._layout)
        self._header_widget = QWidget()
        self.body_widget = QWidget()
        self._layout.addWidget(self._header_widget)
        self._layout.addWidget(self.body_widget)

        self.grid = QGridLayout(self.body_widget)
        self.grid.setContentsMargins(9, 0, 9, 9)
        self.grid.setColumnStretch(0, 1)
        self.grid.setColumnStretch(1, 1)

        self._header_widget_layout = QHBoxLayout(self._header_widget)
        self._header_widget_layout.setContentsMargins(7, 7, 7, 7)
        self._header_widget.setLayout(self._header_widget_layout)

        self._button = QToolButton()
        self._button.setText(header_text)
        self._button.setCheckable(True)
        self._button.setStyleSheet("QToolButton { border: none; }")
        self._button.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
        self._button.pressed.connect(self.button_event)
        self.button_event(override=init_collapsed)
        self._header_widget_layout.addWidget(self._button)
        self._header_widget_layout.addStretch()

    def button_event(self, override=None):
        if override is None:
            checked = not self._button.isChecked()
        else:
            checked = override
            self._button.setChecked(checked)

        if checked:  # collapsed
            self._button.setArrowType(QtCore.Qt.ArrowType.RightArrow)
            self.body_widget.hide()
        else:
            self._button.setArrowType(QtCore.Qt.ArrowType.DownArrow)
            self.body_widget.show()
Example #34
0
class wdgProductHistoricalBuyChart(wdgProductHistoricalChart):
    def __init__(self, parent=None):
        wdgProductHistoricalChart.__init__(self, parent)
        self.labelBuyPrice = QLabel(self.tr("Add wanted price"))
        self.txtBuyPrice = myQLineEdit(self)
        self.cmdBuyPrice = QToolButton(self)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/xulpymoney/tools-wizard.png"), QIcon.Normal,
                       QIcon.Off)
        self.cmdBuyPrice.setIcon(icon)
        self.horizontalLayout_3.addWidget(self.labelBuyPrice)
        self.spacerBuyPrice = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                          QSizePolicy.Minimum)
        self.horizontalLayout_3.addWidget(self.txtBuyPrice)
        self.horizontalLayout_3.addWidget(self.cmdBuyPrice)
        self.horizontalLayout_3.addItem(self.spacerBuyPrice)

        self.cmdBuyPrice.released.connect(self.on_cmdBuyPrice_released)

        self.layAmounts = QHBoxLayout()
        self.label1 = QLabel(self)
        self.label1.setText(self.tr("Amounts to invest separated by ;"))
        self.txtAmounts = QLineEdit(self)
        self.txtAmounts.setText("2500;3500;8400;8400")

        self.labelLastOperationPercentage = QLabel(self)
        self.labelLastOperationPercentage.setText(
            self.tr("Last Operation next buy percentage"))
        self.txtLastOperationPercentage = myQLineEdit(self)
        self.txtLastOperationPercentage.setText(33)

        self.spacer1 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer3 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer4 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer5 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer6 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.layAmounts.addItem(self.spacer1)
        self.layAmounts.addWidget(self.label1)
        self.layAmounts.addWidget(self.txtAmounts)
        self.layAmounts.addItem(self.spacer2)
        self.layAmounts.addWidget(self.labelLastOperationPercentage)
        self.layAmounts.addWidget(self.txtLastOperationPercentage)
        self.layAmounts.addItem(self.spacer6)
        self.verticalLayout.addLayout(self.layAmounts)

        #Add Calculator widget
        self.layOpportunity = QHBoxLayout()
        self.spacerOpportunity = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                             QSizePolicy.Minimum)
        self.cmdOpportunity = QPushButton(self.tr("Add Opportunity"))
        self.cmdOpportunity.released.connect(self.on_cmdOpportunity_released)
        icon1 = QIcon()
        icon1.addPixmap(QPixmap(":/xulpymoney/kcalc.png"), QIcon.Normal,
                        QIcon.Off)
        self.cmdOpportunity.setIcon(icon1)
        self.layOpportunity.addItem(self.spacerOpportunity)
        self.layOpportunity.addWidget(self.cmdOpportunity)

    ## Must be added after setProduct
    def setPrice(self, price):
        self.txtBuyPrice.setText(price)

    def on_cmdBuyPrice_released(self):
        if self.txtBuyPrice.isValid():
            self.generate()
            self.display()

    ## This button allows to open order Opportunity with the first purchase price
    def on_cmdOpportunity_released(self):
        d = QDialog(self)
        d.setModal(True)
        d.setWindowTitle(self.tr("Add new opportunity"))
        w = wdgOpportunitiesAdd(self.mem, None, d)
        w.productSelector.setSelected(self.product)
        w.txtPrice.setText(self.txtBuyPrice.decimal())
        lay = QVBoxLayout(d)
        lay.addWidget(w)
        d.exec_()

    def __qcolor_by_reinvestment_line(self, reinvestment_line):
        if reinvestment_line == ReinvestmentLines.Buy:
            return QColor(85, 170, 127)
        elif reinvestment_line == ReinvestmentLines.Average:
            return QColor(85, 85, 170)
        elif reinvestment_line == ReinvestmentLines.Sell:
            return QColor(170, 85, 85)

    def __qpen_by_amounts_index(self, index, reinvestment_line):
        if index == 0:
            return self._pen(
                Qt.SolidLine,
                self.__qcolor_by_reinvestment_line(reinvestment_line))
        elif index == 1:
            return self._pen(
                Qt.DashLine,
                self.__qcolor_by_reinvestment_line(reinvestment_line))
        elif index == 2:
            return self._pen(
                Qt.DotLine,
                self.__qcolor_by_reinvestment_line(reinvestment_line))
        else:
            return self._pen(
                Qt.DotLine,
                self.__qcolor_by_reinvestment_line(reinvestment_line))

    ## Just draw the chart with selected options. It creates and destroys objects
    def generate(self):
        self.amounts = string2list_of_integers(self.txtAmounts.text(), ";")
        logging.debug(self.amounts)
        wdgProductHistoricalChart.generate(self)

        percentage = Percentage(self.spnGainsPercentage.value(), 100)
        selected_datetime = dtaware_day_start_from_date(
            self.dtFrom.date().toPyDate(), self.mem.localzone_name)

        inv = Investment(self.mem).init__create("Buy Chart", None, None,
                                                self.product, None, True,
                                                False - 1)
        inv.op = InvestmentOperationHomogeneusManager(self.mem, inv)
        p_last_operation = Percentage(
            self.txtLastOperationPercentage.decimal(), 100)

        m_purchase = Money(self.mem, self.txtBuyPrice.decimal(),
                           self.product.currency)
        #index=0 purchase, 1 = first reinvestment
        lastIO = None
        for index, amount in enumerate(self.amounts):
            lastIO = InvestmentOperation(
                self.mem, self.mem.tiposoperaciones.find_by_id(4),
                self.mem.localzone.now(), inv,
                int(self.amounts[index] / m_purchase.amount), 0, 0,
                m_purchase.amount, "", True, 1, -10000)
            inv.op.append(lastIO)
            (inv.op_actual, inv.op_historica
             ) = inv.op.get_current_and_historical_operations()
            new_purchase_price = self.wdgTS.ts.appendTemporalSeries(
                self.tr("Purchase price {}: {}").format(
                    index, m_purchase.string()))
            new_purchase_price.setColor(
                self.__qcolor_by_reinvestment_line(ReinvestmentLines.Buy))
            new_purchase_price.setPen(
                self.__qpen_by_amounts_index(index, ReinvestmentLines.Buy))
            self.wdgTS.ts.appendTemporalSeriesData(new_purchase_price,
                                                   selected_datetime,
                                                   m_purchase.amount)
            self.wdgTS.ts.appendTemporalSeriesData(new_purchase_price,
                                                   self.mem.localzone.now(),
                                                   m_purchase.amount)

            m_new_average_price = inv.op_actual.average_price()
            m_new_selling_price = inv.op_actual.average_price_after_a_gains_percentage(
                percentage)
            new_average_price = self.wdgTS.ts.appendTemporalSeries(
                self.tr("Average price {}: {}".format(index,
                                                      m_new_average_price)))
            new_average_price.setColor(
                self.__qcolor_by_reinvestment_line(ReinvestmentLines.Average))
            new_average_price.setPen(
                self.__qpen_by_amounts_index(index, ReinvestmentLines.Average))
            self.wdgTS.ts.appendTemporalSeriesData(new_average_price,
                                                   selected_datetime,
                                                   m_new_average_price.amount)
            self.wdgTS.ts.appendTemporalSeriesData(new_average_price,
                                                   self.mem.localzone.now(),
                                                   m_new_average_price.amount)

            new_selling_price = self.wdgTS.ts.appendTemporalSeries(
                self.tr("Sell price {} at {} to gain {}".format(
                    index, m_new_selling_price,
                    inv.op_actual.gains_from_percentage(percentage))))
            new_selling_price.setColor(
                self.__qcolor_by_reinvestment_line(ReinvestmentLines.Sell))
            new_selling_price.setPen(
                self.__qpen_by_amounts_index(index, ReinvestmentLines.Sell))
            self.wdgTS.ts.appendTemporalSeriesData(new_selling_price,
                                                   selected_datetime,
                                                   m_new_selling_price.amount)
            self.wdgTS.ts.appendTemporalSeriesData(new_selling_price,
                                                   self.mem.localzone.now(),
                                                   m_new_selling_price.amount)

            m_purchase = Money(self.mem,
                               lastIO.price * (1 - p_last_operation.value),
                               self.product.currency)
Example #35
0
class Main(QMainWindow):
    def __init__(self):
        global downloads_list_file
        QMainWindow.__init__(self)
        self.setWindowIcon(QIcon(":/quartz.png"))
        self.setWindowTitle("Quartz Browser - " + __version__)
        # Window Properties
        self.history = []
        self.downloads = []
        self.confirm_before_quit = True
        # Create required directories
        for folder in [configdir, icon_dir, thumbnails_dir]:
            if not os.path.exists(folder):
                os.mkdir(folder)
        # Import and Apply Settings
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.settings = QSettings(1, 0, "quartz-browser", "Quartz", self)
        self.opensettings()
        self.websettings = QWebSettings.globalSettings()
        self.websettings.setAttribute(QWebSettings.DnsPrefetchEnabled, True)
        self.websettings.setMaximumPagesInCache(10)
        self.websettings.setIconDatabasePath(icon_dir)
        self.websettings.setAttribute(QWebSettings.JavascriptCanOpenWindows,
                                      True)
        self.websettings.setAttribute(QWebSettings.JavascriptCanCloseWindows,
                                      True)
        if webkit.enable_adblock:
            self.websettings.setUserStyleSheetUrl(
                QUrl.fromLocalFile(program_dir + 'userContent.css'))
        # Import Downloads and Bookmarks
        self.dwnldsmodel = DownloadsModel(self.downloads,
                                          QApplication.instance())
        self.dwnldsmodel.deleteDownloadsRequested.connect(self.deleteDownloads)
        imported_downloads = importDownloads(downloads_list_file)
        for [filepath, url, totalsize, timestamp] in imported_downloads:
            try:  # Check if downloads.txt is valid
                tymstamp = float(timestamp)
            except:
                self.downloads = []
                exportDownloads(downloads_list_file, [])
                print("Error in importing Downloads.")
                break
            old_download = Download(networkmanager)
            old_download.loadDownload(filepath, url, totalsize, timestamp)
            old_download.datachanged.connect(self.dwnldsmodel.datachanged)
            self.downloads.append(old_download)
        self.bookmarks = importBookmarks(configdir + "bookmarks.txt")
        self.favourites = importFavourites(configdir + 'favourites.txt')
        # Find and set icon theme name
        for theme_name in ['Adwaita', 'Gnome', 'Tango']:
            if os.path.exists('/usr/share/icons/' + theme_name):
                QIcon.setThemeName(theme_name)
                break
        self.initUI()
        self.resize(1024, 714)

    def initUI(self):
        ###############################  Create  Actions ##############################
        self.loadimagesaction = QAction("Load Images", self)
        self.loadimagesaction.setCheckable(True)
        self.loadimagesaction.triggered.connect(self.loadimages)

        self.javascriptmode = QAction("Enable Javascript", self)
        self.javascriptmode.setCheckable(True)
        self.javascriptmode.triggered.connect(self.setjavascript)

        self.useragent_mode_desktop = QAction("Desktop", self)
        self.useragent_mode_desktop.setCheckable(True)
        self.useragent_mode_desktop.triggered.connect(self.setUserAgentDesktop)

        self.useragent_mode_mobile = QAction("Mobile", self)
        self.useragent_mode_mobile.setCheckable(True)
        self.useragent_mode_mobile.triggered.connect(self.setUserAgentMobile)

        self.useragent_mode_custom = QAction("Custom", self)
        self.useragent_mode_custom.setCheckable(True)
        self.useragent_mode_custom.triggered.connect(self.setUserAgentCustom)

        ################ Add Actions to Menu ####################
        # This sub-menu sets useragent mode to desktop/mobile/custom
        self.useragentMenu = QMenu('UserAgent', self)
        self.useragentMenu.setIcon(QIcon.fromTheme("computer"))
        self.useragentMenu.addAction(self.useragent_mode_desktop)
        self.useragentMenu.addAction(self.useragent_mode_mobile)
        self.useragentMenu.addAction(self.useragent_mode_custom)

        # This is main menu
        self.menu = QMenu(self)
        self.menu.addAction(QIcon.fromTheme("edit-find"), "Find Text",
                            self.findmode, "Ctrl+F")
        self.menu.addAction(QIcon.fromTheme("list-add"), "Zoom In",
                            self.zoomin, "Ctrl++")
        self.menu.addAction(QIcon.fromTheme("list-remove"), "Zoom Out",
                            self.zoomout, "Ctrl+-")
        self.menu.addAction(QIcon.fromTheme("view-fullscreen"),
                            "Toggle Fullscreen", self.fullscreenmode, "F11")
        self.menu.addSeparator()

        self.menu.addAction(self.loadimagesaction)
        self.menu.addAction(self.javascriptmode)
        self.menu.addMenu(self.useragentMenu)
        self.menu.addAction(QIcon.fromTheme("applications-system"), "Settings",
                            self.settingseditor, "Ctrl+,")
        self.menu.addSeparator()

        self.menu.addAction(QIcon.fromTheme("image-x-generic"),
                            "Save as Image", self.saveAsImage, "Shift+Ctrl+S")
        self.menu.addAction(QIcon.fromTheme("text-html"), "Save as HTML",
                            self.saveashtml, "Ctrl+S")
        self.menu.addAction(QIcon.fromTheme("document-print"), "Print to PDF",
                            self.printpage, "Ctrl+P")
        self.menu.addSeparator()
        self.menu.addAction(QIcon.fromTheme("process-stop"), "Quit",
                            self.forceClose, "Ctrl+Q")

        self.bmk_menu = QMenu(self)
        self.bmk_menu.addAction(QIcon(':/add-bookmark.png'), 'Add Bookmark',
                                self.addbookmark)
        self.bmk_menu.addAction(QIcon(':/favourites.png'), 'Add to Home',
                                self.addToFavourites)

        ###############################  Create Gui Parts ##############################
        grid = QGridLayout()
        grid.setSpacing(1)
        grid.setContentsMargins(0, 2, 0, 0)
        self.centralwidget = QWidget(self)
        self.centralwidget.setLayout(grid)
        self.setCentralWidget(self.centralwidget)

        self.addtabBtn = QPushButton(QIcon(":/add-tab.png"), "", self)
        self.addtabBtn.setToolTip("New Tab\n[Ctrl+Tab]")
        self.addtabBtn.setShortcut("Ctrl+Tab")
        self.addtabBtn.clicked.connect(self.addTab)

        self.reload = QPushButton(QIcon(":/refresh.png"), "", self)
        self.reload.setMinimumSize(35, 26)
        self.reload.setToolTip("Reload/Stop\n  [Space]")
        self.reload.setShortcut("Space")
        self.reload.clicked.connect(self.Reload)

        self.back = QPushButton(QIcon(":/prev.png"), "", self)
        self.back.setToolTip("Previous Page\n [Backspace]")
        self.back.setMinimumSize(35, 26)
        self.back.clicked.connect(self.Back)

        self.forw = QPushButton(QIcon(":/next.png"), "", self)
        self.forw.setToolTip("Next Page\n [Shift+Backspace]")
        self.forw.setMinimumSize(35, 26)
        self.forw.clicked.connect(self.Forward)

        self.homeBtn = QPushButton(QIcon(":/home.png"), "", self)
        self.homeBtn.setToolTip("Go Home")
        self.homeBtn.clicked.connect(self.goToHome)

        self.videoDownloadButton = QPushButton(QIcon(":/video-dwnld.png"), "",
                                               self)
        self.videoDownloadButton.setToolTip("Download this Video")
        self.videoDownloadButton.clicked.connect(self.downloadVideo)
        self.videoDownloadButton.hide()

        self.addbookmarkBtn = QToolButton(self)
        self.addbookmarkBtn.setIcon(QIcon(":/add-bookmark.png"))
        self.addbookmarkBtn.setToolTip("Add Bookmark")
        self.addbookmarkBtn.setMenu(self.bmk_menu)
        self.addbookmarkBtn.setPopupMode(QToolButton.InstantPopup)

        self.menuBtn = QToolButton(self)
        self.menuBtn.setIcon(QIcon(":/menu.png"))
        self.menuBtn.setMenu(self.menu)
        self.menuBtn.setPopupMode(QToolButton.InstantPopup)

        self.bookmarkBtn = QPushButton(QIcon(":/bookmarks.png"), "", self)
        self.bookmarkBtn.setToolTip("Manage Bookmarks\n         [Alt+B]")
        self.bookmarkBtn.setShortcut("Alt+B")
        self.bookmarkBtn.clicked.connect(self.managebookmarks)
        self.historyBtn = QPushButton(QIcon(":/history.png"), "", self)
        self.historyBtn.setShortcut("Alt+H")
        self.historyBtn.setToolTip("View History\n     [Alt+H]")
        self.historyBtn.clicked.connect(self.viewhistory)

        self.downloadsBtn = QPushButton(QIcon(":/download.png"), "", self)
        self.downloadsBtn.setToolTip("Download Manager")
        self.downloadsBtn.clicked.connect(self.download_manager)

        self.find = QPushButton(self)
        self.find.setText("Find/Next")
        self.find.clicked.connect(self.findnext)
        self.find.hide()
        self.findprev = QPushButton(self)
        self.findprev.setText("Backward")
        self.findprev.clicked.connect(self.findback)
        self.findprev.hide()
        self.cancelfind = QPushButton(self)
        self.cancelfind.setText("Cancel")
        self.cancelfind.clicked.connect(self.cancelfindmode)
        self.cancelfind.hide()

        self.pbar = QProgressBar(self)
        self.pbar.setTextVisible(False)
        self.pbar.setStyleSheet(
            "QProgressBar::chunk { background-color: #bad8ff; }")
        pbarLayout = QGridLayout(self.pbar)
        pbarLayout.setContentsMargins(0, 0, 0, 0)

        self.line = webkit.UrlEdit(self.pbar)
        self.line.openUrlRequested.connect(self.Enter)
        self.line.textEdited.connect(self.urlsuggestions)
        self.line.downloadRequested.connect(self.download_requested_file)
        pbarLayout.addWidget(self.line)

        self.listmodel = QStringListModel(self)
        self.completer = QCompleter(self.listmodel, self.line)
        self.completer.setCompletionMode(1)
        self.completer.setMaxVisibleItems(10)
        self.line.setCompleter(self.completer)

        self.statusbar = QLabel(self)
        self.statusbar.setStyleSheet(
            "QLabel { font-size: 12px; border-radius: 2px; padding: 2px; background: palette(highlight); color: palette(highlighted-text); }"
        )
        self.statusbar.setMaximumHeight(16)
        self.statusbar.hide()

        self.tabWidget = QTabWidget(self)
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.setDocumentMode(True)
        self.tabWidget.tabBar().setExpanding(True)
        self.tabWidget.tabBar().setElideMode(Qt.ElideMiddle)
        self.tabWidget.currentChanged.connect(self.onTabSwitch)
        self.tabWidget.tabCloseRequested.connect(self.closeTab)
        self.addTab()
        self.applysettings()
        #

        for index, widget in enumerate([
                self.addtabBtn, self.back, self.forw, self.reload,
                self.homeBtn, self.videoDownloadButton, self.pbar, self.find,
                self.findprev, self.cancelfind, self.addbookmarkBtn,
                self.menuBtn, self.bookmarkBtn, self.historyBtn,
                self.downloadsBtn
        ]):
            grid.addWidget(widget, 0, index, 1, 1)
        grid.addWidget(self.tabWidget, 2, 0, 1, 15)

#-----------------------Window settings --------------------------------
#        Must be at the end, otherwise cause segmentation fault
#       self.status = self.statusBar()

    def addTab(self, webview_tab=None):
        """ Creates a new tab and add to QTabWidget
            applysettings() must be called after adding each tab"""
        if not webview_tab:
            webview_tab = webkit.MyWebView(self.tabWidget, networkmanager)
        webview_tab.windowCreated.connect(self.addTab)
        webview_tab.loadStarted.connect(self.onLoadStart)
        webview_tab.loadFinished.connect(self.onLoadFinish)
        webview_tab.loadProgress.connect(self.onProgress)
        webview_tab.urlChanged.connect(self.onUrlChange)
        webview_tab.titleChanged.connect(self.onTitleChange)
        webview_tab.iconChanged.connect(self.onIconChange)
        webview_tab.page().printRequested.connect(self.printpage)
        webview_tab.page().downloadRequested.connect(
            self.download_requested_file)
        webview_tab.page().unsupportedContent.connect(
            self.handleUnsupportedContent)
        webview_tab.page().linkHovered.connect(self.onLinkHover)
        webview_tab.page().windowCloseRequested.connect(self.closeRequestedTab)

        self.tabWidget.addTab(webview_tab, "( Untitled )")
        if self.tabWidget.count() == 1:
            self.tabWidget.tabBar().hide()
        else:
            self.tabWidget.tabBar().show()
        self.tabWidget.setCurrentIndex(self.tabWidget.count() - 1)

    def closeTab(self, index=None):
        """ Closes tab, hides tabbar if only one tab remains"""
        if index == None:
            index = self.tabWidget.currentIndex()
        widget = self.tabWidget.widget(index)
        self.tabWidget.removeTab(index)
        widget.deleteLater()
        # Auto hide tab bar, when no. of tab widget is one
        if self.tabWidget.count() == 1:
            self.tabWidget.tabBar().hide()

    def closeRequestedTab(self):
        """ Close tab requested by the page """
        webview = self.sender().view()
        index = self.tabWidget.indexOf(webview)
        self.closeTab(index)

    def Enter(self):
        url = self.line.text()
        if url == 'about:home':
            self.goToHome()
        else:
            self.GoTo(url)

    def GoTo(self, url):
        URL = QUrl.fromUserInput(url)
        self.tabWidget.currentWidget().openLink(URL)
        self.line.setText(url)
        self.tabWidget.currentWidget().setFocus()

    def goToHome(self):
        self.GoTo(homepage)
        loop = QEventLoop()
        QTimer.singleShot(10, loop.quit)
        loop.exec_()
        document = self.tabWidget.currentWidget().page().mainFrame(
        ).documentElement()
        gallery = document.findFirst('div')
        for i, fav in enumerate(self.favourites):
            title, url, img = fav[0], fav[1], thumbnails_dir + fav[2]
            child = '<div class="photo"> <a href="{}"><img src="{}"></a><div class="desc">{}</div></div>'.format(
                url, img, title)
            gallery.appendInside(child)

    def onLoadStart(self):
        webview = self.sender()
        if webview is self.tabWidget.currentWidget():
            self.reload.setIcon(QIcon(":/stop.png"))

    def onProgress(self, progress):
        webview = self.sender()
        if webview is self.tabWidget.currentWidget() and webview.loading:
            self.pbar.setValue(progress)

    def onLoadFinish(self, ok):
        webview = self.sender()
        if webview is self.tabWidget.currentWidget():
            self.reload.setIcon(QIcon(":/refresh.png"))
            self.pbar.reset()
            url = self.line.text()
            self.handleVideoButton(url)

    def onTabSwitch(self, index):
        """ Updates urlbox, refresh icon, progress bar on switching tab"""
        webview = self.tabWidget.currentWidget()
        if webview.loading == True:
            self.reload.setIcon(QIcon(":/stop.png"))
            self.pbar.setValue(webview.progressVal)
        else:
            self.reload.setIcon(QIcon(":/refresh.png"))
            self.pbar.reset()
        url = webview.url().toString()
        if url == homepage: url = 'about:home'
        self.line.setText(url)
        self.statusbar.hide()
        self.onIconChange(webview)
        self.handleVideoButton(url)

    def onUrlChange(self, url):
        url = url.toString()
        if url == homepage: url = 'about:home'
        webview = self.sender()
        if webview is self.tabWidget.currentWidget():
            self.line.setText(url)
            self.onIconChange(webview)
            self.handleVideoButton(url)

    def onTitleChange(self, title):
        webview = self.sender()
        index = self.tabWidget.indexOf(webview)
        if not title == '':
            self.tabWidget.tabBar().setTabText(index, title)
            url = webview.url().toString()
            for item in self.history:  # Removes the old item, inserts new same item on the top
                if url == item[1]:
                    self.history.remove(item)
            self.history.insert(0, [title, url])

    def onIconChange(self, webview=None):
        if not webview:
            webview = self.sender()
        icon = webview.icon()
        if icon.isNull():
            icon = QIcon(':/quartz.png')
        if webview is self.tabWidget.currentWidget():
            self.line.setIcon(icon)
        index = self.tabWidget.indexOf(webview)
        self.tabWidget.setTabIcon(index, icon)

    def onLinkHover(self, url):
        if url == "":
            self.statusbar.hide()
            return
        self.statusbar.setText(url)
        self.statusbar.adjustSize()
        self.statusbar.show()
        self.statusbar.move(QPoint(0, self.height() - self.statusbar.height()))

    def Back(self):
        self.tabWidget.currentWidget().back()

    def Forward(self):
        self.tabWidget.currentWidget().forward()

    def Reload(self):
        if self.tabWidget.currentWidget().loading:
            self.tabWidget.currentWidget().stop()
        else:
            if self.line.text() == 'about:home':
                self.goToHome()
            else:
                self.tabWidget.currentWidget().reload()

    def urlsuggestions(self, text):
        """ Creates the list of url suggestions for URL box """
        suggestions = []
        if not webkit.find_mode_on:
            for [title, url] in self.history:
                if text in url:
                    suggestions.insert(0, url)
            for [title, address] in self.bookmarks:
                if text in address:
                    suggestions.insert(0, address)
        self.listmodel.setStringList(suggestions)

    def handleVideoButton(self, url):
        if youtube.validYoutubeUrl(url):
            self.videoDownloadButton.show()
            return
        frames = [self.tabWidget.currentWidget().page().mainFrame()]
        frames += self.tabWidget.currentWidget().page().mainFrame(
        ).childFrames()
        for frame in frames:
            videos = frame.findAllElements('video').toList()
            if videos != []:
                self.videoDownloadButton.show()
                return
        self.videoDownloadButton.hide()

##################### Downloading and Printing  ########################

    def download_requested_file(self, networkrequest):
        """ Gets called when the page requests a file to be downloaded """
        reply = networkmanager.get(networkrequest)
        self.handleUnsupportedContent(reply)

    def handleUnsupportedContent(self, reply, force_filename=None):
        """ This is called when url content is a downloadable file. e.g- pdf,mp3,mp4 """
        if reply.rawHeaderList() == []:
            loop = QEventLoop()
            reply.metaDataChanged.connect(loop.quit)
            QTimer.singleShot(5000, loop.quit)
            loop.exec_()
        if reply.hasRawHeader(b'Location'):
            URL = QUrl.fromUserInput(_str(reply.rawHeader(b'Location')))
            reply.abort()
            reply = networkmanager.get(QNetworkRequest(URL))
            self.handleUnsupportedContent(reply, force_filename)
            return
        for (title, header) in reply.rawHeaderPairs():
            print(_str(title) + "-> " + _str(header))
        # Get filename
        content_name = _str(reply.rawHeader(b'Content-Disposition'))
        if force_filename:
            filename = force_filename
        elif 'filename=' in content_name or 'filename*=' in content_name:
            if content_name.count(
                    '"'
            ) >= 2:  # Extracts texts inside quotes when two quotes are present
                start = content_name.find('"') + 1
                end = content_name.rfind('"')
                filename = content_name[start:end]
            else:
                filename = content_name.split('=')[-1]
        else:
            decoded_url = QUrl.fromUserInput(reply.url().toString())
            decoded_url = decoded_url.toString(QUrl.RemoveQuery)
            filename = QFileInfo(decoded_url).fileName()
        filename = validateFileName(filename)
        # Create downld Confirmation dialog
        dlDialog = DownloadDialog(self)
        dlDialog.filenameEdit.setText(filename)
        # Get filesize
        if reply.hasRawHeader(b'Content-Length'):
            filesize = reply.header(1)
            if filesize >= 1048576:
                file_size = "{} M".format(round(float(filesize) / 1048576, 2))
            elif 1023 < filesize < 1048576:
                file_size = "{} k".format(round(float(filesize) / 1024, 1))
            else:
                file_size = "{} B".format(filesize)
            dlDialog.labelFileSize.setText(file_size)
        # Get filetype and resume support info
        if reply.hasRawHeader(b'Content-Type'):
            dlDialog.labelFileType.setText(
                _str(reply.rawHeader(b'Content-Type')))
        if reply.hasRawHeader(b'Accept-Ranges') or reply.hasRawHeader(
                b'Content-Range'):
            dlDialog.labelResume.setText("True")
        # Execute dialog and show confirmation
        if dlDialog.exec_() == QDialog.Accepted:
            filepath = dlDialog.folder + dlDialog.filenameEdit.text()
            url = reply.url().toString()
            if self.useexternaldownloader:
                download_externally(url, self.externaldownloader)
                reply.abort()
                reply.deleteLater()
                return

            global downloads_list_file
            newdownload = Download(networkmanager)
            newdownload.startDownload(reply, filepath)
            newdownload.datachanged.connect(self.dwnldsmodel.datachanged)
            self.downloads.insert(0, newdownload)
            imported_downloads = importDownloads(downloads_list_file)
            imported_downloads.insert(0, [
                filepath, url,
                str(newdownload.totalsize), newdownload.timestamp
            ])
            exportDownloads(downloads_list_file, imported_downloads)
        else:
            reply.abort()
            reply.deleteLater()

    def download_manager(self):
        """ Opens download manager dialog """
        dialog = QDialog(self)
        downloads_dialog = Downloads_Dialog()
        downloads_dialog.setupUi(dialog, self.dwnldsmodel)
        dialog.exec_()

    def deleteDownloads(self, timestamps):
        global downloads_list_file
        imported_downloads = importDownloads(downloads_list_file)
        exported_downloads = []
        for download in imported_downloads:
            if download[-1] not in timestamps:
                exported_downloads.append(download)
        exportDownloads(downloads_list_file, exported_downloads)

    def downloadVideo(self):
        url = self.tabWidget.currentWidget().url().toString()
        # For youtube videos, parse youtube links in separate thread
        if youtube.validYoutubeUrl(url):
            vid_id = parse_qs(urlparse(url).query)['v'][0]
            ytThread = youtube.YoutubeThread(self)
            ytThread.ytParseFailed.connect(self.onYtParseFail)
            ytThread.ytVideoParsed.connect(self.onYtVideoParse)
            ytThread.finished.connect(ytThread.deleteLater)
            ytThread.vid_id = vid_id
            ytThread.start()
            return
        # For embeded HTML5 videos
        self.getVideos()

    def onYtVideoParse(self, videos):
        dialog = youtube.YoutubeDialog(videos, self)
        if dialog.exec_() == 1:
            index = abs(dialog.buttonGroup.checkedId()) - 2
            vid = videos[index]
            reply = networkmanager.get(
                QNetworkRequest(QUrl.fromUserInput(vid.url)))
            self.handleUnsupportedContent(reply,
                                          vid.filename + '.' + vid.extension)

    def onYtParseFail(self):
        # Show error on fail to parse youtube
        QMessageBox.warning(self, "Download Failed !",
                            "This Video can not be downloaded")

    def getVideos(self):
        dialog = Media_Dialog(self, self.tabWidget.currentWidget().page())
        dialog.downloadRequested.connect(self.download_requested_file)
        dialog.exec_()

    def saveAsImage(self):
        """ Saves the whole page as PNG/JPG image"""
        title = self.tabWidget.currentWidget().page().mainFrame().title()
        title == validateFileName(title)
        filename = QFileDialog.getSaveFileName(
            self, "Select Image to Save", downloaddir + title + ".jpg",
            "JPEG Image (*.jpg);;PNG Image (*.png)")[0]
        if filename == '': return
        viewportsize = self.tabWidget.currentWidget().page().viewportSize()
        contentsize = self.tabWidget.currentWidget().page().mainFrame(
        ).contentsSize()
        self.tabWidget.currentWidget().page().setViewportSize(contentsize)
        img = QPixmap(contentsize)
        painter = QPainter(img)
        self.tabWidget.currentWidget().page().mainFrame().render(painter)
        painter.end()
        if img.save(filename):
            QMessageBox.information(
                self, "Successful !",
                "Page has been successfully saved as\n" + filename)
        else:
            QMessageBox.warning(self, "Saving Failed !",
                                "Exporting page to Image hasbeen failed")
        self.tabWidget.currentWidget().page().setViewportSize(viewportsize)

    def saveashtml(self):
        """ Saves current page as HTML , bt does not saves any content (e.g images)"""
        title = self.tabWidget.currentWidget().page().mainFrame().title()
        title = validateFileName(title)
        filename = QFileDialog.getSaveFileName(self, "Enter HTML File Name",
                                               downloaddir + title + ".html",
                                               "HTML Document (*.html)")[0]
        if filename == '': return
        #html = self.tabWidget.currentWidget().page().mainFrame().toHtml()
        page_URL = self.tabWidget.currentWidget().url()
        useragent = self.tabWidget.currentWidget().page().userAgentForUrl(
            page_URL)
        doc = self.tabWidget.currentWidget().page().mainFrame(
        ).documentElement().clone()
        #doc.setInnerXml(html)
        SaveAsHtml(networkmanager, doc, filename, page_URL, useragent)

    def printpage(self, page=None):
        """ Prints current/requested page """
        if not page:
            page = self.tabWidget.currentWidget().page().currentFrame()
        printer = QPrinter(QPrinter.HighResolution)
        printer.setPaperSize(QPrinter.A4)
        printer.setPageSize(QPrinter.A4)
        printer.setColorMode(QPrinter.Color)
        printer.setCreator("Quartz Browser")
        title = self.tabWidget.currentWidget().page().mainFrame().title()
        title = validateFileName(title)
        printer.setDocName(title)
        printer.setOutputFileName(docdir + title + ".pdf")
        #printer.setOutputFormat(QPrinter.PdfFormat)
        print_dialog = QPrintPreviewDialog(printer, self)
        print_dialog.paintRequested.connect(page.print_)
        print_dialog.exec_()

##################################################################################################

    def addToFavourites(self):
        dialog = QDialog(self)
        addbmkdialog = Add_Bookmark_Dialog()
        addbmkdialog.setupUi(dialog)
        dialog.setWindowTitle('Add to HomePage')
        addbmkdialog.titleEdit.setMaxLength(31)
        addbmkdialog.titleEdit.setText(
            self.tabWidget.currentWidget().page().mainFrame().title())
        addbmkdialog.addressEdit.setText(self.line.text())
        if (dialog.exec_() == QDialog.Accepted):
            title = addbmkdialog.titleEdit.text()
            addr = addbmkdialog.addressEdit.text()
            imgfile = str(time()) + '.jpg'
            viewportsize = self.tabWidget.currentWidget().page().viewportSize()
            contentsize = QSize(640, 640)
            self.tabWidget.currentWidget().page().setViewportSize(contentsize)
            img = QPixmap(contentsize)
            painter = QPainter(img)
            self.tabWidget.currentWidget().page().mainFrame().render(
                painter, QWebFrame.AllLayers)
            painter.end()
            self.tabWidget.currentWidget().page().setViewportSize(viewportsize)
            icon = img.scaledToWidth(184, 1).copy(0, 0, 180, 120)
            icon.save(thumbnails_dir + imgfile)
            self.favourites = importFavourites(configdir + 'favourites.txt')
            self.favourites.append([title, addr, imgfile])
            exportFavourites(configdir + 'favourites.txt', self.favourites)

    def addbookmark(self):
        """ Opens add bookmark dialog and gets url from url box"""
        dialog = QDialog(self)
        addbmkdialog = Add_Bookmark_Dialog()
        addbmkdialog.setupUi(dialog)
        addbmkdialog.titleEdit.setText(
            self.tabWidget.currentWidget().page().mainFrame().title())
        addbmkdialog.addressEdit.setText(self.line.text())
        if (dialog.exec_() == QDialog.Accepted):
            url = addbmkdialog.addressEdit.text()
            bmk = [addbmkdialog.titleEdit.text(), url]
            self.bookmarks = importBookmarks(configdir + "bookmarks.txt")
            self.bookmarks.insert(0, bmk)
            exportBookmarks(configdir + "bookmarks.txt", self.bookmarks)
            icon = self.tabWidget.currentWidget().icon()
            if not icon.isNull():
                icon.pixmap(16, 16).save(icon_dir + url.split('/')[2] + '.png')

    def managebookmarks(self):
        """ Opens Bookmarks dialog """
        dialog = QDialog(self)
        bmk_dialog = Bookmarks_Dialog()
        bmk_dialog.setupUi(dialog, self.bookmarks, self.favourites)
        bmk_dialog.bookmarks_table.doubleclicked.connect(self.GoTo)
        bmk_dialog.favs_table.doubleclicked.connect(self.GoTo)
        dialog.exec_()
        if bmk_dialog.bookmarks_table.data_changed:
            self.bookmarks = bmk_dialog.bookmarks_table.data
            exportBookmarks(configdir + "bookmarks.txt", self.bookmarks)
        if bmk_dialog.favs_table.data_changed:
            self.favourites = bmk_dialog.favs_table.data
            exportFavourites(configdir + "favourites.txt", self.favourites)

    def viewhistory(self):
        """ Open history dialog """
        dialog = QDialog(self)
        history_dialog = History_Dialog()
        history_dialog.setupUi(dialog, self.history)
        history_dialog.tableView.doubleclicked.connect(self.GoTo)
        dialog.exec_()

    def findmode(self):
        """ Starts find mode and unhides find buttons"""
        webkit.find_mode_on = True
        self.line.clear()
        self.find.show()
        self.findprev.show()
        self.cancelfind.show()
        self.line.setFocus()

    def cancelfindmode(self):
        """ Hides the find buttons, updates urlbox"""
        webkit.find_mode_on = False
        self.tabWidget.currentWidget().findText("")
        self.find.hide()
        self.findprev.hide()
        self.cancelfind.hide()
        self.line.setText(self.tabWidget.currentWidget().url().toString())

    def findnext(self):
        text = self.line.text()
        self.tabWidget.currentWidget().findText(text)

    def findback(self):
        text = self.line.text()
        self.tabWidget.currentWidget().findText(text, QWebPage.FindBackward)

#####################  View Settings  ###################

    def zoomin(self):
        zoomlevel = self.tabWidget.currentWidget().zoomFactor()
        self.tabWidget.currentWidget().setZoomFactor(
            zoomlevel + 0.1)  # Use setZoomFactor() to zoom text and images

    def zoomout(self):
        zoomlevel = self.tabWidget.currentWidget().zoomFactor()
        self.tabWidget.currentWidget().setZoomFactor(zoomlevel - 0.1)

    def fullscreenmode(self):
        if self.isFullScreen():
            self.showNormal()
        else:
            self.showFullScreen()

    def loadimages(self, state):
        """ TOggles image loading on/off"""
        self.websettings.setAttribute(QWebSettings.AutoLoadImages, state)
        self.loadimagesval = bool(state)

    def setjavascript(self, state):
        """ Toggles js on/off """
        self.websettings.setAttribute(QWebSettings.JavascriptEnabled, state)
        self.javascriptenabledval = bool(state)

    def setUserAgentDesktop(self, checked):
        if bool(checked):
            webkit.useragent_mode = 'Desktop'
            self.useragent_mode_mobile.setChecked(False)
            self.useragent_mode_custom.setChecked(False)

    def setUserAgentMobile(self, checked):
        if bool(checked):
            webkit.useragent_mode = 'Mobile'
            self.useragent_mode_desktop.setChecked(False)
            self.useragent_mode_custom.setChecked(False)

    def setUserAgentCustom(self, checked):
        if bool(checked):
            webkit.useragent_mode = 'Custom'
            self.useragent_mode_mobile.setChecked(False)
            self.useragent_mode_desktop.setChecked(False)

########################## Settings Portion #########################

    def settingseditor(self):
        """ Opens the settings manager dialog, then applies the change"""
        dialog = QDialog(self)
        websettingsdialog = Ui_SettingsDialog()
        websettingsdialog.setupUi(dialog)
        # Enable AdBlock
        websettingsdialog.checkAdBlock.setChecked(webkit.enable_adblock)
        # Fonts blocking
        websettingsdialog.checkFontLoad.setChecked(webkit.block_fonts)
        # Popups blocking
        websettingsdialog.checkBlockPopups.setChecked(webkit.block_popups)
        # Custom user agent
        websettingsdialog.useragentEdit.setText(webkit.useragent_custom)
        # External download manager
        websettingsdialog.checkDownMan.setChecked(self.useexternaldownloader)
        websettingsdialog.downManEdit.setText(self.externaldownloader)
        # RTSP media player command
        websettingsdialog.mediaPlayerEdit.setText(webkit.video_player_command)
        websettingsdialog.mediaPlayerEdit.setCursorPosition(0)
        # Font settings
        websettingsdialog.spinFontSize.setValue(self.minfontsizeval)
        websettingsdialog.standardfontCombo.setCurrentFont(
            QFont(self.standardfontval))
        websettingsdialog.sansfontCombo.setCurrentFont(QFont(self.sansfontval))
        websettingsdialog.seriffontCombo.setCurrentFont(
            QFont(self.seriffontval))
        websettingsdialog.fixedfontCombo.setCurrentFont(
            QFont(self.fixedfontval))
        # Clear Data buttons
        websettingsdialog.clearCacheButton.clicked.connect(
            self.websettings.clearMemoryCaches)
        websettingsdialog.cookiesButton.clicked.connect(cookiejar.clearCookies)
        websettingsdialog.iconDBButton.clicked.connect(
            self.websettings.clearIconDatabase)

        if dialog.exec_() == QDialog.Accepted:
            # Enable AdBlock
            webkit.enable_adblock = websettingsdialog.checkAdBlock.isChecked()
            # Block Fonts
            webkit.block_fonts = websettingsdialog.checkFontLoad.isChecked()
            # Block Popups
            webkit.block_popups = websettingsdialog.checkBlockPopups.isChecked(
            )
            # User Agent
            webkit.useragent_custom = websettingsdialog.useragentEdit.text()
            # Download Manager
            self.useexternaldownloader = websettingsdialog.checkDownMan.isChecked(
            )
            self.externaldownloader = websettingsdialog.downManEdit.text()
            # Media Player Command
            webkit.video_player_command = websettingsdialog.mediaPlayerEdit.text(
            )

            self.minfontsizeval = websettingsdialog.spinFontSize.value()
            self.standardfontval = websettingsdialog.standardfontCombo.currentText(
            )
            self.sansfontval = websettingsdialog.sansfontCombo.currentText()
            self.seriffontval = websettingsdialog.seriffontCombo.currentText()
            self.fixedfontval = websettingsdialog.fixedfontCombo.currentText()
            self.applysettings()
            self.savesettings()

    def opensettings(self):
        """ Reads settings file in ~/.config/quartz-browser/ directory and
            saves values in settings variables"""
        webkit.enable_adblock = _bool(
            self.settings.value('EnableAdblock', True))
        self.loadimagesval = _bool(self.settings.value('LoadImages', True))
        self.javascriptenabledval = _bool(
            self.settings.value('JavaScriptEnabled', True))
        webkit.block_fonts = _bool(
            self.settings.value('BlockFontLoading', False))
        webkit.block_popups = _bool(self.settings.value('BlockPopups', False))
        webkit.useragent_mode = self.settings.value('UserAgentMode',
                                                    webkit.useragent_mode)
        webkit.useragent_custom = self.settings.value('UserAgent',
                                                      webkit.useragent_custom)
        self.useexternaldownloader = _bool(
            self.settings.value('UseExternalDownloader', False))
        self.externaldownloader = self.settings.value(
            'ExternalDownloader', "x-terminal-emulator wget -c %u")
        webkit.video_player_command = self.settings.value(
            'MediaPlayerCommand', webkit.video_player_command)
        self.maximize_window = _bool(
            self.settings.value('MaximizeWindow', False))
        self.minfontsizeval = int(self.settings.value('MinFontSize', 11))
        self.standardfontval = self.settings.value('StandardFont', 'Sans')
        self.sansfontval = self.settings.value('SansFont', 'Sans')
        self.seriffontval = self.settings.value('SerifFont', 'Serif')
        self.fixedfontval = self.settings.value('FixedFont', 'Monospace')

    def savesettings(self):
        """ Writes setings to disk in ~/.config/quartz-browser/ directory"""
        self.settings.setValue('EnableAdblock', webkit.enable_adblock)
        self.settings.setValue('LoadImages', self.loadimagesval)
        self.settings.setValue('JavaScriptEnabled', self.javascriptenabledval)
        self.settings.setValue('BlockFontLoading', webkit.block_fonts)
        self.settings.setValue('BlockPopups', webkit.block_popups)
        self.settings.setValue('UserAgent', webkit.useragent_custom)
        self.settings.setValue('UserAgentMode', webkit.useragent_mode)
        self.settings.setValue('UseExternalDownloader',
                               self.useexternaldownloader)
        self.settings.setValue('ExternalDownloader', self.externaldownloader)
        self.settings.setValue('MediaPlayerCommand',
                               webkit.video_player_command)
        self.settings.setValue('MaximizeWindow', self.isMaximized())
        self.settings.setValue('MinFontSize', self.minfontsizeval)
        self.settings.setValue('StandardFont', self.standardfontval)
        self.settings.setValue('SansFont', self.sansfontval)
        self.settings.setValue('SerifFont', self.seriffontval)
        self.settings.setValue('FixedFont', self.fixedfontval)

    def applysettings(self):
        """ Reads settings variables, and changes browser settings.This is run after
            changing settings by Settings Dialog"""
        if webkit.enable_adblock:
            self.websettings.setUserStyleSheetUrl(
                QUrl.fromLocalFile(program_dir + 'userContent.css'))
        else:
            self.websettings.setUserStyleSheetUrl(QUrl(''))
        self.websettings.setAttribute(QWebSettings.AutoLoadImages,
                                      self.loadimagesval)
        self.loadimagesaction.setChecked(self.loadimagesval)
        self.websettings.setAttribute(QWebSettings.JavascriptEnabled,
                                      self.javascriptenabledval)
        self.javascriptmode.setChecked(self.javascriptenabledval)
        if webkit.useragent_mode == 'Mobile':
            self.useragent_mode_mobile.setChecked(True)
        elif webkit.useragent_mode == 'Custom':
            self.useragent_mode_custom.setChecked(True)
        else:
            self.useragent_mode_desktop.setChecked(True)
        self.websettings.setFontSize(QWebSettings.MinimumFontSize,
                                     self.minfontsizeval)
        self.websettings.setFontFamily(QWebSettings.StandardFont,
                                       self.standardfontval)
        self.websettings.setFontFamily(QWebSettings.SansSerifFont,
                                       self.sansfontval)
        self.websettings.setFontFamily(QWebSettings.SerifFont,
                                       self.seriffontval)
        self.websettings.setFontFamily(QWebSettings.FixedFont,
                                       self.fixedfontval)


#        self.websettings.setFontSize(QWebSettings.DefaultFontSize, 14)

    def forceClose(self):
        self.confirm_before_quit = False
        self.close()

    def closeEvent(self, event):
        """This saves all settings, bookmarks, cookies etc. during window close"""
        if self.confirm_before_quit:
            confirm = QMessageBox.warning(self, 'Quit Browser ?',
                                          'Are you sure to close the Browser',
                                          QMessageBox.Yes | QMessageBox.No,
                                          QMessageBox.Yes)
            if confirm == QMessageBox.No:
                event.ignore()
                return
        self.savesettings()
        cookiejar.exportCookies()
        # Delete excess thumbnails
        thumbnails = [x for x in os.listdir(thumbnails_dir)]
        for fav in self.favourites:
            if fav[2] in thumbnails:
                thumbnails.remove(fav[2])
        for f in thumbnails:
            os.remove(thumbnails_dir + f)
        # Delete excess icons
        icons = [x for x in os.listdir(icon_dir) if x.endswith('.png')]
        for bmk in self.bookmarks:
            if bmk[1].split('/')[2] + '.png' in icons:
                icons.remove(bmk[1].split('/')[2] + '.png')
        for f in icons:
            os.remove(icon_dir + f)
        super(Main, self).closeEvent(event)
Example #36
0
class kstImageViewer(QWidget):

	def __init__(self, sourceFile, data, type, image, mode):
		""" Class constructor.
		"""
		QWidget.__init__(self)

		# Initialize image panel:
		self.imagePanel = _kstImagePanel()

		# Set original mode:
		self.__originalMode = mode

		# Set the type of image with respect of the lightfield pipeline:        
		self.__imageType = type      # 'raw', 'pre-processed', 'reconstructed', 'post-processed'

		# The actual object handled by the image viewer:
		self.__data = data

		# Properties:
		self.__sourceFile = sourceFile		
		
		# Current view index:
		self.__view = 0	
		
		# Top toolbar:
		self.topToolBar = QToolBar()
		self._createTopToolbar()

		# Bottom toolbar:
		self.bottomToolBar = QToolBar()
		self._createBottomToolbar()	

		# Handle mouse hover with custom slot:
		self.imagePanel.mouseHoverEvent.connect(self._handleMouseHover)

		# Compose layout of the whole widget:
		layout = QVBoxLayout()	
		layout.addWidget(self.topToolBar)
		layout.addWidget(self.imagePanel)
		layout.addWidget(self.bottomToolBar)	
		layout.setContentsMargins(0,0,0,0)	
		self.setLayout(layout)
		self.setContentsMargins(0,0,0,0)	

		# Set image:
		self.__setImage(image)



	def _createTopToolbar(self):
		"""
        """
		topToolbarSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)        
		self.topToolBar.setSizePolicy(topToolbarSizePolicy)

		#pan_zoom = QAction(QIcon(dir + "/resources/btnDrag.png"),"Pan (Mouse
		#Left)",self)
		#self.toolBar.addAction(pan_zoom)
		#zoomSelect = QAction(QIcon(dir + "/resources/btnZoomSelect.png"),"ROI Zoom
		#(Mouse Left)",self)
		#self.toolBar.addAction(zoomSelect)
		exitAct = QAction('Exit', self)
		exitAct.setShortcut('Ctrl+Q')

		self._panZoom = QToolButton(self)
		self._panZoom.setIcon(QIcon(PAN_ZOOM_ICON))
		self._panZoom.setToolTip(PAN_ZOOM_TOOLTIP)
		self._panZoom.setCheckable(True)
		self._panZoom.setChecked(True)
		self._panZoom.clicked.connect(self._panZoomSwitch)
		self.topToolBar.addWidget(self._panZoom)

		self._zoomSelect = QToolButton(self)
		self._zoomSelect.setIcon(QIcon(ZOOM_SELECT_ICON))
		self._zoomSelect.setToolTip(ZOOM_SELECT_TOOLTIP)
		self._zoomSelect.setCheckable(True)
		self._zoomSelect.setChecked(False)
		self._zoomSelect.clicked.connect(self._zoomSelectSwitch)
		self.topToolBar.addWidget(self._zoomSelect)

		self.topToolBar.addSeparator()

		zoomIn = QAction(QIcon(ZOOM_IN_ICON),ZOOM_IN_TOOLTIP,self)        
		self.topToolBar.addAction(zoomIn)
		zoomOut = QAction(QIcon(ZOOM_OUT_ICON),ZOOM_OUT_TOOLTIP,self)        
		self.topToolBar.addAction(zoomOut)
		zoomReset = QAction(QIcon(ZOOM_RESET_ICON),ZOOM_RESET_TOOLTIP,self)        
		self.topToolBar.addAction(zoomReset)

		self.topToolBar.addSeparator()

		# Separator:
		#self.fooWidget = QWidget()
		#self.fooWidget.setFixedWidth(6)
		#self.fooWidgetAction = self.topToolBar.addWidget(self.fooWidget)

		#self.extraSeparatorAction = self.topToolBar.addSeparator()

		export = QAction(QIcon(EXPORT_ICON),EXPORT_TOOLTIP,self)        
		self.topToolBar.addAction(export)

		exportAll = QAction(QIcon(EXPORTALL_ICON),EXPORTALL_TOOLTIP,self)        
		self.topToolBar.addAction(exportAll)
								
		# Spacer:
		spacer = QWidget()
		spacerSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)   
		spacer.setSizePolicy(spacerSizePolicy)
		self.topToolBar.addWidget(spacer)
		
		# Label on the right:
		self.hoverLabel = QLabel(self)
		self.hoverLabel.setText("")
		self.topToolBar.addWidget(self.hoverLabel) 
			

		# Connect handler for toolbar buttons:
		self.topToolBar.actionTriggered[QAction].connect(self._toolBarBtnPressed)




	def _createBottomToolbar(self):
		"""
		"""
		
		bottomToolbarSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)        
		self.bottomToolBar.setSizePolicy(bottomToolbarSizePolicy)	
	
		# Combo box for the 4 "views" of a dataset:
		self.lblView = QLabel(" View: ")   # Use spaces		
		self.lblViewAction = self.bottomToolBar.addWidget(self.lblView)			

		self.cbxView = QComboBox()
		self.cbxView.addItems(["Projection/Axial", "Sinogram/Sagittal", "Lateral/Frontal"])
		self.cbxView.currentIndexChanged.connect(self.changeView)
		self.cbxViewAction = self.bottomToolBar.addWidget(self.cbxView)	
		
	
		self.indexLabel = QLabel(self)
		self.indexLabel.setText("")
		self.indexLabel.setFixedWidth(70)
		self.indexLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
		self.bottomToolBar.addWidget(self.indexLabel)


		# Slider for the projection/slices:
		self.lblImageSlider = QLabel(" Image: ") # Use spaces
		self.lblImageSliderAction = self.bottomToolBar.addWidget(self.lblImageSlider)
		
		self.sldDataset = QSlider(Qt.Horizontal) 
		self.sldDataset.setFixedWidth(250)
		self.sldDataset.setFocusPolicy(Qt.StrongFocus)
		self.sldDataset.setTickPosition(QSlider.TicksBelow)
		self.sldDataset.valueChanged.connect(self.changeDatasetView)		
		self.sldDatasetAction = self.bottomToolBar.addWidget(self.sldDataset)		
		
		# Slider for the repetitions:
		self.lblRepetitionIndex = QLabel(self)
		self.lblRepetitionIndex.setText("")
		self.lblRepetitionIndex.setFixedWidth(50)
		self.lblRepetitionIndex.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
		self.bottomToolBar.addWidget(self.lblRepetitionIndex)

		self.lblRepetitionSlider = QLabel(" Repetition: ") # Use spaces
		self.lblRepetitionSlider.setFixedWidth(80)
		self.lblRepetitionSlider.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
		self.lblRepetitionSliderAction = self.bottomToolBar.addWidget(self.lblRepetitionSlider)		
		
		self.sldRepetition = QSlider(Qt.Horizontal) 
		self.sldRepetition.setFixedWidth(150)
		self.sldRepetition.setFocusPolicy(Qt.StrongFocus)
		self.sldRepetition.setTickPosition(QSlider.TicksBelow)
		self.sldRepetition.valueChanged.connect(self.changeRepetitionView)
		self.sldRepetitionAction = self.bottomToolBar.addWidget(self.sldRepetition)		
			

		if self.__data.ndim == 4:
			self.lblRepetitionSliderAction.setVisible(True)
			self.sldRepetitionAction.setVisible(True)
		else:
			self.lblRepetitionSliderAction.setVisible(False)
			self.sldRepetitionAction.setVisible(False)
			

	#def drawBackground(self, painter, rect):

	#	color = self.palette().color(QPalette.Background)
	#	background_brush = QBrush( color, Qt.SolidPattern)
	#	painter.fillRect(rect, background_brush)

	def _panZoomSwitch(self):

		self._zoomSelect.setChecked(not self._panZoom.isChecked())
		self.imagePanel.togglePanZoom = self._zoomSelect.isChecked()

	def _zoomSelectSwitch(self):

		self._panZoom.setChecked(not self._zoomSelect.isChecked())
		self.imagePanel.togglePanZoom = self._zoomSelect.isChecked()
		
	def _toolBarBtnPressed(self, button):

		if button.text() == ZOOM_IN_TOOLTIP:
			self.imagePanel.performZoom(min(400.0,self.imagePanel.zoomFactor*1.15))
		elif button.text() == ZOOM_OUT_TOOLTIP:
			self.imagePanel.performZoom(max(1.0,self.imagePanel.zoomFactor/1.15))
		elif button.text() == ZOOM_RESET_TOOLTIP:
			self.imagePanel.performZoom(1.0)
		elif button.text() == EXPORT_TOOLTIP:

			# Open a Save As dialog:
			try:
				options = QFileDialog.Options()
				options |= QFileDialog.DontUseNativeDialog
				filename, _ = QFileDialog.getSaveFileName(self,"Save as TIFF", 
							  "","TIFF Files (*.tif);;All Files (*)", options=options)
				if filename:
				
					# Call the method to save the current displayed image:
					self.imagePanel.saveAsTIFF(filename)

			except Exception as e:
				eprint(str(e))

		elif button.text() == EXPORTALL_TOOLTIP:

			# Open a Save As dialog:
			try:
				options = QFileDialog.Options()
				options |= QFileDialog.DontUseNativeDialog
				options |= QFileDialog.DirectoryOnly
				folder = QFileDialog.getExistingDirectory(self, "Select Folder for TIFF sequence")

				if folder: 			
				
					for i in range(0,self.__data.shape[2]):
		
						# Prepare filename:
						filename = os.path.join(folder, "image_" + "{:04d}".format(i) + ".tif")

						# Save as TIFF with tiffile library:
						tifffile.imsave(filename, data=self.__data[:,:,i])

			except Exception as e:
				eprint(str(e))
			



	def _handleMouseHover(self, x, y, z, type):

		if (x == -1):
			self.hoverLabel.setText("")
		else:
			if (type == 'float'):
				s = "{:0.4f}".format(z) if (z > 1e-2) else "{:.4E}".format(z)
			else:
				s = "{:d}".format(round(z))
			self.hoverLabel.setText("[" + str(x) + "," + str(y) + "]=" + s + " " )


	def __setImage(self, npImage):
		""" Set the scene's current image pixmap to the input image as a numpy array.
		:type npImage: numpy array
		"""
		# Set the new numpy image:
		self.imagePanel.setImage(npImage)  

		# Enable/disable UI widgets:
		if (self.__imageType == 'raw'):
			self.lblViewAction.setVisible(True)
			self.cbxViewAction.setVisible(True)
			self.lblImageSliderAction.setVisible(True)
			self.sldDatasetAction.setVisible(True)
			if self.__data.ndim == 4:
				self.lblRepetitionSliderAction.setVisible(True)
				self.lblRepetitionIndex.setVisible(True)
				self.sldRepetitionAction.setVisible(True)
			else:
				self.lblRepetitionSliderAction.setVisible(False)
				self.lblRepetitionIndex.setVisible(False)
				self.sldRepetitionAction.setVisible(False)

		elif (self.__imageType == 'pre-processed'):
			self.lblViewAction.setVisible(True)
			self.cbxViewAction.setVisible(True)
			self.lblImageSliderAction.setVisible(True)
			self.sldDatasetAction.setVisible(True)
			self.sldRepetitionAction.setVisible(False)
			self.lblRepetitionIndex.setVisible(False)
			self.lblRepetitionSliderAction.setVisible(False)

		elif (self.__imageType == 'reconstructed'):
			self.lblViewAction.setVisible(True)
			self.cbxViewAction.setVisible(True)
			self.lblImageSliderAction.setVisible(True)
			self.sldDatasetAction.setVisible(True)
			self.sldRepetitionAction.setVisible(False)
			self.lblRepetitionIndex.setVisible(False)
			self.lblRepetitionSliderAction.setVisible(False)

		# Set dimension of the slider and default:
		self.sldDataset.setMinimum(0)
		self.sldDataset.setMaximum(self.__data.shape[2]-1)
		self.sldDataset.setValue(round(self.__data.shape[2]/2))

		self.indexLabel.setText(str(round(self.__data.shape[2]/2)) \
			+ "/" + str(round(self.__data.shape[2])))


	def changeView(self, idx):
		""" Called when the combo box index is changed.
		"""
		# Reset sliders:
		self.sldDataset.setValue(0)
		if self.__data.ndim == 4:
			self.sldRepetition.setValue(0)
	
		# Transpose datasets:
		if idx == 0: # Axial or projection view:
			if self.__data.ndim == 4:
				if self.__view == 1:
					self.__data = numpy.transpose(self.__data, (2,1,0,3)) # OK
				if self.__view == 2:
					self.__data = numpy.transpose(self.__data, (1,2,0,3)) # OK
			else:
				if self.__view == 1:				    
					self.__data = numpy.transpose(self.__data, (2,1,0))   # OK
				if self.__view == 2:
					self.__data = numpy.transpose(self.__data, (1,2,0))   # OK

		elif idx == 1: # Sinogram of sagittal view:
			if self.__data.ndim == 4:
				if self.__view == 0:
					self.__data = numpy.transpose(self.__data, (2,1,0,3)) # OK
				if self.__view == 2:
					self.__data = numpy.transpose(self.__data, (0,2,1,3)) # OK
			else:
				if self.__view == 0:				    
					self.__data = numpy.transpose(self.__data, (2,1,0))   # OK
				if self.__view == 2:
					self.__data = numpy.transpose(self.__data, (0,2,1))   # OK

		else: # Lateral or coronal view:
			if self.__data.ndim == 4:
				if self.__view == 0:
					self.__data = numpy.transpose(self.__data, (2,0,1,3)) # OK
				if self.__view == 1:
					self.__data = numpy.transpose(self.__data, (0,2,1,3)) # OK
			else:
				if self.__view == 0:				    
					self.__data = numpy.transpose(self.__data, (2,0,1))   # OK
				if self.__view == 1:
					self.__data = numpy.transpose(self.__data, (0,2,1))   # OK

		# Set new view:
		self.__view = idx


		# Change to the new numpy image:
		if self.__data.ndim == 4:
			self.imagePanel.changeImage(self.__data[:,:,round(self.__data.shape[2]/2),round(self.__data.shape[3]/2)])
		else:
			self.imagePanel.changeImage(self.__data[:,:,round(self.__data.shape[2]/2)])

		# Set the index:
		self.sldDataset.setMinimum(0)
		self.sldDataset.setMaximum(self.__data.shape[2]-1)
		self.sldDataset.setValue(round(self.__data.shape[2]/2))
	
		# Reset zoom:
		self.imagePanel.performZoom(1.0)

	def changeDatasetView(self):
		""" Called when the slider is moved, so user wants to see a different 
            projection or slice.
		"""
		val = int(self.sldDataset.value())		

		# Change to the new numpy image:
		if self.__data.ndim == 4:
			rep = int(self.sldRepetition.value())
			self.imagePanel.changeImage(self.__data[:,:,val,rep])            
			#self.sldRepetition.setValue(round(self.__data.shape[3]/2))
		else:
			self.imagePanel.changeImage(self.__data[:,:,val])

		# Set the index:
		self.indexLabel.setText(str(val + 1) + "/" + str(round(self.__data.shape[2])))


	def changeRepetitionView(self):
		""" Called when the slider is moved, so user wants to see a different
			repetition of the same projection.
		"""
		img = int(self.sldDataset.value())
		val = int(self.sldRepetition.value())

		# Change to the new numpy image:
		self.imagePanel.changeImage(self.__data[:,:,img,val])

		# Set the index:
		self.lblRepetitionIndex.setText(str(val+1) + "/" + str(round(self.__data.shape[3])))
			

	def getType(self):
		""" Get the type of current image viewer.
		"""

		# Set the new numpy image:
		return self.__imageType


	def getOriginalMode(self):
		""" Get the original mode (2COL or 1COL).
		"""

		# Set the new numpy image:
		return self.__originalMode


	def getSourceFile(self):
		""" Get the source file of current image viewer.
		"""

		# Set the new numpy image:
		return self.__sourceFile


	def getImage(self):
		""" Get the scene's current image pixmap as a numpy array.
		"""

		# Set the new numpy image:
		return self.imagePanel.npImage


	def getData(self):
		""" Get the data connected to this image viewer.
		"""
		
		return self.__data
class TxDialog(QDialog, MessageBoxMixin):
    def __init__(self, tx: Transaction, parent: 'ElectrumWindow', invoice,
                 desc, prompt_if_unsaved):
        '''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)
        # Take a copy; it might get updated in the main window by
        # e.g. the FX plugin.  If this happens during or after a long
        # sign operation the signatures are lost.
        self.tx = tx = copy.deepcopy(tx)
        try:
            self.tx.deserialize()
        except BaseException as e:
            raise SerializationError(e)
        self.main_window = parent
        self.wallet = parent.wallet
        self.prompt_if_unsaved = prompt_if_unsaved
        self.saved = False
        self.desc = desc
        self.invoice = invoice

        # if the wallet can populate the inputs with more info, do it now.
        # as a result, e.g. we might learn an imported address tx is segwit,
        # in which case it's ok to display txid
        tx.add_inputs_info(self.wallet)

        self.setMinimumWidth(950)
        self.setWindowTitle(_("Transaction"))

        vbox = QVBoxLayout()
        self.setLayout(vbox)

        vbox.addWidget(QLabel(_("Transaction ID:")))
        self.tx_hash_e = ButtonsLineEdit()
        qr_show = lambda: parent.show_qrcode(
            str(self.tx_hash_e.text()), 'Transaction ID', parent=self)
        qr_icon = "qrcode_white.png" if ColorScheme.dark_scheme else "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.add_io(vbox)

        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"))
        save_button_disabled = not tx.is_complete()
        b.setDisabled(save_button_disabled)
        if save_button_disabled:
            b.setToolTip(SAVE_BUTTON_DISABLED_TOOLTIP)
        else:
            b.setToolTip(SAVE_BUTTON_ENABLED_TOOLTIP)
        b.clicked.connect(self.save)

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

        export_actions_menu = QMenu()
        action = QAction(_("Copy to clipboard"), self)
        action.triggered.connect(lambda: parent.app.clipboard().setText(
            (lambda: str(self.tx))()))
        export_actions_menu.addAction(action)
        action = QAction(read_QIcon(qr_icon), _("Show as QR code"), self)
        action.triggered.connect(self.show_qr)
        export_actions_menu.addAction(action)
        action = QAction(_("Export to file"), self)
        action.triggered.connect(self.export)
        export_actions_menu.addAction(action)
        self.export_actions_button = QToolButton()
        self.export_actions_button.setText(_("Export"))
        self.export_actions_button.setMenu(export_actions_menu)
        self.export_actions_button.setPopupMode(QToolButton.InstantPopup)

        # Action buttons
        self.buttons = [
            self.sign_button, self.broadcast_button, self.cancel_button
        ]
        # Transaction sharing buttons
        self.sharing_buttons = [self.export_actions_button, self.save_button]

        run_hook('transaction_dialog', self)

        hbox = QHBoxLayout()
        hbox.addLayout(Buttons(*self.sharing_buttons))
        hbox.addStretch(1)
        hbox.addLayout(Buttons(*self.buttons))
        vbox.addLayout(hbox)
        self.update()

    def do_broadcast(self):
        self.main_window.push_top_level_window(self)
        try:
            self.main_window.broadcast_transaction(self.tx,
                                                   invoice=self.invoice,
                                                   tx_desc=self.desc)
        finally:
            self.main_window.pop_top_level_window(self)
        self.saved = True
        self.update()

    def closeEvent(self, event):
        if (self.prompt_if_unsaved and not self.saved and not self.question(
                _('This transaction is not saved. Close anyway?'),
                title=_("Warning"))):
            event.ignore()
        else:
            event.accept()
            try:
                dialogs.remove(self)
            except ValueError:
                pass  # was not in list already

    def reject(self):
        # Override escape-key to close normally (and invoke closeEvent)
        self.close()

    def show_qr(self):
        text = bfh(str(self.tx))
        text = base_encode(text, base=43)
        try:
            self.main_window.show_qrcode(text, 'Transaction', parent=self)
        except qrcode.exceptions.DataOverflowError:
            self.show_error(
                _('Failed to display QR code.') + '\n' +
                _('Transaction is too large in size.'))
        except Exception as e:
            self.show_error(_('Failed to display QR code.') + '\n' + repr(e))

    def sign(self):
        def sign_done(success):
            # note: with segwit we could save partially signed tx, because they have a txid
            if self.tx.is_complete():
                self.prompt_if_unsaved = True
                self.saved = False
                self.save_button.setDisabled(False)
                self.save_button.setToolTip(SAVE_BUTTON_ENABLED_TOOLTIP)
            self.update()
            self.main_window.pop_top_level_window(self)

        self.sign_button.setDisabled(True)
        self.main_window.push_top_level_window(self)
        self.main_window.sign_tx(self.tx, sign_done)

    def save(self):
        self.main_window.push_top_level_window(self)
        if self.main_window.save_transaction_into_wallet(self.tx):
            self.save_button.setDisabled(True)
            self.saved = True
        self.main_window.pop_top_level_window(self)

    def export(self):
        name = 'signed_%s.txn' % (
            self.tx.txid()[0:8]) if self.tx.is_complete() else 'unsigned.txn'
        fileName = self.main_window.getSaveFileName(
            _("Select where to save your signed transaction"), name, "*.txn")
        if fileName:
            with open(fileName, "w+") as f:
                f.write(json.dumps(self.tx.as_dict(), indent=4) + '\n')
            self.show_message(_("Transaction exported successfully"))
            self.saved = True

    def update(self):
        desc = self.desc
        base_unit = self.main_window.base_unit()
        format_amount = self.main_window.format_amount
        tx_details = self.wallet.get_tx_info(self.tx)
        tx_mined_status = tx_details.tx_mined_status
        exp_n = tx_details.mempool_depth_bytes
        amount, fee = tx_details.amount, tx_details.fee
        size = self.tx.estimated_size()
        self.broadcast_button.setEnabled(tx_details.can_broadcast)
        can_sign = not self.tx.is_complete() and \
            (self.wallet.can_sign(self.tx) or bool(self.main_window.tx_external_keypairs))
        self.sign_button.setEnabled(can_sign)
        self.tx_hash_e.setText(tx_details.txid or _('Unknown'))
        if desc is None:
            self.tx_desc.hide()
        else:
            self.tx_desc.setText(_("Description") + ': ' + desc)
            self.tx_desc.show()
        self.status_label.setText(_('Status:') + ' ' + tx_details.status)

        if tx_mined_status.timestamp:
            time_str = datetime.datetime.fromtimestamp(
                tx_mined_status.timestamp).isoformat(' ')[:-3]
            self.date_label.setText(_("Date: {}").format(time_str))
            self.date_label.show()
        elif exp_n:
            text = '%.2f MB' % (exp_n / 1000000)
            self.date_label.setText(
                _('Position in mempool: {} from tip').format(text))
            self.date_label.show()
        else:
            self.date_label.hide()
        self.locktime_label.setText(f"LockTime: {self.tx.locktime}")
        self.rbf_label.setText(f"RBF: {not self.tx.is_final()}")
        if tx_mined_status.header_hash:
            self.block_hash_label.setText(
                _("Included in block: {}").format(tx_mined_status.header_hash))
            self.block_height_label.setText(
                _("At block height: {}").format(tx_mined_status.height))
        else:
            self.block_hash_label.hide()
            self.block_height_label.hide()
        if amount is None:
            amount_str = _("Transaction unrelated to your wallet")
        elif amount > 0:
            amount_str = _("Amount received:"
                           ) + ' %s' % format_amount(amount) + ' ' + base_unit
        else:
            amount_str = _("Amount sent:"
                           ) + ' %s' % format_amount(-amount) + ' ' + base_unit
        size_str = _("Size:") + ' %d bytes' % size
        fee_str = _("Fee") + ': %s' % (format_amount(fee) + ' ' + base_unit
                                       if fee is not None else _('unknown'))
        if fee is not None:
            fee_rate = fee / size * 1000
            fee_str += '  ( %s ) ' % self.main_window.format_fee_rate(fee_rate)
            feerate_warning = simple_config.FEERATE_WARNING_HIGH_FEE
            if fee_rate > feerate_warning:
                fee_str += ' - ' + _('Warning') + ': ' + _("high fee") + '!'
        self.amount_label.setText(amount_str)
        self.fee_label.setText(fee_str)
        self.size_label.setText(size_str)
        run_hook('transaction_dialog_update', self)

    def add_io(self, vbox):
        vbox.addWidget(QLabel(_("Inputs") + ' (%d)' % len(self.tx.inputs())))
        ext = QTextCharFormat()
        rec = QTextCharFormat()
        rec.setBackground(QBrush(ColorScheme.GREEN.as_color(background=True)))
        rec.setToolTip(_("Wallet receive address"))
        chg = QTextCharFormat()
        chg.setBackground(QBrush(ColorScheme.YELLOW.as_color(background=True)))
        chg.setToolTip(_("Wallet change address"))
        twofactor = QTextCharFormat()
        twofactor.setBackground(
            QBrush(ColorScheme.BLUE.as_color(background=True)))
        twofactor.setToolTip(
            _("TrustedCoin (2FA) fee for the next batch of transactions"))

        def text_format(addr):
            if self.wallet.is_mine(addr):
                return chg if self.wallet.is_change(addr) else rec
            elif self.wallet.is_billing_address(addr):
                return twofactor
            return ext

        def format_amount(amt):
            return self.main_window.format_amount(amt, whitespaces=True)

        i_text = QTextEditWithDefaultSize()
        i_text.setFont(QFont(MONOSPACE_FONT))
        i_text.setReadOnly(True)
        cursor = i_text.textCursor()
        for x in self.tx.inputs():
            if x['type'] == 'coinbase':
                cursor.insertText('coinbase')
            else:
                prevout_hash = x.get('prevout_hash')
                prevout_n = x.get('prevout_n')
                cursor.insertText(prevout_hash + ":%-4d " % prevout_n, ext)
                addr = self.wallet.get_txin_address(x)
                if addr is None:
                    addr = ''
                cursor.insertText(addr, text_format(addr))
                if x.get('value'):
                    cursor.insertText(format_amount(x['value']), ext)
            cursor.insertBlock()

        vbox.addWidget(i_text)
        vbox.addWidget(QLabel(_("Outputs") + ' (%d)' % len(self.tx.outputs())))
        o_text = QTextEditWithDefaultSize()
        o_text.setFont(QFont(MONOSPACE_FONT))
        o_text.setReadOnly(True)
        cursor = o_text.textCursor()
        for o in self.tx.get_outputs_for_UI():
            addr, v = o.address, o.value
            cursor.insertText(addr, text_format(addr))
            if v is not None:
                cursor.insertText('\t', ext)
                cursor.insertText(format_amount(v), ext)
            cursor.insertBlock()
        vbox.addWidget(o_text)

    def add_tx_stats(self, vbox):
        hbox_stats = QHBoxLayout()

        # left column
        vbox_left = QVBoxLayout()
        self.tx_desc = TxDetailLabel(word_wrap=True)
        vbox_left.addWidget(self.tx_desc)
        self.status_label = TxDetailLabel()
        vbox_left.addWidget(self.status_label)
        self.date_label = TxDetailLabel()
        vbox_left.addWidget(self.date_label)
        self.amount_label = TxDetailLabel()
        vbox_left.addWidget(self.amount_label)
        self.fee_label = TxDetailLabel()
        vbox_left.addWidget(self.fee_label)
        vbox_left.addStretch(1)
        hbox_stats.addLayout(vbox_left, 50)

        # vertical line separator
        line_separator = QFrame()
        line_separator.setFrameShape(QFrame.VLine)
        line_separator.setFrameShadow(QFrame.Sunken)
        line_separator.setLineWidth(1)
        hbox_stats.addWidget(line_separator)

        # right column
        vbox_right = QVBoxLayout()
        self.size_label = TxDetailLabel()
        vbox_right.addWidget(self.size_label)
        self.rbf_label = TxDetailLabel()
        vbox_right.addWidget(self.rbf_label)
        self.locktime_label = TxDetailLabel()
        vbox_right.addWidget(self.locktime_label)
        self.block_hash_label = TxDetailLabel(word_wrap=True)
        vbox_right.addWidget(self.block_hash_label)
        self.block_height_label = TxDetailLabel()
        vbox_right.addWidget(self.block_height_label)
        vbox_right.addStretch(1)
        hbox_stats.addLayout(vbox_right, 50)

        vbox.addLayout(hbox_stats)
Example #38
0
class Search(plugin.MainWindowPlugin, QWidget):
    def __init__(self, mainwindow):
        QWidget.__init__(self, mainwindow)
        self._currentView = None
        self._positions = []
        self._positionsDirty = True
        self._replace = False  # are we in replace mode?
        self._going = False    # are we moving the text cursor?
        
        mainwindow.currentViewChanged.connect(self.viewChanged)
        mainwindow.actionCollection.edit_find_next.triggered.connect(self.findNext)
        mainwindow.actionCollection.edit_find_previous.triggered.connect(self.findPrevious)
        
        # don't inherit looks from view
        self.setFont(QApplication.font())
        self.setPalette(QApplication.palette())
        
        grid = QGridLayout(spacing=2)
        grid.setContentsMargins(4, 0, 4, 0)
        grid.setVerticalSpacing(0)
        self.setLayout(grid)
        
        self.searchEntry = QLineEdit(textChanged=self.slotSearchChanged)
        self.searchLabel = QLabel()
        self.prevButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus, clicked=self.findPrevious)
        self.prevButton.setIcon(icons.get('go-previous'))
        self.nextButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus, clicked=self.findNext)
        self.nextButton.setIcon(icons.get('go-next'))
        self.caseCheck = QCheckBox(checked=True, focusPolicy=Qt.NoFocus)
        self.regexCheck = QCheckBox(focusPolicy=Qt.NoFocus)
        self.countLabel = QLabel(alignment=Qt.AlignRight | Qt.AlignVCenter)
        self.countLabel.setMinimumWidth(QApplication.fontMetrics().width("9999"))
        self.closeButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus)
        self.hideAction = QAction(self, triggered=self.slotHide)
        self.hideAction.setShortcut(QKeySequence(Qt.Key_Escape))
        self.hideAction.setIcon(self.style().standardIcon(QStyle.SP_DialogCloseButton))
        self.closeButton.setDefaultAction(self.hideAction)
        
        grid.addWidget(self.searchLabel, 0, 0)
        grid.addWidget(self.searchEntry, 0, 1)
        grid.addWidget(self.prevButton, 0, 2)
        grid.addWidget(self.nextButton, 0, 3)
        grid.addWidget(self.caseCheck, 0, 4)
        grid.addWidget(self.regexCheck, 0, 5)
        grid.addWidget(self.countLabel, 0, 6)
        grid.addWidget(self.closeButton, 0, 7)
        
        self.caseCheck.toggled.connect(self.slotSearchChanged)
        self.regexCheck.toggled.connect(self.slotSearchChanged)
        
        self.replaceEntry = QLineEdit()
        self.replaceLabel = QLabel()
        self.replaceButton = QPushButton(clicked=self.slotReplace)
        self.replaceAllButton = QPushButton(clicked=self.slotReplaceAll)
        
        grid.addWidget(self.replaceLabel, 1, 0)
        grid.addWidget(self.replaceEntry, 1, 1)
        grid.addWidget(self.replaceButton, 1, 4)
        grid.addWidget(self.replaceAllButton, 1, 5)
        
        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        app.translateUI(self)
        
    def translateUI(self):
        self.searchLabel.setText(_("Search:"))
        self.prevButton.setToolTip(_("Find Previous"))
        self.nextButton.setToolTip(_("Find Next"))
        self.caseCheck.setText(_("&Case"))
        self.caseCheck.setToolTip(_("Case Sensitive"))
        self.regexCheck.setText(_("&Regex"))
        self.regexCheck.setToolTip(_("Regular Expression"))
        self.countLabel.setToolTip(_("The total number of matches"))
        self.hideAction.setToolTip(_("Close"))
        self.replaceLabel.setText(_("Replace:"))
        self.replaceButton.setText(_("Re&place"))
        self.replaceButton.setToolTip(_("Replaces the next occurrence of the search term."))
        self.replaceAllButton.setText(_("&All"))
        self.replaceAllButton.setToolTip(_("Replaces all occurrences of the search term in the document or selection."))
    
    def readSettings(self):
        data = textformats.formatData('editor')
        self.searchEntry.setFont(data.font)
        self.replaceEntry.setFont(data.font)
        p = data.palette()
        self.searchEntry.setPalette(p)
        self.replaceEntry.setPalette(p)
         
    def currentView(self):
        """Return the currently active View."""
        return self._currentView and self._currentView()
    
    def setCurrentView(self, view):
        """Set the currently active View, called by showWidget()."""
        cur = self.currentView()
        if cur:
            cur.selectionChanged.disconnect(self.slotSelectionChanged)
            cur.document().contentsChanged.disconnect(self.slotDocumentContentsChanged)
        if view:
            view.selectionChanged.connect(self.slotSelectionChanged)
            view.document().contentsChanged.connect(self.slotDocumentContentsChanged)
        self._currentView = weakref.ref(view) if view else None
    
    def showWidget(self):
        """Show the search widget and connect with the active View."""
        if self.isVisible():
            self.hideWidget()
        view = self.window().currentView()
        self.setCurrentView(view)
        layout = gadgets.borderlayout.BorderLayout.get(view)
        layout.addWidget(self, gadgets.borderlayout.BOTTOM)
        self.show()
        
    def hideWidget(self):
        """Hide the widget, but remain connected with the active View."""
        view = self.currentView()
        if view:
            self.highlightingOff()
            self.hide()
            layout = gadgets.borderlayout.BorderLayout.get(view)
            layout.removeWidget(self)
    
    def viewChanged(self, new):
        """Called when the user switches to another View."""
        self.setParent(None)
        self.hideWidget()
        self.setCurrentView(new)
        self.markPositionsDirty()
    
    def slotSelectionChanged(self):
        """Called when the user changes the selection."""
        if not self._going:
            self.markPositionsDirty()
            if self.isVisible():
                self.updatePositions()
                self.highlightingOn()

    def slotDocumentContentsChanged(self):
        """Called when the current document changes."""
        self.markPositionsDirty()
        if self.isVisible():
            self.updatePositions()
            self.highlightingOn()
        
    def slotHide(self):
        """Called when the close button is clicked."""
        view = self.currentView()
        if view:
            self.hideWidget()
            view.setFocus()
        
    def find(self):
        """Called by the main menu Find... command."""
        # hide replace stuff
        self.replaceLabel.hide()
        self.replaceEntry.hide()
        self.replaceButton.hide()
        self.replaceAllButton.hide()
        self._replace = False # we are not in replace mode
        visible = self.isVisible()
        if not visible:
            self.showWidget()
        else:
            self.adjustSize()
        cursor = self.currentView().textCursor()
        #if not visible and self.currentView():
        if cursor.hasSelection():
            word = cursor.selection().toPlainText()
            if not re.search(r'\w', word):
                word = ""
            elif self.regexCheck.isChecked():
                word = re.escape(word)
            with qutil.signalsBlocked(self.searchEntry):
                self.searchEntry.setText(word)
            self.slotSearchChanged()
        else:
            self.searchEntry.selectAll()
            self.highlightingOn()
        self.searchEntry.setFocus()
        
    def replace(self):
        """Called by the main menu Find and Replace... command."""
        # show replace stuff
        self.replaceLabel.show()
        self.replaceEntry.show()
        self.replaceButton.show()
        self.replaceAllButton.show()
        focus = self.replaceEntry if self.isVisible() and self.searchEntry.text() else self.searchEntry
        self._replace = True # we are in replace mode
        if self.isVisible():
            self.adjustSize()
        else:
            self.showWidget()
            self.markPositionsDirty()
            self.updatePositions()
            self.highlightingOn()
        focus.setFocus()
        
    def slotSearchChanged(self):
        """Called on every change in the search text entry."""
        self._going = True
        self.markPositionsDirty()
        self.updatePositions()
        self.highlightingOn()
        if not self._replace and self._positions:
            positions = [c.position() for c in self._positions]
            cursor = self.currentView().textCursor()
            index = bisect.bisect_left(positions, cursor.selectionStart())
            if index == len(positions):
                index -= 1
            elif index > 0:
                # it might be possible that the text cursor currently already
                # is in a search result. This happens when the search is pop up
                # with an empty text and the current word is then set as search
                # text.
                if cursortools.contains(self._positions[index-1], cursor):
                    index -= 1
            self.gotoPosition(index)
        self._going = False

    def highlightingOn(self, view=None):
        """Show the current search result positions."""
        if view is None:
            view = self.currentView()
        if view:
            viewhighlighter.highlighter(view).highlight("search", self._positions, 1)
    
    def highlightingOff(self, view=None):
        """Hide the current search result positions."""
        if view is None:
            view = self.currentView()
        if view:
            viewhighlighter.highlighter(view).clear("search")
            
    def markPositionsDirty(self):
        """Delete positions and mark them dirty, i.e. they need updating."""
        self._positions = []
        self._positionsDirty = True
    
    def updatePositions(self):
        """Update the search result positions if necessary."""
        view = self.currentView()
        if not view or not self._positionsDirty:
            return
        search = self.searchEntry.text()
        cursor = view.textCursor()
        document = view.document()
        self._positions = []
        if search:
            text = document.toPlainText()
            start = 0
            if (self._replace or not self._going) and cursor.hasSelection():
                # don't search outside the selection
                start = cursor.selectionStart()
                text = text[start:cursor.selectionEnd()]
            flags = re.MULTILINE | re.DOTALL
            if not self.caseCheck.isChecked():
                flags |= re.IGNORECASE
            if not self.regexCheck.isChecked():
                search = re.escape(search)
            try:
                matches = re.finditer(search, text, flags)
            except re.error:
                pass
            else:
                for m in matches:
                    c = QTextCursor(document)
                    c.setPosition(start + m.end())
                    c.setPosition(start + m.start(), QTextCursor.KeepAnchor)
                    self._positions.append(c)
        self.countLabel.setText(format(len(self._positions)))
        enabled = len(self._positions) > 0
        self.replaceButton.setEnabled(enabled)
        self.replaceAllButton.setEnabled(enabled)
        self.prevButton.setEnabled(enabled)
        self.nextButton.setEnabled(enabled)
        self._positionsDirty = False
        
    def findNext(self):
        """Called on menu Find Next."""
        self._going = True
        self.updatePositions()
        view = self.currentView()
        if view and self._positions:
            positions = [c.position() for c in self._positions]
            index = bisect.bisect_right(positions, view.textCursor().position())
            if index < len(positions):
                self.gotoPosition(index)
            else:
                self.gotoPosition(0)
            view.ensureCursorVisible()
        self._going = False

    def findPrevious(self):
        """Called on menu Find Previous."""
        self._going = True
        self.updatePositions()
        view = self.currentView()
        positions = [c.position() for c in self._positions]
        if view and positions:
            index = bisect.bisect_left(positions, view.textCursor().position()) - 1
            self.gotoPosition(index)
        self._going = False
    
    def gotoPosition(self, index):
        """Scrolls the current View to the position in the _positions list at index."""
        c = QTextCursor(self._positions[index])
        #c.clearSelection()
        self.currentView().gotoTextCursor(c)
        self.currentView().ensureCursorVisible()

    def event(self, ev):
        """Reimplemented to catch F1 for help and Tab so it does not reach the View."""
        if ev == QKeySequence.HelpContents:
            userguide.show("search_replace")
            ev.accept()
            return True
        elif ev.type() == QEvent.KeyPress:
            modifiers = int(ev.modifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
            if ev.key() == Qt.Key_Tab and modifiers == 0:
                # prevent Tab from reaching the View widget
                self.window().focusNextChild()
                ev.accept()
                return True
            elif ev.key() == Qt.Key_Backtab and modifiers & ~Qt.SHIFT == 0:
                # prevent Tab from reaching the View widget
                self.window().focusPreviousChild()
                ev.accept()
                return True
        return super(Search, self).event(ev)
        
    def keyPressEvent(self, ev):
        """Catches Up and Down to jump between search results."""
        # if in search mode, Up and Down jump between search results
        if not self._replace and self._positions and self.searchEntry.text() and not ev.modifiers():
            if ev.key() == Qt.Key_Up:
                self.findPrevious()
                return
            elif ev.key() ==  Qt.Key_Down:
                self.findNext()
                return
        # use enter or return for search next
        if ev.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.findNext()
            return
        super(Search, self).keyPressEvent(ev)

    def doReplace(self, cursor):
        """Perform one replace action."""
        text = cursor.selection().toPlainText()
        search = self.searchEntry.text()
        replace = self.replaceEntry.text()
        ok = text == search
        if self.regexCheck.isChecked():
            m = re.match(search, text)
            ok = False
            if m:
                try:
                    replace = m.expand(replace)
                    ok = True
                except re.error:
                    pass
        if ok:
            pos = cursor.position()
            cursor.insertText(replace)
            cursor.setPosition(pos, QTextCursor.KeepAnchor)
        return ok
        
    def slotReplace(self):
        """Called when the user clicks Replace."""
        view = self.currentView()
        if view and self._positions:
            positions = [c.position() for c in self._positions]
            index = bisect.bisect_left(positions, view.textCursor().position())
            if index >= len(positions):
                index = 0
            if self.doReplace(self._positions[index]):
                self.findNext()
    
    def slotReplaceAll(self):
        """Called when the user clicks Replace All."""
        view = self.currentView()
        if view:
            replaced = False
            cursors = self._positions
            if view.textCursor().hasSelection():
                cursors = [cursor for cursor in cursors if cursortools.contains(view.textCursor(), cursor)]
            with cursortools.compress_undo(view.textCursor()):
                for cursor in cursors:
                    if self.doReplace(cursor):
                        replaced = True
            if replaced:
                self.highlightingOn()
Example #39
0
 def __init__(self, mainwindow):
     QWidget.__init__(self, mainwindow)
     self._currentView = None
     self._positions = []
     self._positionsDirty = True
     self._replace = False  # are we in replace mode?
     self._going = False    # are we moving the text cursor?
     
     mainwindow.currentViewChanged.connect(self.viewChanged)
     mainwindow.actionCollection.edit_find_next.triggered.connect(self.findNext)
     mainwindow.actionCollection.edit_find_previous.triggered.connect(self.findPrevious)
     
     # don't inherit looks from view
     self.setFont(QApplication.font())
     self.setPalette(QApplication.palette())
     
     grid = QGridLayout(spacing=2)
     grid.setContentsMargins(4, 0, 4, 0)
     grid.setVerticalSpacing(0)
     self.setLayout(grid)
     
     self.searchEntry = QLineEdit(textChanged=self.slotSearchChanged)
     self.searchLabel = QLabel()
     self.prevButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus, clicked=self.findPrevious)
     self.prevButton.setIcon(icons.get('go-previous'))
     self.nextButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus, clicked=self.findNext)
     self.nextButton.setIcon(icons.get('go-next'))
     self.caseCheck = QCheckBox(checked=True, focusPolicy=Qt.NoFocus)
     self.regexCheck = QCheckBox(focusPolicy=Qt.NoFocus)
     self.countLabel = QLabel(alignment=Qt.AlignRight | Qt.AlignVCenter)
     self.countLabel.setMinimumWidth(QApplication.fontMetrics().width("9999"))
     self.closeButton = QToolButton(autoRaise=True, focusPolicy=Qt.NoFocus)
     self.hideAction = QAction(self, triggered=self.slotHide)
     self.hideAction.setShortcut(QKeySequence(Qt.Key_Escape))
     self.hideAction.setIcon(self.style().standardIcon(QStyle.SP_DialogCloseButton))
     self.closeButton.setDefaultAction(self.hideAction)
     
     grid.addWidget(self.searchLabel, 0, 0)
     grid.addWidget(self.searchEntry, 0, 1)
     grid.addWidget(self.prevButton, 0, 2)
     grid.addWidget(self.nextButton, 0, 3)
     grid.addWidget(self.caseCheck, 0, 4)
     grid.addWidget(self.regexCheck, 0, 5)
     grid.addWidget(self.countLabel, 0, 6)
     grid.addWidget(self.closeButton, 0, 7)
     
     self.caseCheck.toggled.connect(self.slotSearchChanged)
     self.regexCheck.toggled.connect(self.slotSearchChanged)
     
     self.replaceEntry = QLineEdit()
     self.replaceLabel = QLabel()
     self.replaceButton = QPushButton(clicked=self.slotReplace)
     self.replaceAllButton = QPushButton(clicked=self.slotReplaceAll)
     
     grid.addWidget(self.replaceLabel, 1, 0)
     grid.addWidget(self.replaceEntry, 1, 1)
     grid.addWidget(self.replaceButton, 1, 4)
     grid.addWidget(self.replaceAllButton, 1, 5)
     
     app.settingsChanged.connect(self.readSettings)
     self.readSettings()
     app.translateUI(self)
Example #40
0
 def addButton(self, icon_name, on_click, tooltip):
     button = QToolButton(self)
     button.setIcon(read_QIcon(icon_name))
     button.setIconSize(QSize(25,25))
     button.setCursor(QCursor(Qt.PointingHandCursor))
     button.setStyleSheet("QToolButton { border: none; hover {border: 1px} pressed {border: 1px} padding: 0px; }")
     button.setVisible(True)
     button.setToolTip(tooltip)
     button.clicked.connect(on_click)
     self.buttons.append(button)
     return button
Example #41
0
 def add_camera_entry_to_recent(self, p: Path):
     if not self.startup_page_ui.label_noRecentCameras.isHidden():
         self.startup_page_ui.label_noRecentCameras.hide()
         self.startup_page_ui.verticalLayout_recentCameras.removeWidget(self.startup_page_ui.label_noRecentCameras)
     if p not in self.recent_cameras:
         self.recent_cameras.insert(0, p)
         action = QAction(str(p.name))
         action.setToolTip(str(p))
         self.recent_cameras_qactions[str(p)] = action
         if len(self.recent_cameras_menu.actions()) > 0:
             self.recent_cameras_menu.insertAction(self.recent_cameras_menu.actions()[0], action)
         else:
             self.recent_cameras_menu.addAction(action)
         btn = QToolButton()
         btn.setDefaultAction(action)
         btn.setStyleSheet('font-size: 12pt')
         btn.setText(str(p.name))
         btn.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
         self.startup_camera_buttons.insert(0, btn)
         self.startup_page_ui.label_noRecentCameras.hide()
         self.startup_page_ui.verticalLayout_recentCameras.insertWidget(0, btn)
     else:
         action_idx = self.recent_cameras_menu.actions().index(self.recent_cameras_qactions[str(p)])
         btn = self.startup_page_ui.verticalLayout_recentCameras.itemAt(action_idx).widget() #self.startup_page_ui.verticalLayout_recentCameras.removeItem(btn)
         self.startup_page_ui.verticalLayout_recentCameras.removeWidget(btn)
         self.startup_page_ui.verticalLayout_recentCameras.insertWidget(0, btn)
         self.recent_cameras.remove(p)
         self.recent_cameras.insert(0, p)
         self.recent_cameras_menu.clear()
         for i in range(self.startup_page_ui.verticalLayout_recentCameras.count()):
             btn: QToolButton = self.startup_page_ui.verticalLayout_recentCameras.itemAt(i).widget()
             self.recent_cameras_menu.addAction(btn.defaultAction())
     if len(self.recent_cameras) > 10:
         self.remove_camera_entry_from_recent(self.recent_cameras[-1])
Example #42
0
    def createToolbarMenus(self):
        self.menuToolBar = QToolBar()

        viewMenu = QToolButton()
        viewMenu.setText('View')
        viewMenu.setPopupMode(QToolButton.MenuButtonPopup)
        aMenu = QMenu()
        aMenu.addAction(self.zoomInAct)
        aMenu.addAction(self.zoomOutAct)
        aMenu.addAction(self.normalSizeAct)
        aMenu.addSeparator()
        aMenu.addAction(self.fitToWindowAct)
        viewMenu.setMenu(aMenu)

        helpMenu = QToolButton()
        helpMenu.setText('Help')
        helpMenu.setPopupMode(QToolButton.MenuButtonPopup)
        bMenu = QMenu()
        bMenu.addAction(self.aboutAct)
        helpMenu.setMenu(bMenu)

        self.menuToolBar.addWidget(viewMenu)
        self.menuToolBar.addWidget(helpMenu)
Example #43
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)

        vbox.addWidget(QLabel(_("Transaction ID:")))
        self.tx_hash_e = ButtonsLineEdit()
        qr_show = lambda: parent.show_qrcode(
            str(self.tx_hash_e.text()), 'Transaction ID', parent=self)
        qr_icon = "qrcode_white.png" if ColorScheme.dark_scheme else "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.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.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._ptx_join_txs_action = QAction(_("Join inputs/outputs"), self)
        self._ptx_join_txs_action.triggered.connect(self.join_tx_with_another)
        partial_tx_actions_menu.addAction(self._ptx_join_txs_action)
        self.partial_tx_actions_button = QToolButton()
        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)
Example #44
0
class PlayerControls(QWidget):

    play = pyqtSignal()
    pause = pyqtSignal()
    stop = pyqtSignal()
    next = pyqtSignal()
    previous = pyqtSignal()
    changeVolume = pyqtSignal(int)
    changeRate = pyqtSignal(float)

    def __init__(self, parent=None):
        super(PlayerControls, self).__init__(parent)

        self.playerState = QMediaPlayer.StoppedState

        self.playButton = QToolButton(clicked=self.playClicked)
        self.playButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

        self.stopButton = QToolButton(clicked=self.stop)
        self.stopButton.setIcon(self.style().standardIcon(QStyle.SP_MediaStop))
        self.stopButton.setEnabled(False)

        self.nextButton = QToolButton(clicked=self.next)
        self.nextButton.setIcon(
                self.style().standardIcon(QStyle.SP_MediaSkipForward))

        self.previousButton = QToolButton(clicked=self.previous)
        self.previousButton.setIcon(
                self.style().standardIcon(QStyle.SP_MediaSkipBackward))

        self.volumeSlider = QSlider(Qt.Horizontal,
                sliderMoved=self.changeVolume)
        self.volumeSlider.setRange(0, 100)

        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(self.stopButton)
        layout.addWidget(self.previousButton)
        layout.addWidget(self.playButton)
        layout.addWidget(self.nextButton)
        layout.addWidget(self.volumeSlider)
        self.setLayout(layout)

    def state(self):
        return self.playerState

    def setState(self,state):
        if state != self.playerState:
            self.playerState = state

            if state == QMediaPlayer.StoppedState:
                self.stopButton.setEnabled(False)
                self.playButton.setIcon(
                        self.style().standardIcon(QStyle.SP_MediaPlay))
            elif state == QMediaPlayer.PlayingState:
                self.stopButton.setEnabled(True)
                self.playButton.setIcon(
                        self.style().standardIcon(QStyle.SP_MediaPause))
            elif state == QMediaPlayer.PausedState:
                self.stopButton.setEnabled(True)
                self.playButton.setIcon(
                        self.style().standardIcon(QStyle.SP_MediaPlay))

    def volume(self):
        return self.volumeSlider.value()

    def setVolume(self, volume):
        self.volumeSlider.setValue(volume)

    def playClicked(self):
        if self.playerState in (QMediaPlayer.StoppedState, QMediaPlayer.PausedState):
            self.play.emit()
        elif self.playerState == QMediaPlayer.PlayingState:
            self.pause.emit()
Example #45
0
class SutdaGame(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.user_info = []
        self.sutda = Sutda()

        self.log = ""
        self.information = {}
        self.get_paeButton = QToolButton()
        self.get_paeButton.setText("패 받기")
        self.get_paeButton.clicked.connect(self.Get_card)
        self.get_paeButton.setFixedSize(105, 50)
        self.get_paeButton.setEnabled(False)

        left_Layout = QGridLayout()
        left_Layout.addWidget(self.get_paeButton, 2, 0)
        cpuDeck = QGridLayout()
        self.computer_pae1 = QLabel(self)
        self.computer_pae2 = QLabel(self)
        self.default = QPixmap('IMG/back.png')
        self.computer_pae1.setPixmap(self.default)
        self.computer_pae2.setPixmap(self.default)
        cpuDeck.addWidget(self.computer_pae1, 0, 0)
        cpuDeck.addWidget(self.computer_pae2, 0, 1)
        left_Layout.addLayout(cpuDeck, 1, 0)

        cpu = QGridLayout()
        self.cpuLabel = QLabel("CPU")
        font = self.cpuLabel.font()
        font.setPointSize(font.pointSize() + 8)
        font.setBold(True)
        font.setFamily('Courier New')
        self.cpuLabel.setAlignment(Qt.AlignTop)
        self.cpuLabel.setFont(font)
        self.cpuResult = QLineEdit()
        self.cpuResult.setReadOnly(True)
        self.cpuResult.setFixedWidth(100)
        self.cpuResult.setAlignment(Qt.AlignCenter)
        cpu.addWidget(self.cpuLabel, 0, 0)
        cpu.addWidget(self.cpuResult, 1, 0)
        left_Layout.addLayout(cpu, 1, 2)

        userDeck = QGridLayout()
        self.user_pae1 = QLabel(self)
        self.user_pae2 = QLabel(self)
        self.user_pae1.setPixmap(self.default)
        self.user_pae2.setPixmap(self.default)
        userDeck.addWidget(self.user_pae1, 0, 0)
        userDeck.addWidget(self.user_pae2, 0, 1)
        left_Layout.addLayout(userDeck, 3, 0)

        user = QGridLayout()
        self.userLabel = QLabel("Player")
        font = self.userLabel.font()
        font.setPointSize(font.pointSize() + 8)
        font.setBold(True)
        font.setFamily('Courier New')
        self.userLabel.setAlignment(Qt.AlignTop)
        self.userLabel.setFont(font)
        self.userResult = QLineEdit()
        self.userResult.setReadOnly(True)
        self.userResult.setFixedWidth(100)
        self.userResult.setAlignment(Qt.AlignCenter)
        user.addWidget(self.userLabel, 0, 0)
        user.addWidget(self.userResult, 1, 0)
        left_Layout.addLayout(user, 3, 2)

        # left_money
        self.lbLefted = QLabel("보유 금액 :")
        self.lbLefted.setAlignment(Qt.AlignRight)
        self.left_money = QLineEdit()
        self.left_money.setReadOnly(True)
        self.left_money.setAlignment(Qt.AlignRight)
        self.lefted_money = 1000000
        self.left_money.setText(str(self.lefted_money))
        self.left_money.setFixedWidth(105)

        self.name_edit = QLineEdit()

        self.name_edit.setAlignment(Qt.AlignRight)

        left_Layout.addWidget(self.left_money, 0, 2)
        left_Layout.addWidget(self.lbLefted, 0, 0)

        betLayout = QGridLayout()
        self.btn_Betting = QToolButton()
        self.btn_Betting.setText("BETTING")
        self.btn_Betting.setEnabled(False)

        # self.start_btn.clicked.connect()

        self.btn_Die = QToolButton()
        self.btn_Die.setText("DIE")
        self.btn_Die.setEnabled(False)

        # self.btn_Die.clicked.connect()
        betLayout.addWidget(self.btn_Betting, 0, 0)
        betLayout.addWidget(self.btn_Die, 1, 0)
        left_Layout.addLayout(betLayout, 2, 2)

        self.btn_Save = QToolButton()
        self.btn_Save.setText("SAVE")
        self.btn_Save.clicked.connect(self.save)

        self.btn_Login = QToolButton()
        self.btn_Login.setText("Login")
        self.btn_Login.clicked.connect(self.start_game)

        self.btn_Ranking = QToolButton()
        self.btn_Ranking.setText("Rank")
        self.btn_Ranking.clicked.connect(self.ranking)

        self.logBox = QTextEdit()
        self.logBox.setReadOnly(True)
        self.lblog = QLabel("--log--")
        self.lblog.setAlignment(Qt.AlignCenter)

        right_layout = QGridLayout()

        right_layout.addWidget(self.name_edit, 0, 0)
        right_layout.addWidget(self.btn_Save, 0, 2)
        right_layout.addWidget(self.btn_Login, 0, 1)
        right_layout.addWidget(self.btn_Ranking, 0, 3)
        right_layout.addWidget(self.lblog, 1, 0, 1, 4)
        right_layout.addWidget(self.logBox, 2, 0, 3, 4)

        self.rank_Edit = QTextEdit()
        self.rank_Edit.setReadOnly(True)
        self.rank_Rabel = QLabel("--Rank--")
        self.rank_Rabel.setAlignment(Qt.AlignCenter)
        self.rank_Edit.setText(self.ranking())

        rank_layout = QGridLayout()
        rank_layout.addWidget(self.rank_Edit, 1, 0)
        rank_layout.addWidget(self.rank_Rabel, 0, 0)
        self.ranking()
        # Layout placement
        mainLayout = QGridLayout()
        self.setWindowTitle("Sutda")
        # mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        mainLayout.addLayout(left_Layout, 0, 0)
        mainLayout.addLayout(right_layout, 0, 1)
        mainLayout.addLayout(rank_layout, 0, 2)
        self.setLayout(mainLayout)
        self.btn_Die.clicked.connect(self.dieClicked)
        self.btn_Betting.clicked.connect(self.bettingClicked)
        self.ranking()

    def Get_card(self):

        self.user_pae1.setPixmap(self.default)
        self.user_pae2.setPixmap(self.default)
        time.sleep(0.5)
        self.computer_pae1.setPixmap(self.default)
        self.computer_pae2.setPixmap(self.default)
        self.userResult.clear()
        self.cpuResult.clear()

        self.get_paeButton.setEnabled(False)
        self.btn_Betting.setEnabled(True)
        self.btn_Die.setEnabled(True)
        self.cardMap = getCard()
        upae1 = QPixmap(cards[self.cardMap["player"][0]]['img'])
        upae2 = QPixmap(cards[self.cardMap["player"][1]]['img'])
        self.user_pae1.setPixmap(upae1)
        self.user_pae2.setPixmap(upae2)
        self.uR = self.sutda.checkDeck(self.cardMap["player"])
        self.cR = self.sutda.checkDeck(self.cardMap["cpu"])
        self.userResult.setText(self.uR)

    def dieClicked(self):
        now = datetime.datetime.now()
        nowtime = now.strftime('[%H:%M:%S]')
        self.log = nowtime + "다이!    내 패: " + self.uR + "\n              잃은 금액:" + str(
            int(self.lefted_money * 0.1)) + "원\n" + self.log
        self.lefted_money = int(self.lefted_money - self.lefted_money * 0.1)
        if self.lefted_money < 100000:
            self.lefted_money += 300000
            self.log = nowtime + "보유 금액이 10만원 미만이 되어 지원금\n              30만원을 지급합니다! " + "\n              얻은 금액: 300000원" + "\n" + self.log
        self.left_money.setText(str(self.lefted_money))
        self.logBox.setText(self.log)
        self.btn_Die.setEnabled(False)
        self.btn_Betting.setEnabled(False)
        self.get_paeButton.setEnabled(True)

    def bettingClicked(self):
        now = datetime.datetime.now()
        nowtime = now.strftime('[%H:%M:%S]')
        cpae1 = QPixmap(cards[self.cardMap["cpu"][0]]['img'])
        cpae2 = QPixmap(cards[self.cardMap["cpu"][1]]['img'])
        self.computer_pae1.setPixmap(cpae1)
        self.computer_pae2.setPixmap(cpae2)

        result = self.sutda.checkWin([self.cR, self.uR])
        self.cpuResult.setText(self.cR)
        time.sleep(0.5)
        if result == 'win':
            self.log = nowtime + "승리!    내 패: " + self.uR + ", 상대 패: " + self.cR + "\n              얻은 금액:" + str(
                int(self.lefted_money * 0.2)) + "원\n" + self.log
            self.lefted_money += int(self.lefted_money * 0.2)
        elif result == 'draw':
            self.log = nowtime + "재경기! 내 패: " + self.uR + ", 상대 패: " + self.cR + "\n" + self.log
        elif result == 'lose':
            self.log = nowtime + "패배!    내 패: " + self.uR + ", 상대 패: " + self.cR + "\n              잃은 금액:" + str(
                int(self.lefted_money * 0.2)) + "원\n" + self.log
            self.lefted_money -= int(self.lefted_money * 0.2)

        if self.lefted_money < 100000:
            self.lefted_money += 300000
            self.log = nowtime + "보유 금액이 10만원 미만이 되어 지원금\n              30만원을 지급합니다! " + "\n              얻은 금액: 300000원" + "\n" + self.log
        self.left_money.setText(str(self.lefted_money))
        self.btn_Die.setEnabled(False)
        self.btn_Betting.setEnabled(False)
        self.get_paeButton.setEnabled(True)
        self.logBox.setText(self.log)

    def start_game(self):
        if self.name_edit.text() == "":
            pass
        else:
            self.name_edit.setReadOnly(True)
            self.get_paeButton.setEnabled(True)
            f = open('user_info.txt', 'r', encoding='UTF8')
            lines = f.readlines()
            f.close()
            information = {}
            self.count = 0

            for line in lines:
                try:
                    line1 = line.split(" ")
                    information[line1[0]] = line1[1]
                except:
                    continue

            info_list = [*information]  #key list
            if self.name_edit.text() in info_list:
                length = len(information[self.name_edit.text()].rstrip())
                self.left_money.setText(
                    information[self.name_edit.text()].rstrip())
                tmp = information[self.name_edit.text()][0:length - 1]
                self.lefted_money = int(tmp)
            else:
                self.lefted_money = 1000000
                self.left_money.setText("1000000")

            #if self.name_edit.text() in info_list:
            #    self.left_money.setText(info_dic[self.name_edit.text()])

    def save(self):
        #try:

        f = open('user_info.txt', 'r', encoding='UTF8')
        lines = f.readlines()
        f.close()
        self.information = {}
        self.count = 0

        if len(self.name_edit.text()) != 0:
            for line in lines:
                try:
                    line1 = line.split(" ")
                    self.information[line1[0]] = line1[1]
                except:
                    continue
            self.information[self.name_edit.text()] = str(self.lefted_money)

            f = open('user_info.txt', 'w', encoding='UTF8')
            info_list = [*self.information]

            for key, val in self.information.items():
                try:
                    f.write(key + " " + val + "\n")
                except:
                    continue
        else:
            pass
        f.close()
        self.name_edit.setReadOnly(False)
        self.name_edit.setText("")
        self.get_paeButton.setEnabled(False)

        return self.information

    def ranking(self):
        f = open('user_info.txt', 'r', encoding='UTF8')
        lines = f.readlines()
        f.close()
        information = {}

        for line in lines:
            try:
                line1 = line.split(" ")
                information[line1[0]] = int(line1[1])
            except:
                continue

        sort_dic = [
            (k, information[k])
            for k in sorted(information, key=information.get, reverse=True)
        ]

        rank_str = ""
        cnt = 1
        for key, val in sort_dic:
            rank_str += str(cnt) + "등  " + key + "  보유금액 :" + str(val) + "\n"
            cnt += 1
        self.rank_Edit.setText(rank_str)
Example #46
0
class BaseTxDialog(QDialog, MessageBoxMixin):
    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)

        vbox.addWidget(QLabel(_("Transaction ID:")))
        self.tx_hash_e = ButtonsLineEdit()
        qr_show = lambda: parent.show_qrcode(
            str(self.tx_hash_e.text()), 'Transaction ID', parent=self)
        qr_icon = "qrcode_white.png" if ColorScheme.dark_scheme else "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.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.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._ptx_join_txs_action = QAction(_("Join inputs/outputs"), self)
        self._ptx_join_txs_action.triggered.connect(self.join_tx_with_another)
        partial_tx_actions_menu.addAction(self._ptx_join_txs_action)
        self.partial_tx_actions_button = QToolButton()
        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)

    def set_buttons_visibility(self):
        for b in [
                self.export_actions_button, self.save_button, self.sign_button,
                self.broadcast_button, self.partial_tx_actions_button
        ]:
            b.setVisible(self.finalized)
        for b in [self.finalize_button]:
            b.setVisible(not self.finalized)

    def set_tx(self, tx: 'Transaction'):
        # Take a copy; it might get updated in the main window by
        # e.g. the FX plugin.  If this happens during or after a long
        # sign operation the signatures are lost.
        self.tx = tx = copy.deepcopy(tx)
        try:
            self.tx.deserialize()
        except BaseException as e:
            raise SerializationError(e)
        # If the wallet can populate the inputs with more info, do it now.
        # As a result, e.g. we might learn an imported address tx is segwit,
        # or that a beyond-gap-limit address is is_mine.
        # note: this might fetch prev txs over the network.
        tx.add_info_from_wallet(self.wallet)

    def do_broadcast(self):
        self.main_window.push_top_level_window(self)
        try:
            self.main_window.broadcast_transaction(self.tx)
        finally:
            self.main_window.pop_top_level_window(self)
        self.saved = True
        self.update()

    def closeEvent(self, event):
        if (self.prompt_if_unsaved and not self.saved and not self.question(
                _('This transaction is not saved. Close anyway?'),
                title=_("Warning"))):
            event.ignore()
        else:
            event.accept()
            try:
                dialogs.remove(self)
            except ValueError:
                pass  # was not in list already

    def reject(self):
        # Override escape-key to close normally (and invoke closeEvent)
        self.close()

    def add_export_actions_to_menu(
            self,
            menu: QMenu,
            *,
            gettx: Callable[[], Transaction] = None) -> None:
        if gettx is None:
            gettx = lambda: None

        action = QAction(_("Copy to clipboard"), self)
        action.triggered.connect(lambda: self.copy_to_clipboard(tx=gettx()))
        menu.addAction(action)

        qr_icon = "qrcode_white.png" if ColorScheme.dark_scheme else "qrcode.png"
        action = QAction(read_QIcon(qr_icon), _("Show as QR code"), self)
        action.triggered.connect(lambda: self.show_qr(tx=gettx()))
        menu.addAction(action)

        action = QAction(_("Export to file"), self)
        action.triggered.connect(lambda: self.export_to_file(tx=gettx()))
        menu.addAction(action)

    def _gettx_for_coinjoin(self) -> PartialTransaction:
        if not isinstance(self.tx, PartialTransaction):
            raise Exception(
                "Can only export partial transactions for coinjoins.")
        tx = copy.deepcopy(self.tx)
        tx.prepare_for_export_for_coinjoin()
        return tx

    def _gettx_for_hardware_device(self) -> PartialTransaction:
        if not isinstance(self.tx, PartialTransaction):
            raise Exception(
                "Can only export partial transactions for hardware device.")
        tx = copy.deepcopy(self.tx)
        tx.add_info_from_wallet(self.wallet, include_xpubs_and_full_paths=True)
        # log warning if PSBT_*_BIP32_DERIVATION fields cannot be filled with full path due to missing info
        from electrum.keystore import Xpub

        def is_ks_missing_info(ks):
            return (isinstance(ks, Xpub)
                    and (ks.get_root_fingerprint() is None
                         or ks.get_derivation_prefix() is None))

        if any([is_ks_missing_info(ks) for ks in self.wallet.get_keystores()]):
            _logger.warning(
                'PSBT was requested to be filled with full bip32 paths but '
                'some keystores lacked either the derivation prefix or the root fingerprint'
            )
        return tx

    def copy_to_clipboard(self, *, tx: Transaction = None):
        if tx is None:
            tx = self.tx
        self.main_window.do_copy(str(tx), title=_("Transaction"))

    def show_qr(self, *, tx: Transaction = None):
        if tx is None:
            tx = self.tx
        tx = copy.deepcopy(tx)  # make copy as we mutate tx
        if isinstance(tx, PartialTransaction):
            # this makes QR codes a lot smaller (or just possible in the first place!)
            tx.convert_all_utxos_to_witness_utxos()
        text = tx.serialize_as_bytes()
        text = base_encode(text, base=43)
        try:
            self.main_window.show_qrcode(text, 'Transaction', parent=self)
        except qrcode.exceptions.DataOverflowError:
            self.show_error(
                _('Failed to display QR code.') + '\n' +
                _('Transaction is too large in size.'))
        except Exception as e:
            self.show_error(_('Failed to display QR code.') + '\n' + repr(e))

    def sign(self):
        def sign_done(success):
            if self.tx.is_complete():
                self.prompt_if_unsaved = True
                self.saved = False
            self.update()
            self.main_window.pop_top_level_window(self)

        self.sign_button.setDisabled(True)
        self.main_window.push_top_level_window(self)
        self.main_window.sign_tx(self.tx,
                                 callback=sign_done,
                                 external_keypairs=self.external_keypairs)

    def save(self):
        self.main_window.push_top_level_window(self)
        if self.main_window.save_transaction_into_wallet(self.tx):
            self.save_button.setDisabled(True)
            self.saved = True
        self.main_window.pop_top_level_window(self)

    def export_to_file(self, *, tx: Transaction = None):
        if tx is None:
            tx = self.tx
        if isinstance(tx, PartialTransaction):
            tx.finalize_psbt()
        if tx.is_complete():
            name = 'signed_%s' % (tx.txid()[0:8])
            extension = 'txn'
            default_filter = TRANSACTION_FILE_EXTENSION_FILTER_ONLY_COMPLETE_TX
        else:
            name = self.wallet.basename() + time.strftime('-%Y%m%d-%H%M')
            extension = 'psbt'
            default_filter = TRANSACTION_FILE_EXTENSION_FILTER_ONLY_PARTIAL_TX
        name = f'{name}.{extension}'
        fileName = self.main_window.getSaveFileName(
            _("Select where to save your transaction"),
            name,
            TRANSACTION_FILE_EXTENSION_FILTER_SEPARATE,
            default_extension=extension,
            default_filter=default_filter)
        if not fileName:
            return
        if tx.is_complete():  # network tx hex
            with open(fileName, "w+") as f:
                network_tx_hex = tx.serialize_to_network()
                f.write(network_tx_hex + '\n')
        else:  # if partial: PSBT bytes
            assert isinstance(tx, PartialTransaction)
            with open(fileName, "wb+") as f:
                f.write(tx.serialize_as_bytes())

        self.show_message(_("Transaction exported successfully"))
        self.saved = True

    def merge_sigs(self):
        if not isinstance(self.tx, PartialTransaction):
            return
        text = text_dialog(self, _('Input raw transaction'),
                           _("Transaction to merge signatures from") + ":",
                           _("Load transaction"))
        if not text:
            return
        tx = self.main_window.tx_from_text(text)
        if not tx:
            return
        try:
            self.tx.combine_with_other_psbt(tx)
        except Exception as e:
            self.show_error(
                _("Error combining partial transactions") + ":\n" + repr(e))
            return
        self.update()

    def join_tx_with_another(self):
        if not isinstance(self.tx, PartialTransaction):
            return
        text = text_dialog(
            self, _('Input raw transaction'),
            _("Transaction to join with") + " (" +
            _("add inputs and outputs") + "):", _("Load transaction"))
        if not text:
            return
        tx = self.main_window.tx_from_text(text)
        if not tx:
            return
        try:
            self.tx.join_with_other_psbt(tx)
        except Exception as e:
            self.show_error(
                _("Error joining partial transactions") + ":\n" + repr(e))
            return
        self.update()

    def update(self):
        if not self.finalized:
            self.update_fee_fields()
            self.finalize_button.setEnabled(self.tx is not None)
        if self.tx is None:
            return
        self.update_io()
        desc = self.desc
        base_unit = self.main_window.base_unit()
        format_amount = self.main_window.format_amount
        tx_details = self.wallet.get_tx_info(self.tx)
        tx_mined_status = tx_details.tx_mined_status
        exp_n = tx_details.mempool_depth_bytes
        amount, fee = tx_details.amount, tx_details.fee
        # TODO: Move this logic into names.py
        name_fee = 0
        for o in self.tx.outputs():
            if o.name_op is not None:
                name_fee = COIN // 100
        size = self.tx.estimated_size()
        txid = self.tx.txid()
        lnworker_history = self.wallet.lnworker.get_onchain_history(
        ) if self.wallet.lnworker else {}
        if txid in lnworker_history:
            item = lnworker_history[txid]
            ln_amount = item['amount_msat'] / 1000
            if amount is None:
                tx_mined_status = self.wallet.lnworker.lnwatcher.get_tx_height(
                    txid)
        else:
            ln_amount = None
        self.broadcast_button.setEnabled(tx_details.can_broadcast)
        can_sign = not self.tx.is_complete() and \
            (self.wallet.can_sign(self.tx) or bool(self.external_keypairs))
        self.sign_button.setEnabled(can_sign)
        if self.finalized and tx_details.txid:
            self.tx_hash_e.setText(tx_details.txid)
        else:
            # note: when not finalized, RBF and locktime changes do not trigger
            #       a make_tx, so the txid is unreliable, hence:
            self.tx_hash_e.setText(_('Unknown'))
        if desc is None:
            self.tx_desc.hide()
        else:
            self.tx_desc.setText(_("Description") + ': ' + desc)
            self.tx_desc.show()
        self.status_label.setText(_('Status:') + ' ' + tx_details.status)

        if tx_mined_status.timestamp:
            time_str = datetime.datetime.fromtimestamp(
                tx_mined_status.timestamp).isoformat(' ')[:-3]
            self.date_label.setText(_("Date: {}").format(time_str))
            self.date_label.show()
        elif exp_n:
            text = '%.2f MB' % (exp_n / 1000000)
            self.date_label.setText(
                _('Position in mempool: {} from tip').format(text))
            self.date_label.show()
        else:
            self.date_label.hide()
        if self.tx.locktime <= NLOCKTIME_BLOCKHEIGHT_MAX:
            locktime_final_str = f"LockTime: {self.tx.locktime} (height)"
        else:
            locktime_final_str = f"LockTime: {self.tx.locktime} ({datetime.datetime.fromtimestamp(self.tx.locktime)})"
        self.locktime_final_label.setText(locktime_final_str)
        if self.locktime_e.get_locktime() is None:
            self.locktime_e.set_locktime(self.tx.locktime)
        self.rbf_label.setText(
            _('Replace by fee') + f": {not self.tx.is_final()}")

        if tx_mined_status.header_hash:
            self.block_hash_label.setText(
                _("Included in block: {}").format(tx_mined_status.header_hash))
            self.block_height_label.setText(
                _("At block height: {}").format(tx_mined_status.height))
        else:
            self.block_hash_label.hide()
            self.block_height_label.hide()
        if amount is None and ln_amount is None:
            amount_str = _("Transaction unrelated to your wallet")
        elif amount is None:
            amount_str = ''
        elif amount > 0:
            amount_str = _("Amount received:"
                           ) + ' %s' % format_amount(amount) + ' ' + base_unit
        else:
            amount_str = _("Amount sent:"
                           ) + ' %s' % format_amount(-amount) + ' ' + base_unit
        if amount_str:
            self.amount_label.setText(amount_str)
        else:
            self.amount_label.hide()
        size_str = _("Size:") + ' %d bytes' % size
        fee_str = _("Fee") + ': %s' % (format_amount(fee) + ' ' + base_unit
                                       if fee is not None else _('unknown'))
        if fee is not None:
            fee_rate = fee / size * 1000
            fee_str += '  ( %s ) ' % self.main_window.format_fee_rate(fee_rate)
            feerate_warning = simple_config.FEERATE_WARNING_HIGH_FEE
            if fee_rate > feerate_warning:
                fee_str += ' - ' + _('Warning') + ': ' + _("high fee") + '!'
        if isinstance(self.tx, PartialTransaction):
            risk_of_burning_coins = (
                can_sign and fee is not None
                and self.wallet.get_warning_for_risk_of_burning_coins_as_fees(
                    self.tx))
            self.fee_warning_icon.setToolTip(str(risk_of_burning_coins))
            self.fee_warning_icon.setVisible(bool(risk_of_burning_coins))
        self.fee_label.setText(fee_str)
        self.size_label.setText(size_str)
        if name_fee is not None and name_fee != 0:
            name_fee_str = _("Name Registration Fee") + ': %s' % (
                format_amount(name_fee) + ' ' + base_unit)
            self.name_fee_label.setText(name_fee_str)
        else:
            self.name_fee_label.setText("")
        if ln_amount is None or ln_amount == 0:
            ln_amount_str = ''
        elif ln_amount > 0:
            ln_amount_str = _(
                'Amount received in channels') + ': ' + format_amount(
                    ln_amount) + ' ' + base_unit
        elif ln_amount < 0:
            ln_amount_str = _(
                'Amount withdrawn from channels') + ': ' + format_amount(
                    -ln_amount) + ' ' + base_unit
        if ln_amount_str:
            self.ln_amount_label.setText(ln_amount_str)
        else:
            self.ln_amount_label.hide()
        show_psbt_only_widgets = self.finalized and isinstance(
            self.tx, PartialTransaction)
        for widget in self.psbt_only_widgets:
            if isinstance(widget, QMenu):
                widget.menuAction().setVisible(show_psbt_only_widgets)
            else:
                widget.setVisible(show_psbt_only_widgets)
        if tx_details.is_lightning_funding_tx:
            self._ptx_join_txs_action.setEnabled(False)  # would change txid

        self.save_button.setEnabled(tx_details.can_save_as_local)
        if tx_details.can_save_as_local:
            self.save_button.setToolTip(_("Save transaction offline"))
        else:
            self.save_button.setToolTip(
                _("Transaction already saved or not yet signed."))

        run_hook('transaction_dialog_update', self)

    def update_io(self):
        inputs_header_text = _("Inputs") + ' (%d)' % len(self.tx.inputs())
        if not self.finalized:
            selected_coins = self.main_window.get_manually_selected_coins()
            if selected_coins is not None:
                inputs_header_text += f"  -  " + _(
                    "Coin selection active ({} UTXOs selected)").format(
                        len(selected_coins))
        self.inputs_header.setText(inputs_header_text)
        ext = QTextCharFormat()
        rec = QTextCharFormat()
        rec.setBackground(QBrush(ColorScheme.GREEN.as_color(background=True)))
        rec.setToolTip(_("Wallet receive address"))
        chg = QTextCharFormat()
        chg.setBackground(QBrush(ColorScheme.YELLOW.as_color(background=True)))
        chg.setToolTip(_("Wallet change address"))
        twofactor = QTextCharFormat()
        twofactor.setBackground(
            QBrush(ColorScheme.BLUE.as_color(background=True)))
        twofactor.setToolTip(
            _("TrustedCoin (2FA) fee for the next batch of transactions"))

        def text_format(addr):
            if self.wallet.is_mine(addr):
                return chg if self.wallet.is_change(addr) else rec
            elif self.wallet.is_billing_address(addr):
                return twofactor
            return ext

        def format_amount(amt):
            return self.main_window.format_amount(amt, whitespaces=True)

        i_text = self.inputs_textedit
        i_text.clear()
        i_text.setFont(QFont(MONOSPACE_FONT))
        i_text.setReadOnly(True)
        cursor = i_text.textCursor()
        for txin in self.tx.inputs():
            if txin.is_coinbase_input():
                cursor.insertText('coinbase')
            else:
                prevout_hash = txin.prevout.txid.hex()
                prevout_n = txin.prevout.out_idx
                cursor.insertText(prevout_hash + ":%-4d " % prevout_n, ext)
                addr = self.wallet.get_txin_address(txin)
                if addr is None:
                    addr = ''
                cursor.insertText(addr, text_format(addr))
                if isinstance(txin, PartialTxInput
                              ) and txin.value_sats_display() is not None:
                    cursor.insertText(format_amount(txin.value_sats_display()),
                                      ext)
            cursor.insertBlock()

        self.outputs_header.setText(
            _("Outputs") + ' (%d)' % len(self.tx.outputs()))
        o_text = self.outputs_textedit
        o_text.clear()
        o_text.setFont(QFont(MONOSPACE_FONT))
        o_text.setReadOnly(True)
        cursor = o_text.textCursor()
        for o in self.tx.outputs():
            addr, v, name_op = o.get_ui_address_str(
            ), o.value_display, o.name_op
            cursor.insertText(addr, text_format(addr))
            if v is not None:
                cursor.insertText('\t', ext)
                cursor.insertText(format_amount(v), ext)
            if name_op is not None:
                cursor.insertText('\n', ext)
                cursor.insertText(format_name_op(name_op), ext)
            cursor.insertBlock()

    def add_tx_stats(self, vbox):
        hbox_stats = QHBoxLayout()

        # left column
        vbox_left = QVBoxLayout()
        self.tx_desc = TxDetailLabel(word_wrap=True)
        vbox_left.addWidget(self.tx_desc)
        self.status_label = TxDetailLabel()
        vbox_left.addWidget(self.status_label)
        self.date_label = TxDetailLabel()
        vbox_left.addWidget(self.date_label)
        self.amount_label = TxDetailLabel()
        vbox_left.addWidget(self.amount_label)
        self.ln_amount_label = TxDetailLabel()
        vbox_left.addWidget(self.ln_amount_label)

        fee_hbox = QHBoxLayout()
        self.fee_label = TxDetailLabel()
        fee_hbox.addWidget(self.fee_label)
        self.fee_warning_icon = QLabel()
        pixmap = QPixmap(icon_path("warning"))
        pixmap_size = round(2 * char_width_in_lineedit())
        pixmap = pixmap.scaled(pixmap_size, pixmap_size, Qt.KeepAspectRatio,
                               Qt.SmoothTransformation)
        self.fee_warning_icon.setPixmap(pixmap)
        self.fee_warning_icon.setVisible(False)
        fee_hbox.addWidget(self.fee_warning_icon)
        fee_hbox.addStretch(1)
        vbox_left.addLayout(fee_hbox)

        name_fee_hbox = QHBoxLayout()
        self.name_fee_label = TxDetailLabel()
        name_fee_hbox.addWidget(self.name_fee_label)
        name_fee_hbox.addStretch(1)
        vbox_left.addLayout(name_fee_hbox)

        vbox_left.addStretch(1)
        hbox_stats.addLayout(vbox_left, 50)

        # vertical line separator
        line_separator = QFrame()
        line_separator.setFrameShape(QFrame.VLine)
        line_separator.setFrameShadow(QFrame.Sunken)
        line_separator.setLineWidth(1)
        hbox_stats.addWidget(line_separator)

        # right column
        vbox_right = QVBoxLayout()
        self.size_label = TxDetailLabel()
        vbox_right.addWidget(self.size_label)
        self.rbf_label = TxDetailLabel()
        vbox_right.addWidget(self.rbf_label)
        self.rbf_cb = QCheckBox(_('Replace by fee'))
        self.rbf_cb.setChecked(bool(self.config.get('use_rbf', True)))
        vbox_right.addWidget(self.rbf_cb)

        self.locktime_final_label = TxDetailLabel()
        vbox_right.addWidget(self.locktime_final_label)

        locktime_setter_hbox = QHBoxLayout()
        locktime_setter_hbox.setContentsMargins(0, 0, 0, 0)
        locktime_setter_hbox.setSpacing(0)
        locktime_setter_label = TxDetailLabel()
        locktime_setter_label.setText("LockTime: ")
        self.locktime_e = LockTimeEdit()
        locktime_setter_hbox.addWidget(locktime_setter_label)
        locktime_setter_hbox.addWidget(self.locktime_e)
        locktime_setter_hbox.addStretch(1)
        self.locktime_setter_widget = QWidget()
        self.locktime_setter_widget.setLayout(locktime_setter_hbox)
        vbox_right.addWidget(self.locktime_setter_widget)

        self.block_height_label = TxDetailLabel()
        vbox_right.addWidget(self.block_height_label)
        vbox_right.addStretch(1)
        hbox_stats.addLayout(vbox_right, 50)

        vbox.addLayout(hbox_stats)

        # below columns
        self.block_hash_label = TxDetailLabel(word_wrap=True)
        vbox.addWidget(self.block_hash_label)

        # set visibility after parenting can be determined by Qt
        self.rbf_label.setVisible(self.finalized)
        self.rbf_cb.setVisible(not self.finalized)
        self.locktime_final_label.setVisible(self.finalized)
        self.locktime_setter_widget.setVisible(not self.finalized)

    def set_title(self):
        self.setWindowTitle(
            _("Create transaction") if not self.finalized else _("Transaction")
        )

    def on_finalize(self):
        pass  # overridden in subclass

    def update_fee_fields(self):
        pass  # overridden in subclass
Example #47
0
	def _createTopToolbar(self):
		"""
        """
		topToolbarSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)        
		self.topToolBar.setSizePolicy(topToolbarSizePolicy)

		#pan_zoom = QAction(QIcon(dir + "/resources/btnDrag.png"),"Pan (Mouse
		#Left)",self)
		#self.toolBar.addAction(pan_zoom)
		#zoomSelect = QAction(QIcon(dir + "/resources/btnZoomSelect.png"),"ROI Zoom
		#(Mouse Left)",self)
		#self.toolBar.addAction(zoomSelect)
		exitAct = QAction('Exit', self)
		exitAct.setShortcut('Ctrl+Q')

		self._panZoom = QToolButton(self)
		self._panZoom.setIcon(QIcon(PAN_ZOOM_ICON))
		self._panZoom.setToolTip(PAN_ZOOM_TOOLTIP)
		self._panZoom.setCheckable(True)
		self._panZoom.setChecked(True)
		self._panZoom.clicked.connect(self._panZoomSwitch)
		self.topToolBar.addWidget(self._panZoom)

		self._zoomSelect = QToolButton(self)
		self._zoomSelect.setIcon(QIcon(ZOOM_SELECT_ICON))
		self._zoomSelect.setToolTip(ZOOM_SELECT_TOOLTIP)
		self._zoomSelect.setCheckable(True)
		self._zoomSelect.setChecked(False)
		self._zoomSelect.clicked.connect(self._zoomSelectSwitch)
		self.topToolBar.addWidget(self._zoomSelect)

		self.topToolBar.addSeparator()

		zoomIn = QAction(QIcon(ZOOM_IN_ICON),ZOOM_IN_TOOLTIP,self)        
		self.topToolBar.addAction(zoomIn)
		zoomOut = QAction(QIcon(ZOOM_OUT_ICON),ZOOM_OUT_TOOLTIP,self)        
		self.topToolBar.addAction(zoomOut)
		zoomReset = QAction(QIcon(ZOOM_RESET_ICON),ZOOM_RESET_TOOLTIP,self)        
		self.topToolBar.addAction(zoomReset)

		self.topToolBar.addSeparator()

		# Separator:
		#self.fooWidget = QWidget()
		#self.fooWidget.setFixedWidth(6)
		#self.fooWidgetAction = self.topToolBar.addWidget(self.fooWidget)

		#self.extraSeparatorAction = self.topToolBar.addSeparator()

		export = QAction(QIcon(EXPORT_ICON),EXPORT_TOOLTIP,self)        
		self.topToolBar.addAction(export)

		exportAll = QAction(QIcon(EXPORTALL_ICON),EXPORTALL_TOOLTIP,self)        
		self.topToolBar.addAction(exportAll)
								
		# Spacer:
		spacer = QWidget()
		spacerSizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)   
		spacer.setSizePolicy(spacerSizePolicy)
		self.topToolBar.addWidget(spacer)
		
		# Label on the right:
		self.hoverLabel = QLabel(self)
		self.hoverLabel.setText("")
		self.topToolBar.addWidget(self.hoverLabel) 
			

		# Connect handler for toolbar buttons:
		self.topToolBar.actionTriggered[QAction].connect(self._toolBarBtnPressed)
Example #48
0
    def __init__(self):
        super().__init__()

        self.dev = None

        self.device_descs = DEVICE_DESC.copy()
        self.load_devices_ini()

        self.qmk_offset = QMK_OFFSET_DEFAULT

        self.progress_signal.connect(self._on_progress)
        self.complete_signal.connect(self._on_complete)
        self.error_signal.connect(self._on_error)

        lbl_warning = QLabel(
            "<font color='red'><b>Make sure jumploader is installed before you flash QMK</b></font>"
        )
        lbl_warning.setWordWrap(True)

        layout_offset = QHBoxLayout()
        rbtn_qmk_offset_200 = QRadioButton("0x200")
        rbtn_qmk_offset_200.setChecked(True)
        rbtn_qmk_offset_200.toggled.connect(
            lambda: self.on_toggle_offset(rbtn_qmk_offset_200))
        rbtn_qmk_offset_0 = QRadioButton("0x00")
        rbtn_qmk_offset_0.toggled.connect(
            lambda: self.on_toggle_offset(rbtn_qmk_offset_0))
        layout_offset.addWidget(rbtn_qmk_offset_200)
        layout_offset.addWidget(rbtn_qmk_offset_0)
        group_qmk_offset = QGroupBox("qmk offset")
        group_qmk_offset.setLayout(layout_offset)

        btn_flash_qmk = QPushButton("Flash QMK...")
        btn_flash_qmk.clicked.connect(self.on_click_flash_qmk)

        lbl_help = QLabel(
            "After jumploader is installed, hold Backspace while plugging in the keyboard to start in bootloader mode."
        )
        lbl_help.setWordWrap(True)

        btn_reboot_bl = QPushButton("Reboot to Bootloader")
        btn_reboot_bl.clicked.connect(self.on_click_reboot)
        btn_flash_jumploader = QPushButton("Flash Jumploader")
        btn_flash_jumploader.clicked.connect(self.on_click_flash_jumploader)
        btn_restore_stock = QPushButton("Revert to Stock Firmware")
        btn_restore_stock.clicked.connect(self.on_click_revert)

        self.progress = QProgressBar()
        self.progress.setRange(0, 100)
        self.progress_label = QLabel("Ready")

        layout_device_type = QHBoxLayout()
        rbtn_device_type_240 = QRadioButton("SN32F24x")
        rbtn_device_type_240.toggled.connect(
            lambda: self.on_toggle_device_type(rbtn_device_type_240))
        rbtn_device_type_260 = QRadioButton("SN32F26x")
        rbtn_device_type_260.setChecked(True)
        rbtn_device_type_260.toggled.connect(
            lambda: self.on_toggle_device_type(rbtn_device_type_260))
        layout_device_type.addWidget(rbtn_device_type_260)
        layout_device_type.addWidget(rbtn_device_type_240)

        self.combobox_devices = QComboBox()
        btn_refresh_devices = QToolButton()
        btn_refresh_devices.setToolButtonStyle(Qt.ToolButtonTextOnly)
        btn_refresh_devices.setText("Refresh")
        btn_refresh_devices.clicked.connect(self.on_click_refresh)

        devices_layout = QHBoxLayout()
        devices_layout.addWidget(self.combobox_devices)
        devices_layout.addWidget(btn_refresh_devices)

        device_group_layout = QVBoxLayout()
        device_group_layout.addLayout(layout_device_type)
        device_group_layout.addLayout(devices_layout)

        group_device = QGroupBox("Device")
        group_device.setLayout(device_group_layout)

        layout_qmk = QVBoxLayout()
        layout_qmk.setAlignment(Qt.AlignTop)
        layout_qmk.addWidget(lbl_warning)
        layout_qmk.addWidget(group_qmk_offset)
        layout_qmk.addWidget(btn_flash_qmk)
        layout_qmk.addWidget(lbl_help)

        layout_stock = QVBoxLayout()
        layout_stock.setAlignment(Qt.AlignTop)
        layout_stock.addWidget(btn_reboot_bl)
        layout_stock.addWidget(btn_flash_jumploader)
        layout_stock.addWidget(btn_restore_stock)

        layout_progress = QVBoxLayout()
        layout_progress.addWidget(self.progress_label)
        layout_progress.addWidget(self.progress)

        group_qmk = QGroupBox("QMK")
        group_qmk.setLayout(layout_qmk)

        group_stock = QGroupBox("Stock")
        group_stock.setLayout(layout_stock)

        group_progress = QGroupBox("")
        group_progress.setLayout(layout_progress)

        group_layout = QHBoxLayout()
        group_layout.addWidget(group_qmk)
        group_layout.addWidget(group_stock)

        layout = QVBoxLayout()
        layout.addWidget(group_device, stretch=0)
        layout.addLayout(group_layout, stretch=1)
        layout.addWidget(group_progress, stretch=0)
        self.setLayout(layout)

        self.lockable = [
            btn_flash_qmk, btn_reboot_bl, btn_flash_jumploader,
            btn_restore_stock, self.combobox_devices, btn_refresh_devices
        ]

        self.on_click_refresh()
    def __init__(self, tx: Transaction, parent: 'ElectrumWindow', invoice,
                 desc, prompt_if_unsaved):
        '''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)
        # Take a copy; it might get updated in the main window by
        # e.g. the FX plugin.  If this happens during or after a long
        # sign operation the signatures are lost.
        self.tx = tx = copy.deepcopy(tx)
        try:
            self.tx.deserialize()
        except BaseException as e:
            raise SerializationError(e)
        self.main_window = parent
        self.wallet = parent.wallet
        self.prompt_if_unsaved = prompt_if_unsaved
        self.saved = False
        self.desc = desc
        self.invoice = invoice

        # if the wallet can populate the inputs with more info, do it now.
        # as a result, e.g. we might learn an imported address tx is segwit,
        # in which case it's ok to display txid
        tx.add_inputs_info(self.wallet)

        self.setMinimumWidth(950)
        self.setWindowTitle(_("Transaction"))

        vbox = QVBoxLayout()
        self.setLayout(vbox)

        vbox.addWidget(QLabel(_("Transaction ID:")))
        self.tx_hash_e = ButtonsLineEdit()
        qr_show = lambda: parent.show_qrcode(
            str(self.tx_hash_e.text()), 'Transaction ID', parent=self)
        qr_icon = "qrcode_white.png" if ColorScheme.dark_scheme else "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.add_io(vbox)

        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"))
        save_button_disabled = not tx.is_complete()
        b.setDisabled(save_button_disabled)
        if save_button_disabled:
            b.setToolTip(SAVE_BUTTON_DISABLED_TOOLTIP)
        else:
            b.setToolTip(SAVE_BUTTON_ENABLED_TOOLTIP)
        b.clicked.connect(self.save)

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

        export_actions_menu = QMenu()
        action = QAction(_("Copy to clipboard"), self)
        action.triggered.connect(lambda: parent.app.clipboard().setText(
            (lambda: str(self.tx))()))
        export_actions_menu.addAction(action)
        action = QAction(read_QIcon(qr_icon), _("Show as QR code"), self)
        action.triggered.connect(self.show_qr)
        export_actions_menu.addAction(action)
        action = QAction(_("Export to file"), self)
        action.triggered.connect(self.export)
        export_actions_menu.addAction(action)
        self.export_actions_button = QToolButton()
        self.export_actions_button.setText(_("Export"))
        self.export_actions_button.setMenu(export_actions_menu)
        self.export_actions_button.setPopupMode(QToolButton.InstantPopup)

        # Action buttons
        self.buttons = [
            self.sign_button, self.broadcast_button, self.cancel_button
        ]
        # Transaction sharing buttons
        self.sharing_buttons = [self.export_actions_button, self.save_button]

        run_hook('transaction_dialog', self)

        hbox = QHBoxLayout()
        hbox.addLayout(Buttons(*self.sharing_buttons))
        hbox.addStretch(1)
        hbox.addLayout(Buttons(*self.buttons))
        vbox.addLayout(hbox)
        self.update()
Example #50
0
class HangmanGame(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)

        # Initialize word database        
        self.word = Word('words.txt')

        # Hangman display window
        self.hangmanWindow = QTextEdit()
        self.hangmanWindow.setReadOnly(True)
        self.hangmanWindow.setAlignment(Qt.AlignLeft)
        font = self.hangmanWindow.font()
        font.setFamily('Courier New')
        self.hangmanWindow.setFont(font)

        # Layout
        hangmanLayout = QGridLayout()
        hangmanLayout.addWidget(self.hangmanWindow, 0, 0)
        # Status Layout creation
        statusLayout = QGridLayout()

        # Display widget for current status
        self.currentWord = QLineEdit()
        self.currentWord.setFixedWidth(400)
        self.currentWord.setReadOnly(True)
        self.currentWord.setAlignment(Qt.AlignCenter)
        font = self.currentWord.font()
        font.setPointSize(font.pointSize() + 8)
        self.currentWord.setFont(font)
        statusLayout.addWidget(self.currentWord, 0, 0, 1, 2)

        # Display widget for already used characters
        self.guessedChars = QLineEdit()
        self.guessedChars.setReadOnly(True)
        self.guessedChars.setAlignment(Qt.AlignLeft)
        self.guessedChars.setMaxLength(52)
        statusLayout.addWidget(self.guessedChars, 1, 0, 1, 2)

        # Display widget for message output
        self.message = QLineEdit()
        self.message.setReadOnly(True)
        self.message.setAlignment(Qt.AlignLeft)
        self.message.setMaxLength(52)
        statusLayout.addWidget(self.message, 2, 0, 1, 2)

        # Input widget for user selected characters
        self.charInput = QLineEdit()
        self.charInput.setMaxLength(1)
        statusLayout.addWidget(self.charInput, 3, 0)

        # Button for submitting a character
        self.guessButton = QToolButton()
        self.guessButton.setText('Guess!')
        self.guessButton.clicked.connect(self.guessClicked)
        statusLayout.addWidget(self.guessButton, 3, 1)

        # Button for a new game
        self.newGameButton = QToolButton()
        self.newGameButton.setText('New Game')
        self.newGameButton.clicked.connect(self.startGame)
        statusLayout.addWidget(self.newGameButton, 4, 0)

        # Layout placement
        mainLayout = QGridLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        mainLayout.addLayout(hangmanLayout, 0, 0)
        mainLayout.addLayout(statusLayout, 0, 1)

        self.setLayout(mainLayout)

        self.setWindowTitle('Hangman Game')

        # Start a new game on application launch!
        self.startGame()


    def startGame(self):
        self.hangman = Hangman()
        self.guess = Guess(self.word.randFromDB(1))
        self.gameOver = False

        self.hangmanWindow.setPlaceholderText(self.hangman.currentShape())
        self.currentWord.setText(self.guess.displayCurrent())
        self.guessedChars.setText(self.guess.displayGuessed())
        self.message.clear()

    def guessClicked(self):
        guessedChar = self.charInput.text()
        self.charInput.clear()
        self.message.clear()

        if self.gameOver == True:
            # 메시지 출력하고 - message.setText() - 리턴
            self.message.setText("Already done game")
            return

        # 입력의 길이가 1 인지를 판단하고, 아닌 경우 메시지 출력, 리턴
        if len(guessedChar) != 1:
            self.message.setText("Please input one alpabet")
            return
        # 이미 사용한 글자인지를 판단하고, 아닌 경우 메시지 출력, 리턴
        if guessedChar in self.guess.guessedChars:
            self.message.setText("You already input this")
            return
        success = self.guess.guess(guessedChar)
        if success == False:
            # 남아 있는 목숨을 1 만큼 감소
            self.hangman.decreaseLife()
            # 메시지 출력
            self.message.setText("SecretWord not include this")
            pass

        # hangmanWindow 에 현재 hangman 상태 그림을 출력
        self.hangmanWindow.setPlaceholderText(self.hangman.currentShape())
        # currentWord 에 현재까지 부분적으로 맞추어진 단어 상태를 출력
        self.currentWord.setText(self.guess.displayCurrent())
        # guessedChars 에 지금까지 이용한 글자들의 집합을 출력
        self.guessedChars.setText(self.guess.displayGuessed())

        if self.guess.finished():
            # 메시지 ("Success!") 출력하고, self.gameOver 는 True 로
            self.message.setText("Success!")
            self.gameOver = True
            pass

        elif self.hangman.getRemainingLives() == 0:
            # 메시지 ("Fail!" + 비밀 단어) 출력하고, self.gameOver 는 True 로
            self.message.setText("Fail!, SecretWord is: "+self.guess.secretWord)
            self.gameOver = True
            pass
Example #51
0
    def __init__(self, parent=None):
        wdgProductHistoricalChart.__init__(self, parent)
        self.labelBuyPrice = QLabel(self.tr("Add wanted price"))
        self.txtBuyPrice = myQLineEdit(self)
        self.cmdBuyPrice = QToolButton(self)
        icon = QIcon()
        icon.addPixmap(QPixmap(":/xulpymoney/tools-wizard.png"), QIcon.Normal,
                       QIcon.Off)
        self.cmdBuyPrice.setIcon(icon)
        self.horizontalLayout_3.addWidget(self.labelBuyPrice)
        self.spacerBuyPrice = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                          QSizePolicy.Minimum)
        self.horizontalLayout_3.addWidget(self.txtBuyPrice)
        self.horizontalLayout_3.addWidget(self.cmdBuyPrice)
        self.horizontalLayout_3.addItem(self.spacerBuyPrice)

        self.cmdBuyPrice.released.connect(self.on_cmdBuyPrice_released)

        self.layAmounts = QHBoxLayout()
        self.label1 = QLabel(self)
        self.label1.setText(self.tr("Amounts to invest separated by ;"))
        self.txtAmounts = QLineEdit(self)
        self.txtAmounts.setText("2500;3500;8400;8400")

        self.labelLastOperationPercentage = QLabel(self)
        self.labelLastOperationPercentage.setText(
            self.tr("Last Operation next buy percentage"))
        self.txtLastOperationPercentage = myQLineEdit(self)
        self.txtLastOperationPercentage.setText(33)

        self.spacer1 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer3 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer4 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer5 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.spacer6 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                   QSizePolicy.Minimum)
        self.layAmounts.addItem(self.spacer1)
        self.layAmounts.addWidget(self.label1)
        self.layAmounts.addWidget(self.txtAmounts)
        self.layAmounts.addItem(self.spacer2)
        self.layAmounts.addWidget(self.labelLastOperationPercentage)
        self.layAmounts.addWidget(self.txtLastOperationPercentage)
        self.layAmounts.addItem(self.spacer6)
        self.verticalLayout.addLayout(self.layAmounts)

        #Add Calculator widget
        self.layOpportunity = QHBoxLayout()
        self.spacerOpportunity = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                             QSizePolicy.Minimum)
        self.cmdOpportunity = QPushButton(self.tr("Add Opportunity"))
        self.cmdOpportunity.released.connect(self.on_cmdOpportunity_released)
        icon1 = QIcon()
        icon1.addPixmap(QPixmap(":/xulpymoney/kcalc.png"), QIcon.Normal,
                        QIcon.Off)
        self.cmdOpportunity.setIcon(icon1)
        self.layOpportunity.addItem(self.spacerOpportunity)
        self.layOpportunity.addWidget(self.cmdOpportunity)
    def create_fee_controls(self):

        self.size_e = TxSizeLabel()
        self.size_e.setAlignment(Qt.AlignCenter)
        self.size_e.setAmount(0)
        self.size_e.setStyleSheet(ColorScheme.DEFAULT.as_stylesheet())

        self.feerate_e = FeerateEdit(lambda: 0)
        self.feerate_e.setAmount(self.config.fee_per_byte())
        self.feerate_e.textEdited.connect(
            partial(self.on_fee_or_feerate, self.feerate_e, False))
        self.feerate_e.editingFinished.connect(
            partial(self.on_fee_or_feerate, self.feerate_e, True))

        self.fee_e = BTCAmountEdit(self.main_window.get_decimal_point)
        self.fee_e.textEdited.connect(
            partial(self.on_fee_or_feerate, self.fee_e, False))
        self.fee_e.editingFinished.connect(
            partial(self.on_fee_or_feerate, self.fee_e, True))

        self.fee_e.textChanged.connect(self.entry_changed)
        self.feerate_e.textChanged.connect(self.entry_changed)

        self.fee_slider = FeeSlider(self, self.config,
                                    self.fee_slider_callback)
        self.fee_combo = FeeComboBox(self.fee_slider)
        self.fee_slider.setFixedWidth(self.fee_e.width())

        def feerounding_onclick():
            text = (
                self.feerounding_text + '\n\n' +
                _('To somewhat protect your privacy, Electrum tries to create change with similar precision to other outputs.'
                  ) + ' ' +
                _('At most 100 satoshis might be lost due to this rounding.') +
                ' ' + _("You can disable this setting in '{}'.").format(
                    _('Preferences')) + '\n' +
                _('Also, dust is not kept as change, but added to the fee.') +
                '\n' +
                _('Also, when batching RBF transactions, BIP 125 imposes a lower bound on the fee.'
                  ))
            self.show_message(title=_('Fee rounding'), msg=text)

        self.feerounding_icon = QToolButton()
        self.feerounding_icon.setIcon(read_QIcon('info.png'))
        self.feerounding_icon.setAutoRaise(True)
        self.feerounding_icon.clicked.connect(feerounding_onclick)
        self.feerounding_icon.setVisible(False)

        self.feecontrol_fields = QWidget()
        hbox = QHBoxLayout(self.feecontrol_fields)
        hbox.setContentsMargins(0, 0, 0, 0)
        grid = QGridLayout()
        grid.addWidget(QLabel(_("Target fee:")), 0, 0)
        grid.addWidget(self.feerate_e, 0, 1)
        grid.addWidget(self.size_e, 0, 2)
        grid.addWidget(self.fee_e, 0, 3)
        grid.addWidget(self.feerounding_icon, 0, 4)
        grid.addWidget(self.fee_slider, 1, 1)
        grid.addWidget(self.fee_combo, 1, 2)
        hbox.addLayout(grid)
        hbox.addStretch(1)
Example #53
0
    def initUI(self):
        ###############################  Create  Actions ##############################
        self.loadimagesaction = QAction("Load Images", self)
        self.loadimagesaction.setCheckable(True)
        self.loadimagesaction.triggered.connect(self.loadimages)

        self.javascriptmode = QAction("Enable Javascript", self)
        self.javascriptmode.setCheckable(True)
        self.javascriptmode.triggered.connect(self.setjavascript)

        self.useragent_mode_desktop = QAction("Desktop", self)
        self.useragent_mode_desktop.setCheckable(True)
        self.useragent_mode_desktop.triggered.connect(self.setUserAgentDesktop)

        self.useragent_mode_mobile = QAction("Mobile", self)
        self.useragent_mode_mobile.setCheckable(True)
        self.useragent_mode_mobile.triggered.connect(self.setUserAgentMobile)

        self.useragent_mode_custom = QAction("Custom", self)
        self.useragent_mode_custom.setCheckable(True)
        self.useragent_mode_custom.triggered.connect(self.setUserAgentCustom)

        ################ Add Actions to Menu ####################
        # This sub-menu sets useragent mode to desktop/mobile/custom
        self.useragentMenu = QMenu('UserAgent', self)
        self.useragentMenu.setIcon(QIcon.fromTheme("computer"))
        self.useragentMenu.addAction(self.useragent_mode_desktop)
        self.useragentMenu.addAction(self.useragent_mode_mobile)
        self.useragentMenu.addAction(self.useragent_mode_custom)

        # This is main menu
        self.menu = QMenu(self)
        self.menu.addAction(QIcon.fromTheme("edit-find"), "Find Text",
                            self.findmode, "Ctrl+F")
        self.menu.addAction(QIcon.fromTheme("list-add"), "Zoom In",
                            self.zoomin, "Ctrl++")
        self.menu.addAction(QIcon.fromTheme("list-remove"), "Zoom Out",
                            self.zoomout, "Ctrl+-")
        self.menu.addAction(QIcon.fromTheme("view-fullscreen"),
                            "Toggle Fullscreen", self.fullscreenmode, "F11")
        self.menu.addSeparator()

        self.menu.addAction(self.loadimagesaction)
        self.menu.addAction(self.javascriptmode)
        self.menu.addMenu(self.useragentMenu)
        self.menu.addAction(QIcon.fromTheme("applications-system"), "Settings",
                            self.settingseditor, "Ctrl+,")
        self.menu.addSeparator()

        self.menu.addAction(QIcon.fromTheme("image-x-generic"),
                            "Save as Image", self.saveAsImage, "Shift+Ctrl+S")
        self.menu.addAction(QIcon.fromTheme("text-html"), "Save as HTML",
                            self.saveashtml, "Ctrl+S")
        self.menu.addAction(QIcon.fromTheme("document-print"), "Print to PDF",
                            self.printpage, "Ctrl+P")
        self.menu.addSeparator()
        self.menu.addAction(QIcon.fromTheme("process-stop"), "Quit",
                            self.forceClose, "Ctrl+Q")

        self.bmk_menu = QMenu(self)
        self.bmk_menu.addAction(QIcon(':/add-bookmark.png'), 'Add Bookmark',
                                self.addbookmark)
        self.bmk_menu.addAction(QIcon(':/favourites.png'), 'Add to Home',
                                self.addToFavourites)

        ###############################  Create Gui Parts ##############################
        grid = QGridLayout()
        grid.setSpacing(1)
        grid.setContentsMargins(0, 2, 0, 0)
        self.centralwidget = QWidget(self)
        self.centralwidget.setLayout(grid)
        self.setCentralWidget(self.centralwidget)

        self.addtabBtn = QPushButton(QIcon(":/add-tab.png"), "", self)
        self.addtabBtn.setToolTip("New Tab\n[Ctrl+Tab]")
        self.addtabBtn.setShortcut("Ctrl+Tab")
        self.addtabBtn.clicked.connect(self.addTab)

        self.reload = QPushButton(QIcon(":/refresh.png"), "", self)
        self.reload.setMinimumSize(35, 26)
        self.reload.setToolTip("Reload/Stop\n  [Space]")
        self.reload.setShortcut("Space")
        self.reload.clicked.connect(self.Reload)

        self.back = QPushButton(QIcon(":/prev.png"), "", self)
        self.back.setToolTip("Previous Page\n [Backspace]")
        self.back.setMinimumSize(35, 26)
        self.back.clicked.connect(self.Back)

        self.forw = QPushButton(QIcon(":/next.png"), "", self)
        self.forw.setToolTip("Next Page\n [Shift+Backspace]")
        self.forw.setMinimumSize(35, 26)
        self.forw.clicked.connect(self.Forward)

        self.homeBtn = QPushButton(QIcon(":/home.png"), "", self)
        self.homeBtn.setToolTip("Go Home")
        self.homeBtn.clicked.connect(self.goToHome)

        self.videoDownloadButton = QPushButton(QIcon(":/video-dwnld.png"), "",
                                               self)
        self.videoDownloadButton.setToolTip("Download this Video")
        self.videoDownloadButton.clicked.connect(self.downloadVideo)
        self.videoDownloadButton.hide()

        self.addbookmarkBtn = QToolButton(self)
        self.addbookmarkBtn.setIcon(QIcon(":/add-bookmark.png"))
        self.addbookmarkBtn.setToolTip("Add Bookmark")
        self.addbookmarkBtn.setMenu(self.bmk_menu)
        self.addbookmarkBtn.setPopupMode(QToolButton.InstantPopup)

        self.menuBtn = QToolButton(self)
        self.menuBtn.setIcon(QIcon(":/menu.png"))
        self.menuBtn.setMenu(self.menu)
        self.menuBtn.setPopupMode(QToolButton.InstantPopup)

        self.bookmarkBtn = QPushButton(QIcon(":/bookmarks.png"), "", self)
        self.bookmarkBtn.setToolTip("Manage Bookmarks\n         [Alt+B]")
        self.bookmarkBtn.setShortcut("Alt+B")
        self.bookmarkBtn.clicked.connect(self.managebookmarks)
        self.historyBtn = QPushButton(QIcon(":/history.png"), "", self)
        self.historyBtn.setShortcut("Alt+H")
        self.historyBtn.setToolTip("View History\n     [Alt+H]")
        self.historyBtn.clicked.connect(self.viewhistory)

        self.downloadsBtn = QPushButton(QIcon(":/download.png"), "", self)
        self.downloadsBtn.setToolTip("Download Manager")
        self.downloadsBtn.clicked.connect(self.download_manager)

        self.find = QPushButton(self)
        self.find.setText("Find/Next")
        self.find.clicked.connect(self.findnext)
        self.find.hide()
        self.findprev = QPushButton(self)
        self.findprev.setText("Backward")
        self.findprev.clicked.connect(self.findback)
        self.findprev.hide()
        self.cancelfind = QPushButton(self)
        self.cancelfind.setText("Cancel")
        self.cancelfind.clicked.connect(self.cancelfindmode)
        self.cancelfind.hide()

        self.pbar = QProgressBar(self)
        self.pbar.setTextVisible(False)
        self.pbar.setStyleSheet(
            "QProgressBar::chunk { background-color: #bad8ff; }")
        pbarLayout = QGridLayout(self.pbar)
        pbarLayout.setContentsMargins(0, 0, 0, 0)

        self.line = webkit.UrlEdit(self.pbar)
        self.line.openUrlRequested.connect(self.Enter)
        self.line.textEdited.connect(self.urlsuggestions)
        self.line.downloadRequested.connect(self.download_requested_file)
        pbarLayout.addWidget(self.line)

        self.listmodel = QStringListModel(self)
        self.completer = QCompleter(self.listmodel, self.line)
        self.completer.setCompletionMode(1)
        self.completer.setMaxVisibleItems(10)
        self.line.setCompleter(self.completer)

        self.statusbar = QLabel(self)
        self.statusbar.setStyleSheet(
            "QLabel { font-size: 12px; border-radius: 2px; padding: 2px; background: palette(highlight); color: palette(highlighted-text); }"
        )
        self.statusbar.setMaximumHeight(16)
        self.statusbar.hide()

        self.tabWidget = QTabWidget(self)
        self.tabWidget.setTabsClosable(True)
        self.tabWidget.setDocumentMode(True)
        self.tabWidget.tabBar().setExpanding(True)
        self.tabWidget.tabBar().setElideMode(Qt.ElideMiddle)
        self.tabWidget.currentChanged.connect(self.onTabSwitch)
        self.tabWidget.tabCloseRequested.connect(self.closeTab)
        self.addTab()
        self.applysettings()
        #

        for index, widget in enumerate([
                self.addtabBtn, self.back, self.forw, self.reload,
                self.homeBtn, self.videoDownloadButton, self.pbar, self.find,
                self.findprev, self.cancelfind, self.addbookmarkBtn,
                self.menuBtn, self.bookmarkBtn, self.historyBtn,
                self.downloadsBtn
        ]):
            grid.addWidget(widget, 0, index, 1, 1)
        grid.addWidget(self.tabWidget, 2, 0, 1, 15)
class PreviewTxDialog(BaseTxDialog, TxEditor):
    def __init__(self, *, make_tx, external_keypairs,
                 window: 'ElectrumWindow'):
        TxEditor.__init__(self,
                          window=window,
                          make_tx=make_tx,
                          is_sweep=bool(external_keypairs))
        BaseTxDialog.__init__(self,
                              parent=window,
                              desc='',
                              prompt_if_unsaved=False,
                              finalized=False,
                              external_keypairs=external_keypairs)
        BlockingWaitingDialog(
            window, _("Preparing transaction..."),
            lambda: self.update_tx(fallback_to_zero_fee=True))
        self.update()

    def create_fee_controls(self):

        self.size_e = TxSizeLabel()
        self.size_e.setAlignment(Qt.AlignCenter)
        self.size_e.setAmount(0)
        self.size_e.setStyleSheet(ColorScheme.DEFAULT.as_stylesheet())

        self.feerate_e = FeerateEdit(lambda: 0)
        self.feerate_e.setAmount(self.config.fee_per_byte())
        self.feerate_e.textEdited.connect(
            partial(self.on_fee_or_feerate, self.feerate_e, False))
        self.feerate_e.editingFinished.connect(
            partial(self.on_fee_or_feerate, self.feerate_e, True))

        self.fee_e = BTCAmountEdit(self.main_window.get_decimal_point)
        self.fee_e.textEdited.connect(
            partial(self.on_fee_or_feerate, self.fee_e, False))
        self.fee_e.editingFinished.connect(
            partial(self.on_fee_or_feerate, self.fee_e, True))

        self.fee_e.textChanged.connect(self.entry_changed)
        self.feerate_e.textChanged.connect(self.entry_changed)

        self.fee_slider = FeeSlider(self, self.config,
                                    self.fee_slider_callback)
        self.fee_combo = FeeComboBox(self.fee_slider)
        self.fee_slider.setFixedWidth(self.fee_e.width())

        def feerounding_onclick():
            text = (
                self.feerounding_text + '\n\n' +
                _('To somewhat protect your privacy, Electrum tries to create change with similar precision to other outputs.'
                  ) + ' ' +
                _('At most 100 satoshis might be lost due to this rounding.') +
                ' ' + _("You can disable this setting in '{}'.").format(
                    _('Preferences')) + '\n' +
                _('Also, dust is not kept as change, but added to the fee.') +
                '\n' +
                _('Also, when batching RBF transactions, BIP 125 imposes a lower bound on the fee.'
                  ))
            self.show_message(title=_('Fee rounding'), msg=text)

        self.feerounding_icon = QToolButton()
        self.feerounding_icon.setIcon(read_QIcon('info.png'))
        self.feerounding_icon.setAutoRaise(True)
        self.feerounding_icon.clicked.connect(feerounding_onclick)
        self.feerounding_icon.setVisible(False)

        self.feecontrol_fields = QWidget()
        hbox = QHBoxLayout(self.feecontrol_fields)
        hbox.setContentsMargins(0, 0, 0, 0)
        grid = QGridLayout()
        grid.addWidget(QLabel(_("Target fee:")), 0, 0)
        grid.addWidget(self.feerate_e, 0, 1)
        grid.addWidget(self.size_e, 0, 2)
        grid.addWidget(self.fee_e, 0, 3)
        grid.addWidget(self.feerounding_icon, 0, 4)
        grid.addWidget(self.fee_slider, 1, 1)
        grid.addWidget(self.fee_combo, 1, 2)
        hbox.addLayout(grid)
        hbox.addStretch(1)

    def fee_slider_callback(self, dyn, pos, fee_rate):
        super().fee_slider_callback(dyn, pos, fee_rate)
        self.fee_slider.activate()
        if fee_rate:
            fee_rate = Decimal(fee_rate)
            self.feerate_e.setAmount(quantize_feerate(fee_rate / 1000))
        else:
            self.feerate_e.setAmount(None)
        self.fee_e.setModified(False)

    def on_fee_or_feerate(self, edit_changed, editing_finished):
        edit_other = self.feerate_e if edit_changed == self.fee_e else self.fee_e
        if editing_finished:
            if edit_changed.get_amount() is None:
                # This is so that when the user blanks the fee and moves on,
                # we go back to auto-calculate mode and put a fee back.
                edit_changed.setModified(False)
        else:
            # edit_changed was edited just now, so make sure we will
            # freeze the correct fee setting (this)
            edit_other.setModified(False)
        self.fee_slider.deactivate()
        self.update()

    def is_send_fee_frozen(self):
        return self.fee_e.isVisible() and self.fee_e.isModified() \
               and (self.fee_e.text() or self.fee_e.hasFocus())

    def is_send_feerate_frozen(self):
        return self.feerate_e.isVisible() and self.feerate_e.isModified() \
               and (self.feerate_e.text() or self.feerate_e.hasFocus())

    def set_feerounding_text(self, num_satoshis_added):
        self.feerounding_text = (
            _('Additional {} satoshis are going to be added.').format(
                num_satoshis_added))

    def get_fee_estimator(self):
        if self.is_send_fee_frozen() and self.fee_e.get_amount() is not None:
            fee_estimator = self.fee_e.get_amount()
        elif self.is_send_feerate_frozen() and self.feerate_e.get_amount(
        ) is not None:
            amount = self.feerate_e.get_amount()  # sat/byte feerate
            amount = 0 if amount is None else amount * 1000  # sat/kilobyte feerate
            fee_estimator = partial(SimpleConfig.estimate_fee_for_feerate,
                                    amount)
        else:
            fee_estimator = None
        return fee_estimator

    def entry_changed(self):
        # blue color denotes auto-filled values
        text = ""
        fee_color = ColorScheme.DEFAULT
        feerate_color = ColorScheme.DEFAULT
        if self.not_enough_funds:
            fee_color = ColorScheme.RED
            feerate_color = ColorScheme.RED
        elif self.fee_e.isModified():
            feerate_color = ColorScheme.BLUE
        elif self.feerate_e.isModified():
            fee_color = ColorScheme.BLUE
        else:
            fee_color = ColorScheme.BLUE
            feerate_color = ColorScheme.BLUE
        self.fee_e.setStyleSheet(fee_color.as_stylesheet())
        self.feerate_e.setStyleSheet(feerate_color.as_stylesheet())
        #
        self.needs_update = True

    def update_fee_fields(self):
        freeze_fee = self.is_send_fee_frozen()
        freeze_feerate = self.is_send_feerate_frozen()
        if self.no_dynfee_estimates:
            size = self.tx.estimated_size()
            self.size_e.setAmount(size)
        if self.not_enough_funds or self.no_dynfee_estimates:
            if not freeze_fee:
                self.fee_e.setAmount(None)
            if not freeze_feerate:
                self.feerate_e.setAmount(None)
            self.feerounding_icon.setVisible(False)
            return

        tx = self.tx
        size = tx.estimated_size()
        fee = tx.get_fee()

        self.size_e.setAmount(size)

        # Displayed fee/fee_rate values are set according to user input.
        # Due to rounding or dropping dust in CoinChooser,
        # actual fees often differ somewhat.
        if freeze_feerate or self.fee_slider.is_active():
            displayed_feerate = self.feerate_e.get_amount()
            if displayed_feerate is not None:
                displayed_feerate = quantize_feerate(displayed_feerate)
            elif self.fee_slider.is_active():
                # fallback to actual fee
                displayed_feerate = quantize_feerate(
                    fee / size) if fee is not None else None
                self.feerate_e.setAmount(displayed_feerate)
            displayed_fee = round(
                displayed_feerate *
                size) if displayed_feerate is not None else None
            self.fee_e.setAmount(displayed_fee)
        else:
            if freeze_fee:
                displayed_fee = self.fee_e.get_amount()
            else:
                # fallback to actual fee if nothing is frozen
                displayed_fee = fee
                self.fee_e.setAmount(displayed_fee)
            displayed_fee = displayed_fee if displayed_fee else 0
            displayed_feerate = quantize_feerate(
                displayed_fee / size) if displayed_fee is not None else None
            self.feerate_e.setAmount(displayed_feerate)

        # show/hide fee rounding icon
        feerounding = (fee -
                       displayed_fee) if (fee
                                          and displayed_fee is not None) else 0
        self.set_feerounding_text(int(feerounding))
        self.feerounding_icon.setToolTip(self.feerounding_text)
        self.feerounding_icon.setVisible(abs(feerounding) >= 1)

    def can_finalize(self):
        return (self.tx is not None and not self.not_enough_funds)

    def on_finalize(self):
        if not self.can_finalize():
            return
        assert self.tx
        self.finalized = True
        self.tx.set_rbf(self.rbf_cb.isChecked())
        self.tx.locktime = self.locktime_e.get_locktime()
        for widget in [
                self.fee_slider, self.fee_combo, self.feecontrol_fields,
                self.rbf_cb, self.locktime_setter_widget, self.locktime_e
        ]:
            widget.setEnabled(False)
            widget.setVisible(False)
        for widget in [self.rbf_label, self.locktime_final_label]:
            widget.setVisible(True)
        self.set_title()
        self.set_buttons_visibility()
        self.update()
    def __init__(self, parent=None):
        super().__init__(parent)

        # Initialize word database        
        self.word = Word('words.txt')

        # Hangman display window
        self.hangmanWindow = QTextEdit()
        self.hangmanWindow.setReadOnly(True)
        self.hangmanWindow.setAlignment(Qt.AlignLeft)
        font = self.hangmanWindow.font()
        font.setFamily('Courier New')
        self.hangmanWindow.setFont(font)

        # Layout
        hangmanLayout = QGridLayout()
        hangmanLayout.addWidget(self.hangmanWindow, 0, 0)

        # Status Layout creation
        statusLayout = QGridLayout()

        # Display widget for current status
        self.currentWord = QLineEdit()
        self.currentWord.setReadOnly(True)
        self.currentWord.setAlignment(Qt.AlignCenter)
# 가로길이를 300까지 크기를 키워주면 13글자 이상도 들어 갈 수 있다.
        self.currentWord.setFixedWidth(300)
        font = self.currentWord.font()
        font.setPointSize(font.pointSize() + 8)
        self.currentWord.setFont(font)
        statusLayout.addWidget(self.currentWord, 0, 0, 1, 2)

        # Display widget for already used characters
        self.guessedChars = QLineEdit()
        self.guessedChars.setReadOnly(True)
        self.guessedChars.setAlignment(Qt.AlignLeft)
        self.guessedChars.setMaxLength(52)
        statusLayout.addWidget(self.guessedChars, 1, 0, 1, 2)

        # Display widget for message output
        self.message = QLineEdit()
        self.message.setReadOnly(True)
        self.message.setAlignment(Qt.AlignLeft)
        self.message.setMaxLength(52)
        statusLayout.addWidget(self.message, 2, 0, 1, 2)

        # Input widget for user selected characters
        self.charInput = QLineEdit()
        self.charInput.setMaxLength(1)
        statusLayout.addWidget(self.charInput, 3, 0)

        # Button for submitting a character
        self.guessButton = QToolButton()
        self.guessButton.setText('Guess!')
        self.guessButton.clicked.connect(self.guessClicked)
        statusLayout.addWidget(self.guessButton, 3, 1)

        # Button for a new game
        self.newGameButton = QToolButton()
        self.newGameButton.setText('New Game')
        self.newGameButton.clicked.connect(self.startGame)
        statusLayout.addWidget(self.newGameButton, 4, 0)

        # Layout placement
        mainLayout = QGridLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)
        mainLayout.addLayout(hangmanLayout, 0, 0)
        mainLayout.addLayout(statusLayout, 0, 1)

        self.setLayout(mainLayout)

        self.setWindowTitle('Hangman Game')

        # Start a new game on application launch!
        self.startGame()
    def __init__(self, parent=None):
        super().__init__(parent)

        # Display Window
        self.display = QLineEdit()
        self.display.setReadOnly(True)
        self.display.setAlignment(Qt.AlignRight)
        self.display.setMaxLength(15)

        # Digit Buttons
        self.digitButton = [x for x in range(0, 10)]

        for i in range(10):
            self.digitButton[i] = QToolButton()
            self.digitButton[i].setText(str(i))
            self.digitButton[i] = Button(str(i), self.buttonClicked)

        #self.digitButton[0] = Button('0', self.buttonClicked)
        #self.digitButton[1] = Button('1', self.buttonClicked)
        #self.digitButton[2] = Button('2', self.buttonClicked)
        #self.digitButton[3] = Button('3', self.buttonClicked)
        #self.digitButton[4] = Button('4', self.buttonClicked)
        #self.digitButton[5] = Button('5', self.buttonClicked)
        #self.digitButton[6] = Button('6', self.buttonClicked)
        #self.digitButton[7] = Button('7', self.buttonClicked)
        #self.digitButton[8] = Button('8', self.buttonClicked)
        #self.digitButton[9] = Button('9', self.buttonClicked)

        # . and = Buttons
        self.decButton = Button('.', self.buttonClicked)
        self.eqButton = Button('=', self.buttonClicked)

        # Operator Buttons
        self.mulButton = Button('*', self.buttonClicked)
        self.divButton = Button('/', self.buttonClicked)
        self.addButton = Button('+', self.buttonClicked)
        self.subButton = Button('-', self.buttonClicked)

        # Parentheses Buttons
        self.lparButton = Button('(', self.buttonClicked)
        self.rparButton = Button(')', self.buttonClicked)

        # Clear Button
        self.clearButton = Button('C', self.buttonClicked)

        # Layout
        mainLayout = QGridLayout()
        mainLayout.setSizeConstraint(QLayout.SetFixedSize)

        #Button clicked

        mainLayout.addWidget(self.display, 0, 0, 1, 2)

        numLayout = QGridLayout()
        for i in range(10):
            if i == 0:
                col = 0
                row = 3 - i // 3
            elif i % 3 == 0:
                col = 2
                row = 3 - i // 3
            else:
                col = i % 3 - 1
                row = 2 - i // 3
            numLayout.addWidget(self.digitButton[i], row, col)

        #numLayout.addWidget(self.digitButton[0], 3, 0) #(
        #numLayout.addWidget(self.digitButton[1], 2, 0)
        #numLayout.addWidget(self.digitButton[2], 2, 1)
        #numLayout.addWidget(self.digitButton[3], 2, 2)
        #numLayout.addWidget(self.digitButton[4], 1, 0)
        #numLayout.addWidget(self.digitButton[5], 1, 1)
        #numLayout.addWidget(self.digitButton[6], 1, 2)
        #numLayout.addWidget(self.digitButton[7], 0, 0)
        #numLayout.addWidget(self.digitButton[8], 0, 1)
        #numLayout.addWidget(self.digitButton[9], 0, 2)

        numLayout.addWidget(self.decButton, 3, 1)
        numLayout.addWidget(self.eqButton, 3, 2)

        mainLayout.addLayout(numLayout, 1, 0)

        opLayout = QGridLayout()

        opLayout.addWidget(self.mulButton, 0, 0)
        opLayout.addWidget(self.divButton, 0, 1)
        opLayout.addWidget(self.addButton, 1, 0)
        opLayout.addWidget(self.subButton, 1, 1)

        opLayout.addWidget(self.lparButton, 2, 0)
        opLayout.addWidget(self.rparButton, 2, 1)

        opLayout.addWidget(self.clearButton, 3, 0)

        mainLayout.addLayout(opLayout, 1, 1)

        self.setLayout(mainLayout)

        self.setWindowTitle("My Calculator")
Example #57
0
class Ui_Register(object):
    def __init__(self, WidgetStack, UIStack):
        self.WidgetStack = WidgetStack
        self.UIStack = UIStack

    WidgetStack = None
    UIStack = None

    hasShow = True

    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1013, 772)
        Form.setStyleSheet("*{\n"
                           "font-size:24px;\n"
                           "font-family:Century Gothic;\n"
                           "}\n"
                           "#Form{ \n"
                           "    background: url(:/resources/background.jpg);\n"
                           "}\n"
                           "\n"
                           "QFrame{\n"
                           "background:rgba(0,0,0,0.8);\n"
                           "border-radius:15px;\n"
                           "}\n"
                           "\n"
                           "QToolButton{\n"
                           "background:#49ebff;\n"
                           "border-radius:60px;\n"
                           "}\n"
                           "QLabel{\n"
                           "color:white;\n"
                           "background:transparent;\n"
                           "}\n"
                           "QPushButton{\n"
                           "background:#49ebff;\n"
                           "border-radius:15px;\n"
                           "}\n"
                           "QPushButton:hover{\n"
                           "background:white;\n"
                           "border-radius:15px;\n"
                           "\n"
                           "}\n"
                           "QLineEdit{\n"
                           "background:transparent;\n"
                           "border:none;\n"
                           "color:#717072;\n"
                           "border-bottom:1px solid #717072;\n"
                           "}"
                           "QErrorMessage{\n"
                           "color:red;\n"
                           "}\n")
        self.frame = QFrame(Form)
        self.frame.setGeometry(QRect(240, 120, 491, 521))
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName("frame")
        self.lineEdit = QLineEdit(self.frame)
        self.lineEdit.setGeometry(QRect(100, 140, 301, 41))
        self.lineEdit.setText("")
        self.lineEdit.setObjectName("lineEdit")
        self.label = QLabel(self.frame)
        self.label.setGeometry(QRect(160, 50, 191, 41))
        self.label.setObjectName("label")
        self.lineEdit_2 = QLineEdit(self.frame)
        self.lineEdit_2.setGeometry(QRect(100, 240, 301, 31))
        self.lineEdit_2.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        self.lineEdit_2.setText("")
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_6 = QLineEdit(self.frame)
        self.lineEdit_6.setGeometry(QRect(100, 320, 301, 41))
        self.lineEdit_6.setText("")
        self.lineEdit_6.setObjectName("lineEdit_6")
        self.pushButton = QPushButton(self.frame)
        self.pushButton.setGeometry(QRect(30, 440, 171, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QPushButton(self.frame)
        self.pushButton_2.setGeometry(QRect(280, 440, 171, 41))
        self.pushButton_2.setObjectName("pushButton_2")
        self.toolButton = QToolButton(Form)
        self.toolButton.setGeometry(QRect(420, 30, 131, 121))
        self.toolButton.setText("")
        icon = QIcon()
        icon.addPixmap(QPixmap(":/resources/people.png"), QIcon.Normal,
                       QIcon.Off)
        self.toolButton.setIcon(icon)
        self.toolButton.setIconSize(QSize(64, 64))
        self.toolButton.setObjectName("toolButton")

        self.retranslateUi(Form)
        QMetaObject.connectSlotsByName(Form)

    def retranslateUi(self, Form):
        _translate = QCoreApplication.translate
        Form.setWindowTitle(_translate("Form", "智慧考勤"))
        self.lineEdit.setPlaceholderText(_translate("Form", "Username"))
        self.label.setText(_translate("Form", "请输入个人信息"))
        self.lineEdit_2.setText(_translate("Form", ""))
        self.lineEdit_2.setPlaceholderText(_translate("Form", "Passwoed"))
        self.lineEdit_6.setPlaceholderText(_translate("Form", "Email Address"))
        self.pushButton.setText(_translate("Form", "注 册"))
        self.pushButton_2.setText(_translate("Form", "返 回"))

        self.pushButton_2.clicked.connect(lambda: self.onPushButton_2Click())
        self.pushButton.clicked.connect(lambda: self.onPushButton_Click())

        self.lineEdit_2.textChanged.connect(self.textChanged2)
        self.lineEdit_6.textChanged.connect(self.textChanged6)
        self.lineEdit.textChanged.connect(self.textChanged)

        #self.pushButton_2.clicked.connect(lambda: self.onPushButtonClick()) #注册接口

    def textChanged2(self, text):
        self.lineEdit_2.setText(text)

    def textChanged6(self, text):
        self.lineEdit_6.setText(text)

    def textChanged(self, text):
        self.lineEdit.setText(text)

    def onPushButton_Click(self):
        arr = []
        arr.append(self.lineEdit_6.text())
        arr.append(self.lineEdit_2.text())
        arr.append(self.lineEdit.text())
        arr.append(100)
        print(SendJSON.getRegisterJSON(arr))
        res = Connect.sendJSON("/client/register",
                               SendJSON.getRegisterJSON(arr))
        if res == None:
            self.hasShow = not self.hasShow
            if self.hasShow == False:
                err = QErrorMessage(self.frame)
                err.setStyleSheet("color:#880000;background:white;")
                err.showMessage("注册失败!")
            return
        if res["msg"] == "ok":
            self.hasShow = not self.hasShow
            if self.hasShow == False:
                err = QErrorMessage(self.frame)
                err.setStyleSheet("color:green;background:white;")
                err.showMessage("注册成功!")

    def onPushButton_2Click(self):
        self.jumpToLogin()

    def jumpToLogin(self):
        hasFind = False
        import src.Login
        self.WidgetStack[3].hide()
        for ui in self.UIStack:
            print(ui.__class__.__name__)
            if ui.__class__.__name__ == "Ui_Login":
                ui.setupUi(self.WidgetStack[1])
                ui.retranslateUi(self.WidgetStack[1])
                hasFind = True
        if hasFind == False:
            newUi = src.Login.Ui_Login(self.WidgetStack, self.UIStack)
            newUi.setupUi(self.WidgetStack[1])
            newUi.retranslateUi(self.WidgetStack[1])
            self.UIStack.append(newUi)
        self.WidgetStack[1].show()
Example #58
0
    def setupUi(self, Form):
        Form.setObjectName("Form")
        Form.resize(1013, 772)
        Form.setStyleSheet("*{\n"
                           "font-size:24px;\n"
                           "font-family:Century Gothic;\n"
                           "}\n"
                           "#Form{ \n"
                           "    background: url(:/resources/background.jpg);\n"
                           "}\n"
                           "\n"
                           "QFrame{\n"
                           "background:rgba(0,0,0,0.8);\n"
                           "border-radius:15px;\n"
                           "}\n"
                           "\n"
                           "QToolButton{\n"
                           "background:#49ebff;\n"
                           "border-radius:60px;\n"
                           "}\n"
                           "QLabel{\n"
                           "color:white;\n"
                           "background:transparent;\n"
                           "}\n"
                           "QPushButton{\n"
                           "background:#49ebff;\n"
                           "border-radius:15px;\n"
                           "}\n"
                           "QPushButton:hover{\n"
                           "background:white;\n"
                           "border-radius:15px;\n"
                           "\n"
                           "}\n"
                           "QLineEdit{\n"
                           "background:transparent;\n"
                           "border:none;\n"
                           "color:#717072;\n"
                           "border-bottom:1px solid #717072;\n"
                           "}"
                           "QErrorMessage{\n"
                           "color:red;\n"
                           "}\n")
        self.frame = QFrame(Form)
        self.frame.setGeometry(QRect(240, 120, 491, 521))
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName("frame")
        self.lineEdit = QLineEdit(self.frame)
        self.lineEdit.setGeometry(QRect(100, 140, 301, 41))
        self.lineEdit.setText("")
        self.lineEdit.setObjectName("lineEdit")
        self.label = QLabel(self.frame)
        self.label.setGeometry(QRect(160, 50, 191, 41))
        self.label.setObjectName("label")
        self.lineEdit_2 = QLineEdit(self.frame)
        self.lineEdit_2.setGeometry(QRect(100, 240, 301, 31))
        self.lineEdit_2.setEchoMode(QLineEdit.PasswordEchoOnEdit)
        self.lineEdit_2.setText("")
        self.lineEdit_2.setObjectName("lineEdit_2")
        self.lineEdit_6 = QLineEdit(self.frame)
        self.lineEdit_6.setGeometry(QRect(100, 320, 301, 41))
        self.lineEdit_6.setText("")
        self.lineEdit_6.setObjectName("lineEdit_6")
        self.pushButton = QPushButton(self.frame)
        self.pushButton.setGeometry(QRect(30, 440, 171, 41))
        self.pushButton.setObjectName("pushButton")
        self.pushButton_2 = QPushButton(self.frame)
        self.pushButton_2.setGeometry(QRect(280, 440, 171, 41))
        self.pushButton_2.setObjectName("pushButton_2")
        self.toolButton = QToolButton(Form)
        self.toolButton.setGeometry(QRect(420, 30, 131, 121))
        self.toolButton.setText("")
        icon = QIcon()
        icon.addPixmap(QPixmap(":/resources/people.png"), QIcon.Normal,
                       QIcon.Off)
        self.toolButton.setIcon(icon)
        self.toolButton.setIconSize(QSize(64, 64))
        self.toolButton.setObjectName("toolButton")

        self.retranslateUi(Form)
        QMetaObject.connectSlotsByName(Form)
class QCustomTitleBar ( QFrame ):
	onMousePressEvent = pyqtSignal ( QEvent )
	onMouseMoveEvent = pyqtSignal ( QEvent )
	onMouseReleaseEvent = pyqtSignal ( QEvent )
	onCloseButtonClickedEvent = pyqtSignal ( QWidget )

	def __init__ ( self, parent ):
		super ( QCustomTitleBar, self ).__init__ ( parent )
		# print ( "[create] QCustomTitleBar for parent", parent )
		self.dragging = False
		self.createFromDraging = False
		self.mouseStartPos = QCursor.pos ()

		if parent.metaObject ().indexOfSignal ( QMetaObject.normalizedSignature ( "contentsChanged" ) ) != -1:
			parent.contentsChanged.connect ( self.onFrameContentsChanged )

		myLayout = QHBoxLayout ( self )
		myLayout.setContentsMargins ( 0, 0, 0, 0 )
		myLayout.setSpacing ( 0 )

		self.setLayout ( myLayout )

		self.caption = QLabel ( self )
		self.caption.setAttribute ( QtCore.Qt.WA_TransparentForMouseEvents )
		self.caption.setSizePolicy ( QSizePolicy.Expanding, QSizePolicy.Preferred )

		self.sysMenuButton = QToolButton ( self )
		self.onIconChange ()
		self.sysMenuButton.setObjectName ( "sysMenu" )
		self.sysMenuButton.setFocusPolicy ( QtCore.Qt.NoFocus )
		self.sysMenuButton.installEventFilter ( self )
		myLayout.addWidget ( self.sysMenuButton )
		myLayout.addWidget ( self.caption, 1 )

		self.minimizeButton = QToolButton ( self )
		self.minimizeButton.setObjectName ( "minimizeButton" )
		self.minimizeButton.setFocusPolicy ( QtCore.Qt.NoFocus )
		# self.minimizeButton.clicked.connect ( parent.showMinimized )
		self.minimizeButton.clicked.connect ( lambda: parent.setWindowState ( Qt.WindowMinimized ) )
		myLayout.addWidget ( self.minimizeButton )

		self.maximizeButton = QToolButton ( self )
		self.maximizeButton.setObjectName ( "maximizeButton" )
		self.maximizeButton.setFocusPolicy ( QtCore.Qt.NoFocus )
		self.maximizeButton.clicked.connect ( self.toggleMaximizedParent )
		myLayout.addWidget ( self.maximizeButton )

		self.closeButton = QToolButton ( self )
		self.closeButton.setObjectName ( "closeButton" )
		self.closeButton.setFocusPolicy ( QtCore.Qt.NoFocus )
		self.closeButton.clicked.connect ( self.onCloseButtonClicked )
		myLayout.addWidget ( self.closeButton )

		parent.windowTitleChanged.connect ( self.caption.setText )
		parent.windowIconChanged.connect ( self.onIconChange )

		self.onFrameContentsChanged ( parent )

		# self.setMouseTracking ( True )

	def updateWindowStateButtons ( self ):
		if self.maximizeButton:
			if self.parentWidget ().windowState () & QtCore.Qt.WindowMaximized:
				self.maximizeButton.setObjectName ( "restoreButton" )
			else:
				self.maximizeButton.setObjectName ( "maximizeButton" )

			self.style ().unpolish ( self.maximizeButton )
			self.style ().polish ( self.maximizeButton )

	def setActive ( self, active ):
		self.caption.setObjectName ( "active" if active else "inactive" )
		self.style ().unpolish ( self.caption )
		self.style ().polish ( self.caption )

	def toggleMaximizedParent ( self ):
		if self.parentWidget ().windowState () & QtCore.Qt.WindowMaximized:
			self.parentWidget ().showNormal ()
		else:
			self.parentWidget ().showMaximized ()
		self.updateWindowStateButtons ()

	def toggleMinimizedParent ( self ):
		flags = self.parentWidget ().windowFlags ()
		self.parentWidget ().setWindowFlags ( flags | QtCore.Qt.CustomizeWindowHint & ~QtCore.Qt.WindowTitleHint )
		# self.setWindowFlags ( flags | QtCore.Qt.CustomizeWindowHint & ~QtCore.Qt.WindowTitleHint )
		self.parentWidget ().showMinimized ()
		self.parentWidget ().setWindowFlags ( self.parentWidget ().windowFlags () & (
					~QtCore.Qt.CustomContextMenu & ~QtCore.Qt.WindowTitleHint ) | QtCore.Qt.FramelessWindowHint )

	def showSystemMenu ( self, p ):
		pass

	def onCloseButtonClicked ( self ):
		# print ( "[QCustomTitleBar] close requested. %s" % self.parentWidget () )
		self.onCloseButtonClickedEvent.emit ( self )
		self.parentWidget ().close ()

	def onIconChange ( self ):
		icon = self.parentWidget ().windowIcon ()
		if icon is None:
			icon = qApp.windowIcon ()
			if icon is None:
				pass
		self.sysMenuButton.setIcon ( icon )

	def onFrameContentsChanged ( self, newContents ):
		flags = self.parentWidget ().windowFlags ()
		self.minimizeButton.setVisible (
			flags & QtCore.Qt.WindowMinimizeButtonHint or flags & QtCore.Qt.MSWindowsFixedSizeDialogHint )
		self.maximizeButton.setVisible (
			flags & QtCore.Qt.WindowMaximizeButtonHint or flags & QtCore.Qt.MSWindowsFixedSizeDialogHint )
		self.closeButton.setVisible ( flags & QtCore.Qt.WindowCloseButtonHint )

		winTitle = self.parentWidget ().windowTitle ()
		if len ( winTitle ) == 0:
			self.caption.setText ( "[QCustomTitleBar] onFrameContentsChanged NoneWindowTitle" )
			return
		self.caption.setText ( winTitle )

	def onBeginDrag ( self ):
		self.dragging = True

	def mousePressEvent ( self, e ):

		self.onMousePressEvent.emit ( e )

		if e.button () == QtCore.Qt.LeftButton and qApp.widgetAt ( QCursor.pos () ) != self.sysMenuButton:
			self.onBeginDrag ()
			self.mouseStartPos = e.globalPos ()
			# qWarning ( "QCustomTitleBar::onBeginDrag" )

		super ().mousePressEvent ( e )

	def mouseMoveEvent ( self, e ):

		self.onMouseMoveEvent.emit ( e )

		if self.dragging:
			# self.window ().move ( e.globalPos () - self.mouseStartPos )
			offset = self.mouseStartPos - e.globalPos ()
			self.mouseStartPos = e.globalPos ()
			self.window ().move ( self.window ().pos () - offset )
			e.accept ()
			# qWarning ( "QCustomTitleBar::mouseMoveEvent" )
		else:
			super ().mouseMoveEvent ( e )

	def mouseReleaseEvent ( self, e ):

		self.onMouseReleaseEvent.emit ( e )

		if not self.dragging:
			if e.button () == QtCore.Qt.RightButton and self.rect ().contains ( self.mapFromGlobal ( QCursor.pos () ) ):
				e.accept ()
				self.showSystemMenu ( QCursor.pos () )
			else:
				e.ignore ()
			return
		self.dragging = False

		if self.createFromDraging:
			self.releaseMouse ()
			self.createFromDraging = False

		# qWarning ( "QCustomTitleBar::mouseReleaseEvent" )

		super ().mouseReleaseEvent ( e )

	def mouseDoubleClickEvent ( self, e ):
		e.accept ()
		self.toggleMaximizedParent ()

	def eventFilter ( self, o, e ):
		if o == self.sysMenuButton:
			if e.type () == QEvent.MouseButtonPress:
				if e.button () == QtCore.Qt.LeftButton and qApp.widgetAt ( QCursor.pos () ) == self.sysMenuButton:
					self.showSystemMenu ( self.mapToGlobal ( self.rect ().bottomLeft () ) )
					return True
			if e.type () == QEvent.MouseButtonDblClick:
				if e.button () == QtCore.Qt.LeftButton and qApp.widgetAt ( QCursor.pos () ) == self.sysMenuButton:
					self.parentWidget ().close ()
					return True

		return super ().eventFilter ( o, e )
Example #60
0
 def insert_mn_list(self, name, ip, port, row=None):
     mnRow = QWidget()
     mnRow.setToolTip("Drag & Drop rows to reorder")
     mnRowLayout = QHBoxLayout()
     ##--- Led
     self.mnLed[name] = QLabel()
     self.mnLed[name].setPixmap(self.caller.ledGrayV_icon)
     mnRowLayout.addWidget(self.mnLed[name])
     ##--- Label
     self.mnLabel[name] = QLabel()
     self.mnLabel[name].setText(
         "%s &nbsp; [<i style='color: #2f005f'>%s:%s</i>]" %
         (name, ip, port))
     mnRowLayout.addWidget(self.mnLabel[name])
     mnRowLayout.addStretch(1)
     ##--- Status Label
     self.mnStatusLabel[name] = QLabel()
     mnRowLayout.addWidget(self.mnStatusLabel[name])
     self.mnStatusLabel[name].hide()
     ##--- Details button
     self.btn_details[name] = QToolButton()
     self.btn_details[name].setIcon(self.details_icon)
     self.btn_details[name].setToolTip(
         'Check STATUS details of masternode "%s"' % name)
     mnRowLayout.addWidget(self.btn_details[name])
     self.btn_details[name].hide()
     ##--- Status button
     self.btn_status[name] = QPushButton()
     self.btn_status[name].setToolTip('get status of masternode "%s"' %
                                      name)
     self.btn_status[name].setIcon(self.getMNstatus_icon)
     self.btn_status[name].alias = name
     mnRowLayout.addWidget(self.btn_status[name])
     ##--- Rewards button
     self.btn_rewards[name] = QPushButton()
     self.btn_rewards[name].setToolTip(
         'tranfer rewards from masternode "%s"' % name)
     self.btn_rewards[name].setIcon(self.rewards_icon)
     self.btn_rewards[name].alias = name
     mnRowLayout.addWidget(self.btn_rewards[name])
     ##--- Start button
     self.btn_start[name] = QPushButton()
     self.btn_start[name].setToolTip('start masternode "%s"' % name)
     self.btn_start[name].setIcon(self.startMN_icon)
     self.btn_start[name].alias = name
     mnRowLayout.addWidget(self.btn_start[name])
     ##--- Edit button
     self.btn_edit[name] = QPushButton()
     self.btn_edit[name].setToolTip('edit masternode "%s"' % name)
     self.btn_edit[name].setIcon(self.editMN_icon)
     self.btn_edit[name].alias = name
     mnRowLayout.addWidget(self.btn_edit[name])
     ##--- Remove button
     self.btn_remove[name] = QPushButton()
     self.btn_remove[name].setToolTip('remove masternode "%s"' % name)
     self.btn_remove[name].setIcon(self.removeMN_icon)
     self.btn_remove[name].alias = name
     mnRowLayout.addWidget(self.btn_remove[name])
     ##--- Three Dots
     threeDots = QLabel()
     threeDots.setPixmap(
         self.threeDots_icon.scaledToHeight(20, Qt.SmoothTransformation))
     mnRowLayout.addWidget(threeDots)
     ##--- Set Row Layout
     mnRow.setLayout(mnRowLayout)
     ##--- Append Row
     self.current_mn[name] = QListWidgetItem()
     #self.current_mn[name].setFlags(Qt.ItemIsSelectable)
     self.current_mn[name].setSizeHint(mnRow.sizeHint())
     if row is not None:
         self.myList.insertItem(row, self.current_mn[name])
     else:
         self.myList.addItem(self.current_mn[name])
     self.myList.setItemWidget(self.current_mn[name], mnRow)