Exemplo n.º 1
0
class MotorizedLinearPoti(COMCUPluginBase):
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletMotorizedLinearPoti, *args)

        self.mp = self.device

        self.cbe_position = CallbackEmulator(self.mp.get_position,
                                             self.cb_position,
                                             self.increase_error_count)

        self.current_position = None

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(0, 100)
        self.slider.setMinimumWidth(200)
        self.slider.setEnabled(False)

        plots = [('Potentiometer Position', Qt.red, lambda: self.current_position, str)]
        self.plot_widget = PlotWidget('Position', plots, extra_key_widgets=[self.slider],
                                      curve_motion_granularity=40, update_interval=0.025)

        self.motor_slider = QSlider(Qt.Horizontal)
        self.motor_slider.setRange(0, 100)
        self.motor_slider.valueChanged.connect(self.motor_slider_value_changed)
        self.motor_hold_position = QCheckBox("Hold Position")
        self.motor_drive_mode = QComboBox()
        self.motor_drive_mode.addItem('Fast')
        self.motor_drive_mode.addItem('Smooth')
        
        def get_motor_slider_value():
            return self.motor_slider.value()
        
        self.motor_hold_position.stateChanged.connect(lambda x: self.motor_slider_value_changed(get_motor_slider_value()))
        self.motor_drive_mode.currentIndexChanged.connect(lambda x: self.motor_slider_value_changed(get_motor_slider_value()))

        self.motor_position_label = MotorPositionLabel('Motor Target Position:')

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.motor_position_label)
        hlayout.addWidget(self.motor_slider)
        hlayout.addWidget(self.motor_drive_mode)
        hlayout.addWidget(self.motor_hold_position)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(hlayout)

    def start(self):
        async_call(self.mp.get_position, None, self.cb_position, self.increase_error_count)
        async_call(self.mp.get_motor_position, None, self.cb_motor_position, self.increase_error_count)

        self.cbe_position.set_period(25)
        self.plot_widget.stop = False

    def stop(self):
        self.cbe_position.set_period(0)
        self.plot_widget.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletMotorizedLinearPoti.DEVICE_IDENTIFIER

    def cb_position(self, position):
        self.current_position = position
        self.slider.setValue(position)

    def cb_motor_position(self, motor):
        self.motor_slider.blockSignals(True)
        self.motor_hold_position.blockSignals(True)
        self.motor_drive_mode.blockSignals(True)

        self.motor_hold_position.setChecked(motor.hold_position)
        self.motor_drive_mode.setCurrentIndex(motor.drive_mode)
        self.motor_position_label.setText(str(motor.position))
        self.motor_slider.setValue(motor.position)

        self.motor_slider.blockSignals(False)
        self.motor_hold_position.blockSignals(False)
        self.motor_drive_mode.blockSignals(False)

    
    def motor_slider_value_changed(self, position):
        self.motor_position_label.setText(str(position))
        self.mp.set_motor_position(self.motor_slider.value(), self.motor_drive_mode.currentIndex(), self.motor_hold_position.isChecked())
Exemplo n.º 2
0
class RecordingWidget(QWidgetWithDpi):
    """Widget containing main recording UI for Freeseer"""

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

        icon = QIcon()
        icon.addPixmap(QPixmap(":/freeseer/logo.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.resize(400, 400)

        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.setStyleSheet(
            """
            QToolButton {
                background-color: #D1D1D1;
                border-style: solid;
                border-width: 1px;
                border-radius: 10px;
                border-color: #969696;
                padding: 6px;
            }

            QToolButton:pressed {
                background-color: #A3A2A2;
                border-width: 2px;
                border-color: #707070;
            }

            QToolButton:checked {
                background-color: #A3A2A2;
                border-width: 2px;
                border-color: #707070;
            }

            QToolButton:disabled {
                background-color: #EDEDED;
                border-color: #BFBDBD;
            }

            QToolButton:hover {
                border-width: 2px;
            }
        """
        )

        boldFont = QFont()
        boldFont.setBold(True)

        fontSize = self.font().pixelSize()
        fontUnit = "px"
        if fontSize == -1:  # Font is set as points, not pixels.
            fontUnit = "pt"
            fontSize = self.font().pointSize()

        # Control bar
        self.controlRow = QHBoxLayout()
        self.mainLayout.addLayout(self.controlRow)

        self.recordIcon = QIcon(":/multimedia/record.png")
        self.stopIcon = QIcon(":/multimedia/stop.png")
        pauseIcon = QIcon(":/multimedia/pause.png")
        playIcon = QIcon(":/multimedia/play.png")
        self.headphoneIcon = QIcon()
        self.headphoneIcon.addPixmap(QPixmap(":/multimedia/headphones.png"), QIcon.Normal, QIcon.Off)

        self.is_recording = False
        self.recordButton = QToolButtonWithDpi()
        self.recordButton.setToolTip("Record")
        self.recordButton.setFixedSize(QSize(60, 40))
        self.recordButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.recordButton.setIcon(self.recordIcon)
        self.recordButton.setEnabled(False)
        self.recordButton.setObjectName("recordButton")
        self.controlRow.addWidget(self.recordButton, 0, Qt.AlignLeft)
        self.connect(self.recordButton, SIGNAL("clicked()"), self.setRecordIcon)

        self.playButton = QToolButtonWithDpi()
        self.playButton.setToolTip("Play last recorded Video")
        self.playButton.setFixedSize(QSize(60, 40))
        self.playButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.playButton.setIcon(playIcon)
        self.playButton.setEnabled(False)
        self.controlRow.addWidget(self.playButton, 0, Qt.AlignLeft)

        self.pauseButton = QToolButtonWithDpi()
        self.pauseButton.setToolTip("Pause")
        self.pauseButton.setIcon(pauseIcon)
        self.pauseButton.setFixedSize(QSize(60, 40))
        self.pauseButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.pauseButton.setEnabled(False)
        self.pauseButton.setCheckable(True)
        self.controlRow.addWidget(self.pauseButton, 0, Qt.AlignLeft)

        self.controlRow.addSpacerItem(self.qspacer_item_with_dpi(30, 40))
        self.controlRow.addStretch(1)

        self.standbyButton = QPushButtonWithDpi("Standby")
        self.standbyButton.setStyleSheet(
            """
            QPushButton {{
                color: white;
                background-color: #47a447;
                border-style: solid;
                border-width: 0px;
                border-radius: 10px;
                border-color: #398439;
                font: bold {}{};
                padding: 6px;
            }}

            QPushButton:pressed {{
                background-color: #3E8A3E;
                border-color: #327532;
            }}

            QPushButton:hover {{
                border-width: 2px;
            }}
        """.format(
                fontSize + 3, fontUnit
            )
        )
        self.standbyButton.setToolTip("Standby")
        self.standbyButton.setFixedSize(QSize(180, 40))
        self.standbyButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.standbyButton.setCheckable(True)
        self.standbyButton.setObjectName("standbyButton")
        self.controlRow.addWidget(self.standbyButton)

        self.disengageButton = QPushButtonWithDpi("Leave record-mode")
        self.disengageButton.setStyleSheet(
            """
            QPushButton {{
                color: white;
                background-color: #D14343;
                border-style: solid;
                border-width: 0px;
                border-radius: 10px;
                border-color: #B02C2C;
                font: bold {}{};
                padding: 6px;
            }}

            QPushButton:pressed {{
                background-color: #AD2B2B;
                border-color: #8C2929;
            }}

            QPushButton:hover {{
                border-width: 2px;
            }}

            QPushButton:disabled {{
                background-color: #B89E9E;
        }}
        """.format(
                fontSize + 3, fontUnit
            )
        )
        self.disengageButton.setToolTip("Leave record-mode")
        self.disengageButton.setFixedSize(QSize(180, 40))
        self.disengageButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.disengageButton.setHidden(True)
        self.disengageButton.setObjectName("disengageButton")
        self.controlRow.addWidget(self.disengageButton)

        # Filter bar
        self.filterBarLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.filterBarLayout)

        self.filterBarLayoutRow_1 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_1)
        self.eventLabel = QLabel("Event")
        self.eventLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.eventComboBox = QComboBox()
        self.eventLabel.setBuddy(self.eventComboBox)
        self.roomLabel = QLabel("Room")
        self.roomLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.roomComboBox = QComboBox()
        self.roomLabel.setBuddy(self.roomComboBox)
        self.dateLabel = QLabel("Date")
        self.dateLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.dateComboBox = QComboBox()
        self.dateLabel.setBuddy(self.dateComboBox)
        self.filterBarLayoutRow_1.addWidget(self.eventLabel)
        self.filterBarLayoutRow_1.addWidget(self.eventComboBox)
        self.filterBarLayoutRow_1.addWidget(self.roomLabel)
        self.filterBarLayoutRow_1.addWidget(self.roomComboBox)
        self.filterBarLayoutRow_1.addWidget(self.dateLabel)
        self.filterBarLayoutRow_1.addWidget(self.dateComboBox)

        self.filterBarLayoutRow_2 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_2)
        self.talkLabel = QLabel("Talk ")
        self.talkLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.talkComboBox = QComboBox()
        self.talkComboBox.setFont(boldFont)
        self.talkComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        self.talkComboBox.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.filterBarLayoutRow_2.addWidget(self.talkLabel)
        self.filterBarLayoutRow_2.addWidget(self.talkComboBox)

        # Preview Layout
        self.previewLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.previewLayout)

        self.previewWidget = QWidget()
        self.audioSlider = QSlider()
        self.audioSlider.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.audioSlider.setEnabled(False)
        self.previewLayout.addWidget(self.previewWidget)
        self.previewLayout.addWidget(self.audioSlider)

        self.statusLabel = QLabel()
        self.mainLayout.addWidget(self.statusLabel)

        # Audio Feedback Checkbox
        self.audioFeedbackCheckbox = QCheckBox()
        self.audioFeedbackCheckbox.setLayoutDirection(Qt.RightToLeft)
        self.audioFeedbackCheckbox.setIcon(self.headphoneIcon)
        self.audioFeedbackCheckbox.setToolTip("Enable Audio Feedback")
        self.mainLayout.addWidget(self.audioFeedbackCheckbox)

    def setRecordIcon(self):
        self.is_recording = not self.is_recording
        if self.is_recording:
            self.recordButton.setIcon(self.stopIcon)
        else:
            self.recordButton.setIcon(self.recordIcon)
Exemplo n.º 3
0
class RecordingWidget(QWidget):
    """Widget containing main recording UI for Freeseer"""

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

        icon = QIcon()
        icon.addPixmap(QPixmap(":/freeseer/logo.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.resize(400, 400)

        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        boldFont = QFont()
        boldFont.setBold(True)

        # Control bar
        self.controlRow = QHBoxLayout()
        self.mainLayout.addLayout(self.controlRow)

        self.standbyIcon = QIcon.fromTheme("system-shutdown")
        recordFallbackIcon = QIcon(":/multimedia/record.png")
        self.recordIcon = QIcon.fromTheme("media-record", recordFallbackIcon)
        stopFallbackIcon = QIcon(":/multimedia/stop.png")
        self.stopIcon = QIcon.fromTheme("media-playback-stop", stopFallbackIcon)
        self.pauseIcon = QIcon.fromTheme("media-playback-pause")
        self.resumeIcon = QIcon.fromTheme("media-playback-start")
        self.headphoneIcon = QIcon()
        self.headphoneIcon.addPixmap(QPixmap(":/multimedia/headphones.png"), QIcon.Normal, QIcon.Off)

        self.standbyPushButton = QPushButton("Standby")
        self.standbyPushButton.setToolTip("Standby")
        self.standbyPushButton.setMinimumSize(QSize(0, 40))
        self.standbyPushButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.standbyPushButton.setIcon(self.standbyIcon)
        self.standbyPushButton.setCheckable(True)
        self.standbyPushButton.setObjectName("standbyButton")
        self.controlRow.addWidget(self.standbyPushButton)

        self.recordPushButton = QPushButton("Record")
        self.recordPushButton.setToolTip("Record")
        self.recordPushButton.setMinimumSize(QSize(0, 40))
        self.recordPushButton.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.recordPushButton.setIcon(self.recordIcon)
        self.recordPushButton.setHidden(True)
        self.recordPushButton.setEnabled(False)
        self.recordPushButton.setCheckable(True)
        self.recordPushButton.setObjectName("recordButton")
        self.controlRow.addWidget(self.recordPushButton)
        self.connect(self.recordPushButton, SIGNAL("toggled(bool)"), self.setRecordIcon)

        self.pauseToolButton = QToolButton()
        self.pauseToolButton.setText("Pause")
        self.pauseToolButton.setToolTip("Pause")
        self.pauseToolButton.setIcon(self.pauseIcon)
        self.pauseToolButton.setMinimumSize(QSize(40, 40))
        self.pauseToolButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.pauseToolButton.setHidden(True)
        self.pauseToolButton.setEnabled(False)
        self.pauseToolButton.setCheckable(True)
        self.controlRow.addWidget(self.pauseToolButton)
        self.connect(self.pauseToolButton, SIGNAL("toggled(bool)"), self.setPauseIcon)

        playbackIcon = QIcon.fromTheme("video-x-generic")
        self.playPushButton = QPushButton()
        self.playPushButton.setText("Play Video")
        self.playPushButton.setToolTip("Play last recorded Video")
        self.playPushButton.setIcon(playbackIcon)
        self.playPushButton.setMinimumSize(QSize(40, 40))
        self.playPushButton.setMaximumSize(QSize(120, 40))
        self.playPushButton.setHidden(True)
        self.playPushButton.setEnabled(False)
        self.playPushButton.setCheckable(True)
        self.controlRow.addWidget(self.playPushButton)

        # Filter bar
        self.filterBarLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.filterBarLayout)

        self.filterBarLayoutRow_1 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_1)
        self.eventLabel = QLabel("Event")
        self.eventLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.eventComboBox = QComboBox()
        self.eventLabel.setBuddy(self.eventComboBox)
        self.roomLabel = QLabel("Room")
        self.roomLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.roomComboBox = QComboBox()
        self.roomLabel.setBuddy(self.roomComboBox)
        self.dateLabel = QLabel("Date")
        self.dateLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.dateComboBox = QComboBox()
        self.dateLabel.setBuddy(self.dateComboBox)
        self.filterBarLayoutRow_1.addWidget(self.eventLabel)
        self.filterBarLayoutRow_1.addWidget(self.eventComboBox)
        self.filterBarLayoutRow_1.addWidget(self.roomLabel)
        self.filterBarLayoutRow_1.addWidget(self.roomComboBox)
        self.filterBarLayoutRow_1.addWidget(self.dateLabel)
        self.filterBarLayoutRow_1.addWidget(self.dateComboBox)

        self.filterBarLayoutRow_2 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_2)
        self.talkLabel = QLabel("Talk ")
        self.talkLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.talkComboBox = QComboBox()
        self.talkComboBox.setFont(boldFont)
        self.talkComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        self.talkComboBox.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.filterBarLayoutRow_2.addWidget(self.talkLabel)
        self.filterBarLayoutRow_2.addWidget(self.talkComboBox)

        # Preview Layout
        self.previewLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.previewLayout)

        self.previewWidget = QWidget()
        self.audioSlider = QSlider()
        self.audioSlider.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.audioSlider.setEnabled(False)
        self.previewLayout.addWidget(self.previewWidget)
        self.previewLayout.addWidget(self.audioSlider)

        self.statusLabel = QLabel()
        self.mainLayout.addWidget(self.statusLabel)

        # Audio Feedback Checkbox
        self.audioFeedbackCheckbox = QCheckBox()
        self.audioFeedbackCheckbox.setLayoutDirection(Qt.RightToLeft)
        self.audioFeedbackCheckbox.setIcon(self.headphoneIcon)
        self.audioFeedbackCheckbox.setToolTip("Enable Audio Feedback")
        self.mainLayout.addWidget(self.audioFeedbackCheckbox)

    def setRecordIcon(self, state):
        if state:
            self.recordPushButton.setIcon(self.stopIcon)
        else:
            self.recordPushButton.setIcon(self.recordIcon)

    def setPauseIcon(self, state):
        if state:
            self.pauseToolButton.setIcon(self.resumeIcon)
        else:
            self.pauseToolButton.setIcon(self.pauseIcon)
