Example #1
0
def kinect_simulator(qapp_args=None):
    from PyQt4.QtGui import (
                             QApplication,
                             QWidget, QSpinBox, QHBoxLayout,
                             QSlider, QPushButton)
    import json
    import zmq
    ctx = zmq.Context()
    socket = ctx.socket(zmq.PUB)
    socket.bind(DIRECCION_PUBLICADOR)

    slider1, slider2 = None, None
    if not qapp_args:
        qapp_args = []
    def value_changed(value):
        data = {'mouseX': slider1.value(), 'mouseY': slider2.value()}
        message = json.dumps(data)
        socket.send(message)

    app = QApplication(qapp_args)
    win = QWidget()
    win.setWindowTitle("Send events to kinect")
    layout = QHBoxLayout()
    slider1 = QSlider()
    slider1.setMaximum(1000)
    layout.addWidget(slider1)
    slider2 = QSlider()
    slider1.setMaximum(1000)
    layout.addWidget(slider2)
    slider1.valueChanged[int].connect(value_changed)
    slider2.valueChanged[int].connect(value_changed)
    win.setLayout(layout)
    win.show()

    return app.exec_()
Example #2
0
 def __init__(self):
     super(PyGui, self).__init__()
     self.setObjectName('PyGui')
     self.pub = rospy.Publisher("pyqt_topic", String, queue_size=10)
     rospy.init_node('pyqt_gui')
     self.current_value = 0
     my_layout = QHBoxLayout()
     my_btn = QPushButton()
     my_btn.setText("Publisher")
     my_btn.setFixedWidth(130)
     my_btn.clicked.connect(self.publish_topic)
     my_layout.addWidget(my_btn)
     my_layout.addSpacing(50)
     self.my_label = QLabel()
     self.my_label.setFixedWidth(140)
     self.my_label.setText("num: " + str(0))
     self.my_label.setEnabled(False)
     my_layout.addWidget(self.my_label)
     my_slider = QSlider()
     my_slider.setMinimum(0)
     my_slider.setMaximum(99)
     my_slider.setOrientation(Qt.Horizontal)
     my_slider.valueChanged.connect(self.changeValue)
     my_vlay = QVBoxLayout()
     my_vlay.addWidget(my_slider)
     layout = QVBoxLayout()
     layout.addLayout(my_layout)
     layout.addLayout(my_vlay)
     self.setLayout(layout)
Example #3
0
class Slider(QWidget):
    def __init__(self,
                 caption,
                 default_value,
                 minimum_value=1,
                 maximum_value=60,
                 single_step=1,
                 page_step=6,
                 caption_size=None,
                 unit='',
                 time=False,
                 tooltip=''):
        QWidget.__init__(self)

        self.value = default_value
        self.unit = unit
        self.time = time

        description = QLabel(caption)
        description.setWordWrap(True)
        description.setToolTip(tooltip)
        if caption_size:
            description.setMaximumWidth(caption_size)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMaximum(maximum_value)
        self.slider.setMinimum(minimum_value)
        self.slider.setSingleStep(single_step)
        self.slider.setPageStep(page_step)
        self.slider.setToolTip(tooltip)
        #self.slider.setTickInterval(2)
        #self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.valueChanged.connect(self.__on_change)

        self.value_label = QLabel()

        hbox = QHBoxLayout()
        hbox.addWidget(description)
        hbox.addWidget(self.slider)
        hbox.addWidget(self.value_label)
        hbox.setMargin(0)
        self.setLayout(hbox)
        self.setContentsMargins(5, 0, 5, 0)
        self.slider.setValue(self.value)
        self.__on_change(self.value)

    def __on_change(self, value):
        # FIXME: Fill with spaces to reach the maximum length
        self.value = value
        unit = self.unit
        if self.time:
            minutes = timedelta(minutes=self.value)
            date = datetime(1, 1, 1) + minutes
            text = "%02dh %02dm" % (date.hour, date.minute)
        else:
            text = "%s %s" % (self.value, self.unit)
        self.value_label.setText(text)

    def get_value(self):
        return int(self.slider.value())
Example #4
0
    def add_slider(self,
                   label,
                   description,
                   minimum,
                   maximum,
                   value,
                   slider_moved_func,
                   parent,
                   tick_interval=1,
                   single_step=1,
                   slider_scale_factor=1,
                   int_values=False):
        # make layout to hold slider and textbox
        control_layout = QHBoxLayout()

        slider_label = label + "_slider"
        textbox_label = label + "_textbox"

        # make slider & add to layout
        slider = QSlider(Qt.Horizontal)
        slider.setObjectName(label)
        slider.setFocusPolicy(Qt.StrongFocus)
        slider.setTickPosition(QSlider.TicksBothSides)
        slider.setTickInterval(tick_interval)
        slider.setSingleStep(single_step)
        slider.setMinimum(minimum)
        slider.setMaximum(maximum)
        slider.setValue(value)
        control_layout.addWidget(slider)

        # make textbox & add to layout
        textbox = QLineEdit()
        textbox.setObjectName(label)
        textbox.setFixedWidth(40)
        textbox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        textbox.returnPressed.connect(
            self.controller.update_crop_params_from_gui)
        self.update_textbox_from_slider(slider, textbox, slider_scale_factor,
                                        int_values)
        control_layout.addWidget(textbox)

        # connect slider to set textbox text & update params
        slider.sliderMoved.connect(lambda: self.update_textbox_from_slider(
            slider, textbox, slider_scale_factor, int_values))
        slider.sliderMoved.connect(slider_moved_func)
        slider.sliderPressed.connect(lambda: self.slider_pressed(slider))
        slider.sliderReleased.connect(lambda: self.slider_released(slider))

        # connect textbox to
        textbox.editingFinished.connect(
            lambda: self.update_slider_from_textbox(slider, textbox,
                                                    slider_scale_factor))
        textbox.editingFinished.connect(slider_moved_func)

        # add row to form layout
        parent.addRow(description, control_layout)

        # add to list of controls
        self.crop_param_controls[-1][slider_label] = slider
        self.crop_param_controls[-1][textbox_label] = textbox
Example #5
0
 def getSlider(self, parent):
     sld = QSlider(parent)
     sld.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
     sld.setMinimum(0)
     sld.setMaximum(99)
     sld.setPageStep(10)
     sld.setPageStep(10)
     sld.setMinimumHeight(50)
     sld.setTickInterval(25)
     sld.setTickPosition(QSlider.TicksBothSides)
     return sld
Example #6
0
 def getSlider(self, parent):
     sld = QSlider(parent)
     sld.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
     sld.setMinimum(0)
     sld.setMaximum(99)
     sld.setPageStep(10)
     sld.setPageStep(10)
     sld.setMinimumHeight(50)
     sld.setTickInterval(25)
     sld.setTickPosition(QSlider.TicksBothSides)
     return sld
Example #7
0
    def initUI(self):
        """Initialize ROS node."""
        self.setGeometry(300, 300, 500, 300)
        self.setWindowTitle('RDDA_GUI')

        btnRun = QPushButton('Run')
        btnRun.setFixedWidth(150)
        self.btnCls = QPushButton('Stop')
        self.btnCls.setFixedWidth(150)
        sldPos = QSlider()
        sldPos.setOrientation(Qt.Horizontal)
        sldPos.setMinimum(0)
        sldPos.setMaximum(100)
        sldStf = QSlider()
        sldStf.setOrientation(Qt.Horizontal)
        sldStf.setMinimum(0)
        sldStf.setMaximum(100)
        self.labelPos = QLabel()
        self.labelPos.setFixedWidth(200)
        self.labelPos.setText("Position: " + str(0))
        self.labelStf = QLabel()
        self.labelStf.setFixedWidth(200)
        self.labelStf.setText("Stiffness: " + str(0))

        hboxBtn = QHBoxLayout()
        hboxBtn.addStretch(1)
        hboxBtn.addWidget(btnRun)
        hboxBtn.addSpacing(20)
        hboxBtn.addWidget(self.btnCls)

        hboxPos = QHBoxLayout()
        hboxPos.addWidget(sldPos)
        hboxPos.addSpacing(50)
        hboxPos.addWidget(self.labelPos)

        hboxStf = QHBoxLayout()
        hboxStf.addWidget(sldStf)
        hboxStf.addSpacing(50)
        hboxStf.addWidget(self.labelStf)

        layout = QVBoxLayout()
        layout.addLayout(hboxPos)
        layout.addLayout(hboxStf)
        layout.addLayout(hboxBtn)
        self.setLayout(layout)

        # self.rosThread = RosThread(self.joint_cmds)
        self.rosThread = RosThread()

        btnRun.clicked.connect(self.start_ros)
        self.btnCls.clicked.connect(self.rosThread.stop)
        sldPos.valueChanged.connect(self.set_pos)
        sldStf.valueChanged.connect(self.set_stf)
Example #8
0
 def _addSlider(self, v, cnt):
     control = QSlider(Qt.Horizontal)
     control.setMinimumWidth(172)
     control.setFocusPolicy(Qt.StrongFocus)
     control.setMaximum(v.max * 160)
     control.setMinimum(v.min * 160)
     control.setValue(v.value * 160)
     control.tag = cnt
     if self.styleName == "mac":
         control.setAttribute(Qt.WA_MacMiniSize, True)
     self.layout.addWidget(control, cnt, 1)
     self.connect(control, SIGNAL("valueChanged(int)"), self.numberChanged_)
Example #9
0
class ConfigWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QFormLayout()
        self.setLayout(layout)

        self.inputLabel = QLabel("Video Input")
        self.inputLayout = QHBoxLayout()
        self.inputCombobox = QComboBox()
        self.inputSettingsToolButton = QToolButton()
        self.inputSettingsToolButton.setText("Settings")
        configIcon = QIcon.fromTheme("preferences-other")
        self.inputSettingsToolButton.setIcon(configIcon)
        self.inputSettingsToolButton.setSizePolicy(QSizePolicy.Maximum,
                                                   QSizePolicy.Maximum)
        self.inputSettingsToolButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.inputSettingsStack = QStackedWidget()
        blankWidget = QWidget()
        self.inputSettingsStack.addWidget(blankWidget)
        self.inputSettingsStack.addWidget(self.inputSettingsToolButton)
        self.inputLayout.addWidget(self.inputCombobox)
        self.inputLayout.addWidget(self.inputSettingsStack)
        layout.addRow(self.inputLabel, self.inputLayout)

        self.videocolourLabel = QLabel(self.tr("Colour Format"))
        self.videocolourComboBox = QComboBox()
        self.videocolourComboBox.addItem("video/x-raw-rgb")
        self.videocolourComboBox.addItem("video/x-raw-yuv")
        self.videocolourComboBox.setSizePolicy(QSizePolicy.Minimum,
                                               QSizePolicy.Maximum)
        layout.addRow(self.videocolourLabel, self.videocolourComboBox)

        self.framerateLabel = QLabel("Framerate")
        self.framerateLayout = QHBoxLayout()
        self.framerateSlider = QSlider()
        self.framerateSlider.setOrientation(Qt.Horizontal)
        self.framerateSlider.setMinimum(1)
        self.framerateSlider.setMaximum(60)
        self.framerateSpinBox = QSpinBox()
        self.framerateSpinBox.setMinimum(1)
        self.framerateSpinBox.setMaximum(60)
        self.framerateLayout.addWidget(self.framerateSlider)
        self.framerateLayout.addWidget(self.framerateSpinBox)
        layout.addRow(self.framerateLabel, self.framerateLayout)

        self.videoscaleLabel = QLabel("Video Scale")
        self.videoscaleComboBox = QComboBox()
        for scale in resmap:
            self.videoscaleComboBox.addItem(scale)
        self.videoscaleComboBox.setSizePolicy(QSizePolicy.Minimum,
                                              QSizePolicy.Maximum)
        layout.addRow(self.videoscaleLabel, self.videoscaleComboBox)
Example #10
0
 def _addSlider(self, v, cnt):
     control = QSlider(Qt.Horizontal)
     control.setMinimumWidth(172)
     control.setFocusPolicy(Qt.StrongFocus)
     control.setMaximum(v.max * 160)
     control.setMinimum(v.min * 160)
     control.setValue(v.value * 160)
     control.tag = cnt
     if self.styleName == "mac":
         control.setAttribute(Qt.WA_MacMiniSize, True)
     self.layout.addWidget(control, cnt, 1)
     self.connect(control, SIGNAL("valueChanged(int)"), self.numberChanged_)
Example #11
0
class ConfigWidget(QWidget):

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

        layout = QFormLayout()
        self.setLayout(layout)

        self.inputLabel = QLabel("Video Input")
        self.inputLayout = QHBoxLayout()
        self.inputCombobox = QComboBox()
        self.inputSettingsToolButton = QToolButton()
        self.inputSettingsToolButton.setText("Settings")
        configIcon = QIcon.fromTheme("preferences-other")
        self.inputSettingsToolButton.setIcon(configIcon)
        self.inputSettingsToolButton.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.inputSettingsToolButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.inputSettingsStack = QStackedWidget()
        blankWidget = QWidget()
        self.inputSettingsStack.addWidget(blankWidget)
        self.inputSettingsStack.addWidget(self.inputSettingsToolButton)
        self.inputLayout.addWidget(self.inputCombobox)
        self.inputLayout.addWidget(self.inputSettingsStack)
        layout.addRow(self.inputLabel, self.inputLayout)

        self.videocolourLabel = QLabel(self.tr("Colour Format"))
        self.videocolourComboBox = QComboBox()
        self.videocolourComboBox.addItem("video/x-raw-rgb")
        self.videocolourComboBox.addItem("video/x-raw-yuv")
        self.videocolourComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        layout.addRow(self.videocolourLabel, self.videocolourComboBox)

        self.framerateLabel = QLabel("Framerate")
        self.framerateLayout = QHBoxLayout()
        self.framerateSlider = QSlider()
        self.framerateSlider.setOrientation(Qt.Horizontal)
        self.framerateSlider.setMinimum(1)
        self.framerateSlider.setMaximum(60)
        self.framerateSpinBox = QSpinBox()
        self.framerateSpinBox.setMinimum(1)
        self.framerateSpinBox.setMaximum(60)
        self.framerateLayout.addWidget(self.framerateSlider)
        self.framerateLayout.addWidget(self.framerateSpinBox)
        layout.addRow(self.framerateLabel, self.framerateLayout)

        self.videoscaleLabel = QLabel("Video Scale")
        self.videoscaleComboBox = QComboBox()
        for scale in resmap:
            self.videoscaleComboBox.addItem(scale)
        self.videoscaleComboBox.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)
        layout.addRow(self.videoscaleLabel, self.videoscaleComboBox)
Example #12
0
    def __init__(self):
        QWidget.__init__(self)
        self.resize(400, 100)
        self.setWindowTitle('Control Duty Cycle of PWM0')

        sl = QSlider(Qt.Horizontal)
        sl.setMinimum(0)

        sl.setMaximum(65535)
        sl.setValue(0)
        sl.valueChanged.connect(self.set_pwm)

        layout = QVBoxLayout()
        layout.addWidget(sl)
        self.setLayout(layout)
        self.init_pwm()
Example #13
0
	def __init__(self):
		QWidget.__init__(self)
		self.resize(400, 100)
		self.setWindowTitle('Control Duty Cycle of PWM0')
		
		sl = QSlider(Qt.Horizontal)
		sl.setMinimum(0)
	
		sl.setMaximum(255)	
		sl.setValue(128)
		sl.valueChanged.connect(self.set_pwm)		

		layout = QVBoxLayout()	
		layout.addWidget(sl)	
		self.setLayout(layout)		
		self.init_pwm()
Example #14
0
class okno_podzialu(QDialog):
    def __init__(self, value=0, parent=None):
        super(okno_podzialu, self).__init__(parent)

        self.aa = str(value)
        self.setWindowTitle("Divide Ringwidth")
        self.resize(150, 80)

        self.s = QSlider(Qt.Horizontal)
        self.s.setMinimum(1)
        self.s.setMaximum(int(self.aa))
        self.wart1 = QLabel("1")
        self.wart2 = QLabel(self.aa)
        self.lab = QLabel("Length = " + self.aa + " [1/100mm]")
        self.ok = QPushButton("OK")
        self.anuluj = QPushButton("Anuluj")

        layout = QGridLayout()
        layout.addWidget(self.wart1, 0, 0)
        layout.addWidget(self.s, 0, 1)
        layout.addWidget(self.wart2, 0, 2)
        layout.addWidget(self.lab, 1, 0, 1, 3)
        layout1 = QHBoxLayout()
        layout1.addWidget(self.ok)
        layout1.addWidget(self.anuluj)
        layout.addLayout(layout1, 2, 0, 1, 3)
        self.setLayout(layout)

        self.connect(self.s, SIGNAL("valueChanged(int)"), self.uaktualnij)
        self.connect(self.anuluj, SIGNAL("clicked()"), self.anulowanie)
        self.connect(self.ok, SIGNAL("clicked()"), self.akceptuj)

    def uaktualnij(self):
        self.wart1.setText(str(self.s.value()))
        self.wart2.setText(str(int(self.aa) - self.s.value()))

    def akceptuj(self):
        self.val0 = self.s.value()
        self.val1 = int(self.aa) - self.s.value()
        self.hide()

    def anulowanie(self):
        self.close()
Example #15
0
class OpencvCameraTestWidget(QWidget):
    available_resolutions = {
        "160x120": [160, 120],
        "176x144": [176, 144],
        "320x240": [320, 240],
        "352x288": [352, 288],
        "640x480": [640, 480],
        "960x720": [960, 720],
        "1280x960": [1280, 960]
    }

    def __init__(self, parent=None, capture=None, widget=None):
        super(OpencvCameraTestWidget, self).__init__(parent)
        self.main_layout = QVBoxLayout(self)
        self.main_layout.setSizeConstraint(QLayout.SetFixedSize)
        if capture is None:
            self.capture = cv2.VideoCapture(0)
        else:
            self.capture = capture

        if widget is None:
            self.camera_widget = QImageWidget()
            self.main_layout.addWidget(self.camera_widget)

            self.camera_ret = 0
            self.raw_camera_image = None
            # cv2.namedWindow("image")

            self.camera_timer = QTimer()
            self.camera_timer.timeout.connect(self.grab_video)
            self.camera_timer.start(1000 / 24)

        self.brightness_layout = QHBoxLayout()
        self.brightness_label = QLabel("Brightness: ")
        self.brightness_layout.addWidget(self.brightness_label)
        self.brightness_value_label = QLabel("")
        self.brightness_value_label.setMinimumWidth(30)

        self.brightness_slider = QSlider(Qt.Horizontal)
        self.brightness_slider.setFocusPolicy(Qt.StrongFocus)
        self.brightness_slider.setTickPosition(QSlider.TicksBothSides)
        self.brightness_slider.setMinimum(-10)
        self.brightness_slider.setMaximum(110)
        self.brightness_slider.setValue(20)
        self.brightness_slider.setTickPosition(QSlider.TicksBelow)
        self.brightness_slider.setTickInterval(10)
        self.brightness_slider.valueChanged.connect(self.set_brightness)
        self.brightness_layout.addWidget(self.brightness_slider)
        self.brightness_layout.addWidget(self.brightness_value_label)
        self.main_layout.addLayout(self.brightness_layout)

        self.contrast_layout = QHBoxLayout()
        self.contrast_label = QLabel("Contrast: ")
        self.contrast_layout.addWidget(self.contrast_label)
        self.contrast_value_label = QLabel("")
        self.contrast_value_label.setMinimumWidth(30)

        self.contrast_slider = QSlider(Qt.Horizontal)
        self.contrast_slider.setFocusPolicy(Qt.StrongFocus)
        self.contrast_slider.setTickPosition(QSlider.TicksBothSides)
        self.contrast_slider.setMinimum(-10)
        self.contrast_slider.setMaximum(110)
        self.contrast_slider.setValue(20)
        self.contrast_slider.setTickPosition(QSlider.TicksBelow)
        self.contrast_slider.setTickInterval(10)
        self.contrast_slider.valueChanged.connect(self.set_contrast)
        self.contrast_layout.addWidget(self.contrast_slider)
        self.contrast_layout.addWidget(self.contrast_value_label)
        self.main_layout.addLayout(self.contrast_layout)

        self.exposure_layout = QHBoxLayout()
        self.exposure_label = QLabel("Exposure: ")
        self.exposure_layout.addWidget(self.exposure_label)
        self.exposure_value_label = QLabel("")
        self.exposure_value_label.setMinimumWidth(30)

        self.exposure_slider = QSlider(Qt.Horizontal)
        self.exposure_slider.setFocusPolicy(Qt.StrongFocus)
        self.exposure_slider.setTickPosition(QSlider.TicksBothSides)
        self.exposure_slider.setMinimum(-10)
        self.exposure_slider.setMaximum(110)
        self.exposure_slider.setValue(20)
        self.exposure_slider.setTickPosition(QSlider.TicksBelow)
        self.exposure_slider.setTickInterval(10)
        self.exposure_slider.valueChanged.connect(self.set_exposure)
        self.exposure_layout.addWidget(self.exposure_slider)
        self.exposure_layout.addWidget(self.exposure_value_label)
        self.main_layout.addLayout(self.exposure_layout)

        self.iso_layout = QHBoxLayout()
        self.iso_label = QLabel("ISO: ")
        self.iso_layout.addWidget(self.iso_label)
        self.iso_value_label = QLabel("")
        self.iso_value_label.setMinimumWidth(30)

        self.iso_slider = QSlider(Qt.Horizontal)
        self.iso_slider.setFocusPolicy(Qt.StrongFocus)
        self.iso_slider.setTickPosition(QSlider.TicksBothSides)
        self.iso_slider.setMinimum(-10)
        self.iso_slider.setMaximum(110)
        self.iso_slider.setValue(20)
        self.iso_slider.setTickPosition(QSlider.TicksBelow)
        self.iso_slider.setTickInterval(10)
        self.iso_slider.valueChanged.connect(self.set_iso)
        self.iso_layout.addWidget(self.iso_slider)
        self.iso_layout.addWidget(self.iso_value_label)
        self.main_layout.addLayout(self.iso_layout)

        self.auto_exposure_label = QLabel("AutoExposure: ")
        self.auto_exposure_checkbox = QCheckBox("AutoExposure: ")
        self.exposure_layout.addWidget(self.auto_exposure_checkbox)
        self.auto_exposure_checkbox.stateChanged.connect(
            self.set_auto_exposure)

        self.resolutions_combo = QComboBox()
        self.resolutions_combo.addItems(self.available_resolutions.keys())
        self.main_layout.addWidget(self.resolutions_combo)
        self.resolutions_combo.currentIndexChanged[str].connect(
            self.set_resolution)

    def set_brightness(self, value):
        self.capture.set(cv2.CAP_PROP_BRIGHTNESS, value / 100.0)
        self.brightness_value_label.setText(str(value / 100.0))

    def set_contrast(self, value):
        self.capture.set(cv2.CAP_PROP_CONTRAST, value / 100.0)
        self.contrast_value_label.setText(str(value / 100.0))

    def set_exposure(self, value):

        self.capture.set(cv2.CAP_PROP_EXPOSURE, value / 100.0)
        self.exposure_value_label.setText(str(value / 100.0))

    def set_iso(self, value):

        self.capture.set(cv2.CAP_PROP_ISO_SPEED, value / 100.0)
        self.exposure_value_label.setText(str(value / 100.0))

    def set_auto_exposure(self, value):
        if value > 0:
            self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 1)
        else:
            self.capture.set(cv2.CAP_PROP_AUTO_EXPOSURE, 0.25)

    def set_resolution(self, string):
        if str(string) in self.available_resolutions:
            height = self.available_resolutions[str(string)][0]
            width = self.available_resolutions[str(string)][1]
            self.capture.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
            self.capture.set(cv2.CAP_PROP_FRAME_WIDTH, width)

    def grab_video(self):
        # print "grab video"
        self.camera_ret, self.raw_camera_image = self.capture.read()
        if self.camera_ret:
            self.raw_camera_image = cv2.cvtColor(self.raw_camera_image,
                                                 cv2.COLOR_BGR2RGB)
            self.camera_widget.set_opencv_image(self.raw_camera_image)
Example #16
0
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletDMX, *args)

        self.setupUi(self)

        self.dmx = self.device

        self.wait_for_first_read = True

        self.dmx_overview = DMXOverview(self)
        self.layout_dmx_overview.insertWidget(1, self.dmx_overview)

        self.qtcb_frame_started.connect(self.cb_frame_started)
        self.qtcb_frame.connect(self.cb_frame)

        self.mode_combobox.currentIndexChanged.connect(self.mode_changed)
        self.frame_duration_spinbox.valueChanged.connect(
            self.frame_duration_changed)

        self.address_spinboxes = []
        self.address_slider = []

        for i in range(512):
            spinbox = QSpinBox()
            spinbox.setMinimum(0)
            spinbox.setMaximum(255)

            slider = QSlider(Qt.Horizontal)
            slider.setMinimum(0)
            slider.setMaximum(255)

            spinbox.valueChanged.connect(slider.setValue)
            slider.valueChanged.connect(spinbox.setValue)

            def get_frame_value_changed_func(i):
                return lambda x: self.frame_value_changed(i, x)

            slider.valueChanged.connect(get_frame_value_changed_func(i))

            self.address_table.setCellWidget(i, 0, spinbox)
            self.address_table.setCellWidget(i, 1, slider)

            self.address_spinboxes.append(spinbox)
            self.address_slider.append(slider)

        self.address_table.horizontalHeader().setStretchLastSection(True)
        self.address_table.show()

        self.current_frame = [0] * 512

        self.com_led_off_action = QAction('Off', self)
        self.com_led_off_action.triggered.connect(
            lambda: self.dmx.set_communication_led_config(
                BrickletDMX.COMMUNICATION_LED_CONFIG_OFF))
        self.com_led_on_action = QAction('On', self)
        self.com_led_on_action.triggered.connect(
            lambda: self.dmx.set_communication_led_config(
                BrickletDMX.COMMUNICATION_LED_CONFIG_ON))
        self.com_led_show_heartbeat_action = QAction('Show Heartbeat', self)
        self.com_led_show_heartbeat_action.triggered.connect(
            lambda: self.dmx.set_communication_led_config(
                BrickletDMX.COMMUNICATION_LED_CONFIG_SHOW_HEARTBEAT))
        self.com_led_show_communication_action = QAction('Show Com', self)
        self.com_led_show_communication_action.triggered.connect(
            lambda: self.dmx.set_communication_led_config(
                BrickletDMX.COMMUNICATION_LED_CONFIG_SHOW_COMMUNICATION))

        self.extra_configs += [(1, 'Com LED:', [
            self.com_led_off_action, self.com_led_on_action,
            self.com_led_show_heartbeat_action,
            self.com_led_show_communication_action
        ])]

        self.error_led_off_action = QAction('Off', self)
        self.error_led_off_action.triggered.connect(
            lambda: self.dmx.set_error_led_config(BrickletDMX.
                                                  ERROR_LED_CONFIG_OFF))
        self.error_led_on_action = QAction('On', self)
        self.error_led_on_action.triggered.connect(
            lambda: self.dmx.set_error_led_config(BrickletDMX.
                                                  ERROR_LED_CONFIG_ON))
        self.error_led_show_heartbeat_action = QAction('Show Heartbeat', self)
        self.error_led_show_heartbeat_action.triggered.connect(
            lambda: self.dmx.set_error_led_config(
                BrickletDMX.ERROR_LED_CONFIG_SHOW_HEARTBEAT))
        self.error_led_show_error_action = QAction('Show Error', self)
        self.error_led_show_error_action.triggered.connect(
            lambda: self.dmx.set_error_led_config(BrickletDMX.
                                                  ERROR_LED_CONFIG_SHOW_ERROR))

        self.extra_configs += [(1, 'Error LED:', [
            self.error_led_off_action, self.error_led_on_action,
            self.error_led_show_heartbeat_action,
            self.error_led_show_error_action
        ])]
Example #17
0
class Window(QWidget):

    def __init__(self, parent = None):

        QWidget.__init__(self, parent)

        format = QAudioFormat()
        format.setChannels(1)
        format.setFrequency(22050)
        format.setSampleSize(16)
        format.setCodec("audio/pcm")
        format.setByteOrder(QAudioFormat.LittleEndian)
        format.setSampleType(QAudioFormat.SignedInt)
        self.output = QAudioOutput(format, self)

        self.frequency = 440
        self.volume = 0
        self.buffer = QBuffer()
        self.data = QByteArray()

        self.deviceLineEdit = QLineEdit()
        self.deviceLineEdit.setReadOnly(True)
        self.deviceLineEdit.setText(QAudioDeviceInfo.defaultOutputDevice().deviceName())

        self.pitchSlider = QSlider(Qt.Horizontal)
        self.pitchSlider.setMaximum(100)
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMaximum(32767)
        self.volumeSlider.setPageStep(1024)

        self.playButton = QPushButton(self.tr("&Play"))

        self.pitchSlider.valueChanged.connect(self.changeFrequency)
        self.volumeSlider.valueChanged.connect(self.changeVolume)
        self.playButton.clicked.connect(self.play)

        formLayout = QFormLayout()
        formLayout.addRow(self.tr("Device:"), self.deviceLineEdit)
        formLayout.addRow(self.tr("P&itch:"), self.pitchSlider)
        formLayout.addRow(self.tr("&Volume:"), self.volumeSlider)

        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.playButton)
        buttonLayout.addStretch()

        horizontalLayout = QHBoxLayout(self)
        horizontalLayout.addLayout(formLayout)
        horizontalLayout.addLayout(buttonLayout)

    def changeFrequency(self, value):

        self.frequency = 440 + (value * 2)

    def play(self):

        if self.output.state() == QAudio.ActiveState:
            self.output.stop()

        if self.buffer.isOpen():
            self.buffer.close()

        self.createData()

        self.buffer.setData(self.data)
        self.buffer.open(QIODevice.ReadOnly)
        self.buffer.seek(0)

        self.output.start(self.buffer)

    def changeVolume(self, value):

        self.volume = value

    def createData(self):

        # Create 2 seconds of data with 22050 samples per second, each sample
        # being 16 bits (2 bytes).

        self.data.clear()
        for i in xrange(2 * 22050):
            t = i / 22050.0
            value = int(self.volume * sin(2 * pi * self.frequency * t))
            self.data.append(struct.pack("<h", value))
Example #18
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)
Example #19
0
class Widget(QWidget):
    def __init__(self, dockwidget):
        super(Widget, self).__init__(dockwidget)
        self._document = None
        self._fileSelector = QComboBox(editable=True,
                                       insertPolicy=QComboBox.NoInsert)
        widgets.drag.ComboDrag(self._fileSelector).role = Qt.UserRole
        self._fileSelector.lineEdit().setReadOnly(True)
        self._fileSelector.lineEdit().setFocusPolicy(Qt.NoFocus)
        self._stopButton = QToolButton()
        self._playButton = QToolButton()
        self._timeSlider = QSlider(Qt.Horizontal,
                                   tracking=False,
                                   singleStep=500,
                                   pageStep=5000,
                                   invertedControls=True)
        self._display = Display()
        self._tempoFactor = QSlider(Qt.Vertical,
                                    minimum=-50,
                                    maximum=50,
                                    singleStep=1,
                                    pageStep=5)

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

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

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

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

        self._player = player.Player()
        self._outputCloseTimer = QTimer(interval=60000,
                                        singleShot=True,
                                        timeout=self.closeOutput)
        self._timeSliderTicker = QTimer(interval=200,
                                        timeout=self.updateTimeSlider)
        self._fileSelector.activated[int].connect(self.slotFileSelected)
        self._tempoFactor.valueChanged.connect(self.slotTempoChanged)
        self._timeSlider.valueChanged.connect(self.slotTimeSliderChanged)
        self._timeSlider.sliderMoved.connect(self.slotTimeSliderMoved)
        self._player.beat.connect(self.updateDisplayBeat)
        self._player.time.connect(self.updateDisplayTime)
        self._player.stateChanged.connect(self.slotPlayerStateChanged)
        self.slotPlayerStateChanged(False)
        dockwidget.mainwindow().currentDocumentChanged.connect(
            self.loadResults)
        app.documentLoaded.connect(self.slotUpdatedFiles)
        app.jobFinished.connect(self.slotUpdatedFiles)
        app.aboutToQuit.connect(self.stop)
        midihub.aboutToRestart.connect(self.slotAboutToRestart)
        midihub.settingsChanged.connect(self.clearMidiSettings, -100)
        midihub.settingsChanged.connect(self.readMidiSettings)
        app.documentClosed.connect(self.slotDocumentClosed)
        app.translateUI(self)
        self.readMidiSettings()
        d = dockwidget.mainwindow().currentDocument()
        if d:
            self.loadResults(d)

    def translateUI(self):
        self._tempoFactor.setToolTip(_("Tempo"))

    def slotAboutToRestart(self):
        self.stop()
        self._player.set_output(None)

    def clearMidiSettings(self):
        """Called first when settings are changed."""
        self.stop()
        self._outputCloseTimer.stop()
        self._player.set_output(None)

    def readMidiSettings(self):
        """Called after clearMidiSettings(), and on first init."""
        pass

    def openOutput(self):
        """Called when playing starts. Ensures an output port is opened."""
        self._outputCloseTimer.stop()
        if not self._player.output():
            p = QSettings().value("midi/player/output_port",
                                  midihub.default_output(), type(""))
            o = midihub.output_by_name(p)
            if o:
                self._player.set_output(output.Output(o))

    def closeOutput(self):
        """Called when the output close timer fires. Closes the output."""
        self._player.set_output(None)

    def slotPlayerStateChanged(self, playing):
        ac = self.parentWidget().actionCollection
        # setDefaultAction also adds the action
        for b in self._stopButton, self._playButton:
            while b.actions():
                b.removeAction(b.actions()[0])
        if playing:
            self._timeSliderTicker.start()
            self._stopButton.setDefaultAction(ac.midi_stop)
            self._playButton.setDefaultAction(ac.midi_pause)
        else:
            self._timeSliderTicker.stop()
            self.updateTimeSlider()
            self._stopButton.setDefaultAction(ac.midi_restart)
            self._playButton.setDefaultAction(ac.midi_play)
            # close the output if the preference is set
            if QSettings().value("midi/close_outputs", False, bool):
                self._outputCloseTimer.start()

    def play(self):
        """Starts the MIDI player, opening an output if necessary."""
        if not self._player.is_playing() and not self._player.has_events():
            self.restart()
        self.openOutput()
        if not self._player.output():
            self._display.statusMessage(_("No output found!"))
        self._player.start()

    def stop(self):
        """Stops the MIDI player."""
        self._player.stop()

    def restart(self):
        """Restarts the MIDI player.
        
        If another file is in the file selector, or the file was updated,
        the new file is loaded.
        
        """
        self._player.seek(0)
        self.updateTimeSlider()
        self._display.reset()
        if self._document:
            files = midifiles.MidiFiles.instance(self._document)
            index = self._fileSelector.currentIndex()
            if files and (files.song(index) is not self._player.song()):
                self.loadSong(index)

    def slotTempoChanged(self, value):
        """Called when the user drags the tempo."""
        # convert -50 to 50 to 0.5 to 2.0
        factor = 2**(value / 50.0)
        self._player.set_tempo_factor(factor)
        self._display.setTempo("{0}%".format(int(factor * 100)))

    def slotTimeSliderChanged(self, value):
        self._player.seek(value)
        self._display.setTime(value)
        if self._player.song():
            self._display.setBeat(*self._player.song().beat(value)[1:])

    def slotTimeSliderMoved(self, value):
        self._display.setTime(value)
        if self._player.song():
            self._display.setBeat(*self._player.song().beat(value)[1:])

    def updateTimeSlider(self):
        if not self._timeSlider.isSliderDown():
            with qutil.signalsBlocked(self._timeSlider):
                self._timeSlider.setMaximum(self._player.total_time())
                self._timeSlider.setValue(self._player.current_time())

    def updateDisplayBeat(self, measnum, beat, num, den):
        if not self._timeSlider.isSliderDown():
            self._display.setBeat(measnum, beat, num, den)

    def updateDisplayTime(self, time):
        if not self._timeSlider.isSliderDown():
            self._display.setTime(time)

    def slotUpdatedFiles(self, document):
        """Called when there are new MIDI files."""
        if document == self.parentWidget().mainwindow().currentDocument():
            self.loadResults(document)

    def loadResults(self, document):
        self._document = document
        files = midifiles.MidiFiles.instance(document)
        self._fileSelector.setModel(files.model())
        if files:
            self._fileSelector.setCurrentIndex(files.current)
            if not self._player.is_playing():
                self.loadSong(files.current)

    def loadSong(self, index):
        files = midifiles.MidiFiles.instance(self._document)
        self._player.set_song(files.song(index))
        m, s = divmod(self._player.total_time() // 1000, 60)
        name = self._fileSelector.currentText()
        self.updateTimeSlider()
        self._display.reset()
        self._display.statusMessage(_("midi lcd screen", "LOADED"), name,
                                    _("midi lcd screen", "TOTAL"),
                                    "{0}:{1:02}".format(m, s))

    def slotFileSelected(self, index):
        if self._document:
            self._player.stop()
            files = midifiles.MidiFiles.instance(self._document)
            if files:
                files.current = index
                self.restart()

    def slotDocumentClosed(self, document):
        if document == self._document:
            self._document = None
            self._fileSelector.clear()
            self._player.stop()
            self._player.clear()
            self.updateTimeSlider()
            self._display.reset()
Example #20
0
class GeneralSection(QWidget):
    """ Clase Configuracion Editor """
    def __init__(self):
        super(GeneralSection, self).__init__()
        main_container = QVBoxLayout(self)

        # Tabs and indentation
        group_indentation = QGroupBox(self.tr("Indentación y Tabs:"))
        box = QGridLayout(group_indentation)
        box.setContentsMargins(20, 5, 20, 5)
        box.addWidget(QLabel(self.tr("Política:")), 0, 0)
        self.combo_tabs = QComboBox()
        self.combo_tabs.setFixedWidth(350)
        self.combo_tabs.addItems([
            self.tr("Solo Espacios"),
            self.tr("Solo Tabulaciones"),
        ])
        box.addWidget(self.combo_tabs, 0, 1)
        self.combo_tabs.setCurrentIndex(
            int(settings.get_setting('editor/usetabs')))
        # Auto indent
        self.check_autoindent = QCheckBox(self.tr("Indentación Automática"))
        box.addWidget(self.check_autoindent, 1, 0)
        box.setAlignment(Qt.AlignLeft)
        self.check_autoindent.setChecked(settings.get_setting('editor/indent'))

        # Minimap
        group_minimap = QGroupBox(self.tr("Minimapa:"))
        box = QGridLayout(group_minimap)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_minimap = QCheckBox(
            self.tr("Activar Minimapa (requiere reiniciar el Editor)"))
        self.check_minimap.setChecked(settings.get_setting('editor/minimap'))
        box.addWidget(self.check_minimap, 0, 0)
        #self.check_minimap_animation = QCheckBox(self.tr("Enable animation"))
        #self.check_minimap_animation.setChecked(
        #settings.get_setting('editor/minimap-animation'))
        #box.addWidget(self.check_minimap_animation, 1, 0)
        #box.addWidget(QLabel(self.tr("Size Area:")), 2, 0)
        #self.spin_area_minimap = QSpinBox()
        #self.spin_area_minimap.setFixedWidth(350)
        #box.addWidget(self.spin_area_minimap, 2, 1)
        box.setAlignment(Qt.AlignLeft)

        # Cursor
        group_caret = QGroupBox(self.tr("Cursor:"))
        box = QGridLayout(group_caret)
        box.setContentsMargins(20, 5, 20, 5)
        box.setAlignment(Qt.AlignLeft)
        # Type
        box.addWidget(QLabel(self.tr("Tipo:")), 0, 0)
        self.combo_caret = QComboBox()
        self.combo_caret.setFixedWidth(300)
        caret_types = [
            self.tr('Invisible'),
            self.tr('Línea'),
            self.tr('Bloque')
        ]
        self.combo_caret.addItems(caret_types)
        index = settings.get_setting('editor/cursor')
        self.combo_caret.setCurrentIndex(index)
        box.addWidget(self.combo_caret, 0, 1)
        # Width
        box.addWidget(QLabel(self.tr("Ancho:")), 1, 0)
        self.spin_caret_width = QSpinBox()
        self.spin_caret_width.setFixedWidth(300)
        if index != 1:
            self.spin_caret_width.setEnabled(False)
        self.spin_caret_width.setRange(1, 3)
        self.spin_caret_width.setValue(
            settings.get_setting('editor/caret-width'))
        box.addWidget(self.spin_caret_width, 1, 1, Qt.AlignLeft)
        # Period
        box.addWidget(QLabel(self.tr("Período (ms):")), 2, 0)
        self.slider_caret_period = QSlider(Qt.Horizontal)
        self.slider_caret_period.setMaximum(500)
        self.slider_caret_period.setFixedWidth(300)
        box.addWidget(self.slider_caret_period, 2, 1, Qt.AlignLeft)
        lcd_caret = QLCDNumber()
        lcd_caret.setSegmentStyle(QLCDNumber.Flat)
        box.addWidget(lcd_caret, 2, 3)

        # Font
        group_typo = QGroupBox(self.tr("Fuente:"))
        box = QGridLayout(group_typo)
        box.setContentsMargins(20, 5, 20, 5)
        box.addWidget(QLabel(self.tr("Familia:")), 0, 0)
        self.combo_font = QFontComboBox()
        self.combo_font.setFixedWidth(350)
        box.addWidget(self.combo_font, 0, 1)
        self._load_font()
        box.addWidget(QLabel(self.tr("Tamaño:")), 1, 0)
        self.spin_size_font = QSpinBox()
        self.spin_size_font.setValue(settings.get_setting('editor/size-font'))
        self.spin_size_font.setFixedWidth(350)
        box.addWidget(self.spin_size_font, 1, 1)
        box.setAlignment(Qt.AlignLeft)

        # Scheme
        group_scheme = QGroupBox(self.tr("Tema:"))
        box = QVBoxLayout(group_scheme)
        box.setContentsMargins(20, 5, 20, 5)
        self.combo_scheme = QComboBox()
        self.combo_scheme.setFixedWidth(350)
        self.combo_scheme.addItems(['Dark Edis', 'White Edis'])
        scheme = settings.get_setting('editor/scheme')
        index = 0
        if scheme != 'dark':
            index = 1
        self.combo_scheme.setCurrentIndex(index)
        box.addWidget(self.combo_scheme)
        box.addWidget(QLabel(self.tr("Requiere reiniciar Edis")))

        ## Agrupación
        main_container.addWidget(group_indentation)
        main_container.addWidget(group_minimap)
        main_container.addWidget(group_caret)
        main_container.addWidget(group_typo)
        main_container.addWidget(group_scheme)
        main_container.addItem(
            QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding))

        EditorConfiguration.install_widget(self.tr("General"), self)

        # Conexiones
        self.combo_scheme.currentIndexChanged['const QString&'].connect(
            self._change_scheme)
        self.combo_caret.currentIndexChanged[int].connect(
            self._caret_type_changed)
        self.slider_caret_period.valueChanged[int].connect(lcd_caret.display)

        self.slider_caret_period.setValue(
            settings.get_setting('editor/cursor-period'))

    def _change_scheme(self, theme):
        theme = theme.split()[0].lower()
        editor_container = Edis.get_component("principal")
        editor = editor_container.get_active_editor()
        if editor is not None:
            # Restyle
            pass

    def _caret_type_changed(self, index):
        self.spin_caret_width.setEnabled(bool(index))

    def _load_font(self):

        font = settings.get_setting('editor/font')
        self.combo_font.setCurrentFont(QFont(font))

    def save(self):
        """ Guarda las configuraciones del Editor. """

        use_tabs = bool(self.combo_tabs.currentIndex())
        settings.set_setting('editor/usetabs', use_tabs)
        auto_indent = self.check_autoindent.isChecked()
        settings.set_setting('editor/indent', auto_indent)
        settings.set_setting('editor/minimap', self.check_minimap.isChecked())
        #settings.set_setting('editor/minimap-animation',
        #self.check_minimap_animation.isChecked())
        font = self.combo_font.currentFont().family()
        settings.set_setting('editor/font', font)
        font_size = self.spin_size_font.value()
        settings.set_setting('editor/size-font', font_size)
        scheme = self.combo_scheme.currentText().split()[0].lower()
        settings.set_setting('editor/scheme', scheme)
        settings.set_setting('editor/cursor', self.combo_caret.currentIndex())
        settings.set_setting('editor/caret-width',
                             self.spin_caret_width.value())
        settings.set_setting('editor/cursor-period',
                             self.slider_caret_period.value())
        editor_container = Edis.get_component("principal")
        editor = editor_container.get_active_editor()
        if editor is not None:
            editor.setIndentationsUseTabs(use_tabs)
            editor.load_font(font, font_size)
Example #21
0
class QuadStatusBar(QHBoxLayout):
    positionChanged = pyqtSignal(int, int, int) # x,y,z
    
    def __init__(self, parent=None ):
        QHBoxLayout.__init__(self, parent)
        self.setContentsMargins(0,4,0,0)
        self.setSpacing(0)
        self.timeControlFontSize = 12

    def showXYCoordinates(self):
        self.zLabel.setHidden(True)
        self.zSpinBox.setHidden(True)
        
    def showXYZCoordinates(self):
        self.zLabel.setHidden(False)
        self.zSpinBox.setHidden(False)
    
    def hideTimeSlider(self,flag):
        self.timeSlider.setHidden(flag)
        self.timeEndButton.setHidden(flag)
        self.timeStartButton.setHidden(flag)

    def setToolTipTimeButtonsCrop(self,croppingFlag=False):
        if croppingFlag==True:
            self.timeStartButton.setToolTip("Set the time coordinate to the beginning of the current crop.")
            self.timeEndButton.setToolTip("Set the time coordinate to the end of the current crop.")
        else:
            self.timeStartButton.setToolTip("Set the time coordinate to the beginning of the current dataset.")
            self.timeEndButton.setToolTip("Set the time coordinate to the end of the current dataset.")

    def setToolTipTimeSliderCrop(self,croppingFlag=False):
        if croppingFlag==True:
            self.timeSlider.setToolTip("Choose the time coordinate of the current crop.")
        else:
            self.timeSlider.setToolTip("Choose the time coordinate of the current dataset.")

    def createQuadViewStatusBar(self,
                                xbackgroundColor, xforegroundColor,
                                ybackgroundColor, yforegroundColor,
                                zbackgroundColor, zforegroundColor):
        self.xLabel, self.xSpinBox = _get_pos_widget('X',
                                                     xbackgroundColor,
                                                     xforegroundColor)
        self.yLabel, self.ySpinBox = _get_pos_widget('Y',
                                                     ybackgroundColor,
                                                     yforegroundColor)
        self.zLabel, self.zSpinBox = _get_pos_widget('Z',
                                                     zbackgroundColor,
                                                     zforegroundColor)
        
        self.xSpinBox.delayedValueChanged.connect( partial(self._handlePositionBoxValueChanged, 'x') )
        self.ySpinBox.delayedValueChanged.connect( partial(self._handlePositionBoxValueChanged, 'y') )
        self.zSpinBox.delayedValueChanged.connect( partial(self._handlePositionBoxValueChanged, 'z') )

        self.addWidget(self.xLabel)
        self.addWidget(self.xSpinBox)
        self.addWidget(self.yLabel)
        self.addWidget(self.ySpinBox)
        self.addWidget(self.zLabel)
        self.addWidget(self.zSpinBox)

        self.addSpacing(10)

        self.busyIndicator = QProgressBar()
        self.busyIndicator.setMaximumWidth(200)
        self.busyIndicator.setMaximum(0)
        self.busyIndicator.setMinimum(0)
        self.busyIndicator.setVisible(False)
        self.busyIndicator.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.addWidget( self.busyIndicator )
        self.setStretchFactor(self.busyIndicator, 1)

        self.addStretch()
        self.addSpacing(10)

        self.positionCheckBox = QCheckBox()
        self.positionCheckBox.setChecked(True)
        self.positionCheckBox.setCheckable(True)
        self.positionCheckBox.setText("Position")
        self.addWidget(self.positionCheckBox)

        self.addSpacing(20)

        self.timeSpinBox = DelayedSpinBox(750)

        self.timeStartButton = QPushButton("Start")
        self.addWidget(self.timeStartButton)
        self.timeStartButton.clicked.connect(self._onTimeStartButtonClicked)

        self.timeSlider = QSlider(Qt.Horizontal)
        self.timeSlider.setMinimumWidth(10)
        self.timeSlider.setMaximumWidth(200)
        self.setToolTipTimeSliderCrop()
        self.addWidget(self.timeSlider)
        self.timeSlider.valueChanged.connect(self._onTimeSliderChanged)

        self.timeEndButton = QPushButton("End")
        self.timeEndButton.setFixedWidth(4*self.timeControlFontSize)

        self.timeStartButton.setFixedWidth(4*self.timeControlFontSize)
        
        self.setToolTipTimeButtonsCrop()
        self.addWidget(self.timeEndButton)
        self.timeEndButton.clicked.connect(self._onTimeEndButtonClicked)

        self.timeLabel = QLabel("       Time:")
        self.addWidget(self.timeLabel)

        timeControlFont = self.timeSpinBox.font()
        if self.timeControlFontSize > timeControlFont.pointSize():
            timeControlFont.setPixelSize(self.timeControlFontSize)
            self.timeStartButton.setFont(timeControlFont)
            self.timeEndButton.setFont(timeControlFont)
            self.timeLabel.setFont(timeControlFont)
            self.timeSpinBox.setFont(timeControlFont)

        self.addWidget(self.timeSpinBox)
        self.timeSpinBox.delayedValueChanged.connect(self._onTimeSpinBoxChanged)

    def _onTimeStartButtonClicked(self):
        self.timeSpinBox.setValue(self.parent().parent().parent().editor.cropModel.get_roi_t()[0])

    def _onTimeEndButtonClicked(self):
        self.timeSpinBox.setValue(self.parent().parent().parent().editor.cropModel.get_roi_t()[1])

    def _onTimeSpinBoxChanged(self):
        editor = self.parent().parent().parent().editor
        cropModel = editor.cropModel
        minValueT = cropModel.get_roi_t()[0]
        maxValueT = cropModel.get_roi_t()[1]

        if cropModel.get_scroll_time_outside_crop():
            if minValueT > self.timeSpinBox.value() or maxValueT < self.timeSpinBox.value():
                for imgView in editor.imageViews:
                    imgView._croppingMarkers._shading_item.set_paint_full_frame(True)
            else:
                for imgView in editor.imageViews:
                    imgView._croppingMarkers._shading_item.set_paint_full_frame(False)
            self.timeSlider.setValue(self.timeSpinBox.value())
        else:
            for imgView in editor.imageViews:
                imgView._croppingMarkers._shading_item.set_paint_full_frame(False)
            if minValueT > self.timeSpinBox.value():
                self.timeSlider.setValue(minValueT)
            elif maxValueT < self.timeSpinBox.value():
                self.timeSlider.setValue(maxValueT)
            elif minValueT <= self.timeSpinBox.value() and self.timeSpinBox.value() <= maxValueT:
                self.timeSlider.setValue(self.timeSpinBox.value())

    def _onTimeSliderChanged(self):
        cropModel = self.parent().parent().parent().editor.cropModel
        minValueT = cropModel.get_roi_t()[0]
        maxValueT = cropModel.get_roi_t()[1]

        if cropModel.get_scroll_time_outside_crop():
            self.timeSpinBox.setValue(self.timeSlider.value())
        else:
            if minValueT > self.timeSlider.value():
                self.timeSpinBox.setValue(minValueT)
                self.timeSlider.setValue(minValueT)
            elif self.timeSlider.value() > maxValueT:
                self.timeSpinBox.setValue(maxValueT)
                self.timeSlider.setValue(maxValueT)
            elif minValueT <= self.timeSlider.value() and self.timeSlider.value() <= maxValueT:
                self.timeSpinBox.setValue(self.timeSlider.value())

    def _handlePositionBoxValueChanged(self, axis, value):
        new_position = [self.xSpinBox.value(), self.ySpinBox.value(), self.zSpinBox.value()]
        changed_axis = ord(axis) - ord('x')
        new_position[changed_axis] = value
        self.positionChanged.emit(*new_position)

    def updateShape5D(self, shape5D):
        self.timeSpinBox.setMaximum(shape5D[0]-1)
        self.xSpinBox.setMaximum(shape5D[1]-1)
        self.ySpinBox.setMaximum(shape5D[2]-1)
        self.zSpinBox.setMaximum(shape5D[3]-1)

    def updateShape5Dcropped(self, shape5DcropMin, shape5Dmax):
        self.timeSpinBox.setMaximum(shape5Dmax[0]-1)
        self.xSpinBox.setMaximum(shape5Dmax[1]-1)
        self.ySpinBox.setMaximum(shape5Dmax[2]-1)
        self.zSpinBox.setMaximum(shape5Dmax[3]-1)
        self.timeSlider.setMaximum(shape5Dmax[0]-1)

        self.timeSpinBox.setValue(shape5DcropMin[0])
        self.xSpinBox.setValue(shape5DcropMin[1])
        self.ySpinBox.setValue(shape5DcropMin[2])
        self.zSpinBox.setValue(shape5DcropMin[3])
        self.timeSlider.setValue(shape5DcropMin[0])

    def setMouseCoords(self, x, y, z):
        self.xSpinBox.setValueWithoutSignal(x)
        self.ySpinBox.setValueWithoutSignal(y)
        self.zSpinBox.setValueWithoutSignal(z)
Example #22
0
class Simulator(QMainWindow):

   def __init__(self, network):
      super(Simulator, self).__init__()
      x, y, w, h = 100, 100, 800, 500
      self.setGeometry(x, y, w, h)

      # Network
      self.network = network

      # Canvas
      self.canvas = Canvas()

      #Controls
      self.slider = QSlider(Qt.Horizontal, self)
      self.slider.setMaximum(self.network.count_snapshots()-1)
      self.slider.setTickPosition(QSlider.TicksBelow)
      self.slider.setTickInterval(1)
      self.connect(self.slider, SIGNAL("valueChanged(int)"), self.draw_network)
      self.prevButton = QPushButton(u"\u25C0")
      self.connect(self.prevButton, SIGNAL("clicked()"), self.onClickPrev)
      self.nextButton = QPushButton(u"\u25B6")
      self.connect(self.nextButton, SIGNAL("clicked()"), self.onClickNext)

      controls = QHBoxLayout()
      controls.addWidget(self.prevButton)
      controls.addWidget(self.slider)
      controls.addWidget(self.nextButton)

      #Main Layout
      mainLayout = QVBoxLayout()
      mainLayout.addWidget(self.canvas)
      mainLayout.addLayout(controls)

      self.widget = QtGui.QWidget()
      self.widget.setLayout(mainLayout)
      self.setCentralWidget(self.widget)

      self.setWindowTitle('DATK Simulator')

      #Reset Network and draw in starting state
      self.draw_network(0)


   def draw_network(self, value):
      self.network.restore_snapshot(value)
      self.canvas.draw(self.network)

   def onClickPrev(self):
      v = self.slider.value()
      if v > 0:
         self.slider.setValue(v-1)

   def onClickNext(self):
      v = self.slider.value()
      if v < self.slider.maximum():
         self.slider.setValue(v+1)

   def closeEvent(self, event): 
      self.network.restore_snapshot(-1)
      self.deleteLater() 
Example #23
0
class DisplaySection(QWidget):

    def __init__(self):
        super(DisplaySection, self).__init__()
        EditorConfiguration.install_widget(self.tr("Visualización"), self)
        container = QVBoxLayout(self)

        # Text wrapping
        group_wrapping = QGroupBox(self.tr("Ajuste de Texto:"))
        box = QGridLayout(group_wrapping)
        self.check_wrap = QCheckBox(self.tr("Activar ajuste de texto"))
        box.addWidget(self.check_wrap, 0, 0)
        self.check_margin = QCheckBox(self.tr("Mostrar márgen derecho:"))
        box.addWidget(self.check_margin, 1, 0)
        self.slider_margin = QSlider(Qt.Horizontal)
        self.slider_margin.setMaximum(180)
        self.slider_margin.setFixedWidth(350)
        box.addWidget(self.slider_margin, 1, 1, Qt.AlignLeft)
        lcd_margin = QLCDNumber()
        lcd_margin.setSegmentStyle(QLCDNumber.Flat)
        box.addWidget(lcd_margin, 1, 2, Qt.AlignLeft)
        box.setAlignment(Qt.AlignLeft)
        container.addWidget(group_wrapping)  # Add group

        # Extras: line number, markers, whitespace, etc
        group_extras = QGroupBox(self.tr("Visualización:"))
        box = QGridLayout(group_extras)
        self.check_line_numbers = QCheckBox(
            self.tr("Mostrar números de líneas"))
        box.addWidget(self.check_line_numbers, 0, 0)
        self.check_current_line = QCheckBox(self.tr("Resaltar línea actual"))
        box.addWidget(self.check_current_line, 0, 1)
        self.check_mark_change = QCheckBox(self.tr("Marcar línea modificada"))
        box.addWidget(self.check_mark_change, 1, 0)
        self.check_match_brace = QCheckBox(
            self.tr("Resaltar [], {}, (), <>"))
        box.addWidget(self.check_match_brace, 1, 1)
        self.check_whitespace = QCheckBox(
            self.tr("Mostrar espacios en blanco"))
        box.addWidget(self.check_whitespace, 2, 0)
        self.check_guides = QCheckBox(self.tr("Mostrar guías de indentación"))
        box.addWidget(self.check_guides, 2, 1)
        self.check_eof = QCheckBox(self.tr("Mostrar EOF"))
        box.addWidget(self.check_eof, 3, 0)
        container.addWidget(group_extras)  # Add group

        # Spacer
        container.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding,
                          QSizePolicy.Expanding))

        # Connections
        self.slider_margin.valueChanged[int].connect(lcd_margin.display)

        # Configuration
        self.check_wrap.setChecked(
            settings.get_setting('editor/wrap-mode'))
        self.check_line_numbers.setChecked(
            settings.get_setting('editor/show-line-number'))
        self.check_mark_change.setChecked(
            settings.get_setting('editor/mark-change'))
        self.check_match_brace.setChecked(
            settings.get_setting('editor/match-brace'))
        self.check_current_line.setChecked(
            settings.get_setting('editor/show-caret-line'))
        self.check_eof.setChecked(
            settings.get_setting('editor/eof'))
        self.check_margin.setChecked(
            settings.get_setting('editor/show-margin'))
        self.slider_margin.setValue(settings.get_setting('editor/width-margin'))
        self.check_whitespace.setChecked(
            settings.get_setting('editor/show-tabs-spaces'))
        self.check_guides.setChecked(
            settings.get_setting('editor/show-guides'))

    def save(self):
        settings.set_setting('editor/wrap-mode',
            self.check_wrap.isChecked())
        settings.set_setting('editor/show-margin',
            self.check_margin.isChecked())
        settings.set_setting('editor/width-margin',
            self.slider_margin.value())
        settings.set_setting('editor/show-line-number',
            self.check_line_numbers.isChecked())
        settings.set_setting('editor/mark-change',
            self.check_mark_change.isChecked())
        settings.set_setting('editor/match-brace',
            self.check_match_brace.isChecked())
        settings.set_setting('editor/show-caret-line',
            self.check_current_line.isChecked())
        settings.set_setting('editor/show-tabs-spaces',
            self.check_whitespace.isChecked())
        settings.set_setting('editor/show-guides',
            self.check_guides.isChecked())
        settings.set_setting('editor/eof',
            self.check_eof.isChecked())
        editor_container = Edis.get_component("principal")
        editor = editor_container.get_active_editor()
        if editor is not None:
            editor.set_brace_matching()
            editor.show_line_numbers()
            editor.update_options()
            editor.update_margin()
Example #24
0
class GeneralSection(QWidget):
    """ Clase Configuracion Editor """

    def __init__(self):
        super(GeneralSection, self).__init__()
        main_container = QVBoxLayout(self)

        # Tabs and indentation
        group_indentation = QGroupBox(self.tr("Indentación y Tabs:"))
        box = QGridLayout(group_indentation)
        box.setContentsMargins(20, 5, 20, 5)
        box.addWidget(QLabel(self.tr("Política:")), 0, 0)
        self.combo_tabs = QComboBox()
        self.combo_tabs.setFixedWidth(350)
        self.combo_tabs.addItems([
            self.tr("Solo Espacios"),
            self.tr("Solo Tabulaciones"),
            ])
        box.addWidget(self.combo_tabs, 0, 1)
        self.combo_tabs.setCurrentIndex(
            int(settings.get_setting('editor/usetabs')))
        # Auto indent
        self.check_autoindent = QCheckBox(self.tr("Indentación Automática"))
        box.addWidget(self.check_autoindent, 1, 0)
        box.setAlignment(Qt.AlignLeft)
        self.check_autoindent.setChecked(settings.get_setting('editor/indent'))

        # Minimap
        group_minimap = QGroupBox(self.tr("Minimapa:"))
        box = QGridLayout(group_minimap)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_minimap = QCheckBox(
            self.tr("Activar Minimapa (requiere reiniciar el Editor)"))
        self.check_minimap.setChecked(settings.get_setting('editor/minimap'))
        box.addWidget(self.check_minimap, 0, 0)
        #self.check_minimap_animation = QCheckBox(self.tr("Enable animation"))
        #self.check_minimap_animation.setChecked(
            #settings.get_setting('editor/minimap-animation'))
        #box.addWidget(self.check_minimap_animation, 1, 0)
        #box.addWidget(QLabel(self.tr("Size Area:")), 2, 0)
        #self.spin_area_minimap = QSpinBox()
        #self.spin_area_minimap.setFixedWidth(350)
        #box.addWidget(self.spin_area_minimap, 2, 1)
        box.setAlignment(Qt.AlignLeft)

        # Cursor
        group_caret = QGroupBox(self.tr("Cursor:"))
        box = QGridLayout(group_caret)
        box.setContentsMargins(20, 5, 20, 5)
        box.setAlignment(Qt.AlignLeft)
        # Type
        box.addWidget(QLabel(self.tr("Tipo:")), 0, 0)
        self.combo_caret = QComboBox()
        self.combo_caret.setFixedWidth(300)
        caret_types = [
            self.tr('Invisible'),
            self.tr('Línea'),
            self.tr('Bloque')
            ]
        self.combo_caret.addItems(caret_types)
        index = settings.get_setting('editor/cursor')
        self.combo_caret.setCurrentIndex(index)
        box.addWidget(self.combo_caret, 0, 1)
        # Width
        box.addWidget(QLabel(self.tr("Ancho:")), 1, 0)
        self.spin_caret_width = QSpinBox()
        self.spin_caret_width.setFixedWidth(300)
        if index != 1:
            self.spin_caret_width.setEnabled(False)
        self.spin_caret_width.setRange(1, 3)
        self.spin_caret_width.setValue(
            settings.get_setting('editor/caret-width'))
        box.addWidget(self.spin_caret_width, 1, 1, Qt.AlignLeft)
        # Period
        box.addWidget(QLabel(self.tr("Período (ms):")), 2, 0)
        self.slider_caret_period = QSlider(Qt.Horizontal)
        self.slider_caret_period.setMaximum(500)
        self.slider_caret_period.setFixedWidth(300)
        box.addWidget(self.slider_caret_period, 2, 1, Qt.AlignLeft)
        lcd_caret = QLCDNumber()
        lcd_caret.setSegmentStyle(QLCDNumber.Flat)
        box.addWidget(lcd_caret, 2, 3)

        # Font
        group_typo = QGroupBox(self.tr("Fuente:"))
        box = QGridLayout(group_typo)
        box.setContentsMargins(20, 5, 20, 5)
        box.addWidget(QLabel(self.tr("Familia:")), 0, 0)
        self.combo_font = QFontComboBox()
        self.combo_font.setFixedWidth(350)
        box.addWidget(self.combo_font, 0, 1)
        self._load_font()
        box.addWidget(QLabel(self.tr("Tamaño:")), 1, 0)
        self.spin_size_font = QSpinBox()
        self.spin_size_font.setValue(settings.get_setting('editor/size-font'))
        self.spin_size_font.setFixedWidth(350)
        box.addWidget(self.spin_size_font, 1, 1)
        box.setAlignment(Qt.AlignLeft)

        # Scheme
        group_scheme = QGroupBox(self.tr("Tema:"))
        box = QVBoxLayout(group_scheme)
        box.setContentsMargins(20, 5, 20, 5)
        self.combo_scheme = QComboBox()
        self.combo_scheme.setFixedWidth(350)
        self.combo_scheme.addItems(['Dark Edis', 'White Edis'])
        scheme = settings.get_setting('editor/scheme')
        index = 0
        if scheme != 'dark':
            index = 1
        self.combo_scheme.setCurrentIndex(index)
        box.addWidget(self.combo_scheme)
        box.addWidget(QLabel(self.tr("Requiere reiniciar Edis")))

        ## Agrupación
        main_container.addWidget(group_indentation)
        main_container.addWidget(group_minimap)
        main_container.addWidget(group_caret)
        main_container.addWidget(group_typo)
        main_container.addWidget(group_scheme)
        main_container.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding,
                               QSizePolicy.Expanding))

        EditorConfiguration.install_widget(self.tr("General"), self)

        # Conexiones
        self.combo_scheme.currentIndexChanged['const QString&'].connect(
            self._change_scheme)
        self.combo_caret.currentIndexChanged[int].connect(
            self._caret_type_changed)
        self.slider_caret_period.valueChanged[int].connect(
            lcd_caret.display)

        self.slider_caret_period.setValue(
            settings.get_setting('editor/cursor-period'))

    def _change_scheme(self, theme):
        theme = theme.split()[0].lower()
        editor_container = Edis.get_component("principal")
        editor = editor_container.get_active_editor()
        if editor is not None:
            # Restyle
            pass

    def _caret_type_changed(self, index):
        self.spin_caret_width.setEnabled(bool(index))

    def _load_font(self):

        font = settings.get_setting('editor/font')
        self.combo_font.setCurrentFont(QFont(font))

    def save(self):
        """ Guarda las configuraciones del Editor. """

        use_tabs = bool(self.combo_tabs.currentIndex())
        settings.set_setting('editor/usetabs', use_tabs)
        auto_indent = self.check_autoindent.isChecked()
        settings.set_setting('editor/indent', auto_indent)
        settings.set_setting('editor/minimap', self.check_minimap.isChecked())
        #settings.set_setting('editor/minimap-animation',
                             #self.check_minimap_animation.isChecked())
        font = self.combo_font.currentFont().family()
        settings.set_setting('editor/font', font)
        font_size = self.spin_size_font.value()
        settings.set_setting('editor/size-font', font_size)
        scheme = self.combo_scheme.currentText().split()[0].lower()
        settings.set_setting('editor/scheme', scheme)
        settings.set_setting('editor/cursor',
                             self.combo_caret.currentIndex())
        settings.set_setting('editor/caret-width',
                             self.spin_caret_width.value())
        settings.set_setting('editor/cursor-period',
                             self.slider_caret_period.value())
        editor_container = Edis.get_component("principal")
        editor = editor_container.get_active_editor()
        if editor is not None:
            editor.setIndentationsUseTabs(use_tabs)
            editor.load_font(font, font_size)
Example #25
0
class QuadStatusBar(QHBoxLayout):
    positionChanged = pyqtSignal(int, int, int) # x,y,z
    
    def __init__(self, parent=None ):
        QHBoxLayout.__init__(self, parent)
        self.setContentsMargins(0,4,0,0)
        self.setSpacing(0)
        self.timeControlFontSize = 12

    def showXYCoordinates(self):
        self.zLabel.setHidden(True)
        self.zSpinBox.setHidden(True)
        
    def showXYZCoordinates(self):
        self.zLabel.setHidden(False)
        self.zSpinBox.setHidden(False)
    
    def hideTimeSlider(self,flag):
        self.timeSlider.setHidden(flag)
        self.timeEndButton.setHidden(flag)
        self.timeStartButton.setHidden(flag)

    def setToolTipTimeButtonsCrop(self,croppingFlag=False):
        if croppingFlag==True:
            self.timeStartButton.setToolTip("Set the time coordinate to the beginning of the current crop.")
            self.timeEndButton.setToolTip("Set the time coordinate to the end of the current crop.")
            self.timePreviousButton.setToolTip("Set the time coordinate to the previous time frame.")
            self.timeNextButton.setToolTip("Set the time coordinate to the next time frame.")
        else:
            self.timeStartButton.setToolTip("Set the time coordinate to the beginning of the current dataset.")
            self.timeEndButton.setToolTip("Set the time coordinate to the end of the current dataset.")
            self.timePreviousButton.setToolTip("Set the time coordinate to the previous time frame.")
            self.timeNextButton.setToolTip("Set the time coordinate to the next time frame.")

    def setToolTipTimeSliderCrop(self,croppingFlag=False):
        if croppingFlag==True:
            self.timeSlider.setToolTip("Choose the time coordinate of the current crop.")
        else:
            self.timeSlider.setToolTip("Choose the time coordinate of the current dataset.")

    def createQuadViewStatusBar(self,
                                xbackgroundColor, xforegroundColor,
                                ybackgroundColor, yforegroundColor,
                                zbackgroundColor, zforegroundColor):
        self.xLabel, self.xSpinBox = _get_pos_widget('X',
                                                     xbackgroundColor,
                                                     xforegroundColor)
        self.yLabel, self.ySpinBox = _get_pos_widget('Y',
                                                     ybackgroundColor,
                                                     yforegroundColor)
        self.zLabel, self.zSpinBox = _get_pos_widget('Z',
                                                     zbackgroundColor,
                                                     zforegroundColor)
        
        self.xSpinBox.delayedValueChanged.connect( partial(self._handlePositionBoxValueChanged, 'x') )
        self.ySpinBox.delayedValueChanged.connect( partial(self._handlePositionBoxValueChanged, 'y') )
        self.zSpinBox.delayedValueChanged.connect( partial(self._handlePositionBoxValueChanged, 'z') )

        self.addWidget(self.xLabel)
        self.addWidget(self.xSpinBox)
        self.addWidget(self.yLabel)
        self.addWidget(self.ySpinBox)
        self.addWidget(self.zLabel)
        self.addWidget(self.zSpinBox)

        self.addSpacing(10)

        self.busyIndicator = QProgressBar()
        self.busyIndicator.setMaximumWidth(200)
        self.busyIndicator.setMaximum(0)
        self.busyIndicator.setMinimum(0)
        self.busyIndicator.setVisible(False)
        self.busyIndicator.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.addWidget( self.busyIndicator )
        self.setStretchFactor(self.busyIndicator, 1)

        self.addStretch()
        self.addSpacing(10)

        self.positionCheckBox = QCheckBox()
        self.positionCheckBox.setChecked(False)
        self.positionCheckBox.setCheckable(True)
        self.positionCheckBox.setText("Position")
        self.addWidget(self.positionCheckBox)

        self.addSpacing(20)

        self.timeSpinBox = DelayedSpinBox(750)

        self.timeStartButton = QPushButton("|<")
        self.addWidget(self.timeStartButton)
        self.timeStartButton.clicked.connect(self._onTimeStartButtonClicked)

        self.timePreviousButton = QPushButton("<")
        self.addWidget(self.timePreviousButton)
        self.timePreviousButton.clicked.connect(self._onTimePreviousButtonClicked)
        self.timePreviousButton.setFixedWidth(4*self.timeControlFontSize)

        self.timeSlider = QSlider(Qt.Horizontal)
        self.timeSlider.setMinimumWidth(10)
        self.timeSlider.setMaximumWidth(200)
        self.setToolTipTimeSliderCrop()
        self.addWidget(self.timeSlider)
        self.timeSlider.valueChanged.connect(self._onTimeSliderChanged)

        self.timeNextButton = QPushButton(">")
        self.addWidget(self.timeNextButton)
        self.timeNextButton.clicked.connect(self._onTimeNextButtonClicked)
        self.timeNextButton.setFixedWidth(4*self.timeControlFontSize)

        self.timeEndButton = QPushButton(">|")
        self.timeEndButton.setFixedWidth(4*self.timeControlFontSize)

        self.timeStartButton.setFixedWidth(4*self.timeControlFontSize)
        
        self.setToolTipTimeButtonsCrop()
        self.addWidget(self.timeEndButton)
        self.timeEndButton.clicked.connect(self._onTimeEndButtonClicked)

        self.timeLabel = QLabel("       Time:")
        self.addWidget(self.timeLabel)

        timeControlFont = self.timeSpinBox.font()
        if self.timeControlFontSize > timeControlFont.pointSize():
            timeControlFont.setPixelSize(2*self.timeControlFontSize)
            self.timeStartButton.setFont(timeControlFont)
            self.timeEndButton.setFont(timeControlFont)
            self.timeLabel.setFont(timeControlFont)
            self.timeSpinBox.setFont(timeControlFont)

        self.addWidget(self.timeSpinBox)
        self.timeSpinBox.delayedValueChanged.connect(self._onTimeSpinBoxChanged)

    def _onTimeStartButtonClicked(self):
        self.timeSpinBox.setValue(self.parent().parent().parent().editor.cropModel.get_roi_t()[0])

    def _onTimeEndButtonClicked(self):
        self.timeSpinBox.setValue(self.parent().parent().parent().editor.cropModel.get_roi_t()[1])

    def _onTimePreviousButtonClicked(self):
        self.timeSpinBox.setValue(self.timeSpinBox.value()-1)

    def _onTimeNextButtonClicked(self):
        self.timeSpinBox.setValue(self.timeSpinBox.value()+1)

    def _onTimeSpinBoxChanged(self):
        editor = self.parent().parent().parent().editor
        cropModel = editor.cropModel
        minValueT = cropModel.get_roi_t()[0]
        maxValueT = cropModel.get_roi_t()[1]

        if cropModel.get_scroll_time_outside_crop():
            if minValueT > self.timeSpinBox.value() or maxValueT < self.timeSpinBox.value():
                for imgView in editor.imageViews:
                    imgView._croppingMarkers._shading_item.set_paint_full_frame(True)
            else:
                for imgView in editor.imageViews:
                    imgView._croppingMarkers._shading_item.set_paint_full_frame(False)
            self.timeSlider.setValue(self.timeSpinBox.value())
        else:
            for imgView in editor.imageViews:
                imgView._croppingMarkers._shading_item.set_paint_full_frame(False)
            if minValueT > self.timeSpinBox.value():
                self.timeSlider.setValue(minValueT)
            elif maxValueT < self.timeSpinBox.value():
                self.timeSlider.setValue(maxValueT)
            elif minValueT <= self.timeSpinBox.value() and self.timeSpinBox.value() <= maxValueT:
                self.timeSlider.setValue(self.timeSpinBox.value())

    def _onTimeSliderChanged(self):
        cropModel = self.parent().parent().parent().editor.cropModel
        minValueT = cropModel.get_roi_t()[0]
        maxValueT = cropModel.get_roi_t()[1]

        if cropModel.get_scroll_time_outside_crop():
            self.timeSpinBox.setValue(self.timeSlider.value())
        else:
            if minValueT > self.timeSlider.value():
                self.timeSpinBox.setValue(minValueT)
                self.timeSlider.setValue(minValueT)
            elif self.timeSlider.value() > maxValueT:
                self.timeSpinBox.setValue(maxValueT)
                self.timeSlider.setValue(maxValueT)
            elif minValueT <= self.timeSlider.value() and self.timeSlider.value() <= maxValueT:
                self.timeSpinBox.setValue(self.timeSlider.value())

    def _handlePositionBoxValueChanged(self, axis, value):
        new_position = [self.xSpinBox.value(), self.ySpinBox.value(), self.zSpinBox.value()]
        changed_axis = ord(axis) - ord('x')
        new_position[changed_axis] = value
        self.positionChanged.emit(*new_position)

    def updateShape5D(self, shape5D):
        self.timeSpinBox.setMaximum(shape5D[0]-1)
        self.xSpinBox.setMaximum(shape5D[1]-1)
        self.ySpinBox.setMaximum(shape5D[2]-1)
        self.zSpinBox.setMaximum(shape5D[3]-1)

    def updateShape5Dcropped(self, shape5DcropMin, shape5Dmax):
        self.timeSpinBox.setMaximum(shape5Dmax[0]-1)
        self.xSpinBox.setMaximum(shape5Dmax[1]-1)
        self.ySpinBox.setMaximum(shape5Dmax[2]-1)
        self.zSpinBox.setMaximum(shape5Dmax[3]-1)
        self.timeSlider.setMaximum(shape5Dmax[0]-1)

        self.timeSpinBox.setValue(shape5DcropMin[0])
        self.xSpinBox.setValue(shape5DcropMin[1])
        self.ySpinBox.setValue(shape5DcropMin[2])
        self.zSpinBox.setValue(shape5DcropMin[3])
        self.timeSlider.setValue(shape5DcropMin[0])

    def setMouseCoords(self, x, y, z):
        self.xSpinBox.setValueWithoutSignal(x)
        self.ySpinBox.setValueWithoutSignal(y)
        self.zSpinBox.setValueWithoutSignal(z)