Exemplo n.º 4
0
Arquivo: mplayer.py Projeto: Ptaah/Ekd
class Mplayer(QDialog):

	REVENIR, PAS_PRECEDENT_SUIVANT, PRECEDENT_SUIVANT, CURSEUR_SUR_UNE_LIGNE,\
		CURSEUR_A_PART, PARCOURIR, PAS_PARCOURIR, LIST, RATIO = range(9)

	HAUTEUR, LARGEUR = range(2)

	def __init__(self, cheminVideo=[], taille=(250,225),
			choixWidget=(RATIO, REVENIR, PAS_PRECEDENT_SUIVANT,CURSEUR_SUR_UNE_LIGNE,PAS_PARCOURIR,LIST),
			debutFin=(0,0), cheminMPlayer=None, barreTaches=None, facteurLimitant=HAUTEUR,
			cheminParcourir=None, parent=None):

		"""widget mplayer"""
		QDialog.__init__(self, parent)

		#=== Paramètres généraux ===#
		self.setAttribute(Qt.WA_DeleteOnClose)
		self.setWindowTitle(_(u"Player vidéo"))
                #On réduit la marge pour gagner de l'espace
                self.setContentsMargins(0,0,0,0)

		self.systeme = os.name
                ### Quand EKD windows est installé, le chemin des dépendances sont ###########
                ### positionnées dans les variables d'environnement donc pas besoin de #######
                ### collecter le chemin des ces dépendances ##################################
                self.cheminMPlayer = "mplayer"

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

		# liste de chemins vidéos
		if type(cheminVideo) != list :
			self.listeVideos=[cheminVideo]
		else :
			self.listeVideos = cheminVideo

		# est-ce que la vidéo est lue?
		self.estLue=False

		# est-ce que la vidéo est en pause?
		self.estEnPause=False

		self.debutFin = debutFin

		# Nom du fichier courant (le self n'est pas encore utile)
		txtParDefaut = u"Pas de fichier lu"
		if self.listeVideos.__len__()!=0:
			self.fichierCourant =  [txtParDefaut, self.listeVideos[0]]
		else: self.fichierCourant = [txtParDefaut, ""]

		# Barre des tâches de la fenêtre
		self.barreTaches = barreTaches

		# Taille de la vidéo
		self.tailleLargeur=taille[0]
		self.tailleHauteur=taille[1]

		# paramètres des boutons-icones
		iconTaille=22
		flat=1

		# Pour récupérer le temps courant depuis certains cadre
		self.temps = 0

		self.dureeTimer = 10 # temps en ms
		###############################################################################################################################

		#Pour être plus précis lors de la lecture, on prend comme unité la miliseconde. ######################
		## Il faut donc utiliser une echelle 1000 fois plus grande pour les unités du slider
		self.echelle=1000
		###############################################################################################################################

		# Permet de récupérer la durée de la vidéo depuis une instance de la classe
		# Sert dans certains cadres
		self.dureeVideo = 0

		# Chemin sur lequel peut s'ouvrir la boite de dialogue de fichier
		# associée au bouton parcourir
		self.cheminPourBoutonParcourir = cheminParcourir

		self.taille = taille

		debug("self.taille avant lecture : %s %s" % (self.taille, type(self.taille)))

		#=== Widgets ===#

		self.icone_lire=QIcon("Icones" + os.sep + "player_play.png")
		self.icone_pause=QIcon("Icones" + os.sep + "player_pause.png")
		self.icone_arret=QIcon("Icones" + os.sep + "player_stop.png")

		if Mplayer.REVENIR in choixWidget:
			self.bout_revenir = QPushButton(u"Revenir")
			self.bout_revenir.setIcon(QIcon("Icones" + os.sep + "revenir.png"))

		if Mplayer.PARCOURIR in choixWidget:
			self.bout_ouvVideo = QPushButton(u"Parcourir...")

		if Mplayer.PRECEDENT_SUIVANT in choixWidget:
			self.bout_prec = QPushButton(QIcon("Icones" + os.sep + "player_rew.png"),"")
			self.bout_prec.setIconSize(QSize(iconTaille, iconTaille))
			self.bout_prec.setFlat(flat)
			self.bout_suivant = QPushButton(QIcon("Icones" + os.sep + "player_fwd.png"),"")
			self.bout_suivant.setIconSize(QSize(iconTaille, iconTaille))
			self.bout_suivant.setFlat(flat)

		self.LISTW=False
		if Mplayer.LIST in choixWidget :
			self.LISTW = True
			self.listFichiers = QComboBox()
			self.listFichiers.hide()
			self.setListeVideo()


		self.bout_LectPause = QPushButton(self.icone_lire,"")
		self.bout_LectPause.setIconSize(QSize(iconTaille, iconTaille))
		self.bout_LectPause.setFlat(flat)

		self.bout_Arret = QPushButton(self.icone_arret,"")
		self.bout_Arret.setIconSize(QSize(iconTaille, iconTaille))
		self.bout_Arret.setFlat(flat)

		# widget qui contiendra la vidéo
		self.cibleVideo = DisplayVid(self)
		# par défaut le widget-cible est noir
		color = QColor(0, 0, 0)
		self.cibleVideo.setAutoFillBackground(True)
		self.cibleVideo.setPalette(QPalette(color))
		self.cibleVideo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
		self.cibleVideo.setFixedHeight(self.taille[1])
		self.cibleVideo.setToolTip(self.fichierCourant[0])

		#Choix de l'aspect ratio de la vidéo
                if Mplayer.RATIO in choixWidget :
                    self.conf = QGroupBox()
                    self.conf.setContentsMargins(0,0,0,0)
                    self.conf.setMinimumSize(QSize(self.tailleLargeur, 0))
                    self.conf.setObjectName("conf")
                    self.verticalLayout = QHBoxLayout(self.conf)
                    self.verticalLayout.setObjectName("verticalLayout")
                    self.choicenorm = QRadioButton(self.conf)
                    self.choicenorm.setObjectName("choicenorm")
                    self.verticalLayout.addWidget(self.choicenorm)
                    self.choicewide = QRadioButton(self.conf)
                    self.choicewide.setObjectName("choicewide")
                    self.verticalLayout.addWidget(self.choicewide)
                    self.choiceone = QRadioButton(self.conf)
                    self.choiceone.setObjectName("choiceone")
                    self.verticalLayout.addWidget(self.choiceone)
                    self.choicenorm.setText("4:3")
                    self.choicewide.setText("16:9")
                    self.choiceone.setText("w:h")
                # Checked le ratio de la vidéo
                if self.listeVideos.__len__()!=0:
                        self.changeRatio(self.listeVideos[0])
                else :
                        self.setRatio(4.0/3.0)
                        if Mplayer.RATIO in choixWidget :
                            self.choicenorm.setChecked(True)

		self.slider = QSlider(Qt.Horizontal)
		self.slider.setEnabled(True)

		self.mplayerProcess = QProcess(self)

		self.timer = QTimer(self)

		self.tempsChrono = TracerChrono()

		#=== mise-en-page/plan ===#
		mhbox = QHBoxLayout()
		vbox = QVBoxLayout()
		vbox.addWidget(self.cibleVideo)
                if Mplayer.RATIO in choixWidget :
                    vbox.addWidget(self.conf)
		hbox = QHBoxLayout()
		if Mplayer.REVENIR in choixWidget:
			hbox.addWidget(self.bout_revenir)
		if Mplayer.PARCOURIR in choixWidget:
			hbox.addWidget(self.bout_ouvVideo)
		hbox.addWidget(self.bout_LectPause)
		hbox.addWidget(self.bout_Arret)
		if Mplayer.PRECEDENT_SUIVANT in choixWidget:
			hbox.addWidget(self.bout_prec)
			hbox.addWidget(self.bout_suivant)
		hbox.addWidget(self.tempsChrono)
		if Mplayer.CURSEUR_A_PART not in choixWidget:
			hbox.addWidget(self.slider)
		vbox.addLayout(hbox)
		if Mplayer.CURSEUR_A_PART in choixWidget:
			hbox.setAlignment(Qt.AlignLeft)
			hbox = QHBoxLayout()
			hbox.addWidget(self.slider)
			vbox.addLayout(hbox)
		# Liste fichier dans combobox
		if self.LISTW :
			hbox = QHBoxLayout()
			hbox.addWidget(self.listFichiers)
			vbox.addLayout(hbox)

		mhbox.addLayout(vbox)
		self.setLayout(mhbox)

		#=== connexion des widgets à des fonctions ===#

		if Mplayer.REVENIR in choixWidget:
			self.connect(self.bout_revenir, SIGNAL('clicked()'), SLOT('close()'))
		if Mplayer.PARCOURIR in choixWidget:
			self.connect(self.bout_ouvVideo, SIGNAL('clicked()'), self.ouvrirVideo)
		if Mplayer.PRECEDENT_SUIVANT in choixWidget:
			self.connect(self.bout_prec, SIGNAL('clicked()'), self.precedent)
			self.connect(self.bout_suivant, SIGNAL('clicked()'), self.suivant)
		#Ajouté le 08/11/2009 - Liste des fichiers dans une combobox
		if self.LISTW :
			self.connect(self.listFichiers, SIGNAL('currentIndexChanged(int)'), self.changeVideo)
		self.connect(self.bout_LectPause, SIGNAL('clicked()'), self.lectPause)
		self.connect(self.bout_Arret, SIGNAL('clicked()'), self.arretMPlayer)
		self.connect(self.mplayerProcess, SIGNAL('readyReadStandardOutput()'), self.recupSortie)
		self.connect(self.mplayerProcess, SIGNAL('finished(int,QProcess::ExitStatus)'), self.finVideo)
		self.connect(self.timer, SIGNAL('timeout()'), self.sonderTempsActuel)
		self.connect(self.slider, SIGNAL('sliderMoved(int)'), self.changerTempsCurseur)
		self.connect(self.cibleVideo, SIGNAL('changeSize'), self.sizeMplayer)
                if Mplayer.RATIO in choixWidget :
                    self.connect(self.choicenorm, SIGNAL("clicked(bool)"), self.defRatio)
                    self.connect(self.choicewide, SIGNAL("clicked(bool)"), self.defRatio)
                    self.connect(self.choiceone, SIGNAL("clicked(bool)"), self.defRatio)

	def setListeVideo(self) :
		self.referenceVideo = []
		self.listFichiers.clear()
		for vid in self.listeVideos :
			self.referenceVideo.append(vid)
			self.listFichiers.addItem(os.path.basename(vid))
		if self.listeVideos.__len__() > 1 :
			self.listFichiers.show()

	def setAudio(self,au) :
		if au :
			self.cibleVideo.hide()
                        if "conf" in self.__dict__ :
			    self.conf.hide()
		else :
			self.cibleVideo.show()
                        if "conf" in self.__dict__ :
                            self.conf.show()
	def changeVideo(self, index) :
		self.arretMPlayer()
		if index >= 0 : # Condition ajoutée pour éviter une erreure de dépassement de range dans la liste.
			self.listeVideos = self.referenceVideo[index]
			self.listFichiers.setCurrentIndex(index)

	def defRatio(self, state=0) :
		if state :
			if self.choicenorm.isChecked() :
				self.setRatio(4.0/3.0)
			if self.choicewide.isChecked() :
				self.setRatio(16.0/9.0)
			if self.choiceone.isChecked() :
				try :
					dim=getVideoSize(unicode(self.listeVideos[0]))
					self.setRatio(dim[0]/dim[1])
				except :
					None
			self.defRatio()
		else :
			self.adjustSize()

	def setRatio(self,ratio) :
		self.ratio = ratio
		self.sizeMplayer()

	def changeRatio(self,video) :
		rv = getVideoRatio(video)
		if rv[0]==0.0 and type(rv[1])==float :
			rat = rv[1]
		else :
			rat = rv[0]

		if rat > 1.7 :
                        if "choicewide" in self.__dict__ :
                            self.choicewide.setChecked(True)
			self.setRatio(16.0/9.0)
		elif rat > 1.3 and rat <= 1.7 :
                        if "choicenorm" in self.__dict__ :
                            self.choicenorm.setChecked(True)
			self.setRatio(4.0/3.0)
		elif rat < 1.3 and rat != 0.0 :
                        if "choiceone" in self.__dict__ :
                            self.choiceone.setChecked(True)
			dim=getVideoSize(video)
			self.setRatio(dim[0]/dim[1])
		else :
                        if "choicenorm" in self.__dict__ :
                            self.choicenorm.setChecked(True)
			self.setRatio(4.0/3.0)

	def sizeMplayer(self) :
		self.cibleVideo.setFixedHeight(int(self.cibleVideo.width()/self.ratio))

	def ouvrirVideo(self):
		"""Ouverture de la boîte de dialogue de fichiers"""
		txt = u"Fichiers vidéo"
		if self.cheminPourBoutonParcourir:
			chemin = self.cheminPourBoutonParcourir

		else:
			try:
				chemin = EkdConfig.get('general','video_input_path').decode("UTF8")
			except:
				chemin = os.path.expanduser('~')

		liste=QFileDialog.getOpenFileNames(None, u"Ouvrir", chemin, "%s (*.avi *.mpg *.mpeg *.mjpeg *.flv *.mp4 *.ogg *.vob *.mov *.wmv *.3gp *.h264)\n*" %txt)
		if not liste: return
		self.listeVideos = liste
		self.changeRatio(unicode(self.listeVideos[0]))

		chemin = unicode(self.listeVideos[0])
		EkdConfig.set('general','video_input_path',os.path.dirname(chemin).encode("UTF8"))

	def setVideos(self, videos) :
		'''Définie proprement la liste des vidéos à jouer'''
		if type(videos) != list :
			self.listeVideos = [videos]
		else :
			self.listeVideos = videos
		if self.LISTW and videos.__len__() > 1 :
			self.setListeVideo()
		elif self.LISTW :
			self.listFichiers.hide()

	def demarrerMPlayer(self):
		"""démarrage de mplayer avec les arguments choisis"""
		if self.estLue:
			return True

		args = QStringList()	# Liste Qt qui contiendra les options de mplayer
					# Ajout d'options à liste: args << "-option"

		# mplayer fonctionnera comme un terminal dans ce script
		args << "-slave"
		# on ne veut pas avoir des commentaires sans grand intérêt
		args << "-quiet"

		# Sous linux, aucun driver n'a été nécessaire et pas de manip pour Wid :)
		if self.systeme=='posix':
			# try - except?
			# la fenêtre de mplayer restera attaché à la fenêtre
			# wid prend en valeur le nombre identifiant le widget (celui qui contiendra la vidéo)
			args << "-wid" << QString.number(self.cibleVideo.winId()) # Objet QString car args est une liste de ch de caractères
			settings = QSettings()
			videoOutput = settings.value("vo", QVariant('')).toString()
			if videoOutput:
				args << '-vo' << videoOutput

		# Sous windows
		else:
			# reinterpret_cast<qlonglong> obligatoire, winId() ne se laissant pas convertir gentiment ;)
			args << "-wid" << self.cibleVideo.winId().__hex__()
			args << "-vo" << "directx:noaccel"
			#args << "-vo" << "gl" # alternative

		# chemin de la vidéo
		args << self.listeVideos

		if PYQT_VERSION_STR >= "4.1.0":
			# mode de canal: on fusionne le canal de sortie normal (stdout) et celui des erreurs (stderr)
			self.mplayerProcess.setProcessChannelMode(QProcess.MergedChannels)
		# démarrage de mplayer (en tenant compte des arguments définis ci-dessus)
		# comme un nouveau processus
		self.mplayerProcess.start(self.cheminMPlayer, args)
		# au cas où mplayer ne démarrerait pas au bout de 3 sec (ex. problème de codec)
		if not self.mplayerProcess.waitForStarted(3000):
			QMessageBox.critical(self, u"Avertissement", u"Bogue au lancement de la vidéo avec mplayer")
			return False

		# donne le temps toutes les x secondes
		self.timer.start(self.dureeTimer)

		self.estLue = True

		return True

	def recupSortie(self):
		"""récupère les lignes d'information émises par QProcess (mplayerProcess) et en tire les conséquences"""
		while self.mplayerProcess.canReadLine(): # renvoie True si une ligne complète peut être lue à partir du système
			# stocker l'ensemble des bits d'une ligne
			tampon=QByteArray(self.mplayerProcess.readLine()) # readline: lit une ligne ascii à partir du système

			# On vérifie si on a eu des réponses
			if tampon.startsWith("Playing"):
				# On récupère les infos de base ('$ mplayer -input cmdlist' pour avoir la liste complète - file:///usr/share/doc/mplayer-doc/tech/slave.txt.gz pour plus de détails)
				self.mplayerProcess.write("get_video_resolution\n") # récupère la résolution de la vidéo
				self.mplayerProcess.write("get_time_length\n")
				# Nouveau fichier chargé -> on récupère son nom
				ind = tampon.length() - 2 # suppression du '.' à la fin
				tampon.remove(ind,ind)
				tampon.remove(0, 8) # vire Playing
				tampon.replace(QByteArray("\n"), QByteArray(""))
				tampon.replace(QByteArray("\r"), QByteArray(""))
				try:
					# Tour de passe-passe pour ne pas avoir de problème d'accents

					# Condition pour détection windows
					if os.name == 'nt':
						self.fichierCourant[1]=unicode(QString(tampon))
					# Condition pour détection Linux ou MacOSX
					elif os.name in ['posix', 'mac']:
						self.fichierCourant[1]=unicode(QString(tampon)).encode("Latin1").decode("UTF8")
				except UnicodeEncodeError, e:
					debug(e)
					self.fichierCourant[1]="?"
				self.cibleVideo.setToolTip(self.fichierCourant[1])
				if self.barreTaches is not None:
					self.barreTaches.showMessage(self.fichierCourant[1])

			# réponse à get_video_resolution : ANS_VIDEO_RESOLUTION='<width> x <height>'
			if tampon.startsWith("ANS_VIDEO_RESOLUTION"): # retourne True si l'ensemble de bits démarre avec "..."
				debug("tampon : %s" % tampon) # ex. -> ANS_VIDEO_RESOLUTION='352 x 288'
				tampon.remove(0, 21) # suppression des 21 1er caract -> '352 x 288'
				tampon.replace(QByteArray("'"), QByteArray("")) # -> 352 x 288
				tampon.replace(QByteArray(" "), QByteArray("")) # -> 352x288
				tampon.replace(QByteArray("\n"), QByteArray("")) # -> 352x288 # retour chariot unix
				tampon.replace(QByteArray("\r"), QByteArray("")) # -> 352x288 # retour chariot windows
				#print "-----tampon.indexOf('x') :", tampon.indexOf('x'), type(tampon.indexOf('x'))
				sepIndex = tampon.indexOf('x') # récupère la position de 'x' # 3 <type 'int'>
				#print "-----tampon.left(sepIndex).toInt():", tampon.left(sepIndex).toInt(), type(tampon.left(sepIndex).toInt())
				resX = tampon.left(sepIndex).toInt()[0] # -> 352 # (352, True) <type 'tuple'>
				#print "-----tampon.mid(sepIndex+1).toInt() :", tampon.mid(sepIndex+1).toInt(), type(tampon.mid(sepIndex+1).toInt())
				resY = tampon.mid(sepIndex+1).toInt()[0] # -> 288 # (288, True) <type 'tuple'>

				# on définit les nouvelles dimensions de l'image du widget-mplayer.
				# try pour éviter les bogues sur les fichiers audio (sans dimension d'image)!!!
				#try:
				if resX!=0 or resY!=0:
					debug( "ratio : %s - %s" % (self.ratio, type(self.ratio)))
				else:
					debug("fichier audio")

			# réponse à get_time_length : ANS_LENGTH=xx.yy
			elif tampon.startsWith("ANS_LENGTH"):
				debug("tampon : %s" % tampon) # -> ANS_LENGTH=279.38
				tampon.remove(0, 11) # vire ANS_LENGTH=
				tampon.replace(QByteArray("'"), QByteArray(""))
				tampon.replace(QByteArray(" "), QByteArray(""))
				tampon.replace(QByteArray("\n"), QByteArray(""))
				tampon.replace(QByteArray("\r"), QByteArray("")) # -> 279.38
				#print "-----tampon.toFloat() :", tampon.toFloat(), type(tampon.toFloat())
				tempsMax = tampon.toFloat()[0] # (279.3800048828125, True) <type 'tuple'>
				self.dureeVideo = tempsMax
				## Modifié le 28/05/2009 : On augmente la précision du slider
				#self.slider.setMaximum(tempsMax) # déf du domaine de valeur du curseur
				self.slider.setMaximum(tempsMax*self.echelle)

				# ATTENTION J'AI COMMENTE CETTE LIGNE !!!
				#self.slider.setMaximum(tempsMax)

			# réponse à get_time_pos : ANS_TIME_POSITION=xx.y
			elif tampon.startsWith("ANS_TIME_POSITION"):
				#print "tampon :",tampon # -> ANS_TIME_POSITION=1.4 (temps courant)
				tampon.remove(0, 18) # vire ANS_TIME_POSITION=
				tampon.replace(QByteArray("'"), QByteArray(""))
				tampon.replace(QByteArray(" "), QByteArray(""))
				tampon.replace(QByteArray("\n"), QByteArray(""))
				tampon.replace(QByteArray("\r"), QByteArray(""))
				#print "-----tampon.toFloat() :", tampon.toFloat(), type(tampon.toFloat())
				tempsCourant = tampon.toFloat()[0] # (1.3999999761581421, True) <type 'tuple'>
				# récupération du temps courant: utile dans certains cadres
				self.temps = tempsCourant
				# Programmer un arrêt. Utile pour les aperçus
				temps = float("%.1f" %self.temps)
				if self.debutFin!=(0,0) and self.debutFin[1]==temps:
					self.arretMPlayer()
					return
				self.slider.setValue(tempsCourant*self.echelle)
				#############################################################################
				self.changerTempsChrono(tempsCourant) # modifier le chrono du bouton
Exemplo n.º 5
0
class FitParam(object):
    def __init__(self,
                 name,
                 value,
                 mini,
                 maxi,
                 logscale=False,
                 steps=5000,
                 format='%.3f',
                 size_offset=0,
                 unit=''):
        self.name = name
        self.value = value
        self.min = mini if logscale == False else max(1e-120, mini)
        self.max = maxi
        self.logscale = logscale
        self.steps = steps
        self.format = format
        self.unit = unit
        self.prefix_label = None
        self.lineedit = None
        self.unit_label = None
        self.slider = None
        self.button = None
        self._widgets = []
        self._size_offset = size_offset
        self._refresh_callback = None
        self.dataset = FitParamDataSet(title=_("Curve fitting parameter"))

    def copy(self):
        """Return a copy of this fitparam"""
        return self.__class__(self.name, self.value, self.min, self.max,
                              self.logscale, self.steps, self.format,
                              self._size_offset, self.unit)

    def create_widgets(self, parent, refresh_callback):
        self._refresh_callback = refresh_callback
        self.prefix_label = QLabel()
        font = self.prefix_label.font()
        font.setPointSize(font.pointSize() + self._size_offset)
        self.prefix_label.setFont(font)
        self.button = QPushButton()
        self.button.setIcon(get_icon('settings.png'))
        self.button.setToolTip(
            _("Edit '%s' fit parameter properties") % self.name)
        QObject.connect(self.button, SIGNAL('clicked()'),
                        lambda: self.edit_param(parent))
        self.lineedit = QLineEdit()
        QObject.connect(self.lineedit, SIGNAL('editingFinished()'),
                        self.line_editing_finished)
        self.unit_label = QLabel(self.unit)
        self.slider = QSlider()
        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setRange(0, self.steps - 1)
        QObject.connect(self.slider, SIGNAL("valueChanged(int)"),
                        self.slider_value_changed)
        self.update(refresh=False)
        self.add_widgets([
            self.prefix_label, self.lineedit, self.unit_label, self.slider,
            self.button
        ])

    def add_widgets(self, widgets):
        self._widgets += widgets

    def get_widgets(self):
        return self._widgets

    def set_scale(self, state):
        self.logscale = state > 0
        self.update_slider_value()

    def set_text(self, fmt=None):
        style = "<span style=\'color: #444444\'><b>%s</b></span>"
        self.prefix_label.setText(style % self.name)
        if self.value is None:
            value_str = ''
        else:
            if fmt is None:
                fmt = self.format
            value_str = fmt % self.value
        self.lineedit.setText(value_str)
        self.lineedit.setDisabled(self.value == self.min
                                  and self.max == self.min)

    def line_editing_finished(self):
        try:
            self.value = float(self.lineedit.text())
        except ValueError:
            self.set_text()
        self.update_slider_value()
        self._refresh_callback()

    def slider_value_changed(self, int_value):
        if self.logscale:
            #~ total_delta = np.log10(1+self.max-self.min)
            #~ self.value = self.min+10**(total_delta*int_value/(self.steps-1))-1
            #~ total_delta = np.log10(self.max)-np.log10(self.min)
            ratio = int_value / (self.steps - 1)
            self.value = self.max**ratio * self.min**(1 - ratio)
        else:
            total_delta = self.max - self.min
            self.value = self.min + total_delta * int_value / (self.steps - 1)
        self.set_text()
        self._refresh_callback()

    def update_slider_value(self):
        from numpy import isnan, isinf
        if (self.value is None or self.min is None or self.max is None):
            self.slider.setEnabled(False)
            if self.slider.parent() and self.slider.parent().isVisible():
                self.slider.show()
        elif self.value == self.min and self.max == self.min:
            self.slider.hide()
        else:
            self.slider.setEnabled(True)
            if self.slider.parent() and self.slider.parent().isVisible():
                self.slider.show()
            if self.logscale:
                value_delta = max([np.log10(self.value / self.min), 0.])
                total_delta = np.log10(self.max / self.min)
                if not isnan(self.steps * value_delta / total_delta):
                    intval = int(self.steps * value_delta / total_delta)
                else:
                    intval = int(self.min)
            else:
                value_delta = self.value - self.min
                total_delta = self.max - self.min
                intval = int(self.steps * value_delta / total_delta)
            self.slider.blockSignals(True)
            print intval
            print
            sys.stdout.flush()
            self.slider.setValue(intval)
            self.slider.blockSignals(False)

    def edit_param(self, parent):
        update_dataset(self.dataset, self)
        if self.dataset.edit(parent=parent):
            restore_dataset(self.dataset, self)
            if self.value > self.max:
                self.max = self.value
            if self.value < self.min:
                self.min = self.value
            self.update(True)

    def update(self, refresh=True):
        self.unit_label.setText(self.unit)
        self.slider.setRange(0, self.steps - 1)
        self.update_slider_value()
        self.set_text()
        if refresh:
            self._refresh_callback()
Exemplo n.º 6
0
class Player(QWidget):
    def __init__(self,app):
        super(Player,self).__init__()
        self.mpd   = app.mpd
        self.ih    = app.imagehelper
        self.timer = None
        self.initGUI()
        self.initState()
        
    def initGUI(self):
        self.setWindowTitle(QApplication.applicationName())
        self.fmt = QFontMetrics(QFont())
        layout = QVBoxLayout()
        
        toplayout = QHBoxLayout()
        currentLayout = QGridLayout()
        currentLayout.setContentsMargins(0,20,0,20)
        currentLayout.setHorizontalSpacing(100)
        currentLayout.setVerticalSpacing(20)
        # current song information
        currentLayout.addWidget(QLabel("<b>Artist</b>"),1,0)
        self.artist = QLabel()
        currentLayout.addWidget(self.artist,1,1)
        currentLayout.addWidget(QLabel("<b>Title</b>"),2,0)
        self.title  = QLabel()
        currentLayout.addWidget(self.title,2,1)
        currentLayout.addWidget(QLabel("<b>Albumartist</b>"),3,0)
        self.albumartist = QLabel()
        currentLayout.addWidget(self.albumartist,3,1)
        currentLayout.addWidget(QLabel("<b>Album</b>"),4,0)
        self.album  = QLabel()
        currentLayout.addWidget(self.album,4,1)
        # playlist and song position
        self.playlistposition = QLabel()
        currentLayout.addWidget(self.playlistposition,5,0)
        poslayout = QHBoxLayout()
        poslayout.setSpacing(10)
        self.time = QLabel("00:00")
        poslayout.addWidget(self.time)
        self.position = QSlider(Qt.Horizontal)
        self.position.setTracking(False)
        self.position.setSingleStep(10)
        self.position.sliderReleased.connect( self.seek)
        self.position.sliderMoved.connect(
            lambda x: self.time.setText(self.mpd.timeString(x)))
        poslayout.addWidget(self.position)
        self.length = QLabel("00:00")
        poslayout.addWidget(self.length)
        currentLayout.addLayout(poslayout,5,1)
        toplayout.addLayout(currentLayout)
        layout.addLayout(toplayout)
        layout.addStretch(1)
        
        self.settingsWidget = QMenu()
        self.consumeBtn = self.settingsWidget.addAction("Consume")
        self.consumeBtn.setCheckable(True)
        self.consumeBtn.triggered.connect( lambda x: self.mpd.consume(int(x)))
        self.singleBtn  = self.settingsWidget.addAction("Single")
        self.singleBtn.setCheckable(True)
        self.singleBtn.triggered.connect( lambda x: self.mpd.single(int(x)))
        
        toolLayout = QHBoxLayout()
        self.settingsBtn = QToolButton()
        self.settingsBtn.setFixedSize(64,64)
        self.settingsBtn.setIcon( self.ih.settingsButton)
        self.settingsBtn.clicked.connect(self.showAdditionalControls)
        toolLayout.addWidget(self.settingsBtn)

        
        toolWidget = QStackedWidget()
        transpWidget = QWidget()
        transpLayout = QHBoxLayout()
        self.prevBtn = self.createButton(
            self.ih.prevButton, self.ih.prevButtonPressed)
        self.prevBtn.clicked.connect( lambda x: self.mpd.previous())
        transpLayout.addWidget(self.prevBtn)
        self.playBtn = self.createCheckButton(
            self.ih.playButton, self.ih.pauseButton)
        self.playBtn.clicked.connect( self.playPressed)
        transpLayout.addWidget(self.playBtn)
        self.stopBtn = self.createButton(
            self.ih.stopButton, self.ih.stopButtonPressed)
        self.stopBtn.clicked.connect( lambda x: self.mpd.stop())
        transpLayout.addWidget(self.stopBtn)
        self.nextBtn = self.createButton(
            self.ih.nextButton, self.ih.nextButtonPressed)
        self.nextBtn.clicked.connect( lambda x: self.mpd.next())
        transpLayout.addWidget(self.nextBtn)
        self.shuffleBtn = self.createCheckButton(
            self.ih.shuffleButton, self.ih.shuffleButtonPressed)
        self.shuffleBtn.toggled.connect(
            lambda x: self.mpd.random(1) if x else self.mpd.random(0))
        transpLayout.addWidget(self.shuffleBtn)
        self.repeatBtn = self.createCheckButton(
            self.ih.repeatButton, self.ih.repeatButtonPressed)
        self.repeatBtn.toggled.connect(
            lambda x: self.mpd.repeat(1) if x else self.mpd.repeat(0))
        transpLayout.addWidget(self.repeatBtn)
        transpLayout.addSpacing(64)
        transpWidget.setLayout(transpLayout)
        toolWidget.addWidget( transpWidget)
        
        self.volume = QSlider(Qt.Horizontal)
        self.volume.valueChanged.connect(self.mpd.setvol)
        toolWidget.addWidget(self.volume)
        
        toolLayout.addWidget(toolWidget)
        self.volumeBtn = QToolButton()
        self.volumeBtn.setFixedSize(64,64)
        self.volumeBtn.setCheckable(True)
        self.volumeBtn.setIcon( self.ih.volumeButton)
        self.volumeBtn.toggled.connect(
            lambda x: toolWidget.setCurrentIndex(x))
        toolLayout.addWidget(self.volumeBtn)
        layout.addLayout(toolLayout)
        self.setLayout(layout)

    def showAdditionalControls(self):
        pos = self.settingsBtn.pos()
        pos.setY( pos.y()-self.settingsWidget.sizeHint().height())
        self.settingsWidget.popup( self.mapToGlobal(pos))

    def createCheckButton(self, offIcon, onIcon):
        i = QIcon()
        i.addPixmap( offIcon.pixmap(64), QIcon.Normal, QIcon.Off)
        i.addPixmap(  onIcon.pixmap(64), QIcon.Normal, QIcon.On)
        b = QToolButton()
        b.setFixedSize(64,64)
        b.setCheckable(True)
        b.setIcon(i)
        b.setStyleSheet("* { background: transparent }")
        return b

    def createButton(self, normal, pressed):
        b = QToolButton()
        b.setFixedSize(64,64)
        b.setIcon(normal)
        b.setStyleSheet("* { background: transparent }")
        b.pressed.connect( lambda: b.setIcon(pressed))
        b.released.connect( lambda: b.setIcon(normal))
        return b
    
    def playPressed(self,state):
        if   self.state == 'stop': self.mpd.play()
        else: self.mpd.pause(int(not state))
        
    def initState(self):
        self.songid  = -1
        self.state = 'stop'
        self.artist.setText("Unknown Artist")
        self.title.setText("Unknown Title")
        self.albumartist.setText("Unknown Artist")
        self.album.setText("Unknown Album")
        self.position.setRange(0,0)
        self.position.setValue(0)
        self.position.setEnabled(False)
        self.length.setText("00:00")
        self.playlistposition.setText("0/0")
        self.setStopState()
        
    def setStopState(self):
        self.playBtn.setChecked(False)
        self.time.setText("00:00")
        self.position.setValue(0)
        self.volume.setEnabled(False)

    def updateStatus(self):
        status = self.mpd.status()
        self.repeatBtn.setChecked(int(status['repeat']))
        self.shuffleBtn.setChecked(int(status['random']))
        self.consumeBtn.setChecked(int(status['consume']))
        self.singleBtn.setChecked(int(status['single']))
        if not status.has_key('songid') and self.songid != -1:
            self.initState()
            return
        stateChanged = False
        state = status['state']
        if state != self.state:
            stateChanged = True
        self.state = state
        volume = int(status['volume'])
        if self.state == 'play' or self.state == 'pause':
            self.playBtn.setChecked(True if self.state == 'play' else False)
            songid = int(status['songid'])
            if songid != self.songid:
                self.songid = songid
                self.updateCurrentSong()
            playlistlength = int(status['playlistlength'])
            song = int(status.get('song',-1))
            self.playlistposition.setText("%d/%d" % (song+1,playlistlength))
            playlistlength = int(status['playlistlength'])
            elapsed = float(status['elapsed'])
            if not self.position.isSliderDown():
                timeString = self.mpd.timeString(round(elapsed))
                self.time.setFixedSize(
                    (len(timeString)+1)*self.fmt.averageCharWidth(),
                    self.fmt.height())
                self.time.setText(timeString)
                if self.position.maximum() > 0:
                    self.position.setSliderPosition(round(elapsed))
            if stateChanged:
                self.volume.setEnabled(True)
            if not self.volume.isSliderDown():
                self.volume.setValue(volume)
            #nextsong = int(status['nextsong'])
        else:
            if self.songid == -1: return
            self.setStopState()
            
    def updateCurrentSong(self):
        currentsong = self.mpd.unifySongInfo(self.mpd.currentsong())
        self.artist.setText(      currentsong['artist'])
        self.title.setText(       currentsong['title'])
        self.albumartist.setText( currentsong['albumartist'])
        self.album.setText(       currentsong['album'])
        self.length.setText(      currentsong['length'])
        self.position.setRange(0,currentsong['time'])
        self.position.setEnabled(True if self.position.maximum() > 0 else False)
        self.position.setValue(0)
        self.time.setText("00:00")
        self.volume.setEnabled(True)

    def seek(self):
        secs = self.position.sliderPosition()
        if self.songid == -1: return
        self.mpd.seekid(self.songid, secs)
       
    def hideEvent(self, ev):
        if self.timer:
            self.killTimer( self.timer)
            self.timer = None
        super(Player,self).hideEvent(ev)

    def showEvent(self,ev):
        if not self.timer:
            self.updateStatus()
            self.timer = self.startTimer(1000)
        super(Player,self).showEvent(ev)

    def timerEvent(self,ev):
        try:
            self.updateStatus()
        except ConnectionError, e:
            self.hide()
            QMaemo5InformationBox.information(
                self, "Connection Error: %s" % str(e),
                QMaemo5InformationBox.DefaultTimeout)
        except socket.error, e:
            QMaemo5InformationBox.information(
                self, "Connection Error: %s" % e[1],
                QMaemo5InformationBox.DefaultTimeout)
            self.hide()
Exemplo n.º 7
0
class RecordingWidget(QWidget):
    """Widget containing main recording UI for Freeseer"""
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        icon = QIcon()
        icon.addPixmap(QPixmap(":/freeseer/logo.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.resize(400, 400)

        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        boldFont = QFont()
        boldFont.setBold(True)

        # Control bar
        self.controlRow = QHBoxLayout()
        self.mainLayout.addLayout(self.controlRow)

        self.standbyIcon = QIcon.fromTheme("system-shutdown")
        recordFallbackIcon = QIcon(":/multimedia/record.png")
        self.recordIcon = QIcon.fromTheme("media-record", recordFallbackIcon)
        stopFallbackIcon = QIcon(":/multimedia/stop.png")
        self.stopIcon = QIcon.fromTheme("media-playback-stop",
                                        stopFallbackIcon)
        self.pauseIcon = QIcon.fromTheme("media-playback-pause")
        self.resumeIcon = QIcon.fromTheme("media-playback-start")
        self.headphoneIcon = QIcon()
        self.headphoneIcon.addPixmap(QPixmap(":/multimedia/headphones.png"),
                                     QIcon.Normal, QIcon.Off)

        self.standbyPushButton = QPushButton("Standby")
        self.standbyPushButton.setToolTip("Standby")
        self.standbyPushButton.setMinimumSize(QSize(0, 40))
        self.standbyPushButton.setSizePolicy(QSizePolicy.Minimum,
                                             QSizePolicy.Fixed)
        self.standbyPushButton.setIcon(self.standbyIcon)
        self.standbyPushButton.setCheckable(True)
        self.standbyPushButton.setObjectName("standbyButton")
        self.controlRow.addWidget(self.standbyPushButton)

        self.autoRecordPushButton = QPushButton("Auto Record")
        self.autoRecordPushButton.setToolTip("Automated Recording")
        self.autoRecordPushButton.setMinimumSize(QSize(40, 40))
        self.autoRecordPushButton.setMaximumSize(QSize(120, 40))
        self.autoRecordPushButton.setCheckable(True)
        self.autoRecordPushButton.setObjectName("autoRecordButton")
        self.controlRow.addWidget(self.autoRecordPushButton)

        self.recordPushButton = QPushButton("Record")
        self.recordPushButton.setToolTip("Record")
        self.recordPushButton.setMinimumSize(QSize(0, 40))
        self.recordPushButton.setSizePolicy(QSizePolicy.Minimum,
                                            QSizePolicy.Fixed)
        self.recordPushButton.setIcon(self.recordIcon)
        self.recordPushButton.setHidden(True)
        self.recordPushButton.setEnabled(False)
        self.recordPushButton.setCheckable(True)
        self.recordPushButton.setObjectName("recordButton")
        self.controlRow.addWidget(self.recordPushButton)
        self.connect(self.recordPushButton, SIGNAL("toggled(bool)"),
                     self.setRecordIcon)

        self.pauseToolButton = QToolButton()
        self.pauseToolButton.setText("Pause")
        self.pauseToolButton.setToolTip("Pause")
        self.pauseToolButton.setIcon(self.pauseIcon)
        self.pauseToolButton.setMinimumSize(QSize(40, 40))
        self.pauseToolButton.setSizePolicy(QSizePolicy.Maximum,
                                           QSizePolicy.Fixed)
        self.pauseToolButton.setHidden(True)
        self.pauseToolButton.setEnabled(False)
        self.pauseToolButton.setCheckable(True)
        self.controlRow.addWidget(self.pauseToolButton)
        self.connect(self.pauseToolButton, SIGNAL("toggled(bool)"),
                     self.setPauseIcon)

        playbackIcon = QIcon.fromTheme("video-x-generic")
        self.playPushButton = QPushButton()
        self.playPushButton.setText("Play Video")
        self.playPushButton.setToolTip("Play last recorded Video")
        self.playPushButton.setIcon(playbackIcon)
        self.playPushButton.setMinimumSize(QSize(40, 40))
        self.playPushButton.setMaximumSize(QSize(120, 40))
        self.playPushButton.setHidden(True)
        self.playPushButton.setEnabled(False)
        self.playPushButton.setCheckable(True)
        self.controlRow.addWidget(self.playPushButton)

        # Filter bar
        self.filterBarLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.filterBarLayout)

        self.filterBarLayoutRow_1 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_1)
        self.eventLabel = QLabel("Event")
        self.eventLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.eventComboBox = QComboBox()
        self.eventLabel.setBuddy(self.eventComboBox)
        self.roomLabel = QLabel("Room")
        self.roomLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.roomComboBox = QComboBox()
        self.roomLabel.setBuddy(self.roomComboBox)
        self.dateLabel = QLabel("Date")
        self.dateLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.dateComboBox = QComboBox()
        self.dateLabel.setBuddy(self.dateComboBox)
        self.filterBarLayoutRow_1.addWidget(self.eventLabel)
        self.filterBarLayoutRow_1.addWidget(self.eventComboBox)
        self.filterBarLayoutRow_1.addWidget(self.roomLabel)
        self.filterBarLayoutRow_1.addWidget(self.roomComboBox)
        self.filterBarLayoutRow_1.addWidget(self.dateLabel)
        self.filterBarLayoutRow_1.addWidget(self.dateComboBox)

        self.filterBarLayoutRow_2 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_2)
        self.talkLabel = QLabel("Talk ")
        self.talkLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.talkComboBox = QComboBox()
        self.talkComboBox.setFont(boldFont)
        self.talkComboBox.setSizePolicy(QSizePolicy.Minimum,
                                        QSizePolicy.Maximum)
        self.talkComboBox.setSizeAdjustPolicy(
            QComboBox.AdjustToMinimumContentsLength)
        self.filterBarLayoutRow_2.addWidget(self.talkLabel)
        self.filterBarLayoutRow_2.addWidget(self.talkComboBox)

        # Preview Layout
        self.previewLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.previewLayout)

        self.previewWidget = QWidget()
        self.audioSlider = QSlider()
        self.audioSlider.setSizePolicy(QSizePolicy.Fixed,
                                       QSizePolicy.Expanding)
        self.audioSlider.setEnabled(False)
        self.previewLayout.addWidget(self.previewWidget)
        self.previewLayout.addWidget(self.audioSlider)

        self.statusLabel = QLabel()
        self.mainLayout.addWidget(self.statusLabel)

        # Audio Feedback Checkbox
        self.audioFeedbackCheckbox = QCheckBox()
        self.audioFeedbackCheckbox.setLayoutDirection(Qt.RightToLeft)
        self.audioFeedbackCheckbox.setIcon(self.headphoneIcon)
        self.audioFeedbackCheckbox.setToolTip("Enable Audio Feedback")
        self.mainLayout.addWidget(self.audioFeedbackCheckbox)

    def setRecordIcon(self, state):
        if state:
            self.recordPushButton.setIcon(self.stopIcon)
        else:
            self.recordPushButton.setIcon(self.recordIcon)

    def setPauseIcon(self, state):
        if state:
            self.pauseToolButton.setIcon(self.resumeIcon)
        else:
            self.pauseToolButton.setIcon(self.pauseIcon)