Example #26
0
 def setMaximum(self, value):
   QSlider.setMaximum(self, self.convert(value))
class QuadStatusBar(QHBoxLayout):
    positionChanged = pyqtSignal(int, int, int)  # x,y,z

    def __init__(self, parent=None):
        QHBoxLayout.__init__(self, parent)
        self.setContentsMargins(0, 4, 0, 0)
        self.setSpacing(0)
        self.timeControlFontSize = 12

    def showXYCoordinates(self):
        self.zLabel.setHidden(True)
        self.zSpinBox.setHidden(True)

    def showXYZCoordinates(self):
        self.zLabel.setHidden(False)
        self.zSpinBox.setHidden(False)

    def hideTimeSlider(self, flag):
        visibleBefore = not self.timeSlider.isHidden()
        self.timeSlider.setHidden(flag)
        self.timeEndButton.setHidden(flag)
        self.timeStartButton.setHidden(flag)
        self.timePreviousButton.setHidden(flag)
        self.timeNextButton.setHidden(flag)
        self._registerTimeframeShortcuts(enabled=not flag,
                                         remove=visibleBefore)

    def setToolTipTimeButtonsCrop(self, croppingFlag=False):
        if croppingFlag == True:
            self.timeStartButton.setToolTip(
                "Jump to lirst frame of current crop")
            self.timeEndButton.setToolTip("Jump to last frame of current crop")
            self.timePreviousButton.setToolTip("Previous Frame")
            self.timeNextButton.setToolTip("Next Frame")
        else:
            self.timeStartButton.setToolTip("First Frame")
            self.timeEndButton.setToolTip("Last Frame")
            self.timePreviousButton.setToolTip("Previous Frame")
            self.timeNextButton.setToolTip("Next Frame")

    def setToolTipTimeSliderCrop(self, croppingFlag=False):
        if croppingFlag == True:
            self.timeSlider.setToolTip(
                "Choose the time coordinate of the current crop.")
        else:
            self.timeSlider.setToolTip(
                "Choose the time coordinate of the current dataset.")

    def createQuadViewStatusBar(self, xbackgroundColor, xforegroundColor,
                                ybackgroundColor, yforegroundColor,
                                zbackgroundColor, zforegroundColor):
        self.xLabel, self.xSpinBox = _get_pos_widget('X', xbackgroundColor,
                                                     xforegroundColor)
        self.yLabel, self.ySpinBox = _get_pos_widget('Y', ybackgroundColor,
                                                     yforegroundColor)
        self.zLabel, self.zSpinBox = _get_pos_widget('Z', zbackgroundColor,
                                                     zforegroundColor)

        self.xSpinBox.delayedValueChanged.connect(
            partial(self._handlePositionBoxValueChanged, 'x'))
        self.ySpinBox.delayedValueChanged.connect(
            partial(self._handlePositionBoxValueChanged, 'y'))
        self.zSpinBox.delayedValueChanged.connect(
            partial(self._handlePositionBoxValueChanged, 'z'))

        self.addWidget(self.xLabel)
        self.addWidget(self.xSpinBox)
        self.addWidget(self.yLabel)
        self.addWidget(self.ySpinBox)
        self.addWidget(self.zLabel)
        self.addWidget(self.zSpinBox)

        self.addSpacing(10)

        self.crosshairsCheckbox = QCheckBox()
        self.crosshairsCheckbox.setChecked(False)
        self.crosshairsCheckbox.setCheckable(True)
        self.crosshairsCheckbox.setText("Crosshairs")
        self.addWidget(self.crosshairsCheckbox)

        self.addSpacing(10)

        self.busyIndicator = QProgressBar()
        self.busyIndicator.setMaximumWidth(200)
        self.busyIndicator.setMaximum(0)
        self.busyIndicator.setMinimum(0)
        self.busyIndicator.setVisible(False)
        self.busyIndicator.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
        self.addWidget(self.busyIndicator)
        self.setStretchFactor(self.busyIndicator, 1)

        self.addStretch()

        self.addSpacing(20)

        self.timeSpinBox = DelayedSpinBox(750)

        icons_dir = os.path.dirname(volumina.__file__) + "/icons"

        self.timeStartButton = QToolButton()
        self.timeStartButton.setIcon(QIcon(icons_dir + "/skip-start.png"))
        self.addWidget(self.timeStartButton)
        self.timeStartButton.clicked.connect(self._onTimeStartButtonClicked)
        #self.timeStartButton.setFixedWidth(4*self.timeControlFontSize)

        self.timePreviousButton = QToolButton()
        self.timePreviousButton.setIcon(QIcon(icons_dir + "/play-reverse.png"))
        self.addWidget(self.timePreviousButton)
        self.timePreviousButton.clicked.connect(
            self._onTimePreviousButtonClicked)
        #self.timePreviousButton.setFixedWidth(4*self.timeControlFontSize)

        self.timeSlider = QSlider(Qt.Horizontal)
        self.timeSlider.setMinimumWidth(10)
        self.timeSlider.setMaximumWidth(200)
        self.setToolTipTimeSliderCrop()
        self.addWidget(self.timeSlider)
        self.timeSlider.valueChanged.connect(self._onTimeSliderChanged)

        self.timeNextButton = QToolButton()
        self.timeNextButton.setIcon(QIcon(icons_dir + "/play.png"))
        self.addWidget(self.timeNextButton)
        self.timeNextButton.clicked.connect(self._onTimeNextButtonClicked)
        #self.timeNextButton.setFixedWidth(4*self.timeControlFontSize)

        self.timeEndButton = QToolButton()
        self.timeEndButton.setIcon(QIcon(icons_dir + "/skip-end.png"))
        #self.timeEndButton.setFixedWidth(4*self.timeControlFontSize)

        self.setToolTipTimeButtonsCrop()
        self.addWidget(self.timeEndButton)
        self.timeEndButton.clicked.connect(self._onTimeEndButtonClicked)

        self.timeLabel = QLabel("       Time:")
        self.addWidget(self.timeLabel)

        timeControlFont = self.timeSpinBox.font()
        if self.timeControlFontSize > timeControlFont.pointSize():
            timeControlFont.setPixelSize(2 * self.timeControlFontSize)
            self.timeStartButton.setFont(timeControlFont)
            self.timeEndButton.setFont(timeControlFont)
            self.timeLabel.setFont(timeControlFont)
            self.timeSpinBox.setFont(timeControlFont)

        self.addWidget(self.timeSpinBox)
        self.timeSpinBox.delayedValueChanged.connect(
            self._onTimeSpinBoxChanged)

        self._registerTimeframeShortcuts()

    def _registerTimeframeShortcuts(self, enabled=True, remove=True):
        """ Register or deregister "," and "." as keyboard shortcuts for scrolling in time """
        mgr = ShortcutManager()
        ActionInfo = ShortcutManager.ActionInfo

        def action(key, actionInfo):
            if enabled:
                mgr.register(key, actionInfo)
            else:
                if remove:
                    mgr.unregister(actionInfo)

        action(
            "<",
            ActionInfo("Navigation", "Go to next time frame",
                       "Go to next time frame", self._onTimeNextButtonClicked,
                       self.timeNextButton, self.timeNextButton))
        action(
            ">",
            ActionInfo("Navigation", "Go to previous time frame",
                       "Go to previous time frame",
                       self._onTimePreviousButtonClicked,
                       self.timePreviousButton, self.timePreviousButton))

    def _onTimeStartButtonClicked(self):
        self.timeSpinBox.setValue(
            self.parent().parent().parent().editor.cropModel.get_roi_t()[0])

    def _onTimeEndButtonClicked(self):
        self.timeSpinBox.setValue(
            self.parent().parent().parent().editor.cropModel.get_roi_t()[1])

    def _onTimePreviousButtonClicked(self):
        self.timeSpinBox.setValue(self.timeSpinBox.value() - 1)

    def _onTimeNextButtonClicked(self):
        self.timeSpinBox.setValue(self.timeSpinBox.value() + 1)

    def _onTimeSpinBoxChanged(self):
        editor = self.parent().parent().parent().editor
        cropModel = editor.cropModel
        minValueT = cropModel.get_roi_t()[0]
        maxValueT = cropModel.get_roi_t()[1]

        if cropModel.get_scroll_time_outside_crop():
            if minValueT > self.timeSpinBox.value(
            ) or maxValueT < self.timeSpinBox.value():
                for imgView in editor.imageViews:
                    imgView._croppingMarkers._shading_item.set_paint_full_frame(
                        True)
            else:
                for imgView in editor.imageViews:
                    imgView._croppingMarkers._shading_item.set_paint_full_frame(
                        False)
            self.timeSlider.setValue(self.timeSpinBox.value())
        else:
            for imgView in editor.imageViews:
                imgView._croppingMarkers._shading_item.set_paint_full_frame(
                    False)
            if minValueT > self.timeSpinBox.value():
                self.timeSlider.setValue(minValueT)
            elif maxValueT < self.timeSpinBox.value():
                self.timeSlider.setValue(maxValueT)
            elif minValueT <= self.timeSpinBox.value(
            ) and self.timeSpinBox.value() <= maxValueT:
                self.timeSlider.setValue(self.timeSpinBox.value())

    def _onTimeSliderChanged(self):
        cropModel = self.parent().parent().parent().editor.cropModel
        minValueT = cropModel.get_roi_t()[0]
        maxValueT = cropModel.get_roi_t()[1]

        if cropModel.get_scroll_time_outside_crop():
            self.timeSpinBox.setValue(self.timeSlider.value())
        else:
            if minValueT > self.timeSlider.value():
                self.timeSpinBox.setValue(minValueT)
                self.timeSlider.setValue(minValueT)
            elif self.timeSlider.value() > maxValueT:
                self.timeSpinBox.setValue(maxValueT)
                self.timeSlider.setValue(maxValueT)
            elif minValueT <= self.timeSlider.value(
            ) and self.timeSlider.value() <= maxValueT:
                self.timeSpinBox.setValue(self.timeSlider.value())

    def _handlePositionBoxValueChanged(self, axis, value):
        new_position = [
            self.xSpinBox.value(),
            self.ySpinBox.value(),
            self.zSpinBox.value()
        ]
        changed_axis = ord(axis) - ord('x')
        new_position[changed_axis] = value
        self.positionChanged.emit(*new_position)

    def updateShape5D(self, shape5D):
        self.timeSpinBox.setMaximum(shape5D[0] - 1)
        self.xSpinBox.setMaximum(shape5D[1] - 1)
        self.ySpinBox.setMaximum(shape5D[2] - 1)
        self.zSpinBox.setMaximum(shape5D[3] - 1)

    def updateShape5Dcropped(self, shape5DcropMin, shape5Dmax):
        self.timeSpinBox.setMaximum(shape5Dmax[0] - 1)
        self.xSpinBox.setMaximum(shape5Dmax[1] - 1)
        self.ySpinBox.setMaximum(shape5Dmax[2] - 1)
        self.zSpinBox.setMaximum(shape5Dmax[3] - 1)
        self.timeSlider.setMaximum(shape5Dmax[0] - 1)

        self.timeSpinBox.setValue(shape5DcropMin[0])
        self.xSpinBox.setValue(shape5DcropMin[1])
        self.ySpinBox.setValue(shape5DcropMin[2])
        self.zSpinBox.setValue(shape5DcropMin[3])
        self.timeSlider.setValue(shape5DcropMin[0])

    def setMouseCoords(self, x, y, z):
        self.xSpinBox.setValueWithoutSignal(x)
        self.ySpinBox.setValueWithoutSignal(y)
        self.zSpinBox.setValueWithoutSignal(z)
class ChooseThresholdsUI(QMainWindow):
    def __init__(self):
        super().__init__()

        self.baseImages = []

        self.SobelXTh = [0, 255]

        self.SobelYTh = [0, 255]

        self.SobelMTh = [0, 255]

        self.SobelATh = [0, 255]

        self.initUI()

    @pyqtSlot()
    def openNewFileDialog(self, index):
        """ @brief slot with open new file dialog
        """
        directory = os.path.dirname(self.loadFileLine[index].text())
        fileName = QFileDialog.getOpenFileName(self, 'Choose image', directory,
                                               'All files (*)')
        if isinstance(fileName, tuple):  # for PyQt5
            if fileName[0]:
                self.loadFileLine[index].setText(fileName[0])
        else:  # for PyQt4
            if fileName:
                self.loadFileLine[index].setText(fileName)

    @pyqtSlot()
    def loadImage(self):

        self.baseImages = []
        for i in range(0, 4):
            if (i > 0):
                if not self.loadFileCB[i - 1].isChecked():
                    continue
            image = cv2.imread(self.loadFileLine[i].text())
            if image is not None:
                self.baseImages.append(image)
        if len(self.baseImages) != 0:
            self.updateImage()

    @pyqtSlot()
    def sliderChange(self):
        self.SobelXTh[0] = self.slider1SobelX.value()
        self.SobelXTh[1] = self.slider2SobelX.value()
        self.labelSobelX.setText("SobelX th: {:03d} {:03d}".format(
            self.SobelXTh[0], self.SobelXTh[1]))

        self.SobelYTh[0] = self.slider1SobelY.value()
        self.SobelYTh[1] = self.slider2SobelY.value()
        self.labelSobelY.setText("SobelY th: {:03d} {:03d}".format(
            self.SobelYTh[0], self.SobelYTh[1]))

        self.SobelMTh[0] = self.slider1SobelM.value()
        self.SobelMTh[1] = self.slider2SobelM.value()
        self.labelSobelM.setText("SobelM th: {:03d} {:03d}".format(
            self.SobelMTh[0], self.SobelMTh[1]))

        self.SobelATh[0] = self.slider1SobelA.value() * np.pi / 510
        self.SobelATh[1] = self.slider2SobelA.value() * np.pi / 510
        self.labelSobelA.setText("SobelA th: {:1.3f} {:1.3f}".format(
            self.SobelATh[0], self.SobelATh[1]))

        self.updateImage()

    def initUI(self):

        # Choose file dialog
        loadFileBtn = QPushButton("Load files:")
        loadFileBtn.clicked.connect(self.loadImage)

        self.loadFileLine = []
        loadFileDialogBtn = []
        self.loadFileCB = []
        for i in range(0, 4):
            self.loadFileLine.append(QLineEdit(""))
            loadFileDialogBtn.append(QPushButton("..."))
            loadFileDialogBtn[i].setMaximumWidth(40)
            if (i > 0):
                self.loadFileCB.append(QCheckBox())
                # self.loadFileCB[i-1].stateChanged.connect(self.updateImage)
        loadFileDialogBtn[0].clicked.connect(lambda: self.openNewFileDialog(0))
        loadFileDialogBtn[1].clicked.connect(lambda: self.openNewFileDialog(1))
        loadFileDialogBtn[2].clicked.connect(lambda: self.openNewFileDialog(2))
        loadFileDialogBtn[3].clicked.connect(lambda: self.openNewFileDialog(3))
        loadFileDialogBtn[1].clicked.connect(
            lambda: self.loadFileCB[0].setChecked(True))
        loadFileDialogBtn[2].clicked.connect(
            lambda: self.loadFileCB[1].setChecked(True))
        loadFileDialogBtn[3].clicked.connect(
            lambda: self.loadFileCB[2].setChecked(True))

        self.labelImage = QLabel()

        labelChannels = QLabel("Channels:")
        self.comboChannel0 = QComboBox()
        self.comboChannel0.addItems(['G', 'L', 'S'])
        self.comboChannel0.currentIndexChanged.connect(self.updateImage)
        self.comboChannel1 = QComboBox()
        self.comboChannel1.addItems(['G', 'L', 'S'])
        self.comboChannel1.currentIndexChanged.connect(self.updateImage)
        self.comboChannel2 = QComboBox()
        self.comboChannel2.addItems(['G', 'L', 'S'])
        self.comboChannel2.currentIndexChanged.connect(self.updateImage)

        labelKernels = QLabel("Kernels:")
        self.kernel0SB = QSpinBox()
        self.kernel0SB.setMinimum(1)
        self.kernel0SB.setMaximum(31)
        self.kernel0SB.setValue(15)
        self.kernel0SB.setSingleStep(2)
        self.kernel0SB.valueChanged.connect(self.updateImage)
        self.kernel1SB = QSpinBox()
        self.kernel1SB.setMinimum(1)
        self.kernel1SB.setMaximum(31)
        self.kernel1SB.setValue(15)
        self.kernel1SB.setSingleStep(2)
        self.kernel1SB.valueChanged.connect(self.updateImage)
        self.kernel2SB = QSpinBox()
        self.kernel2SB.setMinimum(1)
        self.kernel2SB.setMaximum(31)
        self.kernel2SB.setValue(15)
        self.kernel2SB.setSingleStep(2)
        self.kernel2SB.valueChanged.connect(self.updateImage)

        self.labelSobelX = QLabel()
        self.chboxSobelX0 = QCheckBox()
        self.chboxSobelX0.stateChanged.connect(self.updateImage)
        self.chboxSobelX1 = QCheckBox()
        self.chboxSobelX1.stateChanged.connect(self.updateImage)
        self.chboxSobelX2 = QCheckBox()
        self.chboxSobelX2.stateChanged.connect(self.updateImage)
        self.slider1SobelX = QSlider(Qt.Horizontal)
        self.slider1SobelX.setMinimum(0)
        self.slider1SobelX.setMaximum(255)
        self.slider1SobelX.setValue(20)
        self.slider1SobelX.valueChanged.connect(self.sliderChange)
        self.slider2SobelX = QSlider(Qt.Horizontal)
        self.slider2SobelX.setMinimum(0)
        self.slider2SobelX.setMaximum(255)
        self.slider2SobelX.setValue(100)
        self.slider2SobelX.valueChanged.connect(self.sliderChange)

        self.labelSobelY = QLabel()
        self.chboxSobelY0 = QCheckBox()
        self.chboxSobelY0.stateChanged.connect(self.updateImage)
        self.chboxSobelY1 = QCheckBox()
        self.chboxSobelY1.stateChanged.connect(self.updateImage)
        self.chboxSobelY2 = QCheckBox()
        self.chboxSobelY2.stateChanged.connect(self.updateImage)
        self.slider1SobelY = QSlider(Qt.Horizontal)
        self.slider1SobelY.setMinimum(0)
        self.slider1SobelY.setMaximum(255)
        self.slider1SobelY.setValue(20)
        self.slider1SobelY.valueChanged.connect(self.sliderChange)
        self.slider2SobelY = QSlider(Qt.Horizontal)
        self.slider2SobelY.setMinimum(0)
        self.slider2SobelY.setMaximum(255)
        self.slider2SobelY.setValue(100)
        self.slider2SobelY.valueChanged.connect(self.sliderChange)

        self.labelSobelM = QLabel()
        self.chboxSobelM0 = QCheckBox()
        self.chboxSobelM0.stateChanged.connect(self.updateImage)
        self.chboxSobelM1 = QCheckBox()
        self.chboxSobelM1.stateChanged.connect(self.updateImage)
        self.chboxSobelM2 = QCheckBox()
        self.chboxSobelM2.stateChanged.connect(self.updateImage)
        self.slider1SobelM = QSlider(Qt.Horizontal)
        self.slider1SobelM.setMinimum(0)
        self.slider1SobelM.setMaximum(255)
        self.slider1SobelM.setValue(30)
        self.slider1SobelM.valueChanged.connect(self.sliderChange)
        self.slider2SobelM = QSlider(Qt.Horizontal)
        self.slider2SobelM.setMinimum(0)
        self.slider2SobelM.setMaximum(255)
        self.slider2SobelM.setValue(100)
        self.slider2SobelM.valueChanged.connect(self.sliderChange)

        self.labelSobelA = QLabel()
        self.chboxSobelA0 = QCheckBox()
        self.chboxSobelA0.stateChanged.connect(self.updateImage)
        self.chboxSobelA1 = QCheckBox()
        self.chboxSobelA1.stateChanged.connect(self.updateImage)
        self.chboxSobelA2 = QCheckBox()
        self.chboxSobelA2.stateChanged.connect(self.updateImage)
        self.slider1SobelA = QSlider(Qt.Horizontal)
        self.slider1SobelA.setMinimum(0)
        self.slider1SobelA.setMaximum(255)
        self.slider1SobelA.setValue(int(0.7 / np.pi * 510))
        self.slider1SobelA.valueChanged.connect(self.sliderChange)
        self.slider2SobelA = QSlider(Qt.Horizontal)
        self.slider2SobelA.setMinimum(0)
        self.slider2SobelA.setMaximum(255)
        self.slider2SobelA.setValue(int(1.3 / np.pi * 510))
        self.slider2SobelA.valueChanged.connect(self.sliderChange)

        self.sliderChange()

        # Layouts
        layoutMain = QVBoxLayout()
        layoutMain2 = QHBoxLayout()
        layoutSettings = QVBoxLayout()
        layoutChannels = QHBoxLayout()
        layoutKernelSB = QHBoxLayout()
        layoutChboxSobelX = QHBoxLayout()
        layoutChboxSobelY = QHBoxLayout()
        layoutChboxSobelM = QHBoxLayout()
        layoutChboxSobelA = QHBoxLayout()

        layoutsChooseFile = []
        for i in range(0, 4):
            layoutsChooseFile.append(QHBoxLayout())
            if i == 0:
                layoutsChooseFile[i].addWidget(loadFileBtn)
            else:
                layoutsChooseFile[i].addWidget(self.loadFileCB[i - 1])
            layoutsChooseFile[i].addWidget(self.loadFileLine[i])
            layoutsChooseFile[i].addWidget(loadFileDialogBtn[i])
            layoutMain.addLayout(layoutsChooseFile[i])

        layoutMain.addLayout(layoutMain2, 1)

        layoutMain2.addWidget(self.labelImage, 1)
        layoutMain2.addLayout(layoutSettings)

        layoutSettings.addWidget(labelChannels)
        layoutSettings.addLayout(layoutChannels)
        layoutChannels.addWidget(self.comboChannel0)
        layoutChannels.addWidget(self.comboChannel1)
        layoutChannels.addWidget(self.comboChannel2)
        layoutSettings.addWidget(labelKernels)
        layoutSettings.addLayout(layoutKernelSB)
        layoutKernelSB.addWidget(self.kernel0SB)
        layoutKernelSB.addWidget(self.kernel1SB)
        layoutKernelSB.addWidget(self.kernel2SB)
        layoutSettings.addWidget(self.labelSobelX)
        layoutSettings.addLayout(layoutChboxSobelX)
        layoutChboxSobelX.addWidget(self.chboxSobelX0)
        layoutChboxSobelX.addWidget(self.chboxSobelX1)
        layoutChboxSobelX.addWidget(self.chboxSobelX2)
        layoutSettings.addWidget(self.slider1SobelX)
        layoutSettings.addWidget(self.slider2SobelX)
        layoutSettings.addWidget(self.labelSobelY)
        layoutSettings.addLayout(layoutChboxSobelY)
        layoutChboxSobelY.addWidget(self.chboxSobelY0)
        layoutChboxSobelY.addWidget(self.chboxSobelY1)
        layoutChboxSobelY.addWidget(self.chboxSobelY2)
        layoutSettings.addWidget(self.slider1SobelY)
        layoutSettings.addWidget(self.slider2SobelY)
        layoutSettings.addWidget(self.labelSobelM)
        layoutSettings.addLayout(layoutChboxSobelM)
        layoutChboxSobelM.addWidget(self.chboxSobelM0)
        layoutChboxSobelM.addWidget(self.chboxSobelM1)
        layoutChboxSobelM.addWidget(self.chboxSobelM2)
        layoutSettings.addWidget(self.slider1SobelM)
        layoutSettings.addWidget(self.slider2SobelM)
        layoutSettings.addWidget(self.labelSobelA)
        layoutSettings.addLayout(layoutChboxSobelA)
        layoutChboxSobelA.addWidget(self.chboxSobelA0)
        layoutChboxSobelA.addWidget(self.chboxSobelA1)
        layoutChboxSobelA.addWidget(self.chboxSobelA2)
        layoutSettings.addWidget(self.slider1SobelA)
        layoutSettings.addWidget(self.slider2SobelA)
        layoutSettings.addStretch(1)

        mainWidget = QWidget()
        mainWidget.setLayout(layoutMain)
        self.setCentralWidget(mainWidget)
        self.showMaximized()

    def selectChannel(self, combo, N):
        if combo.currentText() == 'G':
            im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2GRAY)
        elif combo.currentText() == 'L':
            im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2HLS)[:, :, 1]
        elif combo.currentText() == 'S':
            im = cv2.cvtColor(self.baseImages[N], cv2.COLOR_BGR2HLS)[:, :, 2]
        return im

    def updateOneImg(self, imN):

        changed = False

        if self.chboxSobelX0.isChecked() or self.chboxSobelY0.isChecked() or self.chboxSobelM0.isChecked() or \
                self.chboxSobelA0.isChecked():
            changed = True
            im = self.selectChannel(self.comboChannel0, imN)
            th = pipeline.Tresholds(im, kernel=self.kernel0SB.value())

            im0 = np.ones_like(im, dtype='uint8')
            if self.chboxSobelX0.isChecked():
                im0 = im0 & th.abs_sobel_thresh(orient='x',
                                                thresh=self.SobelXTh)
            if self.chboxSobelY0.isChecked():
                im0 = im0 & th.abs_sobel_thresh(orient='y',
                                                thresh=self.SobelYTh)
            if self.chboxSobelM0.isChecked():
                im0 = im0 & th.mag_thresh(thresh=self.SobelMTh)
            if self.chboxSobelA0.isChecked():
                im0 = im0 & th.dir_threshold(thresh=self.SobelATh)
        else:
            im0 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8')

        if self.chboxSobelX1.isChecked() or self.chboxSobelY1.isChecked() or self.chboxSobelM1.isChecked() or \
                self.chboxSobelA1.isChecked():
            changed = True
            im = self.selectChannel(self.comboChannel1, imN)
            th = pipeline.Tresholds(im, kernel=self.kernel1SB.value())

            im1 = np.ones_like(im, dtype='uint8')
            if self.chboxSobelX1.isChecked():
                im1 = im1 & th.abs_sobel_thresh(orient='x',
                                                thresh=self.SobelXTh)
            if self.chboxSobelY1.isChecked():
                im1 = im1 & th.abs_sobel_thresh(orient='y',
                                                thresh=self.SobelYTh)
            if self.chboxSobelM1.isChecked():
                im1 = im1 & th.mag_thresh(thresh=self.SobelMTh)
            if self.chboxSobelA1.isChecked():
                im1 = im1 & th.dir_threshold(thresh=self.SobelATh)
        else:
            im1 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8')

        if self.chboxSobelX2.isChecked() or self.chboxSobelY2.isChecked() or self.chboxSobelM2.isChecked() or \
                self.chboxSobelA2.isChecked():
            changed = True
            im = self.selectChannel(self.comboChannel2, imN)
            th = pipeline.Tresholds(im, kernel=self.kernel2SB.value())

            im2 = np.ones_like(im, dtype='uint8')
            if self.chboxSobelX2.isChecked():
                im2 = im2 & th.abs_sobel_thresh(orient='x',
                                                thresh=self.SobelXTh)
            if self.chboxSobelY2.isChecked():
                im2 = im2 & th.abs_sobel_thresh(orient='y',
                                                thresh=self.SobelYTh)
            if self.chboxSobelM2.isChecked():
                im2 = im2 & th.mag_thresh(thresh=self.SobelMTh)
            if self.chboxSobelA2.isChecked():
                im2 = im2 & th.dir_threshold(thresh=self.SobelATh)
        else:
            im2 = np.zeros_like(self.baseImages[imN][:, :, 0], dtype='uint8')

        if not changed:
            imf = cv2.cvtColor(self.baseImages[imN], cv2.COLOR_BGR2RGB)
        else:
            imf = np.dstack((im0 * 255, im1 * 255, im2 * 255))

        return imf

    def updateImage(self):

        if len(self.baseImages) == 0:
            return

        imf = []
        for i in range(len(self.baseImages)):
            im = self.updateOneImg(i)
            imf.append(im)

        frameSize = (self.labelImage.size().width(),
                     self.labelImage.size().height(), 3)
        bytesPerLine = 3 * frameSize[0]

        if len(self.baseImages) == 1:
            frameImg = cv2.resize(imf[0], frameSize[0:2])
        else:
            frameImg = np.zeros([frameSize[1], frameSize[0], frameSize[2]],
                                dtype='uint8')
            midy = frameSize[1] // 2
            midx = frameSize[0] // 2
            # frameImg[0:midy, 0:midx, :] = 255
            frameImg[:midy, :midx, :] = cv2.resize(imf[0], (midx, midy))
            frameImg[:midy,
                     midx:midx * 2, :] = cv2.resize(imf[1], (midx, midy))
            if len(self.baseImages) >= 3:
                frameImg[midy:midy * 2, :midx, :] = cv2.resize(
                    imf[2], (midx, midy))
            if len(self.baseImages) >= 4:
                frameImg[midy:midy * 2,
                         midx:midx * 2, :] = cv2.resize(imf[3], (midx, midy))

        qImg = QImage(frameImg, frameSize[0], frameSize[1], bytesPerLine,
                      QImage.Format_RGB888)
        self.labelImage.setPixmap(QPixmap.fromImage(qImg))
class GUI(QWidget):
    def __init__(self, parent=None):
        global f
        f = open(filename, "a")
        f.write("Widget init.\n")
        f.close()
        QWidget.__init__(self, parent, Qt.WindowStaysOnTopHint)
        self.__setup_gui__(self)
        self._flag = False
        self._change = False
        f = open(filename, "a")
        f.write("End of widget init.\n")
        f.close()

    def closeEvent(self, event):
        reply = QMessageBox.question(self, "Confirm",
                                     "Are you sure You want to quit?",
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes: event.accept()
        else: event.ignore()

    def __setup_gui__(self, Dialog):
        global f
        f = open(filename, "a")
        f.write("Setup of gui.\n")
        f.close()
        Dialog.setObjectName("Dialog")
        Dialog.resize(270, 145)
        self.setWindowTitle("Map Layer")
        screen = QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width()) / 2,
                  (screen.height() - size.height()) / 2)
        self.Render = QPushButton("Render", Dialog)
        self.Render.setGeometry(QRect(85, 90, 100, 25))
        self.Render.setObjectName("Render")
        self.comboBox = QComboBox(Dialog)
        self.comboBox.setGeometry(QRect(100, 34, 115, 18))
        self.comboBox.setEditable(False)
        self.comboBox.setMaxVisibleItems(11)
        self.comboBox.setInsertPolicy(QComboBox.InsertAtBottom)
        self.comboBox.setObjectName("comboBox")
        self.comboBox.addItems([
            "Google Roadmap", "Google Terrain", "Google Satellite",
            "Google Hybrid", "Yahoo Roadmap", "Yahoo Satellite",
            "Yahoo Hybrid", "Bing Roadmap", "Bing Satellite", "Bing Hybrid",
            "Open Street Maps"
        ])
        self.comboBox.setCurrentIndex(10)
        self.label1 = QLabel("Source:", Dialog)
        self.label1.setGeometry(QRect(55, 35, 35, 16))
        self.label1.setObjectName("label1")
        self.slider = QSlider(Dialog)
        self.slider.setOrientation(Qt.Horizontal)
        self.slider.setMinimum(1)
        self.slider.setMaximum(12)
        self.slider.setValue(4)
        self.slider.setGeometry(QRect(110, 61, 114, 16))
        self.label2 = QLabel("Quality: " + str(self.slider.value()), Dialog)
        self.label2.setGeometry(QRect(47, 61, 54, 16))
        self.label2.setObjectName("label2")
        self.doubleSpinBox = QDoubleSpinBox(Dialog)
        self.doubleSpinBox.setGeometry(QRect(160, 5, 40, 20))
        self.doubleSpinBox.setDecimals(0)
        self.doubleSpinBox.setObjectName("doubleSpinBox")
        self.doubleSpinBox.setMinimum(10.0)
        self.doubleSpinBox.setValue(20.0)
        self.doubleSpinBox.setEnabled(False)
        self.checkBox = QCheckBox("Auto refresh", Dialog)
        self.checkBox.setGeometry(QRect(50, 6, 100, 20))
        self.checkBox.setLayoutDirection(Qt.RightToLeft)
        self.checkBox.setObjectName("checkBox")
        self.progressBar = QProgressBar(Dialog)
        self.progressBar.setGeometry(QRect(5, 130, 260, 10))
        self.progressBar.setProperty("value", 0)
        self.progressBar.setTextVisible(False)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setVisible(False)
        QObject.connect(self.Render, SIGNAL("clicked()"), Dialog.__repaint__)
        QMetaObject.connectSlotsByName(Dialog)
        QObject.connect(self.slider, SIGNAL("valueChanged(int)"),
                        self.__update_slider_label__)
        QObject.connect(self.comboBox, SIGNAL("activated(int)"),
                        self.__combobox_changed__)
        self.timerRepaint = QTimer()
        QObject.connect(self.checkBox, SIGNAL("clicked()"),
                        self.__activate_timer__)
        QObject.connect(self.timerRepaint, SIGNAL("timeout()"),
                        self.__on_timer__)
        f = open(filename, "a")
        f.write("End of setup of gui.\n")
        f.close()

    def __combobox_changed__(self):
        self._change = True

    def __activate_timer__(self):
        self.doubleSpinBox.setEnabled(self.checkBox.isChecked())
        if self.checkBox.isChecked():
            self.timerRepaint.start(self.doubleSpinBox.value() * 1000)
            self.Render.setEnabled(False)
            if _progress == 0: self.__repaint__()
        else:
            self.timerRepaint.stop()
            self.Render.setEnabled(True)

    def __get_net_size__(self):
        global f
        f = open(filename, "a")
        f.write("Geting net size...\n")
        f.close()
        if not os.path.exists(Paths["Screenshot"]):
            Visum.Graphic.Screenshot(Paths["Screenshot"])
        size = Image.open(Paths["Screenshot"]).size
        f = open(filename, "a")
        f.write("Read net size:" + str(size) + ".\n")
        f.close()
        return size

    def __on_timer__(self):
        global _paramGlobal
        self._flag = False
        Visum.Graphic.MaximizeNetWindow()
        param = _paramGlobal
        _paramGlobal = Visum.Graphic.GetWindow()
        shift = abs((param[0] - _paramGlobal[0]) / (param[2] - param[0]))
        zoom = abs((param[2] - param[0]) /
                   (_paramGlobal[2] - _paramGlobal[0]) - 1)
        print _windowSizeGlobal
        if _windowSizeGlobal[2:4] != Visum.Graphic.GetMainWindowPos()[2:4]:
            self.__get_net_size__()
            self._flag = True
        elif shift > 0.4 or zoom > 0.2:
            self._flag = True
        if self._flag or self._change and _progress == 0:
            self.__repaint__()
            self._change = False

    def __update_slider_label__(self, value):
        self.label2.setText("Quality: " + str(value))
        self._change = True

    def __update_progress_bar__(self):
        if _progress != 0:
            self.progressBar.setVisible(True)
            self.progressBar.setValue(_progress)
        else:
            self.progressBar.setVisible(False)

    def __rebuild_paths__(self):
        global Paths
        Paths["Images"] = []
        list = os.listdir(Paths["ScriptFolder"])
        imageList = []
        for i in range(len(list)):
            if list[i][-3:] == "png": imageList.append(list[i])
        for i in range(len(imageList)):
            try:
                Visum.Graphic.Backgrounds.ItemByKey(imageList[i])
                Paths["Images"].append(Paths["ScriptFolder"] + "\\" +
                                       imageList[i])
            except:
                pass

    def __repaint__(self):
        global _progress, f
        if len(Visum.Graphic.Backgrounds.GetAll) != len(Paths["Images"]):
            self.__rebuild_paths__()
        if _progress == 0:
            f = open(filename, "a")
            f.write("Doing repaint...\n")
            f.close()
            QWebSettings.clearMemoryCaches()
            timer = QTimer()
            timer.start(100)
            QObject.connect(timer, SIGNAL("timeout()"),
                            self.__update_progress_bar__)
            Main(self.comboBox.currentIndex(), Visum.Graphic.GetWindow(),
                 self.slider.value() / 4.0, self.__get_net_size__())
        Visum.Graphic.Draw()
        self.__update_progress_bar__()
        _progress = 0
        QTimer().singleShot(1500, self.__update_progress_bar__)
        f = open(filename, "a")
        f.write("End of doing repaint.\n")
        f.close()