Exemplo n.º 8
0
class GraphGui(QWidget):
    def __init__(self, G=None, pos=None, parent=None):
        QWidget.__init__(self, parent)
        self.scene = GraphGraphicsScene(G, pos, self)
        self.view = QGraphicsView(self.scene, self)
        self.button = QPushButton("Quit", self)
        self.nodeButton = QPushButton("Node", self)
        self.edgeButton = QPushButton("Edge", self)
        self.addButton = QPushButton("Add", self)
        self.deleteButton = QPushButton("Delete", self)
        self.printButton = QPushButton("Print", self)
        self.eulerButton = QPushButton("Euler", self)
        self.generateFullButton = QPushButton("Full", self)
        self.generateHalfButton = QPushButton("Half", self)
        self.infoButton = QPushButton("Info", self)
        # self.testButton = QPushButton('Test', self)
        self.nodesInputLabel = QLabel("Nodes", self)
        self.edgesInputLabel = QLabel("Edges", self)
        self.saveButton = QPushButton("Save", self)
        self.loadButton = QPushButton("Load", self)
        self.saveAsButton = QPushButton("SaveAs", self)
        self.bridgeButton = QPushButton("Bridge", self)
        self.stepSlider = QSlider(self)
        self.cursorLabelX = QLabel("X:", self)
        self.cursorLabelY = QLabel("Y:", self)
        self.nodeNumberLabel = QLabel("Nr:", self)
        self.fileLabel = QLabel("File:", self)
        self.nodeInfo = QLabel("N:", self)
        self.edgeInfo = QLabel("E:", self)
        self.eulerInfo = QLabel("None", self)
        # self.fileInput = QLineEdit(self)
        self.fileInput = QLabel("", self)
        self.euler = Euler()
        self.eulerStep = 0
        self.eulerPath = []

        validator = QIntValidator(0, 10000)

        self.nodesNumberInput = QLineEdit(self)
        self.nodesNumberInput.setValidator(validator)
        self.edgesNumberInput = QLineEdit(self)
        self.edgesNumberInput.setValidator(validator)

        self.cursorLabelX.setMinimumSize(150, 25)
        self.cursorLabelY.setMinimumSize(150, 25)
        self.nodeNumberLabel.setMinimumSize(150, 25)

        self.labelsGroup = QVBoxLayout()
        self.labelsGroup.addWidget(self.cursorLabelX)
        self.labelsGroup.addWidget(self.cursorLabelY)
        self.labelsGroup.addWidget(self.nodeNumberLabel)

        HEIGHT = 50
        WIDTH = 50

        self.nodeButton.setFixedSize(HEIGHT, WIDTH)
        self.edgeButton.setFixedSize(HEIGHT, WIDTH)
        self.addButton.setFixedSize(HEIGHT, WIDTH)
        self.button.setFixedSize(HEIGHT, WIDTH)
        self.deleteButton.setFixedSize(HEIGHT, WIDTH)
        self.printButton.setFixedSize(HEIGHT, WIDTH)
        self.eulerButton.setFixedSize(HEIGHT, WIDTH)
        self.generateFullButton.setFixedSize(HEIGHT, WIDTH)
        self.generateHalfButton.setFixedSize(HEIGHT, WIDTH)
        self.saveButton.setFixedSize(HEIGHT, WIDTH)
        self.loadButton.setFixedSize(HEIGHT, WIDTH)
        self.saveAsButton.setFixedSize(HEIGHT, WIDTH)
        self.infoButton.setFixedSize(HEIGHT, WIDTH)
        self.bridgeButton.setFixedSize(HEIGHT, WIDTH)
        self.nodesNumberInput.setFixedSize(HEIGHT * 2, 28)
        self.edgesNumberInput.setFixedSize(HEIGHT * 2, 28)
        self.stepSlider.setFixedSize(HEIGHT * 2, 28)
        # self.testButton.setFixedSize(HEIGHT, WIDTH)

        self.disableSlider()
        self.stepSlider.setOrientation(Qt.Horizontal)
        horizontal_expanding_spacer1 = QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)

        self.fileGroup = QHBoxLayout()
        self.fileGroup.addWidget(self.fileLabel)
        self.fileGroup.addWidget(self.fileInput)
        self.fileGroup.addItem(horizontal_expanding_spacer1)

        self.actionsButtonGroup = QHBoxLayout()
        self.actionsButtonGroup.addWidget(self.addButton)
        self.actionsButtonGroup.addWidget(self.deleteButton)
        self.actionsButtonGroup.addWidget(self.printButton)
        self.actionsButtonGroup.addWidget(self.eulerButton)
        self.actionsButtonGroup.addWidget(self.generateFullButton)
        self.actionsButtonGroup.addWidget(self.generateHalfButton)
        self.actionsButtonGroup.addWidget(self.saveButton)
        self.actionsButtonGroup.addWidget(self.loadButton)
        self.actionsButtonGroup.addWidget(self.saveAsButton)
        self.actionsButtonGroup.addWidget(self.infoButton)
        self.actionsButtonGroup.addWidget(self.bridgeButton)
        # self.actionsButtonGroup.addWidget(self.testButton)
        self.actionsButtonGroup.addWidget(self.button)

        self.topGroup = QVBoxLayout()
        self.topGroup.addItem(self.fileGroup)
        self.topGroup.addItem(self.actionsButtonGroup)

        horizontal_expanding_spacer = QSpacerItem(10, 10, QSizePolicy.Expanding, QSizePolicy.Minimum)

        self.actionsButtonGroup.addItem(horizontal_expanding_spacer)
        self.actionsButtonGroup.addItem(self.labelsGroup)

        self.modeButtonGroup = QVBoxLayout()
        self.modeButtonGroup.addWidget(self.nodeButton)
        self.modeButtonGroup.addWidget(self.edgeButton)
        self.modeButtonGroup.addWidget(self.nodesInputLabel)
        self.modeButtonGroup.addWidget(self.nodesNumberInput)
        self.modeButtonGroup.addWidget(self.edgesInputLabel)
        self.modeButtonGroup.addWidget(self.edgesNumberInput)
        self.modeButtonGroup.addWidget(self.stepSlider)

        vertical_expanding_spacer = QSpacerItem(10, 10, QSizePolicy.Minimum, QSizePolicy.Expanding)

        self.modeButtonGroup.addItem(vertical_expanding_spacer)

        self.infoGroup = QVBoxLayout()
        self.infoGroup.addWidget(self.edgeInfo)
        self.infoGroup.addWidget(self.nodeInfo)
        self.infoGroup.addWidget(self.eulerInfo)

        self.modeButtonGroup.addItem(self.infoGroup)

        self.button.clicked.connect(QCoreApplication.instance().quit)
        self.addButton.clicked.connect(self.add)
        self.deleteButton.clicked.connect(self.delete)
        self.nodeButton.clicked.connect(self.nodeButtonEvent)
        self.edgeButton.clicked.connect(self.edgeButtonEvent)
        self.printButton.clicked.connect(self.printButtonEvent)
        self.eulerButton.clicked.connect(self.findEulerPath)
        self.generateFullButton.clicked.connect(self.generateFull)
        self.generateHalfButton.clicked.connect(self.generateHalf)
        # self.testButton.clicked.connect(self.scene.changeColor)
        self.saveAsButton.clicked.connect(self.saveAsFile)
        self.saveButton.clicked.connect(self.saveFile)
        self.loadButton.clicked.connect(self.loadFile)
        self.scene.cursorPositionSignal.connect(self.setLabels)
        self.scene.nodeNumberSignal.connect(self.setLabelNumber)
        self.stepSlider.sliderMoved.connect(self.setEulerStep)
        self.bridgeButton.clicked.connect(self.findBridges)
        self.infoButton.clicked.connect(self.setInfo)

        self.view.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        layoutH = QHBoxLayout()
        layoutH.addWidget(self.view)
        layoutH.addItem(self.modeButtonGroup)

        layoutV = QVBoxLayout()
        layoutV.addItem(self.topGroup)
        layoutV.addItem(layoutH)

        self.setLayout(layoutV)

        self.setWindowTitle("Example")

        self.scene.setSceneRect(0, 0, 1, 1)

        self.view.setMouseTracking(True)

        self.showMaximized()
        self.graphFile = GraphFile("file.txt")

    def findBridges(self):
        bridges = self.euler.find_bridges(self.scene.G)
        print bridges

    def generate(self, h_or_f):
        generator = Generator()
        nodesNumberStr = self.nodesNumberInput.text()
        edgesNumberStr = self.edgesNumberInput.text()

        if nodesNumberStr == "" or edgesNumberStr == "":
            return

        nodeNumber = int(nodesNumberStr)
        edgesNumber = int(edgesNumberStr)

        G = None
        if h_or_f == "FULL":
            G = generator.generate_full_euler_graph(nodeNumber, edgesNumber)
        elif h_or_f == "HALF":
            G = generator.generate_half_euler_graph(nodeNumber, edgesNumber)

        if G is not None:
            self.scene.clear()

            self.scene.drawGraph(G)

        self.setInfo()

    def setInfo(self):
        self.edgeInfo.setText("E: " + str(len(self.scene.G.edges())))
        self.nodeInfo.setText("N: " + str(len(self.scene.G.nodes())))

        info, odds = self.euler.checkGraph(self.scene.G)
        self.eulerInfo.setText(info)

    def generateHalf(self):
        self.generate("HALF")

    def generateFull(self):
        self.generate("FULL")

    def add(self):
        self.scene.add()
        self.setInfo()

    def delete(self):
        self.scene.delete()
        self.setInfo()

    def findEulerPath(self):
        eulerPath = self.euler.start(self.scene.getGraph())
        print eulerPath

        if eulerPath is not None and len(eulerPath) > 0:
            self.enableSlider(len(eulerPath))
            self.eulerPath = eulerPath

    def setEulerStep(self, stepNum):

        self.scene.setColorForAllEdges(QColor.fromRgb(0, 0, 0))
        if stepNum > 0:
            for i in range(stepNum):
                node1 = self.eulerPath[i]
                node2 = self.eulerPath[i + 1]
                self.scene.setColorForEdge(node1, node2, QColor.fromRgb(0, 255, 0))

    def resizeEvent(self, event):
        w = self.view.width() - 10
        h = self.view.height() - 10

        transform = QTransform.fromScale(w, h)

        self.view.setTransform(transform)
        QWidget.resizeEvent(self, event)

    def enableSlider(self, maximum):
        self.stepSlider.setEnabled(True)
        self.stepSlider.setMinimum(0)
        self.stepSlider.setMaximum(maximum - 1)

    def disableSlider(self):
        self.stepSlider.setDisabled(False)

    def setLabels(self, x, y):
        self.cursorLabelX.setText("X:" + str(x))
        self.cursorLabelY.setText("Y:" + str(y))

    def setLabelNumber(self, number):
        self.nodeNumberLabel.setText("Nr:" + str(number))

    def nodeButtonEvent(self):
        if self.scene.getMode() == "None":
            self.scene.changeMode("Node")
            self.nodeButton.setFlat(True)
        elif self.scene.getMode() == "Node":
            self.nodeButton.setFlat(False)
            self.scene.changeMode("None")
        elif self.scene.getMode() == "Edge":
            self.edgeButton.setFlat(False)
            self.scene.changeMode("Node")
            self.nodeButton.setFlat(True)

    def edgeButtonEvent(self):
        if self.scene.getMode() == "None":
            self.scene.changeMode("Edge")
            self.edgeButton.setFlat(True)
        elif self.scene.getMode() == "Edge":
            self.scene.changeMode("None")
            self.edgeButton.setFlat(False)
        elif self.scene.getMode() == "Node":
            self.scene.changeMode("Edge")
            self.nodeButton.setFlat(False)
            self.edgeButton.setFlat(True)

    def printButtonEvent(self):
        print self.scene.G.nodes()
        print self.scene.G.edges()

    def saveFile(self):
        if self.graphFile.path != "":
            self.graphFile.save(self.scene.G, self.scene.getPos())
        else:
            self.saveAsFile()

    def saveAsFile(self):
        path = QFileDialog.getSaveFileName(self, "Open Graph", ".", "Text files (*.txt)")
        self.setFilePath(path)
        self.graphFile.save(self.scene.G, self.scene.getPos())

    def loadFile(self):
        path = QFileDialog.getOpenFileName(self, "Open Graph", ".", "Text files (*.txt)")
        self.setFilePath(path)
        (G, pos, n, n) = self.graphFile.load()
        self.scene.clear()

        self.scene.drawGraph(G, pos)

        self.setInfo()

    def setFilePath(self, path):
        self.graphFile.path = path
        self.fileInput.setText(path)
Exemplo n.º 9
0
class RecordingWidget(QWidgetWithDpi):
    """Widget containing main recording UI for Freeseer"""

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

        icon = QIcon()
        icon.addPixmap(QPixmap(":/freeseer/logo.png"), QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.resize(400, 400)

        self.mainLayout = QVBoxLayout()
        self.setLayout(self.mainLayout)

        self.setStyleSheet("""
            QToolButton {
                background-color: #D1D1D1;
                border-style: solid;
                border-width: 1px;
                border-radius: 10px;
                border-color: #969696;
                padding: 6px;
            }

            QToolButton:pressed {
                background-color: #A3A2A2;
                border-width: 2px;
                border-color: #707070;
            }

            QToolButton:checked {
                background-color: #A3A2A2;
                border-width: 2px;
                border-color: #707070;
            }

            QToolButton:disabled {
                background-color: #EDEDED;
                border-color: #BFBDBD;
            }

            QToolButton:hover {
                border-width: 2px;
            }
        """)

        boldFont = QFont()
        boldFont.setBold(True)

        fontSize = self.font().pixelSize()
        fontUnit = "px"
        if fontSize == -1:  # Font is set as points, not pixels.
            fontUnit = "pt"
            fontSize = self.font().pointSize()

        # Control bar
        self.controlRow = QHBoxLayout()
        self.mainLayout.addLayout(self.controlRow)

        self.recordIcon = QIcon(":/multimedia/record.png")
        self.stopIcon = QIcon(":/multimedia/stop.png")
        pauseIcon = QIcon(":/multimedia/pause.png")
        playIcon = QIcon(":/multimedia/play.png")
        self.headphoneIcon = QIcon()
        self.headphoneIcon.addPixmap(QPixmap(":/multimedia/headphones.png"), QIcon.Normal, QIcon.Off)

        self.is_recording = False
        self.recordButton = QToolButtonWithDpi()
        self.recordButton.setToolTip("Record")
        self.recordButton.setFixedSize(QSize(60, 40))
        self.recordButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.recordButton.setIcon(self.recordIcon)
        self.recordButton.setEnabled(False)
        self.recordButton.setObjectName("recordButton")
        self.controlRow.addWidget(self.recordButton, 0, Qt.AlignLeft)
        self.connect(self.recordButton, SIGNAL("clicked()"), self.setRecordIcon)

        self.playButton = QToolButtonWithDpi()
        self.playButton.setToolTip("Play last recorded Video")
        self.playButton.setFixedSize(QSize(60, 40))
        self.playButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.playButton.setIcon(playIcon)
        self.playButton.setEnabled(False)
        self.controlRow.addWidget(self.playButton, 0, Qt.AlignLeft)

        self.pauseButton = QToolButtonWithDpi()
        self.pauseButton.setToolTip("Pause")
        self.pauseButton.setIcon(pauseIcon)
        self.pauseButton.setFixedSize(QSize(60, 40))
        self.pauseButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.pauseButton.setEnabled(False)
        self.pauseButton.setCheckable(True)
        self.controlRow.addWidget(self.pauseButton, 0, Qt.AlignLeft)

        self.controlRow.addSpacerItem(self.qspacer_item_with_dpi(30, 40))
        self.controlRow.addStretch(1)

        self.standbyButton = QPushButtonWithDpi("Standby")
        self.standbyButton.setStyleSheet("""
            QPushButton {{
                color: white;
                background-color: #47a447;
                border-style: solid;
                border-width: 0px;
                border-radius: 10px;
                border-color: #398439;
                font: bold {}{};
                padding: 6px;
            }}

            QPushButton:pressed {{
                background-color: #3E8A3E;
                border-color: #327532;
            }}

            QPushButton:hover {{
                border-width: 2px;
            }}
        """.format(fontSize + 3, fontUnit))
        self.standbyButton.setToolTip("Standby")
        self.standbyButton.setFixedSize(QSize(180, 40))
        self.standbyButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.standbyButton.setCheckable(True)
        self.standbyButton.setObjectName("standbyButton")
        self.controlRow.addWidget(self.standbyButton)

        self.disengageButton = QPushButtonWithDpi("Leave record-mode")
        self.disengageButton.setStyleSheet("""
            QPushButton {{
                color: white;
                background-color: #D14343;
                border-style: solid;
                border-width: 0px;
                border-radius: 10px;
                border-color: #B02C2C;
                font: bold {}{};
                padding: 6px;
            }}

            QPushButton:pressed {{
                background-color: #AD2B2B;
                border-color: #8C2929;
            }}

            QPushButton:hover {{
                border-width: 2px;
            }}

            QPushButton:disabled {{
                background-color: #B89E9E;
        }}
        """.format(fontSize + 3, fontUnit))
        self.disengageButton.setToolTip("Leave record-mode")
        self.disengageButton.setFixedSize(QSize(180, 40))
        self.disengageButton.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.disengageButton.setHidden(True)
        self.disengageButton.setObjectName("disengageButton")
        self.controlRow.addWidget(self.disengageButton)

        # Filter bar
        self.filterBarLayout = QVBoxLayout()
        self.mainLayout.addLayout(self.filterBarLayout)

        self.filterBarLayoutRow_1 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_1)
        self.eventLabel = QLabel("Event")
        self.eventLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.eventComboBox = QComboBox()
        self.eventLabel.setBuddy(self.eventComboBox)
        self.roomLabel = QLabel("Room")
        self.roomLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.roomComboBox = QComboBox()
        self.roomLabel.setBuddy(self.roomComboBox)
        self.dateLabel = QLabel("Date")
        self.dateLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.dateComboBox = QComboBox()
        self.dateLabel.setBuddy(self.dateComboBox)
        self.filterBarLayoutRow_1.addWidget(self.eventLabel)
        self.filterBarLayoutRow_1.addWidget(self.eventComboBox)
        self.filterBarLayoutRow_1.addWidget(self.roomLabel)
        self.filterBarLayoutRow_1.addWidget(self.roomComboBox)
        self.filterBarLayoutRow_1.addWidget(self.dateLabel)
        self.filterBarLayoutRow_1.addWidget(self.dateComboBox)

        self.filterBarLayoutRow_2 = QHBoxLayout()
        self.filterBarLayout.addLayout(self.filterBarLayoutRow_2)
        self.talkLabel = QLabel("Talk ")
        self.talkLabel.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Fixed)
        self.talkComboBox = QComboBox()
        self.talkComboBox.setFont(boldFont)
        self.talkComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        self.talkComboBox.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.filterBarLayoutRow_2.addWidget(self.talkLabel)
        self.filterBarLayoutRow_2.addWidget(self.talkComboBox)

        # Preview Layout
        self.previewLayout = QHBoxLayout()
        self.mainLayout.addLayout(self.previewLayout)

        self.previewWidget = QWidget()
        self.audioSlider = QSlider()
        self.audioSlider.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.audioSlider.setEnabled(False)
        self.previewLayout.addWidget(self.previewWidget)
        self.previewLayout.addWidget(self.audioSlider)

        self.statusLabel = QLabel()
        self.mainLayout.addWidget(self.statusLabel)

        # Audio Feedback Checkbox
        self.audioFeedbackCheckbox = QCheckBox()
        self.audioFeedbackCheckbox.setLayoutDirection(Qt.RightToLeft)
        self.audioFeedbackCheckbox.setIcon(self.headphoneIcon)
        self.audioFeedbackCheckbox.setToolTip("Enable Audio Feedback")
        self.mainLayout.addWidget(self.audioFeedbackCheckbox)

    def setRecordIcon(self):
        self.is_recording = not self.is_recording
        if self.is_recording:
            self.recordButton.setIcon(self.stopIcon)
        else:
            self.recordButton.setIcon(self.recordIcon)
Exemplo n.º 10
0
class EditGeometryProperties(PyDialog):
    force = True

    def __init__(self, data, win_parent=None):
        """
        +------------------+
        | Edit Actor Props |
        +------------------+------+
        |  Name1                  |
        |  Name2                  |
        |  Name3                  |
        |  Name4                  |
        |                         |
        |  Active_Name    main    |
        |  Color          box     |
        |  Line_Width     2       |
        |  Point_Size     2       |
        |  Bar_Scale      2       |
        |  Opacity        0.5     |
        |  Show/Hide              |
        |                         |
        |    Apply   OK   Cancel  |
        +-------------------------+
        """
        PyDialog.__init__(self, data, win_parent)
        self.set_font_size(data['font_size'])
        del self.out_data['font_size']
        self.setWindowTitle('Edit Geometry Properties')
        self.allow_update = True

        #default
        #self.win_parent = win_parent
        #self.out_data = data

        self.keys = sorted(data.keys())
        self.keys = data.keys()
        keys = self.keys
        nrows = len(keys)
        self.active_key = 'main'  #keys[0]

        items = keys

        header_labels = ['Groups']
        table_model = Model(items, header_labels, self)
        view = CustomQTableView(self)  #Call your custom QTableView here
        view.setModel(table_model)
        if qt_version == 4:
            view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        self.table = view

        actor_obj = data[self.active_key]
        name = actor_obj.name
        line_width = actor_obj.line_width
        point_size = actor_obj.point_size
        bar_scale = actor_obj.bar_scale
        opacity = actor_obj.opacity
        color = actor_obj.color
        show = actor_obj.is_visible
        self.representation = actor_obj.representation

        # table
        header = self.table.horizontalHeader()
        header.setStretchLastSection(True)

        self._default_is_apply = False
        self.name = QLabel("Name:")
        self.name_edit = QLineEdit(str(name))
        self.name_edit.setDisabled(True)

        self.color = QLabel("Color:")
        self.color_edit = QPushButton()
        #self.color_edit.setFlat(True)

        color = self.out_data[self.active_key].color
        qcolor = QtGui.QColor()
        qcolor.setRgb(*color)
        #print('color =%s' % str(color))
        palette = QtGui.QPalette(
            self.color_edit.palette())  # make a copy of the palette
        #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \
        #qcolor)
        palette.setColor(QtGui.QPalette.Background,
                         QtGui.QColor('blue'))  # ButtonText
        self.color_edit.setPalette(palette)

        self.color_edit.setStyleSheet("QPushButton {"
                                      "background-color: rgb(%s, %s, %s);" %
                                      tuple(color) +
                                      #"border:1px solid rgb(255, 170, 255); "
                                      "}")

        self.use_slider = True
        self.is_opacity_edit_active = False
        self.is_opacity_edit_slider_active = False

        self.is_line_width_edit_active = False
        self.is_line_width_edit_slider_active = False

        self.is_point_size_edit_active = False
        self.is_point_size_edit_slider_active = False

        self.is_bar_scale_edit_active = False
        self.is_bar_scale_edit_slider_active = False

        self.opacity = QLabel("Opacity:")
        self.opacity_edit = QDoubleSpinBox(self)
        self.opacity_edit.setRange(0.1, 1.0)
        self.opacity_edit.setDecimals(1)
        self.opacity_edit.setSingleStep(0.1)
        self.opacity_edit.setValue(opacity)
        if self.use_slider:
            self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.opacity_slider_edit.setRange(1, 10)
            self.opacity_slider_edit.setValue(opacity * 10)
            self.opacity_slider_edit.setTickInterval(1)
            self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow)

        self.line_width = QLabel("Line Width:")
        self.line_width_edit = QSpinBox(self)
        self.line_width_edit.setRange(1, 15)
        self.line_width_edit.setSingleStep(1)
        self.line_width_edit.setValue(line_width)
        if self.use_slider:
            self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.line_width_slider_edit.setRange(1, 15)
            self.line_width_slider_edit.setValue(line_width)
            self.line_width_slider_edit.setTickInterval(1)
            self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow)

        if self.representation in ['point', 'surface']:
            self.line_width.setEnabled(False)
            self.line_width_edit.setEnabled(False)
            self.line_width_slider_edit.setEnabled(False)

        self.point_size = QLabel("Point Size:")
        self.point_size_edit = QSpinBox(self)
        self.point_size_edit.setRange(1, 15)
        self.point_size_edit.setSingleStep(1)
        self.point_size_edit.setValue(point_size)
        self.point_size.setVisible(False)
        self.point_size_edit.setVisible(False)
        if self.use_slider:
            self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.point_size_slider_edit.setRange(1, 15)
            self.point_size_slider_edit.setValue(point_size)
            self.point_size_slider_edit.setTickInterval(1)
            self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow)
            self.point_size_slider_edit.setVisible(False)

        if self.representation in ['wire', 'surface']:
            self.point_size.setEnabled(False)
            self.point_size_edit.setEnabled(False)
            if self.use_slider:
                self.point_size_slider_edit.setEnabled(False)

        self.bar_scale = QLabel("Bar Scale:")
        self.bar_scale_edit = QDoubleSpinBox(self)
        #self.bar_scale_edit.setRange(0.01, 1.0)  # was 0.1
        #self.bar_scale_edit.setRange(0.05, 5.0)
        self.bar_scale_edit.setDecimals(1)
        #self.bar_scale_edit.setSingleStep(bar_scale / 10.)
        self.bar_scale_edit.setSingleStep(0.1)
        self.bar_scale_edit.setValue(bar_scale)

        #if self.use_slider:
        #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal)
        #self.bar_scale_slider_edit.setRange(1, 100)  # 1/0.05 = 100/5.0
        #self.bar_scale_slider_edit.setValue(opacity * 0.05)
        #self.bar_scale_slider_edit.setTickInterval(10)
        #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow)

        if self.representation != 'bar':
            self.bar_scale.setEnabled(False)
            self.bar_scale_edit.setEnabled(False)
            self.bar_scale.setVisible(False)
            self.bar_scale_edit.setVisible(False)
            #self.bar_scale_slider_edit.setVisible(False)
            #self.bar_scale_slider_edit.setEnabled(False)

        # show/hide
        self.checkbox_show = QCheckBox("Show")
        self.checkbox_hide = QCheckBox("Hide")
        self.checkbox_show.setChecked(show)
        self.checkbox_hide.setChecked(not show)

        if name == 'main':
            self.color.setEnabled(False)
            self.color_edit.setEnabled(False)
            self.point_size.setEnabled(False)
            self.point_size_edit.setEnabled(False)
            if self.use_slider:
                self.point_size_slider_edit.setEnabled(False)

        self.cancel_button = QPushButton("Close")

        self.create_layout()
        self.set_connections()

    def on_update_geometry_properties_window(self, data):
        """Not Implemented"""
        return
        #new_keys = sorted(data.keys())
        #if self.active_key in new_keys:
        #i = new_keys.index(self.active_key)
        #else:
        #i = 0
        #self.table.update_data(new_keys)
        #self.out_data = data
        #self.update_active_key(i)

    def update_active_key(self, index):
        """
        Parameters
        ----------
        index : PyQt4.QtCore.QModelIndex
            the index of the list

        Internal Parameters
        -------------------
        name : str
            the name of obj
        obj : CoordProperties, AltGeometry
            the storage object for things like line_width, point_size, etc.
        """
        if qt_version == 4:
            name = str(index.data().toString())
        else:
            name = str(index.data())
            print('name = %r' % name)
        #i = self.keys.index(self.active_key)

        self.active_key = name
        self.name_edit.setText(name)
        obj = self.out_data[name]
        if isinstance(obj, CoordProperties):
            opacity = 1.0
            representation = 'coord'
            is_visible = obj.is_visible
        elif isinstance(obj, AltGeometry):
            line_width = obj.line_width
            point_size = obj.point_size
            bar_scale = obj.bar_scale
            opacity = obj.opacity
            representation = obj.representation
            is_visible = obj.is_visible

            self.color_edit.setStyleSheet(
                "QPushButton {"
                "background-color: rgb(%s, %s, %s);" % tuple(obj.color) +
                #"border:1px solid rgb(255, 170, 255); "
                "}")
            self.allow_update = False
            self.force = False
            self.line_width_edit.setValue(line_width)
            self.point_size_edit.setValue(point_size)
            self.bar_scale_edit.setValue(bar_scale)
            self.force = True
            self.allow_update = True
        else:
            raise NotImplementedError(obj)

        allowed_representations = [
            'main', 'surface', 'coord', 'toggle', 'wire', 'point', 'bar'
        ]

        if self.representation != representation:
            self.representation = representation
            if representation not in allowed_representations:
                msg = 'name=%r; representation=%r is invalid\nrepresentations=%r' % (
                    name, representation, allowed_representations)

            if self.representation == 'coord':
                self.color.setVisible(False)
                self.color_edit.setVisible(False)
                self.line_width.setVisible(False)
                self.line_width_edit.setVisible(False)
                self.point_size.setVisible(False)
                self.point_size_edit.setVisible(False)
                self.bar_scale.setVisible(False)
                self.bar_scale_edit.setVisible(False)
                self.opacity.setVisible(False)
                self.opacity_edit.setVisible(False)
                if self.use_slider:
                    self.opacity_slider_edit.setVisible(False)
                    self.point_size_slider_edit.setVisible(False)
                    self.line_width_slider_edit.setVisible(False)
                    #self.bar_scale_slider_edit.setVisible(False)
            else:
                self.color.setVisible(True)
                self.color_edit.setVisible(True)
                self.line_width.setVisible(True)
                self.line_width_edit.setVisible(True)
                self.point_size.setVisible(True)
                self.point_size_edit.setVisible(True)
                self.bar_scale.setVisible(True)
                #self.bar_scale_edit.setVisible(True)
                self.opacity.setVisible(True)
                self.opacity_edit.setVisible(True)
                if self.use_slider:
                    self.opacity_slider_edit.setVisible(True)
                    self.line_width_slider_edit.setVisible(True)
                    self.point_size_slider_edit.setVisible(True)
                    #self.bar_scale_slider_edit.setVisible(True)

                if name == 'main':
                    self.color.setEnabled(False)
                    self.color_edit.setEnabled(False)
                    self.point_size.setEnabled(False)
                    self.point_size_edit.setEnabled(False)
                    self.line_width.setEnabled(True)
                    self.line_width_edit.setEnabled(True)
                    self.bar_scale.setEnabled(False)
                    self.bar_scale_edit.setEnabled(False)
                    show_points = False
                    show_line_width = True
                    show_bar_scale = False
                    if self.use_slider:
                        self.line_width_slider_edit.setEnabled(True)
                        #self.bar_scale_slider_edit.setVisible(False)
                else:
                    self.color.setEnabled(True)
                    self.color_edit.setEnabled(True)

                    show_points = False
                    if self.representation in ['point', 'wire+point']:
                        show_points = True

                    show_line_width = False
                    if self.representation in ['wire', 'wire+point', 'bar']:
                        show_line_width = True

                    if representation == 'bar':
                        show_bar_scale = True
                    else:
                        show_bar_scale = False
                    #self.bar_scale_button.setVisible(show_bar_scale)
                    #self.bar_scale_edit.setSingleStep(bar_scale / 10.)
                    #if self.use_slider:
                    #self.bar_scale_slider_edit.setEnabled(False)

                self.point_size.setEnabled(show_points)
                self.point_size_edit.setEnabled(show_points)
                self.point_size.setVisible(show_points)
                self.point_size_edit.setVisible(show_points)

                self.line_width.setEnabled(show_line_width)
                self.line_width_edit.setEnabled(show_line_width)

                self.bar_scale.setEnabled(show_bar_scale)
                self.bar_scale_edit.setEnabled(show_bar_scale)
                self.bar_scale.setVisible(show_bar_scale)
                self.bar_scale_edit.setVisible(show_bar_scale)
                if self.use_slider:
                    self.point_size_slider_edit.setEnabled(show_points)
                    self.point_size_slider_edit.setVisible(show_points)
                    self.line_width_slider_edit.setEnabled(show_line_width)

            #if self.representation in ['wire', 'surface']:

        self.opacity_edit.setValue(opacity)
        #if self.use_slider:
        #self.opacity_slider_edit.setValue(opacity*10)
        self.checkbox_show.setChecked(is_visible)
        self.checkbox_hide.setChecked(not is_visible)

        passed = self.on_validate()
        #self.on_apply(force=True)  # TODO: was turned on...do I want this???
        #self.allow_update = True

    #def on_name_select(self):
    #print('on_name_select')
    #return

    def create_layout(self):
        ok_cancel_box = QHBoxLayout()
        ok_cancel_box.addWidget(self.cancel_button)

        grid = QGridLayout()

        irow = 0
        grid.addWidget(self.name, irow, 0)
        grid.addWidget(self.name_edit, irow, 1)
        irow += 1

        grid.addWidget(self.color, irow, 0)
        grid.addWidget(self.color_edit, irow, 1)
        irow += 1

        grid.addWidget(self.opacity, irow, 0)
        if self.use_slider:
            grid.addWidget(self.opacity_edit, irow, 2)
            grid.addWidget(self.opacity_slider_edit, irow, 1)
        else:
            grid.addWidget(self.opacity_edit, irow, 1)
        irow += 1

        grid.addWidget(self.line_width, irow, 0)
        if self.use_slider:
            grid.addWidget(self.line_width_edit, irow, 2)
            grid.addWidget(self.line_width_slider_edit, irow, 1)
        else:
            grid.addWidget(self.line_width_edit, irow, 1)
        irow += 1

        grid.addWidget(self.point_size, irow, 0)
        if self.use_slider:
            grid.addWidget(self.point_size_edit, irow, 2)
            grid.addWidget(self.point_size_slider_edit, irow, 1)
        else:
            grid.addWidget(self.point_size_edit, irow, 1)
        irow += 1

        grid.addWidget(self.bar_scale, irow, 0)
        if self.use_slider and 0:
            grid.addWidget(self.bar_scale_edit, irow, 2)
            grid.addWidget(self.bar_scale_slider_edit, irow, 1)
        else:
            grid.addWidget(self.bar_scale_edit, irow, 1)
        irow += 1

        checkboxs = QButtonGroup(self)
        checkboxs.addButton(self.checkbox_show)
        checkboxs.addButton(self.checkbox_hide)

        vbox = QVBoxLayout()
        vbox.addWidget(self.table)
        vbox.addLayout(grid)

        if 0:
            vbox.addWidget(self.checkbox_show)
            vbox.addWidget(self.checkbox_hide)
        else:
            vbox1 = QVBoxLayout()
            vbox1.addWidget(self.checkbox_show)
            vbox1.addWidget(self.checkbox_hide)
            vbox.addLayout(vbox1)

        vbox.addStretch()
        #vbox.addWidget(self.check_apply)
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)

    def set_connections(self):
        self.opacity_edit.valueChanged.connect(self.on_opacity)
        self.line_width_edit.valueChanged.connect(self.on_line_width)
        self.point_size_edit.valueChanged.connect(self.on_point_size)
        self.bar_scale_edit.valueChanged.connect(self.on_bar_scale)

        if self.use_slider:
            self.opacity_slider_edit.valueChanged.connect(
                self.on_opacity_slider)
            self.line_width_slider_edit.valueChanged.connect(
                self.on_line_width_slider)
            self.point_size_slider_edit.valueChanged.connect(
                self.on_point_size_slider)
            #self.bar_scale_slider_edit.valueChanged.connect(self.on_bar_scale_slider)

        # self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity)
        # self.connect(self.line_width, QtCore.SIGNAL('clicked()'), self.on_line_width)
        # self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size)

        if qt_version == 4:
            self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
        self.color_edit.clicked.connect(self.on_color)
        self.checkbox_show.clicked.connect(self.on_show)
        self.checkbox_hide.clicked.connect(self.on_hide)
        self.cancel_button.clicked.connect(self.on_cancel)
        # closeEvent

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()

    def closeEvent(self, event):
        self.on_cancel()

    def on_color(self):
        """called when the user clicks on the color box"""
        name = self.active_key
        obj = self.out_data[name]
        rgb_color_ints = obj.color

        msg = name
        col = QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self,
                                    "Choose a %s color" % msg)
        if col.isValid():
            color_float = col.getRgbF()[:3]
            obj.color = color_float
            color_int = [int(colori * 255) for colori in color_float]
            self.color_edit.setStyleSheet(
                "QPushButton {"
                "background-color: rgb(%s, %s, %s);" % tuple(color_int) +
                #"border:1px solid rgb(255, 170, 255); "
                "}")
        self.on_apply(force=self.force)
        #print(self.allow_update)

    def on_show(self):
        """shows the actor"""
        name = self.active_key
        is_checked = self.checkbox_show.isChecked()
        self.out_data[name].is_visible = is_checked
        self.on_apply(force=self.force)

    def on_hide(self):
        """hides the actor"""
        name = self.active_key
        is_checked = self.checkbox_hide.isChecked()
        self.out_data[name].is_visible = not is_checked
        self.on_apply(force=self.force)

    def on_line_width(self):
        """increases/decreases the wireframe (for solid bodies) or the bar thickness"""
        self.is_line_width_edit_active = True
        name = self.active_key
        line_width = self.line_width_edit.value()
        self.out_data[name].line_width = line_width
        if not self.is_line_width_edit_slider_active:
            if self.use_slider:
                self.line_width_slider_edit.setValue(line_width)
            self.is_line_width_edit_active = False
        self.on_apply(force=self.force)
        self.is_line_width_edit_active = False

    def on_line_width_slider(self):
        """increases/decreases the wireframe (for solid bodies) or the bar thickness"""
        self.is_line_width_edit_slider_active = True
        #name = self.active_key
        line_width = self.line_width_slider_edit.value()
        if not self.is_line_width_edit_active:
            self.line_width_edit.setValue(line_width)
        self.is_line_width_edit_slider_active = False

    def on_point_size(self):
        """increases/decreases the point size"""
        self.is_point_size_edit_active = True
        name = self.active_key
        point_size = self.point_size_edit.value()
        self.out_data[name].point_size = point_size
        if not self.is_point_size_edit_slider_active:
            if self.use_slider:
                self.point_size_slider_edit.setValue(point_size)
            self.is_point_size_edit_active = False
        self.on_apply(force=self.force)
        self.is_point_size_edit_active = False

    def on_point_size_slider(self):
        """increases/decreases the point size"""
        self.is_point_size_edit_slider_active = True
        name = self.active_key
        point_size = self.point_size_slider_edit.value()
        if not self.is_point_size_edit_active:
            self.point_size_edit.setValue(point_size)
        self.is_point_size_edit_slider_active = False

    def on_bar_scale(self):
        """
        Vectors start at some xyz coordinate and can increase in length.
        Increases/decreases the length scale factor.
        """
        self.is_bar_scale_edit_active = True
        name = self.active_key
        float_bar_scale = self.bar_scale_edit.value()
        self.out_data[name].bar_scale = float_bar_scale
        if not self.is_bar_scale_edit_slider_active:
            int_bar_scale = int(round(float_bar_scale * 20, 0))
            #if self.use_slider:
            #self.bar_scale_slider_edit.setValue(int_bar_scale)
            self.is_bar_scale_edit_active = False
        self.on_apply(force=self.force)
        self.is_bar_scale_edit_active = False

    def on_bar_scale_slider(self):
        """
        Vectors start at some xyz coordinate and can increase in length.
        Increases/decreases the length scale factor.
        """
        self.is_bar_scale_edit_slider_active = True
        name = self.active_key
        int_bar_scale = self.bar_scale_slider_edit.value()
        if not self.is_bar_scale_edit_active:
            float_bar_scale = int_bar_scale / 20.
            self.bar_scale_edit.setValue(float_bar_scale)
        self.is_bar_scale_edit_slider_active = False

    def on_opacity(self):
        """
        opacity = 1.0 (solid/opaque)
        opacity = 0.0 (invisible)
        """
        self.is_opacity_edit_active = True
        name = self.active_key
        float_opacity = self.opacity_edit.value()
        self.out_data[name].opacity = float_opacity
        if not self.is_opacity_edit_slider_active:
            int_opacity = int(round(float_opacity * 10, 0))
            if self.use_slider:
                self.opacity_slider_edit.setValue(int_opacity)
            self.is_opacity_edit_active = False
        self.on_apply(force=self.force)
        self.is_opacity_edit_active = False

    def on_opacity_slider(self):
        """
            opacity = 1.0 (solid/opaque)
            opacity = 0.0 (invisible)
            """
        self.is_opacity_edit_slider_active = True
        name = self.active_key
        int_opacity = self.opacity_slider_edit.value()
        if not self.is_opacity_edit_active:
            float_opacity = int_opacity / 10.
            self.opacity_edit.setValue(float_opacity)
        self.is_opacity_edit_slider_active = False

    #def on_axis(self, text):
    ##print(self.combo_axis.itemText())
    #self._axis = str(text)
    #self.plane.setText('Point on %s? Plane:' % self._axis)
    #self.point_a.setText('Point on %s Axis:' % self._axis)
    #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane))

    #def on_plane(self, text):
    #self._plane = str(text)
    #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane))

    #def _on_float(self, field):
    #try:
    #eval_float_from_string(field.text())
    #field.setStyleSheet("QLineEdit{background: white;}")
    #except ValueError:
    #field.setStyleSheet("QLineEdit{background: red;}")

    #def on_default_name(self):
    #self.name_edit.setText(str(self._default_name))
    #self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    #def check_float(self, cell):
    #text = cell.text()
    #try:
    #value = eval_float_from_string(text)
    #cell.setStyleSheet("QLineEdit{background: white;}")
    #return value, True
    #except ValueError:
    #cell.setStyleSheet("QLineEdit{background: red;}")
    #return None, False

    #def check_name(self, cell):
    #text = str(cell.text()).strip()
    #if len(text):
    #cell.setStyleSheet("QLineEdit{background: white;}")
    #return text, True
    #else:
    #cell.setStyleSheet("QLineEdit{background: red;}")
    #return None, False

    def on_validate(self):
        self.out_data['clicked_ok'] = True
        self.out_data['clicked_cancel'] = False

        old_obj = self.out_data[self.active_key]
        old_obj.line_width = self.line_width_edit.value()
        old_obj.point_size = self.point_size_edit.value()
        old_obj.bar_scale = self.bar_scale_edit.value()
        old_obj.opacity = self.opacity_edit.value()
        #old_obj.color = self.color_edit
        old_obj.is_visible = self.checkbox_show.isChecked()
        return True
        #name_value, flag0 = self.check_name(self.name_edit)
        #ox_value, flag1 = self.check_float(self.transparency_edit)
        #if flag0 and flag1:
        #self.out_data['clicked_ok'] = True
        #return True
        #return False

    def on_apply(self, force=False):
        passed = self.on_validate()
        #print("passed=%s force=%s allow=%s" % (passed, force, self.allow_update))
        if (passed or force) and self.allow_update and hasattr(
                self.win_parent, 'on_update_geometry_properties'):
            #print('obj = %s' % self.out_data[self.active_key])
            self.win_parent.on_update_geometry_properties(self.out_data,
                                                          name=self.active_key)
        return passed

    def on_cancel(self):
        passed = self.on_apply(force=True)
        if passed:
            self.close()