class MyMainWindow(QMainWindow):
    ' Main Window '
    def __init__(self, AUTO):
        ' Initialize QWidget inside MyMainWindow '
        super(MyMainWindow, self).__init__()
        QWidget.__init__(self)
        self.auto = AUTO
        self.statusBar().showMessage('               {}'.format(__doc__))
        self.setStyleSheet('QStatusBar{color:grey;}')
        self.setWindowTitle(__doc__)
        self.setWindowIcon(QIcon.fromTheme("face-monkey"))
        self.setFont(QFont('Ubuntu Light', 10))
        self.setMaximumSize(QDesktopWidget().screenGeometry().width(),
                            QDesktopWidget().screenGeometry().height())

        self.base = path.abspath(path.join(getcwd(), str(datetime.now().year)))

        # directory auto completer
        self.completer = QCompleter(self)
        self.dirs = QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.setCompletionMode(QCompleter.PopupCompletion)

        # process
        self.process1 = None
        self.process2 = None
        self.cmd1 = 'nice -n {n} arecord{v} -f {f} -c {c} -r {b} -t raw'
        self.cmd2 = 'oggenc - -r -C {c} -R {b} -q {q} {d}{t}{a} -o {o}'
        self.process3 = QProcess(self)
        #self.process3.finished.connect(self.on_process3_finished)
        #self.process3.error.connect(self.on_process3_error)

        self.cmd3 = ('nice -n 20 ' +
          'sox "{o}" -n spectrogram -x {x} -y {y} -z 99 -t "{o}" -o "{o}.png"')
        self.actual_file = ''

        # re starting timers, one stops, one starts
        self.timerFirst = QTimer(self)
        self.timerFirst.timeout.connect(self.end)
        self.timerSecond = QTimer(self)
        self.timerSecond.timeout.connect(self.run)

        # Proxy support, by reading http_proxy os env variable
        proxy_url = QUrl(environ.get('http_proxy', ''))
        QNetworkProxy.setApplicationProxy(QNetworkProxy(QNetworkProxy.HttpProxy
            if str(proxy_url.scheme()).startswith('http')
            else QNetworkProxy.Socks5Proxy, proxy_url.host(), proxy_url.port(),
                 proxy_url.userName(), proxy_url.password())) \
            if 'http_proxy' in environ else None
        print((' INFO: Proxy Auto-Config as ' + str(proxy_url)))

        # basic widgets layouts and set up
        self.mainwidget = QTabWidget()
        self.mainwidget.setToolTip(__doc__)
        self.mainwidget.setMovable(True)
        self.mainwidget.setTabShape(QTabWidget.Triangular)
        self.mainwidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.mainwidget.setStyleSheet('QTabBar{color:white;font-weight:bold;}')
        self.mainwidget.setTabBar(TabBar(self))
        self.mainwidget.setTabsClosable(False)
        self.setCentralWidget(self.mainwidget)
        self.dock1 = QDockWidget()
        self.dock2 = QDockWidget()
        self.dock3 = QDockWidget()
        self.dock4 = QDockWidget()
        self.dock5 = QDockWidget()
        for a in (self.dock1, self.dock2, self.dock3, self.dock4, self.dock5):
            a.setWindowModality(Qt.NonModal)
            # a.setWindowOpacity(0.9)
            a.setWindowTitle(__doc__
                             if a.windowTitle() == '' else a.windowTitle())
            a.setStyleSheet('QDockWidget::title{text-align:center;}')
            self.mainwidget.addTab(a, QIcon.fromTheme("face-smile"),
                                   'Double Click Me')

        # Paleta de colores para pintar transparente
        self.palette().setBrush(QPalette.Base, Qt.transparent)
        self.setPalette(self.palette())
        self.setAttribute(Qt.WA_OpaquePaintEvent, False)

        # toolbar and basic actions
        self.toolbar = QToolBar(self)
        self.toolbar.setIconSize(QSize(24, 24))
        # spacer widget for left
        self.left_spacer = QWidget(self)
        self.left_spacer.setSizePolicy(QSizePolicy.Expanding,
                                       QSizePolicy.Expanding)
        # spacer widget for right
        self.right_spacer = QWidget(self)
        self.right_spacer.setSizePolicy(QSizePolicy.Expanding,
                                        QSizePolicy.Expanding)
        qaqq = QAction(QIcon.fromTheme("application-exit"), 'Quit', self)
        qaqq.setShortcut('Ctrl+Q')
        qaqq.triggered.connect(exit)
        qamin = QAction(QIcon.fromTheme("go-down"), 'Minimize', self)
        qamin.triggered.connect(lambda: self.showMinimized())
        qamax = QAction(QIcon.fromTheme("go-up"), 'Maximize', self)
        qanor = QAction(QIcon.fromTheme("view-fullscreen"),
                        'AutoCenter AutoResize', self)
        qanor.triggered.connect(self.center)
        qatim = QAction(QIcon.fromTheme("mail-signed-verified"),
                        'View Date and Time', self)
        qatim.triggered.connect(self.timedate)
        qabug = QAction(QIcon.fromTheme("help-about"), 'Report a Problem', self)
        qabug.triggered.connect(lambda: qabug.setDisabled(True) if not call(
            'xdg-open mailto:' + '*****@*****.**'.decode('rot13'),
            shell=True) else ' ERROR ')
        qamax.triggered.connect(lambda: self.showMaximized())
        qaqt = QAction(QIcon.fromTheme("help-about"), 'About Qt', self)
        qaqt.triggered.connect(lambda: QMessageBox.aboutQt(self))
        qakde = QAction(QIcon.fromTheme("help-about"), 'About KDE', self)
        if KDE:
            qakde.triggered.connect(KHelpMenu(self, "", False).aboutKDE)
        qaslf = QAction(QIcon.fromTheme("help-about"), 'About Self', self)
        if KDE:
            qaslf.triggered.connect(
                                KAboutApplicationDialog(aboutData, self).exec_)
        else:
            qaslf.triggered.connect(lambda: QMessageBox.about(self.mainwidget,
            __doc__, ''.join((__doc__, linesep, 'version ', __version__, ', (',
            __license__, '), by ', __author__, ', ( ', __email__, ' )', linesep
            ))))
        qafnt = QAction(QIcon.fromTheme("tools-check-spelling"),
                        'Set GUI Font', self)
        if KDE:
            font = QFont()
            qafnt.triggered.connect(lambda:
            self.setStyleSheet(''.join((
                '*{font-family:', str(font.toString()), '}'))
                if KFontDialog.getFont(font)[0] == QDialog.Accepted else ''))
        else:
            qafnt.triggered.connect(lambda:
                self.setStyleSheet(''.join(('*{font-family:',
                            str(QFontDialog.getFont()[0].toString()), '}'))))
        qasrc = QAction(QIcon.fromTheme("applications-development"),
                        'View Source Code', self)
        qasrc.triggered.connect(lambda:
                            call('xdg-open {}'.format(__file__), shell=True))
        qakb = QAction(QIcon.fromTheme("input-keyboard"),
                       'Keyboard Shortcuts', self)
        qakb.triggered.connect(lambda: QMessageBox.information(self.mainwidget,
                               'Keyboard Shortcuts', ' Ctrl+Q = Quit '))
        qapic = QAction(QIcon.fromTheme("camera-photo"),
                        'Take a Screenshot', self)
        qapic.triggered.connect(lambda: QPixmap.grabWindow(
            QApplication.desktop().winId()).save(QFileDialog.getSaveFileName(
            self.mainwidget, " Save Screenshot As ...", path.expanduser("~"),
            ';;(*.png) PNG', 'png')))
        qatb = QAction(QIcon.fromTheme("go-top"), 'Toggle ToolBar', self)
        qatb.triggered.connect(lambda: self.toolbar.hide()
                if self.toolbar.isVisible() is True else self.toolbar.show())
        qati = QAction(QIcon.fromTheme("zoom-in"),
                       'Switch ToolBar Icon Size', self)
        qati.triggered.connect(lambda:
            self.toolbar.setIconSize(self.toolbar.iconSize() * 4)
            if self.toolbar.iconSize().width() * 4 == 24
            else self.toolbar.setIconSize(self.toolbar.iconSize() / 4))
        qasb = QAction(QIcon.fromTheme("preferences-other"),
                       'Toggle Tabs Bar', self)
        qasb.triggered.connect(lambda: self.mainwidget.tabBar().hide()
                               if self.mainwidget.tabBar().isVisible() is True
                               else self.mainwidget.tabBar().show())
        qadoc = QAction(QIcon.fromTheme("help-browser"), 'On-line Docs', self)
        qadoc.triggered.connect(lambda: open_new_tab(str(__url__).strip()))
        qapy = QAction(QIcon.fromTheme("help-about"), 'About Python', self)
        qapy.triggered.connect(lambda: open_new_tab('http://python.org/about'))
        qali = QAction(QIcon.fromTheme("help-browser"), 'Read Licence', self)
        qali.triggered.connect(lambda: open_new_tab(__full_licence__))
        qacol = QAction(QIcon.fromTheme("preferences-system"), 'Set GUI Colors',
                        self)
        if KDE:
            color = QColor()
            qacol.triggered.connect(lambda:
                self.setStyleSheet(''.join(('* { background-color: ',
                                            str(color.name()), '}')))
                if KColorDialog.getColor(color, self) else '')
        else:
            qacol.triggered.connect(lambda: self.setStyleSheet(''.join((
                ' * { background-color: ', str(QColorDialog.getColor().name()),
                ' } '))))
        qatit = QAction(QIcon.fromTheme("preferences-system"),
                        'Set the App Window Title', self)
        qatit.triggered.connect(self.seTitle)
        self.toolbar.addWidget(self.left_spacer)
        self.toolbar.addSeparator()
        self.toolbar.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
            qatim, qatb, qafnt, qati, qasb, qatit, qapic, qadoc, qali, qaslf,
            qaqt, qakde, qapy, qabug))
        self.addToolBar(Qt.TopToolBarArea, self.toolbar)
        self.toolbar.addSeparator()
        self.toolbar.addWidget(self.right_spacer)
        # define the menu
        menu = self.menuBar()
        # File menu items
        menu.addMenu('&File').addActions((qaqq, ))
        menu.addMenu('&Window').addActions((qamax, qanor, qamin))
        # Settings menu
        menu.addMenu('&Settings').addActions((qasrc, qacol, qafnt, qatim,
                                              qatb, qati, qasb, qapic))
        # Help menu items
        menu.addMenu('&Help').addActions((qadoc, qakb, qabug, qali,
                                          qaqt, qakde, qapy, qaslf))
        # Tray Icon
        tray = QSystemTrayIcon(QIcon.fromTheme("face-devilish"), self)
        tray.setToolTip(__doc__)
        traymenu = QMenu()
        traymenu.addActions((qamax, qanor, qamin, qaqq))
        tray.setContextMenu(traymenu)
        tray.show()

        def contextMenuRequested(point):
            ' quick and dirty custom context menu '
            menu = QMenu()
            menu.addActions((qaqq, qamin, qanor, qamax, qasrc, qakb, qacol,
                qafnt, qati, qasb, qatb, qatim, qatit, qapic, qadoc, qali,
                qaslf, qaqt, qakde, qapy, qabug))
            menu.exec_(self.mapToGlobal(point))
        self.mainwidget.customContextMenuRequested.connect(contextMenuRequested)

        def must_be_checked(widget_list):
            ' widget tuple passed as argument should be checked as ON '
            for each_widget in widget_list:
                try:
                    each_widget.setChecked(True)
                except:
                    pass

        def must_have_tooltip(widget_list):
            ' widget tuple passed as argument should have tooltips '
            for each_widget in widget_list:
                try:
                    each_widget.setToolTip(each_widget.text())
                except:
                    each_widget.setToolTip(each_widget.currentText())
                finally:
                    each_widget.setCursor(QCursor(Qt.PointingHandCursor))

        def must_autofillbackground(widget_list):
            ' widget tuple passed as argument should have filled background '
            for each_widget in widget_list:
                try:
                    each_widget.setAutoFillBackground(True)
                except:
                    pass

        def must_glow(widget_list):
            ' apply an glow effect to the widget '
            for glow, each_widget in enumerate(widget_list):
                try:
                    if each_widget.graphicsEffect() is None:
                        glow = QGraphicsDropShadowEffect(self)
                        glow.setOffset(0)
                        glow.setBlurRadius(99)
                        glow.setColor(QColor(99, 255, 255))
                        each_widget.setGraphicsEffect(glow)
                        # glow.setEnabled(False)
                        try:
                            each_widget.clicked.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                        except:
                            each_widget.sliderPressed.connect(lambda:
                            each_widget.graphicsEffect().setEnabled(True)
                            if each_widget.graphicsEffect().isEnabled() is False
                            else each_widget.graphicsEffect().setEnabled(False))
                except:
                    pass

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

        # dock 1
        QLabel('<h1 style="color:white;"> Record !</h1>', self.dock1).resize(
               self.dock3.size().width() / 4, 25)
        self.group1 = QGroupBox()
        self.group1.setTitle(__doc__)

        self.spec = QPushButton(self)
        self.spec.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.spec.setMinimumSize(self.spec.size().width(), 250)
        self.spec.setFlat(True)
        self.spec.clicked.connect(self.spectro)

        self.clock = QLCDNumber()
        self.clock.setSegmentStyle(QLCDNumber.Flat)
        self.clock.setMinimumSize(self.clock.size().width(), 50)
        self.clock.setNumDigits(25)
        self.timer1 = QTimer(self)
        self.timer1.timeout.connect(lambda: self.clock.display(
            datetime.now().strftime("%d-%m-%Y %H:%M:%S %p")))
        self.timer1.start(1000)
        self.clock.setToolTip(datetime.now().strftime("%c %x"))
        self.clock.setCursor(QCursor(Qt.CrossCursor))

        self.diskBar = QProgressBar()
        self.diskBar.setMinimum(0)
        self.diskBar.setMaximum(statvfs(HOME).f_blocks *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setValue(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024)
        self.diskBar.setToolTip(str(statvfs(HOME).f_bfree *
            statvfs(HOME).f_frsize / 1024 / 1024 / 1024) + ' Gigabytes free')

        self.feedback = QPlainTextEdit(''.join(('<center><h3>', __doc__,
            ', version', __version__, __license__, ' <br> by ', __author__,
            ' <i>(Dev)</i>, Radio Comunitaria FM Reconquista <i>(Q.A.)</i><br>',
            'FMReconquista.org.ar & GitHub.com/JuanCarlosPaco/Cinta-Testigo')))

        self.rec = QPushButton(QIcon.fromTheme("media-record"), 'Record')
        self.rec.setMinimumSize(self.rec.size().width(), 50)
        self.rec.clicked.connect(self.go)  # self.run

        self.stop = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.stop.clicked.connect(self.end)

        self.kill = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.kill.clicked.connect(self.killer)

        vboxg1 = QVBoxLayout(self.group1)
        for each_widget in (
            QLabel('<b style="color:white;"> Spectro'), self.spec,
            QLabel('<b style="color:white;"> Time '), self.clock,
            QLabel('<b style="color:white;"> Disk '), self.diskBar,
            QLabel('<b style="color:white;"> STDOUT + STDIN '), self.feedback,
            QLabel('<b style="color:white;"> Record '), self.rec, self.stop,
            self.kill):
            vboxg1.addWidget(each_widget)

        self.group2 = QGroupBox()
        self.group2.setTitle(__doc__)

        self.slider = QSlider(self)
        self.slid_l = QLabel(self.slider)
        self.slider.setCursor(QCursor(Qt.OpenHandCursor))
        self.slider.sliderPressed.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.slider.sliderReleased.connect(lambda:
                            self.slider.setCursor(QCursor(Qt.OpenHandCursor)))
        self.slider.valueChanged.connect(lambda:
                            self.slider.setToolTip(str(self.slider.value())))
        self.slider.valueChanged.connect(lambda: self.slid_l.setText(
                    '<h2 style="color:white;">{}'.format(self.slider.value())))
        self.slider.setMinimum(10)
        self.slider.setMaximum(99)
        self.slider.setValue(30)
        self.slider.setOrientation(Qt.Vertical)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setTickInterval(2)
        self.slider.setSingleStep(10)
        self.slider.setPageStep(10)

        vboxg2 = QVBoxLayout(self.group2)
        for each_widget in (
            QLabel('<b style="color:white;">MINUTES of recording'), self.slider,
            QLabel('<b style="color:white;"> Default: 30 Min')):
            vboxg2.addWidget(each_widget)

        group3 = QGroupBox()
        group3.setTitle(__doc__)
        try:
            self.label2 = QLabel(getoutput('sox --version', shell=True))
            self.label4 = QLabel(getoutput('arecord --version', shell=1)[:25])
            self.label6 = QLabel(str(getoutput('oggenc --version', shell=True)))
        except:
            print(''' ERROR: No SOX, OGGenc avaliable !
                  ( sudo apt-get install vorbis-tools sox alsa-utils ) ''')
            exit()

        self.button5 = QPushButton(QIcon.fromTheme("audio-x-generic"),
                                   'OGG --> ZIP')
        self.button5.clicked.connect(lambda: make_archive(
            str(QFileDialog.getSaveFileName(self, "Save OGG to ZIP file As...",
            getcwd(), ';;(*.zip)', 'zip')).replace('.zip', ''), "zip",
            path.abspath(path.join(getcwd(), str(datetime.now().year)))))

        self.button1 = QPushButton(QIcon.fromTheme("folder-open"), 'Files')
        self.button1.clicked.connect(lambda:
                                     call('xdg-open ' + getcwd(), shell=True))

        self.button0 = QPushButton(
            QIcon.fromTheme("preferences-desktop-screensaver"), 'LCD OFF')
        self.button0.clicked.connect(lambda:
            call('sleep 3 ; xset dpms force off', shell=True))

        vboxg3 = QVBoxLayout(group3)
        for each_widget in (
            QLabel('<b style="color:white;"> OGG Output Codec '), self.label6,
            QLabel('<b style="color:white;"> Raw Record Backend '), self.label4,
            QLabel('<b style="color:white;"> Helper Libs '), self.label2,
            QLabel('<b style="color:white;"> OGG ZIP '), self.button5,
            QLabel('<b style="color:white;"> Files '), self.button1,
            QLabel('<b style="color:white;"> LCD '), self.button0):
            vboxg3.addWidget(each_widget)
        container = QWidget()
        hbox = QHBoxLayout(container)
        for each_widget in (self.group2, self.group1, group3):
            hbox.addWidget(each_widget)
        self.dock1.setWidget(container)

        # dock 2
        QLabel('<h1 style="color:white;"> Hardware !</h1>', self.dock2).resize(
               self.dock2.size().width() / 4, 25)
        try:
            audioDriverStr = {Solid.AudioInterface.Alsa: "ALSA",
                Solid.AudioInterface.OpenSoundSystem: "Open Sound",
                Solid.AudioInterface.UnknownAudioDriver: "Unknown?"}
            audioInterfaceTypeStr = {
                Solid.AudioInterface.AudioControl: "Control",
                Solid.AudioInterface.UnknownAudioInterfaceType: "Unknown?",
                Solid.AudioInterface.AudioInput: "In",
                Solid.AudioInterface.AudioOutput: "Out"}
            soundcardTypeStr = {
                Solid.AudioInterface.InternalSoundcard: "Internal",
                Solid.AudioInterface.UsbSoundcard: "USB3",
                Solid.AudioInterface.FirewireSoundcard: "FireWire",
                Solid.AudioInterface.Headset: "Headsets",
                Solid.AudioInterface.Modem: "Modem"}
            display = QTreeWidget()
            display.setAlternatingRowColors(True)
            display.setHeaderLabels(["Items", "ID", "Drivers", "I / O", "Type"])
            display.setColumnWidth(0, 350)
            display.setColumnWidth(1, 350)
            display.setColumnWidth(3, 75)
            # retrieve a list of Solid.Device for this machine
            deviceList = Solid.Device.allDevices()
            # filter the list of all devices and display matching results
            # note that we never create a Solid.AudioInterface object, but
            # receive one from the 'asDeviceInterface' call
            for device in deviceList:
                if device.isDeviceInterface(
                                         Solid.DeviceInterface.AudioInterface):
                    audio = device.asDeviceInterface(
                            Solid.DeviceInterface.AudioInterface)
                    devtype = audio.deviceType()
                    devstr = []
                    for key in audioInterfaceTypeStr:
                        flag = key & devtype
                        if flag:
                            devstr.append(audioInterfaceTypeStr[key])
                    QTreeWidgetItem(display, [device.product(), audio.name(),
                        audioDriverStr[audio.driver()], "/".join(devstr),
                        soundcardTypeStr[audio.soundcardType()]])
            self.dock2.setWidget(display)
        except:
            self.dock2.setWidget(QLabel(""" <center style='color:white;'>
            <h1>:(<br>ERROR: Please, install PyKDE !</h1><br>
            <br><i> (Sorry, can not use non-Qt Libs). Thanks </i><center>"""))

        ## dock 3
        QLabel('<h1 style="color:white;"> Previews !</h1>', self.dock3).resize(
               self.dock3.size().width() / 4, 25)
        self.fileView = QColumnView()
        self.fileView.updatePreviewWidget.connect(self.play)
        self.fileView.setToolTip(' Browse and Preview Files ')
        self.media = None
        self.model = QDirModel()
        self.fileView.setModel(self.model)
        self.dock3.setWidget(self.fileView)

        # dock4
        QLabel('<h1 style="color:white;"> Setup !</h1>', self.dock4).resize(
               self.dock4.size().width() / 4, 25)
        self.group4 = QGroupBox()
        self.group4.setTitle(__doc__)

        self.combo0 = QComboBox()
        self.combo0.addItems(['S16_LE', 'S32_LE', 'S16_BE', 'U16_LE', 'U16_BE',
          'S24_LE', 'S24_BE', 'U24_LE', 'U24_BE', 'S32_BE', 'U32_LE', 'U32_BE'])

        self.combo1 = QComboBox()
        self.combo1.addItems(['1', '-1', '0', '2', '3', '4',
                              '5', '6', '7', '8', '9', '10'])

        self.combo2 = QComboBox()
        self.combo2.addItems(['128', '256', '512', '1024', '64', '32', '16'])

        self.combo3 = QComboBox(self)
        self.combo3.addItems(['MONO', 'STEREO', 'Surround'])

        self.combo4 = QComboBox()
        self.combo4.addItems(['44100', '96000', '48000', '32000',
                              '22050', '16000', '11025', '8000'])

        self.combo5 = QComboBox(self)
        self.combo5.addItems(['20', '19', '18', '17', '16', '15', '14', '13',
            '12', '10', '9', '8', '7', '6', '5', '4', '3', '2', '1', '0'])

        self.nepochoose = QCheckBox('Auto-Tag Files using Nepomuk Semantic')

        self.chckbx0 = QCheckBox('Disable Software based Volume Control')

        self.chckbx1 = QCheckBox('Output Sound Stereo-to-Mono Downmix')

        self.chckbx2 = QCheckBox('Add Date and Time MetaData to Sound files')

        self.chckbx3 = QCheckBox('Add Yourself as the Author Artist of Sound')

        vboxg4 = QVBoxLayout(self.group4)
        for each_widget in (
            QLabel('<b style="color:white;"> Sound OGG Quality'), self.combo1,
            QLabel('<b style="color:white;"> Sound Record Format'), self.combo0,
            QLabel('<b style="color:white;"> Sound KBps '), self.combo2,
            QLabel('<b style="color:white;"> Sound Channels '), self.combo3,
            QLabel('<b style="color:white;"> Sound Sample Rate '), self.combo4,
            QLabel('<b style="color:white;"> Sound Volume'), self.chckbx0,
            QLabel('<b style="color:white;"> Sound Mix'), self.chckbx1,
            QLabel('<b style="color:white;"> Sound Meta'), self.chckbx2,
            QLabel('<b style="color:white;"> Sound Authorship'), self.chckbx3,
            QLabel('<b style="color:white;"> CPUs Priority'), self.combo5,
            QLabel('<b style="color:white;">Nepomuk Semantic User Experience'),
            self.nepochoose):
            vboxg4.addWidget(each_widget)
        self.dock4.setWidget(self.group4)

        # dock 5
        QLabel('<h1 style="color:white;"> Voice Changer ! </h1>', self.dock5
               ).resize(self.dock5.size().width() / 3, 25)
        self.group5 = QGroupBox()
        self.group5.setTitle(__doc__)

        self.dial = QDial()
        self.dial.setCursor(QCursor(Qt.OpenHandCursor))
        self.di_l = QLabel(self.dial)
        self.di_l.resize(self.dial.size() / 8)
        self.dial.sliderPressed.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.ClosedHandCursor)))
        self.dial.sliderReleased.connect(lambda:
                            self.dial.setCursor(QCursor(Qt.OpenHandCursor)))
        self.dial.valueChanged.connect(lambda:
                            self.dial.setToolTip(str(self.dial.value())))
        self.dial.valueChanged.connect(lambda: self.di_l.setText(
                    '<h1 style="color:white;">{}'.format(self.dial.value())))
        self.dial.setValue(0)
        self.dial.setMinimum(-999)
        self.dial.setMaximum(999)
        self.dial.setSingleStep(100)
        self.dial.setPageStep(100)
        self.dial.setWrapping(False)
        self.dial.setNotchesVisible(True)

        self.defo = QPushButton(QIcon.fromTheme("media-playback-start"), 'Run')
        self.defo.setMinimumSize(self.defo.size().width(), 50)
        self.defo.clicked.connect(lambda: self.process3.start(
            'play -q -V0 "|rec -q -V0 -n -d -R riaa pitch {} "'
            .format(self.dial.value()) if int(self.dial.value()) != 0 else
            'play -q -V0 "|rec -q -V0 --multi-threaded -n -d -R bend {} "'
            .format(' 3,2500,3 3,-2500,3 ' * 999)))

        self.qq = QPushButton(QIcon.fromTheme("media-playback-stop"), 'Stop')
        self.qq.clicked.connect(self.process3.kill)

        self.die = QPushButton(QIcon.fromTheme("process-stop"), 'Kill')
        self.die.clicked.connect(lambda: call('killall rec', shell=True))

        vboxg5 = QVBoxLayout(self.group5)
        for each_widget in (self.dial, self.defo, self.qq, self.die):
            vboxg5.addWidget(each_widget)
        self.dock5.setWidget(self.group5)

        # configure some widget settings
        must_be_checked((self.nepochoose, self.chckbx1,
                         self.chckbx2, self.chckbx3))
        must_have_tooltip((self.label2, self.label4, self.label6, self.combo0,
            self.nepochoose, self.combo1, self.combo2, self.combo3, self.combo4,
            self.combo5, self.chckbx0, self.chckbx1, self.chckbx2, self.chckbx3,
            self.rec, self.stop, self.defo, self.qq, self.die, self.kill,
            self.button0, self.button1, self.button5))
        must_autofillbackground((self.clock, self.label2, self.label4,
            self.label6, self.nepochoose, self.chckbx0, self.chckbx1,
            self.chckbx2, self.chckbx3))
        must_glow((self.rec, self.dial, self.combo1))
        self.nepomuk_get('testigo')
        if self.auto is True:
            self.go()

    def play(self, index):
        ' play with delay '
        if not self.media:
            self.media = Phonon.MediaObject(self)
            audioOutput = Phonon.AudioOutput(Phonon.MusicCategory, self)
            Phonon.createPath(self.media, audioOutput)
        self.media.setCurrentSource(Phonon.MediaSource(
            self.model.filePath(index)))
        self.media.play()

    def end(self):
        ' kill it with fire '
        print((' INFO: Stoping Processes at {}'.format(str(datetime.now()))))
        self.process1.terminate()
        self.process2.terminate()
        self.feedback.setText('''
            <h5>Errors for RECORDER QProcess 1:</h5>{}<hr>
            <h5>Errors for ENCODER QProcess 2:</h5>{}<hr>
            <h5>Output for RECORDER QProcess 1:</h5>{}<hr>
            <h5>Output for ENCODER QProcess 2:</h5>{}<hr>
            '''.format(self.process1.readAllStandardError(),
                       self.process2.readAllStandardError(),
                       self.process1.readAllStandardOutput(),
                       self.process2.readAllStandardOutput(),
        ))

    def killer(self):
        ' kill -9 '
        QMessageBox.information(self.mainwidget, __doc__,
            ' KILL -9 was sent to the multi-process backend ! ')
        self.process1.kill()
        self.process2.kill()

    def go(self):
        ' run timeout re-starting timers '
        self.timerFirst.start(int(self.slider.value()) * 60 * 1000 + 2000)
        self.timerSecond.start(int(self.slider.value()) * 60 * 1000 + 2010)
        self.run()

    def run(self):
        ' run forest run '
        print((' INFO: Working at {}'.format(str(datetime.now()))))

        chnl = 1 if self.combo3.currentText() == 'MONO' else 2
        print((' INFO: Using {} Channels . . . '.format(chnl)))

        btrt = int(self.combo4.currentText())
        print((' INFO: Using {} Hz per Second . . . '.format(btrt)))

        threshold = int(self.dial.value())
        print((' INFO: Using Thresold of {} . . . '.format(threshold)))

        print((' INFO: Using Recording time of {}'.format(self.slider.value())))

        frmt = str(self.combo0.currentText()).strip()
        print((' INFO: Using Recording quality of {} ...'.format(frmt)))

        qlt = str(self.combo1.currentText()).strip()
        print((' INFO: Using Recording quality of {} ...'.format(qlt)))

        prio = str(self.combo5.currentText()).strip()
        print((' INFO: Using CPU Priority of {} ...'.format(prio)))

        downmix = '--downmix ' if self.chckbx1.isChecked() is True else ''
        print((' INFO: Using Downmix is {} ...'.format(downmix)))

        aut = '-a ' + getuser() if self.chckbx3.isChecked() is True else ''
        print((' INFO: The Author Artist of this sound is: {}'.format(aut)))

        T = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        tim = '--date {} '.format(T) if self.chckbx2.isChecked() is True else ''
        print((' INFO: The Date and Time of this sound is: {}'.format(tim)))

        vol = ' --disable-softvol' if self.chckbx0.isChecked() is True else ''
        print((' INFO: Software based Volume Control is: {}'.format(vol)))

        # make base directory
        try:
            mkdir(self.base)
            print((' INFO: Base Directory path created {}'.format(self.base)))
        except OSError:
            print((' INFO: Base Directory already exist {}'.format(self.base)))
        except:
            print((' ERROR: Can not create Directory ?, {}'.format(self.base)))

        # make directory tree
        try:
            for dr in range(1, 13):
                mkdir(path.abspath(path.join(self.base, str(dr))))
                print((' INFO:Directory created {}/{}'.format(self.base, dr)))
        except OSError:
            print((' INFO: Directory already exist {}/1,12'.format(self.base)))
        except:
            print((' ERROR: Cant create Directory?, {}/1,12'.format(self.base)))

        # make new filename
        flnm = path.abspath(path.join(self.base, str(datetime.now().month),
                   datetime.now().strftime("%Y-%m-%d_%H:%M:%S.ogg")))
        self.actual_file = flnm
        print((' INFO: Recording on the file {}'.format(flnm)))

        # make custom commands
        cmd1 = self.cmd1.format(n=prio, f=frmt, c=chnl, b=btrt, v=vol)
        cmd2 = self.cmd2.format(c=chnl, b=btrt, q=qlt,
                                d=downmix, o=flnm, a=aut, t=tim)
        print((cmd1, cmd2))
        #  multiprocess recording loop pipe
        self.process1 = QProcess(self)
        self.process2 = QProcess(self)
        self.process1.setStandardOutputProcess(self.process2)
        self.process1.start(cmd1)
        if not self.process1.waitForStarted():
            print((" ERROR: RECORDER QProcess 1 Failed: \n {}   ".format(cmd1)))
        self.process2.start(cmd2)
        if not self.process2.waitForStarted():
            print((" ERROR: ENCODER QProcess 2 Failed: \n   {} ".format(cmd2)))
        self.nepomuk_set(flnm, 'testigo', 'testigo', 'AutoTag by Cinta-Testigo')

    def spectro(self):
        ' spectrometer '
        wid = self.spec.size().width()
        hei = self.spec.size().height()
        command = self.cmd3.format(o=self.actual_file, x=wid, y=hei)
        print(' INFO: Spectrometer is deleting OLD .ogg.png Files on target ')
        call('rm --verbose --force {}/*/*.ogg.png'.format(self.base), shell=1)
        print(' INFO: Spectrometer finished Deleting Files, Starting Render ')
        call(command, shell=True)
        print((''' INFO: Spectrometer finished Rendering Sound using:
               {}{}   OutPut: {}'''.format(command, linesep, self.actual_file)))
        self.spec.setIcon(QIcon('{o}.png'.format(o=self.actual_file)))
        self.spec.setIconSize(QSize(wid, hei))
        self.spec.resize(wid, hei)

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

    def paintEvent(self, event):
        'Paint semi-transparent background, animated pattern, background text'
        QWidget.paintEvent(self, event)
        # make a painter
        p = QPainter(self)
        p.setRenderHint(QPainter.TextAntialiasing)
        p.setRenderHint(QPainter.HighQualityAntialiasing)
        # fill a rectangle with transparent painting
        p.fillRect(event.rect(), Qt.transparent)
        # animated random dots background pattern
        for i in range(4096):
            x = randint(9, self.size().width() - 9)
            y = randint(9, self.size().height() - 9)
            p.setPen(QPen(QColor(randint(200, 255), randint(200, 255), 255), 1))
            p.drawPoint(x, y)
        # set pen to use white color
        p.setPen(QPen(QColor(randint(9, 255), randint(9, 255), 255), 1))
        # Rotate painter 45 Degree
        p.rotate(35)
        # Set painter Font for text
        p.setFont(QFont('Ubuntu', 300))
        # draw the background text, with antialiasing
        p.drawText(99, 199, "Radio")
        # Rotate -45 the QPen back !
        p.rotate(-35)
        # set the pen to no pen
        p.setPen(Qt.NoPen)
        # Background Color
        p.setBrush(QColor(0, 0, 0))
        # Background Opacity
        p.setOpacity(0.75)
        # Background Rounded Borders
        p.drawRoundedRect(self.rect(), 50, 50)
        # finalize the painter
        p.end()

    def seTitle(self):
        ' set the title of the main window '
        dialog = QDialog(self)
        textEditInput = QLineEdit(' Type Title Here ')
        ok = QPushButton(' O K ')
        ok.clicked.connect(lambda: self.setWindowTitle(textEditInput.text()))
        ly = QVBoxLayout()
        [ly.addWidget(wdgt) for wdgt in (QLabel('Title:'), textEditInput, ok)]
        dialog.setLayout(ly)
        dialog.exec_()

    def timedate(self):
        ' get the time and date '
        dialog = QDialog(self)
        clock = QLCDNumber()
        clock.setNumDigits(24)
        timer = QTimer()
        timer.timeout.connect(lambda: clock.display(
            datetime.now().strftime("%d-%m-%Y %H:%M:%S %p")))
        timer.start(1000)
        clock.setToolTip(datetime.now().strftime("%c %x"))
        ok = QPushButton(' O K ')
        ok.clicked.connect(dialog.close)
        ly = QVBoxLayout()
        [ly.addWidget(wdgt) for wdgt in (QCalendarWidget(), clock, ok)]
        dialog.setLayout(ly)
        dialog.exec_()

    def closeEvent(self, event):
        ' Ask to Quit '
        if QMessageBox.question(self, ' Close ', ' Quit ? ',
           QMessageBox.Yes | QMessageBox.No, QMessageBox.No) == QMessageBox.Yes:
            event.accept()
        else:
            event.ignore()

    def center(self):
        ' Center and resize the window '
        self.showNormal()
        self.resize(QDesktopWidget().screenGeometry().width() // 1.25,
                    QDesktopWidget().screenGeometry().height() // 1.25)
        qr = self.frameGeometry()
        qr.moveCenter(QDesktopWidget().availableGeometry().center())
        self.move(qr.topLeft())

    def nepomuk_set(self, file_tag=None, __tag='', _label='', _description=''):
        ' Quick and Easy Nepomuk Taggify for Files '
        print((''' INFO: Semantic Desktop Experience is Tagging Files :
              {}, {}, {}, {})'''.format(file_tag, __tag, _label, _description)))
        if Nepomuk.ResourceManager.instance().init() is 0:
            fle = Nepomuk.Resource(KUrl(QFileInfo(file_tag).absoluteFilePath()))
            _tag = Nepomuk.Tag(__tag)
            _tag.setLabel(_label)
            fle.addTag(_tag)
            fle.setDescription(_description)
            print(([str(a.label()) for a in fle.tags()], fle.description()))
            return ([str(a.label()) for a in fle.tags()], fle.description())
        else:
            print(" ERROR: FAIL: Nepomuk is not running ! ")

    def nepomuk_get(self, query_to_search):
        ' Quick and Easy Nepomuk Query for Files '
        print((''' INFO: Semantic Desktop Experience is Quering Files :
              {} '''.format(query_to_search)))
        results = []
        nepo = Nepomuk.Query.QueryServiceClient()
        nepo.desktopQuery("hasTag:{}".format(query_to_search))

        def _query(data):
            ''' ('filename.ext', 'file description', ['list', 'of', 'tags']) '''
            results.append(([str(a.resource().genericLabel()) for a in data][0],
                            [str(a.resource().description()) for a in data][0],
            [str(a.label()) for a in iter([a.resource().tags() for a in data][0]
            )]))
        nepo.newEntries.connect(_query)

        def _end():
            '''
            [  ('filename.ext', 'file description', ['list', 'of', 'tags']),
               ('filename.ext', 'file description', ['list', 'of', 'tags']),
               ('filename.ext', 'file description', ['list', 'of', 'tags'])  ]
            '''
            nepo.newEntries.disconnect
            print(results)
            return results
        nepo.finishedListing.connect(_end)
Example #31
0
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        self.setupUi(self)
        self.setWindowTitle('DMX Test Tool by LauerSystems')

        # create and setup ipcon

        self.ipcon = IPConnection()
        self.ipcon.connect(HOST, PORT)
        self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE,
                                     self.qtcb_ipcon_enumerate.emit)
        self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED,
                                     self.qtcb_ipcon_connected.emit)

        self.dmx = BrickletDMX(UID_DMX, self.ipcon)
        self.label_image.setText("Started!")

        #Configs
        self.wait_for_first_read = True

        self.qtcb_frame_started.connect(self.cb_frame_started)
        self.qtcb_frame.connect(self.cb_frame)

        self.dmx.set_dmx_mode(BrickletDMX.DMX_MODE_MASTER)
        print("DMX Mode [0=Master; 1=Slave]: " + str(self.dmx.get_dmx_mode()))
        self.dmx.set_frame_duration(200)
        print("Frame Duration [ms]: " + str(self.dmx.get_frame_duration()))

        self.address_spinboxes = []
        self.address_slider = []
        print("Config Ende")

        for i in range(20):
            spinbox = QSpinBox()
            spinbox.setMinimum(0)
            spinbox.setMaximum(255)

            slider = QSlider(Qt.Horizontal)
            slider.setMinimum(0)
            slider.setMaximum(255)

            spinbox.valueChanged.connect(slider.setValue)
            slider.valueChanged.connect(spinbox.setValue)

            def get_frame_value_changed_func(i):
                return lambda x: self.frame_value_changed(i, x)

            slider.valueChanged.connect(get_frame_value_changed_func(i))

            self.address_table.setCellWidget(i, 0, spinbox)
            self.address_table.setCellWidget(i, 1, slider)

            self.address_spinboxes.append(spinbox)
            self.address_slider.append(slider)
            print("Erzeuge Set: " + str(i))

        self.address_table.horizontalHeader().setStretchLastSection(True)
        self.address_table.show()

        self.current_frame = [0] * 512

        print(self.current_frame)

        self.dmx.register_callback(self.dmx.CALLBACK_FRAME_STARTED,
                                   self.qtcb_frame_started.emit)
        self.dmx.register_callback(self.dmx.CALLBACK_FRAME,
                                   self.qtcb_frame.emit)
        self.dmx.set_frame_callback_config(True, False, True, False)