Exemplo n.º 11
0
class FeeSelectionDialog(ArmoryDialog):
   
   #############################################################################
   def __init__(self, parent, main, cs_callback, get_csstate):
      super(FeeSelectionDialog, self).__init__(parent, main)
      
      #Button Label
      self.lblButtonFee = QLabelButton("")
      
      #get default values
      flatFee = self.main.getSettingOrSetDefault("Default_Fee", MIN_TX_FEE)
      flatFee = coin2str(flatFee, maxZeros=1).strip()
      fee_byte = str(self.main.getSettingOrSetDefault("Default_FeeByte", MIN_FEE_BYTE))
      blocksToConfirm = self.main.getSettingOrSetDefault(\
         "Default_FeeByte_BlocksToConfirm", NBLOCKS_TO_CONFIRM)
      
      self.coinSelectionCallback = cs_callback
      self.getCoinSelectionState = get_csstate
      self.validAutoFee = True
      try:
         autoFee_byte = str(estimateFee(blocksToConfirm) / 1000.0)
      except:
         autoFee_byte = "N/A"
         self.validAutoFee = False
         
      defaultCheckState = \
         self.main.getSettingOrSetDefault("FeeOption", DEFAULT_FEE_TYPE)
      
      #flat free
      def setFlatFee():
         def callbck():
            return self.selectType('FlatFee')
         return callbck
      
      def updateLbl():
         self.updateCoinSelection()
      
      self.radioFlatFee = QRadioButton(self.tr("Flat Fee (BTC)"))
      self.edtFeeAmt = QLineEdit(flatFee)
      self.edtFeeAmt.setFont(GETFONT('Fixed'))
      self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0])
      self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0])
      
      self.connect(self.radioFlatFee, SIGNAL('clicked()'), setFlatFee())
      self.connect(self.edtFeeAmt, SIGNAL('textChanged(QString)'), updateLbl)
      
      frmFlatFee = QFrame()
      frmFlatFee.setFrameStyle(STYLE_RAISED)
      layoutFlatFee = QGridLayout()
      layoutFlatFee.addWidget(self.radioFlatFee, 0, 0, 1, 1)
      layoutFlatFee.addWidget(self.edtFeeAmt, 0, 1, 1, 1)
      frmFlatFee.setLayout(layoutFlatFee)
      
      #fee/byte
      def setFeeByte():
         def callbck():
            return self.selectType('FeeByte')
         return callbck
      
      self.radioFeeByte = QRadioButton(self.tr("Fee/Byte (Satoshi/Byte)"))
      self.edtFeeByte = QLineEdit(fee_byte)
      self.edtFeeByte.setFont(GETFONT('Fixed'))
      self.edtFeeByte.setMinimumWidth(tightSizeNChar(self.edtFeeByte, 6)[0])
      self.edtFeeByte.setMaximumWidth(tightSizeNChar(self.edtFeeByte, 12)[0])
      
      self.connect(self.radioFeeByte, SIGNAL('clicked()'), setFeeByte())
      self.connect(self.edtFeeByte, SIGNAL('textChanged(QString)'), updateLbl)
            
      frmFeeByte = QFrame()
      frmFeeByte.setFrameStyle(STYLE_RAISED)
      layoutFeeByte = QGridLayout()
      layoutFeeByte.addWidget(self.radioFeeByte, 0, 0, 1, 1)
      layoutFeeByte.addWidget(self.edtFeeByte, 0, 1, 1, 1)
      frmFeeByte.setLayout(layoutFeeByte)
      
      #auto fee/byte
      def setAutoFeeByte():
         def callbck():
            return self.selectType('Auto')
         return callbck      
      
      radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ")
      if not self.validAutoFee:      
         radioButtonTxt = self.tr("Failed to fetch fee/byte from node")
         
      self.radioAutoFeeByte = QRadioButton(radioButtonTxt)
      self.lblAutoFeeByte = QLabel(autoFee_byte)
      self.lblAutoFeeByte.setFont(GETFONT('Fixed'))
      self.lblAutoFeeByte.setMinimumWidth(tightSizeNChar(self.lblAutoFeeByte, 6)[0])
      self.lblAutoFeeByte.setMaximumWidth(tightSizeNChar(self.lblAutoFeeByte, 12)[0])
      
      self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self)
      self.sliderAutoFeeByte.setMinimum(2)
      self.sliderAutoFeeByte.setMaximum(6)
      self.sliderAutoFeeByte.setValue(blocksToConfirm)
      self.lblSlider = QLabel()
      
      def getSliderLabelTxt():
         return self.tr("Blocks to confirm: %1").arg(\
               unicode(self.sliderAutoFeeByte.value()))
         
      def updateAutoFeeByte():
         blocksToConfirm = self.sliderAutoFeeByte.value()
         try:
            autoFee_byte = str(estimateFee(blocksToConfirm) / 1000.0)

         except:
            autoFee_byte = "N/A"
         
         self.lblSlider.setText(getSliderLabelTxt())         
         self.lblAutoFeeByte.setText(autoFee_byte)
         updateLbl()
         
      self.lblSlider.setText(getSliderLabelTxt())
      
      self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte())
      self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte)
      self.sliderAutoFeeByte.setEnabled(False)
            
      frmAutoFeeByte = QFrame()
      frmAutoFeeByte.setFrameStyle(STYLE_RAISED)
      layoutAutoFeeByte = QGridLayout()
      layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 1)
      layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 1, 1, 1)  
      layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 2)
      layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 2)
      frmAutoFeeByte.setLayout(layoutAutoFeeByte)
      
      if not self.validAutoFee:
         frmAutoFeeByte.setEnabled(False)
      
      #adjust and close
      self.btnClose = QPushButton(self.tr('Close'))
      self.connect(self.btnClose, SIGNAL('clicked()'), self.accept)
      
      self.checkBoxAdjust = QCheckBox(self.tr('Adjust fee/byte for privacy'))
      self.checkBoxAdjust.setChecked(\
         self.main.getSettingOrSetDefault('AdjustFee', True))
            
      self.connect(self.checkBoxAdjust, SIGNAL('clicked()'), updateLbl)
      
      frmClose = makeHorizFrame(\
         [self.checkBoxAdjust, 'Stretch', self.btnClose], STYLE_NONE)
      
      #main layout
      layout = QGridLayout()
      layout.addWidget(frmAutoFeeByte, 0, 0, 1, 4)
      layout.addWidget(frmFeeByte, 2, 0, 1, 4)
      layout.addWidget(frmFlatFee, 4, 0, 1, 4)
      layout.addWidget(frmClose, 5, 0, 1, 4)
      
      self.setLayout(layout)      
      self.setWindowTitle(self.tr('Select Fee Type'))
      
      self.selectType(defaultCheckState)

      self.setFocus()  
   
   #############################################################################   
   def selectType(self, strType):
      self.radioFlatFee.setChecked(False)
      self.radioFeeByte.setChecked(False)
      self.radioAutoFeeByte.setChecked(False)
      self.sliderAutoFeeByte.setEnabled(False)
      
      if strType == 'FlatFee':
         self.radioFlatFee.setChecked(True)
      elif strType == 'FeeByte':
         self.radioFeeByte.setChecked(True)
      elif strType == 'Auto':
         if not self.validAutoFee:
            self.radioFeeByte.setChecked(True)
         else:
            self.radioAutoFeeByte.setChecked(True)
            self.sliderAutoFeeByte.setEnabled(True)
            
      self.updateCoinSelection()
      self.updateLabelButton()
      
   #############################################################################
   def updateCoinSelection(self):
      try:
         self.coinSelectionCallback()
      except:
         self.updateLabelButton()
   
   #############################################################################   
   def getLabelButton(self):
      return self.lblButtonFee
   
   #############################################################################
   def updateLabelButtonText(self, txSize, flatFee, fee_byte):
      txSize = str(txSize)
      if txSize != 'N/A':
         txSize += " B"
      
      if flatFee != 'N/A':
         flatFee = coin2str(flatFee, maxZeros=0).strip()
         flatFee += " BTC"   
      
      if not isinstance(fee_byte, str):   
         fee_byte = '%.2f' % fee_byte 
      
      lblStr = "Size: %s, Fee: %s" % (txSize, flatFee)
      if fee_byte != 'N/A':
         lblStr += " (%s sat/B)" % fee_byte
      
      self.lblButtonFee.setText(lblStr)
   
   #############################################################################   
   def updateLabelButton(self, reset=False):
      try:
         if reset:
            raise Exception()
         txSize, flatFee, feeByte = self.getCoinSelectionState()      
         self.updateLabelButtonText(txSize, flatFee, feeByte)

      except:
         self.updateLabelButtonText('N/A', 'N/A', 'N/A')
         
   #############################################################################
   def resetLabel(self):
      self.updateLabelButton(True)
   
   #############################################################################
   def getFeeData(self):
      fee = 0
      fee_byte = 0
      
      if self.radioFlatFee.isChecked():
         flatFeeText = str(self.edtFeeAmt.text())
         fee = str2coin(flatFeeText)
      
      elif self.radioFeeByte.isChecked():
         fee_byteText = str(self.edtFeeByte.text())
         fee_byte = float(fee_byteText)
                 
      elif self.radioAutoFeeByte.isChecked():
         fee_byteText = str(self.lblAutoFeeByte.text())
         fee_byte = float(fee_byteText)
         
      adjust_fee = self.checkBoxAdjust.isChecked()
         
      return fee, fee_byte, adjust_fee    
Exemplo n.º 12
0
class FeeSelectionDialog(ArmoryDialog):

    #############################################################################
    def __init__(self, parent, main, cs_callback, get_csstate):
        super(FeeSelectionDialog, self).__init__(parent, main)

        #Button Label
        self.lblButtonFee = QLabelButton("")

        #get default values
        flatFee = self.main.getSettingOrSetDefault("Default_Fee", MIN_TX_FEE)
        flatFee = coin2str(flatFee, maxZeros=1).strip()
        fee_byte = str(
            self.main.getSettingOrSetDefault("Default_FeeByte", MIN_FEE_BYTE))
        blocksToConfirm = self.main.getSettingOrSetDefault(\
           "Default_FeeByte_BlocksToConfirm", NBLOCKS_TO_CONFIRM)
        feeStrategy = str(self.main.getSettingOrSetDefault(\
           "Default_FeeByte_Strategy", FEEBYTE_CONSERVATIVE))

        self.coinSelectionCallback = cs_callback
        self.getCoinSelectionState = get_csstate
        self.validAutoFee = True

        isSmartFee = True
        try:
            feeEstimate, isSmartFee, errorMsg = self.getFeeByteFromNode(
                blocksToConfirm, feeStrategy)
        except:
            feeEstimate = "N/A"
            self.validAutoFee = False

        defaultCheckState = \
           self.main.getSettingOrSetDefault("FeeOption", DEFAULT_FEE_TYPE)

        #flat free
        def setFlatFee():
            def callbck():
                return self.selectType('FlatFee')

            return callbck

        def updateLbl():
            self.updateCoinSelection()

        self.radioFlatFee = QRadioButton(self.tr("Flat Fee (BTC)"))
        self.edtFeeAmt = QLineEdit(flatFee)
        self.edtFeeAmt.setFont(GETFONT('Fixed'))
        self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0])
        self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0])

        self.connect(self.radioFlatFee, SIGNAL('clicked()'), setFlatFee())
        self.connect(self.edtFeeAmt, SIGNAL('textChanged(QString)'), updateLbl)

        frmFlatFee = QFrame()
        frmFlatFee.setFrameStyle(STYLE_RAISED)
        layoutFlatFee = QGridLayout()
        layoutFlatFee.addWidget(self.radioFlatFee, 0, 0, 1, 1)
        layoutFlatFee.addWidget(self.edtFeeAmt, 0, 1, 1, 1)
        frmFlatFee.setLayout(layoutFlatFee)

        #fee/byte
        def setFeeByte():
            def callbck():
                return self.selectType('FeeByte')

            return callbck

        self.radioFeeByte = QRadioButton(self.tr("Fee/Byte (Satoshi/Byte)"))
        self.edtFeeByte = QLineEdit(fee_byte)
        self.edtFeeByte.setFont(GETFONT('Fixed'))
        self.edtFeeByte.setMinimumWidth(tightSizeNChar(self.edtFeeByte, 6)[0])
        self.edtFeeByte.setMaximumWidth(tightSizeNChar(self.edtFeeByte, 12)[0])

        self.connect(self.radioFeeByte, SIGNAL('clicked()'), setFeeByte())
        self.connect(self.edtFeeByte, SIGNAL('textChanged(QString)'),
                     updateLbl)

        frmFeeByte = QFrame()
        frmFeeByte.setFrameStyle(STYLE_RAISED)
        layoutFeeByte = QGridLayout()
        layoutFeeByte.addWidget(self.radioFeeByte, 0, 0, 1, 1)
        layoutFeeByte.addWidget(self.edtFeeByte, 0, 1, 1, 1)
        frmFeeByte.setLayout(layoutFeeByte)

        #auto fee/byte
        if isSmartFee:
            frmAutoFeeByte = self.setupSmartAutoFeeByteUI(\
               feeEstimate, blocksToConfirm, feeStrategy)
        else:
            frmAutoFeeByte = self.setupLegacyAutoFeeByteUI(\
               feeEstimate, blocksToConfirm)

        #adjust and close
        self.btnClose = QPushButton(self.tr('Close'))
        self.connect(self.btnClose, SIGNAL('clicked()'), self.accept)

        self.checkBoxAdjust = QCheckBox(self.tr('Adjust fee/byte for privacy'))
        self.checkBoxAdjust.setChecked(\
           self.main.getSettingOrSetDefault('AdjustFee', True))

        self.connect(self.checkBoxAdjust, SIGNAL('clicked()'), updateLbl)

        frmClose = makeHorizFrame(\
           [self.checkBoxAdjust, 'Stretch', self.btnClose], STYLE_NONE)

        #main layout
        layout = QGridLayout()
        layout.addWidget(frmAutoFeeByte, 0, 0, 1, 4)
        layout.addWidget(frmFeeByte, 2, 0, 1, 4)
        layout.addWidget(frmFlatFee, 4, 0, 1, 4)
        layout.addWidget(frmClose, 5, 0, 1, 4)

        self.setLayout(layout)
        self.setWindowTitle(self.tr('Select Fee Type'))

        self.selectType(defaultCheckState)

        self.setFocus()

    #############################################################################
    def setupLegacyAutoFeeByteUI(self, feeEstimate, blocksToConfirm):
        def setAutoFeeByte():
            def callbck():
                return self.selectType('Auto')

            return callbck

        def updateLbl():
            self.updateCoinSelection()

        def feeByteToStr(feeByte):
            try:
                self.feeByte = feeByte
                return "<u>%.1f</u>" % feeByte
            except:
                self.feeByte = -1
                if isinstance(feeByte, str):
                    return feeByte
                else:
                    return "N/A"

        radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ")
        if not self.validAutoFee:
            radioButtonTxt = self.tr("Failed to fetch fee/byte from node")

        self.radioAutoFeeByte = QRadioButton(radioButtonTxt)
        self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate))
        self.lblAutoFeeByte.setFont(GETFONT('Fixed'))
        self.lblAutoFeeByte.setMinimumWidth(
            tightSizeNChar(self.lblAutoFeeByte, 6)[0])
        self.lblAutoFeeByte.setMaximumWidth(
            tightSizeNChar(self.lblAutoFeeByte, 12)[0])

        self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self)
        self.sliderAutoFeeByte.setMinimum(2)
        self.sliderAutoFeeByte.setMaximum(6)
        self.sliderAutoFeeByte.setValue(blocksToConfirm)
        self.lblSlider = QLabel()

        def getSliderLabelTxt():
            return self.tr("Blocks to confirm: %1").arg(\
               unicode(self.sliderAutoFeeByte.value()))

        def updateAutoFeeByte():
            blocksToConfirm = self.sliderAutoFeeByte.value()
            try:
                feeEstimate, version, err = \
                   self.getFeeByteFromNode(blocksToConfirm, FEEBYTE_CONSERVATIVE)
            except:
                feeEstimate = "N/A"

            self.lblSlider.setText(getSliderLabelTxt())
            self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate))
            updateLbl()

        self.lblSlider.setText(getSliderLabelTxt())

        self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'),
                     setAutoFeeByte())
        self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte)
        self.sliderAutoFeeByte.setEnabled(False)

        frmAutoFeeByte = QFrame()
        frmAutoFeeByte.setFrameStyle(STYLE_RAISED)
        layoutAutoFeeByte = QGridLayout()
        layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 1)
        layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 1, 1, 1)
        layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 2)
        layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 2)
        frmAutoFeeByte.setLayout(layoutAutoFeeByte)

        if not self.validAutoFee:
            frmAutoFeeByte.setEnabled(False)

        return frmAutoFeeByte

    #############################################################################
    def setupSmartAutoFeeByteUI(self, feeEstimate, blocksToConfirm, strat):
        def setAutoFeeByte():
            def callbck():
                return self.selectType('Auto')

            return callbck

        stratList = [FEEBYTE_CONSERVATIVE, FEEBYTE_ECONOMICAL]

        def updateLbl():
            self.updateCoinSelection()

        def getStrategyString():
            try:
                cbIndex = self.comboStrat.currentIndex()
                return stratList[cbIndex]
            except:
                return FEEBYTE_CONSERVATIVE

        def feeByteToStr(feeByte):
            try:
                self.feeByte = feeByte
                return "<u>%.1f</u>" % feeByte
            except:
                self.feeByte = -1
                if isinstance(feeByte, str):
                    return feeByte
                else:
                    return "N/A"

        radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ")
        if not self.validAutoFee:
            radioButtonTxt = self.tr("Failed to fetch fee/byte from node")

        self.radioAutoFeeByte = QRadioButton(radioButtonTxt)
        self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate))
        self.lblAutoFeeByte.setFont(GETFONT('Fixed'))
        self.lblAutoFeeByte.setMinimumWidth(
            tightSizeNChar(self.lblAutoFeeByte, 6)[0])
        self.lblAutoFeeByte.setMaximumWidth(
            tightSizeNChar(self.lblAutoFeeByte, 12)[0])

        self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self)
        self.sliderAutoFeeByte.setMinimum(2)
        self.sliderAutoFeeByte.setMaximum(100)
        self.sliderAutoFeeByte.setValue(blocksToConfirm)
        self.lblSlider = QLabel()

        self.lblStrat = QLabel(self.tr("Profile:"))
        self.ttStart = self.main.createToolTipWidget(
            self.tr('''
         <u>Fee Estimation Profiles:</u><br><br>
         <b>CONSERVATIVE:</b> Short term estimate. More reactive to current 
         changes in the mempool. Use this estimate if you want a high probability 
         of getting your transaction mined quickly. <br><br>
         <b>ECONOMICAL:</b> Long term estimate. Ignores short term changes to the 
         mempool. Use this profile if you want low fees and can tolerate swings 
         in the projected confirmation window. <br><br>

         The estimate profiles may not diverge until your node has gathered 
         enough data from the network to refine its predictions. Refer to the
         \"estimatesmartfee\" section in the Bitcoin Core 0.15 changelog for more
         informations.
         '''))
        self.comboStrat = QComboBox()
        currentIndex = 0
        for i in range(len(stratList)):
            self.comboStrat.addItem(stratList[i])
            if stratList[i] == strat:
                currentIndex = i
        self.comboStrat.setCurrentIndex(currentIndex)

        def getSliderLabelTxt():
            return self.tr("Blocks to confirm: %1").arg(\
                  unicode(self.sliderAutoFeeByte.value()))

        def updateAutoFeeByte():
            blocksToConfirm = self.sliderAutoFeeByte.value()
            strategy = getStrategyString()
            try:
                feeEstimate, version, err = \
                   self.getFeeByteFromNode(blocksToConfirm, strategy)
            except:
                feeEstimate = "N/A"

            self.lblSlider.setText(getSliderLabelTxt())
            self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate))
            updateLbl()

        def stratComboChange():
            updateAutoFeeByte()

        self.lblSlider.setText(getSliderLabelTxt())

        self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'),
                     setAutoFeeByte())
        self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte)
        self.sliderAutoFeeByte.setEnabled(False)

        self.connect(self.comboStrat, SIGNAL('currentIndexChanged(int)'),
                     stratComboChange)

        frmAutoFeeByte = QFrame()
        frmAutoFeeByte.setFrameStyle(STYLE_RAISED)
        layoutAutoFeeByte = QGridLayout()
        layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 2)
        layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 2, 1, 2)
        layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 1)
        layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 4)
        layoutAutoFeeByte.addWidget(self.lblStrat, 3, 0, 1, 1)
        layoutAutoFeeByte.addWidget(self.comboStrat, 3, 1, 1, 2)
        layoutAutoFeeByte.addWidget(self.ttStart, 3, 3, 1, 1)

        frmAutoFeeByte.setLayout(layoutAutoFeeByte)

        if not self.validAutoFee:
            frmAutoFeeByte.setEnabled(False)

        return frmAutoFeeByte

    #############################################################################
    def getFeeByteFromNode(self, blocksToConfirm, strategy):
        try:
            feeEstimateResult = estimateFee(blocksToConfirm, strategy)
            return feeEstimateResult.val_ * 100000, \
               feeEstimateResult.isSmart_, \
               feeEstimateResult.error_
        except:
            self.validAutoFee = False
            return "N/A", False, ""

    #############################################################################
    def selectType(self, strType):
        self.radioFlatFee.setChecked(False)
        self.radioFeeByte.setChecked(False)
        self.radioAutoFeeByte.setChecked(False)
        self.sliderAutoFeeByte.setEnabled(False)

        if strType == 'FlatFee':
            self.radioFlatFee.setChecked(True)
        elif strType == 'FeeByte':
            self.radioFeeByte.setChecked(True)
        elif strType == 'Auto':
            if not self.validAutoFee:
                self.radioFeeByte.setChecked(True)
            else:
                self.radioAutoFeeByte.setChecked(True)
                self.sliderAutoFeeByte.setEnabled(True)

        self.updateCoinSelection()
        self.updateLabelButton()

    #############################################################################
    def updateCoinSelection(self):
        try:
            self.coinSelectionCallback()
        except:
            self.updateLabelButton()

    #############################################################################
    def getLabelButton(self):
        return self.lblButtonFee

    #############################################################################
    def updateLabelButtonText(self, txSize, flatFee, fee_byte):
        txSize = str(txSize)
        if txSize != 'N/A':
            txSize += " B"

        if flatFee != 'N/A':
            flatFee = coin2str(flatFee, maxZeros=0).strip()
            flatFee += " BTC"

        if not isinstance(fee_byte, str):
            fee_byte = '%.2f' % fee_byte

        lblStr = "Size: %s, Fee: %s" % (txSize, flatFee)
        if fee_byte != 'N/A':
            lblStr += " (%s sat/B)" % fee_byte

        self.lblButtonFee.setText(lblStr)

    #############################################################################
    def updateLabelButton(self, reset=False):
        try:
            if reset:
                raise Exception()
            txSize, flatFee, feeByte = self.getCoinSelectionState()
            self.updateLabelButtonText(txSize, flatFee, feeByte)

        except:
            self.updateLabelButtonText('N/A', 'N/A', 'N/A')

    #############################################################################
    def resetLabel(self):
        self.updateLabelButton(True)

    #############################################################################
    def getFeeData(self):
        fee = 0
        fee_byte = 0

        if self.radioFlatFee.isChecked():
            flatFeeText = str(self.edtFeeAmt.text())
            fee = str2coin(flatFeeText)

        elif self.radioFeeByte.isChecked():
            fee_byteText = str(self.edtFeeByte.text())
            fee_byte = float(fee_byteText)

        elif self.radioAutoFeeByte.isChecked():
            fee_byte = self.feeByte

        adjust_fee = self.checkBoxAdjust.isChecked()

        return fee, fee_byte, adjust_fee

    #############################################################################
    def setZeroFee(self):
        self.edtFeeAmt.setText('0')
        self.selectType('FlatFee')