Example #32
0
class Window(QWidget):

    def __init__(self, parent = None):
    
        QWidget.__init__(self, parent)
        
        format = QAudioFormat()
        format.setChannels(1)
        format.setFrequency(22050)
        format.setSampleSize(16)
        format.setCodec("audio/pcm")
        format.setByteOrder(QAudioFormat.LittleEndian)
        format.setSampleType(QAudioFormat.SignedInt)
        self.output = QAudioOutput(format, self)
        
        self.frequency = 440
        self.volume = 0
        self.buffer = QBuffer()
        self.data = QByteArray()
        
        self.deviceLineEdit = QLineEdit()
        self.deviceLineEdit.setReadOnly(True)
        self.deviceLineEdit.setText(QAudioDeviceInfo.defaultOutputDevice().deviceName())
        
        self.pitchSlider = QSlider(Qt.Horizontal)
        self.pitchSlider.setMaximum(100)
        self.volumeSlider = QSlider(Qt.Horizontal)
        self.volumeSlider.setMaximum(32767)
        self.volumeSlider.setPageStep(1024)
        
        self.playButton = QPushButton(self.tr("&Play"))
        
        self.pitchSlider.valueChanged.connect(self.changeFrequency)
        self.volumeSlider.valueChanged.connect(self.changeVolume)
        self.playButton.clicked.connect(self.play)
        
        formLayout = QFormLayout()
        formLayout.addRow(self.tr("Device:"), self.deviceLineEdit)
        formLayout.addRow(self.tr("P&itch:"), self.pitchSlider)
        formLayout.addRow(self.tr("&Volume:"), self.volumeSlider)
        
        buttonLayout = QVBoxLayout()
        buttonLayout.addWidget(self.playButton)
        buttonLayout.addStretch()
        
        horizontalLayout = QHBoxLayout(self)
        horizontalLayout.addLayout(formLayout)
        horizontalLayout.addLayout(buttonLayout)
    
    def changeFrequency(self, value):
    
        self.frequency = 440 + (value * 2)
    
    def play(self):
    
        if self.output.state() == QAudio.ActiveState:
            self.output.stop()
        
        if self.buffer.isOpen():
            self.buffer.close()
        
        self.createData()
        
        self.buffer.setData(self.data)
        self.buffer.open(QIODevice.ReadOnly)
        self.buffer.seek(0)
        
        self.output.start(self.buffer)
    
    def changeVolume(self, value):
    
        self.volume = value
    
    def createData(self):
    
        # Create 2 seconds of data with 22050 samples per second, each sample
        # being 16 bits (2 bytes).
        
        self.data.clear()
        for i in xrange(2 * 22050):
            t = i / 22050.0
            value = int(self.volume * sin(2 * pi * self.frequency * t))
            self.data.append(struct.pack("<h", value))
Example #33
0
class CaracteristicasEditor(QWidget):
    """ Clase Configuracion Editor """

    def __init__(self):
        super(CaracteristicasEditor, self).__init__()
        contenedor = QVBoxLayout(self)

        # Márgen de línea
        grupo_margen = QGroupBox(self.tr("Márgen:"))
        box = QGridLayout(grupo_margen)
        self.check_margen = QCheckBox(self.tr("Mostrar"))
        box.addWidget(self.check_margen, 0, 0)
        self.slider_margen = QSlider(Qt.Horizontal)
        self.slider_margen.setMaximum(180)
        box.addWidget(self.slider_margen, 0, 1)
        lcd_margen = QLCDNumber()
        lcd_margen.setStyleSheet("color: #dedede")
        lcd_margen.setSegmentStyle(lcd_margen.Flat)
        box.addWidget(lcd_margen, 0, 2)

        # Indentación
        grupo_indentacion = QGroupBox(self.tr("Indentación:"))
        box = QGridLayout(grupo_indentacion)
        self.check_indentacion = QCheckBox(self.tr("Activar"))
        box.addWidget(self.check_indentacion, 0, 0)
        self.slider_indentacion = QSlider(Qt.Horizontal)
        self.slider_indentacion.setMaximum(20)
        box.addWidget(self.slider_indentacion, 0, 1)
        lcd_indentacion = QLCDNumber()
        lcd_indentacion.setStyleSheet("color: #dedede")
        lcd_indentacion.setSegmentStyle(lcd_indentacion.Flat)
        box.addWidget(lcd_indentacion, 0, 2)
        self.check_guia = QCheckBox(self.tr("Activar guías"))
        box.addWidget(self.check_guia, 1, 0)

        # Tipo de letra
        grupo_fuente = QGroupBox(self.tr("Tipo de letra:"))
        box = QHBoxLayout(grupo_fuente)
        self.btn_fuente = QPushButton()
        self.btn_fuente.setObjectName("custom")
        self.btn_fuente.setMaximumWidth(250)
        self._cargar_fuente()
        box.addWidget(self.btn_fuente)
        box.addStretch(1)

        # Cursor
        grupo_cursor = QGroupBox(self.tr("Tipo de cursor:"))
        box = QVBoxLayout(grupo_cursor)
        tipos_cursor = [
            self.tr('Invisible'),
            self.tr('Línea'),
            self.tr('Bloque')
            ]
        self.radio_cursor = []
        [self.radio_cursor.append(QRadioButton(cursor))
            for cursor in tipos_cursor]
        for ntipo, radiob in enumerate(self.radio_cursor):
            box.addWidget(radiob)
            if ntipo == ESettings.get('editor/tipoCursor'):
                radiob.setChecked(True)

        contenedor.addWidget(grupo_margen)
        contenedor.addWidget(grupo_indentacion)
        contenedor.addWidget(grupo_fuente)
        contenedor.addWidget(grupo_cursor)
        contenedor.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding,
                           QSizePolicy.Expanding))

        # Conexiones
        self.slider_margen.valueChanged[int].connect(lcd_margen.display)
        self.slider_indentacion.valueChanged[int].connect(
            lcd_indentacion.display)
        self.btn_fuente.clicked.connect(self._seleccionar_fuente)

        # Configuraciones
        # Márgen
        self.check_margen.setChecked(ESettings.get('editor/margen'))
        self.slider_margen.setValue(ESettings.get('editor/margenAncho'))
        # Indentación
        self.check_indentacion.setChecked(ESettings.get(
                                          'editor/indentacion'))
        self.slider_indentacion.setValue(ESettings.get(
                                         'editor/indentacionAncho'))
        self.check_guia.setChecked(ESettings.get('editor/guias'))

    def _cargar_fuente(self):
        fuente = ESettings.get('editor/fuente')
        if not fuente:
            fuente = configuracion.FUENTE
        size = str(ESettings.get('editor/fuenteTam'))
        texto = fuente + ', ' + size
        self.btn_fuente.setText(texto)

    def _seleccionar_fuente(self):
        seleccion, ok = QFontDialog.getFont()
        if ok:
            fuente = seleccion.family()
            size = str(seleccion.pointSize())
            self.btn_fuente.setText(fuente + ', ' + size)

    def guardar(self):
        """ Guarda las configuraciones del Editor. """

        fuente, fuente_tam = self.btn_fuente.text().split(',')
        ESettings.set('editor/fuente', fuente)
        ESettings.set('editor/fuenteTam', int(fuente_tam.strip()))
        ESettings.set('editor/margen', self.check_margen.isChecked())
        ESettings.set('editor/margenAncho', self.slider_margen.value())
        ESettings.set('editor/guias', self.check_guia.isChecked())
        ESettings.set('editor/indentacionAncho',
                      self.slider_indentacion.value())
        for ntipo, radio in enumerate(self.radio_cursor):
            if radio.isChecked():
                tipo = ntipo
        ESettings.set('editor/tipoCursor', tipo)
        principal = EDIS.componente("principal")
        weditor = principal.devolver_editor()
        if weditor is not None:
            weditor.cargar_fuente(fuente, int(fuente_tam))
            weditor.actualizar()
            weditor.actualizar_margen()
            weditor.actualizar_indentacion()
class MainWindow(QWidget):
    def __init__(self):
        QWidget.__init__(self, None)

        # initiate timer
        self.timer = QTimer()
        self.timer.timeout.connect(self.reload)

        # layout id gridbox-like
        self.box = QGridLayout()
        self.resize(800, 800)
        self.setLayout(self.box)

        # Create two labels and a button
        self.vertLabel = QLabel("Radolan Data Window", self)
        self.timeLabel = QLabel("Time", self)
        self.sliderLabel = QLabel("00:00", self)

        # File Dialog
        self.dlg = QFileDialog()
        self.dlg.setFileMode(QFileDialog.Directory)
        self.dlg.setOption(QFileDialog.ShowDirsOnly, True)

        # Canvas
        self.canvas = None
        self.cbar = CBarCanvas()

        # Sliders
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(1)
        self.slider.setMaximum(100)
        self.slider.setTickInterval(1)
        self.slider.setSingleStep(1)
        self.slider.valueChanged.connect(self.slider_moved)

        self.cHighSlider = QSlider(Qt.Horizontal)
        self.cHighSlider.setMinimum(0)
        self.cHighSlider.setMaximum(4096)
        self.cHighSlider.setTickInterval(1)
        self.cHighSlider.setSingleStep(1)
        self.cHighSlider.setValue(4096)
        self.cHighSlider.valueChanged.connect(self.cHighSlider_moved)

        self.cHighLabel = QLabel("Upper Limit:")
        self.cHighValue = QLabel("4096")

        # Load Button
        self.loadButton = QPushButton("Open Directory")
        self.loadButton.clicked.connect(self.button_clicked)

        # Text Output Widget
        self.attrWidget = TextWidget()
        self.attrWidget.setVisible(False)

        self.createButtons()

        # grid parameters
        self.c1 = 0
        self.c2 = 10

        # add Widgets to Layout
        self.box.addWidget(self.loadButton, 0, self.c1, 1, 11)
        self.box.addWidget(self.dlg, 1, self.c1, 3, 11)
        self.box.addWidget(self.attrWidget, 1, self.c1, 3, -1)
        self.box.addWidget(self.vertLabel, 6, self.c1, 1, 10)
        self.box.addWidget(self.cbar.native, 5, self.c2, 10, 1)
        self.box.addWidget(self.timeLabel, 4, self.c1, 1, 10)
        self.box.addWidget(self.playPauseButton, 4, self.c1 + 1, 1, 1)
        self.box.addWidget(self.cHighLabel, 4, self.c1 + 4, 1, 1)
        self.box.addWidget(self.cHighValue, 4, self.c1 + 5, 1, 1)
        self.box.addWidget(self.cHighSlider, 4, self.c1 + 6, 1, 4)
        self.box.addWidget(self.sliderLabel, 5, self.c1, 1, 1)
        self.box.addWidget(self.slider, 5, self.c1 + 1, 1, 9)
        self.show()

        # connect Filedialog
        self.dlg.fileSelected.connect(self.folder_selected)

    def folder_selected(self, folder):
        if not self.canvas:
            self.canvas = Canvas()
            self.box.addWidget(self.canvas.native, 7, self.c1, -1, 10)
        inname = "/raa*"
        self.canvas.flist = sorted(glob.glob(str(folder) + inname))
        self.canvas.frames = len(self.canvas.flist)
        self.slider.setMaximum(self.canvas.frames)
        self.attrWidget.setVisible(True)
        self.slider.setValue(1)
        self.slider_moved(1)

    def button_clicked(self):
        self.attrWidget.setVisible(False)
        self.dlg.setVisible(True)

    # loop continuously through data
    def reload(self):
        if self.slider.value() == self.slider.maximum():
            self.slider.setValue(1)
        else:
            self.slider.setValue(self.slider.value() + 1)

    # changing upper limit
    def cHighSlider_moved(self, position):
        clow, chigh = self.canvas.image.clim
        self.canvas.image.clim = (clow, position)
        self.cHighValue.setText(str(position))

    # slide through data
    def slider_moved(self, position):
        self.canvas.actualFrame = position - 1
        self.canvas.data, self.canvas.attrs = read_RADOLAN_composite(self.canvas.flist[self.canvas.actualFrame],
                                                                     missing=0)
        # adapt color limits
        if self.canvas.data.dtype == 'uint8':
            self.cHighSlider.setMaximum(255)
        else:
            self.cHighSlider.setMaximum(4096)

        # change and update
        self.canvas.update()
        self.sliderLabel.setText(self.canvas.attrs['datetime'].strftime("%H:%M"))
        self.attrWidget.radolanVersion.setText(self.canvas.attrs['radolanversion'])
        self.attrWidget.dateTime.setText(self.canvas.attrs['datetime'].strftime("%Y-%m-%d"))
        self.attrWidget.productType.setText(self.canvas.attrs['producttype'].upper())

    # start/stop capability
    def playpause(self):
        if self.playPauseButton.toolTip() == 'Play':
            self.playPauseButton.setToolTip("Pause")
            self.timer.start()
            self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPause))
        else:
            self.playPauseButton.setToolTip("Play")
            self.timer.stop()
            self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))

    # create play/pause Button
    def createButtons(self):
        iconSize = QSize(18, 18)

        self.playPauseButton = QToolButton()
        self.playPauseButton.setIcon(self.style().standardIcon(QStyle.SP_MediaPlay))
        self.playPauseButton.setIconSize(iconSize)
        self.playPauseButton.setToolTip("Play")
        self.playPauseButton.clicked.connect(self.playpause)
Example #35
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')
Example #36
0
class DisplaySection(QWidget):
    def __init__(self):
        super(DisplaySection, self).__init__()
        EditorConfiguration.install_widget(self.tr("Visualización"), self)
        container = QVBoxLayout(self)

        # Text wrapping
        group_wrapping = QGroupBox(self.tr("Ajuste de Texto:"))
        box = QGridLayout(group_wrapping)
        self.check_wrap = QCheckBox(self.tr("Activar ajuste de texto"))
        box.addWidget(self.check_wrap, 0, 0)
        self.check_margin = QCheckBox(self.tr("Mostrar márgen derecho:"))
        box.addWidget(self.check_margin, 1, 0)
        self.slider_margin = QSlider(Qt.Horizontal)
        self.slider_margin.setMaximum(180)
        self.slider_margin.setFixedWidth(350)
        box.addWidget(self.slider_margin, 1, 1, Qt.AlignLeft)
        lcd_margin = QLCDNumber()
        lcd_margin.setSegmentStyle(QLCDNumber.Flat)
        box.addWidget(lcd_margin, 1, 2, Qt.AlignLeft)
        box.setAlignment(Qt.AlignLeft)
        container.addWidget(group_wrapping)  # Add group

        # Extras: line number, markers, whitespace, etc
        group_extras = QGroupBox(self.tr("Visualización:"))
        box = QGridLayout(group_extras)
        self.check_line_numbers = QCheckBox(
            self.tr("Mostrar números de líneas"))
        box.addWidget(self.check_line_numbers, 0, 0)
        self.check_current_line = QCheckBox(self.tr("Resaltar línea actual"))
        box.addWidget(self.check_current_line, 0, 1)
        self.check_mark_change = QCheckBox(self.tr("Marcar línea modificada"))
        box.addWidget(self.check_mark_change, 1, 0)
        self.check_match_brace = QCheckBox(self.tr("Resaltar [], {}, (), <>"))
        box.addWidget(self.check_match_brace, 1, 1)
        self.check_whitespace = QCheckBox(
            self.tr("Mostrar espacios en blanco"))
        box.addWidget(self.check_whitespace, 2, 0)
        self.check_guides = QCheckBox(self.tr("Mostrar guías de indentación"))
        box.addWidget(self.check_guides, 2, 1)
        self.check_eof = QCheckBox(self.tr("Mostrar EOF"))
        box.addWidget(self.check_eof, 3, 0)
        container.addWidget(group_extras)  # Add group

        # Spacer
        container.addItem(
            QSpacerItem(0, 10, QSizePolicy.Expanding, QSizePolicy.Expanding))

        # Connections
        self.slider_margin.valueChanged[int].connect(lcd_margin.display)

        # Configuration
        self.check_wrap.setChecked(settings.get_setting('editor/wrap-mode'))
        self.check_line_numbers.setChecked(
            settings.get_setting('editor/show-line-number'))
        self.check_mark_change.setChecked(
            settings.get_setting('editor/mark-change'))
        self.check_match_brace.setChecked(
            settings.get_setting('editor/match-brace'))
        self.check_current_line.setChecked(
            settings.get_setting('editor/show-caret-line'))
        self.check_eof.setChecked(settings.get_setting('editor/eof'))
        self.check_margin.setChecked(
            settings.get_setting('editor/show-margin'))
        self.slider_margin.setValue(
            settings.get_setting('editor/width-margin'))
        self.check_whitespace.setChecked(
            settings.get_setting('editor/show-tabs-spaces'))
        self.check_guides.setChecked(
            settings.get_setting('editor/show-guides'))

    def save(self):
        settings.set_setting('editor/wrap-mode', self.check_wrap.isChecked())
        settings.set_setting('editor/show-margin',
                             self.check_margin.isChecked())
        settings.set_setting('editor/width-margin', self.slider_margin.value())
        settings.set_setting('editor/show-line-number',
                             self.check_line_numbers.isChecked())
        settings.set_setting('editor/mark-change',
                             self.check_mark_change.isChecked())
        settings.set_setting('editor/match-brace',
                             self.check_match_brace.isChecked())
        settings.set_setting('editor/show-caret-line',
                             self.check_current_line.isChecked())
        settings.set_setting('editor/show-tabs-spaces',
                             self.check_whitespace.isChecked())
        settings.set_setting('editor/show-guides',
                             self.check_guides.isChecked())
        settings.set_setting('editor/eof', self.check_eof.isChecked())
        editor_container = Edis.get_component("principal")
        editor = editor_container.get_active_editor()
        if editor is not None:
            editor.set_brace_matching()
            editor.show_line_numbers()
            editor.update_options()
            editor.update_margin()
Example #37
0
File: View0.py Project: iras/JADE
class View (QFrame):

    def __init__ (self, name, graph_view, scene, parent=None):
        
        QFrame.__init__(self, parent)
        
        self.graph_view = graph_view
        self.graph_view.setView0 (self)
        self.scene = scene

        self.setFrameStyle (QFrame.Sunken | QFrame.StyledPanel)
        
        self.font = QFont()
        self.font.setPointSize(10)
        
        
        self.graphicsView = CustomGraphicsView ()
        self.graphicsView.setRenderHint (QPainter.Antialiasing, True)
        self.graphicsView.setDragMode (QGraphicsView.RubberBandDrag)
        self.graphicsView.setViewportUpdateMode (QGraphicsView.SmartViewportUpdate)
        #self.graphicsView.setMouseTracking(True)
        
        # toolbox definition + group page definition
        sizePolicy = QSizePolicy (QSizePolicy.Fixed, QSizePolicy.Expanding)
        self.setObjectName ('Form')
        self.resize (900, 1000)
        self._toolBox = QToolBox (self)
        self._toolBox.setGeometry (QRect (0, 0, 131, 301))
        self._toolBox.setFont (self.font)
        self._toolBox.setObjectName ('_toolBox')
        self._toolBox.setCursor (Qt.PointingHandCursor)
        self.groupCluster = QWidget ()
        self.groupCluster.setGeometry (QRect(0, 0, 91, 241))
        self.groupCluster.setObjectName ('groupCluster')
        self.groupLineEdit = QLineEdit (self.groupCluster)
        self.groupLineEdit.setGeometry (QRect (2, 20, 60, 16))
        self.groupLineEdit.setObjectName ('groupLineEdit')
        self.label = QLabel (self.groupCluster)
        self.label.setGeometry (QRect (4, 6, 62, 16))
        self.label.setFont (self.font)
        self.label.setObjectName ('label')
        self.label_2 = QLabel (self.groupCluster)
        self.label_2.setGeometry (QRect (4, 40, 62, 16))
        self.label_2.setFont (self.font)
        self.label_2.setObjectName ('label_2')
        self.groupLineEdit_2 = QLineEdit (self.groupCluster)
        self.groupLineEdit_2.setGeometry (QRect(2, 54, 60, 16))
        self.groupLineEdit_2.setObjectName ('groupLineEdit_2')
        self.pushButton = QPushButton (self.groupCluster)
        self.pushButton.setGeometry (QRect (2, 90, 60, 16))
        self.pushButton.setFont (self.font)
        self.pushButton.setObjectName ('pushButton')
        self._toolBox.addItem (self.groupCluster, '')
        self._toolBox.setItemText (self._toolBox.indexOf (self.groupCluster), QApplication.translate ("Form", "Group", None, QApplication.UnicodeUTF8))
        self.setWindowTitle (QApplication.translate ("Form", "Form", None, QApplication.UnicodeUTF8))
        self.label.setText (QApplication.translate ("Form", "name group", None, QApplication.UnicodeUTF8))
        self.label_2.setText (QApplication.translate ("Form", "group id", None, QApplication.UnicodeUTF8))
        self.pushButton.setText (QApplication.translate ("Form", "add cluster", None, QApplication.UnicodeUTF8))
        self._toolBox.setSizePolicy (sizePolicy)
        self._toolBox.setEnabled (False)
        
        # adding the first cluster to the toolbox - a cluster is always present!
        self._cluster_page_list = []
        self.connect (self.pushButton, SIGNAL ("clicked()"), self.addCluster)  # connect the 'add-cluster' button to the method that taps into the model for cluster addition.
        self.connect (self.graph_view.getComm(), SIGNAL ("addCluster_MSignal(int)"), self.addClusterPage)
        self.connect (self.graph_view.getComm(), SIGNAL ("deleteCluster_MSignal(int)"), self.removeClusterPage)
        self.connect (self.graph_view.getComm(), SIGNAL ("updateClusterName_MSignal(int, QString)"), self.updateClusterViewName)
        self.addCluster () # add the first cluster. At least one cluster needs to be always present.
        self.disableAllClusterPagesDeleteButton() # since there's only one cluster page, the delete button is disabled.
        
        #size = self.style ().pixelMetric (QStyle.PM_ToolBarIconSize)
        iconSize = QSize (16, 16) #QSize (size, size)
        
        zoomInIcon = QToolButton ()
        zoomInIcon.setCursor (Qt.PointingHandCursor)
        zoomInIcon.setAutoRepeat (True)
        zoomInIcon.setAutoRepeatInterval (33)
        zoomInIcon.setAutoRepeatDelay (0)
        zoomInIcon.setIconSize (iconSize)
        
        zoomOutIcon = QToolButton ()
        zoomOutIcon.setCursor (Qt.PointingHandCursor)
        zoomOutIcon.setAutoRepeat (True)
        zoomOutIcon.setAutoRepeatInterval (33)
        zoomOutIcon.setAutoRepeatDelay (0)
        zoomOutIcon.setIconSize (iconSize)
        
        self.zoomSlider = QSlider ()
        self.zoomSlider.setCursor (Qt.PointingHandCursor)
        self.zoomSlider.setMinimum (200)
        self.zoomSlider.setMaximum (280)
        self.zoomSlider.setValue   (240)
        self.zoomSlider.setTickPosition (QSlider.TicksRight)
        
        # Zoom slider layout
        zoomSliderLayout = QVBoxLayout ()
        zoomSliderLayout.addWidget (zoomInIcon)
        zoomSliderLayout.addWidget (self.zoomSlider)
        zoomSliderLayout.addWidget (zoomOutIcon)
        
        self.printOutBtn = QPushButton()
        self.printOutBtn.setText ("print")
        self.printOutBtn.setFont (self.font)
        self.printOutBtn.setEnabled (False)
        
        self.newJADESceneBtn = QPushButton()
        self.newJADESceneBtn.setText ("new")
        self.newJADESceneBtn.setFont (self.font)
        self.newJADESceneBtn.setEnabled (False)
        
        self.loadNodesDescrpBtn = QPushButton()
        self.loadNodesDescrpBtn.setText ("load Nodes Description")
        self.loadNodesDescrpBtn.setFont (self.font)
        self.loadNodesDescrpBtn.setEnabled (True)
        
        self.graphLoadBtn = QPushButton()
        self.graphLoadBtn.setText ("load")
        self.graphLoadBtn.setFont (self.font)
        self.graphLoadBtn.setEnabled (False)
        
        self.graphSaveBtn = QPushButton()
        self.graphSaveBtn.setText ("save")
        self.graphSaveBtn.setFont (self.font)
        self.graphSaveBtn.setEnabled (False)
        
        self.resetButton = QToolButton ()
        self.resetButton.setText ("r")
        self.resetButton.setFont (self.font)
        self.resetButton.setEnabled (False)
        
        self.message_bar = QLineEdit ()
        self.message_bar.setGeometry (QRect (0, 0, 190, 12))
        self.message_bar.setObjectName ('message_bar')
        self.message_bar.setText ('Node description file, please.')
        self.message_bar.setFont (self.font)
        self.message_bar.setEnabled  (True)
        self.message_bar.setReadOnly (True)
        
        self.spacer = QSpacerItem (30, 20, QSizePolicy.Fixed, QSizePolicy.Fixed );
        
        # Label layout
        labelLayout = QHBoxLayout ()
        self.label = QLabel (name)
        self.label.setFont (self.font)
        labelLayout.addWidget (self.loadNodesDescrpBtn)
        labelLayout.addWidget (self.newJADESceneBtn)
        labelLayout.addWidget (self.graphLoadBtn)
        labelLayout.addWidget (self.graphSaveBtn)
        labelLayout.addWidget (self.printOutBtn)
        labelLayout.addItem   (self.spacer)
        labelLayout.addWidget (self.message_bar)
        #labelLayout.addWidget (self.label)
        labelLayout.addStretch ()
        
        # top layout
        topLayout = QGridLayout ()
        topLayout.setHorizontalSpacing (0)
        topLayout.setVerticalSpacing (0)
        topLayout.addLayout (labelLayout, 0, 1)
        topLayout.addWidget (self._toolBox, 1, 0)
        topLayout.addWidget (self.resetButton, 0, 2)
        topLayout.addWidget (self.graphicsView, 1, 1)
        topLayout.addLayout (zoomSliderLayout, 1, 2)
        self.setLayout (topLayout)
        
        self.connect (self.resetButton, SIGNAL ("clicked()"), self.resetView)
        self.connect (self.zoomSlider,  SIGNAL ("valueChanged(int)"), self.setupMatrix)
        self.connect (self.graphicsView.verticalScrollBar   (), SIGNAL ("valueChanged(int)"), self.setResetButtonEnabled)
        self.connect (self.graphicsView.horizontalScrollBar (), SIGNAL ("valueChanged(int)"), self.setResetButtonEnabled)
        self.connect (zoomInIcon,  SIGNAL ("clicked()"), self.zoomIn)
        self.connect (zoomOutIcon, SIGNAL ("clicked()"), self.zoomOut)
        
        self.setupMatrix ()
        
        self.printer = QPrinter (QPrinter.HighResolution)
        
        self.prev_selection_list = []
        
        self.isClusterRemovalOverridden = False
    
    def setMessageBarText (self, text):
        
        self.message_bar.setText (text)
    
    def enableControls (self):
        
        self.printOutBtn.setEnabled (True)
        self.newJADESceneBtn.setEnabled (True)
        self.graphLoadBtn.setEnabled (True)
        self.graphSaveBtn.setEnabled (True)
        self._toolBox.setEnabled (True)
    
    def disableControls (self):
        
        self.printOutBtn.setEnabled (False)
        self.newJADESceneBtn.setEnabled (False)
        self.graphLoadBtn.setEnabled (False)
        self.graphSaveBtn.setEnabled (False)
        self._toolBox.setEnabled (False)
    
    def setGraphicsViewCSSBackground (self):
        
        self.graphicsView.setStyleSheet('background-color: qlineargradient(spread:pad, x1:0, y1:1, x2:0, y2:0, stop:0 rgba(125, 125, 135, 255), stop:1 rgba(215, 215, 215, 255));\ncolor: rgb(255, 255, 255);')
    
    def selectionChanged (self):
        
        current_selection_list = self.scene.selectedItems ()
        list_of_unselected_items = [item for item in self.prev_selection_list if item not in current_selection_list]
        
        # un-mark items in list_of_unselected_items
        for item in list_of_unselected_items:
            if self.graph_view.isTag (item) == True:
                item.switchToUnSelectedStateColour ()
        
        # mark items in current_selection_list
        for item in current_selection_list:
            if self.graph_view.isTag (item) == True:
                item.switchToSelectedStateColour ()
        
        self.prev_selection_list = current_selection_list
    
    # - - -    cluster-specific methods   - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def addCluster (self):
        
        self.graph_view.delegateClusterAddition ()
    
    def addClusterPage (self, new_cluster_id):
        
        self.enableAllClusterPagesDeleteButton () # enable all the cluster page's delete buttons (as I can be bothered to go look for the one that got previously disabled) 
        
        tmp_w = QWidget ()
        tmp_l = QLabel (tmp_w)
        tmp_e = QLineEdit (tmp_w)
        tmp_b = QPushButton (tmp_w)
        self._cluster_page_list.append ([new_cluster_id, tmp_w, tmp_l, tmp_e, tmp_b])
        
        tmp_w.setGeometry (QRect (0, 0, 131, 241))
        tmp_w.setObjectName ('Cluster_' + str (new_cluster_id))
        
        tmp_l.setGeometry (QRect (4, 6, 62, 16))
        tmp_l.setFont (self.font)
        tmp_l.setObjectName ('label_' + str (new_cluster_id))
        
        tmp_e.setGeometry (QRect (2, 20, 60, 16))
        tmp_e.setObjectName ('groupLineEdit_' + str (new_cluster_id))
        
        tmp_b.setGeometry (QRect (2, 50, 60, 16))
        tmp_b.setFont (self.font)
        tmp_b.setObjectName ('pushButton_' + str (new_cluster_id))
        
        self._toolBox.addItem (tmp_w, 'cluster_page_'+str(new_cluster_id))
        self._toolBox.setItemText (self._toolBox.indexOf (tmp_w), QApplication.translate ('Form', 'C_'+str(new_cluster_id), None, QApplication.UnicodeUTF8))
        tmp_l.setText (QApplication.translate ("Form", "name cluster", None, QApplication.UnicodeUTF8))
        tmp_b.setText (QApplication.translate ("Form", "delete", None, QApplication.UnicodeUTF8))
        self._toolBox.setCurrentIndex (new_cluster_id)
        QMetaObject.connectSlotsByName (self)
        
        # hook up the delete button (use a closure)
        receiver = lambda : self.removeCluster (new_cluster_id)
        self.connect (tmp_b, SIGNAL ("clicked()"), receiver)  # connect the 'add cluster' button to the method generating new cluster pages.
        
        receiver2 = lambda value : self.updateClusterModelName (new_cluster_id, value)
        self.connect (tmp_e, SIGNAL ("textChanged(QString)"), receiver2)
    
    def removeAllClusters (self):
        
        copy_list = list (self._cluster_page_list)
        
        self.isClusterRemovalOverridden = True
        for item in copy_list:
                self.removeCluster (item[0])
        
        self.graph_view.initGraphViewLists ()
        self.graph_view.initComm  ()
        self.graph_view.initModel ()
        
        self._cluster_page_list = []
        self.addCluster () # add the first cluster. At least one cluster needs to be always present.
        
        self.isClusterRemovalOverridden = False # remove override
    
    def removeCluster (self, cluster_id):
        
        self.graph_view.delegateClusterRemoval (cluster_id)
    
    def removeClusterPage (self, cluster_id):
        
        threshold = 1 if self.isClusterRemovalOverridden==False else 0
        
        qq = len(self._cluster_page_list)
        if qq > threshold:
            for i in range (qq-1, -1, -1):
                if int(self._cluster_page_list[i][0]) == cluster_id:
                    self._toolBox.removeItem (self._toolBox.indexOf(self._cluster_page_list[i][1]))
                    del self._cluster_page_list[i]
                    break
        
        if len(self._cluster_page_list) == 1:
            self.disableAllClusterPagesDeleteButton ()
    
    def disableAllClusterPagesDeleteButton (self):
        
        if len(self._cluster_page_list) > 0:
            for item in self._cluster_page_list:
                item[4].setEnabled (False)
    
    def enableAllClusterPagesDeleteButton (self):
        
        if len(self._cluster_page_list) > 0:
            for item in self._cluster_page_list:
                item[4].setEnabled (True)
    
    def updateClusterModelName (self, cluster_id, text):
        
        self.graph_view.delegateUpdateClusterName (cluster_id, text)
    
    def updateClusterViewName (self, cluster_id, text):
        
        if len(self._cluster_page_list) > 0:
            for item in self._cluster_page_list:
                if int(item[0]) == cluster_id:
                    item[3].setText (str(text))
    
    def updateCurrentClusterNodeList (self, node):
        
        # fetch the current cluster's id.
        curr_widget = self._toolBox.currentWidget()
        for item in self._cluster_page_list:
            if item[1] == curr_widget:
                
                # delegate cluster node list update.
                self.graph_view.delegateClusterNodeListUpdate (item[0], node)
                break
    
    def getCurrentClusterIndex (self):
        
        return self._toolBox.currentIndex ()
    
    # - - - - - - - - - - - - - - - - - - -  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def getGraphicsView (self):
        
        return self.graphicsView
    
    def resetView (self):
        
        self.zoomSlider.setValue (250)
        self.setupMatrix ()
        self.graphicsView.ensureVisible (QRectF (0, 0, 0, 0))
        
        self.resetButton.setEnabled (False)
    
    def setResetButtonEnabled (self):
        
        self.resetButton.setEnabled (True)
    
    def setupMatrix (self):
        
        scale = pow (2.0, (self.zoomSlider.value () - 250) / 50.0)
        
        matrix = QMatrix ()
        matrix.scale (scale, scale)
        
        self.graphicsView.setMatrix (matrix)
        self.setResetButtonEnabled ()
    
    def printOutGraph (self):
        
        qqq = QPainter (self.printer)
        self.graphicsView.render(qqq)
    
    def importNodesDescription (self):
        
        aa = QFileDialog (self).getOpenFileName()
        if aa != QString (u''): # it can be equal to QString(u'') when the user presses the Escape key, so in that circumstance, nothing is returned.
            self.graph_view.setNodesDescription (open(aa).read())
    
    def resetScene (self):
        
        self.removeAllClusters ()
        self.resetView ()
    
    def exportGraph (self):
        
        aa = QFileDialog (self).getSaveFileName ()
        if aa != QString (u''): # it can be equal to QString(u'') when the user presses the Escape key, so in that circumstance, nothing is returned.
            file0 = open (aa, 'w')
            file0.write (self.graph_view.delegateExport ())
            file0.close ()
            print '\n*** file exported.\n'
    
    def importGraph (self):
        
        aa = QFileDialog (self).getOpenFileName ()
        if aa != QString (u''): # it can be equal to QString(u'') when the user presses the Escape key, so in that circumstance, nothing is returned.
            file0 = open (aa, 'r')
            XML_content = file0.read()
            file0.close ()
            self.graph_view.delegateImport (XML_content)
            print '\n*** file imported.\n'
    
    # zoom slider
    def zoomIn  (self) : self.zoomSlider.setValue (self.zoomSlider.value() + 1)
    def zoomOut (self) : self.zoomSlider.setValue (self.zoomSlider.value() - 1)
    def getZoomSlider (self): return self.zoomSlider
    
    def setToolboxCSSColorScheme (self, css): self._toolBox.setStyleSheet (css)

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    def wireViewItemsUp (self):
        
        self.connect (self.newJADESceneBtn,    SIGNAL ("clicked()"), self.resetScene)
        self.connect (self.loadNodesDescrpBtn, SIGNAL ("clicked()"), self.importNodesDescription)
        self.connect (self.graphSaveBtn,       SIGNAL ("clicked()"), self.exportGraph)
        self.connect (self.graphLoadBtn,       SIGNAL ("clicked()"), self.importGraph)
        self.connect (self.printOutBtn,        SIGNAL ("clicked()"), self.printOutGraph)
Example #38
0
class QtSlider(QtControl, ProxySlider):
    """ A Qt implementation of an Enaml ProxySlider.

    """
    #: A reference to the widget created by the proxy.
    widget = Typed(QSlider)

    #: Cyclic notification guard flags.
    _guard = Int(0)

    #--------------------------------------------------------------------------
    # Initialization API
    #--------------------------------------------------------------------------
    def create_widget(self):
        """ Create the underlying QSlider widget.

        """
        self.widget = QSlider(self.parent_widget())

    def init_widget(self):
        """ Initialize the underlying widget.

        """
        super(QtSlider, self).init_widget()
        d = self.declaration
        self.set_minimum(d.minimum)
        self.set_maximum(d.maximum)
        self.set_value(d.value)
        self.set_orientation(d.orientation)
        self.set_page_step(d.page_step)
        self.set_single_step(d.single_step)
        self.set_tick_interval(d.tick_interval)
        self.set_tick_position(d.tick_position)
        self.set_tracking(d.tracking)
        self.widget.valueChanged.connect(self.on_value_changed)

    #--------------------------------------------------------------------------
    # Signal Handlers
    #--------------------------------------------------------------------------
    def on_value_changed(self):
        """ Send the 'value_changed' action to the Enaml widget when the
        slider value has changed.

        """
        if not self._guard & VALUE_FLAG:
            self._guard |= VALUE_FLAG
            try:
                self.declaration.value = self.widget.value()
            finally:
                self._guard &= ~VALUE_FLAG

    #--------------------------------------------------------------------------
    # ProxySlider API
    #--------------------------------------------------------------------------
    def set_maximum(self, maximum):
        """ Set the maximum value of the underlying widget.

        """
        self.widget.setMaximum(maximum)

    def set_minimum(self, minimum):
        """ Set the minimum value of the underlying widget.

        """
        self.widget.setMinimum(minimum)

    def set_value(self, value):
        """ Set the value of the underlying widget.

        """
        if not self._guard & VALUE_FLAG:
            self._guard |= VALUE_FLAG
            try:
                self.widget.setValue(value)
            finally:
                self._guard &= ~VALUE_FLAG

    def set_page_step(self, page_step):
        """ Set the page step of the underlying widget.

        """
        self.widget.setPageStep(page_step)

    def set_single_step(self, single_step):
        """ Set the single step of the underlying widget.

        """
        self.widget.setSingleStep(single_step)

    def set_tick_interval(self, interval):
        """ Set the tick interval of the underlying widget.

        """
        self.widget.setTickInterval(interval)

    def set_tick_position(self, tick_position):
        """ Set the tick position of the underlying widget.

        """
        self.widget.setTickPosition(TICK_POSITION[tick_position])

    def set_orientation(self, orientation):
        """ Set the orientation of the underlying widget.

        """
        self.widget.setOrientation(ORIENTATION[orientation])

    def set_tracking(self, tracking):
        """ Set the tracking of the underlying widget.

        """
        self.widget.setTracking(tracking)
class PreviewWindow(QMainWindow):
    """
    QMainWindow subclass used to show frames & tracking.
    """
    def __init__(self, controller):
        QMainWindow.__init__(self)

        # set controller
        self.controller = controller

        # set title
        self.setWindowTitle("Preview")

        # get parameter window position & size
        param_window_x = self.controller.param_window.x()
        param_window_y = self.controller.param_window.y()
        param_window_width = self.controller.param_window.width()

        # set position & size to be next to the parameter window
        self.setGeometry(param_window_x + param_window_width, param_window_y,
                         10, 10)

        # create main widget
        self.main_widget = QWidget(self)
        self.main_widget.setMinimumSize(QSize(500, 500))

        # create main layout
        self.main_layout = QGridLayout(self.main_widget)
        self.main_layout.setContentsMargins(0, 0, 0, 0)
        self.main_layout.setSpacing(0)

        # create label that shows frames
        self.image_widget = QWidget(self)
        self.image_layout = QVBoxLayout(self.image_widget)
        self.image_layout.setContentsMargins(0, 0, 0, 0)
        self.image_label = PreviewQLabel(self)
        self.image_label.setSizePolicy(QSizePolicy.MinimumExpanding,
                                       QSizePolicy.MinimumExpanding)
        self.image_label.setAlignment(Qt.AlignTop | Qt.AlignLeft)
        self.image_label.hide()
        self.image_layout.addWidget(self.image_label)
        self.main_layout.addWidget(self.image_widget, 0, 0)

        # self.image_label.setStyleSheet("border: 1px solid rgba(122, 127, 130, 0.5)")

        self.bottom_widget = QWidget(self)
        self.bottom_layout = QVBoxLayout(self.bottom_widget)
        self.bottom_layout.setContentsMargins(8, 0, 8, 8)
        self.bottom_widget.setMaximumHeight(40)
        self.main_layout.addWidget(self.bottom_widget, 1, 0)

        # create label that shows crop instructions
        self.instructions_label = QLabel("")
        self.instructions_label.setStyleSheet("font-size: 11px;")
        self.instructions_label.setAlignment(Qt.AlignCenter)
        self.bottom_layout.addWidget(self.instructions_label)

        # create image slider
        self.image_slider = QSlider(Qt.Horizontal)
        self.image_slider.setFocusPolicy(Qt.StrongFocus)
        self.image_slider.setTickPosition(QSlider.NoTicks)
        self.image_slider.setTickInterval(1)
        self.image_slider.setSingleStep(1)
        self.image_slider.setValue(0)
        self.image_slider.valueChanged.connect(self.controller.show_frame)
        self.image_slider.hide()
        self.bottom_layout.addWidget(self.image_slider)

        self.zoom = 1
        self.offset = [0, 0]
        self.center_y = 0
        self.center_x = 0

        # initialize variables
        self.image = None  # image to show
        self.tracking_data = None  # list of tracking data
        self.selecting_crop = False  # whether user is selecting a crop
        self.changing_heading_angle = False  # whether the user is changing the heading angle
        self.body_crop = None
        self.final_image = None

        # set main widget
        self.setCentralWidget(self.main_widget)

        # set window buttons
        if pyqt_version == 5:
            self.setWindowFlags(Qt.CustomizeWindowHint
                                | Qt.WindowMinimizeButtonHint
                                | Qt.WindowMaximizeButtonHint
                                | Qt.WindowFullscreenButtonHint)
        else:
            self.setWindowFlags(Qt.CustomizeWindowHint
                                | Qt.WindowMinimizeButtonHint
                                | Qt.WindowMaximizeButtonHint)

        self.show()

    def wheelEvent(self, event):
        old_zoom = self.zoom
        self.zoom = max(1, self.zoom + event.pixelDelta().y() / 100)

        self.zoom = int(self.zoom * 100) / 100.0

        self.update_image_label(self.final_image, zooming=True)

    def start_selecting_crop(self):
        # start selecting crop
        self.selecting_crop = True

        # add instruction text
        self.instructions_label.setText("Click & drag to select crop area.")

    def plot_image(self,
                   image,
                   params,
                   crop_params,
                   tracking_results,
                   new_load=False,
                   new_frame=False,
                   show_slider=True,
                   crop_around_body=False):
        if image is None:
            self.update_image_label(None)
            self.image_slider.hide()
            self.image_label.hide()
        else:
            if new_load:
                self.image_label.show()
                self.remove_tail_start()
                if show_slider:
                    if not self.image_slider.isVisible():
                        self.image_slider.setValue(0)
                        self.image_slider.setMaximum(self.controller.n_frames -
                                                     1)
                        self.image_slider.show()
                else:
                    self.image_slider.hide()

                max_inititial_size = 500
                if image.shape[0] > max_inititial_size:
                    min_height = max_inititial_size
                    min_width = max_inititial_size * image.shape[
                        1] / image.shape[0]
                elif image.shape[1] > max_inititial_size:
                    min_width = max_inititial_size
                    min_height = max_inititial_size * image.shape[
                        0] / image.shape[1]
                else:
                    min_height = image.shape[0]
                    min_width = image.shape[1]

                self.main_widget.setMinimumSize(
                    QSize(min_width, min_height + self.bottom_widget.height()))

            # convert to RGB
            if len(image.shape) == 2:
                image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB)

            # update image
            self.image = image.copy()

            try:
                body_crop = params['body_crop']
            except:
                body_crop = None

            try:
                tail_start_coords = params['tail_start_coords']

                # add tail start point to image
                cv2.circle(image, (int(
                    round(tail_start_coords[1] - crop_params['offset'][1])),
                                   int(
                                       round(tail_start_coords[0] -
                                             crop_params['offset'][0]))), 1,
                           (180, 180, 50), -1)
            except (KeyError, TypeError) as error:
                tail_start_coords = None

            if tracking_results is not None:
                body_position = tracking_results['body_position']
                heading_angle = tracking_results['heading_angle']

                # add tracking to image
                image = tracking.add_tracking_to_frame(image,
                                                       tracking_results,
                                                       cropped=True)

                if body_crop is not None and body_position is not None:
                    if not crop_around_body:
                        # copy image
                        overlay = image.copy()

                        # draw tail crop overlay
                        cv2.rectangle(overlay,
                                      (int(body_position[1] - body_crop[1]),
                                       int(body_position[0] - body_crop[0])),
                                      (int(body_position[1] + body_crop[1]),
                                       int(body_position[0] + body_crop[0])),
                                      (242, 242, 65), -1)

                        # overlay with the original image
                        cv2.addWeighted(overlay, 0.2, image, 0.8, 0, image)

                        self.body_crop = None
                    else:
                        self.body_crop = body_crop

            if crop_around_body:
                _, image = tracking.crop_frame_around_body(
                    image, body_position, params['body_crop'])

            self.final_image = image

            # update image label
            self.update_image_label(
                self.final_image,
                zoom=(not (crop_around_body and body_position is not None)),
                new_load=new_load)

    def draw_crop_selection(self, start_crop_coords, end_crop_coords):
        if self.selecting_crop and self.image is not None:
            # convert image to rgb
            if len(self.image.shape) < 3:
                image = np.repeat(self.image[:, :, np.newaxis], 3, axis=2)
            else:
                image = self.image.copy()

            # copy image
            overlay = image.copy()

            # draw crop selection overlay
            cv2.rectangle(overlay,
                          (start_crop_coords[1], start_crop_coords[0]),
                          (end_crop_coords[1], end_crop_coords[0]),
                          (255, 51, 0), -1)

            # overlay with the original image
            cv2.addWeighted(overlay, 0.5, image, 0.5, 0, image)

            # update image label
            self.update_image_label(image)

    def change_offset(self, prev_coords, new_coords):
        self.offset[0] -= new_coords[0] - prev_coords[0]
        self.offset[1] -= new_coords[1] - prev_coords[1]

        self.update_image_label(self.final_image)

    def draw_tail_start(self, rel_tail_start_coords):
        if self.controller.params['type'] == "headfixed":
            # send new tail start coordinates to controller
            self.controller.update_tail_start_coords(rel_tail_start_coords)

            # clear instructions text
            self.instructions_label.setText("")

        if self.image is not None:
            image = self.image.copy()

            cv2.circle(image, (int(round(rel_tail_start_coords[1])),
                               int(round(rel_tail_start_coords[0]))), 1,
                       (180, 180, 50), -1)

            # update image label
            self.update_image_label(image)

    def remove_tail_start(self):
        self.update_image_label(self.image)

    def add_angle_overlay(self, angle):
        image = self.image.copy()
        image_height = self.image.shape[0]
        image_width = self.image.shape[1]
        center_y = image_height / 2
        center_x = image_width / 2

        cv2.arrowedLine(
            image,
            (int(center_x -
                 0.3 * image_height * np.sin((angle + 90) * np.pi / 180)),
             int(center_y -
                 0.3 * image_width * np.cos((angle + 90) * np.pi / 180))),
            (int(center_x +
                 0.3 * image_height * np.sin((angle + 90) * np.pi / 180)),
             int(center_y +
                 0.3 * image_width * np.cos((angle + 90) * np.pi / 180))),
            (50, 255, 50), 2)

        self.update_image_label(image)

    def remove_angle_overlay(self):
        self.update_image_label(self.image)

    def update_image_label(self,
                           image,
                           zoom=True,
                           new_load=False,
                           zooming=False):
        if image is not None and self.zoom != 1 and zoom:
            if zooming:
                self.offset[0] = min(
                    max(
                        0, self.offset[0] + int(
                            (self.image_label.image.shape[0]) / 2.0) -
                        int(round((image.shape[0] / self.zoom) / 2.0))),
                    image.shape[0] - int(round(image.shape[0] / self.zoom)))
                self.offset[1] = min(
                    max(
                        0, self.offset[1] + int(
                            (self.image_label.image.shape[1]) / 2.0) -
                        int(round((image.shape[1] / self.zoom) / 2.0))),
                    image.shape[1] - int(round(image.shape[1] / self.zoom)))
            else:
                self.offset[0] = min(
                    max(0, self.offset[0]),
                    image.shape[0] - int(round(image.shape[0] / self.zoom)))
                self.offset[1] = min(
                    max(0, self.offset[1]),
                    image.shape[1] - int(round(image.shape[1] / self.zoom)))

            if self.center_y is None:
                self.center_y = int(round(image.shape[0] / 2.0))
            if self.center_x is None:
                self.center_x = int(round(image.shape[1] / 2.0))

            image = image[
                self.offset[0]:int(round(image.shape[0] / self.zoom)) +
                self.offset[0],
                self.offset[1]:int(round(image.shape[1] / self.zoom)) +
                self.offset[1], :].copy()

        if image is not None:
            if zoom:
                self.setWindowTitle("Preview - Zoom: {:.1f}x".format(
                    self.zoom))
            else:
                self.setWindowTitle("Preview - Zoom: 1x")
        else:
            self.setWindowTitle("Preview")

        self.image_label.update_pixmap(image, new_load=new_load)

    def crop_selection(self, start_crop_coord, end_crop_coord):
        if self.selecting_crop:
            # stop selecting the crop
            self.selecting_crop = False

            # clear instruction text
            self.instructions_label.setText("")

            # update crop parameters from the selection
            self.controller.update_crop_from_selection(start_crop_coord,
                                                       end_crop_coord)

    def closeEvent(self, ce):
        if not self.controller.closing:
            ce.ignore()
        else:
            ce.accept()
Example #40
0
class ControlBar(QWidget):
    """
    Widget that contains the play/pause button, the progress bar and the speed slider.
    """
    play = pyqtSignal(name="Play")
    pause = pyqtSignal(name="Pause")
    seek = pyqtSignal(float, name="Time changed")
    speedChanged = pyqtSignal(int, name="Speed changed")

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

        self.log = getLoggerPassFilters(LOGGER_NAMES.LIVEPLAYER)

        self.button = PlayPauseButton()
        self.button.setMaximumWidth(100)
        self.button.clicked.connect(self.onButtonClicked)

        self.timeSlider = ClickableProgressBar()
        self.timeSlider.setMinimum(0)
        self.timeSlider.setMaximum(int(duration * 1000))
        self.timeSlider.valueChanged.connect(self.onSeek)

        self.speedLabel = QLabel("Speed: 1x")

        self.speedSlider = QSlider(Qt.Horizontal)
        self.speedSlider.setMaximumWidth(300)
        self.speedSlider.setMinimum(1)
        self.speedSlider.setMaximum(10)
        self.speedSlider.valueChanged.connect(self.onSpeedChanged)

        vertical = QVBoxLayout()

        horizontal = QHBoxLayout()
        horizontal.addWidget(self.speedLabel)
        horizontal.addWidget(self.speedSlider)
        horizontal.addItem(QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Expanding))
        vertical.addLayout(horizontal)

        horizontal = QHBoxLayout()
        horizontal.addWidget(self.button)
        horizontal.addWidget(self.timeSlider)
        vertical.addLayout(horizontal)

        self.setLayout(vertical)
        self.setGeometry(0, 0, 80, 60)

    def onButtonClicked(self):
        if self.button.playing:
            self.log.debug("Play clicked")
            self.play.emit()
        else:
            self.log.debug("Pause clicked")
            self.pause.emit()

    def onSeek(self):
        time = self.timeSlider.value() / 1000.0
        self.log.debug("Seek to %(arg1)d seconds", {"arg1": time})
        self.seek.emit(time)

    def onSpeedChanged(self):
        speed = self.speedSlider.value()
        self.log.debug("Slider changed value: %(arg1)d", {"arg1": speed})
        self.speedLabel.setText("Speed: {}x".format(speed))
        self.speedChanged.emit(speed)
class PreferencesDialogBase(QDialog):
    def __init__(self, parent, app):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self.app = app
        self._setupUi()
        
        self.connect(self.filterHardnessSlider, SIGNAL("valueChanged(int)"), self.filterHardnessLabel.setNum)
        self.connect(self.buttonBox, SIGNAL('clicked(QAbstractButton*)'), self.buttonClicked)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
    
    def _setupScanTypeBox(self, labels):
        self.scanTypeHLayout = QHBoxLayout()
        self.scanTypeLabel = QLabel(self)
        self.scanTypeLabel.setText(tr("Scan Type:"))
        self.scanTypeLabel.setMinimumSize(QSize(100, 0))
        self.scanTypeLabel.setMaximumSize(QSize(100, 16777215))
        self.scanTypeHLayout.addWidget(self.scanTypeLabel)
        self.scanTypeComboBox = QComboBox(self)
        for label in labels:
            self.scanTypeComboBox.addItem(label)
        self.scanTypeHLayout.addWidget(self.scanTypeComboBox)
        self.widgetsVLayout.addLayout(self.scanTypeHLayout)
    
    def _setupFilterHardnessBox(self):
        self.filterHardnessHLayout = QHBoxLayout()
        self.filterHardnessLabel = QLabel(self)
        self.filterHardnessLabel.setText(tr("Filter Hardness:"))
        self.filterHardnessLabel.setMinimumSize(QSize(0, 0))
        self.filterHardnessHLayout.addWidget(self.filterHardnessLabel)
        self.filterHardnessVLayout = QVBoxLayout()
        self.filterHardnessVLayout.setSpacing(0)
        self.filterHardnessHLayoutSub1 = QHBoxLayout()
        self.filterHardnessHLayoutSub1.setSpacing(12)
        self.filterHardnessSlider = QSlider(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.filterHardnessSlider.sizePolicy().hasHeightForWidth())
        self.filterHardnessSlider.setSizePolicy(sizePolicy)
        self.filterHardnessSlider.setMinimum(1)
        self.filterHardnessSlider.setMaximum(100)
        self.filterHardnessSlider.setTracking(True)
        self.filterHardnessSlider.setOrientation(Qt.Horizontal)
        self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessSlider)
        self.filterHardnessLabel = QLabel(self)
        self.filterHardnessLabel.setText("100")
        self.filterHardnessLabel.setMinimumSize(QSize(21, 0))
        self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessLabel)
        self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub1)
        self.filterHardnessHLayoutSub2 = QHBoxLayout()
        self.filterHardnessHLayoutSub2.setContentsMargins(-1, 0, -1, -1)
        self.moreResultsLabel = QLabel(self)
        self.moreResultsLabel.setText(tr("More Results"))
        self.filterHardnessHLayoutSub2.addWidget(self.moreResultsLabel)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.filterHardnessHLayoutSub2.addItem(spacerItem)
        self.fewerResultsLabel = QLabel(self)
        self.fewerResultsLabel.setText(tr("Fewer Results"))
        self.filterHardnessHLayoutSub2.addWidget(self.fewerResultsLabel)
        self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub2)
        self.filterHardnessHLayout.addLayout(self.filterHardnessVLayout)
    
    def _setupBottomPart(self):
        # The bottom part of the pref panel is always the same in all editions.
        self.fontSizeLabel = QLabel(tr("Font size:"))
        self.fontSizeSpinBox = QSpinBox()
        self.fontSizeSpinBox.setMinimum(5)
        self.widgetsVLayout.addLayout(horizontalWrap([self.fontSizeLabel, self.fontSizeSpinBox, None]))
        self.languageLabel = QLabel(tr("Language:"), self)
        self.languageComboBox = QComboBox(self)
        for lang in SUPPORTED_LANGUAGES:
            self.languageComboBox.addItem(LANGNAMES[lang])
        self.widgetsVLayout.addLayout(horizontalWrap([self.languageLabel, self.languageComboBox, None]))
        self.copyMoveLabel = QLabel(self)
        self.copyMoveLabel.setText(tr("Copy and Move:"))
        self.widgetsVLayout.addWidget(self.copyMoveLabel)
        self.copyMoveDestinationComboBox = QComboBox(self)
        self.copyMoveDestinationComboBox.addItem(tr("Right in destination"))
        self.copyMoveDestinationComboBox.addItem(tr("Recreate relative path"))
        self.copyMoveDestinationComboBox.addItem(tr("Recreate absolute path"))
        self.widgetsVLayout.addWidget(self.copyMoveDestinationComboBox)
        self.customCommandLabel = QLabel(self)
        self.customCommandLabel.setText(tr("Custom Command (arguments: %d for dupe, %r for ref):"))
        self.widgetsVLayout.addWidget(self.customCommandLabel)
        self.customCommandEdit = QLineEdit(self)
        self.widgetsVLayout.addWidget(self.customCommandEdit)
    
    def _setupAddCheckbox(self, name, label, parent=None):
        if parent is None:
            parent = self
        cb = QCheckBox(parent)
        cb.setText(label)
        setattr(self, name, cb)
    
    def _setupPreferenceWidgets(self):
        # Edition-specific
        pass
    
    def _setupUi(self):
        self.setWindowTitle(tr("Preferences"))
        self.resize(304, 263)
        self.setSizeGripEnabled(False)
        self.setModal(True)
        self.mainVLayout = QVBoxLayout(self)
        self.widgetsVLayout = QVBoxLayout()
        self._setupPreferenceWidgets()
        self.mainVLayout.addLayout(self.widgetsVLayout)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok|QDialogButtonBox.RestoreDefaults)
        self.mainVLayout.addWidget(self.buttonBox)
        if (not ISOSX) and (not ISLINUX):
            self.mainVLayout.removeWidget(self.ignoreHardlinkMatches)
            self.ignoreHardlinkMatches.setHidden(True)
    
    def _load(self, prefs, setchecked):
        # Edition-specific
        pass
    
    def _save(self, prefs, ischecked):
        # Edition-specific
        pass
    
    def load(self, prefs=None):
        if prefs is None:
            prefs = self.app.prefs
        self.filterHardnessSlider.setValue(prefs.filter_hardness)
        self.filterHardnessLabel.setNum(prefs.filter_hardness)
        setchecked = lambda cb, b: cb.setCheckState(Qt.Checked if b else Qt.Unchecked)
        setchecked(self.mixFileKindBox, prefs.mix_file_kind)
        setchecked(self.useRegexpBox, prefs.use_regexp)
        setchecked(self.removeEmptyFoldersBox, prefs.remove_empty_folders)
        setchecked(self.ignoreHardlinkMatches, prefs.ignore_hardlink_matches)
        setchecked(self.debugModeBox, prefs.debug_mode)
        self.copyMoveDestinationComboBox.setCurrentIndex(prefs.destination_type)
        self.customCommandEdit.setText(prefs.custom_command)
        self.fontSizeSpinBox.setValue(prefs.tableFontSize)
        try:
            langindex = SUPPORTED_LANGUAGES.index(self.app.prefs.language)
        except ValueError:
            langindex = 0
        self.languageComboBox.setCurrentIndex(langindex)
        self._load(prefs, setchecked)
    
    def save(self):
        prefs = self.app.prefs
        prefs.filter_hardness = self.filterHardnessSlider.value()
        ischecked = lambda cb: cb.checkState() == Qt.Checked
        prefs.mix_file_kind = ischecked(self.mixFileKindBox)
        prefs.use_regexp = ischecked(self.useRegexpBox)
        prefs.remove_empty_folders = ischecked(self.removeEmptyFoldersBox)
        prefs.ignore_hardlink_matches = ischecked(self.ignoreHardlinkMatches)
        prefs.debug_mode = ischecked(self.debugModeBox)
        prefs.destination_type = self.copyMoveDestinationComboBox.currentIndex()
        prefs.custom_command = str(self.customCommandEdit.text())
        prefs.tableFontSize = self.fontSizeSpinBox.value()
        lang = SUPPORTED_LANGUAGES[self.languageComboBox.currentIndex()]
        oldlang = self.app.prefs.language
        if oldlang not in SUPPORTED_LANGUAGES:
            oldlang = 'en'
        if lang != oldlang:
            QMessageBox.information(self, "", tr("dupeGuru has to restart for language changes to take effect."))
        self.app.prefs.language = lang
        self._save(prefs, ischecked)
    
    #--- Events
    def buttonClicked(self, button):
        role = self.buttonBox.buttonRole(button)
        if role == QDialogButtonBox.ResetRole:
            self.resetToDefaults()
Example #42
0
class XZoomSlider(QWidget):
    zoomAmountChanged   = Signal(int)
    
    def __init__(self, parent=None):
        super(XZoomSlider, self).__init__(parent)
        
        # define the interface
        in_icon  = projexui.resources.find('img/zoom_in.png')
        out_icon = projexui.resources.find('img/zoom_out.png')
        
        self._zoomInButton = QToolButton(self)
        self._zoomInButton.setAutoRaise(True)
        self._zoomInButton.setToolTip('Zoom In')
        self._zoomInButton.setIcon(QIcon(in_icon))
        
        self._zoomOutButton = QToolButton(self)
        self._zoomOutButton.setAutoRaise(True)
        self._zoomOutButton.setToolTip('Zoom Out')
        self._zoomOutButton.setIcon(QIcon(out_icon))
        
        self._zoomSlider = QSlider(Qt.Horizontal, self)
        self._zoomSlider.setRange(10, 100)
        self._zoomSlider.setValue(100)
        
        # define the layout
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self._zoomOutButton)
        layout.addWidget(self._zoomSlider)
        layout.addWidget(self._zoomInButton)
        
        self.setLayout(layout)
        
        # create connections
        self._zoomSlider.valueChanged.connect(self.emitZoomAmountChanged)
        self._zoomInButton.clicked.connect(self.zoomIn)
        self._zoomOutButton.clicked.connect(self.zoomOut)
    
    def emitZoomAmountChanged(self):
        """
        Emits the current zoom amount, provided the signals are not being
        blocked.
        """
        if not self.signalsBlocked():
            self.zoomAmountChanged.emit(self.zoomAmount())
    
    def maximum(self):
        """
        Returns the maximum zoom level for this widget.
        
        :return     <int>
        """
        return self._zoomSlider.maximum()
    
    def minimum(self):
        """
        Returns the minimum zoom level for this widget.
        
        :return     <int>
        """
        return self._zoomSlider.minimum()
    
    def setMaximum(self, maximum):
        """
        Sets the maximum zoom level for this widget.
        
        :param      maximum | <int>
        """
        self._zoomSlider.setMaximum(minimum)
    
    def setMinimum(self, minimum):
        """
        Sets the minimum zoom level for this widget.
        
        :param      minimum | <int>
        """
        self._zoomSlider.setMinimum(minimum)
    
    def setZoomStep(self, amount):
        """
        Sets how much a single step for the zoom in/out will be.
        
        :param      amount | <int>
        """
        self._zoomSlider.setPageStep(amount)
    
    @Slot(int)
    def setZoomAmount(self, amount):
        """
        Sets the zoom amount for this widget to the inputed amount.
        
        :param      amount | <int>
        """
        self._zoomSlider.setValue(amount)
    
    def zoomAmount(self):
        """
        Returns the current zoom amount for this widget.
        
        :return     <int>
        """
        return self._zoomSlider.value()
    
    @Slot()
    def zoomIn(self):
        """
        Zooms in by a single page step.
        """
        self._zoomSlider.triggerAction(QSlider.SliderPageStepAdd)
    
    def zoomInButton(self):
        """
        Returns the zoom in button from the left side of this widget.
        
        :return     <QToolButton>
        """
        return self._zoomInButton
    
    @Slot()
    def zoomOut(self):
        """
        Zooms out by a single page step.
        """
        self._zoomSlider.triggerAction(QSlider.SliderPageStepSub)
    
    def zoomOutButton(self):
        """
        Returns the zoom out button from the right side of this widget.
        
        :return     <QToolButton>
        """
        return self._zoomOutButton
    
    def zoomSlider(self):
        """
        Returns the slider widget of this zoom slider.
        
        :return     <QSlider>
        """
        return self._zoomSlider
    
    def zoomStep(self):
        """
        Returns the amount for a single step when the user clicks the zoom in/
        out amount.
        
        :return     <int>
        """
        return self._zoomSlider.pageStep()
    
    x_maximum  = Property(int, maximum, setMaximum)
    x_minimum  = Property(int, minimum, setMinimum)
    z_zoomStep = Property(int, zoomStep, setZoomStep)
Example #43
0
class XZoomSlider(QWidget):
    zoomAmountChanged = Signal(int)

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

        # define the interface
        in_icon = projexui.resources.find('img/zoom_in.png')
        out_icon = projexui.resources.find('img/zoom_out.png')

        self._zoomInButton = QToolButton(self)
        self._zoomInButton.setAutoRaise(True)
        self._zoomInButton.setToolTip('Zoom In')
        self._zoomInButton.setIcon(QIcon(in_icon))

        self._zoomOutButton = QToolButton(self)
        self._zoomOutButton.setAutoRaise(True)
        self._zoomOutButton.setToolTip('Zoom Out')
        self._zoomOutButton.setIcon(QIcon(out_icon))

        self._zoomSlider = QSlider(Qt.Horizontal, self)
        self._zoomSlider.setRange(10, 100)
        self._zoomSlider.setValue(100)

        # define the layout
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(self._zoomOutButton)
        layout.addWidget(self._zoomSlider)
        layout.addWidget(self._zoomInButton)

        self.setLayout(layout)

        # create connections
        self._zoomSlider.valueChanged.connect(self.emitZoomAmountChanged)
        self._zoomInButton.clicked.connect(self.zoomIn)
        self._zoomOutButton.clicked.connect(self.zoomOut)

    def emitZoomAmountChanged(self):
        """
        Emits the current zoom amount, provided the signals are not being
        blocked.
        """
        if not self.signalsBlocked():
            self.zoomAmountChanged.emit(self.zoomAmount())

    def maximum(self):
        """
        Returns the maximum zoom level for this widget.
        
        :return     <int>
        """
        return self._zoomSlider.maximum()

    def minimum(self):
        """
        Returns the minimum zoom level for this widget.
        
        :return     <int>
        """
        return self._zoomSlider.minimum()

    def setMaximum(self, maximum):
        """
        Sets the maximum zoom level for this widget.
        
        :param      maximum | <int>
        """
        self._zoomSlider.setMaximum(minimum)

    def setMinimum(self, minimum):
        """
        Sets the minimum zoom level for this widget.
        
        :param      minimum | <int>
        """
        self._zoomSlider.setMinimum(minimum)

    def setZoomStep(self, amount):
        """
        Sets how much a single step for the zoom in/out will be.
        
        :param      amount | <int>
        """
        self._zoomSlider.setPageStep(amount)

    @Slot(int)
    def setZoomAmount(self, amount):
        """
        Sets the zoom amount for this widget to the inputed amount.
        
        :param      amount | <int>
        """
        self._zoomSlider.setValue(amount)

    def zoomAmount(self):
        """
        Returns the current zoom amount for this widget.
        
        :return     <int>
        """
        return self._zoomSlider.value()

    @Slot()
    def zoomIn(self):
        """
        Zooms in by a single page step.
        """
        self._zoomSlider.triggerAction(QSlider.SliderPageStepAdd)

    def zoomInButton(self):
        """
        Returns the zoom in button from the left side of this widget.
        
        :return     <QToolButton>
        """
        return self._zoomInButton

    @Slot()
    def zoomOut(self):
        """
        Zooms out by a single page step.
        """
        self._zoomSlider.triggerAction(QSlider.SliderPageStepSub)

    def zoomOutButton(self):
        """
        Returns the zoom out button from the right side of this widget.
        
        :return     <QToolButton>
        """
        return self._zoomOutButton

    def zoomSlider(self):
        """
        Returns the slider widget of this zoom slider.
        
        :return     <QSlider>
        """
        return self._zoomSlider

    def zoomStep(self):
        """
        Returns the amount for a single step when the user clicks the zoom in/
        out amount.
        
        :return     <int>
        """
        return self._zoomSlider.pageStep()

    x_maximum = Property(int, maximum, setMaximum)
    x_minimum = Property(int, minimum, setMinimum)
    z_zoomStep = Property(int, zoomStep, setZoomStep)
Example #44
0
 def setMaximum(self, val):
     QSlider.setMaximum(self, val * 100)