Exemplo n.º 13
0
class EditGeometryProperties(QDialog):
    force = True
    allow_update = True
    def __init__(self, data, win_parent=None):
        """
        +------------------+
        | Edit Actor Props |
        +------------------+------+
        |  Name1                  |
        |  Name2                  |
        |  Name3                  |
        |  Name4                  |
        |                         |
        |  Active_Name    main    |
        |  Color          box     |
        |  Line_Width     2       |
        |  Point_Size     2       |
        |  Bar_Scale      2       |
        |  Opacity        0.5     |
        |  Show/Hide              |
        |                         |
        |    Apply   OK   Cancel  |
        +-------------------------+
        """
        QDialog.__init__(self, win_parent)
        self.setWindowTitle('Edit Geometry Properties')

        #default
        self.win_parent = win_parent
        self.out_data = data

        self.keys = sorted(data.keys())
        self.keys = data.keys()
        keys = self.keys
        nrows = len(keys)
        self.active_key = 'main'#keys[0]

        items = keys

        header_labels = ['Groups']
        table_model = Model(items, header_labels, self)
        view = CustomQTableView(self) #Call your custom QTableView here
        view.setModel(table_model)
        if qt_version == 4:
            view.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)

        self.table = view

        actor_obj = data[self.active_key]
        name = actor_obj.name
        line_width = actor_obj.line_width
        point_size = actor_obj.point_size
        bar_scale = actor_obj.bar_scale
        opacity = actor_obj.opacity
        color = actor_obj.color
        show = actor_obj.is_visible
        self.representation = actor_obj.representation

        # table
        header = self.table.horizontalHeader()
        header.setStretchLastSection(True)

        self._default_is_apply = False
        self.name = QLabel("Name:")
        self.name_edit = QLineEdit(str(name))
        self.name_edit.setDisabled(True)

        self.color = QLabel("Color:")
        self.color_edit = QPushButton()
        #self.color_edit.setFlat(True)

        color = self.out_data[self.active_key].color
        qcolor = QtGui.QColor()
        qcolor.setRgb(*color)
        #print('color =%s' % str(color))
        palette = QtGui.QPalette(self.color_edit.palette()) # make a copy of the palette
        #palette.setColor(QtGui.QPalette.Active, QtGui.QPalette.Base, \
                         #qcolor)
        palette.setColor(QtGui.QPalette.Background, QtGui.QColor('blue'))  # ButtonText
        self.color_edit.setPalette(palette)

        self.color_edit.setStyleSheet("QPushButton {"
                                      "background-color: rgb(%s, %s, %s);" % tuple(color) +
                                      #"border:1px solid rgb(255, 170, 255); "
                                      "}")

        self.use_slider = True
        self.is_opacity_edit_active = False
        self.is_opacity_edit_slider_active = False

        self.is_line_width_edit_active = False
        self.is_line_width_edit_slider_active = False

        self.is_point_size_edit_active = False
        self.is_point_size_edit_slider_active = False

        self.is_bar_scale_edit_active = False
        self.is_bar_scale_edit_slider_active = False

        self.opacity = QLabel("Opacity:")
        self.opacity_edit = QDoubleSpinBox(self)
        self.opacity_edit.setRange(0.1, 1.0)
        self.opacity_edit.setDecimals(1)
        self.opacity_edit.setSingleStep(0.1)
        self.opacity_edit.setValue(opacity)
        if self.use_slider:
            self.opacity_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.opacity_slider_edit.setRange(1, 10)
            self.opacity_slider_edit.setValue(opacity * 10)
            self.opacity_slider_edit.setTickInterval(1)
            self.opacity_slider_edit.setTickPosition(QSlider.TicksBelow)

        self.line_width = QLabel("Line Width:")
        self.line_width_edit = QSpinBox(self)
        self.line_width_edit.setRange(1, 15)
        self.line_width_edit.setSingleStep(1)
        self.line_width_edit.setValue(line_width)
        if self.use_slider:
            self.line_width_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.line_width_slider_edit.setRange(1, 15)
            self.line_width_slider_edit.setValue(line_width)
            self.line_width_slider_edit.setTickInterval(1)
            self.line_width_slider_edit.setTickPosition(QSlider.TicksBelow)

        if self.representation in ['point', 'surface']:
            self.line_width.setEnabled(False)
            self.line_width_edit.setEnabled(False)
            self.line_width_slider_edit.setEnabled(False)

        self.point_size = QLabel("Point Size:")
        self.point_size_edit = QSpinBox(self)
        self.point_size_edit.setRange(1, 15)
        self.point_size_edit.setSingleStep(1)
        self.point_size_edit.setValue(point_size)
        self.point_size.setVisible(False)
        self.point_size_edit.setVisible(False)
        if self.use_slider:
            self.point_size_slider_edit = QSlider(QtCore.Qt.Horizontal)
            self.point_size_slider_edit.setRange(1, 15)
            self.point_size_slider_edit.setValue(point_size)
            self.point_size_slider_edit.setTickInterval(1)
            self.point_size_slider_edit.setTickPosition(QSlider.TicksBelow)
            self.point_size_slider_edit.setVisible(False)

        if self.representation in ['wire', 'surface']:
            self.point_size.setEnabled(False)
            self.point_size_edit.setEnabled(False)
            if self.use_slider:
                self.point_size_slider_edit.setEnabled(False)

        self.bar_scale = QLabel("Bar Scale:")
        self.bar_scale_edit = QDoubleSpinBox(self)
        #self.bar_scale_edit.setRange(0.01, 1.0)  # was 0.1
        #self.bar_scale_edit.setRange(0.05, 5.0)
        self.bar_scale_edit.setDecimals(1)
        #self.bar_scale_edit.setSingleStep(bar_scale / 10.)
        self.bar_scale_edit.setSingleStep(0.1)
        self.bar_scale_edit.setValue(bar_scale)

        #if self.use_slider:
            #self.bar_scale_slider_edit = QSlider(QtCore.Qt.Horizontal)
            #self.bar_scale_slider_edit.setRange(1, 100)  # 1/0.05 = 100/5.0
            #self.bar_scale_slider_edit.setValue(opacity * 0.05)
            #self.bar_scale_slider_edit.setTickInterval(10)
            #self.bar_scale_slider_edit.setTickPosition(QSlider.TicksBelow)

        if self.representation != 'bar':
            self.bar_scale.setEnabled(False)
            self.bar_scale_edit.setEnabled(False)
            self.bar_scale.setVisible(False)
            self.bar_scale_edit.setVisible(False)
            #self.bar_scale_slider_edit.setVisible(False)
            #self.bar_scale_slider_edit.setEnabled(False)

        # show/hide
        self.checkbox_show = QCheckBox("Show")
        self.checkbox_hide = QCheckBox("Hide")
        self.checkbox_show.setChecked(show)
        self.checkbox_hide.setChecked(not show)

        if name == 'main':
            self.color.setEnabled(False)
            self.color_edit.setEnabled(False)
            self.point_size.setEnabled(False)
            self.point_size_edit.setEnabled(False)
            if self.use_slider:
                self.point_size_slider_edit.setEnabled(False)


        # closing
        # self.apply_button = QPushButton("Apply")
        #if self._default_is_apply:
            #self.apply_button.setDisabled(True)

        # self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Close")

        self.create_layout()
        self.set_connections()

    def on_update_geometry_properties_window(self, data):
        """Not Implemented"""
        return
        new_keys = sorted(data.keys())
        if self.active_key in new_keys:
            i = new_keys.index(self.active_key)
        else:
            i = 0
        self.table.update_data(new_keys)
        self.out_data = data
        self.update_active_key(i)

    def update_active_key(self, index):
        """
        Parameters
        ----------
        index : PyQt4.QtCore.QModelIndex
            the index of the list

        Internal Parameters
        -------------------
        name : str
            the name of obj
        obj : CoordProperties, AltGeometry
            the storage object for things like line_width, point_size, etc.
        """
        old_obj = self.out_data[self.active_key]
        old_obj.line_width = self.line_width_edit.value()
        old_obj.point_size = self.point_size_edit.value()
        old_obj.bar_scale = self.bar_scale_edit.value()
        old_obj.opacity = self.opacity_edit.value()
        old_obj.is_visible = self.checkbox_show.isChecked()

        if qt_version == 4:
            name = str(index.data().toString())
        else:
            name = str(index.data())
            print('name = %r' % name)
        #i = self.keys.index(self.active_key)

        self.active_key = name
        self.name_edit.setText(name)
        obj = self.out_data[name]
        if isinstance(obj, CoordProperties):
            opacity = 1.0
            representation = 'coord'
            is_visible = obj.is_visible
        elif isinstance(obj, AltGeometry):
            line_width = obj.line_width
            point_size = obj.point_size
            bar_scale = obj.bar_scale
            opacity = obj.opacity
            representation = obj.representation
            is_visible = obj.is_visible

            self.color_edit.setStyleSheet("QPushButton {"
                                          "background-color: rgb(%s, %s, %s);" % tuple(obj.color) +
                                          #"border:1px solid rgb(255, 170, 255); "
                                          "}")
            self.allow_update = False
            self.force = False
            self.line_width_edit.setValue(line_width)
            self.point_size_edit.setValue(point_size)
            self.bar_scale_edit.setValue(bar_scale)
            self.force = True
            self.allow_update = True
        else:
            raise NotImplementedError(obj)

        allowed_representations = [
            'main', 'surface', 'coord', 'toggle', 'wire', 'point', 'bar']

        if self.representation != representation:
            self.representation = representation
            if representation not in allowed_representations:
                msg = 'name=%r; representation=%r is invalid\nrepresentations=%r' % (
                    name, representation, allowed_representations)

            if self.representation == 'coord':
                self.color.setVisible(False)
                self.color_edit.setVisible(False)
                self.line_width.setVisible(False)
                self.line_width_edit.setVisible(False)
                self.point_size.setVisible(False)
                self.point_size_edit.setVisible(False)
                self.bar_scale.setVisible(False)
                self.bar_scale_edit.setVisible(False)
                self.opacity.setVisible(False)
                self.opacity_edit.setVisible(False)
                if self.use_slider:
                    self.opacity_slider_edit.setVisible(False)
                    self.point_size_slider_edit.setVisible(False)
                    self.line_width_slider_edit.setVisible(False)
                    #self.bar_scale_slider_edit.setVisible(False)
            else:
                self.color.setVisible(True)
                self.color_edit.setVisible(True)
                self.line_width.setVisible(True)
                self.line_width_edit.setVisible(True)
                self.point_size.setVisible(True)
                self.point_size_edit.setVisible(True)
                self.bar_scale.setVisible(True)
                #self.bar_scale_edit.setVisible(True)
                self.opacity.setVisible(True)
                self.opacity_edit.setVisible(True)
                if self.use_slider:
                    self.opacity_slider_edit.setVisible(True)
                    self.line_width_slider_edit.setVisible(True)
                    self.point_size_slider_edit.setVisible(True)
                    #self.bar_scale_slider_edit.setVisible(True)

                if name == 'main':
                    self.color.setEnabled(False)
                    self.color_edit.setEnabled(False)
                    self.point_size.setEnabled(False)
                    self.point_size_edit.setEnabled(False)
                    self.line_width.setEnabled(True)
                    self.line_width_edit.setEnabled(True)
                    self.bar_scale.setEnabled(False)
                    self.bar_scale_edit.setEnabled(False)
                    show_points = False
                    show_line_width = True
                    show_bar_scale = False
                    if self.use_slider:
                        self.line_width_slider_edit.setEnabled(True)
                        #self.bar_scale_slider_edit.setVisible(False)
                else:
                    self.color.setEnabled(True)
                    self.color_edit.setEnabled(True)

                    show_points = False
                    if self.representation in ['point', 'wire+point']:
                        show_points = True

                    show_line_width = False
                    if self.representation in ['wire', 'wire+point', 'bar']:
                        show_line_width = True

                    if representation == 'bar':
                        show_bar_scale = True
                    else:
                        show_bar_scale = False
                    #self.bar_scale_button.setVisible(show_bar_scale)
                    #self.bar_scale_edit.setSingleStep(bar_scale / 10.)
                    #if self.use_slider:
                        #self.bar_scale_slider_edit.setEnabled(False)

                self.point_size.setEnabled(show_points)
                self.point_size_edit.setEnabled(show_points)
                self.point_size.setVisible(show_points)
                self.point_size_edit.setVisible(show_points)

                self.line_width.setEnabled(show_line_width)
                self.line_width_edit.setEnabled(show_line_width)

                self.bar_scale.setEnabled(show_bar_scale)
                self.bar_scale_edit.setEnabled(show_bar_scale)
                self.bar_scale.setVisible(show_bar_scale)
                self.bar_scale_edit.setVisible(show_bar_scale)
                if self.use_slider:
                    self.point_size_slider_edit.setEnabled(show_points)
                    self.point_size_slider_edit.setVisible(show_points)
                    self.line_width_slider_edit.setEnabled(show_line_width)


            #if self.representation in ['wire', 'surface']:

        self.opacity_edit.setValue(opacity)
        #if self.use_slider:
            #self.opacity_slider_edit.setValue(opacity*10)
        self.checkbox_show.setChecked(is_visible)
        self.checkbox_hide.setChecked(not is_visible)

        passed = self.on_validate()
        #self.on_apply(force=True)  # TODO: was turned on...do I want this???
        #self.allow_update = True

    #def on_name_select(self):
        #print('on_name_select')
        #return

    def create_layout(self):
        ok_cancel_box = QHBoxLayout()
        # ok_cancel_box.addWidget(self.apply_button)
        # ok_cancel_box.addWidget(self.ok_button)
        ok_cancel_box.addWidget(self.cancel_button)

        grid = QGridLayout()

        irow = 0
        grid.addWidget(self.name, irow, 0)
        grid.addWidget(self.name_edit, irow, 1)
        irow += 1

        grid.addWidget(self.color, irow, 0)
        grid.addWidget(self.color_edit, irow, 1)
        irow += 1

        grid.addWidget(self.opacity, irow, 0)
        if self.use_slider:
            grid.addWidget(self.opacity_edit, irow, 2)
            grid.addWidget(self.opacity_slider_edit, irow, 1)
        else:
            grid.addWidget(self.opacity_edit, irow, 1)
        irow += 1

        grid.addWidget(self.line_width, irow, 0)
        if self.use_slider:
            grid.addWidget(self.line_width_edit, irow, 2)
            grid.addWidget(self.line_width_slider_edit, irow, 1)
        else:
            grid.addWidget(self.line_width_edit, irow, 1)
        irow += 1

        grid.addWidget(self.point_size, irow, 0)
        if self.use_slider:
            grid.addWidget(self.point_size_edit, irow, 2)
            grid.addWidget(self.point_size_slider_edit, irow, 1)
        else:
            grid.addWidget(self.point_size_edit, irow, 1)
        irow += 1

        grid.addWidget(self.bar_scale, irow, 0)
        if self.use_slider and 0:
            grid.addWidget(self.bar_scale_edit, irow, 2)
            grid.addWidget(self.bar_scale_slider_edit, irow, 1)
        else:
            grid.addWidget(self.bar_scale_edit, irow, 1)
        irow += 1

        checkboxs = QButtonGroup(self)
        checkboxs.addButton(self.checkbox_show)
        checkboxs.addButton(self.checkbox_hide)

        vbox = QVBoxLayout()
        vbox.addWidget(self.table)
        vbox.addLayout(grid)

        if 0:
            vbox.addWidget(self.checkbox_show)
            vbox.addWidget(self.checkbox_hide)
        else:
            vbox1 = QVBoxLayout()
            vbox1.addWidget(self.checkbox_show)
            vbox1.addWidget(self.checkbox_hide)
            vbox.addLayout(vbox1)

        vbox.addStretch()
        #vbox.addWidget(self.check_apply)
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)

    def set_connections(self):
        # self.opacity_edit.connect(arg0, QObject, arg1)
        if qt_version == 4:
            self.connect(self.opacity_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity)
                #self.connect(self.opacity_slider_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_opacity)
                #grid.addWidget(self.opacity_slider_edit, irow, 1)

            # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width)
            # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size)

            # self.connect(self.line_width, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_line_width)
            # self.connect(self.point_size, QtCore.SIGNAL('valueChanged(const QString&)'), self.on_point_size)
            self.connect(self.line_width_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_line_width)
            self.connect(self.point_size_edit, QtCore.SIGNAL('valueChanged(int)'), self.on_point_size)
            self.connect(self.bar_scale_edit, QtCore.SIGNAL('valueChanged(double)'), self.on_bar_scale)
        else:
            self.opacity_edit.valueChanged.connect(self.on_opacity)
            self.line_width_edit.valueChanged.connect(self.on_line_width)
            self.point_size_edit.valueChanged.connect(self.on_point_size)
            self.bar_scale_edit.valueChanged.connect(self.on_bar_scale)

        if self.use_slider:
            self.opacity_slider_edit.valueChanged.connect(self.on_opacity_slider)
            self.line_width_slider_edit.valueChanged.connect(self.on_line_width_slider)
            self.point_size_slider_edit.valueChanged.connect(self.on_point_size_slider)
            #self.bar_scale_slider_edit.valueChanged.connect(self.on_bar_scale_slider)



        # self.connect(self.opacity_edit, QtCore.SIGNAL('clicked()'), self.on_opacity)
        # self.connect(self.line_width, QtCore.SIGNAL('clicked()'), self.on_line_width)
        # self.connect(self.point_size, QtCore.SIGNAL('clicked()'), self.on_point_size)

        if qt_version == 4:
            self.connect(self.color_edit, QtCore.SIGNAL('clicked()'), self.on_color)
            self.connect(self.checkbox_show, QtCore.SIGNAL('clicked()'), self.on_show)
            self.connect(self.checkbox_hide, QtCore.SIGNAL('clicked()'), self.on_hide)
            #self.connect(self.check_apply, QtCore.SIGNAL('clicked()'), self.on_check_apply)

            # self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply)
            # self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok)
            self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel)
            self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
        else:
            self.color_edit.clicked.connect(self.on_color)
            self.checkbox_show.clicked.connect(self.on_show)
            self.checkbox_hide.clicked.connect(self.on_hide)
            self.cancel_button.clicked.connect(self.on_cancel)
            # closeEvent

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.close()

    def closeEvent(self, event):
        self.on_cancel()

    def on_color(self):
        name = self.active_key
        obj = self.out_data[name]
        rgb_color_ints = obj.color

        msg = name
        col = QtGui.QColorDialog.getColor(QtGui.QColor(*rgb_color_ints), self, "Choose a %s color" % msg)
        if col.isValid():
            color = col.getRgbF()[:3]
            obj.color = color
            #print('new_color =', color)
            self.color_edit.setStyleSheet("QPushButton {"
                                          "background-color: rgb(%s, %s, %s);" % tuple(obj.color) +
                                          #"border:1px solid rgb(255, 170, 255); "
                                          "}")
        self.on_apply(force=self.force)

    def on_show(self):
        name = self.active_key
        is_checked = self.checkbox_show.isChecked()
        self.out_data[name].is_visible = is_checked
        self.on_apply(force=self.force)

    def on_hide(self):
        name = self.active_key
        is_checked = self.checkbox_hide.isChecked()
        self.out_data[name].is_visible = not is_checked
        self.on_apply(force=self.force)

    def on_line_width(self):
        self.is_line_width_edit_active = True
        name = self.active_key
        line_width = self.line_width_edit.value()
        self.out_data[name].line_width = line_width
        if not self.is_line_width_edit_slider_active:
            if self.use_slider:
                self.line_width_slider_edit.setValue(line_width)
            self.is_line_width_edit_active = False
        self.on_apply(force=self.force)
        self.is_line_width_edit_active = False

    def on_line_width_slider(self):
        self.is_line_width_edit_slider_active = True
        name = self.active_key
        line_width = self.line_width_slider_edit.value()
        if not self.is_line_width_edit_active:
            self.line_width_edit.setValue(line_width)
        self.is_line_width_edit_slider_active = False

    def on_point_size(self):
        self.is_point_size_edit_active = True
        name = self.active_key
        point_size = self.point_size_edit.value()
        self.out_data[name].point_size = point_size
        if not self.is_point_size_edit_slider_active:
            if self.use_slider:
                self.point_size_slider_edit.setValue(point_size)
            self.is_point_size_edit_active = False
        self.on_apply(force=self.force)
        self.is_point_size_edit_active = False

    def on_point_size_slider(self):
        self.is_point_size_edit_slider_active = True
        name = self.active_key
        point_size = self.point_size_slider_edit.value()
        if not self.is_point_size_edit_active:
            self.point_size_edit.setValue(point_size)
        self.is_point_size_edit_slider_active = False

    def on_bar_scale(self):
        self.is_bar_scale_edit_active = True
        name = self.active_key
        float_bar_scale = self.bar_scale_edit.value()
        self.out_data[name].bar_scale = float_bar_scale
        if not self.is_bar_scale_edit_slider_active:
            int_bar_scale = int(round(float_bar_scale * 20, 0))
            #if self.use_slider:
                #self.bar_scale_slider_edit.setValue(int_bar_scale)
            self.is_bar_scale_edit_active = False
        self.on_apply(force=self.force)
        self.is_bar_scale_edit_active = False

    def on_bar_scale_slider(self):
        self.is_bar_scale_edit_slider_active = True
        name = self.active_key
        int_bar_scale = self.bar_scale_slider_edit.value()
        if not self.is_bar_scale_edit_active:
            float_bar_scale = int_bar_scale / 20.
            self.bar_scale_edit.setValue(float_bar_scale)
        self.is_bar_scale_edit_slider_active = False

    def on_opacity(self):
        self.is_opacity_edit_active = True
        name = self.active_key
        float_opacity = self.opacity_edit.value()
        self.out_data[name].opacity = float_opacity
        if not self.is_opacity_edit_slider_active:
            int_opacity = int(round(float_opacity * 10, 0))
            if self.use_slider:
                self.opacity_slider_edit.setValue(int_opacity)
            self.is_opacity_edit_active = False
        self.on_apply(force=self.force)
        self.is_opacity_edit_active = False

    def on_opacity_slider(self):
        self.is_opacity_edit_slider_active = True
        name = self.active_key
        int_opacity = self.opacity_slider_edit.value()
        if not self.is_opacity_edit_active:
            float_opacity = int_opacity / 10.
            self.opacity_edit.setValue(float_opacity)
        self.is_opacity_edit_slider_active = False

    #def on_axis(self, text):
        ##print(self.combo_axis.itemText())
        #self._axis = str(text)
        #self.plane.setText('Point on %s? Plane:' % self._axis)
        #self.point_a.setText('Point on %s Axis:' % self._axis)
        #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane))

    #def on_plane(self, text):
        #self._plane = str(text)
        #self.point_b.setText('Point on %s%s Plane:' % (self._axis, self._plane))

    def on_check_apply(self):
        is_checked = self.check_apply.isChecked()
        self.apply_button.setDisabled(is_checked)

    def _on_float(self, field):
        try:
            eval_float_from_string(field.text())
            field.setStyleSheet("QLineEdit{background: white;}")
        except ValueError:
            field.setStyleSheet("QLineEdit{background: red;}")

    #def on_default_name(self):
        #self.name_edit.setText(str(self._default_name))
        #self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    #def check_float(self, cell):
        #text = cell.text()
        #try:
            #value = eval_float_from_string(text)
            #cell.setStyleSheet("QLineEdit{background: white;}")
            #return value, True
        #except ValueError:
            #cell.setStyleSheet("QLineEdit{background: red;}")
            #return None, False

    #def check_name(self, cell):
        #text = str(cell.text()).strip()
        #if len(text):
            #cell.setStyleSheet("QLineEdit{background: white;}")
            #return text, True
        #else:
            #cell.setStyleSheet("QLineEdit{background: red;}")
            #return None, False

    def on_validate(self):
        self.out_data['clicked_ok'] = True
        self.out_data['clicked_cancel'] = False

        old_obj = self.out_data[self.active_key]
        old_obj.line_width = self.line_width_edit.value()
        old_obj.point_size = self.point_size_edit.value()
        old_obj.bar_scale = self.bar_scale_edit.value()
        old_obj.opacity = self.opacity_edit.value()
        old_obj.is_visible = self.checkbox_show.isChecked()
        return True
        #name_value, flag0 = self.check_name(self.name_edit)
        #ox_value, flag1 = self.check_float(self.transparency_edit)
        #if flag0 and flag1:
            #self.out_data['clicked_ok'] = True
            #return True
        #return False

    def on_apply(self, force=False):
        passed = self.on_validate()
        if (passed or force) and self.allow_update:
            self.win_parent.on_update_geometry_properties(self.out_data)
        return passed

    def on_cancel(self):
        passed = self.on_apply(force=True)
        if passed:
            self.close()