Example #45
0
class Slider(QWidget):
    def __init__(
        self,
        caption,
        default_value,
        minimum_value=1,
        maximum_value=60,
        single_step=1,
        page_step=6,
        caption_size=None,
        unit="",
        time=False,
        tooltip="",
    ):
        QWidget.__init__(self)

        self.value = default_value
        self.unit = unit
        self.time = time

        description = QLabel(caption)
        description.setWordWrap(True)
        description.setToolTip(tooltip)
        if caption_size:
            description.setMaximumWidth(caption_size)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMaximum(maximum_value)
        self.slider.setMinimum(minimum_value)
        self.slider.setSingleStep(single_step)
        self.slider.setPageStep(page_step)
        self.slider.setToolTip(tooltip)
        # self.slider.setTickInterval(2)
        # self.slider.setTickPosition(QSlider.TicksBelow)
        self.slider.valueChanged.connect(self.__on_change)

        self.value_label = QLabel()

        hbox = QHBoxLayout()
        hbox.addWidget(description)
        hbox.addWidget(self.slider)
        hbox.addWidget(self.value_label)
        hbox.setMargin(0)
        self.setLayout(hbox)
        self.setContentsMargins(5, 0, 5, 0)
        self.slider.setValue(self.value)
        self.__on_change(self.value)

    def __on_change(self, value):
        # FIXME: Fill with spaces to reach the maximum length
        self.value = value
        unit = self.unit
        if self.time:
            minutes = timedelta(minutes=self.value)
            date = datetime(1, 1, 1) + minutes
            text = "%02dh %02dm" % (date.hour, date.minute)
        else:
            text = "%s %s" % (self.value, self.unit)
        self.value_label.setText(text)

    def get_value(self):
        return int(self.slider.value())
Example #46
0
File: mplayer.py Project: 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
Example #47
0
  def __init__(self,model):
    super(QWidget,self).__init__()
    if not isinstance(model,Model):
      raise Exception('Constructor argument of type Model expected.')
    self.setWindowTitle('Strandbeest simulator')

    # lazily simulates on full movement cycle of the strandbeest
    def iterateStates():
      '''
      Iterates over the first full movement cycle of the Strandbeest.
      In order to determine when the movement repeats, a heuristic is
      used, that stops simulating once the state vector becomes similar
      enough to the initial state vector. This heuristic assumes that
      the movement of the Strandbeest is time independent.
      '''
      x0 = model.state()
      yield x0
      for _ in range(2):
        model.increment(0.01)
        xi = model.state()
        yield xi
      limit = norm(xi-x0)
      while True:
        model.increment(0.01)
        xi = model.state()
        yield xi
        if norm(xi-x0) < limit: # <- heuristic condition for a full simulation cycle
          break

    # record simulation results
    record = _Record()
    view = _View(model,record)

    def recordStates(states):
      '''
      The _Canvas uses the states of the simulation to display movement curves of
      the nodes. For that purposes the simulated states are stored to the model in
      the record.states list.
      In order to notify the _View of newly simulated states, all callables in
      the record.changeListeners list are notified, with the new state vector as
      argument.
      '''
      for x in states:
        record.states.append(x)
        record.velocities.append( model.v(x,t=None) )
        record.times.append( model.t )
        for listener in record.changeListeners:
          listener(x)
        yield x
      del record.changeListeners

    def recordSceenshots(statesLoop):
      '''
      A little utility i created to be able to generate GIFs from
      the simulation. Saves screenshots from the current view of
      every 10th simulation step.
      '''
      i,j = 0,0
      for x in statesLoop:
        if i < 2*943 and 0 == i % 10:
          img = QPixmap.grabWidget(self)
          img = img.scaled(640,500,transformMode = Qt.SmoothTransformation)
          img.save('data/img%(j)d.jpg' % locals(),'jpg')
          j+=1
        i += 1
        yield x

    statesLoop = iterateStates()
    statesLoop = recordStates(statesLoop)
    statesLoop = itertools.cycle(statesLoop)
#     statesLoop = recordSceenshots(statesLoop)

    def tick():
      '''
      Advances the view by one tick (not neccessarily the simulation)
      '''
      model.setState( next(statesLoop) ) # <- in the first cycle this statement is redundant
    tick()
    timer = QTimer()
    timer.timeout.connect(tick)

    speedLabel = QLabel('? * Realtime')
    speedLabel.resize(speedLabel.sizeHint())
    speedLabel.setToolTip('Simulation speed [ticks/sec.].')
    
    speedSlider = QSlider(Qt.Horizontal)
    speedSlider.resize(speedSlider.sizeHint())
    speedSlider.setMinimum(0)
    speedSlider.setMaximum(6)
    speedSlider.setTickPosition(QSlider.TicksBelow)
    def tpsChange(value): # <- called whenever ticks/sec. change
      '''
      Changes the number of simulation ticks per second.
      '''
      value = 2**(value-2)
      speedLabel.setText( '%(value)6.2f * Realtime' % locals() )
      timer.setInterval(10/value)
    speedSlider.valueChanged[int].connect(tpsChange)
    speedSlider.setValue(4)

    def startStopClick():
      startStopClick.running ^= True 
      if startStopClick.running:
        timer.start()
        startStop.setText('Stop')
      else:
        timer.stop()
        startStop.setText('Start')
    startStop = QPushButton('Start/Stop')
    startStop.resize(startStop.sizeHint())
    startStop.setToolTip('Start the simulation.')
    startStop.clicked.connect(startStopClick)
    startStopClick.running = True
    startStopClick()

    grid = QGridLayout(self)
    grid.addWidget(startStop,0,0)
    grid.addWidget(speedSlider,0,1)
    grid.addWidget(speedLabel,0,2)
    grid.addWidget(view,1,0,1,3)
Example #48
0
class Tool(QToolBar):
    def __init__(self,parent):
        QToolBar.__init__(self,parent)
        self.parent = parent
        self.action_NewProject = QAction(Icons.newprj, 'Project', self)
        self.action_NewProject.triggered.connect(self.parent.treeWidget.newProject)
        self.action_NewProject.setToolTip("Create a New Project")

        self.action_Open = QAction(Icons.open, 'Open', self)
        self.action_Open.triggered.connect(self.parent.fileOpen)
        self.action_Open.setToolTip("Open File")

        self.action_Save = QAction(Icons.save, 'Save', self)
        self.action_Save.setShortcut('Ctrl+S')
        self.action_Save.triggered.connect(self.parent.fileSave)
        self.action_Save.setToolTip("Save Current File")

        self.action_SaveAll = QAction(Icons.saveall, 'SaveAll', self)
        self.action_SaveAll.setShortcut('Ctrl+A')
        self.action_SaveAll.triggered.connect(self.parent.fileSaveAll)
        self.action_SaveAll.setToolTip("Save All Files")
        
        
        
        self.action_Build = QAction(Icons.thread_view, 'Build', self)
        self.action_Build.setShortcut('Ctrl+B')
        self.action_Build.triggered.connect(self.parent.build_project)
        self.action_Debug = QAction(Icons.debug_exec, 'Debug', self)
        self.action_Refresh = QAction(Icons.refresh_tab, 'Refresh', self)
        self.action_Refresh.triggered.connect(self.parent.treeWidget.refreshCurrentProject)
        
        self.action_Run = QAction(Icons.run, 'Run', self)
        self.action_Run.setShortcut('Ctrl+R')
        self.action_Run.triggered.connect(self.parent.adb.run)
        self.action_RunFile = QAction(Icons.go, 'Cmd', self)
        self.action_RunFile.triggered.connect(self.parent.openCommand)
        self.parent.runButton.clicked.connect(self.parent.command.setCmdLine)
        self.action_Stop = QAction(Icons.stop, 'Stop', self)
        self.action_Stop.setShortcut('Ctrl+Q')
        self.action_Stop.triggered.connect(self.parent.adb.stop)
        self.action_Design = QAction(Icons.color_palette, 'Design', self)
        self.action_Design.triggered.connect(self.parent.design)
        self.action_Level = QAction(Icons.cmpC_pal, 'Level', self)
        self.action_Level.triggered.connect(self.parent.level)
        self.action_Todo = QAction(Icons.task_set, 'Todo', self)
        self.action_Todo.triggered.connect(self.parent.todo)
        
        self.action_Help = QAction(Icons.toc_open, 'Help', self)
        self.action_Help.triggered.connect(self.parent.help)
        self.action_Full = QAction(Icons.fullscreen, 'Full', self)
        self.action_Full.triggered.connect(self.parent.full)

        self.action_Stop.setDisabled(True)
        self.setToolLabel()
        self.setAllowedAreas(Qt.AllToolBarAreas)
        #self.setFixedHeight(40)
        #self.setIconSize(QSize(config.iconSize(),config.iconSize()))

        ''' Adding all Actions '''
        self.addAction(self.action_NewProject)
        self.addAction(self.action_Open)
        self.addAction(self.action_Save)
        self.addAction(self.action_SaveAll)
        #self.addAction(self.action_Refresh)
        self.addSeparator()
        self.addAction(self.action_Build)
        self.addAction(self.action_Run)
        #self.addAction(self.action_RunFile)
        self.addAction(self.action_Stop)
        self.addAction(self.action_Debug)
        self.addSeparator()
        self.addAction(self.action_Design)
        self.addAction(self.action_Level)
        self.addAction(self.action_Todo)
        self.initOptionsMenu()
        self.addSeparator()
        self.initStyleMenu()
        self.initLexerMenu()
        self.initApiMenu()
        #self.addAction(self.action_Help)
        #self.addAction(self.action_Full)
        self.addSeparator()
        self.initModeMenu()
            
    def colorChange(self, text, color):
        #print "colorChange ",text,color
        editStyle = config.readStyle()
        editStyle[text] = color
        config.writeStyle(editStyle)
        for i in range(len(self.parent.files)):
            self.parent.tabWidget.widget(i).setEditorStyle()
            
    def setColors(self,action):
        print action.text()
        
    def changeAll(self):
        self.colorChange("base", "#ffffff")
            
    def setIcon(self,val):
        config.setIconSize(val)
        self.setIconSize(QSize(val,val))
        
        
    def setToolLabel(self):
        if (config.toolLabel()):
            self.setToolButtonStyle(Qt.ToolButtonIconOnly)
            self.setIconSize(QSize(24,24))
        else:
            self.setIconSize(QSize(16,16))
            self.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
        
    '''Important for multiple callbacks in for loop'''
    def make_callback(self, text):
        return lambda:self.colorChange(text)
    
    ''' Options Menu '''
    def initOptionsMenu(self):
        men = QMenu()
        
        #Threshold Slider
        self.threshSlider = QSlider()
        self.threshSlider.setTickPosition(QSlider.TicksLeft)
        self.threshSlider.setOrientation(Qt.Horizontal)
        self.threshSlider.setValue(config.thresh())
        self.threshSlider.setMinimum(0)
        self.threshSlider.setMaximum(5)
        self.threshSlider.valueChanged.connect(self.parent.setThreshold)
        self.threshSliderAction = QWidgetAction(men)
        self.threshSliderAction.setDefaultWidget(self.threshSlider)
        
        #TabsWidth Slider
        self.tabsSlider = QSlider()
        self.tabsSlider.setTickPosition(QSlider.TicksLeft)
        self.tabsSlider.setOrientation(Qt.Horizontal)
        self.tabsSlider.setValue(config.tabwidth())
        self.tabsSlider.setMinimum(0)
        self.tabsSlider.setMaximum(8)
        self.tabsSlider.valueChanged.connect(self.parent.setTabWidth)
        self.tabsSliderAction = QWidgetAction(men)
        self.tabsSliderAction.setDefaultWidget(self.tabsSlider)
        
        #iconSize Slider
        self.iconSlider = QSlider()
        self.iconSlider.setTickPosition(QSlider.TicksLeft)
        self.iconSlider.setOrientation(Qt.Horizontal)
        self.iconSlider.setValue(config.iconSize())
        self.iconSlider.setMinimum(16)
        self.iconSlider.setMaximum(32)
        self.iconSlider.setSingleStep(2)
        self.iconSlider.valueChanged.connect(self.setIcon)
        self.iconSliderAction = QWidgetAction(men)
        self.iconSliderAction.setDefaultWidget(self.iconSlider)
        
        '''Font Button'''
        self.fontCombo = QFontComboBox()
        self.fontCombo.currentFontChanged.connect(self.parent.setFont)
        self.fontCombo.setCurrentFont(QFont(config.fontName()))
        self.fontComboMenu = QWidgetAction(men)
        self.fontComboMenu.setDefaultWidget(self.fontCombo)
        
        '''Font Size'''
        self.fontSizeCombo = QComboBox()
        for size in range(1,40):
            self.fontSizeCombo.addItem(str(size))
        self.fontSizeCombo.setCurrentIndex(config.fontSize())
        self.fontSizeCombo.currentIndexChanged.connect(self.parent.setFontSize)
        self.fontSizeComboMenu = QWidgetAction(men)
        self.fontSizeComboMenu.setDefaultWidget(self.fontSizeCombo)
        
        
        action_Android = QAction(Icons.android,'Android', self)
        action_Android.triggered.connect(self.parent.android)
        action_Ant = QAction(Icons.ant_view,'Ant', self)
        action_Ant.triggered.connect(self.parent.antt)
        action_Squirrel = QAction(Icons.nut,'Squirrel', self)
        action_Squirrel.triggered.connect(self.parent.squirrel)
        action_Ios1 = QAction(Icons.ios,'iOS', self)
        action_Update = QAction(Icons.update,"Update",self)
        action_Update.triggered.connect(self.parent.update)
        
        action_explorer = QAction("Explorer",self)
        action_explorer.triggered.connect(self.parent.exp)
        action_explorer.setCheckable(True)
        action_explorer.setChecked(True)
        action_console = QAction("Console",self)
        action_console.triggered.connect(self.parent.cmd)
        action_console.setCheckable(True)
        action_console.setChecked(False)
        #action_designer = QAction("Designer",self)
        #action_designer.triggered.connect(self.parent.design)
        action_Indentation = QAction("Indentation Guides",self)
        action_Indentation.triggered.connect(self.parent.setIndent)
        action_Indentation.setCheckable(True)
        action_Indentation.setChecked(config.indent())
        action_WhiteSpace = QAction("WhiteSpace",self)
        action_WhiteSpace.triggered.connect(self.parent.setWhiteSpace)
        action_WhiteSpace.setCheckable(True)
        action_WhiteSpace.setChecked(config.whiteSpace())
        action_EndLine = QAction("End of Lines",self)
        action_EndLine.triggered.connect(self.parent.setEndLine)
        action_EndLine.setCheckable(True)
        action_Margin = QAction("Line Numbers",self)
        action_Margin.triggered.connect(self.parent.setMargin)
        action_Margin.setCheckable(True)
        action_Margin.setChecked(config.margin())
        action_ToolLabel = QAction("Tool Labels",self)
        action_ToolLabel.triggered.connect(self.setToolLabel)
        action_ToolLabel.setCheckable(True)
        #action_ToolLabel.setChecked(config.toolLabel())
        
        '''Encoding'''
        encodingGroup = QActionGroup(self)
        encodingGroup.setExclusive(True)
        action_Ascii = QAction("Ascii",encodingGroup)
        action_Ascii.setCheckable(True)
        action_Unicode = QAction("Unicode",encodingGroup)
        action_Unicode.setCheckable(False)
        encodingGroup.addAction(action_Ascii)
        encodingGroup.addAction(action_Unicode)
        encodingGroup.selected.connect(self.parent.setEncoding)
        if(config.encoding() == Encoding.ASCII):
            action_Ascii.setChecked(True)
        else:
            action_Unicode.setChecked(True)
        men.addAction(action_Update)
        men.addAction(self.action_Help)
        men.addAction(self.action_Full)
        men.addSeparator()
        men.addAction(action_Android)
        men.addAction(action_Ant)
        men.addAction(action_Squirrel)
        men.addAction(action_Ios1)
        
        men.addSeparator()
        men.addAction(action_explorer)
        men.addAction(action_console)
        #men.addAction(action_designer)
        men.addSeparator()
        men.addAction(action_Indentation)
        men.addAction(action_WhiteSpace)
        men.addAction(action_EndLine)
        men.addAction(action_Margin)
        men.addAction(action_ToolLabel)
        men.addSeparator()
        men.addActions(encodingGroup.actions())
        men.addSeparator()
        head_font = QLabel("Font---------------------")
        fnt = head_font.font()
        fnt.setBold(True)
        head_font.setFont(fnt)
        head_fontWidgetAction = QWidgetAction(men)
        head_fontWidgetAction.setDefaultWidget(head_font)
        men.addAction(head_fontWidgetAction)
        men.addAction(self.fontComboMenu)
        men.addAction(self.fontSizeComboMenu)
        men.addSeparator()
        men.addAction(QAction("TabWidth",self))
        men.addAction(self.tabsSliderAction)
        men.addSeparator()
        men.addAction(QAction("Threshold",self))
        men.addAction(self.threshSliderAction)
        #men.addAction(QAction("Icon Size",self))
        #men.addAction(self.iconSliderAction)
        
        self.action_Options = QAction(Icons.emblem_system, 'Options', self)
        self.action_Options.setMenu(men)
        self.addAction(self.action_Options)
    
    ''' Mode Menu '''
    def initModeMenu(self):
        self.modeGroup = QActionGroup(self)
        self.modeGroup.setExclusive(True)
        self.modeGroup.selected.connect(self.parent.setMode)
        self.action_Squirrel = QAction(Icons.nut, 'Squ', self.modeGroup)
        self.action_Squirrel.setCheckable(True)
        self.action_Emo = QAction(Icons.emo, 'Emo', self.modeGroup)
        self.action_Emo.setCheckable(True)
        self.action_And = QAction(Icons.android, 'Android', self.modeGroup)
        self.action_And.setCheckable(True)
        self.action_Ios = QAction(Icons.ios, 'ios', self.modeGroup)
        self.action_Ios.setCheckable(True)
        self.modeGroup.addAction(self.action_Squirrel)
        self.modeGroup.addAction(self.action_Emo)
        self.modeGroup.addAction(self.action_And)
        self.modeGroup.addAction(self.action_Ios)
        self.addActions(self.modeGroup.actions())
        if(config.mode() == 0):
            self.action_Squirrel.setChecked(True)
            self.action_Build.setEnabled(False)
            self.action_Run.setEnabled(False)
        elif(config.mode() == 1):
            self.action_Emo.setChecked(True)
            self.action_Build.setEnabled(True)
            self.action_Run.setEnabled(True)
        elif(config.mode() == 2):
            self.action_And.setChecked(True)
            self.action_Build.setEnabled(True)
            self.action_Run.setEnabled(True)
        elif(config.mode() == 3):
            self.action_Ios.setChecked(True)
            self.action_Build.setEnabled(False)
            self.action_Run.setEnabled(False)
        
    
    ''' Style Menu '''
    def initStyleMenu(self):
        editStyle = config.readStyle()
        self.action_Style = QAction(Icons.style, 'Style', self) 
        men = QMenu(self)
        men1 = QMenu()
        self.base = StyleWidget(self,"base",editStyle["base"])
        self.back = StyleWidget(self,"back",editStyle["back"])
        self.caret = StyleWidget(self,"caret",editStyle["caret"])
        self.margin = StyleWidget(self,"margin",editStyle["margin"])
        self.marker = StyleWidget(self,"marker",editStyle["marker"])
        self.comment = StyleWidget(self,"comment",editStyle["comment"])
        self.number = StyleWidget(self,"number",editStyle["number"])
        self.keyword = StyleWidget(self,"keyword",editStyle["keyword"])
        self.string = StyleWidget(self,"string",editStyle["string"])
        self.operator = StyleWidget(self,"operator",editStyle["operator"])
        self.connect(self.base, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.back, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.caret, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.margin, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.marker, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.comment, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.number, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.keyword, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.string, SIGNAL("colorChange"),self.colorChange)
        self.connect(self.operator, SIGNAL("colorChange"),self.colorChange)
        self.baseMenu = QWidgetAction(men)
        self.baseMenu.setDefaultWidget(self.base)
        self.backMenu = QWidgetAction(men)
        self.backMenu.setDefaultWidget(self.back)
        self.caretMenu = QWidgetAction(men)
        self.caretMenu.setDefaultWidget(self.caret)
        self.marginMenu = QWidgetAction(men)
        self.marginMenu.setDefaultWidget(self.margin)
        self.markerMenu = QWidgetAction(men)
        self.markerMenu.setDefaultWidget(self.marker)
        self.commentMenu = QWidgetAction(men)
        self.commentMenu.setDefaultWidget(self.comment)
        self.numberMenu = QWidgetAction(men)
        self.numberMenu.setDefaultWidget(self.number)
        self.keywordMenu = QWidgetAction(men)
        self.keywordMenu.setDefaultWidget(self.keyword)
        self.stringMenu = QWidgetAction(men)
        self.stringMenu.setDefaultWidget(self.string)
        self.operatorMenu = QWidgetAction(men)
        self.operatorMenu.setDefaultWidget(self.operator)
        self.styleGroup = QActionGroup(self)
        self.styleGroup.setExclusive(True)
        self.styleGroup.selected.connect(self.setColors)
        self.style1 = QAction("All Hallow's Eve",self.styleGroup)
        self.style1.setCheckable(True)
        self.style2 = QAction("Amy",self.styleGroup)
        self.style2.setCheckable(True)
        self.style3 = QAction("Aptana Studio",self.styleGroup)
        self.style3.setCheckable(True)
        self.style4 = QAction("Bespin",self.styleGroup)
        self.style4.setCheckable(True)
        self.style5 = QAction("Blackboard",self.styleGroup)
        self.style5.setCheckable(True)
        self.style6 = QAction("Choco",self.styleGroup)
        self.style6.setCheckable(True)
        self.style7 = QAction("Cobalt",self.styleGroup)
        self.style7.setCheckable(True)
        self.style8 = QAction("Dawn",self.styleGroup)
        self.style8.setCheckable(True)
        self.style9 = QAction("Eclipse",self.styleGroup)
        self.style9.setCheckable(True)
        self.styleGroup.addAction(self.style1)
        self.styleGroup.addAction(self.style2)
        self.styleGroup.addAction(self.style3)
        self.styleGroup.addAction(self.style4)
        self.styleGroup.addAction(self.style5)
        self.styleGroup.addAction(self.style6)
        self.styleGroup.addAction(self.style7)
        self.styleGroup.addAction(self.style8)
        self.styleGroup.addAction(self.style9)
        men1.addAction(self.baseMenu)
        men1.addAction(self.backMenu)
        men1.addAction(self.caretMenu)
        men1.addAction(self.marginMenu)
        men1.addAction(self.markerMenu)
        men1.addAction(self.commentMenu)
        men1.addAction(self.numberMenu)
        men1.addAction(self.keywordMenu)
        men1.addAction(self.stringMenu)
        men1.addAction(self.operatorMenu)
        men1.addSeparator()
        men2 = QMenu(self)
        men2.setTitle("Styles")
        men2.addActions(self.styleGroup.actions())
        men1.addMenu(men2)
        self.action_Style.setMenu(men1)
        self.addAction(self.action_Style)
       
    ''' Lexer Menu'''
    def make_action_lex(self, text):
        action = QAction(text, self.lexGroup)
        action.setCheckable(True)
        return action
   
    def initLexerMenu(self):
        self.action_Lexer = QAction(Icons.file_obj, 'Lexer', self)
        men = QMenu()
        self.lexGroup = QActionGroup(self)
        self.lexGroup.setExclusive(True)
        self.lexGroup.selected.connect(self.parent.setLexer)
        #langs = [i for i in dir(Qsci) if i.startswith('QsciLexer')]
        langs = ['Bash', 'Batch', 'CMake', 'CPP', 'CSS', 'C#','HTML','Java', 'JavaScript', 'Lua', 'Makefile','Python', 'SQL', 'XML', 'YAML']
        for l in langs:
            act = self.make_action_lex(l)
            self.lexGroup.addAction(act)
            if(langs.index(l) == 8): #For javascript
                act.setChecked(True)
            #print l[9:] # we don't need to print "QsciLexer" before each name
        men.addActions(self.lexGroup.actions())
        self.action_Lexer.setMenu(men)
        self.addAction(self.action_Lexer)
        
    
        
    ''' Api Menu '''
    def make_action_api(self, text):
        action = QAction(text, self.apiGroup)
        action.setCheckable(True)
        return action
    
    def initApiMenu(self):
        self.action_Api = QAction(Icons.lib, 'Api', self)
        men = QMenu()
        self.apiGroup = QActionGroup(self)
        self.apiGroup.setExclusive(True)
        self.apiGroup.selected.connect(self.parent.setApi)
        list = oslistdir(apiDir)
        apis = []
        if(list != None):
            for i in list:
                if i.endswith("api"):
                    apis.append(i.replace(".api", ""))
        if(apis != None):
            for i in apis:
                act = self.make_action_api(i)
                self.apiGroup.addAction(act)
                if(i == "emo"): #For emo
                    act.setChecked(True)
        men.addActions(self.apiGroup.actions())
        self.action_Api.setMenu(men)
        self.addAction(self.action_Api)
        
        
Example #49
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    
Example #50
0
class SliderDlg(QDialog):
    def __init__(self, parent, sigma):
        QDialog.__init__(self, parent, Qt.FramelessWindowHint)
        
        # init
        # ------------------------------------------------
        self.oldSigma = sigma
        self.sigma = sigma
        self.brushSize = 0
        self.setStyleSheet("background-color:window;")
        # widgets and layouts
        # ------------------------------------------------
        
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        
        labelsLayout =  QHBoxLayout()
        self.labelSigma = QLabel("Sigma: xx")
        self.labelBrushSize = QLabel("BrushSize: xx")
        labelsLayout.addWidget(self.labelSigma)
        labelsLayout.addWidget(self.labelBrushSize)
        self.layout.addLayout(labelsLayout)
        
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(1)
        self.slider.setMaximum(100)
        self.slider.sliderMoved.connect(self.on_sliderMoved)
        self.layout.addWidget(self.slider)
        
        self.buttonsLayout = QHBoxLayout()
        self.cancel = QToolButton()
        self.cancel.setText("cancel")
        self.cancel.clicked.connect(self.on_cancelClicked)
        self.buttonsLayout.addWidget(self.cancel)
        
        
        self.ok = QToolButton()
        self.ok.setText("OK")
        self.ok.clicked.connect(self.on_okClicked)
        self.buttonsLayout.addWidget(self.ok)

        self.layout.addLayout(self.buttonsLayout)
        
        self.layout.setContentsMargins(10, 0, 10, 0)
        labelsLayout.setContentsMargins(0, 0, 0, 0)
        self.buttonsLayout.setContentsMargins(0, 0, 0, 0)
        
        self.setlabelSigma()
        self.setLabelBrushSize()
        self.setSliderPosition()
        
    def setlabelSigma(self):
        self.labelSigma.setText("Sigma: " + str(self.sigma))
        
    def setLabelBrushSize(self):
        self.brushSize = int(3.0*self.sigma + 0.5)*2 + 1
        self.labelBrushSize.setText("BrushSize: " + str(self.brushSize))
        
    def setSliderPosition(self):
        self.slider.setSliderPosition(self.sigma*10)
    
    def on_sliderMoved(self, i):
        self.sigma = float(i)/10
        self.setlabelSigma()
        self.setLabelBrushSize()
        self.parent().parent().parent().preView.setSizeToLabel(self.brushSize)
    
    def on_cancelClicked(self):
        self.reject()
        
    def on_okClicked(self):
        self.accept()
        
    def exec_(self):
        if QDialog.exec_(self) == QDialog.Accepted:
            return  self.sigma
        else:
            return self.oldSigma
Example #51
0
class options(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.heditor = parent

    def initShape(self):
        self.vbox = QVBoxLayout()
        self.optab = QTabWidget()

        self.fill = QWidget()

        self.createHexOptions()
        #        self.createPageOptions()
        self.createPixelOptions()
        self.vbox.addWidget(self.optab)

        self.createButtons()
        self.vbox.addWidget(self.fill)

        self.setLayout(self.vbox)

    def createPageOptions(self):
        self.pagegrid = QGridLayout()
        self.pagegroup = QWidget()

        pagelabel = QLabel("Page size : ")
        self.sizeEdit = QFFSpinBox(self)
        self.sizeEdit.setMaximum(self.heditor.filesize)
        self.sizeEdit.setValue(self.heditor.pageSize)
        #        psize = QString("%.2d" % self.heditor.pageSize)
        #        self.sizeEdit.insert(psize)

        headerlabel = QLabel("Header size : ")
        self.headEdit = QFFSpinBox(self)
        self.headEdit.setMaximum(self.heditor.filesize)
        self.headEdit.setValue(self.heditor.pageHead)
        #        phead = QString("%.2d" % self.heditor.pageHead)
        #        self.headEdit.insert(phead)

        sparelabel = QLabel("Spare size : ")
        self.spareEdit = QFFSpinBox(self)
        self.spareEdit.setMaximum(self.heditor.filesize)
        self.spareEdit.setValue(self.heditor.pageSpare)
        #        pspare = QString("%.2d" % self.heditor.pageSpare)
        #        self.spareEdit.insert(pspare)

        ppb = QLabel("Pages per block:")
        self.pagesperblock = QComboBox()
        self.pagesperblock.addItem("8")
        self.pagesperblock.addItem("16")
        self.pagesperblock.addItem("32")
        self.pagesperblock.addItem("64")
        self.pagesperblock.addItem("128")
        self.pagesperblock.addItem("256")
        self.pagesperblock.addItem("512")
        self.pagesperblock.setCurrentIndex(2)

        lview = QLabel("Left indication: ")
        self.indic = QComboBox()
        self.indic.addItem("Offset")
        self.indic.addItem("Block")

        #        self.pagesperlineEdit = QLineEdit()
        #        ppl = QString("%.2d" % self.heditor.pagesPerBlock)
        #        self.pagesperlineEdit.insert(ppl)

        self.pagegrid.addWidget(pagelabel, 0, 0)
        self.pagegrid.addWidget(self.sizeEdit, 0, 1)

        self.pagegrid.addWidget(headerlabel, 1, 0)
        self.pagegrid.addWidget(self.headEdit, 1, 1)

        self.pagegrid.addWidget(sparelabel, 2, 0)
        self.pagegrid.addWidget(self.spareEdit, 2, 1)

        self.pagegrid.addWidget(ppb, 3, 0)
        self.pagegrid.addWidget(self.pagesperblock, 3, 1)

        self.pagegrid.addWidget(lview, 4, 0)
        self.pagegrid.addWidget(self.indic, 4, 1)

        self.pagegrid.addWidget(self.fill, 5, 0)
        self.pagegrid.setRowStretch(5, 1)
        #        self.pagegrid.addWidget(self.fill, 6, 0)

        #        self.pagegrid.addWidget(pagesperline, 6, 0)
        #        self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0)

        self.pagegroup.setLayout(self.pagegrid)
        self.vvbox.addWidget(self.pagegroup)

#        self.optab.insertTab(1, self.pagegroup, "Pages" )

#        self.vbox.addWidget(self.pagegroup)

    def createHexOptions(self):
        self.vvbox = QVBoxLayout()
        self.vcontainer = QWidget()

        self.hexgroup = QWidget()

        self.hexgrid = QGridLayout()

        groupebylabel = QLabel("Groupe by:")
        self.groupeby = QComboBox()
        self.groupeby.addItem("1")
        self.groupeby.addItem("2")
        self.groupeby.addItem("4")

        offsetlabel = QLabel("Offset as")
        self.offsetas = QComboBox()
        self.offsetas.addItem("Hexadecimal")
        self.offsetas.addItem("Decimal")

        #        self.hexgrid.addWidget(groupebylabel, 0, 0)
        #        self.hexgrid.addWidget(self.groupeby, 1, 0)
        self.hexgrid.addWidget(offsetlabel, 0, 0)
        self.hexgrid.addWidget(self.offsetas, 0, 1)
        #        self.hexgrid.addWidget(self.fill, 2, 0)
        #        self.hexgrid.setRowStretch(2, 1)

        self.hexgroup.setLayout(self.hexgrid)

        self.vvbox.addWidget(self.hexgroup)

        self.createPageOptions()

        self.vcontainer.setLayout(self.vvbox)

        self.optab.insertTab(0, self.vcontainer, "General")

#        self.vbox.addWidget(self.hexgroup)

#Offset as decimal / hexadecimal

    def createPixelOptions(self):
        self.pixgroup = QWidget()

        self.pixgrid = QGridLayout()

        formatlabel = QLabel("Format :")
        self.format = QComboBox()
        self.format.addItem("RGB")
        self.format.addItem("Alpha RGB")
        self.format.addItem("Indexed 8bit")
        self.format.addItem("Mono")
        self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"),
                     self.formatChanged)

        colorlabel = QLabel("Indexed Color :")
        self.icolor = QComboBox()
        self.icolor.addItem("Green")
        self.icolor.addItem("Red")
        self.icolor.addItem("Blue")
        self.icolor.addItem("Ascii")
        self.icolor.addItem("256")
        self.icolor.setEnabled(False)

        slidelabel = QLabel("Resolution : ")

        self.sliderspin = QSpinBox(self)
        self.sliderspin.setMinimum(64)
        self.sliderspin.setMaximum(1024)
        self.sliderspin.setValue(self.heditor.wpixel.view.w)
        self.connect(self.sliderspin, SIGNAL("valueChanged(int)"),
                     self.slidermoved)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(64)
        self.slider.setMaximum(1024)
        self.slider.setValue(self.heditor.wpixel.view.w)
        self.slider.setSingleStep(1)

        self.zoomlabel = QLabel("Scale factor : 1")
        self.zoom = QSlider(Qt.Horizontal)
        self.zoom.setMinimum(1)
        self.zoom.setMaximum(5)
        self.zoom.setValue(1)
        self.zoom.setSingleStep(1)
        self.zoom.setTickInterval(1)
        self.zoom.setTickPosition(QSlider.TicksBelow)

        self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved)
        self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale)

        self.pixgrid.addWidget(formatlabel, 0, 0)
        self.pixgrid.addWidget(self.format, 0, 1)
        self.pixgrid.addWidget(colorlabel, 1, 0)
        self.pixgrid.addWidget(self.icolor, 1, 1)

        self.pixgrid.addWidget(slidelabel, 2, 0)
        self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft)

        self.pixgrid.addWidget(self.slider, 3, 0)
        self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft)
        self.pixgrid.addWidget(self.zoom, 5, 0)

        self.pixgrid.addWidget(self.fill, 6, 0)
        self.pixgrid.setRowStretch(6, 1)

        self.pixgroup.setLayout(self.pixgrid)

        self.optab.insertTab(1, self.pixgroup, "Pixel")

    def setSliderLabel(self, value):
        cvalue = QString()
        cvalue = "%2.d" % value
        self.sliderlabel.setText(cvalue)

    def setZoomLabel(self, value):
        zvalue = QString("Scale factor : ")
        zvalue += "%2.d" % value
        self.zoomlabel.setText(zvalue)

    def createButtons(self):
        self.applyB = QPushButton("Apply")
        self.connect(self.applyB, SIGNAL('clicked()'), self.apply)

        self.vbox.addWidget(self.applyB)

    def checkValue(self, value):
        try:
            n = int(value)
            return n
        except ValueError:
            return -1

    def apply(self):
        #PAGE CHECK
        pagesize = self.sizeEdit.value()
        headsize = self.headEdit.value()
        sparesize = self.spareEdit.value()
        pagesperblock = self.checkValue(self.pagesperblock.currentText())

        if (pagesize < 0) or (headsize < 0) or (sparesize <
                                                0) or (pagesperblock < 0):
            print "Wrong values"
        else:
            offas = self.offsetas.currentText()
            if offas == "Decimal":
                self.heditor.decimalview = True
            elif offas == "Hexadecimal":
                self.heditor.decimalview = False
            #Hexview refresh
            self.heditor.readOffset(self.heditor.currentOffset)
            #Pageview refresh
            if self.indic.currentText() == "Offset":
                self.heditor.pageOffView = True
            else:
                self.heditor.pageOffView = False

            self.heditor.refreshPageValues(headsize, pagesize, sparesize,
                                           pagesperblock)
            if self.heditor.wpage.scroll:
                self.heditor.wpage.scroll.refreshValues(
                    self.heditor.pagesPerBlock, self.heditor.pageSize)
            self.heditor.wpage.view.refreshAllContent()
            #PageView scrollbar refres
            #Pixel View refresh
            format = self.format.currentText()
            if format == "Indexed 8bit":
                self.heditor.wpixel.view.format = 0
            elif format == "Mono":
                self.heditor.wpixel.view.format = 1
            elif format == "RGB":
                self.heditor.wpixel.view.format = 2
            elif format == "Alpha RGB":
                self.heditor.wpixel.view.format = 3

            if self.heditor.wpixel.scroll:
                self.heditor.wpixel.scroll.refreshValues()
            #Color
            icolor = self.icolor.currentText()
            if icolor == "Red":
                self.heditor.wpixel.view.icolor = 0
            elif icolor == "Green":
                self.heditor.wpixel.view.icolor = 1
            elif icolor == "Blue":
                self.heditor.wpixel.view.icolor = 2
            elif icolor == "Ascii":
                self.heditor.wpixel.view.icolor = 3
            elif icolor == "256":
                self.heditor.wpixel.view.icolor = 4

            pixoffset = self.heditor.wpixel.view.currentOffset
            self.heditor.wpixel.view.read_image(pixoffset)

    def slidermoved(self, value):
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.w = value
        self.sliderspin.setValue(value)
        #        self.setSliderLabel(value)
        self.heditor.wpixel.view.read_image(pixoffset)
        if self.heditor.wpixel.scroll:
            self.heditor.wpixel.scroll.refreshValues()