Exemplo n.º 14
0
class FeeSelectionDialog(ArmoryDialog):
   
   #############################################################################
   def __init__(self, parent, main, cs_callback, get_csstate):
      super(FeeSelectionDialog, self).__init__(parent, main)
      
      #Button Label
      self.lblButtonFee = QLabelButton("")
      
      #get default values
      flatFee = self.main.getSettingOrSetDefault("Default_Fee", MIN_TX_FEE)
      flatFee = coin2str(flatFee, maxZeros=1).strip()
      fee_byte = str(self.main.getSettingOrSetDefault("Default_FeeByte", MIN_FEE_BYTE))
      blocksToConfirm = self.main.getSettingOrSetDefault(\
         "Default_FeeByte_BlocksToConfirm", NBLOCKS_TO_CONFIRM)
      feeStrategy = str(self.main.getSettingOrSetDefault(\
         "Default_FeeByte_Strategy", FEEBYTE_CONSERVATIVE))
      
      self.coinSelectionCallback = cs_callback
      self.getCoinSelectionState = get_csstate
      self.validAutoFee = True

      isSmartFee = True
      try:
         feeEstimate, isSmartFee, errorMsg = self.getFeeByteFromNode(blocksToConfirm, feeStrategy)
      except:
         feeEstimate = "N/A"
         self.validAutoFee = False
         
      defaultCheckState = \
         self.main.getSettingOrSetDefault("FeeOption", DEFAULT_FEE_TYPE)
      
      #flat free
      def setFlatFee():
         def callbck():
            return self.selectType('FlatFee')
         return callbck
      
      def updateLbl():
         self.updateCoinSelection()
      
      self.radioFlatFee = QRadioButton(self.tr("Flat Fee (BTC)"))
      self.edtFeeAmt = QLineEdit(flatFee)
      self.edtFeeAmt.setFont(GETFONT('Fixed'))
      self.edtFeeAmt.setMinimumWidth(tightSizeNChar(self.edtFeeAmt, 6)[0])
      self.edtFeeAmt.setMaximumWidth(tightSizeNChar(self.edtFeeAmt, 12)[0])
      
      self.connect(self.radioFlatFee, SIGNAL('clicked()'), setFlatFee())
      self.connect(self.edtFeeAmt, SIGNAL('textChanged(QString)'), updateLbl)
      
      frmFlatFee = QFrame()
      frmFlatFee.setFrameStyle(STYLE_RAISED)
      layoutFlatFee = QGridLayout()
      layoutFlatFee.addWidget(self.radioFlatFee, 0, 0, 1, 1)
      layoutFlatFee.addWidget(self.edtFeeAmt, 0, 1, 1, 1)
      frmFlatFee.setLayout(layoutFlatFee)
      
      #fee/byte
      def setFeeByte():
         def callbck():
            return self.selectType('FeeByte')
         return callbck
      
      self.radioFeeByte = QRadioButton(self.tr("Fee/Byte (Satoshi/Byte)"))
      self.edtFeeByte = QLineEdit(fee_byte)
      self.edtFeeByte.setFont(GETFONT('Fixed'))
      self.edtFeeByte.setMinimumWidth(tightSizeNChar(self.edtFeeByte, 6)[0])
      self.edtFeeByte.setMaximumWidth(tightSizeNChar(self.edtFeeByte, 12)[0])
      
      self.connect(self.radioFeeByte, SIGNAL('clicked()'), setFeeByte())
      self.connect(self.edtFeeByte, SIGNAL('textChanged(QString)'), updateLbl)
            
      frmFeeByte = QFrame()
      frmFeeByte.setFrameStyle(STYLE_RAISED)
      layoutFeeByte = QGridLayout()
      layoutFeeByte.addWidget(self.radioFeeByte, 0, 0, 1, 1)
      layoutFeeByte.addWidget(self.edtFeeByte, 0, 1, 1, 1)
      frmFeeByte.setLayout(layoutFeeByte)
      
      #auto fee/byte
      if isSmartFee:
         frmAutoFeeByte = self.setupSmartAutoFeeByteUI(\
            feeEstimate, blocksToConfirm, feeStrategy)
      else:
         frmAutoFeeByte = self.setupLegacyAutoFeeByteUI(\
            feeEstimate, blocksToConfirm)
      
      #adjust and close
      self.btnClose = QPushButton(self.tr('Close'))
      self.connect(self.btnClose, SIGNAL('clicked()'), self.accept)
      
      self.checkBoxAdjust = QCheckBox(self.tr('Adjust fee/byte for privacy'))
      self.checkBoxAdjust.setChecked(\
         self.main.getSettingOrSetDefault('AdjustFee', True))
            
      self.connect(self.checkBoxAdjust, SIGNAL('clicked()'), updateLbl)
      
      frmClose = makeHorizFrame(\
         [self.checkBoxAdjust, 'Stretch', self.btnClose], STYLE_NONE)
      
      #main layout
      layout = QGridLayout()
      layout.addWidget(frmAutoFeeByte, 0, 0, 1, 4)
      layout.addWidget(frmFeeByte, 2, 0, 1, 4)
      layout.addWidget(frmFlatFee, 4, 0, 1, 4)
      layout.addWidget(frmClose, 5, 0, 1, 4)
      
      self.setLayout(layout)      
      self.setWindowTitle(self.tr('Select Fee Type'))
      
      self.selectType(defaultCheckState)

      self.setFocus()  

   #############################################################################   
   def setupLegacyAutoFeeByteUI(self, feeEstimate, blocksToConfirm):
      def setAutoFeeByte():
         def callbck():
            return self.selectType('Auto')
         return callbck      
 
      def updateLbl():
         self.updateCoinSelection()

      def feeByteToStr(feeByte):
         try:
            self.feeByte = feeByte
            return "<u>%.1f</u>" % feeByte
         except:
            self.feeByte = -1
            if isinstance(feeByte, str):
               return feeByte
            else:
               return "N/A"

      radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ")
      if not self.validAutoFee:      
         radioButtonTxt = self.tr("Failed to fetch fee/byte from node")
         
      self.radioAutoFeeByte = QRadioButton(radioButtonTxt)
      self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate))
      self.lblAutoFeeByte.setFont(GETFONT('Fixed'))
      self.lblAutoFeeByte.setMinimumWidth(tightSizeNChar(self.lblAutoFeeByte, 6)[0])
      self.lblAutoFeeByte.setMaximumWidth(tightSizeNChar(self.lblAutoFeeByte, 12)[0])
      
      self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self)
      self.sliderAutoFeeByte.setMinimum(2)
      self.sliderAutoFeeByte.setMaximum(6)
      self.sliderAutoFeeByte.setValue(blocksToConfirm)
      self.lblSlider = QLabel()
      
      def getSliderLabelTxt():
         return self.tr("Blocks to confirm: %1").arg(\
            unicode(self.sliderAutoFeeByte.value()))
         
      def updateAutoFeeByte():
         blocksToConfirm = self.sliderAutoFeeByte.value()
         try:
            feeEstimate, version, err = \
               self.getFeeByteFromNode(blocksToConfirm, FEEBYTE_CONSERVATIVE)
         except:
            feeEstimate = "N/A"
         
         self.lblSlider.setText(getSliderLabelTxt())         
         self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate))
         updateLbl()
         
      self.lblSlider.setText(getSliderLabelTxt())
      
      self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte())
      self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte)
      self.sliderAutoFeeByte.setEnabled(False)
            
      frmAutoFeeByte = QFrame()
      frmAutoFeeByte.setFrameStyle(STYLE_RAISED)
      layoutAutoFeeByte = QGridLayout()
      layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 1)
      layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 1, 1, 1)  
      layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 2)
      layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 2)
      frmAutoFeeByte.setLayout(layoutAutoFeeByte)
      
      if not self.validAutoFee:
         frmAutoFeeByte.setEnabled(False)

      return frmAutoFeeByte

   #############################################################################   
   def setupSmartAutoFeeByteUI(self, feeEstimate, blocksToConfirm, strat):
      def setAutoFeeByte():
         def callbck():
            return self.selectType('Auto')
         return callbck      
               
      stratList = [FEEBYTE_CONSERVATIVE, FEEBYTE_ECONOMICAL]

      def updateLbl():
         self.updateCoinSelection()

      def getStrategyString():
         try:
            cbIndex = self.comboStrat.currentIndex()
            return stratList[cbIndex]
         except:
            return FEEBYTE_CONSERVATIVE

      def feeByteToStr(feeByte):
         try:
            self.feeByte = feeByte
            return "<u>%.1f</u>" % feeByte
         except:
            self.feeByte = -1
            if isinstance(feeByte, str):
               return feeByte
            else:
               return "N/A"
      
      radioButtonTxt = self.tr("Fee rate from node (sat/Byte): ")
      if not self.validAutoFee:      
         radioButtonTxt = self.tr("Failed to fetch fee/byte from node")
         
      self.radioAutoFeeByte = QRadioButton(radioButtonTxt)
      self.lblAutoFeeByte = QLabel(feeByteToStr(feeEstimate))
      self.lblAutoFeeByte.setFont(GETFONT('Fixed'))
      self.lblAutoFeeByte.setMinimumWidth(tightSizeNChar(self.lblAutoFeeByte, 6)[0])
      self.lblAutoFeeByte.setMaximumWidth(tightSizeNChar(self.lblAutoFeeByte, 12)[0])
      
      self.sliderAutoFeeByte = QSlider(Qt.Horizontal, self)
      self.sliderAutoFeeByte.setMinimum(2)
      self.sliderAutoFeeByte.setMaximum(100)
      self.sliderAutoFeeByte.setValue(blocksToConfirm)
      self.lblSlider = QLabel()

      self.lblStrat = QLabel(self.tr("Profile:"))
      self.ttStart = self.main.createToolTipWidget(self.tr(
         '''
         <u>Fee Estimation Profiles:</u><br><br>
         <b>CONSERVATIVE:</b> Short term estimate. More reactive to current 
         changes in the mempool. Use this estimate if you want a high probability 
         of getting your transaction mined quickly. <br><br>
         <b>ECONOMICAL:</b> Long term estimate. Ignores short term changes to the 
         mempool. Use this profile if you want low fees and can tolerate swings 
         in the projected confirmation window. <br><br>

         The estimate profiles may not diverge until your node has gathered 
         enough data from the network to refine its predictions. Refer to the
         \"estimatesmartfee\" section in the Bitcoin Core 0.15 changelog for more
         informations.
         '''))
      self.comboStrat = QComboBox()
      currentIndex = 0
      for i in range(len(stratList)):
         self.comboStrat.addItem(stratList[i])
         if stratList[i] == strat:
            currentIndex = i
      self.comboStrat.setCurrentIndex(currentIndex)

      def getSliderLabelTxt():
         return self.tr("Blocks to confirm: %1").arg(\
               unicode(self.sliderAutoFeeByte.value()))
         
      def updateAutoFeeByte():
         blocksToConfirm = self.sliderAutoFeeByte.value()
         strategy = getStrategyString()
         try:
            feeEstimate, version, err = \
               self.getFeeByteFromNode(blocksToConfirm, strategy)
         except:
            feeEstimate = "N/A"
         
         self.lblSlider.setText(getSliderLabelTxt())         
         self.lblAutoFeeByte.setText(feeByteToStr(feeEstimate))
         updateLbl()

      def stratComboChange():
         updateAutoFeeByte()

      self.lblSlider.setText(getSliderLabelTxt())
     
      self.connect(self.radioAutoFeeByte, SIGNAL('clicked()'), setAutoFeeByte())
      self.sliderAutoFeeByte.valueChanged.connect(updateAutoFeeByte)
      self.sliderAutoFeeByte.setEnabled(False)

      self.connect(self.comboStrat, SIGNAL('currentIndexChanged(int)'), stratComboChange)
            
      frmAutoFeeByte = QFrame()
      frmAutoFeeByte.setFrameStyle(STYLE_RAISED)
      layoutAutoFeeByte = QGridLayout()
      layoutAutoFeeByte.addWidget(self.radioAutoFeeByte, 0, 0, 1, 2)
      layoutAutoFeeByte.addWidget(self.lblAutoFeeByte, 0, 2, 1, 2)  
      layoutAutoFeeByte.addWidget(self.lblSlider, 1, 0, 1, 1)
      layoutAutoFeeByte.addWidget(self.sliderAutoFeeByte, 2, 0, 1, 4)
      layoutAutoFeeByte.addWidget(self.lblStrat, 3, 0, 1, 1)
      layoutAutoFeeByte.addWidget(self.comboStrat, 3, 1, 1, 2)
      layoutAutoFeeByte.addWidget(self.ttStart, 3, 3, 1, 1)

      frmAutoFeeByte.setLayout(layoutAutoFeeByte)
      
      if not self.validAutoFee:
         frmAutoFeeByte.setEnabled(False)

      return frmAutoFeeByte

   #############################################################################   
   def getFeeByteFromNode(self, blocksToConfirm, strategy):
      try:
         feeEstimateResult = estimateFee(blocksToConfirm, strategy)
         return feeEstimateResult.val_ * 100000, \
            feeEstimateResult.isSmart_, \
            feeEstimateResult.error_
      except:
         self.validAutoFee = False
         return "N/A", False, ""

   #############################################################################   
   def selectType(self, strType):
      self.radioFlatFee.setChecked(False)
      self.radioFeeByte.setChecked(False)
      self.radioAutoFeeByte.setChecked(False)
      self.sliderAutoFeeByte.setEnabled(False)
      
      if strType == 'FlatFee':
         self.radioFlatFee.setChecked(True)
      elif strType == 'FeeByte':
         self.radioFeeByte.setChecked(True)
      elif strType == 'Auto':
         if not self.validAutoFee:
            self.radioFeeByte.setChecked(True)
         else:
            self.radioAutoFeeByte.setChecked(True)
            self.sliderAutoFeeByte.setEnabled(True)
            
      self.updateCoinSelection()
      self.updateLabelButton()
      
   #############################################################################
   def updateCoinSelection(self):
      try:
         self.coinSelectionCallback()
      except:
         self.updateLabelButton()
   
   #############################################################################   
   def getLabelButton(self):
      return self.lblButtonFee
   
   #############################################################################
   def updateLabelButtonText(self, txSize, flatFee, fee_byte):
      txSize = str(txSize)
      if txSize != 'N/A':
         txSize += " B"
      
      if flatFee != 'N/A':
         flatFee = coin2str(flatFee, maxZeros=0).strip()
         flatFee += " BTC"   
      
      if not isinstance(fee_byte, str):   
         fee_byte = '%.2f' % fee_byte 
      
      lblStr = "Size: %s, Fee: %s" % (txSize, flatFee)
      if fee_byte != 'N/A':
         lblStr += " (%s sat/B)" % fee_byte
      
      self.lblButtonFee.setText(lblStr)
   
   #############################################################################   
   def updateLabelButton(self, reset=False):
      try:
         if reset:
            raise Exception()
         txSize, flatFee, feeByte = self.getCoinSelectionState()      
         self.updateLabelButtonText(txSize, flatFee, feeByte)

      except:
         self.updateLabelButtonText('N/A', 'N/A', 'N/A')
         
   #############################################################################
   def resetLabel(self):
      self.updateLabelButton(True)
   
   #############################################################################
   def getFeeData(self):
      fee = 0
      fee_byte = 0
      
      if self.radioFlatFee.isChecked():
         flatFeeText = str(self.edtFeeAmt.text())
         fee = str2coin(flatFeeText)
      
      elif self.radioFeeByte.isChecked():
         fee_byteText = str(self.edtFeeByte.text())
         fee_byte = float(fee_byteText)
                 
      elif self.radioAutoFeeByte.isChecked():
         fee_byte = self.feeByte
         
      adjust_fee = self.checkBoxAdjust.isChecked()
         
      return fee, fee_byte, adjust_fee    
   
   #############################################################################
   def setZeroFee(self):
      self.edtFeeAmt.setText('0')
      self.selectType('FlatFee')