#        print value

    def scale(self, value):
        self.setZoomLabel(value)
        self.heditor.wpixel.view.scale = value
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.read_image(pixoffset)

    def formatChanged(self, format):
        if format == "Indexed 8bit":
            self.icolor.setEnabled(True)
        else:
            self.icolor.setEnabled(False)

    def keyPressEvent(self, kEvent):
        key = kEvent.key()
        if key == Qt.Key_Return or key == Qt.Key_Enter:
            self.apply()
Example #52
0
class SliderDlg(QDialog):
    def __init__(self, parent, sigma):
        QDialog.__init__(self, parent, Qt.FramelessWindowHint)
        
        # init
        # ------------------------------------------------
        self.oldSigma = sigma
        self.sigma = sigma
        self.brushSize = 0
        self.setStyleSheet("background-color:window;")
        # widgets and layouts
        # ------------------------------------------------
        
        self.layout = QVBoxLayout()
        self.setLayout(self.layout)
        
        labelsLayout =  QHBoxLayout()
        self.labelSigma = QLabel("Sigma: xx")
        self.labelBrushSize = QLabel("BrushSize: xx")
        labelsLayout.addWidget(self.labelSigma)
        labelsLayout.addWidget(self.labelBrushSize)
        self.layout.addLayout(labelsLayout)
        
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(1)
        self.slider.setMaximum(100)
        self.slider.sliderMoved.connect(self.on_sliderMoved)
        self.layout.addWidget(self.slider)
        
        self.buttonsLayout = QHBoxLayout()
        self.cancel = QToolButton()
        self.cancel.setText("cancel")
        self.cancel.clicked.connect(self.on_cancelClicked)
        self.buttonsLayout.addWidget(self.cancel)
        
        
        self.ok = QToolButton()
        self.ok.setText("OK")
        self.ok.clicked.connect(self.on_okClicked)
        self.buttonsLayout.addWidget(self.ok)

        self.layout.addLayout(self.buttonsLayout)
        
        self.layout.setContentsMargins(10, 0, 10, 0)
        labelsLayout.setContentsMargins(0, 0, 0, 0)
        self.buttonsLayout.setContentsMargins(0, 0, 0, 0)
        
        self.setlabelSigma()
        self.setLabelBrushSize()
        self.setSliderPosition()
        
    def setlabelSigma(self):
        self.labelSigma.setText("Sigma: " + str(self.sigma))
        
    def setLabelBrushSize(self):
        self.brushSize = int(3.0*self.sigma + 0.5)*2 + 1
        self.labelBrushSize.setText("BrushSize: " + str(self.brushSize))
        
    def setSliderPosition(self):
        self.slider.setSliderPosition(self.sigma*10)
    
    def on_sliderMoved(self, i):
        self.sigma = float(i)/10
        self.setlabelSigma()
        self.setLabelBrushSize()
        self.parent().parent().parent().preView.setSizeToLabel(self.brushSize)
    
    def on_cancelClicked(self):
        self.reject()
        
    def on_okClicked(self):
        self.accept()
        
    def exec_(self):
        if QDialog.exec_(self) == QDialog.Accepted:
            return  self.sigma
        else:
            return self.oldSigma
Example #53
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')
Example #54
0
class options(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.heditor = parent        

    def initShape(self):
        self.vbox = QVBoxLayout()
        self.optab = QTabWidget()

        self.fill = QWidget()

        self.createHexOptions()
#        self.createPageOptions()
        self.createPixelOptions()
        self.vbox.addWidget(self.optab)

        self.createButtons()
        self.vbox.addWidget(self.fill)

        self.setLayout(self.vbox)
        
    def createPageOptions(self):
        self.pagegrid = QGridLayout()
        self.pagegroup = QWidget()
        
        pagelabel = QLabel("Page size : ")
        self.sizeEdit = QFFSpinBox(self)
        self.sizeEdit.setMaximum(self.heditor.filesize)
        self.sizeEdit.setValue(self.heditor.pageSize)
#        psize = QString("%.2d" % self.heditor.pageSize)
#        self.sizeEdit.insert(psize)

        headerlabel = QLabel("Header size : ")
        self.headEdit = QFFSpinBox(self)
        self.headEdit.setMaximum(self.heditor.filesize)
        self.headEdit.setValue(self.heditor.pageHead)
#        phead = QString("%.2d" % self.heditor.pageHead)
#        self.headEdit.insert(phead)

        sparelabel = QLabel("Spare size : ")
        self.spareEdit = QFFSpinBox(self)
        self.spareEdit.setMaximum(self.heditor.filesize)
        self.spareEdit.setValue(self.heditor.pageSpare)
#        pspare = QString("%.2d" % self.heditor.pageSpare)
#        self.spareEdit.insert(pspare)
        
        ppb = QLabel("Pages per block:")
        self.pagesperblock = QComboBox()
        self.pagesperblock.addItem("8")
        self.pagesperblock.addItem("16")
        self.pagesperblock.addItem("32")
        self.pagesperblock.addItem("64")
        self.pagesperblock.addItem("128")
        self.pagesperblock.addItem("256")
        self.pagesperblock.addItem("512")
        self.pagesperblock.setCurrentIndex(2)

        lview = QLabel("Left indication: ")
        self.indic = QComboBox()
        self.indic.addItem("Offset")
        self.indic.addItem("Block")

#        self.pagesperlineEdit = QLineEdit()
#        ppl = QString("%.2d" % self.heditor.pagesPerBlock)
#        self.pagesperlineEdit.insert(ppl)

        self.pagegrid.addWidget(pagelabel, 0, 0)
        self.pagegrid.addWidget(self.sizeEdit, 0, 1)

        self.pagegrid.addWidget(headerlabel, 1, 0)
        self.pagegrid.addWidget(self.headEdit, 1, 1)

        self.pagegrid.addWidget(sparelabel, 2, 0)
        self.pagegrid.addWidget(self.spareEdit, 2, 1)

        self.pagegrid.addWidget(ppb, 3 ,0)
        self.pagegrid.addWidget(self.pagesperblock, 3, 1)

        self.pagegrid.addWidget(lview, 4, 0)
        self.pagegrid.addWidget(self.indic, 4, 1)

        self.pagegrid.addWidget(self.fill, 5, 0)
        self.pagegrid.setRowStretch(5, 1)
#        self.pagegrid.addWidget(self.fill, 6, 0)

#        self.pagegrid.addWidget(pagesperline, 6, 0)
#        self.pagegrid.addWidget(self.pagesperlineEdit, 7, 0)

        self.pagegroup.setLayout(self.pagegrid)
        self.vvbox.addWidget(self.pagegroup)

#        self.optab.insertTab(1, self.pagegroup, "Pages" )

#        self.vbox.addWidget(self.pagegroup)

    def createHexOptions(self):
        self.vvbox = QVBoxLayout()
        self.vcontainer = QWidget()

        self.hexgroup = QWidget()

        self.hexgrid = QGridLayout()

        groupebylabel = QLabel("Groupe by:")
        self.groupeby = QComboBox()
        self.groupeby.addItem("1")
        self.groupeby.addItem("2")
        self.groupeby.addItem("4")

        offsetlabel = QLabel("Offset as")
        self.offsetas = QComboBox()
        self.offsetas.addItem("Hexadecimal")
        self.offsetas.addItem("Decimal")


#        self.hexgrid.addWidget(groupebylabel, 0, 0)
#        self.hexgrid.addWidget(self.groupeby, 1, 0)
        self.hexgrid.addWidget(offsetlabel, 0, 0)
        self.hexgrid.addWidget(self.offsetas, 0, 1)
#        self.hexgrid.addWidget(self.fill, 2, 0)
#        self.hexgrid.setRowStretch(2, 1)

        self.hexgroup.setLayout(self.hexgrid)
        
        self.vvbox.addWidget(self.hexgroup)

        self.createPageOptions()

        self.vcontainer.setLayout(self.vvbox)

        self.optab.insertTab(0, self.vcontainer, "General")

#        self.vbox.addWidget(self.hexgroup)

        #Offset as decimal / hexadecimal

    def createPixelOptions(self):
        self.pixgroup = QWidget()

        self.pixgrid = QGridLayout()

        formatlabel = QLabel("Format :")
        self.format = QComboBox()
        self.format.addItem("RGB")
        self.format.addItem("Alpha RGB")
        self.format.addItem("Indexed 8bit")
        self.format.addItem("Mono")
        self.connect(self.format, SIGNAL("currentIndexChanged(const QString)"), self.formatChanged)

        colorlabel = QLabel("Indexed Color :")
        self.icolor = QComboBox()
        self.icolor.addItem("Green")
        self.icolor.addItem("Red")
        self.icolor.addItem("Blue")
        self.icolor.addItem("Ascii")
        self.icolor.addItem("256")
        self.icolor.setEnabled(False)


        slidelabel = QLabel("Resolution : ")

        self.sliderspin = QSpinBox(self)
        self.sliderspin.setMinimum(64)
        self.sliderspin.setMaximum(1024)
        self.sliderspin.setValue(self.heditor.wpixel.view.w)
        self.connect(self.sliderspin, SIGNAL("valueChanged(int)"), self.slidermoved)

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(64)
        self.slider.setMaximum(1024)
        self.slider.setValue(self.heditor.wpixel.view.w)
        self.slider.setSingleStep(1)

        self.zoomlabel = QLabel("Scale factor : 1")
        self.zoom = QSlider(Qt.Horizontal)
        self.zoom.setMinimum(1)
        self.zoom.setMaximum(5)
        self.zoom.setValue(1)
        self.zoom.setSingleStep(1)
        self.zoom.setTickInterval(1)
        self.zoom.setTickPosition(QSlider.TicksBelow)

        self.connect(self.slider, SIGNAL("sliderMoved(int)"), self.slidermoved)
        self.connect(self.zoom, SIGNAL("sliderMoved(int)"), self.scale)

        self.pixgrid.addWidget(formatlabel, 0, 0)
        self.pixgrid.addWidget(self.format, 0, 1)
        self.pixgrid.addWidget(colorlabel, 1, 0)
        self.pixgrid.addWidget(self.icolor, 1, 1)

        self.pixgrid.addWidget(slidelabel, 2, 0)
        self.pixgrid.addWidget(self.sliderspin, 2, 1, Qt.AlignLeft)

        self.pixgrid.addWidget(self.slider, 3, 0)
        self.pixgrid.addWidget(self.zoomlabel, 4, 0, Qt.AlignLeft)
        self.pixgrid.addWidget(self.zoom, 5, 0)

        self.pixgrid.addWidget(self.fill, 6, 0)
        self.pixgrid.setRowStretch(6, 1)

        self.pixgroup.setLayout(self.pixgrid)

        self.optab.insertTab(1, self.pixgroup, "Pixel")

    def setSliderLabel(self, value):
        cvalue = QString()
        cvalue = "%2.d" % value
        self.sliderlabel.setText(cvalue)
    
    def setZoomLabel(self, value):
        zvalue = QString("Scale factor : ")
        zvalue += "%2.d" % value
        self.zoomlabel.setText(zvalue)


    def createButtons(self):
        self.applyB = QPushButton("Apply")
        self.connect(self.applyB, SIGNAL('clicked()'), self.apply)



        self.vbox.addWidget(self.applyB)

    def checkValue(self, value):
        try:
            n = int(value)
            return n
        except ValueError:
            return -1

    def apply(self):
        #PAGE CHECK
        pagesize = self.sizeEdit.value()
        headsize = self.headEdit.value()
        sparesize = self.spareEdit.value()
        pagesperblock = self.checkValue(self.pagesperblock.currentText())

        if (pagesize < 0) or (headsize < 0) or (sparesize < 0) or (pagesperblock < 0):
            print "Wrong values"
        else:
            offas = self.offsetas.currentText()
            if offas == "Decimal":
                self.heditor.decimalview = True
            elif offas == "Hexadecimal":
                self.heditor.decimalview = False
            #Hexview refresh
            self.heditor.readOffset(self.heditor.currentOffset)
            #Pageview refresh
            if self.indic.currentText() == "Offset":
                self.heditor.pageOffView = True
            else:
                self.heditor.pageOffView = False

            self.heditor.refreshPageValues(headsize, pagesize, sparesize, pagesperblock)
            if self.heditor.wpage.scroll:
                self.heditor.wpage.scroll.refreshValues(self.heditor.pagesPerBlock, self.heditor.pageSize)
            self.heditor.wpage.view.refreshAllContent()
            #PageView scrollbar refres
            #Pixel View refresh
            format = self.format.currentText()
            if format == "Indexed 8bit":
                self.heditor.wpixel.view.format = 0
            elif format == "Mono":
                self.heditor.wpixel.view.format = 1
            elif format == "RGB":
                self.heditor.wpixel.view.format = 2
            elif format == "Alpha RGB":
                self.heditor.wpixel.view.format = 3

            if self.heditor.wpixel.scroll:
                self.heditor.wpixel.scroll.refreshValues()
            #Color
            icolor = self.icolor.currentText()
            if icolor == "Red":
                self.heditor.wpixel.view.icolor = 0
            elif icolor == "Green":
                self.heditor.wpixel.view.icolor = 1
            elif icolor == "Blue":
                self.heditor.wpixel.view.icolor = 2
            elif icolor == "Ascii":
                self.heditor.wpixel.view.icolor = 3
            elif icolor == "256":
                self.heditor.wpixel.view.icolor = 4

            pixoffset = self.heditor.wpixel.view.currentOffset
            self.heditor.wpixel.view.read_image(pixoffset)

    def slidermoved(self, value):       
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.w = value
        self.sliderspin.setValue(value)
#        self.setSliderLabel(value)
        self.heditor.wpixel.view.read_image(pixoffset)
        if self.heditor.wpixel.scroll:
            self.heditor.wpixel.scroll.refreshValues()
#        print value

    def scale(self, value):
        self.setZoomLabel(value)
        self.heditor.wpixel.view.scale = value
        pixoffset = self.heditor.wpixel.view.currentOffset
        self.heditor.wpixel.view.read_image(pixoffset)


    def formatChanged(self, format):
        if format == "Indexed 8bit":
            self.icolor.setEnabled(True)
        else:
            self.icolor.setEnabled(False)


    def keyPressEvent(self, kEvent):
        key = kEvent.key()
        if key == Qt.Key_Return or key == Qt.Key_Enter:
            self.apply()
Example #55
0
class Trackers(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.v_layout = QVBoxLayout()

        self.hSliderMin = QSlider()
        self.hSliderMin.setOrientation(Qt.Horizontal)
        self.hLabelMin = QLabel('H min: 0')
        self.hSliderMin.setMinimum(0)
        self.hSliderMin.setMaximum(179)

        self.hSliderMax = QSlider()
        self.hSliderMax.setOrientation(Qt.Horizontal)
        self.hLabelMax = QLabel('H max: 0')
        self.hSliderMax.setMinimum(0)
        self.hSliderMax.setMaximum(179)

        self.sSliderMin = QSlider()
        self.sSliderMin.setOrientation(Qt.Horizontal)
        self.sLabelMin = QLabel('S min: 0')
        self.sSliderMin.setMinimum(0)
        self.sSliderMin.setMaximum(255)

        self.sSliderMax = QSlider()
        self.sSliderMax.setOrientation(Qt.Horizontal)
        self.sLabelMax = QLabel('S max: 0')
        self.sSliderMax.setMinimum(0)
        self.sSliderMax.setMaximum(255)

        self.vSliderMin = QSlider()
        self.vSliderMin.setOrientation(Qt.Horizontal)
        self.vLabelMin = QLabel('V min: 0')
        self.vSliderMin.setMinimum(0)
        self.vSliderMin.setMaximum(255)

        self.vSliderMax = QSlider()
        self.vSliderMax.setOrientation(Qt.Horizontal)
        self.vLabelMax = QLabel('V max: 0')
        self.vSliderMax.setMinimum(0)
        self.vSliderMax.setMaximum(255)

        self.v_layout.addWidget(self.hLabelMin)
        self.v_layout.addWidget(self.hSliderMin)
        self.v_layout.addWidget(self.hLabelMax)
        self.v_layout.addWidget(self.hSliderMax)

        self.v_layout.addWidget(self.sLabelMin)
        self.v_layout.addWidget(self.sSliderMin)
        self.v_layout.addWidget(self.sLabelMax)
        self.v_layout.addWidget(self.sSliderMax)

        self.v_layout.addWidget(self.vLabelMin)
        self.v_layout.addWidget(self.vSliderMin)
        self.v_layout.addWidget(self.vLabelMax)
        self.v_layout.addWidget(self.vSliderMax)

        self.setLayout(self.v_layout)

        self.hSliderMin.valueChanged.connect(self.slider_movedHmin)
        self.sSliderMin.valueChanged.connect(self.slider_movedSmin)
        self.vSliderMin.valueChanged.connect(self.slider_movedVmin)
        self.hSliderMax.valueChanged.connect(self.slider_movedHmax)
        self.sSliderMax.valueChanged.connect(self.slider_movedSmax)
        self.vSliderMax.valueChanged.connect(self.slider_movedVmax)

    def keyPressEvent(self, event):
        if event.key()==Qt.Key_Right:
            self.slider.setValue(self.slider.value() + 1)
        elif event.key()==Qt.Key_Left:
            self.slider.setValue(self.slider.value() - 1)
        else:
            QWidget.keyPressEvent(self, event)

    def slider_movedHmin(self, position):
        self.hLabelMin.setText('H min: %d' % position)
    def slider_movedSmin(self, position):
        self.sLabelMin.setText('S min: %d' % position)
    def slider_movedVmin(self, position):
        self.vLabelMin.setText('V min: %d' % position)
    def slider_movedHmax(self, position):
        self.hLabelMax.setText('H max: %d' % position)
    def slider_movedSmax(self, position):
        self.sLabelMax.setText('S max: %d' % position)
    def slider_movedVmax(self, position):
        self.vLabelMax.setText('V max: %d' % position)
Example #56
0
class Ui_Form (QWidget):
    '''
    Ui class. Generated with pyuic4.
    '''
    def __init__ (self, parent=None):
        
        QWidget.__init__(self, parent)
        self.timer = QTimer (self)
        
        self.image    = QImage (720, 450, QImage.Format_RGB888)
        
        self.__engine = REngineThread ()
        self.__model  = Model ()
        self.__fsm    = DebugStateMachine (self)
    
        
    def wireEngineUp (self):
        '''
        this method connects the REngine's signals.
        '''
        self.connect (self.__engine, SIGNAL ("update (float)"), self.updateImage)
        self.connect (self.__engine, SIGNAL ("thread_completed()"), self.__fsm.finaliseRender)
        self.connect (self.__engine, SIGNAL ("inters_created (PyQt_PyObject, PyQt_PyObject)"), self.widget.addIntersection)
        self.connect (self.__engine, SIGNAL ("vector_created (PyQt_PyObject, PyQt_PyObject, QString)"), self.widget.addArrow)
        self.connect (self.__engine, SIGNAL ("line_created   (PyQt_PyObject, PyQt_PyObject, QString)"), self.widget.addLine)
    
    def wireOGLViewerUp (self):
        '''
        this method connects the REngine's signals.
        '''
        self.widget.setModel (self.__model)
        
        QObject.connect (self.widget, SIGNAL ("MatrixChanged (PyQt_PyObject)"), self.displayGLMatrix)

        # call the function run regularly when the focus is on it. (60 FPS if interval = 20)
        QObject.connect (self.timer, SIGNAL ('timeout()'), self.widget.run)
    
    def freezeGLFrameRate (self):
        
        self.timer.stop ()
    
    def speedUpGLFrameRate (self):
        
        self.timer.start ()
        self.timer.setInterval (20)
        
    def setupUi (self, Form):
        
        font = QFont ()
        font.setPointSize (9)
        font.setBold (False)
        font.setWeight (50)
        
        sizePolicy = QSizePolicy (QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch (0)
        sizePolicy.setVerticalStretch (0)
        
        Form.setObjectName (_fromUtf8("Form"))
        Form.resize (971, 930)
        self.plainTextEdit = QPlainTextEdit (Form)
        self.plainTextEdit.setGeometry (QRect (740, 280, 221, 611))
        self.plainTextEdit.setObjectName (_fromUtf8 ("plainTextEdit"))
        self.plainTextEdit.setFont (font)
        
        self.widget = OGLViewer (Form)
        self.widget.setUi_Form (self)
        self.widget.setGeometry (QRect (10, 10, 720, 450))
        sizePolicy.setHeightForWidth (self.widget.sizePolicy().hasHeightForWidth())
        self.widget.setSizePolicy (sizePolicy)
        self.widget.setObjectName (_fromUtf8 ("widget"))
        
        self.wireOGLViewerUp ()
        self.wireEngineUp ()
        
        self.label_view = QLabel (Form)
        self.label_view.setGeometry  (QRect (10, 470, 720, 450))
        sizePolicy.setHeightForWidth (self.label_view.sizePolicy().hasHeightForWidth())
        self.label_view.setSizePolicy (sizePolicy)
        self.label_view.setObjectName (_fromUtf8 ("label_view"))
        self.initLabel ()          
        self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image))
        
        # buttons definitions
        
        self.renderBtn    = QPushButton (Form)
        self.pauseBtn     = QPushButton (Form)
        self.stopBtn      = QPushButton (Form)
        self.upBtn        = QPushButton (Form)
        self.downBtn      = QPushButton (Form)
        self.moreDownBtn  = QPushButton (Form)
        self.moreUpBtn    = QPushButton (Form)
        self.rightBtn     = QPushButton (Form)
        self.moreRightBtn = QPushButton (Form)
        self.leftBtn      = QPushButton (Form)
        self.furtherLeft  = QPushButton (Form)
        self.grid_switch  = QPushButton (Form)
        
        buttons_properties_list = [[self.renderBtn,    True,  QRect (740, 140, 61, 21), "render"],
                                   [self.pauseBtn,     False, QRect (740, 120, 61, 21), "pause"],
                                   [self.stopBtn,      False, QRect (740, 100, 61, 21), "stop"],
                                   [self.upBtn,        False, QRect (820, 120, 21, 21), "one_row_up"],
                                   [self.downBtn,      False, QRect (820, 140, 21, 21), "one_row_down"],
                                   [self.moreDownBtn,  False, QRect (820, 160, 21, 21), "ten_rows_down"],
                                   [self.moreUpBtn,    False, QRect (820, 100, 21, 21), "ten_rows_up"],
                                   [self.rightBtn,     False, QRect (780, 180, 21, 21), "one_column_right"],
                                   [self.moreRightBtn, False, QRect (800, 180, 21, 21), "ten_columns_right"],
                                   [self.leftBtn,      False, QRect (760, 180, 21, 21), "one_column_left"],
                                   [self.furtherLeft,  False, QRect (740, 180, 21, 21), "ten_columns_left"],
                                   [self.grid_switch,  False, QRect (870, 230, 91, 31), "grid_switch"]]
        
        for button in buttons_properties_list:
            button[0].setEnabled  (button[1])
            button[0].setGeometry (button[2])
            button[0].setFont (font)
            button[0].setObjectName (_fromUtf8 (button[3]))
        
        # other UI elements
        
        self.progressBar = QProgressBar (Form)
        self.progressBar.setGeometry (QRect (740, 901, 221, 20))
        self.progressBar.setProperty ("value", 0)
        self.progressBar.setObjectName (_fromUtf8("progressBar"))
        self.progressBar.setMinimum (0)
        self.progressBar.setMaximum (100)
        
        self.slider_label = QLabel (Form)
        self.slider_label.setGeometry (QRect(900, 260, 61, 16))
        self.slider_label.setFont(font)
        self.slider_label.setObjectName (_fromUtf8("slider_label"))
        self.slider_label.setEnabled (True)
        
        self.arrowSizeSlider = QSlider (Form)
        self.arrowSizeSlider.setGeometry (QRect (740, 258, 151, 22))
        self.arrowSizeSlider.setMinimum (2)
        self.arrowSizeSlider.setMaximum (40)
        self.arrowSizeSlider.setSingleStep (1)
        self.arrowSizeSlider.setProperty ("value", 4)
        self.arrowSizeSlider.setOrientation (Qt.Horizontal)
        self.arrowSizeSlider.setObjectName  (_fromUtf8("arrowSizeSlider"))

        self.retranslateUi (Form)
        QMetaObject.connectSlotsByName (Form)
    
    def retranslateUi (self, Form):
        
        Form.setWindowTitle       (_translate ("Form", "RayTracing Debugging Tool", None))
        
        self.renderBtn.setText    (_translate ("Form", "Render", None))
        self.pauseBtn.setText     (_translate ("Form", "Pause",  None))
        self.stopBtn.setText      (_translate ("Form", "Stop",   None))
        self.upBtn.setText        (_translate ("Form", "^",      None))
        self.downBtn.setText      (_translate ("Form", "v",      None))
        self.moreDownBtn.setText  (_translate ("Form", "+",      None))
        self.moreUpBtn.setText    (_translate ("Form", "-",      None))
        self.rightBtn.setText     (_translate ("Form", ">",      None))
        self.moreRightBtn.setText (_translate ("Form", "+",      None))
        self.leftBtn.setText      (_translate ("Form", "<",      None))
        self.furtherLeft.setText  (_translate ("Form", "-",      None))
        
        self.grid_switch.setText  (_translate ("Form", "Grid on/off", None))
        self.slider_label.setText (_translate ("Form", "Arrows size", None))
        
        self.connect (self.renderBtn,       SIGNAL ("clicked()"),        self.__fsm.startRendering)
        self.connect (self.pauseBtn,        SIGNAL ("clicked()"),        self.__fsm.pauseRendering)
        self.connect (self.stopBtn,         SIGNAL ("clicked()"),        self.__fsm.stopRendering)
        self.connect (self.arrowSizeSlider, SIGNAL ("sliderMoved(int)"), self.resizeArrows)
    
    def initLabel (self):
        
        color = QColor (250, 250, 250)
        self.image.fill (color)
        
        '''
        # test init
        for i in range (0, 200, 20):
            for x in range (i, i+20):
                for y in range (i, i+20):
                    self.image.setPixel (x,y, qRgb (0, 0, 0))
        '''
    
    def enableUIButtons (self, boolean_dict):
        '''
        method used by the debug state machine to manage the greyed-out state of buttons.
        '''
        b_dict = dict (boolean_dict)
        
        self.renderBtn.setEnabled    (b_dict['renderBtn'])
        self.pauseBtn.setEnabled     (b_dict['pauseBtn'])
        self.stopBtn.setEnabled      (b_dict['stopBtn'])
        self.upBtn.setEnabled        (b_dict['upBtn'])
        self.downBtn.setEnabled      (b_dict['downBtn'])
        self.moreDownBtn.setEnabled  (b_dict['moreDownBtn'])
        self.moreUpBtn.setEnabled    (b_dict['moreUpBtn'])
        self.rightBtn.setEnabled     (b_dict['rightBtn'])
        self.moreRightBtn.setEnabled (b_dict['moreRightBtn'])
        self.leftBtn.setEnabled      (b_dict['leftBtn'])
        self.furtherLeft.setEnabled  (b_dict['furtherLeft'])
        
        if b_dict['progressBar'] == 'completed':
            self.progressBar.setValue (100)
        elif b_dict['progressBar'] == 'reset':
            self.progressBar.reset ()
    
    def addScreenshot (self):
        '''
        it grabs a screenshot of OpenGL viewer and add it into the QImage instance.
        '''
        self.image = self.widget.grabFrameBuffer ()
        self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image))
    
    def prepAndStartEngineUp (self):
        '''
        it preps the engine and start it up.
        '''
        self.__engine.setImage (self.image)
        self.__engine.setCameraNormalMatrix (self.widget.getNormalMatrix(), self.widget.getFovy ())
        self.__engine.setModel (self.__model)
        self.__engine.start ()
    
    def addCamera (self): self.widget.addCamera ()
    def setIsStoppedFlag (self, boo):  self.__engine.setIsStoppedFlag (boo)
    def setIsPausedFlag  (self, boo):  self.__engine.setIsPausedFlag  (boo)
    def changeRenderBtnName (self, title):  self.renderBtn.setText (_translate ("Form", title, None))
    
    # listeners  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def resizeArrows (self, e):
        self.widget.changeArrowsSize (e*0.5)
    def updateImage (self, e):
        self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image))
        self.progressBar.setValue (int(100*e))
    def displayGLMatrix (self, e):
        '''
        this method is registered to the MatrixChanged event fired from the OGLViewer
        component. It prints the model matrix. Only for debugging purposes.
        '''
        pass
Example #57
0
class PreferencesDialogBase(QDialog):
    def __init__(self, parent, app):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self.app = app
        self._setupUi()

        self.connect(self.filterHardnessSlider, SIGNAL("valueChanged(int)"),
                     self.filterHardnessLabel.setNum)
        self.connect(self.buttonBox, SIGNAL('clicked(QAbstractButton*)'),
                     self.buttonClicked)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def _setupScanTypeBox(self, labels):
        self.scanTypeHLayout = QHBoxLayout()
        self.scanTypeLabel = QLabel(self)
        self.scanTypeLabel.setText(tr("Scan Type:"))
        self.scanTypeLabel.setMinimumSize(QSize(100, 0))
        self.scanTypeLabel.setMaximumSize(QSize(100, 16777215))
        self.scanTypeHLayout.addWidget(self.scanTypeLabel)
        self.scanTypeComboBox = QComboBox(self)
        for label in labels:
            self.scanTypeComboBox.addItem(label)
        self.scanTypeHLayout.addWidget(self.scanTypeComboBox)
        self.widgetsVLayout.addLayout(self.scanTypeHLayout)

    def _setupFilterHardnessBox(self):
        self.filterHardnessHLayout = QHBoxLayout()
        self.filterHardnessLabel = QLabel(self)
        self.filterHardnessLabel.setText(tr("Filter Hardness:"))
        self.filterHardnessLabel.setMinimumSize(QSize(0, 0))
        self.filterHardnessHLayout.addWidget(self.filterHardnessLabel)
        self.filterHardnessVLayout = QVBoxLayout()
        self.filterHardnessVLayout.setSpacing(0)
        self.filterHardnessHLayoutSub1 = QHBoxLayout()
        self.filterHardnessHLayoutSub1.setSpacing(12)
        self.filterHardnessSlider = QSlider(self)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.filterHardnessSlider.sizePolicy().hasHeightForWidth())
        self.filterHardnessSlider.setSizePolicy(sizePolicy)
        self.filterHardnessSlider.setMinimum(1)
        self.filterHardnessSlider.setMaximum(100)
        self.filterHardnessSlider.setTracking(True)
        self.filterHardnessSlider.setOrientation(Qt.Horizontal)
        self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessSlider)
        self.filterHardnessLabel = QLabel(self)
        self.filterHardnessLabel.setText("100")
        self.filterHardnessLabel.setMinimumSize(QSize(21, 0))
        self.filterHardnessHLayoutSub1.addWidget(self.filterHardnessLabel)
        self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub1)
        self.filterHardnessHLayoutSub2 = QHBoxLayout()
        self.filterHardnessHLayoutSub2.setContentsMargins(-1, 0, -1, -1)
        self.moreResultsLabel = QLabel(self)
        self.moreResultsLabel.setText(tr("More Results"))
        self.filterHardnessHLayoutSub2.addWidget(self.moreResultsLabel)
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding,
                                 QSizePolicy.Minimum)
        self.filterHardnessHLayoutSub2.addItem(spacerItem)
        self.fewerResultsLabel = QLabel(self)
        self.fewerResultsLabel.setText(tr("Fewer Results"))
        self.filterHardnessHLayoutSub2.addWidget(self.fewerResultsLabel)
        self.filterHardnessVLayout.addLayout(self.filterHardnessHLayoutSub2)
        self.filterHardnessHLayout.addLayout(self.filterHardnessVLayout)

    def _setupBottomPart(self):
        # The bottom part of the pref panel is always the same in all editions.
        self.fontSizeLabel = QLabel(tr("Font size:"))
        self.fontSizeSpinBox = QSpinBox()
        self.fontSizeSpinBox.setMinimum(5)
        self.widgetsVLayout.addLayout(
            horizontalWrap([self.fontSizeLabel, self.fontSizeSpinBox, None]))
        self.languageLabel = QLabel(tr("Language:"), self)
        self.languageComboBox = QComboBox(self)
        for lang in SUPPORTED_LANGUAGES:
            self.languageComboBox.addItem(LANGNAMES[lang])
        self.widgetsVLayout.addLayout(
            horizontalWrap([self.languageLabel, self.languageComboBox, None]))
        self.copyMoveLabel = QLabel(self)
        self.copyMoveLabel.setText(tr("Copy and Move:"))
        self.widgetsVLayout.addWidget(self.copyMoveLabel)
        self.copyMoveDestinationComboBox = QComboBox(self)
        self.copyMoveDestinationComboBox.addItem(tr("Right in destination"))
        self.copyMoveDestinationComboBox.addItem(tr("Recreate relative path"))
        self.copyMoveDestinationComboBox.addItem(tr("Recreate absolute path"))
        self.widgetsVLayout.addWidget(self.copyMoveDestinationComboBox)
        self.customCommandLabel = QLabel(self)
        self.customCommandLabel.setText(
            tr("Custom Command (arguments: %d for dupe, %r for ref):"))
        self.widgetsVLayout.addWidget(self.customCommandLabel)
        self.customCommandEdit = QLineEdit(self)
        self.widgetsVLayout.addWidget(self.customCommandEdit)

    def _setupAddCheckbox(self, name, label, parent=None):
        if parent is None:
            parent = self
        cb = QCheckBox(parent)
        cb.setText(label)
        setattr(self, name, cb)

    def _setupPreferenceWidgets(self):
        # Edition-specific
        pass

    def _setupUi(self):
        self.setWindowTitle(tr("Preferences"))
        self.resize(304, 263)
        self.setSizeGripEnabled(False)
        self.setModal(True)
        self.mainVLayout = QVBoxLayout(self)
        self.widgetsVLayout = QVBoxLayout()
        self._setupPreferenceWidgets()
        self.mainVLayout.addLayout(self.widgetsVLayout)
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok
                                          | QDialogButtonBox.RestoreDefaults)
        self.mainVLayout.addWidget(self.buttonBox)
        if (not ISOSX) and (not ISLINUX):
            self.mainVLayout.removeWidget(self.ignoreHardlinkMatches)
            self.ignoreHardlinkMatches.setHidden(True)

    def _load(self, prefs, setchecked):
        # Edition-specific
        pass

    def _save(self, prefs, ischecked):
        # Edition-specific
        pass

    def load(self, prefs=None):
        if prefs is None:
            prefs = self.app.prefs
        self.filterHardnessSlider.setValue(prefs.filter_hardness)
        self.filterHardnessLabel.setNum(prefs.filter_hardness)
        setchecked = lambda cb, b: cb.setCheckState(Qt.Checked
                                                    if b else Qt.Unchecked)
        setchecked(self.mixFileKindBox, prefs.mix_file_kind)
        setchecked(self.useRegexpBox, prefs.use_regexp)
        setchecked(self.removeEmptyFoldersBox, prefs.remove_empty_folders)
        setchecked(self.ignoreHardlinkMatches, prefs.ignore_hardlink_matches)
        setchecked(self.debugModeBox, prefs.debug_mode)
        self.copyMoveDestinationComboBox.setCurrentIndex(
            prefs.destination_type)
        self.customCommandEdit.setText(prefs.custom_command)
        self.fontSizeSpinBox.setValue(prefs.tableFontSize)
        try:
            langindex = SUPPORTED_LANGUAGES.index(self.app.prefs.language)
        except ValueError:
            langindex = 0
        self.languageComboBox.setCurrentIndex(langindex)
        self._load(prefs, setchecked)

    def save(self):
        prefs = self.app.prefs
        prefs.filter_hardness = self.filterHardnessSlider.value()
        ischecked = lambda cb: cb.checkState() == Qt.Checked
        prefs.mix_file_kind = ischecked(self.mixFileKindBox)
        prefs.use_regexp = ischecked(self.useRegexpBox)
        prefs.remove_empty_folders = ischecked(self.removeEmptyFoldersBox)
        prefs.ignore_hardlink_matches = ischecked(self.ignoreHardlinkMatches)
        prefs.debug_mode = ischecked(self.debugModeBox)
        prefs.destination_type = self.copyMoveDestinationComboBox.currentIndex(
        )
        prefs.custom_command = str(self.customCommandEdit.text())
        prefs.tableFontSize = self.fontSizeSpinBox.value()
        lang = SUPPORTED_LANGUAGES[self.languageComboBox.currentIndex()]
        oldlang = self.app.prefs.language
        if oldlang not in SUPPORTED_LANGUAGES:
            oldlang = 'en'
        if lang != oldlang:
            QMessageBox.information(
                self, "",
                tr("dupeGuru has to restart for language changes to take effect."
                   ))
        self.app.prefs.language = lang
        self._save(prefs, ischecked)

    #--- Events
    def buttonClicked(self, button):
        role = self.buttonBox.buttonRole(button)
        if role == QDialogButtonBox.ResetRole:
            self.resetToDefaults()