Exemple #1
0
    def __init__(self, parent):
        super(ElastixMainDialog, self).__init__(parent)
        self.transformation = None

        self.transformations = AppResources.elastixTemplates()
        self.radioButtons = []
        for transformation in self.transformations:
            self.radioButtons.append(QRadioButton(transformation.name))
        self.radioButtons.append(QRadioButton("Load custom parameter file..."))
        self.radioButtons[0].setChecked(True)

        self.nextButton = QPushButton("Next")
        self.nextButton.clicked.connect(self.next)
        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.clicked.connect(self.cancel)

        groupLayout = QVBoxLayout()
        for radioButton in self.radioButtons:
            groupLayout.addWidget(radioButton)

        self.groupBox = QGroupBox("Choose parameter file")
        self.groupBox.setLayout(groupLayout)

        self.setModal(True)

        layout = QGridLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.addWidget(self.groupBox, 0, 0, 1, 2)
        layout.addWidget(self.cancelButton, 1, 0)
        layout.addWidget(self.nextButton, 1, 1)
        self.setLayout(layout)
Exemple #2
0
 def _buildSpeedPanel(self):
     '''
     Creates the sub-panel containing control widgets for controlling the 
     speed of execution of the algorithm.
     '''
     self._runBtn = QPushButton("Run", self._window)
     self._stepBtn = QPushButton("Step Once", self._window)        
     self._runBtn.clicked.connect(self._onRun)
     self._stepBtn.clicked.connect(self._onStep)        
     
     slowRadio = QRadioButton('Slow', self._window)
     medRadio = QRadioButton('Medium', self._window)
     fastRadio = QRadioButton('Fast', self._window)
     notVisRadio = QRadioButton('Not visible', self._window)
     slowRadio.setChecked(True)        
     
     self._speedGroup = QButtonGroup(self._window)
     self._speedGroup.addButton(slowRadio, 0)
     self._speedGroup.addButton(medRadio, 1)
     self._speedGroup.addButton(fastRadio, 2)
     self._speedGroup.addButton(notVisRadio, 3)
     self._speedGroup.buttonClicked.connect(self._onSpeedChange)
       
     layout = QVBoxLayout()
     layout.addWidget(self._runBtn)
     layout.addWidget(self._stepBtn)
     layout.addWidget(slowRadio)
     layout.addWidget(medRadio)
     layout.addWidget(fastRadio)
     layout.addWidget(notVisRadio)
     
     grpBx = QGroupBox("Run Controls")
     grpBx.setLayout(layout)
     grpBx.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
     return grpBx
Exemple #3
0
    def createWidgets(self):
        settings = QSettings()

        self.txtGroupBox = QGroupBox("Plain Text Format (.txt)")
        self.indentLabel = QLabel("&Indent")
        self.indentComboBox = QComboBox()
        self.indentLabel.setBuddy(self.indentComboBox)
        oldIndent = IndentKind.TAB
        oldIndent = self.config.get(Gconf.Key.Indent, oldIndent)
        index = -1
        for i, indent in enumerate(IndentKind):
            text = indent.name.replace("_", " ").title()
            self.indentComboBox.addItem(text, indent.value)
            if indent is oldIndent:
                index = i
        self.indentComboBox.setCurrentIndex(index)
        self.form.tooltips.append((self.indentComboBox, """\
<p><b>Indent</b></p>
<p>The indentation to use when outputting an indented-style index in
plain text format for each level of indentation.</p>"""))

        self.rtfGroupBox = QGroupBox("Rich Text Format (.rtf)")
        self.rtfIndentLabel = QLabel("I&ndent")
        self.rtfIndentComboBox = QComboBox()
        self.rtfIndentLabel.setBuddy(self.rtfIndentComboBox)
        oldIndent = IndentKind(int(settings.value(Gopt.Key.IndentRTF,
                                                  Gopt.Default.IndentRTF)))
        index = -1
        for i, indent in enumerate(IndentKind):
            text = ("Indent" if i == 0 else
                    indent.name.replace("_", " ").title())
            self.rtfIndentComboBox.addItem(text, indent.value)
            if indent is oldIndent:
                index = i
        self.rtfIndentComboBox.setCurrentIndex(index)
        self.form.tooltips.append((self.rtfIndentComboBox, """\
<p><b>Indent</b></p>
<p>The indentation to use when outputting an indented-style index in
rich text format for each level of indentation.</p>"""))

        self.pdfGroupBox = QGroupBox("Portable Document Format (.pdf)")
        self.paperSizeLabel = QLabel("Paper Size")
        self.letterRadioButton = QRadioButton("&Letter")
        self.a4RadioButton = QRadioButton("&A4")
        size = PaperSizeKind(int(settings.value(Gopt.Key.PaperSize,
                                                Gopt.Default.PaperSize)))
        if size is PaperSizeKind.LETTER:
            self.letterRadioButton.setChecked(True)
        else:
            self.a4RadioButton.setChecked(True)
        self.form.tooltips.append((self.letterRadioButton, """\
<p><b>Paper Size, Letter</b></p>
<p>If checked, when outputting a PDF of the index, US Letter
8.5"x11"-sized pages will be used.</p>"""))
        self.form.tooltips.append((self.a4RadioButton, """\
<p><b>Paper Size, A4</b></p>
<p>If checked, when outputting a PDF of the index, European A4-sized
pages will be used.</p>"""))
    def initWidgets(self):
        self.showAllServicesItem = QListWidgetItem(
            self.tr("(All registered services)"))
        self.servicesListWidget = QListWidget()
        self.interfacesListWidget = QListWidget()
        self.interfacesListWidget.addItem(self.tr("(Select a service)"))
        self.attributesListWidget = QListWidget()
        self.attributesListWidget.addItem(
            self.tr("(Select an interface implementation)"))
        self.interfacesListWidget.setMinimumWidth(450)
        self.servicesListWidget.currentItemChanged.connect(
            self.reloadInterfaceImplementationsList)
        self.interfacesListWidget.currentItemChanged.connect(
            self.currentInterfaceImplChanged)
        self.defaultInterfaceButton = QPushButton(
            self.tr("Set as default implementation"))
        self.defaultInterfaceButton.setEnabled(False)
        self.defaultInterfaceButton.clicked.connect(
            self.setDefaultInterfaceImplementation)
        self.selectedImplRadioButton = QRadioButton(
            self.tr("Selected interface implementation"))
        self.defaultImplRadioButton = QRadioButton(
            self.tr("Default implementation"))
        self.selectedImplRadioButton.setChecked(True)
        self.radioButtons = QButtonGroup(self)
        self.radioButtons.addButton(self.selectedImplRadioButton)
        self.radioButtons.addButton(self.defaultImplRadioButton)
        self.radioButtons.buttonClicked.connect(self.reloadAttributesList)

        self.servicesGroup = QGroupBox(self.tr("Show services for:"))
        servicesLayout = QVBoxLayout()
        servicesLayout.addWidget(self.servicesListWidget)
        self.servicesGroup.setLayout(servicesLayout)

        self.interfacesGroup = QGroupBox(self.tr("Interface implementations"))
        interfacesLayout = QVBoxLayout()
        interfacesLayout.addWidget(self.interfacesListWidget)
        interfacesLayout.addWidget(self.defaultInterfaceButton)
        self.interfacesGroup.setLayout(interfacesLayout)

        self.attributesGroup = QGroupBox(self.tr("Invokable attributes"))
        attributesLayout = QVBoxLayout()
        self.attributesGroup.setLayout(attributesLayout)
        attributesLayout.addWidget(self.attributesListWidget)
        attributesLayout.addWidget(QLabel(self.tr("Show attributes for:")))
        attributesLayout.addWidget(self.selectedImplRadioButton)
        attributesLayout.addWidget(self.defaultImplRadioButton)

        self.attributesGroup.setLayout(attributesLayout)

        layout = QGridLayout()
        layout.addWidget(self.servicesGroup, 0, 0)
        layout.addWidget(self.attributesGroup, 0, 1, 2, 1)
        layout.addWidget(self.interfacesGroup, 1, 0)

        self.setLayout(layout)
Exemple #5
0
    def addReadinessTab(self):
        self.readyFrame = QtGui.QFrame()
        self.readyLayout = QtGui.QVBoxLayout()
        self.readyFrame.setLayout(self.readyLayout)

        # Initial state

        self.readyInitialGroup = QtGui.QGroupBox(u"Initial readiness state")
        self.readyInitialLayout = QtGui.QVBoxLayout()
        self.readyInitialGroup.setLayout(self.readyInitialLayout)
        self.readyatstartCheckbox = QCheckBox(getMessage("readyatstart-label"))
        self.readyatstartCheckbox.setObjectName("readyAtStart")
        self.readyInitialLayout.addWidget(self.readyatstartCheckbox)
        self.readyLayout.addWidget(self.readyInitialGroup)

        # Automatically pausing
        self.readyPauseGroup = QtGui.QGroupBox(u"Pausing")
        self.readyPauseLayout = QtGui.QVBoxLayout()
        self.readyPauseGroup.setLayout(self.readyPauseLayout)
        self.pauseonleaveCheckbox = QCheckBox(getMessage("pauseonleave-label"))
        self.pauseonleaveCheckbox.setObjectName("pauseOnLeave")
        self.readyPauseLayout.addWidget(self.pauseonleaveCheckbox)
        self.readyLayout.addWidget(self.readyPauseGroup)

        # Unpausing
        self.readyUnpauseGroup = QtGui.QGroupBox(getMessage("unpause-title"))
        self.readyUnpauseLayout = QtGui.QVBoxLayout()
        self.readyUnpauseGroup.setLayout(self.readyUnpauseLayout)
        self.readyUnpauseButtonGroup = QButtonGroup()
        self.unpauseIfAlreadyReadyOption = QRadioButton(getMessage("unpause-ifalreadyready-option"))
        self.readyUnpauseButtonGroup.addButton(self.unpauseIfAlreadyReadyOption)
        self.unpauseIfAlreadyReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.unpauseIfAlreadyReadyOption.setObjectName("unpause-ifalreadyready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFALREADYREADY_MODE)
        self.readyUnpauseLayout.addWidget(self.unpauseIfAlreadyReadyOption)
        self.unpauseIfOthersReadyOption = QRadioButton(getMessage("unpause-ifothersready-option"))
        self.readyUnpauseButtonGroup.addButton(self.unpauseIfOthersReadyOption)
        self.unpauseIfOthersReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.unpauseIfOthersReadyOption.setObjectName("unpause-ifothersready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFOTHERSREADY_MODE)
        self.readyUnpauseLayout.addWidget(self.unpauseIfOthersReadyOption)
        self.unpauseIfMinUsersReadyOption = QRadioButton(getMessage("unpause-ifminusersready-option"))
        self.readyUnpauseButtonGroup.addButton(self.unpauseIfMinUsersReadyOption)
        self.unpauseIfMinUsersReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.unpauseIfMinUsersReadyOption.setObjectName("unpause-ifminusersready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFMINUSERSREADY_MODE)
        self.readyUnpauseLayout.addWidget(self.unpauseIfMinUsersReadyOption)
        self.unpauseAlwaysUnpauseOption = QRadioButton(getMessage("unpause-always"))
        self.readyUnpauseButtonGroup.addButton(self.unpauseAlwaysUnpauseOption)
        self.unpauseAlwaysUnpauseOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.unpauseAlwaysUnpauseOption.setObjectName("unpause-always" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_ALWAYS_MODE)
        self.readyUnpauseLayout.addWidget(self.unpauseAlwaysUnpauseOption)
        self.readyLayout.addWidget(self.readyUnpauseGroup)

        self.readyLayout.setAlignment(Qt.AlignTop)
        self.stackedLayout.addWidget(self.readyFrame)
Exemple #6
0
    def _create_zbar(self, settings):
        radio = QRadioButton(
            'My objects are labelled with either 1D barcodes or QR codes')
        radio.setChecked('zbar' == settings['engine'])
        radio.setEnabled(zbar_available())
        self._layout.addWidget(radio)

        prompt = QLabel('Barcodes will be decoded using the open-source '
                        '<a href="http://zbar.sourceforge.net/">ZBar</a> library')
        prompt.setOpenExternalLinks(True)
        prompt.setStyleSheet(self.STYLESHEET)
        self._layout.addWidget(prompt)

        self._layout.addWidget(HorizontalLine())
        return radio
Exemple #7
0
    def _create_libdmtx(self, settings):
        radio = QRadioButton('My objects are labelled with Data Matrix barcodes')
        radio.setChecked('libdmtx' == settings['engine'])
        radio.setEnabled(libdmtx_available())
        self._layout.addWidget(radio)

        prompt = QLabel(
            'Barcodes will be decoded using the open-source '
            '<a href="http://www.libdmtx.org/">libdmtx</a> library')
        prompt.setOpenExternalLinks(True)
        prompt.setStyleSheet(self.STYLESHEET)
        self._layout.addWidget(prompt)

        self._layout.addWidget(HorizontalLine())
        return radio
Exemple #8
0
 def __init__(self, attributeDict, existingFields, parent=None):
   super(ScrapeAttributeDialog, self).__init__(parent)
   self._choice_dict = {"field_name":'', "attr_name":'', "attr_value":''}
   self._rdbtn_label_map = {}
   self._field_names = existingFields
   layout = QGridLayout()
   for index, (attr_name, attr_value) in attributeDict:
     rdbtn_attr_name = QRadioButton(attr_name)
     label_attr_value = QLabel(attr_value)
     label_attr_value.setMaximumWidth(120)
     layout.addWidget(rdbtn_attr_name, index, 0)
     layout.addWidget(label_attr_value, index, 1, 1, 2)
     self._rdbtn_label_map[rdbtn_attr_name] = label_attr_value
   label_output_field = QLabel(self.tr("Output Field"))
   self.combo_output_field = SingleEditCombobox(existingFields)
   self._button_ok = QPushButton(self.tr("OK"))
   self._button_ok.clicked.connect(self._collectChoices)
   self._button_cancel = QPushButton(self.tr("Cancel"))
   self._button_cancel.clicked.connect(self.reject)
   index += 1
   layout.addWidget(label_output_field, index, 0)
   layout.addWidget(self.combo_output_field, index, 1, 1, 2)
   index += 1
   layout.addWidget(self._button_ok, index, 1)
   layout.addWidget(self._button_cancel, index, 2)
   self.setLayout(layout)
   self.setWindowTitle(self.tr("Choose Attributes"))
Exemple #9
0
    def __init__(self, choices, title = "select one from choices", parent = None):
        super(ChoiceDialog, self).__init__(parent)

        layout = QVBoxLayout(self)
        self.choiceButtonGroup=QButtonGroup(parent)  # it is not a visible UI
        self.choiceButtonGroup.setExclusive(True)
        if choices and len(choices)>=1:
            self.choices = choices
            for id, choice in enumerate(self.choices):
                rb = QRadioButton(choice)
                self.choiceButtonGroup.addButton(rb)
                self.choiceButtonGroup.setId(rb, id)  # negative id if not specified
                layout.addWidget(rb)

        self.choiceButtonGroup.buttonClicked.connect(self.choiceChanged)
        # OK and Cancel buttons
        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
            Qt.Horizontal, self)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        layout.addWidget(buttons)

        self.setLayout(layout)
        self.setWindowTitle(title)
Exemple #10
0
 def __init__(self, group_name, name_dict, handler = None, help_instance = None):
     QGroupBox.__init__(self, group_name)
     the_layout = QVBoxLayout()
     self.setLayout(the_layout)
     self.widget_dict = {}
     rows = 0
     for module_name, name_list in name_dict.items():
         the_layout.addWidget(QLabel(module_name))
         for txt in name_list:
             cb = QRadioButton(txt)
             cb.setFont(regular_small_font)
             the_layout.addWidget(cb, rows, 0)
             if handler != None:
                 cb.toggled.connect(handler)
             self.widget_dict[txt] = cb
             rows += 1
     return
Exemple #11
0
    def rebuild_editor ( self ):
        """ Rebuilds the contents of the editor whenever the original factory
            object's **values** facet changes.
        """
        # Clear any existing content:
        ### self.clear_layout()

        # Get the current facet value:
        cur_name = self.str_value

        # Create a sizer to manage the radio buttons:
        names   = self.names
        mapping = self.mapping
        n       = len( names )
        cols    = self.factory.cols
        rows    = (n + cols - 1) / cols
        incr    = [ n / cols ] * cols
        rem     = n % cols
        for i in range( cols ):
            incr[i] += (rem > i)

        incr[-1] = -( reduce( lambda x, y: x + y, incr[:-1], 0 ) - 1 )

        # Add the set of all possible choices:
        index = 0

        for i in range( rows ):
            for j in range( cols ):
                if n > 0:
                    name = label = names[ index ]
                    label = self.string_value( label, capitalize )
                    rb = QRadioButton( label )
                    rb.value = mapping[ name ]

                    rb.setChecked( name == cur_name )

                    QObject.connect( rb, SIGNAL( 'clicked()' ), self._mapper,
                                     SLOT( 'map()' ) )
                    self._mapper.setMapping( rb, rb )

                    self.set_tooltip( rb )
                    self.control.addWidget( rb, i, j )

                    index += incr[j]
                    n     -= 1
    def _initGUI(self):
        self.layout = QVBoxLayout()
        self.form = QFormLayout()

        self.name = QLineEdit()
        self.surname = QLineEdit()

        self.birthdate = QCalendarWidget()
        self.birthdate.setGridVisible(True)
        self.birthdate.setMinimumDate(QDate(1850, 1, 1))
        self.birthdate.setMaximumDate(QDate.currentDate())

        self.male = QRadioButton("Male")
        self.male.setChecked(True)
        self.female = QRadioButton("Female")

        self.height = QDoubleSpinBox()
        self.height.setMaximum(250)
        self.height.setMinimum(50)
        self.height.setValue(165)
        self.height.setSuffix(" cm")

        self.mass = QDoubleSpinBox()
        self.mass.setMaximum(300)
        self.mass.setMinimum(20)
        self.mass.setValue(60)
        self.mass.setSuffix(" Kg")

        btnLayout = QVBoxLayout()

        self.form.addRow("Name", self.name)
        self.form.addRow("Surname", self.surname)
        self.form.addRow("Birth date", self.birthdate)

        sexLayout = QHBoxLayout()
        sexLayout.addWidget(self.male)
        sexLayout.addWidget(self.female)
        self.form.addRow("Sex", sexLayout)

        self.form.addRow("Height", self.height)
        self.form.addRow("Mass", self.mass)

        self.layout.addLayout(self.form)
        self.layout.addLayout(btnLayout)
        self.setLayout(self.layout)
 def _initGUI(self):
     self.layout = QVBoxLayout()
     self.form = QFormLayout()
     
     self.name = QLineEdit()
     self.surname = QLineEdit()
     
     self.birthdate = QCalendarWidget()
     self.birthdate.setGridVisible(True)
     self.birthdate.setMinimumDate(QDate(1850,1,1))
     self.birthdate.setMaximumDate(QDate.currentDate())
     
     self.male = QRadioButton("Male")
     self.male.setChecked(True)
     self.female = QRadioButton("Female")
     
     self.height = QDoubleSpinBox()
     self.height.setMaximum(250)
     self.height.setMinimum(50)
     self.height.setValue(165)
     self.height.setSuffix(" cm")
     
     self.mass = QDoubleSpinBox()
     self.mass.setMaximum(300)
     self.mass.setMinimum(20)
     self.mass.setValue(60)
     self.mass.setSuffix(" Kg")
     
     btnLayout = QVBoxLayout()
     
     self.form.addRow("Name", self.name)
     self.form.addRow("Surname", self.surname)
     self.form.addRow("Birth date",self.birthdate)
     
     sexLayout = QHBoxLayout()
     sexLayout.addWidget(self.male)
     sexLayout.addWidget(self.female)
     self.form.addRow("Sex", sexLayout)
     
     self.form.addRow("Height", self.height)
     self.form.addRow("Mass", self.mass)
             
     self.layout.addLayout(self.form)
     self.layout.addLayout(btnLayout)
     self.setLayout(self.layout)
Exemple #14
0
    def createWidgets(self):
        self.termLabel = Widgets.Label.HtmlLabel(
            "<p>Sort “{}” with</p>".format(Lib.elidePatchHtml(self.term,
                                                              self.state)))
        self.radioButtons = []
        seen = set()
        for index, candidate in enumerate(self.candidates, 1):
            candidate_word = str(candidate.candidate_word)
            name = self.nameForKind(candidate.kind, candidate_word)
            extra = ""
            if candidate_word in seen:
                extra = " (treat roman numbers as literal text)"
            else:
                seen.add(candidate_word)
            radioButton = QRadioButton("&{} “{}” as{} “{}”{}".format(
                index, candidate.term_word, name, candidate_word, extra))
            self.radioButtons.append(radioButton)
        self.radioButtons[0].setChecked(True)
        self.customRadioButton = QRadioButton("&Custom:")
        self.tooltips.append((self.customRadioButton, """\
<p><b>Custom</b></p>
<p>If checked, this entry's <b>Automatically Calculate Sort As</b>
setting will be <i>unchecked</i>, and the sort as text entered here will
be used as ther entry's sort as text.</p>"""))
        self.sortAsEdit = Widgets.LineEdit.LineEdit(self.state)
        self.tooltips.append((self.sortAsEdit, """\
<p><b>Custom Sort As editor</b></p>
<p>If <b>Custom</b> is checked, this entry's <b>Automatically Calculate
Sort As</b> setting will be <i>unchecked</i>, and the sort as text
entered here will be used as ther entry's sort as text.</p>"""))
        self.sortAsEdit.setText(self.candidates[0].candidate)
        self.sortAsEdit.selectAll()
        self.buttonBox = QDialogButtonBox()
        self.okButton = QPushButton(QIcon(":/ok.svg"), "&OK")
        self.tooltips.append((self.okButton, """\
<p><b>OK</b></p>
<p>Use the specified or custom sort as text for entry
“{}”.</p>""".format(Lib.elidePatchHtml(self.term, self.state))))
        self.buttonBox.addButton(
            self.okButton, QDialogButtonBox.AcceptRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append((self.helpButton,
                              "Help on the Sort As dialog"))
        self.buttonBox.addButton(
            self.helpButton, QDialogButtonBox.HelpRole)
Exemple #15
0
 def __init__(self, title, labels):
     QGroupBox.__init__(self, title)
     self.layout = QBoxLayout(QBoxLayout.LeftToRight)
     self.buttons = {}
     for label in labels:
         button = QRadioButton(label)
         self.buttons[label] = button
         self.layout.addWidget(button)
     self.setLayout(self.layout)
Exemple #16
0
    def __init__(self, choices, help_texts=[], parent=None):
        super(ChoiceWidget, self).__init__(parent)

        title = "select one from choices"
        self.setWindowTitle(title)

        layout = QVBoxLayout(self)
        self.choiceButtonGroup = QButtonGroup(self)  # it is not a visible UI
        self.choiceButtonGroup.setExclusive(True)
        if choices and len(choices) >= 1:
            if len(help_texts) < len(choices):
                help_texts = choices
            self.choices = choices
            for id, choice in enumerate(self.choices):
                rb = QRadioButton(choice)
                rb.setToolTip(help_texts[id])
                self.choiceButtonGroup.addButton(rb)
                self.choiceButtonGroup.setId(
                    rb, id)  # negative id if not specified
                layout.addWidget(rb)
                if id == 0:
                    rb.setChecked(True)

        self.choiceButtonGroup.buttonClicked.connect(self.choiceChanged)
        self.setLayout(layout)
Exemple #17
0
    def _createWidgets(self):
        '''Create the widgets contained in this box'''

        # Rate or lifetime chooser
        self.rate = QRadioButton('Rate', self)
        self.rate.setToolTip(ttt('Choose this to express exchange as rate'))
        self.lifetime = QRadioButton('Lifetime', self)
        self.lifetime.setToolTip(ttt('Choose this to express exchange as '
                                     'lifetime'))

        # Box containing value
        self.rate_value = QLineEdit(self)
        validate = QDoubleValidator(self.rate_value)
        validate.setDecimals(3)
        validate.setBottom(0.0)
        self.rate_value.setValidator(validate)
        self.rate_value.setToolTip(ttt('The rate or lifetime value'))

        # Unit
        self.unit = QComboBox(self)
        self.unit.setToolTip(ttt('Selects the input unit for the rate '
                                 'or lifetime'))
Exemple #18
0
    def initWidgets(self):
        self.showAllServicesItem = QListWidgetItem(self.tr("(All registered services)"))
        self.servicesListWidget = QListWidget()
        self.interfacesListWidget = QListWidget()
        self.interfacesListWidget.addItem(self.tr("(Select a service)"))
        self.attributesListWidget = QListWidget()
        self.attributesListWidget.addItem(self.tr("(Select an interface implementation)"))
        self.interfacesListWidget.setMinimumWidth(450)
        self.servicesListWidget.currentItemChanged.connect(self.reloadInterfaceImplementationsList)
        self.interfacesListWidget.currentItemChanged.connect(self.currentInterfaceImplChanged)
        self.defaultInterfaceButton = QPushButton(self.tr("Set as default implementation"))
        self.defaultInterfaceButton.setEnabled(False)
        self.defaultInterfaceButton.clicked.connect(self.setDefaultInterfaceImplementation)
        self.selectedImplRadioButton = QRadioButton(self.tr("Selected interface implementation"))
        self.defaultImplRadioButton = QRadioButton(self.tr("Default implementation"))
        self.selectedImplRadioButton.setChecked(True)
        self.radioButtons = QButtonGroup(self)
        self.radioButtons.addButton(self.selectedImplRadioButton)
        self.radioButtons.addButton(self.defaultImplRadioButton)
        self.radioButtons.buttonClicked.connect(self.reloadAttributesList)

        self.servicesGroup = QGroupBox(self.tr("Show services for:"))
        servicesLayout = QVBoxLayout()
        servicesLayout.addWidget(self.servicesListWidget)
        self.servicesGroup.setLayout(servicesLayout)

        self.interfacesGroup = QGroupBox(self.tr("Interface implementations"))
        interfacesLayout = QVBoxLayout()
        interfacesLayout.addWidget(self.interfacesListWidget)
        interfacesLayout.addWidget(self.defaultInterfaceButton)
        self.interfacesGroup.setLayout(interfacesLayout)

        self.attributesGroup = QGroupBox(self.tr("Invokable attributes"))
        attributesLayout = QVBoxLayout()
        self.attributesGroup.setLayout(attributesLayout)
        attributesLayout.addWidget(self.attributesListWidget)
        attributesLayout.addWidget(QLabel(self.tr("Show attributes for:")))
        attributesLayout.addWidget(self.selectedImplRadioButton)
        attributesLayout.addWidget(self.defaultImplRadioButton)

        self.attributesGroup.setLayout(attributesLayout)

        layout = QGridLayout()
        layout.addWidget(self.servicesGroup, 0, 0)
        layout.addWidget(self.attributesGroup, 0, 1, 2, 1)
        layout.addWidget(self.interfacesGroup, 1, 0)

        self.setLayout(layout)
 def __init__(self, radioStrings, checkedRadio='', parent=None):
   super(HorizontalRadioGroup, self).__init__(parent)
   self._radios = []
   layout = QHBoxLayout()
   for original_s in radioStrings:
     # radio buttons have have text for display and original text. they only differ for empty strings
     radiobutton = QRadioButton()
     radiobutton.setProperty("_original_value", original_s)
     radiobutton.clicked.connect(self._handleRadioClicked)
     display_s = original_s if original_s else "(empty)"
     radiobutton.setText(display_s)
     if original_s == checkedRadio:
       radiobutton.setChecked(True)
     self._radios.append(radiobutton)
     layout.addWidget(radiobutton)
   self.setLayout(layout)
Exemple #20
0
def _createChoiceGroup(valueTypes, valueTypeTips):
    _buttonGroupLayout = QHBoxLayout()
    buttonGroupValueType = QButtonGroup()
    buttonGroupValueType.setExclusive(True)

    for id, choice in enumerate(valueTypes):
        rb = QRadioButton(choice)
        rb.setToolTip(valueTypeTips[id])
        buttonGroupValueType.addButton(rb, id)
        _buttonGroupLayout.addWidget(rb)
        if id == 0:
            rb.setChecked(True)
    return buttonGroupValueType, _buttonGroupLayout
Exemple #21
0
    def initGui(self):
        self.setWindowTitle("Aeneid Window")
        self.setGeometry(200, 100, 400, 200)
        # label
        self.label1 = QLabel('today me, tomorrow the world!', self)
        self.label1.setFont('Arial')
        self.label1.move(20, 10)
        # check box creation
        self.checkbox1 = QCheckBox('OK', self)
        self.checkbox1.clicked.connect(self.onCheckBox1)
        self.checkbox1.toggle()

        # Radio buttons
        self.radioButton = QRadioButton('click me', self)
        self.radioButton.clicked.connect(self.onRadioButton)

        # ok cancel button
        self
        self.show()
    def addPrivacyTab(self):
        self.privacySettingsGroup = QtGui.QGroupBox("Privacy settings")
        self.privacySettingsLayout = QtGui.QVBoxLayout()
        self.privacySettingsFrame = QtGui.QFrame()
        self.privacyFrame = QtGui.QFrame()
        self.privacyLayout = QtGui.QGridLayout()

        self.filenameprivacyLabel = QLabel(getMessage("filename-privacy-label"), self)
        self.filenameprivacyButtonGroup = QButtonGroup()
        self.filenameprivacySendRawOption = QRadioButton(getMessage("privacy-sendraw-option"))
        self.filenameprivacySendHashedOption = QRadioButton(getMessage("privacy-sendhashed-option"))
        self.filenameprivacyDontSendOption = QRadioButton(getMessage("privacy-dontsend-option"))
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption)

        self.filesizeprivacyLabel = QLabel(getMessage("filesize-privacy-label"), self)
        self.filesizeprivacyButtonGroup = QButtonGroup()
        self.filesizeprivacySendRawOption = QRadioButton(getMessage("privacy-sendraw-option"))
        self.filesizeprivacySendHashedOption = QRadioButton(getMessage("privacy-sendhashed-option"))
        self.filesizeprivacyDontSendOption = QRadioButton(getMessage("privacy-dontsend-option"))
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption)

        self.filenameprivacyLabel.setObjectName("filename-privacy")
        self.filenameprivacySendRawOption.setObjectName("privacy-sendraw" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDRAW_MODE)
        self.filenameprivacySendHashedOption.setObjectName("privacy-sendhashed" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDHASHED_MODE)
        self.filenameprivacyDontSendOption.setObjectName("privacy-dontsend" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_DONTSEND_MODE)
        self.filesizeprivacyLabel.setObjectName("filesize-privacy")
        self.filesizeprivacySendRawOption.setObjectName("privacy-sendraw" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDRAW_MODE)
        self.filesizeprivacySendHashedOption.setObjectName("privacy-sendhashed" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDHASHED_MODE)
        self.filesizeprivacyDontSendOption.setObjectName("privacy-dontsend" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_DONTSEND_MODE)

        self.privacyLayout.addWidget(self.filenameprivacyLabel, 1, 0)
        self.privacyLayout.addWidget(self.filenameprivacySendRawOption, 1, 1, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filenameprivacySendHashedOption, 1, 2, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filenameprivacyDontSendOption, 1, 3, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filesizeprivacyLabel, 2, 0)
        self.privacyLayout.addWidget(self.filesizeprivacySendRawOption, 2, 1, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filesizeprivacySendHashedOption, 2, 2, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filesizeprivacyDontSendOption, 2, 3, Qt.AlignLeft)

        self.privacyFrame.setLayout(self.privacyLayout)
        self.privacySettingsGroup.setLayout(self.privacyLayout)
        self.privacySettingsGroup.setMaximumHeight(self.privacySettingsGroup.minimumSizeHint().height())
        self.privacySettingsLayout.addWidget(self.privacySettingsGroup)
        self.privacySettingsLayout.setAlignment(Qt.AlignTop)
        self.privacyFrame.setLayout(self.privacySettingsLayout)
        self.stackedLayout.addWidget(self.privacyFrame)
Exemple #23
0
    def __init__(self, parent):
        super(PickerTypeDialog, self).__init__(parent)

        self.pickerType = None

        self.pickerTypes = [(SurfaceType, "Surface picker"),
                            (TwoStepType, "Two step picker")]

        self.radioButtons = []
        for picker in self.pickerTypes:
            self.radioButtons.append(QRadioButton(picker[1]))
        # self.radioButtons[0].setChecked(True)
        self.buttonGroup = QButtonGroup()
        ind = 0
        for button in self.radioButtons:
            self.buttonGroup.addButton(button)
            self.buttonGroup.setId(button, ind)
            ind += 1

        self.nextButton = QPushButton("Choose")
        self.nextButton.clicked.connect(self.choose)
        self.cancelButton = QPushButton("Cancel")
        self.cancelButton.clicked.connect(self.cancel)

        groupLayout = QVBoxLayout()
        for radioButton in self.radioButtons:
            groupLayout.addWidget(radioButton)

        self.groupBox = QGroupBox("Choose picker type:")
        self.groupBox.setLayout(groupLayout)

        self.setModal(True)

        layout = QGridLayout()
        layout.setAlignment(Qt.AlignTop)
        layout.addWidget(self.groupBox, 0, 0, 1, 2)
        layout.addWidget(self.cancelButton, 1, 0)
        layout.addWidget(self.nextButton, 1, 1)
        self.setLayout(layout)
Exemple #24
0
    def addMiscTab(self):
        self.miscFrame = QtGui.QFrame()
        self.miscLayout = QtGui.QVBoxLayout()
        self.miscFrame.setLayout(self.miscLayout)

        self.coreSettingsGroup = QtGui.QGroupBox(getMessage("core-behaviour-title"))
        self.coreSettingsLayout = QtGui.QGridLayout()
        self.coreSettingsGroup.setLayout(self.coreSettingsLayout)

        ### Privacy:

        self.filenameprivacyLabel = QLabel(getMessage("filename-privacy-label"), self)
        self.filenameprivacyButtonGroup = QButtonGroup()
        self.filenameprivacySendRawOption = QRadioButton(getMessage("privacy-sendraw-option"))
        self.filenameprivacySendHashedOption = QRadioButton(getMessage("privacy-sendhashed-option"))
        self.filenameprivacyDontSendOption = QRadioButton(getMessage("privacy-dontsend-option"))
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption)

        self.filesizeprivacyLabel = QLabel(getMessage("filesize-privacy-label"), self)
        self.filesizeprivacyButtonGroup = QButtonGroup()
        self.filesizeprivacySendRawOption = QRadioButton(getMessage("privacy-sendraw-option"))
        self.filesizeprivacySendHashedOption = QRadioButton(getMessage("privacy-sendhashed-option"))
        self.filesizeprivacyDontSendOption = QRadioButton(getMessage("privacy-dontsend-option"))
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption)

        self.filenameprivacyLabel.setObjectName("filename-privacy")
        self.filenameprivacySendRawOption.setObjectName("privacy-sendraw" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDRAW_MODE)
        self.filenameprivacySendHashedOption.setObjectName("privacy-sendhashed" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDHASHED_MODE)
        self.filenameprivacyDontSendOption.setObjectName("privacy-dontsend" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_DONTSEND_MODE)
        self.filesizeprivacyLabel.setObjectName("filesize-privacy")
        self.filesizeprivacySendRawOption.setObjectName("privacy-sendraw" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDRAW_MODE)
        self.filesizeprivacySendHashedOption.setObjectName("privacy-sendhashed" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDHASHED_MODE)
        self.filesizeprivacyDontSendOption.setObjectName("privacy-dontsend" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_DONTSEND_MODE)

        self.coreSettingsLayout.addWidget(self.filenameprivacyLabel, 3, 0)
        self.coreSettingsLayout.addWidget(self.filenameprivacySendRawOption, 3, 1, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filenameprivacySendHashedOption, 3, 2, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filenameprivacyDontSendOption, 3, 3, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filesizeprivacyLabel, 4, 0)
        self.coreSettingsLayout.addWidget(self.filesizeprivacySendRawOption, 4, 1, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 4, 2, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 4, 3, Qt.AlignLeft)

        ## Syncplay internals

        self.internalSettingsGroup = QtGui.QGroupBox(getMessage("syncplay-internals-title"))
        self.internalSettingsLayout = QtGui.QVBoxLayout()
        self.internalSettingsGroup.setLayout(self.internalSettingsLayout)

        self.alwaysshowCheckbox = QCheckBox(getMessage("forceguiprompt-label"))
        self.alwaysshowCheckbox.setObjectName(constants.INVERTED_STATE_MARKER + "forceGuiPrompt")
        self.internalSettingsLayout.addWidget(self.alwaysshowCheckbox)

        self.automaticupdatesCheckbox = QCheckBox(getMessage("checkforupdatesautomatically-label"))
        self.automaticupdatesCheckbox.setObjectName("checkForUpdatesAutomatically")
        self.internalSettingsLayout.addWidget(self.automaticupdatesCheckbox)

        self.miscLayout.addWidget(self.coreSettingsGroup)
        self.miscLayout.addWidget(self.internalSettingsGroup)
        self.miscLayout.setAlignment(Qt.AlignTop)
        self.stackedLayout.addWidget(self.miscFrame)
Exemple #25
0
class Form(QDialog):
    def __init__(self, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.state = state
        self.setWindowTitle("Copy Entry — {}".format(
            QApplication.applicationName()))
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        self.updateUi()
        settings = QSettings()
        self.updateToolTips(
            bool(
                int(
                    settings.value(Gopt.Key.ShowDialogToolTips,
                                   Gopt.Default.ShowDialogToolTips))))

    def createWidgets(self):
        selectedEid = self.state.viewAllPanel.view.selectedEid
        self.selectedEntry = self.state.model.entry(selectedEid)
        self.entryLabel = QLabel("Copy ")
        termText = Lib.elidePatchHtml(self.selectedEntry.term, self.state)
        self.termLabel = Widgets.Label.HtmlLabel("“{}”".format(termText))

        self.eidGroup = QGroupBox()

        self.copyToTopRadioButton = QRadioButton("to be a &Main Entry")
        self.tooltips.append((self.copyToTopRadioButton, """\
<p><b>to be a Main Entry</b></p>
<p>Copy the original entry to be a Main Entry (even if it is
already).</p>"""))
        self.subentryRadioButton = QRadioButton("to be a &Subentry of itself")
        self.tooltips.append((self.subentryRadioButton, """\
<p><b>to be a Subentry of itself</b></p>
<p>Copy the original entry to be a subentry of the original entry.</p>"""))
        self.siblingRadioButton = QRadioButton("to be a Si&bling of itself")
        self.tooltips.append((self.subentryRadioButton, """\
<p><b>to be a Sibling of itself</b></p>
<p>Copy the original entry to be a sibling of itself, i.e., to be a
subentry of the original entry's parent.</p>"""))

        self.filteredEntry = self.circledEntry = None
        filteredEid = self.state.viewFilteredPanel.view.selectedEid
        if filteredEid is not None:
            self.filteredEntry = self.state.model.entry(filteredEid)
        circledEid = self.state.viewAllPanel.view.circledEid
        if circledEid is not None:
            self.circledEntry = self.state.model.entry(circledEid)

        self.filteredRadioButton = QRadioButton("under &Filtered")
        self.circledRadioButton = QRadioButton("under C&ircled")
        self.recentRadioButton = QRadioButton("under &Recent")
        self.tooltips.append(
            (self.recentRadioButton, """<p><b>under Recent</b></p>
<p>Copy the current entry under a recently visited entry.</p>"""))

        self.filteredLabel = Widgets.Label.HtmlLabel()
        self.circledLabel = Widgets.Label.HtmlLabel()

        self.copyToTopRadioButton.setChecked(True)
        seen = {selectedEid}
        self.buttons = (self.copyToTopRadioButton, self.subentryRadioButton,
                        self.filteredRadioButton, self.circledRadioButton,
                        self.recentRadioButton)
        Forms.Util.setUpRadioButton(
            self, self.filteredEntry, self.filteredRadioButton,
            self.filteredLabel, self.buttons, seen,
            """<p><b>under Filtered</b></p>
<p>Copy the current entry under the filtered entry “{}”.</p>""")
        Forms.Util.setUpRadioButton(
            self, self.circledEntry, self.circledRadioButton,
            self.circledLabel, self.buttons, seen,
            """<p><b>under Circled</b></p>
<p>Copy the current entry under the circled entry “{}”.</p>""")
        self.recentComboBox = Forms.Util.createTermsComboBox(
            self.state, self.state.gotoEids, ignore=seen, maximum=MAX_RECENT)

        self.optionsGroup = QGroupBox()
        self.copyAllCheckBox = QCheckBox("Copy &All:")
        self.tooltips.append((self.copyAllCheckBox, """\
<p><b>Copy All</b></p>
<p>If you check this checkbox, the other Copy checkboxes are checked in
one go.</p>"""))
        self.copyXrefsCheckBox = QCheckBox("Cross-r&eferences")
        self.tooltips.append((self.copyXrefsCheckBox, """\
<p><b>Cross-references</b></p>
<p>Copy cross-references from the original entry(ies) to the copied
entry(ies).</p>"""))
        self.copyGroupsCheckBox = QCheckBox("&Groups")
        self.tooltips.append((self.copyGroupsCheckBox, """\
<p><b>Groups</b></p>
<p>Copy groups from the original entry(ies) to the copied
entry(ies).</p>
<p>If you check the <b>Link Pages...</b> checkbox, this checkbox will be
both checked and disabled, since linking is achieved by copying a linked
group (creating one if necessary).</p>"""))
        self.copySubentriesCheckBox = QCheckBox("S&ubentries")
        self.tooltips.append((self.copySubentriesCheckBox, """\
<p><b>Subentries</b></p>
<p>Copy the copied entry's subentries, subsubentries, and so on.</p>"""))
        self.linkPagesCheckBox = QCheckBox("&Link Pages between")
        self.linkLabel = Widgets.Label.HtmlLabel(
            "“{}” and its copy".format(termText))
        self.tooltips.append((self.linkPagesCheckBox, """\
<p><b>Link Pages</b></p>
<p>If the original entry belongs to a linked group, its copy is added to
that linked group. If the original doesn't belong to a linked group, a
new linked group is created with the name of the original's term, and
both the original and its copy are added to this new linked group.</p>
<p>If you check the this checkbox, the <b>Copy Groups</b> checkbox will be
both checked and disabled, since linking is achieved by copying a linked
group (creating one if necessary).</p>"""))
        self.withSeeCheckBox = QCheckBox("A&dd a")
        self.withSeeLabel1 = Widgets.Label.HtmlLabel(
            "<i>see</i> cross-reference from the copy to “{}”".format(
                termText))
        self.withSeeLabel2 = Widgets.Label.HtmlLabel(
            "and <i>don't</i> copy the pages")
        self.withSeeLabel2.setIndent(self.fontMetrics().width("WW"))

        self.buttonBox = QDialogButtonBox()
        self.copyButton = QPushButton(QIcon(":/copy.svg"), "C&opy")
        self.tooltips.append((self.copyButton, """<p><b>Copy</b></p>
<p>Copy the “{}” entry.</p>""".format(self.termLabel.text())))
        self.buttonBox.addButton(self.copyButton, QDialogButtonBox.AcceptRole)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel")
        self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p>
<p>Close the dialog without making any changes to the index.</p>"""))
        self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the Copy Entry dialog"))
        self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)

    def layoutWidgets(self):
        layout = QVBoxLayout()
        entryLayout = QHBoxLayout()
        entryLayout.setSpacing(0)
        entryLayout.addWidget(self.entryLabel)
        entryLayout.addWidget(self.termLabel)
        entryLayout.addStretch()
        layout.addLayout(entryLayout)
        eidLayout = QVBoxLayout()
        eidLayout.addWidget(self.copyToTopRadioButton)
        eidLayout.addWidget(self.subentryRadioButton)
        eidLayout.addWidget(self.siblingRadioButton)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.filteredRadioButton)
        hbox.addWidget(self.filteredLabel, 1)
        eidLayout.addLayout(hbox)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.circledRadioButton)
        hbox.addWidget(self.circledLabel, 1)
        eidLayout.addLayout(hbox)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.recentRadioButton)
        hbox.addWidget(self.recentComboBox, 1)
        eidLayout.addLayout(hbox)
        eidLayout.addStretch()
        self.eidGroup.setLayout(eidLayout)
        layout.addWidget(self.eidGroup)
        vbox = QVBoxLayout()
        hbox = QHBoxLayout()
        hbox.addWidget(self.copyAllCheckBox)
        hbox.addWidget(self.copyXrefsCheckBox)
        hbox.addWidget(self.copyGroupsCheckBox)
        hbox.addWidget(self.copySubentriesCheckBox)
        hbox.addStretch()
        vbox.addLayout(hbox)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.linkPagesCheckBox)
        hbox.addWidget(self.linkLabel)
        hbox.addStretch()
        vbox.addLayout(hbox)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.withSeeCheckBox)
        hbox.addWidget(self.withSeeLabel1)
        hbox.addStretch()
        vbox.addLayout(hbox)
        vbox.addWidget(self.withSeeLabel2)
        self.optionsGroup.setLayout(vbox)
        layout.addWidget(self.optionsGroup)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def createConnections(self):
        self.buttonBox.accepted.connect(self.copy)
        self.buttonBox.rejected.connect(self.reject)
        self.helpButton.clicked.connect(self.help)
        self.copyXrefsCheckBox.toggled.connect(self.updateUi)
        self.copyGroupsCheckBox.toggled.connect(self.updateUi)
        self.copySubentriesCheckBox.toggled.connect(self.updateUi)
        self.linkPagesCheckBox.toggled.connect(self.updateUi)
        self.withSeeCheckBox.toggled.connect(self.updateUi)
        self.copyAllCheckBox.toggled.connect(self.copyAll)
        self.recentRadioButton.toggled.connect(self.moveFocus)
        self.recentComboBox.currentIndexChanged[int].connect(
            self.recentChanged)

    def recentChanged(self):
        self.recentRadioButton.setChecked(True)
        self.updateUi()

    def moveFocus(self):
        if self.recentRadioButton.isChecked():
            self.recentComboBox.setFocus()

    def updateUi(self):
        self.recentRadioButton.setEnabled(self.recentComboBox.count())
        self.recentComboBox.setEnabled(self.recentComboBox.count())
        enable = not self.withSeeCheckBox.isChecked()
        for widget in (self.copyAllCheckBox, self.copyXrefsCheckBox,
                       self.copyGroupsCheckBox, self.copySubentriesCheckBox,
                       self.linkPagesCheckBox):
            if not enable:
                widget.setChecked(False)
            widget.setEnabled(enable)
        self.linkLabel.setEnabled(enable)
        if enable:
            if self.linkPagesCheckBox.isChecked():
                self.copyGroupsCheckBox.setChecked(True)
                self.copyGroupsCheckBox.setEnabled(False)
            else:
                self.copyGroupsCheckBox.setEnabled(True)
            self.copyAllCheckBox.setChecked(
                all(widget.isChecked()
                    for widget in (self.copyXrefsCheckBox,
                                   self.copyGroupsCheckBox,
                                   self.copySubentriesCheckBox)))

    def copyAll(self, checked):
        if checked:
            for widget in (self.copyXrefsCheckBox, self.copyGroupsCheckBox,
                           self.copySubentriesCheckBox):
                widget.setChecked(True)

    def help(self):
        self.state.help("xix_ref_dlg_copy.html")

    def copy(self):
        self.state.maybeSave()
        eid = self.selectedEntry.eid
        peid = None
        if self.copyToTopRadioButton.isChecked():
            peid = ROOT
            description = "copy “{}” to be main entry"
        elif self.subentryRadioButton.isChecked():
            peid = eid
            description = "copy “{}” to be subentry of itself"
        elif self.siblingRadioButton.isChecked():
            peid = self.selectedEntry.peid
            description = "copy “{}” to be sibling of itself"
        elif self.filteredRadioButton.isChecked():
            peid = self.filteredEntry.eid
            description = "copy “{}” under filtered"
        elif self.circledRadioButton.isChecked():
            peid = self.circledEntry.eid
            description = "copy “{}” under circled"
        elif self.recentRadioButton.isChecked():
            peid = self.recentComboBox.itemData(
                self.recentComboBox.currentIndex())
            description = "copy “{}” under recently visited"
        if peid is not None:  # Should always be True
            description = description.format(
                Lib.elidePatchHtml(self.selectedEntry.term, self.state))
            self.state.model.copyEntry(
                Lib.CopyInfo(eid, peid, self.copyXrefsCheckBox.isChecked(),
                             self.copyGroupsCheckBox.isChecked(),
                             self.copySubentriesCheckBox.isChecked(),
                             self.linkPagesCheckBox.isChecked(),
                             self.withSeeCheckBox.isChecked(), description))
            say(re.sub(r"^copy", "Copied", Lib.htmlToPlainText(description)),
                SAY_TIMEOUT)
        self.accept()
Exemple #26
0
    def createWidgets(self):
        selectedEid = self.state.viewAllPanel.view.selectedEid
        self.selectedEntry = self.state.model.entry(selectedEid)
        self.entryLabel = QLabel("Copy ")
        termText = Lib.elidePatchHtml(self.selectedEntry.term, self.state)
        self.termLabel = Widgets.Label.HtmlLabel("“{}”".format(termText))

        self.eidGroup = QGroupBox()

        self.copyToTopRadioButton = QRadioButton("to be a &Main Entry")
        self.tooltips.append((self.copyToTopRadioButton, """\
<p><b>to be a Main Entry</b></p>
<p>Copy the original entry to be a Main Entry (even if it is
already).</p>"""))
        self.subentryRadioButton = QRadioButton("to be a &Subentry of itself")
        self.tooltips.append((self.subentryRadioButton, """\
<p><b>to be a Subentry of itself</b></p>
<p>Copy the original entry to be a subentry of the original entry.</p>"""))
        self.siblingRadioButton = QRadioButton("to be a Si&bling of itself")
        self.tooltips.append((self.subentryRadioButton, """\
<p><b>to be a Sibling of itself</b></p>
<p>Copy the original entry to be a sibling of itself, i.e., to be a
subentry of the original entry's parent.</p>"""))

        self.filteredEntry = self.circledEntry = None
        filteredEid = self.state.viewFilteredPanel.view.selectedEid
        if filteredEid is not None:
            self.filteredEntry = self.state.model.entry(filteredEid)
        circledEid = self.state.viewAllPanel.view.circledEid
        if circledEid is not None:
            self.circledEntry = self.state.model.entry(circledEid)

        self.filteredRadioButton = QRadioButton("under &Filtered")
        self.circledRadioButton = QRadioButton("under C&ircled")
        self.recentRadioButton = QRadioButton("under &Recent")
        self.tooltips.append(
            (self.recentRadioButton, """<p><b>under Recent</b></p>
<p>Copy the current entry under a recently visited entry.</p>"""))

        self.filteredLabel = Widgets.Label.HtmlLabel()
        self.circledLabel = Widgets.Label.HtmlLabel()

        self.copyToTopRadioButton.setChecked(True)
        seen = {selectedEid}
        self.buttons = (self.copyToTopRadioButton, self.subentryRadioButton,
                        self.filteredRadioButton, self.circledRadioButton,
                        self.recentRadioButton)
        Forms.Util.setUpRadioButton(
            self, self.filteredEntry, self.filteredRadioButton,
            self.filteredLabel, self.buttons, seen,
            """<p><b>under Filtered</b></p>
<p>Copy the current entry under the filtered entry “{}”.</p>""")
        Forms.Util.setUpRadioButton(
            self, self.circledEntry, self.circledRadioButton,
            self.circledLabel, self.buttons, seen,
            """<p><b>under Circled</b></p>
<p>Copy the current entry under the circled entry “{}”.</p>""")
        self.recentComboBox = Forms.Util.createTermsComboBox(
            self.state, self.state.gotoEids, ignore=seen, maximum=MAX_RECENT)

        self.optionsGroup = QGroupBox()
        self.copyAllCheckBox = QCheckBox("Copy &All:")
        self.tooltips.append((self.copyAllCheckBox, """\
<p><b>Copy All</b></p>
<p>If you check this checkbox, the other Copy checkboxes are checked in
one go.</p>"""))
        self.copyXrefsCheckBox = QCheckBox("Cross-r&eferences")
        self.tooltips.append((self.copyXrefsCheckBox, """\
<p><b>Cross-references</b></p>
<p>Copy cross-references from the original entry(ies) to the copied
entry(ies).</p>"""))
        self.copyGroupsCheckBox = QCheckBox("&Groups")
        self.tooltips.append((self.copyGroupsCheckBox, """\
<p><b>Groups</b></p>
<p>Copy groups from the original entry(ies) to the copied
entry(ies).</p>
<p>If you check the <b>Link Pages...</b> checkbox, this checkbox will be
both checked and disabled, since linking is achieved by copying a linked
group (creating one if necessary).</p>"""))
        self.copySubentriesCheckBox = QCheckBox("S&ubentries")
        self.tooltips.append((self.copySubentriesCheckBox, """\
<p><b>Subentries</b></p>
<p>Copy the copied entry's subentries, subsubentries, and so on.</p>"""))
        self.linkPagesCheckBox = QCheckBox("&Link Pages between")
        self.linkLabel = Widgets.Label.HtmlLabel(
            "“{}” and its copy".format(termText))
        self.tooltips.append((self.linkPagesCheckBox, """\
<p><b>Link Pages</b></p>
<p>If the original entry belongs to a linked group, its copy is added to
that linked group. If the original doesn't belong to a linked group, a
new linked group is created with the name of the original's term, and
both the original and its copy are added to this new linked group.</p>
<p>If you check the this checkbox, the <b>Copy Groups</b> checkbox will be
both checked and disabled, since linking is achieved by copying a linked
group (creating one if necessary).</p>"""))
        self.withSeeCheckBox = QCheckBox("A&dd a")
        self.withSeeLabel1 = Widgets.Label.HtmlLabel(
            "<i>see</i> cross-reference from the copy to “{}”".format(
                termText))
        self.withSeeLabel2 = Widgets.Label.HtmlLabel(
            "and <i>don't</i> copy the pages")
        self.withSeeLabel2.setIndent(self.fontMetrics().width("WW"))

        self.buttonBox = QDialogButtonBox()
        self.copyButton = QPushButton(QIcon(":/copy.svg"), "C&opy")
        self.tooltips.append((self.copyButton, """<p><b>Copy</b></p>
<p>Copy the “{}” entry.</p>""".format(self.termLabel.text())))
        self.buttonBox.addButton(self.copyButton, QDialogButtonBox.AcceptRole)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel")
        self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p>
<p>Close the dialog without making any changes to the index.</p>"""))
        self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the Copy Entry dialog"))
        self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
Exemple #27
0
    def __init__(self):
        '''
        Constructor
        '''
        super(MyWidget1, self).__init__()
        gridlayout = QGridLayout()

        label1 = QLabel("KATEGORIJA")
        label2 = QLabel("DEONICA")
        label3 = QLabel("VALUTA")

        kategorija = QGroupBox()
        hbox = QHBoxLayout()

        iakat = QRadioButton("Ia")
        iakat.setChecked(True)
        #lakat.setIcon(QIcon("lakat.png"))
        ikat = QRadioButton("I")
        iikat = QRadioButton("II")
        iiikat = QRadioButton("III")
        ivkat = QRadioButton("IV")
        hbox.addWidget(iakat)
        hbox.addWidget(ikat)
        hbox.addWidget(iikat)
        hbox.addWidget(iiikat)
        hbox.addWidget(ivkat)
        kategorija.setLayout(hbox)

        deonica = QComboBox()
        deonica.setEditable(False)

        deonica.addItems(Deonice().listaDeonica)

        valuta = QGroupBox()
        hbox1 = QHBoxLayout()
        eur = QRadioButton("EUR")
        rsd = QRadioButton("RSD")
        rsd.setChecked(True)
        cenaRsd = QLineEdit()
        cenaRsd.setReadOnly(True)
        cenaEur = QLineEdit()
        cenaEur.setReadOnly(True)
        hbox1.addWidget(rsd)
        hbox1.addWidget(cenaRsd)
        hbox1.addWidget(eur)
        hbox1.addWidget(cenaEur)
        valuta.setLayout(hbox1)

        btnNaplati = QPushButton("\nNAPLATI\n")
        btnNaplati.clicked.connect(self.naplatiAction)

        btnPodigni = QPushButton("\nPODIGNI RAMPU\n")
        btnPodigni.clicked.connect(self.podigniAction)

        btnSpusti = QPushButton("\nSPUSTI RAMPU\n")
        btnSpusti.clicked.connect(self.spustiAction)

        gridlayout.addWidget(label1, 0, 0, 2, 3, int(Qt.AlignCenter))
        gridlayout.addWidget(label2, 2, 0, 2, 3, int(Qt.AlignCenter))
        gridlayout.addWidget(label3, 4, 0, 2, 3, int(Qt.AlignCenter))

        gridlayout.addWidget(kategorija, 0, 3, 2, 6)

        gridlayout.addWidget(deonica, 2, 3, 2, 6)

        gridlayout.addWidget(valuta, 4, 3, 2, 6)

        gridlayout.addWidget(btnNaplati, 6, 0, 2, 10)

        gridlayout.addWidget(btnPodigni, 8, 0, 2, 5)
        gridlayout.addWidget(btnSpusti, 8, 5, 2, 5)

        self.setLayout(gridlayout)
Exemple #28
0
    def _create_inlite(self, settings):
        radio = QRadioButton(
            'Either my objects are labelled with a barcode not listed above '
            'or I would like the performance and reliability of a commercial '
            'library')
        radio.setChecked('inlite' == settings['engine'])
        radio.setEnabled(inlite_available())
        self._layout.addWidget(radio)

        prompt = QLabel(
            'Only available on Windows. '
            'Visit <a href="http://www.inliteresearch.com/">Inlite Research</a> '
            'to download and install Inlite Research\'s ClearImage library.'
        )
        prompt.setWordWrap(True)
        prompt.setOpenExternalLinks(True)
        prompt.setStyleSheet(self.STYLESHEET)
        self._layout.addWidget(prompt)

        prompt = QLabel('My objects are labelled with:')
        format = settings['inlite-format']
        radio_1d = QRadioButton('1D barcodes')
        radio_1d.setChecked('1d' == format)
        radio_datamatrix = QRadioButton('Data Matrix barcodes')
        radio_datamatrix.setChecked('datamatrix' == format)
        radio_pdf417 = QRadioButton('PDF 417 barcodes')
        radio_pdf417.setChecked('pdf417' == format)
        radio_qr = QRadioButton('QR codes')
        radio_qr.setChecked('qrcode' == format)

        layout = QVBoxLayout()
        layout.addWidget(prompt)
        layout.addWidget(radio_1d)
        layout.addWidget(radio_datamatrix)
        layout.addWidget(radio_pdf417)
        layout.addWidget(radio_qr)

        group = QWidget()
        group.setLayout(layout)
        group.setStyleSheet(self.STYLESHEET)
        radio.toggled.connect(group.setEnabled)
        group.setEnabled(inlite_available() and 'inlite' == settings['engine'])

        self._layout.addWidget(group)

        return radio, radio_1d, radio_datamatrix, radio_pdf417, radio_qr
class ProfileFormWidget(QWidget):
    '''
    classdocs
    '''
    
    def __init__(self):
        '''
        Constructor
        '''
        QWidget.__init__(self)
        self._initGUI()
        
    def _initGUI(self):
        self.layout = QVBoxLayout()
        self.form = QFormLayout()
        
        self.name = QLineEdit()
        self.surname = QLineEdit()
        
        self.birthdate = QCalendarWidget()
        self.birthdate.setGridVisible(True)
        self.birthdate.setMinimumDate(QDate(1850,1,1))
        self.birthdate.setMaximumDate(QDate.currentDate())
        
        self.male = QRadioButton("Male")
        self.male.setChecked(True)
        self.female = QRadioButton("Female")
        
        self.height = QDoubleSpinBox()
        self.height.setMaximum(250)
        self.height.setMinimum(50)
        self.height.setValue(165)
        self.height.setSuffix(" cm")
        
        self.mass = QDoubleSpinBox()
        self.mass.setMaximum(300)
        self.mass.setMinimum(20)
        self.mass.setValue(60)
        self.mass.setSuffix(" Kg")
        
        btnLayout = QVBoxLayout()
        
        self.form.addRow("Name", self.name)
        self.form.addRow("Surname", self.surname)
        self.form.addRow("Birth date",self.birthdate)
        
        sexLayout = QHBoxLayout()
        sexLayout.addWidget(self.male)
        sexLayout.addWidget(self.female)
        self.form.addRow("Sex", sexLayout)
        
        self.form.addRow("Height", self.height)
        self.form.addRow("Mass", self.mass)
                
        self.layout.addLayout(self.form)
        self.layout.addLayout(btnLayout)
        self.setLayout(self.layout)
        
    def getLayout(self):
        return self.layout
    
    def getWidget(self):
        widget = QWidget()
        widget.setLayout(self.layout)
    
        return widget
    
    def setProfile(self, athlete):
        self.name.setText(athlete._name)
        self.surname.setText(athlete._surname)
        self.birthdate.setSelectedDate(athlete._birthDate)
        
        if athlete._sex=="Male":
            self.male.setChecked(True)
        else:
            self.female.setChecked(True)
            
        self.height.setValue(athlete._height)
        self.mass.setValue(athlete._mass)
                
    def getProfile(self):        
        qDate = self.birthdate.selectedDate()
        birthDate = self.qDate_to_date(qDate)
        
        athleteProfile = Athlete(self.name.text(),
                                 self.surname.text(),
                                 self._getSex(),
                                 birthDate,
                                 self.height.value(),
                                 self.mass.value())
        return athleteProfile 
    
    def qDate_to_date(self, qDate):        
        return date(qDate.year(), qDate.month(),qDate.day())
     
    def _getSex(self):
        if (self.male.isChecked()):
            return "Male"
        elif (self.female.isChecked()):
            return "Female"
        else :
            print "Error: No sex selected"
            return False
Exemple #30
0
class Form(QDialog):

    def __init__(self, state, term, candidates, result, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.state = state
        self.term = term
        self.candidates = []
        for candidate in candidates:
            self.candidates.append(humanizedCandidate(
                term, candidate.candidate, candidate.saf))
        self.result = result
        self.setWindowTitle("Sort As — {}".format(
                            QApplication.applicationName()))
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        self.updateUi()
        settings = QSettings()
        self.updateToolTips(bool(int(settings.value(
            Gopt.Key.ShowDialogToolTips, Gopt.Default.ShowDialogToolTips))))


    def createWidgets(self):
        self.termLabel = Widgets.Label.HtmlLabel(
            "<p>Sort “{}” with</p>".format(Lib.elidePatchHtml(self.term,
                                                              self.state)))
        self.radioButtons = []
        seen = set()
        for index, candidate in enumerate(self.candidates, 1):
            candidate_word = str(candidate.candidate_word)
            name = self.nameForKind(candidate.kind, candidate_word)
            extra = ""
            if candidate_word in seen:
                extra = " (treat roman numbers as literal text)"
            else:
                seen.add(candidate_word)
            radioButton = QRadioButton("&{} “{}” as{} “{}”{}".format(
                index, candidate.term_word, name, candidate_word, extra))
            self.radioButtons.append(radioButton)
        self.radioButtons[0].setChecked(True)
        self.customRadioButton = QRadioButton("&Custom:")
        self.tooltips.append((self.customRadioButton, """\
<p><b>Custom</b></p>
<p>If checked, this entry's <b>Automatically Calculate Sort As</b>
setting will be <i>unchecked</i>, and the sort as text entered here will
be used as ther entry's sort as text.</p>"""))
        self.sortAsEdit = Widgets.LineEdit.LineEdit(self.state)
        self.tooltips.append((self.sortAsEdit, """\
<p><b>Custom Sort As editor</b></p>
<p>If <b>Custom</b> is checked, this entry's <b>Automatically Calculate
Sort As</b> setting will be <i>unchecked</i>, and the sort as text
entered here will be used as ther entry's sort as text.</p>"""))
        self.sortAsEdit.setText(self.candidates[0].candidate)
        self.sortAsEdit.selectAll()
        self.buttonBox = QDialogButtonBox()
        self.okButton = QPushButton(QIcon(":/ok.svg"), "&OK")
        self.tooltips.append((self.okButton, """\
<p><b>OK</b></p>
<p>Use the specified or custom sort as text for entry
“{}”.</p>""".format(Lib.elidePatchHtml(self.term, self.state))))
        self.buttonBox.addButton(
            self.okButton, QDialogButtonBox.AcceptRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append((self.helpButton,
                              "Help on the Sort As dialog"))
        self.buttonBox.addButton(
            self.helpButton, QDialogButtonBox.HelpRole)


    def nameForKind(self, kind, candidate_word):
        name = kind.name.lower()
        if name == "unchanged":
            name = ""
        elif (name == "roman" or (
                name == "phrase" and
                re.fullmatch(r"[\d.]+", candidate_word) is not None)):
            name = "number"
        if name:
            name = " " + name
        return name


    def layoutWidgets(self):
        vbox = QVBoxLayout()
        vbox.addWidget(self.termLabel)
        for radioButton in self.radioButtons:
            vbox.addWidget(radioButton)
        hbox = QHBoxLayout()
        hbox.addWidget(self.customRadioButton)
        hbox.addWidget(self.sortAsEdit)
        vbox.addLayout(hbox)
        vbox.addWidget(self.buttonBox)
        self.setLayout(vbox)


    def createConnections(self):
        for radioButton in itertools.chain((self.customRadioButton,),
                                           self.radioButtons):
            radioButton.toggled.connect(self.updateUi)
        self.sortAsEdit.textChanged.connect(self.updateUi)
        self.okButton.clicked.connect(self.accept)
        self.helpButton.clicked.connect(self.help)


    def help(self):
        self.state.help("xix_ref_dlg_sortas.html")


    def updateUi(self):
        self.sortAsEdit.setEnabled(self.customRadioButton.isChecked())
        with Lib.BlockSignals(self.sortAsEdit):
            for i, radioButton in enumerate(self.radioButtons):
                if radioButton.isChecked():
                    self.sortAsEdit.setText(self.candidates[i].candidate)
                    self.sortAsEdit.selectAll()
                    break
        self.okButton.setEnabled(
            not self.customRadioButton.isChecked() or
            (self.customRadioButton.isChecked() and
             bool(self.sortAsEdit.toPlainText())))


    def reject(self):
        self.accept()


    def accept(self):
        if self.customRadioButton.isChecked():
            self.result.sortas = self.sortAsEdit.toPlainText()
            self.result.saf = Saf.CUSTOM
        else:
            for index, radioButton in enumerate(self.radioButtons):
                if radioButton.isChecked():
                    self.result.sortas = self.candidates[index].candidate
                    kind = self.candidates[index].kind
                    if kind is CandidateKind.LITERAL:
                        saf = Saf.AUTO_BASIC
                    elif kind is CandidateKind.NUMBER:
                        saf = Saf.AUTO_NUMBER
                    elif kind is CandidateKind.ROMAN:
                        saf = Saf.AUTO_NUMBER_ROMAN
                    elif kind is CandidateKind.PHRASE:
                        saf = Saf.AUTO
                    elif kind is CandidateKind.UNCHANGED:
                        saf = self.candidates[index].saf
                    self.result.saf = saf
                    break
        super().accept()
class ProfileFormWidget(QWidget):
    '''
    classdocs
    '''
    def __init__(self):
        '''
        Constructor
        '''
        QWidget.__init__(self)
        self._initGUI()

    def _initGUI(self):
        self.layout = QVBoxLayout()
        self.form = QFormLayout()

        self.name = QLineEdit()
        self.surname = QLineEdit()

        self.birthdate = QCalendarWidget()
        self.birthdate.setGridVisible(True)
        self.birthdate.setMinimumDate(QDate(1850, 1, 1))
        self.birthdate.setMaximumDate(QDate.currentDate())

        self.male = QRadioButton("Male")
        self.male.setChecked(True)
        self.female = QRadioButton("Female")

        self.height = QDoubleSpinBox()
        self.height.setMaximum(250)
        self.height.setMinimum(50)
        self.height.setValue(165)
        self.height.setSuffix(" cm")

        self.mass = QDoubleSpinBox()
        self.mass.setMaximum(300)
        self.mass.setMinimum(20)
        self.mass.setValue(60)
        self.mass.setSuffix(" Kg")

        btnLayout = QVBoxLayout()

        self.form.addRow("Name", self.name)
        self.form.addRow("Surname", self.surname)
        self.form.addRow("Birth date", self.birthdate)

        sexLayout = QHBoxLayout()
        sexLayout.addWidget(self.male)
        sexLayout.addWidget(self.female)
        self.form.addRow("Sex", sexLayout)

        self.form.addRow("Height", self.height)
        self.form.addRow("Mass", self.mass)

        self.layout.addLayout(self.form)
        self.layout.addLayout(btnLayout)
        self.setLayout(self.layout)

    def getLayout(self):
        return self.layout

    def getWidget(self):
        widget = QWidget()
        widget.setLayout(self.layout)

        return widget

    def setProfile(self, athlete):
        self.name.setText(athlete._name)
        self.surname.setText(athlete._surname)
        self.birthdate.setSelectedDate(athlete._birthDate)

        if athlete._sex == "Male":
            self.male.setChecked(True)
        else:
            self.female.setChecked(True)

        self.height.setValue(athlete._height)
        self.mass.setValue(athlete._mass)

    def getProfile(self):
        qDate = self.birthdate.selectedDate()
        birthDate = self.qDate_to_date(qDate)

        athleteProfile = Athlete(self.name.text(), self.surname.text(),
                                 self._getSex(), birthDate,
                                 self.height.value(), self.mass.value())
        return athleteProfile

    def qDate_to_date(self, qDate):
        return date(qDate.year(), qDate.month(), qDate.day())

    def _getSex(self):
        if (self.male.isChecked()):
            return "Male"
        elif (self.female.isChecked()):
            return "Female"
        else:
            print "Error: No sex selected"
            return False
Exemple #32
0
    def createWidgets(self):
        settings = QSettings()

        self.searchLabel = QLabel("Search For")
        self.searchLineEdit = QLineEdit()
        self.tooltips.append((self.searchLineEdit, """\
<p><b>Search For editor</b></p>
<p>The text or regular expression to search for.</p>"""))
        self.searchLabel.setBuddy(self.searchLineEdit)
        self.replaceLabel = QLabel("Replace With")
        self.replaceLineEdit = QLineEdit()
        self.tooltips.append((self.replaceLineEdit, """\
<p><b>Replace With editor</b></p>
<p>The replacement text (which may include backreferences, \\1, \\2,
etc., if a regular expression search is being made).</p>"""))
        self.replaceLabel.setBuddy(self.replaceLineEdit)

        self.allEntriesRadioButton = QRadioButton("All Entries")
        self.allEntriesRadioButton.setChecked(
            bool(int(settings.value("RP/All", 1))))
        self.tooltips.append((self.allEntriesRadioButton, """\
<p><b>All Entries</b></p>
<p>If checked, the search will consider every entry in the index.</p>"""))
        self.filteredEntriesRadioButton = QRadioButton("Filtered Entries")
        self.filteredEntriesRadioButton.setChecked(
            bool(int(settings.value("RP/Filtered", 0))))
        self.tooltips.append((self.filteredEntriesRadioButton, """\
<p><b>Filtered Entries</b></p>
<p>If checked, the search will consider only those entries that are in
the current filtered view.</p>"""))
        self.considerLabel = QLabel("Consider")
        self.scopeGroup = QButtonGroup()
        self.scopeGroup.addButton(self.allEntriesRadioButton)
        self.scopeGroup.addButton(self.filteredEntriesRadioButton)

        self.literalRadioButton = QRadioButton("Literal")
        self.literalRadioButton.setChecked(
            bool(int(settings.value("RP/Literal", 1))))
        self.tooltips.append((self.literalRadioButton, """<p><b>Literal</b></p>
<p>If checked, the <b>Search For</b> text will be searched for
literally.</p>"""))
        self.regexRadioButton = QRadioButton("Regex")
        self.regexRadioButton.setChecked(
            bool(int(settings.value("RP/Regex", 0))))
        self.tooltips.append((self.regexRadioButton, """<p><b>Regex</b></p>
<p>If checked, the <b>Search For</b> text will be searched for
as a regular expression pattern.</p>"""))
        self.matchAsGroup = QButtonGroup()
        self.matchAsGroup.addButton(self.literalRadioButton)
        self.matchAsGroup.addButton(self.regexRadioButton)
        self.ignoreCaseCheckBox = QCheckBox("Ignore Case")
        self.ignoreCaseCheckBox.setChecked(
            bool(int(settings.value("RP/ICase", 0))))
        self.tooltips.append((self.ignoreCaseCheckBox, """\
<p><b>Ignore Case</b></p>
<p>If checked, the <b>Search For</b> text will be searched for
case-insensitively.</p>"""))
        self.wholeWordsCheckBox = QCheckBox("Whole Words")
        self.wholeWordsCheckBox.setChecked(
            bool(int(settings.value("RP/WW", 0))))
        self.tooltips.append((self.wholeWordsCheckBox, """\
<p><b>Whole Words</b></p>
<p>If checked&mdash;and when <b>Literal</b> is checked&mdash;the
<b>Search For</b> text will be matched as whole words.</p>
<p>For example, “habit” will not match “habitat” when whole words is
checked.</p>
<p>(For regular expressions use \\b before and after each word to get
whole word matches.)</p>"""))

        self.replaceInLabel = QLabel("Look In")
        self.replaceInTermsCheckBox = QCheckBox("Terms")
        self.replaceInTermsCheckBox.setChecked(
            bool(int(settings.value("RP/Terms", 1))))
        self.tooltips.append((self.replaceInTermsCheckBox, """\
<p><b>Terms</b></p>
<p>If checked, the search will look in term texts.</p>"""))
        self.replaceInPagesCheckBox = QCheckBox("Pages")
        self.replaceInPagesCheckBox.setChecked(
            bool(int(settings.value("RP/Pages", 0))))
        self.tooltips.append((self.replaceInPagesCheckBox, """\
<p><b>Pages</b></p>
<p>If checked, the search will look in pages texts.</p>"""))
        self.replaceInNotesCheckBox = QCheckBox("Notes")
        self.replaceInNotesCheckBox.setChecked(
            bool(int(settings.value("RP/Notes", 0))))
        self.tooltips.append((self.replaceInNotesCheckBox, """\
<p><b>Notes</b></p>
<p>If checked, the search will look in notes texts.</p>"""))
        self.startButton = QPushButton(QIcon(":/edit-find.svg"),
                                       "Start Search")
        self.tooltips.append((self.startButton, """<p><b>Start Search</b></p>
<p>Start the search from the first entry in the index or the first entry
in the filtered view's entries.</p>"""))
        self.replaceButton = QPushButton(QIcon(":/edit-find-replace.svg"),
                                         "Replace")
        self.tooltips.append((self.replaceButton, """<p><b>Replace</b></p>
<p>Replace the highlighted text with the <b>Replace With</b> text (using
backreferences if they are in the replacement text and a <b>Regex</b>
search is underway), and then try to find the next matching text.</p>"""))
        self.skipButton = QPushButton(QIcon(":/skip.svg"), "S&kip")
        self.tooltips.append((self.skipButton, """<p><b>Skip</b></p>
<p>Skip the highlighted text and try to find the next matching
text.</p>"""))
        self.stopButton = QPushButton(QIcon(":/process-stop.svg"),
                                      "Stop Search")
        self.tooltips.append((self.stopButton, """<p><b>Stop Search</b></p>
<p>Stop the current search. This allows the search options to be
changed.</p>"""))
        self.closeButton = QToolButton()
        self.closeButton.setIcon(QIcon(":/hide.svg"))
        self.closeButton.setFocusPolicy(Qt.NoFocus)
        self.tooltips.append((self.closeButton, """<p><b>Hide</b></p>
<p>Hide the Search and Replace panel.</p>
<p>Press <b>Ctrl+H</b> or click <img src=":/edit-find-replace.svg"
width={0} height={0}> or click <b>Edit→Search and Replace</b> to show it
again.</p>""".format(TOOLTIP_IMAGE_SIZE)))
        self.helpButton = QToolButton()
        self.helpButton.setIcon(QIcon(":/help.svg"))
        self.helpButton.setFocusPolicy(Qt.NoFocus)
        self.tooltips.append(
            (self.helpButton, "Help on the Search and Replace panel."))
class ConfigDialog(QtGui.QDialog):

    pressedclosebutton = False
    moreToggling = False

    def moreToggled(self):
        if self.moreToggling == False:
            self.moreToggling = True

            if self.showmoreCheckbox.isChecked():
                self.tabListFrame.show()
                self.resetButton.show()
                self.nostoreCheckbox.show()
                self.alwaysshowCheckbox.show()
                self.saveMoreState(True)
                self.tabListWidget.setCurrentRow(0)
                self.ensureTabListIsVisible()
            else:
                self.tabListFrame.hide()
                self.resetButton.hide()
                self.nostoreCheckbox.hide()
                self.alwaysshowCheckbox.hide()
                self.saveMoreState(False)
                self.stackedLayout.setCurrentIndex(0)

            self.adjustSize()
            self.setFixedSize(self.sizeHint())
        self.moreToggling = False
        self.setFixedWidth(self.minimumSizeHint().width())
        self.executablepathCombobox.setFixedWidth(self.mediapathTextbox.width())

    def runButtonTextUpdate(self):
        if self.nostoreCheckbox.isChecked():
            self.runButton.setText(getMessage("run-label"))
        else:
            self.runButton.setText(getMessage("storeandrun-label"))

    def openHelp(self):
        self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/client/")

    def _tryToFillPlayerPath(self, playerpath, playerpathlist):
        settings = QSettings("Syncplay", "PlayerList")
        settings.beginGroup("PlayerList")
        savedPlayers = settings.value("PlayerList", [])
        if not isinstance(savedPlayers, list):
            savedPlayers = []
        playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers)))
        settings.endGroup()
        foundpath = ""

        if playerpath != None and playerpath != "":
            if not os.path.isfile(playerpath):
                expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath)
                if expandedpath != None and os.path.isfile(expandedpath):
                    playerpath = expandedpath

            if os.path.isfile(playerpath):
                foundpath = playerpath
                self.executablepathCombobox.addItem(foundpath)

        for path in playerpathlist:
            if os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath)):
                self.executablepathCombobox.addItem(path)
                if foundpath == "":
                    foundpath = path

        if foundpath != "":
            settings.beginGroup("PlayerList")
            playerpathlist.append(os.path.normcase(os.path.normpath(foundpath)))
            settings.setValue("PlayerList", list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist))))
            settings.endGroup()
        return foundpath

    def updateExecutableIcon(self):
        currentplayerpath = unicode(self.executablepathCombobox.currentText())
        iconpath = PlayerFactory().getPlayerIconByPath(currentplayerpath)
        if iconpath != None and iconpath != "":
            self.executableiconImage.load(self.resourcespath + iconpath)
            self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(self.executableiconImage))
        else:
            self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage()))


    def browsePlayerpath(self):
        options = QtGui.QFileDialog.Options()
        defaultdirectory = ""
        browserfilter = "All files (*)"

        if os.name == 'nt':
            browserfilter = "Executable files (*.exe);;All files (*)"
            if "PROGRAMFILES(X86)" in os.environ:
                defaultdirectory = os.environ["ProgramFiles(x86)"]
            elif "PROGRAMFILES" in os.environ:
                defaultdirectory = os.environ["ProgramFiles"]
            elif "PROGRAMW6432" in os.environ:
                defaultdirectory = os.environ["ProgramW6432"]
        elif sys.platform.startswith('linux'):
            defaultdirectory = "/usr/bin"
        elif sys.platform.startswith('darwin'):
            defaultdirectory = "/Applications/"

        fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,
                "Browse for media player executable",
                defaultdirectory,
                browserfilter, "", options)
        if fileName:
            self.executablepathCombobox.setEditText(os.path.normpath(fileName))

    def loadMediaBrowseSettings(self):
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.beginGroup("MediaBrowseDialog")
        self.mediadirectory = settings.value("mediadir", "")
        settings.endGroup()

    def saveMediaBrowseSettings(self):
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.beginGroup("MediaBrowseDialog")
        settings.setValue("mediadir", self.mediadirectory)
        settings.endGroup()

    def getMoreState(self):
        settings = QSettings("Syncplay", "MoreSettings")
        settings.beginGroup("MoreSettings")
        morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false")))
        settings.endGroup()
        if morestate == "true":
            return True
        else:
            return False

    def saveMoreState(self, morestate):
        settings = QSettings("Syncplay", "MoreSettings")
        settings.beginGroup("MoreSettings")
        settings.setValue("ShowMoreSettings", morestate)
        settings.endGroup()

    def browseMediapath(self):
        self.loadMediaBrowseSettings()
        options = QtGui.QFileDialog.Options()
        if os.path.isdir(self.mediadirectory):
            defaultdirectory = self.mediadirectory
        elif os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)):
            defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
        elif os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation)):
            defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        else:
            defaultdirectory = ""
        browserfilter = "All files (*)"
        fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media files", defaultdirectory,
                browserfilter, "", options)
        if fileName:
            self.mediapathTextbox.setText(os.path.normpath(fileName))
            self.mediadirectory = os.path.dirname(fileName)
            self.saveMediaBrowseSettings()

    def _saveDataAndLeave(self):
        self.processWidget(self, lambda w: self.saveValues(w))
        if self.hostTextbox.text():
            self.config['host'] = self.hostTextbox.text() if ":" in self.hostTextbox.text() else self.hostTextbox.text() + ":" + unicode(constants.DEFAULT_PORT)
        else:
            self.config['host'] = None
        self.config['playerPath'] = unicode(self.executablepathCombobox.currentText())
        if self.mediapathTextbox.text() == "":
            self.config['file'] = None
        elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())):
            self.config['file'] = os.path.abspath(self.mediapathTextbox.text())
        else:
            self.config['file'] = unicode(self.mediapathTextbox.text())

        if not self.slowdownThresholdSpinbox.text:
            self.slowdownThresholdSpinbox.value = constants.DEFAULT_SLOWDOWN_KICKIN_THRESHOLD
        if not self.rewindThresholdSpinbox.text:
            self.rewindThresholdSpinbox.value = constants.DEFAULT_REWIND_THRESHOLD
        self.config['slowdownThreshold'] = self.slowdownThresholdSpinbox.value()
        self.config['rewindThreshold'] = self.rewindThresholdSpinbox.value()

        self.pressedclosebutton = True
        self.close()
        return

    def closeEvent(self, event):
        if self.pressedclosebutton == False:
            sys.exit()
            raise GuiConfiguration.WindowClosed
            event.accept()

    def dragEnterEvent(self, event):
        data = event.mimeData()
        urls = data.urls()
        if urls and urls[0].scheme() == 'file':
            event.acceptProposedAction()

    def dropEvent(self, event):
        data = event.mimeData()
        urls = data.urls()
        if urls and urls[0].scheme() == 'file':
            if sys.platform.startswith('win'):
                dropfilepath = unicode(urls[0].path())[1:]  # Removes starting slash
            else:
                dropfilepath = unicode(urls[0].path())
            if dropfilepath[-4:].lower() == ".exe":
                self.executablepathCombobox.setEditText(dropfilepath)
            else:
                self.mediapathTextbox.setText(dropfilepath)

    def processWidget(self, container, torun):
        for widget in container.children():
            self.processWidget(widget, torun)
            if hasattr(widget, 'objectName') and widget.objectName() and widget.objectName()[:3] != "qt_":
                torun(widget)

    def loadTooltips(self, widget):
        tooltipName = widget.objectName().lower().split(constants.CONFIG_NAME_MARKER)[0] + "-tooltip"
        if tooltipName[:1] == constants.INVERTED_STATE_MARKER or tooltipName[:1] == constants.LOAD_SAVE_MANUALLY_MARKER:
            tooltipName = tooltipName[1:]
        widget.setToolTip(getMessage(tooltipName))

    def loadValues(self, widget):
        valueName = str(widget.objectName())
        if valueName[:1] == constants.LOAD_SAVE_MANUALLY_MARKER:
            return

        if isinstance(widget, QCheckBox) and widget.objectName():
            if valueName[:1] == constants.INVERTED_STATE_MARKER:
                valueName = valueName[1:]
                inverted = True
            else:
                inverted = False
            widget.setChecked(self.config[valueName] != inverted)
        elif isinstance(widget, QRadioButton):
            radioName, radioValue  = valueName.split(constants.CONFIG_NAME_MARKER)[1].split(constants.CONFIG_VALUE_MARKER)
            if self.config[radioName] == radioValue:
                widget.setChecked(True)
        elif isinstance(widget, QLineEdit):
            widget.setText(self.config[valueName])

    def saveValues(self, widget):
        valueName = str(widget.objectName())
        if valueName[:1] == constants.LOAD_SAVE_MANUALLY_MARKER:
            return

        if isinstance(widget, QCheckBox) and widget.objectName():
            if valueName[:1] == constants.INVERTED_STATE_MARKER:
                valueName = valueName[1:]
                inverted = True
            else:
                inverted = False
            self.config[valueName] = widget.isChecked() != inverted
        elif isinstance(widget, QRadioButton):
            radioName, radioValue  = valueName.split(constants.CONFIG_NAME_MARKER)[1].split(constants.CONFIG_VALUE_MARKER)
            if widget.isChecked():
                self.config[radioName] = radioValue
        elif isinstance(widget, QLineEdit):
            self.config[valueName] = widget.text()

    def connectChildren(self, widget):
        widgetName = str(widget.objectName())
        if self.subitems.has_key(widgetName) and isinstance(widget, QCheckBox):
            widget.stateChanged.connect(lambda: self.updateSubwidgets(self, widget))
            self.updateSubwidgets(self, widget)

    def updateSubwidgets(self, container, parentwidget, subwidgets=None):
        widgetName = parentwidget.objectName()
        if not subwidgets:
            subwidgets = self.subitems[widgetName]
        for widget in container.children():
            self.updateSubwidgets(widget, parentwidget, subwidgets)
            if hasattr(widget, 'objectName') and widget.objectName() and widget.objectName() in subwidgets:
                widget.setDisabled(not parentwidget.isChecked())

    def addBasicTab(self):
        config = self.config
        playerpaths = self.playerpaths
        resourcespath = self.resourcespath
        error = self.error
        if self.datacleared == True:
            error = constants.ERROR_MESSAGE_MARKER + "{}".format(getMessage("gui-data-cleared-notification"))
        if config['host'] == None:
            host = ""
        elif ":" in config['host']:
            host = config['host']
        else:
            host = config['host'] + ":" + str(config['port'])

        self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("connection-group-title"))
        self.hostTextbox = QLineEdit(host, self)
        self.hostLabel = QLabel(getMessage("host-label"), self)
        self.usernameTextbox = QLineEdit(self)
        self.usernameTextbox.setObjectName("name")
        self.serverpassLabel = QLabel(getMessage("password-label"), self)
        self.defaultroomTextbox = QLineEdit(self)
        self.usernameLabel = QLabel(getMessage("name-label"), self)
        self.serverpassTextbox = QLineEdit(self)
        self.defaultroomLabel = QLabel(getMessage("room-label"), self)

        self.hostLabel.setObjectName("host")
        self.hostTextbox.setObjectName(constants.LOAD_SAVE_MANUALLY_MARKER + "host")
        self.usernameLabel.setObjectName("name")
        self.usernameTextbox.setObjectName("name")
        self.serverpassLabel.setObjectName("password")
        self.serverpassTextbox.setObjectName("password")
        self.defaultroomLabel.setObjectName("room")
        self.defaultroomTextbox.setObjectName("room")

        self.connectionSettingsLayout = QtGui.QGridLayout()
        self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0)
        self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1)
        self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0)
        self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1)
        self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0)
        self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1)
        self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0)
        self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1)
        self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout)

        self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("media-setting-title"))
        self.executableiconImage = QtGui.QImage()
        self.executableiconLabel = QLabel(self)
        self.executableiconLabel.setMinimumWidth(16)
        self.executablepathCombobox = QtGui.QComboBox(self)
        self.executablepathCombobox.setEditable(True)
        self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon)
        self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths))
        self.executablepathCombobox.setFixedWidth(165)
        self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon)

        self.executablepathLabel = QLabel(getMessage("executable-path-label"), self)
        self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("browse-label"))
        self.executablebrowseButton.clicked.connect(self.browsePlayerpath)
        self.mediapathTextbox = QLineEdit(config['file'], self)
        self.mediapathLabel = QLabel(getMessage("media-path-label"), self)
        self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("browse-label"))
        self.mediabrowseButton.clicked.connect(self.browseMediapath)

        self.executablepathLabel.setObjectName("executable-path")
        self.executablepathCombobox.setObjectName("executable-path")
        self.mediapathLabel.setObjectName("media-path")
        self.mediapathTextbox.setObjectName(constants.LOAD_SAVE_MANUALLY_MARKER + "media-path")

        self.mediaplayerSettingsLayout = QtGui.QGridLayout()
        self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0)
        self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1)
        self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2)
        self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2)
        self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3)
        self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout)

        self.showmoreCheckbox = QCheckBox(getMessage("more-title"))
        self.showmoreCheckbox.setObjectName(constants.LOAD_SAVE_MANUALLY_MARKER + "more")

        self.basicOptionsFrame = QtGui.QFrame()
        self.basicOptionsLayout = QtGui.QVBoxLayout()
        if error:
            self.errorLabel = QLabel(self)
            if error[:1] != constants.ERROR_MESSAGE_MARKER:
                self.errorLabel.setStyleSheet(constants.STYLE_ERRORLABEL)
            else:
                error = error[1:]
                self.errorLabel.setStyleSheet(constants.STYLE_SUCCESSLABEL)
            self.errorLabel.setText(error)
            self.errorLabel.setAlignment(Qt.AlignCenter)

            self.basicOptionsLayout.addWidget(self.errorLabel, 0, 0)
        self.basicOptionsLayout.addWidget(self.connectionSettingsGroup)
        self.basicOptionsLayout.addSpacing(12)
        self.basicOptionsLayout.addWidget(self.mediaplayerSettingsGroup)

        self.basicOptionsFrame.setLayout(self.basicOptionsLayout)
        self.stackedLayout.addWidget(self.basicOptionsFrame)

    def addSyncTab(self):
        self.syncSettingsFrame = QtGui.QFrame()
        self.syncSettingsLayout = QtGui.QVBoxLayout()

        self.desyncSettingsGroup = QtGui.QGroupBox("If others are lagging behind...")
        self.desyncOptionsFrame = QtGui.QFrame()
        self.desyncSettingsOptionsLayout = QtGui.QHBoxLayout()
        config = self.config

        self.slowdownCheckbox = QCheckBox(getMessage("slowondesync-label"))
        self.slowdownCheckbox.setObjectName("slowOnDesync")
        self.rewindCheckbox = QCheckBox(getMessage("rewindondesync-label"))
        self.rewindCheckbox.setObjectName("rewindOnDesync")

        self.spaceLabel = QLabel()
        self.spaceLabel.setFixedHeight(5)

        self.desyncSettingsLayout = QtGui.QGridLayout()
        self.desyncSettingsLayout.setSpacing(2)
        self.desyncFrame = QtGui.QFrame()
        self.desyncFrame.setLineWidth(0)
        self.desyncFrame.setMidLineWidth(0)

        self.slowdownThresholdLabel = QLabel(getMessage("slowdown-threshold-label"), self)
        self.slowdownThresholdLabel.setStyleSheet(constants.STYLE_SUBLABEL.format(self.posixresourcespath + "bullet_black.png"))

        self.slowdownThresholdSpinbox = QDoubleSpinBox()
        try:
            slowdownThreshold = float(config['slowdownThreshold'])
            self.slowdownThresholdSpinbox.setValue(slowdownThreshold)
            if slowdownThreshold < constants.MINIMUM_SLOWDOWN_THRESHOLD:
                constants.MINIMUM_SLOWDOWN_THRESHOLD = slowdownThreshold
        except ValueError:
            self.slowdownThresholdSpinbox.setValue(constants.DEFAULT_SLOWDOWN_KICKIN_THRESHOLD)
        self.slowdownThresholdSpinbox.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        self.slowdownThresholdSpinbox.setMinimum(constants.MINIMUM_SLOWDOWN_THRESHOLD)
        self.slowdownThresholdSpinbox.setSingleStep(0.1)
        self.slowdownThresholdSpinbox.setSuffix(getMessage("seconds-suffix"))
        self.slowdownThresholdSpinbox.adjustSize()

        self.rewindThresholdLabel = QLabel(getMessage("rewind-threshold-label"), self)
        self.rewindThresholdLabel.setStyleSheet(constants.STYLE_SUBLABEL.format(self.posixresourcespath + "bullet_black.png"))
        self.rewindThresholdSpinbox = QDoubleSpinBox()
        try:
            rewindThreshold = float(config['rewindThreshold'])
            self.rewindThresholdSpinbox.setValue(rewindThreshold)
            if rewindThreshold < constants.MINIMUM_REWIND_THRESHOLD:
                constants.MINIMUM_REWIND_THRESHOLD = rewindThreshold
        except ValueError:
            self.rewindThresholdSpinbox.setValue(constants.DEFAULT_REWIND_THRESHOLD)
        self.rewindThresholdSpinbox.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        self.rewindThresholdSpinbox.setMinimum(constants.MINIMUM_REWIND_THRESHOLD)
        self.rewindThresholdSpinbox.setSingleStep(0.1)
        self.rewindThresholdSpinbox.setSuffix(getMessage("seconds-suffix"))
        self.rewindThresholdSpinbox.adjustSize()

        self.slowdownThresholdLabel.setObjectName("slowdown-threshold")
        self.slowdownThresholdSpinbox.setObjectName("slowdown-threshold")
        self.rewindThresholdLabel.setObjectName("rewind-threshold")
        self.rewindThresholdSpinbox.setObjectName("rewind-threshold")

        self.desyncSettingsLayout.addWidget(self.slowdownCheckbox, 0, 0, 1, 2, Qt.AlignLeft)
        self.desyncSettingsLayout.addWidget(self.slowdownThresholdLabel, 1, 0, 1, 1, Qt.AlignLeft)
        self.desyncSettingsLayout.addWidget(self.slowdownThresholdSpinbox, 1, 1, 1, 1, Qt.AlignLeft)
        self.desyncSettingsLayout.addWidget(self.spaceLabel, 2, 0,1,2, Qt.AlignLeft)
        self.desyncSettingsLayout.addWidget(self.rewindCheckbox, 3, 0,1,2, Qt.AlignLeft)
        self.desyncSettingsLayout.addWidget(self.rewindThresholdLabel, 4, 0, 1, 1, Qt.AlignLeft)
        self.desyncSettingsLayout.addWidget(self.rewindThresholdSpinbox, 4, 1, Qt.AlignLeft)

        self.subitems['slowOnDesync'] = ["slowdown-threshold"]
        self.subitems['rewindOnDesync'] = ["rewind-threshold"]

        self.desyncSettingsLayout.setAlignment(Qt.AlignLeft)
        self.desyncSettingsGroup.setLayout(self.desyncSettingsLayout)
        self.desyncSettingsOptionsLayout.addWidget(self.desyncFrame)
        self.syncSettingsLayout.addWidget(self.desyncSettingsGroup)
        self.desyncFrame.setLayout(self.syncSettingsLayout)

        self.othersyncSettingsGroup = QtGui.QGroupBox("Other sync options")
        self.othersyncOptionsFrame = QtGui.QFrame()
        self.othersyncSettingsLayout = QtGui.QGridLayout()


        self.dontslowwithmeCheckbox = QCheckBox(getMessage("dontslowdownwithme-label"))
        self.pauseonleaveCheckbox = QCheckBox(getMessage("pauseonleave-label"))
        self.othersyncSettingsLayout.addWidget(self.dontslowwithmeCheckbox)
        self.othersyncSettingsLayout.addWidget(self.pauseonleaveCheckbox)
        self.dontslowwithmeCheckbox.setObjectName("dontSlowDownWithMe")
        self.pauseonleaveCheckbox.setObjectName("pauseOnLeave")

        self.othersyncSettingsGroup.setLayout(self.othersyncSettingsLayout)
        self.syncSettingsLayout.addWidget(self.othersyncSettingsGroup)

        self.syncSettingsFrame.setLayout(self.syncSettingsLayout)
        self.desyncSettingsGroup.setMaximumHeight(self.desyncSettingsGroup.minimumSizeHint().height())
        self.syncSettingsLayout.setAlignment(Qt.AlignTop)
        self.stackedLayout.addWidget(self.syncSettingsFrame)

    def addMessageTab(self):
        self.messageFrame = QtGui.QFrame()
        self.messageLayout = QtGui.QVBoxLayout()

        # OSD
        self.osdSettingsGroup = QtGui.QGroupBox("On-screen Display settings")
        self.osdSettingsLayout = QtGui.QVBoxLayout()
        self.osdSettingsFrame = QtGui.QFrame()

        self.showOSDCheckbox = QCheckBox(getMessage("showosd-label"))
        self.showOSDCheckbox.setObjectName("showOSD")
        self.osdSettingsLayout.addWidget(self.showOSDCheckbox)

        self.showSameRoomOSDCheckbox = QCheckBox(getMessage("showsameroomosd-label"))
        self.showSameRoomOSDCheckbox.setObjectName("showSameRoomOSD")
        self.showSameRoomOSDCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "bullet_black.png"))
        self.osdSettingsLayout.addWidget(self.showSameRoomOSDCheckbox)

        self.showDifferentRoomOSDCheckbox = QCheckBox(getMessage("showdifferentroomosd-label"))
        self.showDifferentRoomOSDCheckbox.setObjectName("showDifferentRoomOSD")
        self.showDifferentRoomOSDCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "bullet_black.png"))
        self.osdSettingsLayout.addWidget(self.showDifferentRoomOSDCheckbox)

        self.slowdownOSDCheckbox = QCheckBox(getMessage("showslowdownosd-label"))
        self.slowdownOSDCheckbox.setObjectName("showSlowdownOSD")
        self.slowdownOSDCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "bullet_black.png"))
        self.osdSettingsLayout.addWidget(self.slowdownOSDCheckbox)

        self.showOSDWarningsCheckbox = QCheckBox(getMessage("showosdwarnings-label"))
        self.showOSDWarningsCheckbox.setObjectName("showOSDWarnings")
        self.showOSDWarningsCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "bullet_black.png"))
        self.osdSettingsLayout.addWidget(self.showOSDWarningsCheckbox)

        self.subitems['showOSD'] = ["showSameRoomOSD", "showDifferentRoomOSD", "showSlowdownOSD", "showOSDWarnings"]

        self.osdSettingsGroup.setLayout(self.osdSettingsLayout)
        self.osdSettingsLayout.setAlignment(Qt.AlignTop)
        self.messageLayout.addWidget(self.osdSettingsGroup)

        # Other display

        self.displaySettingsGroup = QtGui.QGroupBox("Other display settings")
        self.displaySettingsLayout = QtGui.QVBoxLayout()
        self.displaySettingsFrame = QtGui.QFrame()

        self.showDurationNotificationCheckbox = QCheckBox(getMessage("showdurationnotification-label"))
        self.showDurationNotificationCheckbox.setObjectName("showDurationNotification")
        self.displaySettingsLayout.addWidget(self.showDurationNotificationCheckbox)

        self.showcontactinfoCheckbox = QCheckBox(getMessage("showcontactinfo-label"))
        self.showcontactinfoCheckbox.setObjectName("showContactInfo")
        self.displaySettingsLayout.addWidget(self.showcontactinfoCheckbox)

        self.showButtonLabelsCheckbox = QCheckBox(getMessage("showbuttonlabels-label"))
        self.showButtonLabelsCheckbox.setObjectName("showButtonLabels")
        self.displaySettingsLayout.addWidget(self.showButtonLabelsCheckbox)

        self.showTooltipsCheckbox = QCheckBox(getMessage("showtooltips-label"))
        self.showTooltipsCheckbox.setObjectName("showTooltips")
        self.displaySettingsLayout.addWidget(self.showTooltipsCheckbox)


        self.displaySettingsGroup.setLayout(self.displaySettingsLayout)
        self.displaySettingsLayout.setAlignment(Qt.AlignTop)
        self.messageLayout.addWidget(self.displaySettingsGroup)

        # messageFrame
        self.messageFrame.setLayout(self.messageLayout)
        self.stackedLayout.addWidget(self.messageFrame)

    def addPrivacyTab(self):
        self.privacySettingsGroup = QtGui.QGroupBox("Privacy settings")
        self.privacySettingsLayout = QtGui.QVBoxLayout()
        self.privacySettingsFrame = QtGui.QFrame()
        self.privacyFrame = QtGui.QFrame()
        self.privacyLayout = QtGui.QGridLayout()

        self.filenameprivacyLabel = QLabel(getMessage("filename-privacy-label"), self)
        self.filenameprivacyButtonGroup = QButtonGroup()
        self.filenameprivacySendRawOption = QRadioButton(getMessage("privacy-sendraw-option"))
        self.filenameprivacySendHashedOption = QRadioButton(getMessage("privacy-sendhashed-option"))
        self.filenameprivacyDontSendOption = QRadioButton(getMessage("privacy-dontsend-option"))
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption)

        self.filesizeprivacyLabel = QLabel(getMessage("filesize-privacy-label"), self)
        self.filesizeprivacyButtonGroup = QButtonGroup()
        self.filesizeprivacySendRawOption = QRadioButton(getMessage("privacy-sendraw-option"))
        self.filesizeprivacySendHashedOption = QRadioButton(getMessage("privacy-sendhashed-option"))
        self.filesizeprivacyDontSendOption = QRadioButton(getMessage("privacy-dontsend-option"))
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption)

        self.filenameprivacyLabel.setObjectName("filename-privacy")
        self.filenameprivacySendRawOption.setObjectName("privacy-sendraw" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDRAW_MODE)
        self.filenameprivacySendHashedOption.setObjectName("privacy-sendhashed" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDHASHED_MODE)
        self.filenameprivacyDontSendOption.setObjectName("privacy-dontsend" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_DONTSEND_MODE)
        self.filesizeprivacyLabel.setObjectName("filesize-privacy")
        self.filesizeprivacySendRawOption.setObjectName("privacy-sendraw" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDRAW_MODE)
        self.filesizeprivacySendHashedOption.setObjectName("privacy-sendhashed" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDHASHED_MODE)
        self.filesizeprivacyDontSendOption.setObjectName("privacy-dontsend" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_DONTSEND_MODE)

        self.privacyLayout.addWidget(self.filenameprivacyLabel, 1, 0)
        self.privacyLayout.addWidget(self.filenameprivacySendRawOption, 1, 1, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filenameprivacySendHashedOption, 1, 2, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filenameprivacyDontSendOption, 1, 3, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filesizeprivacyLabel, 2, 0)
        self.privacyLayout.addWidget(self.filesizeprivacySendRawOption, 2, 1, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filesizeprivacySendHashedOption, 2, 2, Qt.AlignLeft)
        self.privacyLayout.addWidget(self.filesizeprivacyDontSendOption, 2, 3, Qt.AlignLeft)

        self.privacyFrame.setLayout(self.privacyLayout)
        self.privacySettingsGroup.setLayout(self.privacyLayout)
        self.privacySettingsGroup.setMaximumHeight(self.privacySettingsGroup.minimumSizeHint().height())
        self.privacySettingsLayout.addWidget(self.privacySettingsGroup)
        self.privacySettingsLayout.setAlignment(Qt.AlignTop)
        self.privacyFrame.setLayout(self.privacySettingsLayout)
        self.stackedLayout.addWidget(self.privacyFrame)

    def addBottomLayout(self):
        config = self.config
        resourcespath = self.resourcespath

        self.bottomButtonFrame = QtGui.QFrame()
        self.bottomButtonLayout = QtGui.QHBoxLayout()
        self.helpButton = QtGui.QPushButton(QtGui.QIcon(self.resourcespath + 'help.png'), getMessage("help-label"))
        self.helpButton.setObjectName("help")
        self.helpButton.setMaximumSize(self.helpButton.sizeHint())
        self.helpButton.pressed.connect(self.openHelp)

        self.resetButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'cog_delete.png'),getMessage("reset-label"))
        self.resetButton.setMaximumSize(self.resetButton.sizeHint())
        self.resetButton.setObjectName("reset")
        self.resetButton.pressed.connect(self.resetSettings)

        self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'), getMessage("storeandrun-label"))
        self.runButton.pressed.connect(self._saveDataAndLeave)
        self.bottomButtonLayout.addWidget(self.helpButton)
        self.bottomButtonLayout.addWidget(self.resetButton)
        self.bottomButtonLayout.addWidget(self.runButton)
        self.bottomButtonFrame.setLayout(self.bottomButtonLayout)
        if config['noStore'] == True:
            self.runButton.setText(getMessage("run-label"))
        self.bottomButtonLayout.setContentsMargins(5,0,5,0)
        self.mainLayout.addWidget(self.bottomButtonFrame, 1, 0, 1, 2)

        self.bottomCheckboxFrame = QtGui.QFrame()
        self.bottomCheckboxFrame.setContentsMargins(0,0,0,0)
        self.bottomCheckboxLayout = QtGui.QGridLayout()
        self.alwaysshowCheckbox = QCheckBox(getMessage("forceguiprompt-label"))

        self.nostoreCheckbox = QCheckBox(getMessage("nostore-label"))
        self.bottomCheckboxLayout.addWidget(self.showmoreCheckbox)
        self.bottomCheckboxLayout.addWidget(self.alwaysshowCheckbox, 0, 1, Qt.AlignLeft)
        self.bottomCheckboxLayout.addWidget(self.nostoreCheckbox, 0, 2, Qt.AlignRight)
        self.alwaysshowCheckbox.setObjectName(constants.INVERTED_STATE_MARKER + "forceGuiPrompt")
        self.nostoreCheckbox.setObjectName("noStore")
        self.nostoreCheckbox.toggled.connect(self.runButtonTextUpdate)
        self.bottomCheckboxFrame.setLayout(self.bottomCheckboxLayout)
        self.mainLayout.addWidget(self.bottomCheckboxFrame, 2, 0, 1, 2)

    def tabList(self):
        self.tabListLayout = QtGui.QHBoxLayout()
        self.tabListFrame = QtGui.QFrame()
        self.tabListWidget = QtGui.QListWidget()
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "house.png"),getMessage("basics-label")))
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "film_link.png"),getMessage("sync-label")))
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "comments.png"),getMessage("messages-label")))
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "eye.png"),getMessage("privacy-label")))
        self.tabListLayout.addWidget(self.tabListWidget)
        self.tabListFrame.setLayout(self.tabListLayout)
        self.tabListFrame.setFixedWidth(self.tabListFrame.minimumSizeHint().width())
        self.tabListWidget.setStyleSheet(constants.STYLE_TABLIST)

        self.tabListWidget.currentItemChanged.connect(self.tabChange)
        self.tabListWidget.itemClicked.connect(self.tabChange)
        self.tabListWidget.itemPressed.connect(self.tabChange)
        self.mainLayout.addWidget(self.tabListFrame, 0, 0, 1, 1)

    def ensureTabListIsVisible(self):
        self.stackedFrame.setFixedWidth(self.stackedFrame.width())
        while self.tabListWidget.horizontalScrollBar().isVisible() and self.tabListFrame.width() < 200:
            self.tabListFrame.setFixedWidth(self.tabListFrame.width()+1)

    def tabChange(self):
        self.setFocus()
        self.stackedLayout.setCurrentIndex(self.tabListWidget.currentRow())

    def resetSettings(self):
        self.clearGUIData(leaveMore=True)
        self.config['resetConfig'] = True
        self.pressedclosebutton = True
        self.close()

    def showEvent(self, *args, **kwargs):
        self.ensureTabListIsVisible()
        self.setFixedWidth(self.minimumSizeHint().width())
        self.executablepathCombobox.setFixedWidth(self.mediapathTextbox.width())

    def clearGUIData(self, leaveMore=False):
        settings = QSettings("Syncplay", "PlayerList")
        settings.clear()
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.clear()
        settings = QSettings("Syncplay", "MainWindow")
        settings.clear()
        if not leaveMore:
            settings = QSettings("Syncplay", "MoreSettings")
            settings.clear()
        self.datacleared = True

    def __init__(self, config, playerpaths, error, defaultConfig):

        from syncplay import utils
        self.config = config
        self.defaultConfig = defaultConfig
        self.playerpaths = playerpaths
        self.datacleared = False
        self.config['resetConfig'] = False
        self.subitems = {}

        if self.config['clearGUIData'] == True:
            self.config['clearGUIData'] = False
            self.clearGUIData()

        self.QtGui = QtGui
        self.error = error
        if sys.platform.startswith('win'):
            resourcespath = utils.findWorkingDir() + "\\resources\\"
        else:
            resourcespath = utils.findWorkingDir() + "/resources/"
        self.posixresourcespath = utils.findWorkingDir().replace("\\","/") + "/resources/"
        self.resourcespath = resourcespath

        super(ConfigDialog, self).__init__()

        self.setWindowTitle(getMessage("config-window-title"))
        self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
        self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png"))

        self.stackedLayout = QtGui.QStackedLayout()
        self.stackedFrame = QtGui.QFrame()
        self.stackedFrame.setLayout(self.stackedLayout)

        self.mainLayout = QtGui.QGridLayout()
        self.mainLayout.setSpacing(0)
        self.mainLayout.setContentsMargins(0,0,0,0)

        self.addBasicTab()
        self.addSyncTab()
        self.addMessageTab()
        self.addPrivacyTab()
        self.tabList()

        self.mainLayout.addWidget(self.stackedFrame, 0, 1)
        self.addBottomLayout()


        if self.getMoreState() == False:
            self.tabListFrame.hide()
            self.nostoreCheckbox.hide()
            self.alwaysshowCheckbox.hide()
            self.resetButton.hide()
        else:
            self.showmoreCheckbox.setChecked(True)
            self.tabListWidget.setCurrentRow(0)

        self.showmoreCheckbox.toggled.connect(self.moreToggled)

        self.setLayout(self.mainLayout)
        self.runButton.setFocus()
        self.setFixedSize(self.sizeHint())
        self.setAcceptDrops(True)

        if constants.SHOW_TOOLTIPS:
            self.processWidget(self, lambda w: self.loadTooltips(w))
        self.processWidget(self, lambda w: self.loadValues(w))
        self.processWidget(self, lambda w: self.connectChildren(w))
Exemple #34
0
class ExportOrthoWin(QDialog
                     ):  #новый класс как приложение с интерфейсом и кодом
    def __init__(self, parent):
        #_____________Пременные уровня класса___________
        self.OUT_dir = ''  #выходная дирректория
        self.orthoBounds = []
        # ВЫХОДНАЯ ПРОЕКЦИЯ по умолчанию
        #out_crs='PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        self.out_crs = PhotoScan.CoordinateSystem(
            'PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        )
        #out_crs=PhotoScan.CoordinateSystem('PROJCS["WGS 84 / UTM zone 38N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",45],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32638"]]')
        self.crsShapes = PhotoScan.CoordinateSystem(
            'PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        )
        self.DATA_OK = 0
        #print ('orthoBounds=',len(self.orthoBounds))
        #формат массива:0-имя ортофото, 1-Xmin, 2-Ymin, 3-sizeX, 4-sizeY, 5-ID полигона
        #__________________________________________________

        QDialog.__init__(self, parent)
        self.setWindowTitle("Экспорт Орто по разграфке")  #Заголвок окна
        self.resize(500, 250)  #размер окна
        self.txt_comment = QLabel(
            "	Модуль экспортирует ортофото и DEM из фотоскана по нарезке. \
Нарезка в текстовом файле: название листа, координаты нижнего левого угла, размеры. \n	Проекция нарезки должна совпадать с проекцией выходного ортофотоплана.\
Листы делятся по нарезке, а внутри нарезки по блокам, размеры задаются. ФОРМАТ JPG \n	При импорте SHP должно быть текстовое поле NAME \n \
Адрес сервера: " + ServerIP +
            " меняем в теле программы. Ваша версия фотоскана: " + PH_version +
            " \n")
        self.txt_comment.setWordWrap(True)
        self.now_prj = QLabel(str(self.out_crs))
        self.select_prj = QPushButton("Выберете проекцию")  #(" открыть ")
        self.select_prj.setFixedSize(170, 26)

        self.TXT_dif_pix = QLabel("<B>Размер пикселя: </B>")
        self.TXT_dif_pix.setFixedSize(170, 26)
        self.dif_pix = QLineEdit()
        self.dif_pix.setText('0.1')  # Задает размер пикселя по умолчанию
        self.dif_pix.setFixedSize(100, 26)

        items_bloksize = ('5000', '8192', '10000', '15000', '20000', '25000',
                          '29999', 'Full')  # список с размерами тайлов
        #items_bloksize = {5000:5000, 8192:8192, 10000:10000, 15000:15000, 20000:20000, 25000:25000, 29999:29999}
        self.TXT_block_size = QLabel("<B>Размер блока: </B>", )
        self.TXT_block_size.setFixedSize(170, 26)
        self.block_size = QComboBox()
        self.block_size.setFixedSize(100, 26)
        self.block_size.addItems(items_bloksize)
        self.block_size.setCurrentIndex(
            1)  #Устанавливает по умолчанию второе значение из списка - 8192

        self.TXT_SHPname = QLabel("Файл разграфки SHP (NAME,poligons)")
        self.SHPname = QPushButton(
            "Выберете файл разграфки SHP")  #(" открыть ")
        self.SHPname.setFixedSize(170, 26)

        self.TXT_filename = QLabel(
            "Файл разграфки TXT(имя; X0; Y0; sizeX; SizeY)")
        self.filename = QPushButton("Выберете Файл разграфки")  #(" открыть ")
        self.filename.setFixedSize(170, 26)

        self.TXT_CheckOrthoDem = QLabel("Вид выходной продукции")
        self.TXT_CheckOrthoDem.setFixedSize(170, 26)
        self.CheckOrtho_Radio = QRadioButton("Ортофото")
        self.CheckOrtho_Radio.setChecked(True)
        self.CheckDem_Radio = QRadioButton("ДЕМ")

        self.TXT_OUTFOLDER = QLabel("Выходная дирректория")
        self.OUTFOLDER = QPushButton("Выберете дирректорию")  #(" открыть ")
        self.OUTFOLDER.setFixedSize(170, 26)

        items_format = (
            'JPG', 'TIF'
        )  # список форматов, ПРИ выборе ДЕМ будет выбран второй формат - внимательно при изменении списка!!!
        self.file_format = QComboBox()
        self.file_format.setFixedSize(50, 26)
        self.file_format.addItems(items_format)
        self.file_format.setCurrentIndex(
            0)  #Устанавливает по умолчанию первое значение

        self.TXT_checkExportOrtho = QLabel("Построить ортофото:")  # Ортофото
        self.TXT_checkExportOrtho.setFixedSize(170, 26)
        self.checkExportOrtho = QCheckBox()
        self.checkExportOrtho.setChecked(False)

        self.GoGo = QPushButton("Экспорт локально")  #(" Экспорт локально ")
        self.GoGo.setFixedSize(170, 26)
        self.GoGo.setDisabled(True)

        self.GoGoNet = QPushButton("Экспорт по сети")  #(" Экспорт по сети ")
        self.GoGoNet.setFixedSize(170, 26)
        self.GoGoNet.setDisabled(True)

        hbox0 = QHBoxLayout()
        hbox0.addWidget(self.txt_comment, alignment=0)

        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.select_prj, alignment=0)
        hbox1.addWidget(self.now_prj, alignment=0)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.TXT_block_size, alignment=1)
        hbox2.addWidget(self.block_size, alignment=1)

        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.TXT_dif_pix, alignment=1)
        hbox3.addWidget(self.dif_pix, alignment=1)

        hbox4 = QHBoxLayout()
        #hbox4.addStretch(1)
        hbox4.addWidget(self.SHPname, alignment=0)
        hbox4.addWidget(self.TXT_SHPname, alignment=0)

        hbox5 = QHBoxLayout()
        #hbox5.addStretch(1)
        hbox5.addWidget(self.filename, alignment=0)
        hbox5.addWidget(self.TXT_filename, alignment=0)

        hbox51 = QHBoxLayout()
        hbox51.addWidget(self.TXT_CheckOrthoDem, alignment=0)
        hbox51.addWidget(self.CheckOrtho_Radio, alignment=0)
        hbox51.addWidget(self.CheckDem_Radio, alignment=0)

        hbox6 = QHBoxLayout()
        #hbox5.addStretch(1)
        hbox6.addWidget(self.OUTFOLDER, alignment=0)
        hbox6.addWidget(self.TXT_OUTFOLDER, alignment=0)
        hbox6.addWidget(self.file_format, alignment=0)

        hbox7 = QHBoxLayout()  #build ortho
        hbox7.addWidget(self.TXT_checkExportOrtho, alignment=0)
        hbox7.addWidget(self.checkExportOrtho, alignment=0)

        hbox8 = QHBoxLayout()
        hbox8.addWidget(self.GoGo, stretch=0, alignment=0)
        hbox8.addWidget(self.GoGoNet, stretch=0, alignment=0)

        vbox = QVBoxLayout()  #Определяем вбокс и забиваем его Нбоксами
        #vbox.addStretch(1)
        vbox.addLayout(hbox0)
        vbox.addLayout(hbox1)
        vbox.addLayout(hbox2)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        vbox.addLayout(hbox5)
        vbox.addLayout(hbox51)  #выбор, что строить орто или дем
        vbox.addLayout(hbox6)
        #Функция построения ортофото спрятана, поскольку работает не стабильно и построение ортофото для каждого листа в сумме занимает очень много времени,
        #гораздо больше, чем один раз построить ортофото для всех
        #vbox.addLayout(hbox7) #build ortho
        vbox.addLayout(hbox8)

        self.setLayout(vbox)

        self.select_prj.clicked.connect(self.set_projection)
        self.SHPname.clicked.connect(self.input_razgr_SHPname)
        self.filename.clicked.connect(self.input_razgr_name)
        self.OUTFOLDER.clicked.connect(self.input_out_dir)
        self.GoGo.clicked.connect(self.ortho_local)
        self.GoGoNet.clicked.connect(self.ortho_net)
        #Организация блокировки интерфейса для радио кнопок
        self.CheckOrtho_Radio.clicked.connect(self.CheckOrtho_Radio_DO)
        self.CheckDem_Radio.clicked.connect(self.CheckDem_Radio_DO)
        #____________
        self.checkExportOrtho.clicked.connect(
            self.PrintChkStat)  #Функция для проверки работы чека
        #self.WindowContextHelpButtonHint.clicked.connect(self.prog_hint)
        #self.WindowTitleHint.clicked.connect(self.prog_hint)

        self.exec()
        #____________________________________________________________________________

    def PrintChkStat(
        self
    ):  #Эта функция работает в принте с подстановкой и получение значения чека
        if self.checkExportOrtho.isChecked() == True:
            stat = 'ДА'
        else:
            stat = 'НЕТ'
        print('Строить орто %s здесь' % stat)

    def CheckOrtho_Radio_DO(
            self):  #Если выбран Ортоф - формат Джипег и свободен!!!
        print("Орто")
        self.file_format.setCurrentIndex(0)
        self.file_format.setDisabled(False)

    def CheckDem_Radio_DO(
            self):  #Если выбран ДЕМ - формат тифф и блокируется!!!
        print("DEM")
        self.file_format.setCurrentIndex(1)
        self.file_format.setDisabled(True)

    def ortho_local(self):
        self.export_ortho('local')

    def ortho_net(self):
        self.export_ortho('net')

    def prog_hint(self):
        print("OK")

    def unlock_export(self, sel):
        #Переменная нужна для разблокирования кнопки Экспорт. Два критических параметра:Файл разграфки и выходная дирректория, каждый добавляет по еденице.
        #Sel=5 блокирует кнопки при запуске сетевой обработки
        '''
		DATA_OK логика работы: Для экспорта нужно задать выходную директорию и файл разграфки, текстовый или векторный
		при запуске сетевой обработки кнопки опять блокируются
		DATA_OK меняет только эта процедура!!!
		
		0-ничего не задано экспорт заблокирован
		1-выбран  файл разграфки проверяем выбран ли путь, да, разблокируем 3
		2-выбран путь проверяем выбран ли файл разграфки, да, разблокируем 3
		'''
        if sel == 5 and self.DATA_OK == 1:
            self.DATA_OK = 0
            self.GoGo.setDisabled(True)
            self.GoGoNet.setDisabled(True)
        if sel == 5 and self.DATA_OK == 2:
            self.DATA_OK = 2
            self.GoGo.setDisabled(True)
            self.GoGoNet.setDisabled(True)
        if sel == 5 and self.DATA_OK == 3:
            self.DATA_OK = 2
            self.GoGo.setDisabled(True)
            self.GoGoNet.setDisabled(True)
        if self.DATA_OK == 1 and sel == 2: self.DATA_OK = 3
        if self.DATA_OK == 2 and sel == 1: self.DATA_OK = 3
        if self.DATA_OK == 0 and sel != 5: self.DATA_OK = sel
        if self.DATA_OK == 3 and sel != 5:
            self.GoGo.setDisabled(False)
            self.GoGoNet.setDisabled(False)
            print('unlock')
        print(sel, self.DATA_OK)

    def OrthoBoundCalc(self, Xn, Yn, XS,
                       YS):  # изменить под сетевую обработку с тайлами
        DifPix = float(self.dif_pix.text())
        ''' Округление начала Если надо
		Xnround=floor(Xn/DifPix)*DifPix #
		Ynround=floor(Yn/DifPix)*DifPix
		'''
        '''
		if self.block_size.currentText()=='Full' or CommandStack==5 : #Экспорт целикового фрагмента
			print('границы целиковые')
			Xnround=Xn
			Ynround=Yn-DifPix
			XSround=ceil(XS/DifPix+1)*DifPix #Границы округляем в большую сторону и расширяем на пиксель
			YSround=ceil(YS/DifPix+1)*DifPix
			XSround=Xnround+XSround
			YSround=Ynround+YSround
			
		elif CommandStack==1 and self.block_size.currentText()!='Full': # Экспорт по тайлам
			print("Границы со сдвигом")
			BlockSize=float(self.block_size.currentText())
			Xnround=Xn
			Ynround=Yn #-DifPix
			XSround=ceil(XS/DifPix+1)*DifPix #Границы округляем в большую сторону и расширяем на пиксель
			YSround=ceil(YS/DifPix+1)*DifPix
			YBlockSize=BlockSize*DifPix 
			TileShift=YBlockSize-YSround
			Ynround=Ynround+TileShift
			XSround=Xnround+XSround
			YSround=Ynround+YSround+TileShift
		else:
			Print("Bound version error, OrthoBoundCalc")
			pass
			'''
        Xnround = Xn
        Ynround = Yn - DifPix
        XSround = ceil(
            XS / DifPix + 1
        ) * DifPix  #Границы округляем в большую сторону и расширяем на пиксель
        YSround = ceil(YS / DifPix + 1) * DifPix
        XSround = Xnround + XSround
        YSround = Ynround + YSround
        point = [
        ]  #"Эта конструкция нужна для поиска максимальных координат квадрата при переходе из системы в систему
        print("точки")
        point.append(PhotoScan.Vector((Xnround, Ynround)))
        point.append(PhotoScan.Vector((Xnround, YSround)))
        point.append(PhotoScan.Vector((XSround, YSround)))
        point.append(PhotoScan.Vector((XSround, Ynround)))
        print("точки2")
        point_trans = []
        point_trans.append(
            PhotoScan.CoordinateSystem.transform(point[0], self.crsShapes,
                                                 self.out_crs))
        point_trans.append(
            PhotoScan.CoordinateSystem.transform(point[1], self.crsShapes,
                                                 self.out_crs))
        point_trans.append(
            PhotoScan.CoordinateSystem.transform(point[2], self.crsShapes,
                                                 self.out_crs))
        point_trans.append(
            PhotoScan.CoordinateSystem.transform(point[3], self.crsShapes,
                                                 self.out_crs))
        x = []
        y = []
        for i in range(4):
            print(i)
            x.append(point_trans[i][0])
            y.append(point_trans[i][1])
        xMin = min(x)
        yMin = min(y)
        xMax = max(x)
        yMax = max(y)
        #OrthoBound=(Xnround,Ynround,XSround,YSround)
        OrthoBound = (Xnround, Ynround, XSround, YSround)
        print(OrthoBound)
        OrthoBound = (xMin, yMin, xMax, yMax)
        print(OrthoBound)
        return OrthoBound

    def input_razgr_SHPname(self):
        #global listShapes
        SHPname = ''  #Векторный файл разграфки
        DataDir = os.path.dirname(
            __file__)  # Дирректория по умолчанию - дирректория скрипта!!
        shpfilename = QFileDialog.getOpenFileName(
            self, 'выберете векторный файл разграфки', DataDir,
            filter='*.shp')  #Координаты в выходной проекции
        #проверка  на пустоту
        if not shpfilename[0] == '':
            SHP_name = shpfilename[0]
        else:
            return
        sname = os.path.basename(SHP_name)
        file_sname = os.path.splitext(sname)[0]

        print('Путь до шейпа: ', SHP_name)
        print('Имя шейпа: ', file_sname)
        chunk.importShapes(SHP_name, True)  # Импорт шейпфайла с заменой
        shapes = chunk.shapes
        #Сделать проверку на ИМЯ ПОЛИГОНА
        #shapes=PhotoScan.app.document.chunk.shapes
        listShapes = shapes.items()  #Массив (список) шейпов в проекте
        self.crsShapes = shapes.crs  #Проекция шейпа
        print(self.crsShapes)
        PhotoScan.app.messageBox('Импортированы объекты: ' + str(shapes) +
                                 '\n Старые объекты удалены')

        #Получили список векторных объектов, загруженных в проект, теперь проходим по каждому объекту и определяем его минимум и максимум по коориднатам

        if len(listShapes) != 0:
            poligon_ID = 0
            self.orthoBounds = []
            for shape in listShapes:  # ЗДЕСЬ определяются координаты минимум и максимум в текущей проекции в другой все по другому - Могут быть дыры
                # в OrthoBoundCalc стоит заглушка - имщет максимальные коориднаты углов прямоугольника после перепроецирования - можно но не совсем корректно
                x = []
                y = []
                vertices = shape.vertices
                for vertex in vertices:
                    x.append(vertex[0])
                    y.append(vertex[1])

                # Если есть NAME - это будет имя, если нет - имя шейпа и номер фичи
                if str(shape.label) == '':
                    poligonName = str(file_sname) + '_' + str(poligon_ID)
                else:
                    poligonName = str(shape.label)
                xMin = min(x)
                yMin = min(y)
                xSize = max(x) - min(x)
                ySize = max(y) - min(y)
                element = [poligonName, xMin, yMin, xSize, ySize, poligon_ID]
                self.orthoBounds.append(
                    element)  #ЭТО МАССИВ с ГРАНИЦАМИ ОРТОФОТО
                #формат массива:0-имя ортофото, 1-Xmin, 2-Ymin, 3-sizeX, 4-sizeY
                poligon_ID += 1  #Увеличение на единицу
            print(len(self.orthoBounds), poligon_ID)
            if len(self.orthoBounds) != 0: self.unlock_export(1)
            self.TXT_SHPname.setText(str(sname))
            self.TXT_filename.setText(
                "Файл разграфки TXT(имя; X0; Y0; sizeX; SizeY)")
        else:
            PhotoScan.app.messageBox('Пустой SHP файл')
            self.unlock_export(5)
        print('orthoBounds=', len(self.orthoBounds))
        # Шейп засосали,  минимум максимум нашли, с обрезкой дальше разберемся
        #_____________________________________________________________________________

    def input_razgr_name(self):
        TXT_name = ''  #имя файла с разграфкой
        # КООРДИАНТЫ ДОЛЖНЫ БЫТЬ В ВЫХОДНОЙ ПРОЕКЦИИ!!!!!
        DataDir = os.path.dirname(
            __file__)  # Дирректория по умолчанию - дирректория скрипта!!
        textfilename = QFileDialog.getOpenFileName(
            self, 'выберете  файл разграфки', DataDir,
            filter='*.txt')  #Координаты в выходной проекции
        #проверка текстфайлнайм на пустоту
        if not textfilename[0] == '':
            with open(textfilename[0]) as f:
                for line in f:
                    znach = line.split(";")
                    try:
                        if not (isinstance(znach[0], str)):
                            PhotoScan.app.messageBox('Неверный форматS')
                            self.unlock_export(5)
                            return
                        if not (isinstance(float(znach[1]), (float, int))):
                            PhotoScan.app.messageBox('Неверный формат1i')
                            self.unlock_export(5)
                            return
                        if not (isinstance(float(znach[2]), (float, int))):
                            PhotoScan.app.messageBox('Неверный формат2i')
                            self.unlock_export(5)
                            return
                        if not (isinstance(float(znach[3]), (float, int))):
                            PhotoScan.app.messageBox('Неверный формат3i')
                            self.unlock_export(5)
                            return
                        if not (isinstance(float(znach[4]), (float, int))):
                            PhotoScan.app.messageBox('Неверный формат4i')
                            self.unlock_export(5)
                            return
                    except:
                        PhotoScan.app.messageBox('Неверный формат_;')
                        self.unlock_export(5)
                        return
        else:
            return
        if not (textfilename[0]
                == ''):  #Если все нормально заполняем orthoBounds
            TXT_name = textfilename
            self.orthoBounds = []
            with open(TXT_name[0]) as f:
                count = 0
                for line in f:
                    znach = line.split(";")
                    element = [
                        znach[0], znach[1], znach[2], znach[3], znach[4], count
                    ]
                    self.orthoBounds.append(
                        element)  #ЭТО МАССИВ с ГРАНИЦАМИ ОРТОФОТО
                    count += 1
            print('orthoBounds=', len(self.orthoBounds))
            self.unlock_export(
                1)  #разблокирует экспорт, если заданы разграфка и дирректория
            self.TXT_filename.setText(str(TXT_name[0]))
            self.TXT_SHPname.setText("Файл разграфки SHP (NAME,poligons)")

    def set_projection(self):
        self.out_crs = PhotoScan.app.getCoordinateSystem(
            'Система координат',
            self.out_crs)  #Специальная форма для задания системы координат
        self.now_prj.setText(str(self.out_crs))

    def input_out_dir(self):
        DataDir = os.path.dirname(__file__)
        outputdir = QFileDialog.getExistingDirectory(self,
                                                     'выберете дирректорию',
                                                     DataDir)
        if not outputdir == '':
            self.OUT_dir = outputdir
            self.TXT_OUTFOLDER.setText(str(self.OUT_dir))
            self.unlock_export(
                2)  #разблокирует экспорт, если заданы разграфка и дирректория
        else:
            return
        print('orthoBounds=', len(self.orthoBounds))

    def export_ortho(
        self, proc_type
    ):  # универсальная процедура экспорта для локлаьной и для сетевой обработки
        #global chunk
        ''' ЭТО ПРОВЕРКА ДЛЯ ПОСТРОЕНИЯ ОРТО ПЕРЕД РАБОТОЙ В ТЕКУЩЕЙ ВЕРСИИ ФУНКЦИЯ ОТКЛЮЧЕНА!!
		if self.checkExportOrtho.isChecked()==True:
			statOrthoBuild=True
		else:
			statOrthoBuild=False
		# 000000 Проверка на наличие ортофото или дем перед работой
		if (doc.chunk.orthomosaic==None and statOrthoBuild==False):
			PhotoScan.app.messageBox('Нет орто!!')
			return
		elif (doc.chunk.elevation==None and statOrthoBuild==True):
			PhotoScan.app.messageBox('Нет ДЕМ!!')
			return
		'''
        #Определение вида экспорта - орто или дем
        if self.CheckOrtho_Radio.isChecked() == True:
            ExportType = 'ORTHO'
        elif self.CheckDem_Radio.isChecked() == True:
            ExportType = 'DEM'
        else:
            AssertionError("Какой процесс экспорта?")

        #ПРОВЕРКИ НАЛИЧИЯ ДЕМ И ОРТО
        if (doc.chunk.orthomosaic == None and ExportType == 'ORTHO'):
            PhotoScan.app.messageBox('Нет орто!!')
            return
        elif (doc.chunk.elevation == None and ExportType == 'DEM'):
            PhotoScan.app.messageBox('Нет ДЕМ!!')
            return

        file_format = self.file_format.currentText()
        print('orthoBounds=', len(self.orthoBounds))
        task = []  #Это СПИСОК тасков
        DifPix = float(self.dif_pix.text())
        if self.block_size.currentText() == 'Full':
            BlockSize = 0
        else:
            BlockSize = int(self.block_size.currentText())

        # Цикл для запуска ортофото локально или для забивания стека на сеть из массива
        try:
            for cu_string in self.orthoBounds:
                OName = cu_string[0]
                XMLeft = float(cu_string[1])
                YMDown = float(cu_string[2])
                sizeXM = float(cu_string[3])
                sizeYM = float(cu_string[4])
                shapeNumber = int(cu_string[5])
                cu_Region = self.OrthoBoundCalc(
                    XMLeft, YMDown, sizeXM, sizeYM
                )  #Функция вычисления границ # изменить под сетевую обработку с тайлами
                if file_format == 'JPG' and ExportType == 'ORTHO':
                    fileoutname = self.OUT_dir + "\\ortho_" + OName + ".jpg"
                elif file_format == 'TIF' and ExportType == 'ORTHO':
                    fileoutname = self.OUT_dir + "\\ortho_" + OName + ".tif"
                elif file_format == 'TIF' and ExportType == 'DEM':
                    fileoutname = self.OUT_dir + "\\dem_" + OName + ".tif"
                else:
                    print("Формат файла?")

                if proc_type == 'local':  #КОММАНДЫ для локальной обработки
                    print('Обработка локально')
                    ''' ПОСТРОЕНИЕ ОРТОФОТО В ЭТОЙ ВЕРСИИ ОТКЛЮЧЕНО
					if statOrthoBuild==True: 
						#chunk.buildOrthomosaic(surface=PhotoScan.ElevationData, blending=PhotoScan.MosaicBlending, color_correction=False, projection=self.out_crs, region=cu_Region,dx=DifPix, dy=DifPix)
						chunk.buildOrthomosaic(surface=PhotoScan.ElevationData, blending=PhotoScan.MosaicBlending, projection=self.out_crs, region=cu_Region,dx=DifPix, dy=DifPix)
					'''

                    if CommandStack == 1 and ExportType == 'ORTHO':
                        if file_format == 'JPG':
                            chunk.exportOrthomosaic(fileoutname,
                                                    format="jpg",
                                                    projection=self.out_crs,
                                                    region=cu_Region,
                                                    dx=DifPix,
                                                    dy=DifPix,
                                                    blockw=BlockSize,
                                                    blockh=BlockSize,
                                                    write_kml=False,
                                                    write_world=True)
                        elif file_format == 'TIF':
                            chunk.exportOrthomosaic(fileoutname,
                                                    format="tif",
                                                    projection=self.out_crs,
                                                    region=cu_Region,
                                                    dx=DifPix,
                                                    dy=DifPix,
                                                    blockw=BlockSize,
                                                    blockh=BlockSize,
                                                    write_kml=False,
                                                    write_world=True,
                                                    tiff_compression="jpeg",
                                                    tiff_big=False)
                            #сжатие LZW
                            #elif file_format=='TIF': chunk.exportOrthomosaic(fileoutname, format="tif", region=cu_Region, projection=self.out_crs,dx=DifPix, dy=DifPix, blockw=BlockSize, blockh=BlockSize, write_kml=False, write_world=True, tiff_compression="lzw", tiff_big=False)
                        else:
                            print("Формат файла?")
                    elif CommandStack == 5 and ExportType == 'ORTHO':
                        if file_format == 'JPG':
                            chunk.exportOrthomosaic(
                                fileoutname,
                                PhotoScan.RasterFormatTiles,
                                PhotoScan.ImageFormatJPEG,
                                region=cu_Region,
                                projection=self.out_crs,
                                dx=DifPix,
                                dy=DifPix,
                                blockw=BlockSize,
                                blockh=BlockSize,
                                write_kml=False,
                                write_world=True)
                        elif file_format == 'TIF':
                            chunk.exportOrthomosaic(
                                fileoutname,
                                PhotoScan.RasterFormatTiles,
                                PhotoScan.ImageFormatTIFF,
                                region=cu_Region,
                                projection=self.out_crs,
                                dx=DifPix,
                                dy=DifPix,
                                blockw=BlockSize,
                                blockh=BlockSize,
                                write_kml=False,
                                write_world=True,
                                tiff_compression=PhotoScan.TiffCompressionJPEG,
                                tiff_big=False)
                            #сжатие LZW
                            #elif file_format=='TIF': chunk.exportOrthomosaic(fileoutname, PhotoScan.RasterFormatTiles,PhotoScan.ImageFormatTIFF, region=cu_Region, projection=self.out_crs,dx=DifPix, dy=DifPix, blockw=BlockSize, blockh=BlockSize, write_kml=False, write_world=True, tiff_compression=PhotoScan.TiffCompressionLZW, tiff_big=False)
                        else:
                            print("Формат файла?")
                    elif CommandStack == 1 and ExportType == 'DEM':
                        print("Экспорт ДЕМ локально")
                        if file_format == 'TIF':
                            chunk.exportDem(fileoutname,
                                            format="tif",
                                            projection=self.out_crs,
                                            region=cu_Region,
                                            dx=DifPix,
                                            dy=DifPix,
                                            blockw=BlockSize,
                                            blockh=BlockSize,
                                            write_kml=False,
                                            write_world=True,
                                            tiff_big=False)
                    elif CommandStack == 5 and ExportType == 'DEM':
                        print("Экспорт ДЕМ локально")
                        if file_format == 'TIF':
                            chunk.exportDem(fileoutname,
                                            PhotoScan.RasterFormatTiles,
                                            PhotoScan.ImageFormatTIFF,
                                            region=cu_Region,
                                            projection=self.out_crs,
                                            dx=DifPix,
                                            dy=DifPix,
                                            blockw=BlockSize,
                                            blockh=BlockSize,
                                            write_kml=False,
                                            write_world=True,
                                            tiff_big=False)

                elif proc_type == 'net':
                    print('Обработка по сети')
                    ''' ПОСТРОЕНИЕ ОРТОФОТО В ЭТОЙ ВЕРСИИ ОТКЛЮЧЕНО
					#Построить ортофото
					if statOrthoBuild==True:
						workBuild = PhotoScan.NetworkTask() # СОздаем ворк и забиваем его параметрами
						#Версионность
						if CommandStack==1:
							workBuild.params['ortho_surface'] = 0
							workBuild.params['resolution_x'] = DifPix
							workBuild.params['resolution_y'] = DifPix
						elif CommandStack==5:
							workBuild.params['ortho_surface'] = 4
							workBuild.params['resolution'] = DifPix
						else:
							return
						workBuild.name = "BuildOrthomosaic"
						workBuild.frames.append((chunk.key,0))
						workBuild.params['network_distribute'] = True
						
						task.append(workBuild) #Добавляем задачу построения в таск
					'''

                    #Экспортировать ортофото
                    workExport = PhotoScan.NetworkTask(
                    )  # СОздаем ворк и забиваем его параметрами
                    #ВЕРСИОННОСТЬ
                    if CommandStack == 1 and ExportType == 'ORTHO':
                        workExport.name = "ExportOrthomosaic"
                        workExport.params['resolution_x'] = DifPix
                        workExport.params['resolution_y'] = DifPix
                        if file_format == 'JPG':
                            workExport.params['raster_format'] = 2
                        elif file_format == 'TIF':
                            workExport.params['raster_format'] = 1
                        else:
                            print("Формат файла?")
                    elif CommandStack == 5 and ExportType == 'ORTHO':
                        workExport.name = "ExportRaster"
                        workExport.params['resolution'] = DifPix
                        if file_format == 'JPG':
                            workExport.params['image_format'] = 1
                        elif file_format == 'TIF':
                            workExport.params[
                                'image_format'] = 2  #Значение на шару!!! ПРОВЕРИТЬ
                        else:
                            print("Формат файла?")
                    elif CommandStack == 1 and ExportType == 'DEM':
                        print("Экспорт ДЕМ по сети")
                        workExport.name = "ExportDem"
                        workExport.params['resolution_x'] = DifPix
                        workExport.params['resolution_y'] = DifPix
                    elif CommandStack == 5 and ExportType == 'DEM':  #НЕ ОТЛАЖЕНО ПАРАМЕТРЫ НА ШАРУ
                        print("Экспорт ДЕМ по сети")
                        workExport.name = "ExportOrthomosaic"
                        workExport.params['resolution'] = DifPix
                        pass
                    else:
                        return

                    workExport.frames.append((chunk.key, 0))
                    workExport.params['write_world'] = 1
                    if self.block_size.currentText(
                    ) == 'Full':  # Условие на запись тайлов
                        workExport.params['write_tiles'] = 0
                    else:
                        workExport.params['write_tiles'] = 1
                    workExport.params['tile_width'] = BlockSize
                    workExport.params['tile_height'] = BlockSize
                    workExport.params[
                        'path'] = fileoutname  #выходная дирректория с именем файла
                    workExport.params['region'] = cu_Region
                    # ВНИМАНИЕ! По сети нельзя экспортировать в пользовательской проекции ИЛИ проекция должна быть НА ВСЕХ НОДАХ
                    workExport.params[
                        'projection'] = self.out_crs.authority  #Из объекта проекция берется только ее номер EPSG::32637
                    #ВНИМАНИЕ ЭКСПОРТ ОТКЛЮЧЕН!!!!
                    task.append(workExport)  #Добавляем задачу в таск
                else:
                    print('Пока не задано')
            PhotoScan.app.messageBox('Обработка закончена')
        except Exception as e:
            print(e)
            PhotoScan.app.messageBox('Что-то пошло не так ((')
            return
            #break
#Запуск сетевого стека, таска в обработку
        if proc_type == 'net':
            print(ProjectLocalPath_auto)
            print(ProjectPath)
            client.connect(ServerIP)
            batch_id = client.createBatch(ProjectPath, task)

            if batch_id == None:  #Проверка наличия проекта в сети
                PhotoScan.app.messageBox(
                    '<B>Этот проект уже запущен в обработку!!!<B>')
                self.unlock_export(5)
            else:
                print('Проект работает под номером ', batch_id)
                client.resumeBatch(batch_id)
                self.unlock_export(5)
                PhotoScan.app.messageBox(
                    'Проект поставлен в очередь сетевой обработки')

            client.disconnect()
            pass
    def _initUI(self):
        # Widgets
        self._rb_delimited = QRadioButton('Delimited')
        self._rb_delimited.setChecked(False)

        self._lbl_elevation = QLabel("Elevation")
        self._lbl_elevation.setStyleSheet("color: blue")
        self._txt_elevation = _AngleRangeWidget(_DelimitedDetector.elevation_rad)
        self._txt_elevation.setEnabled(False)
        self._txt_elevation.setRequired(False)

        self._lbl_azimuth = QLabel('Azimuth')
        self._lbl_azimuth.setStyleSheet("color: blue")
        self._txt_azimuth = _AngleRangeWidget(_DelimitedDetector.azimuth_rad)
        self._txt_azimuth.setEnabled(False)
        self._txt_azimuth.setRequired(False)

        self._rb_annular = QRadioButton('Annular')
        self._rb_annular.setChecked(True)

        self._lbl_takeoffangle = QLabel('Take-off angle')
        self._lbl_takeoffangle.setStyleSheet("color: blue")
        param_takeoffangle = \
            AngleParameter(validators=range_validator(0.0, HALFPI),
                           doc='Take-off angle from the x-y plane')
        param_takeoffangle._name = 'takeoffangle'
        self._txt_takeoffangle = AngleParameterWidget(param_takeoffangle)

        self._lbl_opening = QLabel('Opening')
        self._lbl_opening.setStyleSheet("color: blue")
        param_opening = \
            AngleParameter(validators=range_validator(0.0, HALFPI, False),
                           doc='Opening angle from the take-off angle (above and below)')
        param_opening._name = 'opening'
        self._txt_opening = AngleParameterWidget(param_opening)

        # Layouts
        layout = _DetectorWidget._initUI(self)

        layout.addRow(self._rb_delimited)

        sublayout = QFormLayout()
        sublayout.setContentsMargins(10, 0, 0, 0)
        if sys.platform == 'darwin': # Fix for Mac OS
            sublayout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
        sublayout.addRow(self._lbl_elevation, self._txt_elevation)
        sublayout.addRow(self._lbl_azimuth, self._txt_azimuth)
        layout.addRow(sublayout)

        layout.addRow(self._rb_annular)

        sublayout = QFormLayout()
        sublayout.setContentsMargins(10, 0, 0, 0)
        if sys.platform == 'darwin': # Fix for Mac OS
            sublayout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
        sublayout.addRow(self._lbl_takeoffangle, self._txt_takeoffangle)
        sublayout.addRow(self._lbl_opening, self._txt_opening)
        layout.addRow(sublayout)

        # Signals
        self._rb_delimited.toggled.connect(self._onToggle)
        self._rb_annular.toggled.connect(self._onToggle)

        return layout
class _DelimitedDetectorWidget(_DetectorWidget):

    def _initUI(self):
        # Widgets
        self._rb_delimited = QRadioButton('Delimited')
        self._rb_delimited.setChecked(False)

        self._lbl_elevation = QLabel("Elevation")
        self._lbl_elevation.setStyleSheet("color: blue")
        self._txt_elevation = _AngleRangeWidget(_DelimitedDetector.elevation_rad)
        self._txt_elevation.setEnabled(False)
        self._txt_elevation.setRequired(False)

        self._lbl_azimuth = QLabel('Azimuth')
        self._lbl_azimuth.setStyleSheet("color: blue")
        self._txt_azimuth = _AngleRangeWidget(_DelimitedDetector.azimuth_rad)
        self._txt_azimuth.setEnabled(False)
        self._txt_azimuth.setRequired(False)

        self._rb_annular = QRadioButton('Annular')
        self._rb_annular.setChecked(True)

        self._lbl_takeoffangle = QLabel('Take-off angle')
        self._lbl_takeoffangle.setStyleSheet("color: blue")
        param_takeoffangle = \
            AngleParameter(validators=range_validator(0.0, HALFPI),
                           doc='Take-off angle from the x-y plane')
        param_takeoffangle._name = 'takeoffangle'
        self._txt_takeoffangle = AngleParameterWidget(param_takeoffangle)

        self._lbl_opening = QLabel('Opening')
        self._lbl_opening.setStyleSheet("color: blue")
        param_opening = \
            AngleParameter(validators=range_validator(0.0, HALFPI, False),
                           doc='Opening angle from the take-off angle (above and below)')
        param_opening._name = 'opening'
        self._txt_opening = AngleParameterWidget(param_opening)

        # Layouts
        layout = _DetectorWidget._initUI(self)

        layout.addRow(self._rb_delimited)

        sublayout = QFormLayout()
        sublayout.setContentsMargins(10, 0, 0, 0)
        if sys.platform == 'darwin': # Fix for Mac OS
            sublayout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
        sublayout.addRow(self._lbl_elevation, self._txt_elevation)
        sublayout.addRow(self._lbl_azimuth, self._txt_azimuth)
        layout.addRow(sublayout)

        layout.addRow(self._rb_annular)

        sublayout = QFormLayout()
        sublayout.setContentsMargins(10, 0, 0, 0)
        if sys.platform == 'darwin': # Fix for Mac OS
            sublayout.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.ExpandingFieldsGrow)
        sublayout.addRow(self._lbl_takeoffangle, self._txt_takeoffangle)
        sublayout.addRow(self._lbl_opening, self._txt_opening)
        layout.addRow(sublayout)

        # Signals
        self._rb_delimited.toggled.connect(self._onToggle)
        self._rb_annular.toggled.connect(self._onToggle)

        return layout

    def _onToggle(self):
        state = self._rb_delimited.isChecked()
        self._txt_elevation.setEnabled(state)
        self._txt_azimuth.setEnabled(state)
        self._txt_elevation.setRequired(state)
        self._txt_azimuth.setRequired(state)
        self._txt_takeoffangle.setEnabled(not state)
        self._txt_opening.setEnabled(not state)
        self._txt_takeoffangle.setRequired(not state)
        self._txt_opening.setRequired(not state)

    def _getElevationValues(self):
        if self._rb_delimited.isChecked():
            return self._txt_elevation.values()
        else:
            takeoffangles = self._txt_takeoffangle.values()
            openings = self._txt_opening.values()

            elevations = []
            for takeoffangle, opening in product(takeoffangles, openings):
                elevation = (takeoffangle - opening, takeoffangle + opening)
                elevations.append(elevation)

            return elevations

    def _getAzimuthValues(self):
        if self._rb_delimited.isChecked():
            return self._txt_azimuth.values()
        else:
            return [(0.0, TWOPI)]

    def setValue(self, value):
        self._rb_delimited.setChecked(True)
        self._txt_elevation.setValues(value.elevation_rad)
        self._txt_azimuth.setValues(value.azimuth_rad)
        self._txt_takeoffangle.setValues([])
        self._txt_opening.setValues([])

    def setReadOnly(self, state):
        _DetectorWidget.setReadOnly(self, state)
        style = 'color: none' if state else 'color: blue'
        self._rb_delimited.setEnabled(not state)
        self._rb_annular.setEnabled(not state)
        self._lbl_elevation.setStyleSheet(style)
        self._txt_elevation.setReadOnly(state)
        self._lbl_azimuth.setStyleSheet(style)
        self._txt_azimuth.setReadOnly(state)
        self._lbl_takeoffangle.setStyleSheet(style)
        self._txt_takeoffangle.setReadOnly(state)
        self._lbl_opening.setStyleSheet(style)
        self._txt_opening.setReadOnly(state)
Exemple #37
0
class ServiceBrowser(QWidget):
    def __init__(self, parent = None):
        QWidget.__init__(self, parent)
        self.serviceManager = QServiceManager(self)
        self.registerExampleServices()
        self.initWidgets()
        self.reloadServicesList()
        self.setWindowTitle(self.tr("Services Browser"))

    def __del__(self):
        self.unregisterExampleServices()

    def currentInterfaceImplChanged(self, current, previous):
        if not current:
            return

        descriptor = current.data(Qt.UserRole)
        self.reloadAttributesList()
        self.reloadAttributesRadioButtonText()
        if descriptor.isValid():
            self.defaultInterfaceButton.setText(self.tr("Set as default implementation for %s" % str(descriptor.interfaceName())))
        self.defaultInterfaceButton.setEnabled(True)

    def reloadServicesList(self):
        self.servicesListWidget.clear()
        services = self.serviceManager.findServices()
        for serv in services:
            self.servicesListWidget.addItem(serv)

        self.servicesListWidget.addItem(self.showAllServicesItem)
        self._services = services

    def reloadInterfaceImplementationsList(self):
        serviceName = None
        allServices = self.servicesListWidget.currentItem().text() == self.showAllServicesItem.text()
        if self.servicesListWidget.currentItem() and not allServices:
            serviceName = self.servicesListWidget.currentItem().text()
            self.interfacesGroup.setTitle(self.tr("Interfaces implemented by %s" % str(serviceName)))
        else:
            self.interfacesGroup.setTitle(self.tr("All interface implementations"))

        descriptors = self.serviceManager.findInterfaces(serviceName)
        self.attributesListWidget.clear()
        self.interfacesListWidget.clear()
        self._i = []
        for desc in descriptors:
            text = "%s %d.%d" % (desc.interfaceName(), desc.majorVersion(), desc.minorVersion())

            if not serviceName:
                text += " (" + desc.serviceName() + ")"

            defaultInterfaceImpl = self.serviceManager.interfaceDefault(desc.interfaceName())
            if desc == defaultInterfaceImpl:
                text += self.tr(" (default)")

            item = QListWidgetItem(text)
            item.setData(Qt.UserRole, desc)
            item._data = desc
            self.interfacesListWidget.addItem(item)

        self.defaultInterfaceButton.setEnabled(False)

    def reloadAttributesList(self):
        item = self.interfacesListWidget.currentItem()
        if not item:
            return

        selectedImpl = item.data(Qt.UserRole)
        implementationRef = None
        if self.selectedImplRadioButton.isChecked():
            implementationRef = self.serviceManager.loadInterface(selectedImpl)
        else:
            implementationRef = self.serviceManager.loadInterface(selectedImpl.interfaceName())

        self.attributesListWidget.clear()
        if not implementationRef:
            self.attributesListWidget.addItem(self.tr("(Error loading service plugin)"))
            return

        metaObject = implementationRef.metaObject()
        self.attributesGroup.setTitle(self.tr("Invokable attributes for %s class" % metaObject.className()))
        for i in range(metaObject.methodCount()):
            method = metaObject.method(i)
            self.attributesListWidget.addItem("[METHOD] " + method.signature())

        for i in range(metaObject.propertyCount()):
            p = metaObject.property(i)
            self.attributesListWidget.addItem("[PROPERTY] " + p.name())

    def setDefaultInterfaceImplementation(self):
        item = self.interfacesListWidget.currentItem()
        if not item:
            return

        descriptor = item.data(Qt.UserRole)
        if descriptor.isValid():
            if self.serviceManager.setInterfaceDefault(descriptor):
                currentIndex = self.interfacesListWidget.row(item)
                self.reloadInterfaceImplementationsList()
                self.interfacesListWidget.setCurrentRow(currentIndex)
            else:
                print "Unable to set default service for interface:",  descriptor.interfaceName()

    def registerExampleServices(self):
        exampleXmlFiles = ["filemanagerservice.xml", "bluetoothtransferservice.xml"]
        for fileName in exampleXmlFiles:
            path = "./xmldata/" + fileName
            self.serviceManager.addService(path)

    def unregisterExampleServices(self):
        self.serviceManager.removeService("FileManagerService")
        self.serviceManager.removeService("BluetoothTransferService")

    def reloadAttributesRadioButtonText(self):
        item = self.interfacesListWidget.currentItem()
        if not item:
            return

        selectedImpl = item.data(Qt.UserRole)
        defaultImpl = self.serviceManager.interfaceDefault(selectedImpl.interfaceName())
        self.defaultImplRadioButton.setText(self.tr("Default implementation for %s\n(currently provided by %s)" % (str(defaultImpl.interfaceName()), str(defaultImpl.serviceName()))))

    def initWidgets(self):
        self.showAllServicesItem = QListWidgetItem(self.tr("(All registered services)"))
        self.servicesListWidget = QListWidget()
        self.interfacesListWidget = QListWidget()
        self.interfacesListWidget.addItem(self.tr("(Select a service)"))
        self.attributesListWidget = QListWidget()
        self.attributesListWidget.addItem(self.tr("(Select an interface implementation)"))
        self.interfacesListWidget.setMinimumWidth(450)
        self.servicesListWidget.currentItemChanged.connect(self.reloadInterfaceImplementationsList)
        self.interfacesListWidget.currentItemChanged.connect(self.currentInterfaceImplChanged)
        self.defaultInterfaceButton = QPushButton(self.tr("Set as default implementation"))
        self.defaultInterfaceButton.setEnabled(False)
        self.defaultInterfaceButton.clicked.connect(self.setDefaultInterfaceImplementation)
        self.selectedImplRadioButton = QRadioButton(self.tr("Selected interface implementation"))
        self.defaultImplRadioButton = QRadioButton(self.tr("Default implementation"))
        self.selectedImplRadioButton.setChecked(True)
        self.radioButtons = QButtonGroup(self)
        self.radioButtons.addButton(self.selectedImplRadioButton)
        self.radioButtons.addButton(self.defaultImplRadioButton)
        self.radioButtons.buttonClicked.connect(self.reloadAttributesList)

        self.servicesGroup = QGroupBox(self.tr("Show services for:"))
        servicesLayout = QVBoxLayout()
        servicesLayout.addWidget(self.servicesListWidget)
        self.servicesGroup.setLayout(servicesLayout)

        self.interfacesGroup = QGroupBox(self.tr("Interface implementations"))
        interfacesLayout = QVBoxLayout()
        interfacesLayout.addWidget(self.interfacesListWidget)
        interfacesLayout.addWidget(self.defaultInterfaceButton)
        self.interfacesGroup.setLayout(interfacesLayout)

        self.attributesGroup = QGroupBox(self.tr("Invokable attributes"))
        attributesLayout = QVBoxLayout()
        self.attributesGroup.setLayout(attributesLayout)
        attributesLayout.addWidget(self.attributesListWidget)
        attributesLayout.addWidget(QLabel(self.tr("Show attributes for:")))
        attributesLayout.addWidget(self.selectedImplRadioButton)
        attributesLayout.addWidget(self.defaultImplRadioButton)

        self.attributesGroup.setLayout(attributesLayout)

        layout = QGridLayout()
        layout.addWidget(self.servicesGroup, 0, 0)
        layout.addWidget(self.attributesGroup, 0, 1, 2, 1)
        layout.addWidget(self.interfacesGroup, 1, 0)

        self.setLayout(layout)
Exemple #38
0
    def createWidgets(self):
        selectedEid = self.state.viewAllPanel.view.selectedEid
        self.selectedEntry = self.state.model.entry(selectedEid)
        self.entryLabel = QLabel("Move ")
        self.termLabel = Widgets.Label.HtmlLabel("“{}”".format(
            Lib.elidePatchHtml(self.selectedEntry.term, self.state)))

        self.eidGroup = QGroupBox()

        parentEid = self.selectedEntry.peid
        self.moveToTopRadioButton = QRadioButton("to be a &Main Entry")
        self.grandParentEntry = None
        grandParentEid = None
        if parentEid != ROOT:
            grandParentEid = self.state.model.parentOf(parentEid)
            if grandParentEid != ROOT:
                self.grandParentEntry = self.state.model.entry(grandParentEid)
        self.grandParentRadioButton = QRadioButton("up under &Grandparent")

        self.filteredEntry = self.circledEntry = None
        filteredEid = self.state.viewFilteredPanel.view.selectedEid
        if filteredEid is not None:
            self.filteredEntry = self.state.model.entry(filteredEid)
        circledEid = self.state.viewAllPanel.view.circledEid
        if circledEid is not None:
            self.circledEntry = self.state.model.entry(circledEid)
        self.filteredRadioButton = QRadioButton("under &Filtered")
        self.circledRadioButton = QRadioButton("under C&ircled")
        self.recentRadioButton = QRadioButton("under &Recent")
        self.tooltips.append(
            (self.recentRadioButton, """<p><b>under Recent</b></p>
<p>Move the current entry under a recently visited entry.</p>"""))

        self.grandParentLabel = Widgets.Label.HtmlLabel()
        self.filteredLabel = Widgets.Label.HtmlLabel()
        self.circledLabel = Widgets.Label.HtmlLabel()

        self.moveToTopRadioButton.setEnabled(parentEid != ROOT)
        self.moveToTopRadioButton.setChecked(parentEid != ROOT)
        seen = {selectedEid, self.selectedEntry.peid}
        self.buttons = (self.moveToTopRadioButton, self.grandParentRadioButton,
                        self.filteredRadioButton, self.circledRadioButton,
                        self.recentRadioButton)
        Forms.Util.setUpRadioButton(
            self, self.grandParentEntry, self.grandParentRadioButton,
            self.grandParentLabel, self.buttons, seen,
            """<p><b>under Grandparent</b></p>
<p>Move the current entry up under its grandparent “{}”.</p>""")
        Forms.Util.setUpRadioButton(
            self, self.filteredEntry, self.filteredRadioButton,
            self.filteredLabel, self.buttons, seen,
            """<p><b>under Filtered</b></p>
<p>Move the current entry under the filtered entry “{}”.</p>""")
        Forms.Util.setUpRadioButton(
            self, self.circledEntry, self.circledRadioButton,
            self.circledLabel, self.buttons, seen,
            """<p><b>under Circled</b></p>
<p>Move the current entry under the circled entry “{}”.</p>""")
        self.recentComboBox = Forms.Util.createTermsComboBox(
            self.state, self.state.gotoEids, ignore=seen, maximum=MAX_RECENT)
        if self.recentComboBox.count() and all(not radio.isChecked()
                                               for radio in self.buttons):
            self.recentRadioButton.setChecked(True)
            self.recentComboBox.setFocus()

        self.buttonBox = QDialogButtonBox()
        self.moveButton = QPushButton(QIcon(":/move.svg"), "M&ove")
        self.tooltips.append((self.moveButton, """<p><b>Move</b></p>
<p>Move the “{}” entry.</p>""".format(self.termLabel.text())))
        self.buttonBox.addButton(self.moveButton, QDialogButtonBox.AcceptRole)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel")
        self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p>
<p>Close the dialog without making any changes to the index.</p>"""))
        self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the Move Entry dialog"))
        self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
class ConfigDialog(QtGui.QDialog):

    pressedclosebutton = False
    moreToggling = False

    def moreToggled(self):
        if self.moreToggling == False:
            self.moreToggling = True

            if self.showmoreCheckbox.isChecked() and self.showmoreCheckbox.isVisible():
                self.showmoreCheckbox.setChecked(False)
                self.moreSettingsGroup.setChecked(True)
                self.moreSettingsGroup.show()
                self.showmoreCheckbox.hide()
                self.saveMoreState(True)
            else:
                self.moreSettingsGroup.setChecked(False)
                self.moreSettingsGroup.hide()
                self.showmoreCheckbox.show()
                self.saveMoreState(False)

            self.moreToggling = False
            self.adjustSize()
            self.setFixedSize(self.sizeHint())

    def runButtonTextUpdate(self):
        if (self.donotstoreCheckbox.isChecked()):
            self.runButton.setText(getMessage("en", "run-label"))
        else:
            self.runButton.setText(getMessage("en", "storeandrun-label"))

    def openHelp(self):
        self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/client/")

    def _tryToFillPlayerPath(self, playerpath, playerpathlist):
        settings = QSettings("Syncplay", "PlayerList")
        settings.beginGroup("PlayerList")
        savedPlayers = settings.value("PlayerList", [])
        if(not isinstance(savedPlayers, list)):
            savedPlayers = []
        playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers)))
        settings.endGroup()
        foundpath = ""

        if playerpath != None and playerpath != "":
            if not os.path.isfile(playerpath):
                expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath)
                if expandedpath != None and os.path.isfile(expandedpath):
                    playerpath = expandedpath

            if os.path.isfile(playerpath):
                foundpath = playerpath
                self.executablepathCombobox.addItem(foundpath)

        for path in playerpathlist:
            if(os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath))):
                self.executablepathCombobox.addItem(path)
                if foundpath == "":
                    foundpath = path

        if foundpath != "":
            settings.beginGroup("PlayerList")
            playerpathlist.append(os.path.normcase(os.path.normpath(foundpath)))
            settings.setValue("PlayerList", list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist))))
            settings.endGroup()
        return(foundpath)

    def updateExecutableIcon(self):
        currentplayerpath = unicode(self.executablepathCombobox.currentText())
        iconpath = PlayerFactory().getPlayerIconByPath(currentplayerpath)
        if iconpath != None and iconpath != "":
            self.executableiconImage.load(self.resourcespath + iconpath)
            self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(self.executableiconImage))
        else:
            self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage()))


    def browsePlayerpath(self):
        options = QtGui.QFileDialog.Options()
        defaultdirectory = ""
        browserfilter = "All files (*)"

        if os.name == 'nt':
            browserfilter = "Executable files (*.exe);;All files (*)"
            if "PROGRAMFILES(X86)" in os.environ:
                defaultdirectory = os.environ["ProgramFiles(x86)"]
            elif "PROGRAMFILES" in os.environ:
                defaultdirectory = os.environ["ProgramFiles"]
            elif "PROGRAMW6432" in os.environ:
                defaultdirectory = os.environ["ProgramW6432"]
        elif sys.platform.startswith('linux'):
            defaultdirectory = "/usr/bin"

        fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,
                "Browse for media player executable",
                defaultdirectory,
                browserfilter, "", options)
        if fileName:
            self.executablepathCombobox.setEditText(os.path.normpath(fileName))

    def loadMediaBrowseSettings(self):
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.beginGroup("MediaBrowseDialog")
        self.mediadirectory = settings.value("mediadir", "")
        settings.endGroup()

    def saveMediaBrowseSettings(self):
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.beginGroup("MediaBrowseDialog")
        settings.setValue("mediadir", self.mediadirectory)
        settings.endGroup()

    def getMoreState(self):
        settings = QSettings("Syncplay", "MoreSettings")
        settings.beginGroup("MoreSettings")
        morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false")))
        settings.endGroup()
        if morestate == "true":
            return(True)
        else:
            return(False)

    def saveMoreState(self, morestate):
        settings = QSettings("Syncplay", "MoreSettings")
        settings.beginGroup("MoreSettings")
        settings.setValue("ShowMoreSettings", morestate)
        settings.endGroup()

    def browseMediapath(self):
        self.loadMediaBrowseSettings()
        options = QtGui.QFileDialog.Options()
        if (os.path.isdir(self.mediadirectory)):
            defaultdirectory = self.mediadirectory
        elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))):
            defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
        elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))):
            defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        else:
            defaultdirectory = ""
        browserfilter = "All files (*)"
        fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media files", defaultdirectory,
                browserfilter, "", options)
        if fileName:
            self.mediapathTextbox.setText(os.path.normpath(fileName))
            self.mediadirectory = os.path.dirname(fileName)
            self.saveMediaBrowseSettings()

    def _saveDataAndLeave(self):
        self.config['host'] = self.hostTextbox.text() if ":" in self.hostTextbox.text() else self.hostTextbox.text() + ":" + unicode(constants.DEFAULT_PORT)
        self.config['name'] = self.usernameTextbox.text()
        self.config['room'] = self.defaultroomTextbox.text()
        self.config['password'] = self.serverpassTextbox.text()
        self.config['playerPath'] = unicode(self.executablepathCombobox.currentText())
        if self.mediapathTextbox.text() == "":
            self.config['file'] = None
        elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())):
            self.config['file'] = os.path.abspath(self.mediapathTextbox.text())
        else:
            self.config['file'] = unicode(self.mediapathTextbox.text())
        if self.alwaysshowCheckbox.isChecked() == True:
            self.config['forceGuiPrompt'] = True
        else:
            self.config['forceGuiPrompt'] = False
        if self.donotstoreCheckbox.isChecked() == True:
            self.config['noStore'] = True
        else:
            self.config['noStore'] = False
        if self.slowdownCheckbox.isChecked() == True:
            self.config['slowOnDesync'] = True
        else:
            self.config['slowOnDesync'] = False
        if self.dontslowwithmeCheckbox.isChecked() == True:
            self.config['dontSlowDownWithMe'] = True
        else:
            self.config['dontSlowDownWithMe'] = False
        if self.pauseonleaveCheckbox.isChecked() == True:
            self.config['pauseOnLeave'] = True
        else:
            self.config['pauseOnLeave'] = False


        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            if self.rewindCheckbox.isChecked() == True:
                self.config['rewindOnDesync'] = True
            else:
                self.config['rewindOnDesync'] = False

        if self.filenameprivacySendRawOption.isChecked() == True:
            self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE
        elif self.filenameprivacySendHashedOption.isChecked() == True:
            self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE
        elif self.filenameprivacyDontSendOption.isChecked() == True:
            self.config['filenamePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE

        if self.filesizeprivacySendRawOption.isChecked() == True:
            self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE
        elif self.filesizeprivacySendHashedOption.isChecked() == True:
            self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE
        elif self.filesizeprivacyDontSendOption.isChecked() == True:
            self.config['filesizePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE

        self.pressedclosebutton = True
        self.close()
        return

    def closeEvent(self, event):
        if self.pressedclosebutton == False:
            sys.exit()
            raise GuiConfiguration.WindowClosed
            event.accept()

    def dragEnterEvent(self, event):
        data = event.mimeData()
        urls = data.urls()
        if (urls and urls[0].scheme() == 'file'):
            event.acceptProposedAction()

    def dropEvent(self, event):
        data = event.mimeData()
        urls = data.urls()
        if (urls and urls[0].scheme() == 'file'):
            if sys.platform.startswith('linux'):
                dropfilepath = unicode(urls[0].path())
            else:
                dropfilepath = unicode(urls[0].path())[1:]  # Removes starting slash
            if dropfilepath[-4:].lower() == ".exe":
                self.executablepathCombobox.setEditText(dropfilepath)
            else:
                self.mediapathTextbox.setText(dropfilepath)

    def __init__(self, config, playerpaths, error):

        from syncplay import utils
        self.config = config
        self.datacleared = False
        if config['clearGUIData'] == True:
            settings = QSettings("Syncplay", "PlayerList")
            settings.clear()
            settings = QSettings("Syncplay", "MediaBrowseDialog")
            settings.clear()
            settings = QSettings("Syncplay", "MainWindow")
            settings.clear()
            settings = QSettings("Syncplay", "MoreSettings")
            settings.clear()
            self.datacleared = True
        self.QtGui = QtGui
        self.error = error
        if sys.platform.startswith('linux'):
            resourcespath = utils.findWorkingDir() + "/resources/"
        else:
            resourcespath = utils.findWorkingDir() + "\\resources\\"
        self.resourcespath = resourcespath

        super(ConfigDialog, self).__init__()

        self.setWindowTitle(getMessage("en", "config-window-title"))
        self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
        self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png"))

        if(config['host'] == None):
            host = ""
        elif(":" in config['host']):
            host = config['host']
        else:
            host = config['host'] + ":" + str(config['port'])

        self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title"))
        self.hostTextbox = QLineEdit(host, self)
        self.hostLabel = QLabel(getMessage("en", "host-label"), self)
        self.usernameTextbox = QLineEdit(config['name'], self)
        self.serverpassLabel = QLabel(getMessage("en", "password-label"), self)
        self.defaultroomTextbox = QLineEdit(config['room'], self)
        self.usernameLabel = QLabel(getMessage("en", "username-label"), self)
        self.serverpassTextbox = QLineEdit(config['password'], self)
        self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self)

        if (constants.SHOW_TOOLTIPS == True):
            self.hostLabel.setToolTip(getMessage("en", "host-tooltip"))
            self.hostTextbox.setToolTip(getMessage("en", "host-tooltip"))
            self.usernameLabel.setToolTip(getMessage("en", "username-tooltip"))
            self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip"))
            self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip"))
            self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip"))
            self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip"))
            self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip"))

        self.connectionSettingsLayout = QtGui.QGridLayout()
        self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0)
        self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1)
        self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0)
        self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1)
        self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0)
        self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1)
        self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0)
        self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1)
        self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout)

        self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title"))
        self.executableiconImage = QtGui.QImage()
        self.executableiconLabel = QLabel(self)
        self.executableiconLabel.setMinimumWidth(16)
        self.executablepathCombobox = QtGui.QComboBox(self)
        self.executablepathCombobox.setEditable(True)
        self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon)
        self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths))
        self.executablepathCombobox.setMinimumWidth(200)
        self.executablepathCombobox.setMaximumWidth(200)
        self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon)

        self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self)
        self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("en", "browse-label"))
        self.executablebrowseButton.clicked.connect(self.browsePlayerpath)
        self.mediapathTextbox = QLineEdit(config['file'], self)
        self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self)
        self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("en", "browse-label"))
        self.mediabrowseButton.clicked.connect(self.browseMediapath)

        if (constants.SHOW_TOOLTIPS == True):
            self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip"))
            self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip"))
            self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip"))
            self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip"))

        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label"))
            if (constants.SHOW_TOOLTIPS == True):
                self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip"))
        self.mediaplayerSettingsLayout = QtGui.QGridLayout()
        self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0)
        self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1)
        self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2)
        self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2)
        self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3)
        self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout)

        self.moreSettingsGroup = QtGui.QGroupBox(getMessage("en", "more-title"))

        self.moreSettingsGroup.setCheckable(True)

        self.filenameprivacyLabel = QLabel(getMessage("en", "filename-privacy-label"), self)
        self.filenameprivacyButtonGroup = QButtonGroup()
        self.filenameprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option"))
        self.filenameprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option"))
        self.filenameprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option"))
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption)

        self.filesizeprivacyLabel = QLabel(getMessage("en", "filesize-privacy-label"), self)
        self.filesizeprivacyButtonGroup = QButtonGroup()
        self.filesizeprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option"))
        self.filesizeprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option"))
        self.filesizeprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option"))
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption)

        self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label"))
        self.dontslowwithmeCheckbox = QCheckBox(getMessage("en", "dontslowwithme-label"))
        self.pauseonleaveCheckbox = QCheckBox(getMessage("en", "pauseonleave-label"))
        self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label"))
        self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label"))

        filenamePrivacyMode = config['filenamePrivacyMode']
        if filenamePrivacyMode == constants.PRIVACY_DONTSEND_MODE:
            self.filenameprivacyDontSendOption.setChecked(True)
        elif filenamePrivacyMode == constants.PRIVACY_SENDHASHED_MODE:
            self.filenameprivacySendHashedOption.setChecked(True)
        else:
            self.filenameprivacySendRawOption.setChecked(True)

        filesizePrivacyMode = config['filesizePrivacyMode']
        if filesizePrivacyMode == constants.PRIVACY_DONTSEND_MODE:
            self.filesizeprivacyDontSendOption.setChecked(True)
        elif filesizePrivacyMode == constants.PRIVACY_SENDHASHED_MODE:
            self.filesizeprivacySendHashedOption.setChecked(True)
        else:
            self.filesizeprivacySendRawOption.setChecked(True)

        if config['slowOnDesync'] == True:
            self.slowdownCheckbox.setChecked(True)
        if config['dontSlowDownWithMe'] == True:
            self.dontslowwithmeCheckbox.setChecked(True)

        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True:
            self.rewindCheckbox.setChecked(True)
        if config['pauseOnLeave'] == True:
            self.pauseonleaveCheckbox.setChecked(True)

        if (constants.SHOW_TOOLTIPS == True):
            self.filenameprivacyLabel.setToolTip(getMessage("en", "filename-privacy-tooltip"))
            self.filenameprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip"))
            self.filenameprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip"))
            self.filenameprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip"))
            self.filesizeprivacyLabel.setToolTip(getMessage("en", "filesize-privacy-tooltip"))
            self.filesizeprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip"))
            self.filesizeprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip"))
            self.filesizeprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip"))

            self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip"))
            self.dontslowwithmeCheckbox.setToolTip(getMessage("en", "dontslowwithme-tooltip"))
            self.pauseonleaveCheckbox.setToolTip(getMessage("en", "pauseonleave-tooltip"))
            self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip"))
            self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip"))
            self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip"))

        self.moreSettingsLayout = QtGui.QGridLayout()

        self.privacySettingsLayout = QtGui.QGridLayout()
        self.privacyFrame = QtGui.QFrame()
        self.privacyFrame.setLineWidth(0)
        self.privacyFrame.setMidLineWidth(0)
        self.privacySettingsLayout.setContentsMargins(0, 0, 0, 0)
        self.privacySettingsLayout.addWidget(self.filenameprivacyLabel, 0, 0)
        self.privacySettingsLayout.addWidget(self.filenameprivacySendRawOption, 0, 1, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filenameprivacySendHashedOption, 0, 2, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filenameprivacyDontSendOption, 0, 3, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacyLabel, 1, 0)
        self.privacySettingsLayout.addWidget(self.filesizeprivacySendRawOption, 1, 1, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 1, 2, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 1, 3, Qt.AlignRight)
        self.privacyFrame.setLayout(self.privacySettingsLayout)

        self.moreSettingsLayout.addWidget(self.privacyFrame, 0, 0, 1, 4)

        self.moreSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.dontslowwithmeCheckbox, 3, 0, 1, 4)
        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            self.moreSettingsLayout.addWidget(self.rewindCheckbox, 4, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.pauseonleaveCheckbox, 5, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.alwaysshowCheckbox, 6, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.donotstoreCheckbox, 7, 0, 1, 4)

        self.moreSettingsGroup.setLayout(self.moreSettingsLayout)

        self.showmoreCheckbox = QCheckBox(getMessage("en", "more-title"))

        if self.getMoreState() == False:
            self.showmoreCheckbox.setChecked(False)
            self.moreSettingsGroup.hide()
        else:
            self.showmoreCheckbox.hide()
        self.showmoreCheckbox.toggled.connect(self.moreToggled)
        self.moreSettingsGroup.toggled.connect(self.moreToggled)

        if config['forceGuiPrompt'] == True:
            self.alwaysshowCheckbox.setChecked(True)

        if (constants.SHOW_TOOLTIPS == True):
            self.showmoreCheckbox.setToolTip(getMessage("en", "more-tooltip"))

        self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate)

        self.mainLayout = QtGui.QVBoxLayout()
        if error:
            self.errorLabel = QLabel(error, self)
            self.errorLabel.setAlignment(Qt.AlignCenter)
            self.errorLabel.setStyleSheet("QLabel { color : red; }")
            self.mainLayout.addWidget(self.errorLabel)
        self.mainLayout.addWidget(self.connectionSettingsGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.mediaplayerSettingsGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.showmoreCheckbox)
        self.mainLayout.addWidget(self.moreSettingsGroup)
        self.mainLayout.addSpacing(12)

        self.topLayout = QtGui.QHBoxLayout()
        self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'), getMessage("en", "help-label"))
        if (constants.SHOW_TOOLTIPS == True):
            self.helpButton.setToolTip(getMessage("en", "help-tooltip"))
        self.helpButton.setMaximumSize(self.helpButton.sizeHint())
        self.helpButton.pressed.connect(self.openHelp)
        self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'), getMessage("en", "storeandrun-label"))
        self.runButton.pressed.connect(self._saveDataAndLeave)
        if config['noStore'] == True:
            self.donotstoreCheckbox.setChecked(True)
            self.runButton.setText(getMessage("en", "run-label"))
        self.topLayout.addWidget(self.helpButton, Qt.AlignLeft)
        self.topLayout.addWidget(self.runButton, Qt.AlignRight)
        self.mainLayout.addLayout(self.topLayout)

        self.mainLayout.addStretch(1)
        self.setLayout(self.mainLayout)
        self.runButton.setFocus()
        self.setFixedSize(self.sizeHint())
        self.setAcceptDrops(True)

        if self.datacleared == True:
            QtGui.QMessageBox.information(self, "Syncplay", getMessage("en", "gui-data-cleared-notification"))
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

        lbMinWidth = 65
        # leMinWidth = 200

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(400, 310)

        # self.centralwidget = QWidget(MainWindow)
        self.mainSplitter = QSplitter(Qt.Horizontal, MainWindow)
        self.mainSplitter.setObjectName("centralwidget")
        self.mainSplitter.setProperty("childrenCollapsible", False)
        MainWindow.setCentralWidget(self.mainSplitter)

        self.leftSplitter = QSplitter(Qt.Vertical, self.mainSplitter)
        self.leftSplitter.setProperty("childrenCollapsible", False)
        ##### login_gbox
        self.login_gbox = QGroupBox(self.leftSplitter)
        self.login_gbox.setFlat(True)
        self.login_gbox.setObjectName("login_gbox")

        login_gbox_layout = QVBoxLayout(self.login_gbox)
        login_gbox_csf_layout = QHBoxLayout()
        login_gbox_account_layout = QHBoxLayout()
        login_gbox_connect_layout = QHBoxLayout()
        login_gbox_layout.addLayout(login_gbox_csf_layout)
        login_gbox_layout.addLayout(login_gbox_account_layout)
        login_gbox_layout.addLayout(login_gbox_connect_layout)

        self.lb_client_secrets_file_path = QLabel(self.login_gbox)
        self.lb_client_secrets_file_path.setObjectName("lb_client_secrets_file_path")
        self.lb_client_secrets_file_path.setMinimumWidth(lbMinWidth)

        self.client_secrets_file_path_le = QLineEdit(self.login_gbox)
        self.client_secrets_file_path_le.setObjectName("client_secrets_file_path_le")

        self.client_secret_file_path_tBtn = QToolButton(self.login_gbox)
        self.client_secret_file_path_tBtn.setObjectName("client_secret_file_path_tBtn")

        login_gbox_csf_layout.addWidget(self.lb_client_secrets_file_path)
        login_gbox_csf_layout.addWidget(self.client_secrets_file_path_le)
        login_gbox_csf_layout.addWidget(self.client_secret_file_path_tBtn)

        self.lb_account = QLabel(self.login_gbox)
        self.lb_account.setMaximumWidth(lbMinWidth)
        self.lb_account.setObjectName("lb_account")

        self.remove_account_btn = QToolButton(self.login_gbox)
        self.remove_account_btn.setObjectName("remove_account_btn")
        self.remove_account_btn.setMinimumWidth(20)
        self.remove_account_btn.setEnabled(False)

        self.add_account_btn = QToolButton(self.login_gbox)
        self.add_account_btn.setObjectName("add_account_btn")
        self.add_account_btn.setMinimumWidth(20)

        self.accounts_cb = QComboBox(self.login_gbox)
        self.accounts_cb.setObjectName("accounts_cb")

        login_gbox_account_layout.addWidget(self.lb_account)
        login_gbox_account_layout.addWidget(self.remove_account_btn)
        login_gbox_account_layout.addWidget(self.add_account_btn)
        login_gbox_account_layout.addWidget(self.accounts_cb)

        self.lb_decryption_key = QLabel(self.login_gbox)
        self.lb_decryption_key.setObjectName("lb_decryption_key")
        self.lb_decryption_key.setMinimumWidth(lbMinWidth)
        self.lb_decryption_key.hide()

        self.decryption_key_le = QLineEdit(self.login_gbox)
        self.decryption_key_le.setEchoMode(QLineEdit.Password)
        self.decryption_key_le.setObjectName("decryption_key_le")
        self.decryption_key_le.hide()

        self.connect_btn = QPushButton(self.login_gbox)
        self.connect_btn.setEnabled(False)
        self.connect_btn.setObjectName("connect_btn")

        login_gbox_connect_layout.addWidget(self.lb_decryption_key)
        login_gbox_connect_layout.addWidget(self.decryption_key_le)
        login_gbox_connect_layout.addWidget(self.connect_btn)

        #### search_gbox
        self.search_gbox = QGroupBox(self.leftSplitter)
        self.search_gbox.setFlat(True)
        self.search_gbox.setObjectName("search_gbox")
        self.search_gbox.hide()

        search_gbox_layout = QVBoxLayout(self.search_gbox)
        search_gbox_mailbox_layout = QVBoxLayout()
        search_gbox_date_layout = QHBoxLayout()
        search_gbox_from_layout = QHBoxLayout()
        search_gbox_to_layout = QHBoxLayout()
        search_gbox_subject_layout = QHBoxLayout()
        search_gbox_threads_layout = QHBoxLayout()
        search_gbox_paramaters_layout = QHBoxLayout()

        search_gbox_layout.addLayout(search_gbox_mailbox_layout)
        search_gbox_layout.addLayout(search_gbox_date_layout)
        search_gbox_layout.addLayout(search_gbox_from_layout)
        search_gbox_layout.addLayout(search_gbox_to_layout)
        search_gbox_layout.addLayout(search_gbox_subject_layout)
        search_gbox_layout.addLayout(search_gbox_threads_layout)
        search_gbox_layout.addLayout(search_gbox_paramaters_layout)

        self.lb_select_mailbox = QLabel(self.search_gbox)
        self.lb_select_mailbox.setObjectName("lb_select_mailbox")
        self.mailboxes_lw = QListWidget(self.search_gbox)
        self.mailboxes_lw.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.mailboxes_lw.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.mailboxes_lw.setObjectName("mailboxes_lw")
        search_gbox_mailbox_layout.addWidget(self.lb_select_mailbox)
        search_gbox_mailbox_layout.addWidget(self.mailboxes_lw)

        self.after_date_cb = QCheckBox(self.search_gbox)
        self.after_date_cb.setObjectName("after_date_cb")
        self.after_date_cb.setMinimumWidth(lbMinWidth)
        self.after_date_cb.setMaximumWidth(lbMinWidth)
        self.after_date_edit = QDateEdit(self.search_gbox)
        self.after_date_edit.setCalendarPopup(True)
        self.after_date_edit.setObjectName("after_date_edit")
        self.after_date_edit.setDate(QDate.currentDate().addDays(-365))
        self.after_date_edit.setMaximumDate(QDate.currentDate())
        self.after_date_edit.setEnabled(False)
        self.before_date_cb = QCheckBox(self.search_gbox)
        self.before_date_cb.setObjectName("before_date_cb")
        self.before_date_cb.setMinimumWidth(70)
        self.before_date_cb.setMaximumWidth(70)
        self.before_date_edit = QDateEdit(self.search_gbox)
        self.before_date_edit.setCalendarPopup(True)
        self.before_date_edit.setObjectName("before_date_edit")
        self.before_date_edit.setDate(QDate.currentDate())
        self.before_date_edit.setMaximumDate(QDate.currentDate())
        self.before_date_edit.setEnabled(False)
        search_gbox_date_layout.addWidget(self.after_date_cb)
        search_gbox_date_layout.addWidget(self.after_date_edit)
        search_gbox_date_layout.addWidget(self.before_date_cb)
        search_gbox_date_layout.addWidget(self.before_date_edit)

        self.lb_from = QLabel(self.search_gbox)
        self.lb_from.setObjectName("lb_from")
        self.lb_from.setMinimumWidth(lbMinWidth)
        self.from_le = QLineEdit(self.search_gbox)
        self.from_le.setObjectName("from_le")
        search_gbox_from_layout.addWidget(self.lb_from)
        search_gbox_from_layout.addWidget(self.from_le)

        self.lb_to = QLabel(self.search_gbox)
        self.lb_to.setObjectName("lb_to")
        self.lb_to.setMinimumWidth(lbMinWidth)
        self.to_le = QLineEdit(self.search_gbox)
        self.to_le.setObjectName("to_le")
        search_gbox_to_layout.addWidget(self.lb_to)
        search_gbox_to_layout.addWidget(self.to_le)

        self.lb_subject = QLabel(self.search_gbox)
        self.lb_subject.setObjectName("lb_subject")
        self.lb_subject.setMinimumWidth(lbMinWidth)
        self.subject_le = QLineEdit(self.search_gbox)
        self.subject_le.setObjectName("subject_le")
        search_gbox_subject_layout.addWidget(self.lb_subject)
        search_gbox_subject_layout.addWidget(self.subject_le)

        self.lb_threads = QLabel(self.search_gbox)
        self.lb_threads.setObjectName("lb_threads")
        self.lb_threads.setMaximumWidth(lbMinWidth)
        self.thread_count_sb = QSpinBox(self.search_gbox)
        self.thread_count_sb.setMinimum(1)
        self.thread_count_sb.setMaximum(10)
        self.thread_count_sb.setObjectName("thread_count_sb")
        self.html_radio = QRadioButton(self.search_gbox)
        self.html_radio.setObjectName("html_radio")
        self.text_radio = QRadioButton(self.search_gbox)
        self.text_radio.setObjectName("text_radio")
        self.extactTypeButtonGroup = QButtonGroup(self)
        self.extactTypeButtonGroup.addButton(self.html_radio)
        self.extactTypeButtonGroup.addButton(self.text_radio)
        self.html_radio.setChecked(True)
        self.search_btn = QPushButton(self.search_gbox)
        self.search_btn.setObjectName("search_btn")
        search_gbox_threads_layout.addWidget(self.lb_threads)
        search_gbox_threads_layout.addWidget(self.thread_count_sb)
        search_gbox_threads_layout.addWidget(self.html_radio)
        search_gbox_threads_layout.addWidget(self.text_radio)
        search_gbox_threads_layout.addWidget(self.search_btn)

        self.parameters_cb = QCheckBox(self.search_gbox)
        self.parameters_cb.setText("")
        self.parameters_cb.setObjectName("parameters_cb")
        self.parameters_le = QLineEdit(self.search_gbox)
        self.parameters_le.setEnabled(False)
        self.parameters_le.setObjectName("parameters_le")
        search_gbox_paramaters_layout.addWidget(self.parameters_cb)
        search_gbox_paramaters_layout.addWidget(self.parameters_le)

        #### log_gbox
        self.log_gbox = QGroupBox(self.leftSplitter)
        self.log_gbox.setFlat(True)
        self.log_gbox.setObjectName("log_gbox")
        log_layout = QVBoxLayout(self.log_gbox)
        self.log_te = QTextEdit(self.log_gbox)
        self.log_te.setLineWrapMode(QTextEdit.NoWrap)
        self.log_te.setReadOnly(True)
        self.log_te.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse)
        self.log_te.setObjectName("log_te")

        self.disconnect_btn = QPushButton(self.log_gbox)
        self.disconnect_btn.setObjectName("disconnect_btn")
        self.disconnect_btn.hide()
        log_layout.addWidget(self.log_te)
        log_layout_btn = QHBoxLayout()
        log_layout.addLayout(log_layout_btn)
        log_layout_btn.addWidget(self.disconnect_btn)
        log_layout_btn.addStretch()

        #### links_gbox
        self.links_gbox = QGroupBox(self.mainSplitter)
        self.links_gbox.setFlat(True)
        self.links_gbox.setObjectName("links_gbox")
        self.links_gbox.hide()
        links_gbox_layout = QVBoxLayout(self.links_gbox)
        links_gbox_links_layout = QVBoxLayout()
        links_gbox_buttons_layout = QHBoxLayout()
        links_gbox_layout.addLayout(links_gbox_links_layout)
        links_gbox_layout.addLayout(links_gbox_buttons_layout)

        self.links_text_edit = QTextEdit(self.links_gbox)
        self.links_text_edit.setObjectName("links_text_edit")
        links_gbox_links_layout.addWidget(self.links_text_edit)

        self.export_txt_btn = QPushButton(self.links_gbox)
        self.export_txt_btn.setObjectName("export_txt_btn")
        self.export_txt_btn.setEnabled(False)
        self.export_html_btn = QPushButton(self.links_gbox)
        self.export_html_btn.setObjectName("export_html_btn")
        self.export_html_btn.setEnabled(False)

        links_gbox_buttons_layout.addWidget(self.export_txt_btn)
        links_gbox_buttons_layout.addWidget(self.export_html_btn)
        
        ### menubar
        self.menubar = QMenuBar(MainWindow)
        # self.menubar.setGeometry(QRect(0, 0, 860, 21))
        self.menubar.setObjectName("menubar")
        self.menu_file = QMenu(self.menubar)
        self.menu_file.setObjectName("menu_file")
        self.menu_help = QMenu(self.menubar)
        self.menu_help.setObjectName("menu_help")
        MainWindow.setMenuBar(self.menubar)
        self.action_about = QAction(MainWindow)
        self.action_about.setObjectName("action_about")
        self.action_About_Qt = QAction(MainWindow)
        self.action_About_Qt.setObjectName("action_About_Qt")
        self.action_exit = QAction(MainWindow)
        self.action_exit.setObjectName("action_exit")
        self.actionSave = QAction(MainWindow)
        self.actionSave.setObjectName("actionSave")
        self.action_Gmail_Advanced_Search_Syntax = QAction(MainWindow)
        self.action_Gmail_Advanced_Search_Syntax.setObjectName("action_Gmail_Advanced_Search_Syntax")
        self.menu_file.addAction(self.action_exit)
        self.menu_help.addAction(self.action_Gmail_Advanced_Search_Syntax)
        self.menu_help.addSeparator()
        self.menu_help.addAction(self.action_about)
        self.menu_help.addAction(self.action_About_Qt)
        self.menubar.addAction(self.menu_file.menuAction())
        self.menubar.addAction(self.menu_help.menuAction())
        
        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.setTabOrder(self.client_secrets_file_path_le, self.client_secret_file_path_tBtn)
        MainWindow.setTabOrder(self.client_secret_file_path_tBtn, self.remove_account_btn)
        MainWindow.setTabOrder(self.remove_account_btn, self.add_account_btn)
        MainWindow.setTabOrder(self.add_account_btn, self.accounts_cb)
        MainWindow.setTabOrder(self.decryption_key_le, self.connect_btn)
        MainWindow.setTabOrder(self.connect_btn, self.log_te)
        MainWindow.setTabOrder(self.log_te, self.mailboxes_lw)
        MainWindow.setTabOrder(self.mailboxes_lw, self.after_date_cb)
        MainWindow.setTabOrder(self.after_date_cb, self.after_date_edit)
        MainWindow.setTabOrder(self.after_date_edit, self.before_date_cb)
        MainWindow.setTabOrder(self.before_date_cb, self.before_date_edit)
        MainWindow.setTabOrder(self.before_date_edit, self.from_le)
        MainWindow.setTabOrder(self.from_le, self.to_le)
        MainWindow.setTabOrder(self.to_le, self.subject_le)
        MainWindow.setTabOrder(self.subject_le, self.thread_count_sb)
        MainWindow.setTabOrder(self.thread_count_sb, self.html_radio)
        MainWindow.setTabOrder(self.html_radio, self.text_radio)
        MainWindow.setTabOrder(self.text_radio, self.search_btn)
        MainWindow.setTabOrder(self.search_btn, self.parameters_cb)
        MainWindow.setTabOrder(self.parameters_cb, self.parameters_le)
        MainWindow.setTabOrder(self.parameters_le, self.disconnect_btn)
        MainWindow.setTabOrder(self.disconnect_btn, self.links_text_edit)
        MainWindow.setTabOrder(self.links_text_edit, self.export_txt_btn)
        MainWindow.setTabOrder(self.export_txt_btn, self.export_html_btn)
        MainWindow.setTabOrder(self.export_html_btn, self.mailboxes_lw)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QApplication.translate("MainWindow", "Gmail URL Parser", None, QApplication.UnicodeUTF8))
        self.login_gbox.setTitle(QApplication.translate("MainWindow", "  Client secrets file path  ", None, QApplication.UnicodeUTF8))
        self.client_secrets_file_path_le.setPlaceholderText(QApplication.translate("MainWindow", "Please select your client secrets file", None, QApplication.UnicodeUTF8))
        self.lb_client_secrets_file_path.setText(QApplication.translate("MainWindow", "Path", None, QApplication.UnicodeUTF8))
        self.connect_btn.setText(QApplication.translate("MainWindow", "Connect", None, QApplication.UnicodeUTF8))
        self.client_secret_file_path_tBtn.setText(QApplication.translate("MainWindow", "...", None, QApplication.UnicodeUTF8))
        self.lb_account.setText(QApplication.translate("MainWindow", "Account", None, QApplication.UnicodeUTF8))
        self.add_account_btn.setText(QApplication.translate("MainWindow", "+", None, QApplication.UnicodeUTF8))
        self.remove_account_btn.setText(QApplication.translate("MainWindow", "-", None, QApplication.UnicodeUTF8))
        self.decryption_key_le.setPlaceholderText(QApplication.translate("MainWindow", "Decryption key", None, QApplication.UnicodeUTF8))
        self.lb_decryption_key.setText(QApplication.translate("MainWindow", "Key", None, QApplication.UnicodeUTF8))
        self.log_gbox.setTitle(QApplication.translate("MainWindow", "  Log  ", None, QApplication.UnicodeUTF8))
        self.search_gbox.setTitle(QApplication.translate("MainWindow", "  Search Parameters  ", None, QApplication.UnicodeUTF8))
        self.lb_to.setText(QApplication.translate("MainWindow", "To", None, QApplication.UnicodeUTF8))
        self.lb_from.setText(QApplication.translate("MainWindow", "From", None, QApplication.UnicodeUTF8))
        self.lb_subject.setText(QApplication.translate("MainWindow", "Subject", None, QApplication.UnicodeUTF8))
        self.search_btn.setText(QApplication.translate("MainWindow", "Search", None, QApplication.UnicodeUTF8))
        self.after_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "yyyy-MM-dd", None, QApplication.UnicodeUTF8))
        self.before_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "yyyy-MM-dd", None, QApplication.UnicodeUTF8))
        self.lb_select_mailbox.setToolTip(QApplication.translate("MainWindow", "<html><head/><body><p>Select multiple items to select labels</p></body></html>", None, QApplication.UnicodeUTF8))
        self.lb_select_mailbox.setText(QApplication.translate("MainWindow", "Select Mailbox or Labels", None, QApplication.UnicodeUTF8))
        self.after_date_cb.setText(QApplication.translate("MainWindow", "After", None, QApplication.UnicodeUTF8))
        self.before_date_cb.setText(QApplication.translate("MainWindow", "Before", None, QApplication.UnicodeUTF8))
        self.html_radio.setText(QApplication.translate("MainWindow", "html", None, QApplication.UnicodeUTF8))
        self.text_radio.setText(QApplication.translate("MainWindow", "text", None, QApplication.UnicodeUTF8))
        self.lb_threads.setText(QApplication.translate("MainWindow", "Threads", None, QApplication.UnicodeUTF8))
        self.links_gbox.setTitle(QApplication.translate("MainWindow", "  Links  ", None, QApplication.UnicodeUTF8))
        self.disconnect_btn.setText(QApplication.translate("MainWindow", "Disconnect", None, QApplication.UnicodeUTF8))
        self.export_txt_btn.setText(QApplication.translate("MainWindow", "Export as txt", None, QApplication.UnicodeUTF8))
        self.export_html_btn.setText(QApplication.translate("MainWindow", "Export as HTML", None, QApplication.UnicodeUTF8))
        self.menu_file.setTitle(QApplication.translate("MainWindow", "File", None, QApplication.UnicodeUTF8))
        self.menu_help.setTitle(QApplication.translate("MainWindow", "Help", None, QApplication.UnicodeUTF8))
        self.action_about.setText(QApplication.translate("MainWindow", "About", None, QApplication.UnicodeUTF8))
        self.action_About_Qt.setText(QApplication.translate("MainWindow", "About Qt", None, QApplication.UnicodeUTF8))
        self.action_exit.setText(QApplication.translate("MainWindow", "Exit", None, QApplication.UnicodeUTF8))
        self.action_exit.setShortcut(QApplication.translate("MainWindow", "Ctrl+Q", None, QApplication.UnicodeUTF8))
        self.actionSave.setText(QApplication.translate("MainWindow", "Save", None, QApplication.UnicodeUTF8))
        self.action_Gmail_Advanced_Search_Syntax.setText(QApplication.translate("MainWindow", "Gmail Advanced Search Syntax", None, QApplication.UnicodeUTF8))
    def setupUi(self, MainWindow):

        lbMinWidth = 65
        # leMinWidth = 200

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(400, 310)

        # self.centralwidget = QWidget(MainWindow)
        self.mainSplitter = QSplitter(Qt.Horizontal, MainWindow)
        self.mainSplitter.setObjectName("centralwidget")
        self.mainSplitter.setProperty("childrenCollapsible", False)
        MainWindow.setCentralWidget(self.mainSplitter)

        self.leftSplitter = QSplitter(Qt.Vertical, self.mainSplitter)
        self.leftSplitter.setProperty("childrenCollapsible", False)
        ##### login_gbox
        self.login_gbox = QGroupBox(self.leftSplitter)
        self.login_gbox.setFlat(True)
        self.login_gbox.setObjectName("login_gbox")

        login_gbox_layout = QVBoxLayout(self.login_gbox)
        login_gbox_csf_layout = QHBoxLayout()
        login_gbox_account_layout = QHBoxLayout()
        login_gbox_connect_layout = QHBoxLayout()
        login_gbox_layout.addLayout(login_gbox_csf_layout)
        login_gbox_layout.addLayout(login_gbox_account_layout)
        login_gbox_layout.addLayout(login_gbox_connect_layout)

        self.lb_client_secrets_file_path = QLabel(self.login_gbox)
        self.lb_client_secrets_file_path.setObjectName("lb_client_secrets_file_path")
        self.lb_client_secrets_file_path.setMinimumWidth(lbMinWidth)

        self.client_secrets_file_path_le = QLineEdit(self.login_gbox)
        self.client_secrets_file_path_le.setObjectName("client_secrets_file_path_le")

        self.client_secret_file_path_tBtn = QToolButton(self.login_gbox)
        self.client_secret_file_path_tBtn.setObjectName("client_secret_file_path_tBtn")

        login_gbox_csf_layout.addWidget(self.lb_client_secrets_file_path)
        login_gbox_csf_layout.addWidget(self.client_secrets_file_path_le)
        login_gbox_csf_layout.addWidget(self.client_secret_file_path_tBtn)

        self.lb_account = QLabel(self.login_gbox)
        self.lb_account.setMaximumWidth(lbMinWidth)
        self.lb_account.setObjectName("lb_account")

        self.remove_account_btn = QToolButton(self.login_gbox)
        self.remove_account_btn.setObjectName("remove_account_btn")
        self.remove_account_btn.setMinimumWidth(20)
        self.remove_account_btn.setEnabled(False)

        self.add_account_btn = QToolButton(self.login_gbox)
        self.add_account_btn.setObjectName("add_account_btn")
        self.add_account_btn.setMinimumWidth(20)

        self.accounts_cb = QComboBox(self.login_gbox)
        self.accounts_cb.setObjectName("accounts_cb")

        login_gbox_account_layout.addWidget(self.lb_account)
        login_gbox_account_layout.addWidget(self.remove_account_btn)
        login_gbox_account_layout.addWidget(self.add_account_btn)
        login_gbox_account_layout.addWidget(self.accounts_cb)

        self.lb_decryption_key = QLabel(self.login_gbox)
        self.lb_decryption_key.setObjectName("lb_decryption_key")
        self.lb_decryption_key.setMinimumWidth(lbMinWidth)
        self.lb_decryption_key.hide()

        self.decryption_key_le = QLineEdit(self.login_gbox)
        self.decryption_key_le.setEchoMode(QLineEdit.Password)
        self.decryption_key_le.setObjectName("decryption_key_le")
        self.decryption_key_le.hide()

        self.connect_btn = QPushButton(self.login_gbox)
        self.connect_btn.setEnabled(False)
        self.connect_btn.setObjectName("connect_btn")

        login_gbox_connect_layout.addWidget(self.lb_decryption_key)
        login_gbox_connect_layout.addWidget(self.decryption_key_le)
        login_gbox_connect_layout.addWidget(self.connect_btn)

        #### search_gbox
        self.search_gbox = QGroupBox(self.leftSplitter)
        self.search_gbox.setFlat(True)
        self.search_gbox.setObjectName("search_gbox")
        self.search_gbox.hide()

        search_gbox_layout = QVBoxLayout(self.search_gbox)
        search_gbox_mailbox_layout = QVBoxLayout()
        search_gbox_date_layout = QHBoxLayout()
        search_gbox_from_layout = QHBoxLayout()
        search_gbox_to_layout = QHBoxLayout()
        search_gbox_subject_layout = QHBoxLayout()
        search_gbox_threads_layout = QHBoxLayout()
        search_gbox_paramaters_layout = QHBoxLayout()

        search_gbox_layout.addLayout(search_gbox_mailbox_layout)
        search_gbox_layout.addLayout(search_gbox_date_layout)
        search_gbox_layout.addLayout(search_gbox_from_layout)
        search_gbox_layout.addLayout(search_gbox_to_layout)
        search_gbox_layout.addLayout(search_gbox_subject_layout)
        search_gbox_layout.addLayout(search_gbox_threads_layout)
        search_gbox_layout.addLayout(search_gbox_paramaters_layout)

        self.lb_select_mailbox = QLabel(self.search_gbox)
        self.lb_select_mailbox.setObjectName("lb_select_mailbox")
        self.mailboxes_lw = QListWidget(self.search_gbox)
        self.mailboxes_lw.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.mailboxes_lw.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.mailboxes_lw.setObjectName("mailboxes_lw")
        search_gbox_mailbox_layout.addWidget(self.lb_select_mailbox)
        search_gbox_mailbox_layout.addWidget(self.mailboxes_lw)

        self.after_date_cb = QCheckBox(self.search_gbox)
        self.after_date_cb.setObjectName("after_date_cb")
        self.after_date_cb.setMinimumWidth(lbMinWidth)
        self.after_date_cb.setMaximumWidth(lbMinWidth)
        self.after_date_edit = QDateEdit(self.search_gbox)
        self.after_date_edit.setCalendarPopup(True)
        self.after_date_edit.setObjectName("after_date_edit")
        self.after_date_edit.setDate(QDate.currentDate().addDays(-365))
        self.after_date_edit.setMaximumDate(QDate.currentDate())
        self.after_date_edit.setEnabled(False)
        self.before_date_cb = QCheckBox(self.search_gbox)
        self.before_date_cb.setObjectName("before_date_cb")
        self.before_date_cb.setMinimumWidth(70)
        self.before_date_cb.setMaximumWidth(70)
        self.before_date_edit = QDateEdit(self.search_gbox)
        self.before_date_edit.setCalendarPopup(True)
        self.before_date_edit.setObjectName("before_date_edit")
        self.before_date_edit.setDate(QDate.currentDate())
        self.before_date_edit.setMaximumDate(QDate.currentDate())
        self.before_date_edit.setEnabled(False)
        search_gbox_date_layout.addWidget(self.after_date_cb)
        search_gbox_date_layout.addWidget(self.after_date_edit)
        search_gbox_date_layout.addWidget(self.before_date_cb)
        search_gbox_date_layout.addWidget(self.before_date_edit)

        self.lb_from = QLabel(self.search_gbox)
        self.lb_from.setObjectName("lb_from")
        self.lb_from.setMinimumWidth(lbMinWidth)
        self.from_le = QLineEdit(self.search_gbox)
        self.from_le.setObjectName("from_le")
        search_gbox_from_layout.addWidget(self.lb_from)
        search_gbox_from_layout.addWidget(self.from_le)

        self.lb_to = QLabel(self.search_gbox)
        self.lb_to.setObjectName("lb_to")
        self.lb_to.setMinimumWidth(lbMinWidth)
        self.to_le = QLineEdit(self.search_gbox)
        self.to_le.setObjectName("to_le")
        search_gbox_to_layout.addWidget(self.lb_to)
        search_gbox_to_layout.addWidget(self.to_le)

        self.lb_subject = QLabel(self.search_gbox)
        self.lb_subject.setObjectName("lb_subject")
        self.lb_subject.setMinimumWidth(lbMinWidth)
        self.subject_le = QLineEdit(self.search_gbox)
        self.subject_le.setObjectName("subject_le")
        search_gbox_subject_layout.addWidget(self.lb_subject)
        search_gbox_subject_layout.addWidget(self.subject_le)

        self.lb_threads = QLabel(self.search_gbox)
        self.lb_threads.setObjectName("lb_threads")
        self.lb_threads.setMaximumWidth(lbMinWidth)
        self.thread_count_sb = QSpinBox(self.search_gbox)
        self.thread_count_sb.setMinimum(1)
        self.thread_count_sb.setMaximum(10)
        self.thread_count_sb.setObjectName("thread_count_sb")
        self.html_radio = QRadioButton(self.search_gbox)
        self.html_radio.setObjectName("html_radio")
        self.text_radio = QRadioButton(self.search_gbox)
        self.text_radio.setObjectName("text_radio")
        self.extactTypeButtonGroup = QButtonGroup(self)
        self.extactTypeButtonGroup.addButton(self.html_radio)
        self.extactTypeButtonGroup.addButton(self.text_radio)
        self.html_radio.setChecked(True)
        self.search_btn = QPushButton(self.search_gbox)
        self.search_btn.setObjectName("search_btn")
        search_gbox_threads_layout.addWidget(self.lb_threads)
        search_gbox_threads_layout.addWidget(self.thread_count_sb)
        search_gbox_threads_layout.addWidget(self.html_radio)
        search_gbox_threads_layout.addWidget(self.text_radio)
        search_gbox_threads_layout.addWidget(self.search_btn)

        self.parameters_cb = QCheckBox(self.search_gbox)
        self.parameters_cb.setText("")
        self.parameters_cb.setObjectName("parameters_cb")
        self.parameters_le = QLineEdit(self.search_gbox)
        self.parameters_le.setEnabled(False)
        self.parameters_le.setObjectName("parameters_le")
        search_gbox_paramaters_layout.addWidget(self.parameters_cb)
        search_gbox_paramaters_layout.addWidget(self.parameters_le)

        #### log_gbox
        self.log_gbox = QGroupBox(self.leftSplitter)
        self.log_gbox.setFlat(True)
        self.log_gbox.setObjectName("log_gbox")
        log_layout = QVBoxLayout(self.log_gbox)
        self.log_te = QTextEdit(self.log_gbox)
        self.log_te.setLineWrapMode(QTextEdit.NoWrap)
        self.log_te.setReadOnly(True)
        self.log_te.setTextInteractionFlags(Qt.TextSelectableByKeyboard | Qt.TextSelectableByMouse)
        self.log_te.setObjectName("log_te")

        self.disconnect_btn = QPushButton(self.log_gbox)
        self.disconnect_btn.setObjectName("disconnect_btn")
        self.disconnect_btn.hide()
        log_layout.addWidget(self.log_te)
        log_layout_btn = QHBoxLayout()
        log_layout.addLayout(log_layout_btn)
        log_layout_btn.addWidget(self.disconnect_btn)
        log_layout_btn.addStretch()

        #### links_gbox
        self.links_gbox = QGroupBox(self.mainSplitter)
        self.links_gbox.setFlat(True)
        self.links_gbox.setObjectName("links_gbox")
        self.links_gbox.hide()
        links_gbox_layout = QVBoxLayout(self.links_gbox)
        links_gbox_links_layout = QVBoxLayout()
        links_gbox_buttons_layout = QHBoxLayout()
        links_gbox_layout.addLayout(links_gbox_links_layout)
        links_gbox_layout.addLayout(links_gbox_buttons_layout)

        self.links_text_edit = QTextEdit(self.links_gbox)
        self.links_text_edit.setObjectName("links_text_edit")
        links_gbox_links_layout.addWidget(self.links_text_edit)

        self.export_txt_btn = QPushButton(self.links_gbox)
        self.export_txt_btn.setObjectName("export_txt_btn")
        self.export_txt_btn.setEnabled(False)
        self.export_html_btn = QPushButton(self.links_gbox)
        self.export_html_btn.setObjectName("export_html_btn")
        self.export_html_btn.setEnabled(False)

        links_gbox_buttons_layout.addWidget(self.export_txt_btn)
        links_gbox_buttons_layout.addWidget(self.export_html_btn)
        
        ### menubar
        self.menubar = QMenuBar(MainWindow)
        # self.menubar.setGeometry(QRect(0, 0, 860, 21))
        self.menubar.setObjectName("menubar")
        self.menu_file = QMenu(self.menubar)
        self.menu_file.setObjectName("menu_file")
        self.menu_help = QMenu(self.menubar)
        self.menu_help.setObjectName("menu_help")
        MainWindow.setMenuBar(self.menubar)
        self.action_about = QAction(MainWindow)
        self.action_about.setObjectName("action_about")
        self.action_About_Qt = QAction(MainWindow)
        self.action_About_Qt.setObjectName("action_About_Qt")
        self.action_exit = QAction(MainWindow)
        self.action_exit.setObjectName("action_exit")
        self.actionSave = QAction(MainWindow)
        self.actionSave.setObjectName("actionSave")
        self.action_Gmail_Advanced_Search_Syntax = QAction(MainWindow)
        self.action_Gmail_Advanced_Search_Syntax.setObjectName("action_Gmail_Advanced_Search_Syntax")
        self.menu_file.addAction(self.action_exit)
        self.menu_help.addAction(self.action_Gmail_Advanced_Search_Syntax)
        self.menu_help.addSeparator()
        self.menu_help.addAction(self.action_about)
        self.menu_help.addAction(self.action_About_Qt)
        self.menubar.addAction(self.menu_file.menuAction())
        self.menubar.addAction(self.menu_help.menuAction())
        
        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.setTabOrder(self.client_secrets_file_path_le, self.client_secret_file_path_tBtn)
        MainWindow.setTabOrder(self.client_secret_file_path_tBtn, self.remove_account_btn)
        MainWindow.setTabOrder(self.remove_account_btn, self.add_account_btn)
        MainWindow.setTabOrder(self.add_account_btn, self.accounts_cb)
        MainWindow.setTabOrder(self.decryption_key_le, self.connect_btn)
        MainWindow.setTabOrder(self.connect_btn, self.log_te)
        MainWindow.setTabOrder(self.log_te, self.mailboxes_lw)
        MainWindow.setTabOrder(self.mailboxes_lw, self.after_date_cb)
        MainWindow.setTabOrder(self.after_date_cb, self.after_date_edit)
        MainWindow.setTabOrder(self.after_date_edit, self.before_date_cb)
        MainWindow.setTabOrder(self.before_date_cb, self.before_date_edit)
        MainWindow.setTabOrder(self.before_date_edit, self.from_le)
        MainWindow.setTabOrder(self.from_le, self.to_le)
        MainWindow.setTabOrder(self.to_le, self.subject_le)
        MainWindow.setTabOrder(self.subject_le, self.thread_count_sb)
        MainWindow.setTabOrder(self.thread_count_sb, self.html_radio)
        MainWindow.setTabOrder(self.html_radio, self.text_radio)
        MainWindow.setTabOrder(self.text_radio, self.search_btn)
        MainWindow.setTabOrder(self.search_btn, self.parameters_cb)
        MainWindow.setTabOrder(self.parameters_cb, self.parameters_le)
        MainWindow.setTabOrder(self.parameters_le, self.disconnect_btn)
        MainWindow.setTabOrder(self.disconnect_btn, self.links_text_edit)
        MainWindow.setTabOrder(self.links_text_edit, self.export_txt_btn)
        MainWindow.setTabOrder(self.export_txt_btn, self.export_html_btn)
        MainWindow.setTabOrder(self.export_html_btn, self.mailboxes_lw)
Exemple #42
0
    def __init__(self, parent):
        #_____________Пременные уровня класса___________
        self.OUT_dir = ''  #выходная дирректория
        self.orthoBounds = []
        # ВЫХОДНАЯ ПРОЕКЦИЯ по умолчанию
        #out_crs='PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        self.out_crs = PhotoScan.CoordinateSystem(
            'PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        )
        #out_crs=PhotoScan.CoordinateSystem('PROJCS["WGS 84 / UTM zone 38N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",45],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32638"]]')
        self.crsShapes = PhotoScan.CoordinateSystem(
            'PROJCS["WGS 84 / UTM zone 37N",GEOGCS["WGS 84",DATUM["World Geodetic System 1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],TOWGS84[0,0,0,0,0,0,0],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.01745329251994328,AUTHORITY["EPSG","9102"]],AUTHORITY["EPSG","4326"]],PROJECTION["Transverse_Mercator",AUTHORITY["EPSG","9807"]],PARAMETER["latitude_of_origin",0],PARAMETER["central_meridian",39],PARAMETER["scale_factor",0.9996],PARAMETER["false_easting",500000],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AUTHORITY["EPSG","32637"]]'
        )
        self.DATA_OK = 0
        #print ('orthoBounds=',len(self.orthoBounds))
        #формат массива:0-имя ортофото, 1-Xmin, 2-Ymin, 3-sizeX, 4-sizeY, 5-ID полигона
        #__________________________________________________

        QDialog.__init__(self, parent)
        self.setWindowTitle("Экспорт Орто по разграфке")  #Заголвок окна
        self.resize(500, 250)  #размер окна
        self.txt_comment = QLabel(
            "	Модуль экспортирует ортофото и DEM из фотоскана по нарезке. \
Нарезка в текстовом файле: название листа, координаты нижнего левого угла, размеры. \n	Проекция нарезки должна совпадать с проекцией выходного ортофотоплана.\
Листы делятся по нарезке, а внутри нарезки по блокам, размеры задаются. ФОРМАТ JPG \n	При импорте SHP должно быть текстовое поле NAME \n \
Адрес сервера: " + ServerIP +
            " меняем в теле программы. Ваша версия фотоскана: " + PH_version +
            " \n")
        self.txt_comment.setWordWrap(True)
        self.now_prj = QLabel(str(self.out_crs))
        self.select_prj = QPushButton("Выберете проекцию")  #(" открыть ")
        self.select_prj.setFixedSize(170, 26)

        self.TXT_dif_pix = QLabel("<B>Размер пикселя: </B>")
        self.TXT_dif_pix.setFixedSize(170, 26)
        self.dif_pix = QLineEdit()
        self.dif_pix.setText('0.1')  # Задает размер пикселя по умолчанию
        self.dif_pix.setFixedSize(100, 26)

        items_bloksize = ('5000', '8192', '10000', '15000', '20000', '25000',
                          '29999', 'Full')  # список с размерами тайлов
        #items_bloksize = {5000:5000, 8192:8192, 10000:10000, 15000:15000, 20000:20000, 25000:25000, 29999:29999}
        self.TXT_block_size = QLabel("<B>Размер блока: </B>", )
        self.TXT_block_size.setFixedSize(170, 26)
        self.block_size = QComboBox()
        self.block_size.setFixedSize(100, 26)
        self.block_size.addItems(items_bloksize)
        self.block_size.setCurrentIndex(
            1)  #Устанавливает по умолчанию второе значение из списка - 8192

        self.TXT_SHPname = QLabel("Файл разграфки SHP (NAME,poligons)")
        self.SHPname = QPushButton(
            "Выберете файл разграфки SHP")  #(" открыть ")
        self.SHPname.setFixedSize(170, 26)

        self.TXT_filename = QLabel(
            "Файл разграфки TXT(имя; X0; Y0; sizeX; SizeY)")
        self.filename = QPushButton("Выберете Файл разграфки")  #(" открыть ")
        self.filename.setFixedSize(170, 26)

        self.TXT_CheckOrthoDem = QLabel("Вид выходной продукции")
        self.TXT_CheckOrthoDem.setFixedSize(170, 26)
        self.CheckOrtho_Radio = QRadioButton("Ортофото")
        self.CheckOrtho_Radio.setChecked(True)
        self.CheckDem_Radio = QRadioButton("ДЕМ")

        self.TXT_OUTFOLDER = QLabel("Выходная дирректория")
        self.OUTFOLDER = QPushButton("Выберете дирректорию")  #(" открыть ")
        self.OUTFOLDER.setFixedSize(170, 26)

        items_format = (
            'JPG', 'TIF'
        )  # список форматов, ПРИ выборе ДЕМ будет выбран второй формат - внимательно при изменении списка!!!
        self.file_format = QComboBox()
        self.file_format.setFixedSize(50, 26)
        self.file_format.addItems(items_format)
        self.file_format.setCurrentIndex(
            0)  #Устанавливает по умолчанию первое значение

        self.TXT_checkExportOrtho = QLabel("Построить ортофото:")  # Ортофото
        self.TXT_checkExportOrtho.setFixedSize(170, 26)
        self.checkExportOrtho = QCheckBox()
        self.checkExportOrtho.setChecked(False)

        self.GoGo = QPushButton("Экспорт локально")  #(" Экспорт локально ")
        self.GoGo.setFixedSize(170, 26)
        self.GoGo.setDisabled(True)

        self.GoGoNet = QPushButton("Экспорт по сети")  #(" Экспорт по сети ")
        self.GoGoNet.setFixedSize(170, 26)
        self.GoGoNet.setDisabled(True)

        hbox0 = QHBoxLayout()
        hbox0.addWidget(self.txt_comment, alignment=0)

        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.select_prj, alignment=0)
        hbox1.addWidget(self.now_prj, alignment=0)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.TXT_block_size, alignment=1)
        hbox2.addWidget(self.block_size, alignment=1)

        hbox3 = QHBoxLayout()
        hbox3.addWidget(self.TXT_dif_pix, alignment=1)
        hbox3.addWidget(self.dif_pix, alignment=1)

        hbox4 = QHBoxLayout()
        #hbox4.addStretch(1)
        hbox4.addWidget(self.SHPname, alignment=0)
        hbox4.addWidget(self.TXT_SHPname, alignment=0)

        hbox5 = QHBoxLayout()
        #hbox5.addStretch(1)
        hbox5.addWidget(self.filename, alignment=0)
        hbox5.addWidget(self.TXT_filename, alignment=0)

        hbox51 = QHBoxLayout()
        hbox51.addWidget(self.TXT_CheckOrthoDem, alignment=0)
        hbox51.addWidget(self.CheckOrtho_Radio, alignment=0)
        hbox51.addWidget(self.CheckDem_Radio, alignment=0)

        hbox6 = QHBoxLayout()
        #hbox5.addStretch(1)
        hbox6.addWidget(self.OUTFOLDER, alignment=0)
        hbox6.addWidget(self.TXT_OUTFOLDER, alignment=0)
        hbox6.addWidget(self.file_format, alignment=0)

        hbox7 = QHBoxLayout()  #build ortho
        hbox7.addWidget(self.TXT_checkExportOrtho, alignment=0)
        hbox7.addWidget(self.checkExportOrtho, alignment=0)

        hbox8 = QHBoxLayout()
        hbox8.addWidget(self.GoGo, stretch=0, alignment=0)
        hbox8.addWidget(self.GoGoNet, stretch=0, alignment=0)

        vbox = QVBoxLayout()  #Определяем вбокс и забиваем его Нбоксами
        #vbox.addStretch(1)
        vbox.addLayout(hbox0)
        vbox.addLayout(hbox1)
        vbox.addLayout(hbox2)
        vbox.addLayout(hbox3)
        vbox.addLayout(hbox4)
        vbox.addLayout(hbox5)
        vbox.addLayout(hbox51)  #выбор, что строить орто или дем
        vbox.addLayout(hbox6)
        #Функция построения ортофото спрятана, поскольку работает не стабильно и построение ортофото для каждого листа в сумме занимает очень много времени,
        #гораздо больше, чем один раз построить ортофото для всех
        #vbox.addLayout(hbox7) #build ortho
        vbox.addLayout(hbox8)

        self.setLayout(vbox)

        self.select_prj.clicked.connect(self.set_projection)
        self.SHPname.clicked.connect(self.input_razgr_SHPname)
        self.filename.clicked.connect(self.input_razgr_name)
        self.OUTFOLDER.clicked.connect(self.input_out_dir)
        self.GoGo.clicked.connect(self.ortho_local)
        self.GoGoNet.clicked.connect(self.ortho_net)
        #Организация блокировки интерфейса для радио кнопок
        self.CheckOrtho_Radio.clicked.connect(self.CheckOrtho_Radio_DO)
        self.CheckDem_Radio.clicked.connect(self.CheckDem_Radio_DO)
        #____________
        self.checkExportOrtho.clicked.connect(
            self.PrintChkStat)  #Функция для проверки работы чека
        #self.WindowContextHelpButtonHint.clicked.connect(self.prog_hint)
        #self.WindowTitleHint.clicked.connect(self.prog_hint)

        self.exec()
Exemple #43
0
class Form(QDialog):
    def __init__(self, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.state = state
        self.setWindowTitle("Move Entry — {}".format(
            QApplication.applicationName()))
        self.message = None
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()
        self.updateUi()
        settings = QSettings()
        self.updateToolTips(
            bool(
                int(
                    settings.value(Gopt.Key.ShowDialogToolTips,
                                   Gopt.Default.ShowDialogToolTips))))

    def createWidgets(self):
        selectedEid = self.state.viewAllPanel.view.selectedEid
        self.selectedEntry = self.state.model.entry(selectedEid)
        self.entryLabel = QLabel("Move ")
        self.termLabel = Widgets.Label.HtmlLabel("“{}”".format(
            Lib.elidePatchHtml(self.selectedEntry.term, self.state)))

        self.eidGroup = QGroupBox()

        parentEid = self.selectedEntry.peid
        self.moveToTopRadioButton = QRadioButton("to be a &Main Entry")
        self.grandParentEntry = None
        grandParentEid = None
        if parentEid != ROOT:
            grandParentEid = self.state.model.parentOf(parentEid)
            if grandParentEid != ROOT:
                self.grandParentEntry = self.state.model.entry(grandParentEid)
        self.grandParentRadioButton = QRadioButton("up under &Grandparent")

        self.filteredEntry = self.circledEntry = None
        filteredEid = self.state.viewFilteredPanel.view.selectedEid
        if filteredEid is not None:
            self.filteredEntry = self.state.model.entry(filteredEid)
        circledEid = self.state.viewAllPanel.view.circledEid
        if circledEid is not None:
            self.circledEntry = self.state.model.entry(circledEid)
        self.filteredRadioButton = QRadioButton("under &Filtered")
        self.circledRadioButton = QRadioButton("under C&ircled")
        self.recentRadioButton = QRadioButton("under &Recent")
        self.tooltips.append(
            (self.recentRadioButton, """<p><b>under Recent</b></p>
<p>Move the current entry under a recently visited entry.</p>"""))

        self.grandParentLabel = Widgets.Label.HtmlLabel()
        self.filteredLabel = Widgets.Label.HtmlLabel()
        self.circledLabel = Widgets.Label.HtmlLabel()

        self.moveToTopRadioButton.setEnabled(parentEid != ROOT)
        self.moveToTopRadioButton.setChecked(parentEid != ROOT)
        seen = {selectedEid, self.selectedEntry.peid}
        self.buttons = (self.moveToTopRadioButton, self.grandParentRadioButton,
                        self.filteredRadioButton, self.circledRadioButton,
                        self.recentRadioButton)
        Forms.Util.setUpRadioButton(
            self, self.grandParentEntry, self.grandParentRadioButton,
            self.grandParentLabel, self.buttons, seen,
            """<p><b>under Grandparent</b></p>
<p>Move the current entry up under its grandparent “{}”.</p>""")
        Forms.Util.setUpRadioButton(
            self, self.filteredEntry, self.filteredRadioButton,
            self.filteredLabel, self.buttons, seen,
            """<p><b>under Filtered</b></p>
<p>Move the current entry under the filtered entry “{}”.</p>""")
        Forms.Util.setUpRadioButton(
            self, self.circledEntry, self.circledRadioButton,
            self.circledLabel, self.buttons, seen,
            """<p><b>under Circled</b></p>
<p>Move the current entry under the circled entry “{}”.</p>""")
        self.recentComboBox = Forms.Util.createTermsComboBox(
            self.state, self.state.gotoEids, ignore=seen, maximum=MAX_RECENT)
        if self.recentComboBox.count() and all(not radio.isChecked()
                                               for radio in self.buttons):
            self.recentRadioButton.setChecked(True)
            self.recentComboBox.setFocus()

        self.buttonBox = QDialogButtonBox()
        self.moveButton = QPushButton(QIcon(":/move.svg"), "M&ove")
        self.tooltips.append((self.moveButton, """<p><b>Move</b></p>
<p>Move the “{}” entry.</p>""".format(self.termLabel.text())))
        self.buttonBox.addButton(self.moveButton, QDialogButtonBox.AcceptRole)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel")
        self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p>
<p>Close the dialog without making any changes to the index.</p>"""))
        self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the Move Entry dialog"))
        self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)

    def layoutWidgets(self):
        layout = QVBoxLayout()
        entryLayout = QHBoxLayout()
        entryLayout.setSpacing(0)
        entryLayout.addWidget(self.entryLabel)
        entryLayout.addWidget(self.termLabel)
        entryLayout.addStretch()
        layout.addLayout(entryLayout)
        eidLayout = QVBoxLayout()
        eidLayout.addWidget(self.moveToTopRadioButton)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.grandParentRadioButton)
        hbox.addWidget(self.grandParentLabel, 1)
        eidLayout.addLayout(hbox)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.filteredRadioButton)
        hbox.addWidget(self.filteredLabel, 1)
        eidLayout.addLayout(hbox)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.circledRadioButton)
        hbox.addWidget(self.circledLabel, 1)
        eidLayout.addLayout(hbox)
        hbox = QHBoxLayout()
        hbox.setSpacing(0)
        hbox.addWidget(self.recentRadioButton)
        hbox.addWidget(self.recentComboBox, 1)
        eidLayout.addLayout(hbox)
        eidLayout.addStretch()
        self.eidGroup.setLayout(eidLayout)
        layout.addWidget(self.eidGroup)
        layout.addWidget(self.buttonBox)
        self.setLayout(layout)

    def createConnections(self):
        self.buttonBox.accepted.connect(self.move)
        self.buttonBox.rejected.connect(self.reject)
        self.helpButton.clicked.connect(self.help)
        self.recentRadioButton.toggled.connect(self.moveFocus)
        self.recentComboBox.currentIndexChanged[int].connect(
            self.recentChanged)

    def recentChanged(self):
        self.recentRadioButton.setChecked(True)
        self.updateUi()

    def moveFocus(self):
        if self.recentRadioButton.isChecked():
            self.recentComboBox.setFocus()

    def updateUi(self):
        self.recentRadioButton.setEnabled(self.recentComboBox.count())
        self.recentComboBox.setEnabled(self.recentComboBox.count())
        self.moveButton.setEnabled(
            any(button.isChecked() for button in self.buttons))

    def help(self):
        self.state.help("xix_ref_dlg_move.html")

    def move(self):
        self.state.maybeSave()
        eid = self.selectedEntry.eid
        if self.moveToTopRadioButton.isChecked():
            self.state.model.moveToTop(eid)
        else:
            peid = None
            if self.grandParentRadioButton.isChecked():
                peid = self.grandParentEntry.eid
                message = "move up"
            elif self.filteredRadioButton.isChecked():
                peid = self.filteredEntry.eid
                message = "move under filtered"
            elif self.circledRadioButton.isChecked():
                peid = self.circledEntry.eid
                message = "move under circled"
            elif self.recentRadioButton.isChecked():
                peid = self.recentComboBox.itemData(
                    self.recentComboBox.currentIndex())
                message = "move under recently visited"
            if peid is not None:  # Should always be True
                self.state.model.moveUnder(eid, peid, message)
                term = Lib.htmlToPlainText(self.state.model.term(eid))
                if peid == ROOT:
                    message = "Moved “{}” to be a main entry".format(term)
                else:
                    message = "Moved “{}” under “{}”".format(
                        term, Lib.htmlToPlainText(self.state.model.term(peid)))
                say(message, SAY_TIMEOUT)
        self.accept()
    def __init__(self, setting_dict):
        BasePane.__init__( self )

        networkLayout = QFormLayout()

        matchAlgorithmBox = QGroupBox()
        self.ccRadio = QRadioButton('Cross-correlation')
        self.dtwRadio = QRadioButton('DTW')
        self.dctRadio = QRadioButton('DCT')

        hbox = QHBoxLayout()
        hbox.addWidget(self.ccRadio)
        hbox.addWidget(self.dtwRadio)
        hbox.addWidget(self.dctRadio)
        matchAlgorithmBox.setLayout(hbox)

        networkLayout.addRow(QLabel('Similarity algorithm:'),matchAlgorithmBox)

        clusterBox = QGroupBox()
        self.completeRadio = QRadioButton('Complete')
        self.thresholdRadio = QRadioButton('Threshold')
        self.apRadio = QRadioButton('Affinity propagation')
        self.scRadio = QRadioButton('Spectral clustering')

        hbox = QHBoxLayout()
        hbox.addWidget(self.completeRadio)
        hbox.addWidget(self.thresholdRadio)
        hbox.addWidget(self.apRadio)
        hbox.addWidget(self.scRadio)
        clusterBox.setLayout(hbox)

        networkLayout.addRow(QLabel('Cluster algorithm:'),clusterBox)

        self.oneClusterCheck = QCheckBox()
        networkLayout.addRow(QLabel('Enforce single cluster:'),self.oneClusterCheck)

        self.thresholdEdit = QLineEdit()
        networkLayout.addRow(QLabel('Similarity threshold:'),self.thresholdEdit)

        self.setLayout(networkLayout)

        #set up defaults

        matchAlgorithm = setting_dict['dist_func']
        clustAlgorithm = setting_dict['cluster_alg']
        oneCluster = setting_dict['one_cluster']

        if matchAlgorithm == 'xcorr':
            self.ccRadio.setChecked(True)
        elif matchAlgorithm == 'dct':
            self.dctRadio.setChecked(True)
        else:
            self.dtwRadio.setChecked(True)

        if clustAlgorithm == 'complete':
            self.completeRadio.setChecked(True)
        elif clustAlgorithm == 'threshold':
            self.thresholdRadio.setChecked(True)
        elif clustAlgorithm == 'affinity':
            self.apRadio.setChecked(True)
        elif clustAlgorithm == 'spectral':
            self.scRadio.setChecked(True)

        if oneCluster:
            self.oneClusterCheck.setChecked(True)
        self.thresholdEdit.setText(str(setting_dict['threshold']))

        self.prev_state = setting_dict
class ServiceBrowser(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.serviceManager = QServiceManager(self)
        self.registerExampleServices()
        self.initWidgets()
        self.reloadServicesList()
        self.setWindowTitle(self.tr("Services Browser"))

    def __del__(self):
        self.unregisterExampleServices()

    def currentInterfaceImplChanged(self, current, previous):
        if not current:
            return

        descriptor = current.data(Qt.UserRole)
        self.reloadAttributesList()
        self.reloadAttributesRadioButtonText()
        if descriptor.isValid():
            self.defaultInterfaceButton.setText(
                self.tr("Set as default implementation for %s" %
                        str(descriptor.interfaceName())))
        self.defaultInterfaceButton.setEnabled(True)

    def reloadServicesList(self):
        self.servicesListWidget.clear()
        services = self.serviceManager.findServices()
        for serv in services:
            self.servicesListWidget.addItem(serv)

        self.servicesListWidget.addItem(self.showAllServicesItem)
        self._services = services

    def reloadInterfaceImplementationsList(self):
        serviceName = None
        allServices = self.servicesListWidget.currentItem().text(
        ) == self.showAllServicesItem.text()
        if self.servicesListWidget.currentItem() and not allServices:
            serviceName = self.servicesListWidget.currentItem().text()
            self.interfacesGroup.setTitle(
                self.tr("Interfaces implemented by %s" % str(serviceName)))
        else:
            self.interfacesGroup.setTitle(
                self.tr("All interface implementations"))

        descriptors = self.serviceManager.findInterfaces(serviceName)
        self.attributesListWidget.clear()
        self.interfacesListWidget.clear()
        self._i = []
        for desc in descriptors:
            text = "%s %d.%d" % (desc.interfaceName(), desc.majorVersion(),
                                 desc.minorVersion())

            if not serviceName:
                text += " (" + desc.serviceName() + ")"

            defaultInterfaceImpl = self.serviceManager.interfaceDefault(
                desc.interfaceName())
            if desc == defaultInterfaceImpl:
                text += self.tr(" (default)")

            item = QListWidgetItem(text)
            item.setData(Qt.UserRole, desc)
            item._data = desc
            self.interfacesListWidget.addItem(item)

        self.defaultInterfaceButton.setEnabled(False)

    def reloadAttributesList(self):
        item = self.interfacesListWidget.currentItem()
        if not item:
            return

        selectedImpl = item.data(Qt.UserRole)
        implementationRef = None
        if self.selectedImplRadioButton.isChecked():
            implementationRef = self.serviceManager.loadInterface(selectedImpl)
        else:
            implementationRef = self.serviceManager.loadInterface(
                selectedImpl.interfaceName())

        self.attributesListWidget.clear()
        if not implementationRef:
            self.attributesListWidget.addItem(
                self.tr("(Error loading service plugin)"))
            return

        metaObject = implementationRef.metaObject()
        self.attributesGroup.setTitle(
            self.tr("Invokable attributes for %s class" %
                    metaObject.className()))
        for i in range(metaObject.methodCount()):
            method = metaObject.method(i)
            self.attributesListWidget.addItem("[METHOD] " + method.signature())

        for i in range(metaObject.propertyCount()):
            p = metaObject.property(i)
            self.attributesListWidget.addItem("[PROPERTY] " + p.name())

    def setDefaultInterfaceImplementation(self):
        item = self.interfacesListWidget.currentItem()
        if not item:
            return

        descriptor = item.data(Qt.UserRole)
        if descriptor.isValid():
            if self.serviceManager.setInterfaceDefault(descriptor):
                currentIndex = self.interfacesListWidget.row(item)
                self.reloadInterfaceImplementationsList()
                self.interfacesListWidget.setCurrentRow(currentIndex)
            else:
                print "Unable to set default service for interface:", descriptor.interfaceName(
                )

    def registerExampleServices(self):
        exampleXmlFiles = [
            "filemanagerservice.xml", "bluetoothtransferservice.xml"
        ]
        for fileName in exampleXmlFiles:
            path = "./xmldata/" + fileName
            self.serviceManager.addService(path)

    def unregisterExampleServices(self):
        self.serviceManager.removeService("FileManagerService")
        self.serviceManager.removeService("BluetoothTransferService")

    def reloadAttributesRadioButtonText(self):
        item = self.interfacesListWidget.currentItem()
        if not item:
            return

        selectedImpl = item.data(Qt.UserRole)
        defaultImpl = self.serviceManager.interfaceDefault(
            selectedImpl.interfaceName())
        self.defaultImplRadioButton.setText(
            self.tr(
                "Default implementation for %s\n(currently provided by %s)" %
                (str(defaultImpl.interfaceName()),
                 str(defaultImpl.serviceName()))))

    def initWidgets(self):
        self.showAllServicesItem = QListWidgetItem(
            self.tr("(All registered services)"))
        self.servicesListWidget = QListWidget()
        self.interfacesListWidget = QListWidget()
        self.interfacesListWidget.addItem(self.tr("(Select a service)"))
        self.attributesListWidget = QListWidget()
        self.attributesListWidget.addItem(
            self.tr("(Select an interface implementation)"))
        self.interfacesListWidget.setMinimumWidth(450)
        self.servicesListWidget.currentItemChanged.connect(
            self.reloadInterfaceImplementationsList)
        self.interfacesListWidget.currentItemChanged.connect(
            self.currentInterfaceImplChanged)
        self.defaultInterfaceButton = QPushButton(
            self.tr("Set as default implementation"))
        self.defaultInterfaceButton.setEnabled(False)
        self.defaultInterfaceButton.clicked.connect(
            self.setDefaultInterfaceImplementation)
        self.selectedImplRadioButton = QRadioButton(
            self.tr("Selected interface implementation"))
        self.defaultImplRadioButton = QRadioButton(
            self.tr("Default implementation"))
        self.selectedImplRadioButton.setChecked(True)
        self.radioButtons = QButtonGroup(self)
        self.radioButtons.addButton(self.selectedImplRadioButton)
        self.radioButtons.addButton(self.defaultImplRadioButton)
        self.radioButtons.buttonClicked.connect(self.reloadAttributesList)

        self.servicesGroup = QGroupBox(self.tr("Show services for:"))
        servicesLayout = QVBoxLayout()
        servicesLayout.addWidget(self.servicesListWidget)
        self.servicesGroup.setLayout(servicesLayout)

        self.interfacesGroup = QGroupBox(self.tr("Interface implementations"))
        interfacesLayout = QVBoxLayout()
        interfacesLayout.addWidget(self.interfacesListWidget)
        interfacesLayout.addWidget(self.defaultInterfaceButton)
        self.interfacesGroup.setLayout(interfacesLayout)

        self.attributesGroup = QGroupBox(self.tr("Invokable attributes"))
        attributesLayout = QVBoxLayout()
        self.attributesGroup.setLayout(attributesLayout)
        attributesLayout.addWidget(self.attributesListWidget)
        attributesLayout.addWidget(QLabel(self.tr("Show attributes for:")))
        attributesLayout.addWidget(self.selectedImplRadioButton)
        attributesLayout.addWidget(self.defaultImplRadioButton)

        self.attributesGroup.setLayout(attributesLayout)

        layout = QGridLayout()
        layout.addWidget(self.servicesGroup, 0, 0)
        layout.addWidget(self.attributesGroup, 0, 1, 2, 1)
        layout.addWidget(self.interfacesGroup, 1, 0)

        self.setLayout(layout)
    def __init__(self, config, playerpaths, error):

        from syncplay import utils
        self.config = config
        self.datacleared = False
        if config['clearGUIData'] == True:
            settings = QSettings("Syncplay", "PlayerList")
            settings.clear()
            settings = QSettings("Syncplay", "MediaBrowseDialog")
            settings.clear()
            settings = QSettings("Syncplay", "MainWindow")
            settings.clear()
            settings = QSettings("Syncplay", "MoreSettings")
            settings.clear()
            self.datacleared = True
        self.QtGui = QtGui
        self.error = error
        if sys.platform.startswith('linux'):
            resourcespath = utils.findWorkingDir() + "/resources/"
        else:
            resourcespath = utils.findWorkingDir() + "\\resources\\"
        self.resourcespath = resourcespath

        super(ConfigDialog, self).__init__()

        self.setWindowTitle(getMessage("en", "config-window-title"))
        self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
        self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png"))

        if(config['host'] == None):
            host = ""
        elif(":" in config['host']):
            host = config['host']
        else:
            host = config['host'] + ":" + str(config['port'])

        self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title"))
        self.hostTextbox = QLineEdit(host, self)
        self.hostLabel = QLabel(getMessage("en", "host-label"), self)
        self.usernameTextbox = QLineEdit(config['name'], self)
        self.serverpassLabel = QLabel(getMessage("en", "password-label"), self)
        self.defaultroomTextbox = QLineEdit(config['room'], self)
        self.usernameLabel = QLabel(getMessage("en", "username-label"), self)
        self.serverpassTextbox = QLineEdit(config['password'], self)
        self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self)

        if (constants.SHOW_TOOLTIPS == True):
            self.hostLabel.setToolTip(getMessage("en", "host-tooltip"))
            self.hostTextbox.setToolTip(getMessage("en", "host-tooltip"))
            self.usernameLabel.setToolTip(getMessage("en", "username-tooltip"))
            self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip"))
            self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip"))
            self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip"))
            self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip"))
            self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip"))

        self.connectionSettingsLayout = QtGui.QGridLayout()
        self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0)
        self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1)
        self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0)
        self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1)
        self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0)
        self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1)
        self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0)
        self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1)
        self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout)

        self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title"))
        self.executableiconImage = QtGui.QImage()
        self.executableiconLabel = QLabel(self)
        self.executableiconLabel.setMinimumWidth(16)
        self.executablepathCombobox = QtGui.QComboBox(self)
        self.executablepathCombobox.setEditable(True)
        self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon)
        self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths))
        self.executablepathCombobox.setMinimumWidth(200)
        self.executablepathCombobox.setMaximumWidth(200)
        self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon)

        self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self)
        self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("en", "browse-label"))
        self.executablebrowseButton.clicked.connect(self.browsePlayerpath)
        self.mediapathTextbox = QLineEdit(config['file'], self)
        self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self)
        self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("en", "browse-label"))
        self.mediabrowseButton.clicked.connect(self.browseMediapath)

        if (constants.SHOW_TOOLTIPS == True):
            self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip"))
            self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip"))
            self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip"))
            self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip"))

        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label"))
            if (constants.SHOW_TOOLTIPS == True):
                self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip"))
        self.mediaplayerSettingsLayout = QtGui.QGridLayout()
        self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0)
        self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1)
        self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2)
        self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2)
        self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3)
        self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout)

        self.moreSettingsGroup = QtGui.QGroupBox(getMessage("en", "more-title"))

        self.moreSettingsGroup.setCheckable(True)

        self.filenameprivacyLabel = QLabel(getMessage("en", "filename-privacy-label"), self)
        self.filenameprivacyButtonGroup = QButtonGroup()
        self.filenameprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option"))
        self.filenameprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option"))
        self.filenameprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option"))
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption)

        self.filesizeprivacyLabel = QLabel(getMessage("en", "filesize-privacy-label"), self)
        self.filesizeprivacyButtonGroup = QButtonGroup()
        self.filesizeprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option"))
        self.filesizeprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option"))
        self.filesizeprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option"))
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption)

        self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label"))
        self.dontslowwithmeCheckbox = QCheckBox(getMessage("en", "dontslowwithme-label"))
        self.pauseonleaveCheckbox = QCheckBox(getMessage("en", "pauseonleave-label"))
        self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label"))
        self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label"))

        filenamePrivacyMode = config['filenamePrivacyMode']
        if filenamePrivacyMode == constants.PRIVACY_DONTSEND_MODE:
            self.filenameprivacyDontSendOption.setChecked(True)
        elif filenamePrivacyMode == constants.PRIVACY_SENDHASHED_MODE:
            self.filenameprivacySendHashedOption.setChecked(True)
        else:
            self.filenameprivacySendRawOption.setChecked(True)

        filesizePrivacyMode = config['filesizePrivacyMode']
        if filesizePrivacyMode == constants.PRIVACY_DONTSEND_MODE:
            self.filesizeprivacyDontSendOption.setChecked(True)
        elif filesizePrivacyMode == constants.PRIVACY_SENDHASHED_MODE:
            self.filesizeprivacySendHashedOption.setChecked(True)
        else:
            self.filesizeprivacySendRawOption.setChecked(True)

        if config['slowOnDesync'] == True:
            self.slowdownCheckbox.setChecked(True)
        if config['dontSlowDownWithMe'] == True:
            self.dontslowwithmeCheckbox.setChecked(True)

        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True:
            self.rewindCheckbox.setChecked(True)
        if config['pauseOnLeave'] == True:
            self.pauseonleaveCheckbox.setChecked(True)

        if (constants.SHOW_TOOLTIPS == True):
            self.filenameprivacyLabel.setToolTip(getMessage("en", "filename-privacy-tooltip"))
            self.filenameprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip"))
            self.filenameprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip"))
            self.filenameprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip"))
            self.filesizeprivacyLabel.setToolTip(getMessage("en", "filesize-privacy-tooltip"))
            self.filesizeprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip"))
            self.filesizeprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip"))
            self.filesizeprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip"))

            self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip"))
            self.dontslowwithmeCheckbox.setToolTip(getMessage("en", "dontslowwithme-tooltip"))
            self.pauseonleaveCheckbox.setToolTip(getMessage("en", "pauseonleave-tooltip"))
            self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip"))
            self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip"))
            self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip"))

        self.moreSettingsLayout = QtGui.QGridLayout()

        self.privacySettingsLayout = QtGui.QGridLayout()
        self.privacyFrame = QtGui.QFrame()
        self.privacyFrame.setLineWidth(0)
        self.privacyFrame.setMidLineWidth(0)
        self.privacySettingsLayout.setContentsMargins(0, 0, 0, 0)
        self.privacySettingsLayout.addWidget(self.filenameprivacyLabel, 0, 0)
        self.privacySettingsLayout.addWidget(self.filenameprivacySendRawOption, 0, 1, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filenameprivacySendHashedOption, 0, 2, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filenameprivacyDontSendOption, 0, 3, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacyLabel, 1, 0)
        self.privacySettingsLayout.addWidget(self.filesizeprivacySendRawOption, 1, 1, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 1, 2, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 1, 3, Qt.AlignRight)
        self.privacyFrame.setLayout(self.privacySettingsLayout)

        self.moreSettingsLayout.addWidget(self.privacyFrame, 0, 0, 1, 4)

        self.moreSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.dontslowwithmeCheckbox, 3, 0, 1, 4)
        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            self.moreSettingsLayout.addWidget(self.rewindCheckbox, 4, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.pauseonleaveCheckbox, 5, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.alwaysshowCheckbox, 6, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.donotstoreCheckbox, 7, 0, 1, 4)

        self.moreSettingsGroup.setLayout(self.moreSettingsLayout)

        self.showmoreCheckbox = QCheckBox(getMessage("en", "more-title"))

        if self.getMoreState() == False:
            self.showmoreCheckbox.setChecked(False)
            self.moreSettingsGroup.hide()
        else:
            self.showmoreCheckbox.hide()
        self.showmoreCheckbox.toggled.connect(self.moreToggled)
        self.moreSettingsGroup.toggled.connect(self.moreToggled)

        if config['forceGuiPrompt'] == True:
            self.alwaysshowCheckbox.setChecked(True)

        if (constants.SHOW_TOOLTIPS == True):
            self.showmoreCheckbox.setToolTip(getMessage("en", "more-tooltip"))

        self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate)

        self.mainLayout = QtGui.QVBoxLayout()
        if error:
            self.errorLabel = QLabel(error, self)
            self.errorLabel.setAlignment(Qt.AlignCenter)
            self.errorLabel.setStyleSheet("QLabel { color : red; }")
            self.mainLayout.addWidget(self.errorLabel)
        self.mainLayout.addWidget(self.connectionSettingsGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.mediaplayerSettingsGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.showmoreCheckbox)
        self.mainLayout.addWidget(self.moreSettingsGroup)
        self.mainLayout.addSpacing(12)

        self.topLayout = QtGui.QHBoxLayout()
        self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'), getMessage("en", "help-label"))
        if (constants.SHOW_TOOLTIPS == True):
            self.helpButton.setToolTip(getMessage("en", "help-tooltip"))
        self.helpButton.setMaximumSize(self.helpButton.sizeHint())
        self.helpButton.pressed.connect(self.openHelp)
        self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'), getMessage("en", "storeandrun-label"))
        self.runButton.pressed.connect(self._saveDataAndLeave)
        if config['noStore'] == True:
            self.donotstoreCheckbox.setChecked(True)
            self.runButton.setText(getMessage("en", "run-label"))
        self.topLayout.addWidget(self.helpButton, Qt.AlignLeft)
        self.topLayout.addWidget(self.runButton, Qt.AlignRight)
        self.mainLayout.addLayout(self.topLayout)

        self.mainLayout.addStretch(1)
        self.setLayout(self.mainLayout)
        self.runButton.setFocus()
        self.setFixedSize(self.sizeHint())
        self.setAcceptDrops(True)

        if self.datacleared == True:
            QtGui.QMessageBox.information(self, "Syncplay", getMessage("en", "gui-data-cleared-notification"))
Exemple #47
0
    def __init__(self, config, playerpaths, error):
        
        from syncplay import utils
        self.config = config
        self.datacleared = False
        if config['clearGUIData'] == True:
            settings = QSettings("Syncplay","PlayerList")
            settings.clear()
            settings = QSettings("Syncplay","MediaBrowseDialog")
            settings.clear()
            settings = QSettings("Syncplay","MainWindow")
            settings.clear()
            settings = QSettings("Syncplay","MoreSettings")
            settings.clear()
            self.datacleared = True
        self.QtGui = QtGui
        self.error = error
        if sys.platform.startswith('linux'):
            resourcespath = utils.findWorkingDir() + "/resources/"
        else:
            resourcespath = utils.findWorkingDir() + "\\resources\\"
        self.resourcespath = resourcespath

        super(ConfigDialog, self).__init__()
        
        self.setWindowTitle(getMessage("en", "config-window-title"))
        self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
        self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png"))
              
        if(config['host'] == None):
            host = ""
        elif(":" in config['host']):
            host = config['host']
        else:
            host = config['host']+":"+str(config['port'])
            
        self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title"))
        self.hostTextbox = QLineEdit(host, self)
        self.hostLabel = QLabel(getMessage("en", "host-label"), self)
        self.usernameTextbox = QLineEdit(config['name'],self)
        self.serverpassLabel = QLabel(getMessage("en", "password-label"), self)
        self.defaultroomTextbox = QLineEdit(config['room'],self)
        self.usernameLabel = QLabel(getMessage("en", "username-label"), self)
        self.serverpassTextbox = QLineEdit(config['password'],self)
        self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self)

        if (constants.SHOW_TOOLTIPS == True):
            self.hostLabel.setToolTip(getMessage("en", "host-tooltip"))
            self.hostTextbox.setToolTip(getMessage("en", "host-tooltip"))
            self.usernameLabel.setToolTip(getMessage("en", "username-tooltip"))
            self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip"))
            self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip"))
            self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip"))
            self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip"))
            self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip"))
            
        self.connectionSettingsLayout = QtGui.QGridLayout()
        self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0)
        self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1)
        self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0)
        self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1)
        self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0)
        self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1)
        self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0)
        self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1)
        self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout)
        
        self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title"))
        self.executableiconImage = QtGui.QImage()
        self.executableiconLabel = QLabel(self)
        self.executableiconLabel.setMinimumWidth(16)
        self.executablepathCombobox = QtGui.QComboBox(self)
        self.executablepathCombobox.setEditable(True)
        self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon)
        self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths))
        self.executablepathCombobox.setMinimumWidth(200)
        self.executablepathCombobox.setMaximumWidth(200)
        self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon)
        
        self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self)
        self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label"))
        self.executablebrowseButton.clicked.connect(self.browsePlayerpath)
        self.mediapathTextbox = QLineEdit(config['file'], self)
        self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self)
        self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label"))
        self.mediabrowseButton.clicked.connect(self.browseMediapath)
        
        if (constants.SHOW_TOOLTIPS == True):
            self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip"))
            self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip"))
            self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip"))
            self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip"))
        
        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label"))
            if (constants.SHOW_TOOLTIPS == True):
                self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip"))
        self.mediaplayerSettingsLayout = QtGui.QGridLayout()
        self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0)
        self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1)
        self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2)
        self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2)
        self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3)
        self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout)

        self.moreSettingsGroup = QtGui.QGroupBox(getMessage("en", "more-title"))

        self.moreSettingsGroup.setCheckable(True)
        self.malSettingsSplit = QtGui.QSplitter(self)
        self.malusernameTextbox = QLineEdit(config['malUsername'],self)
        self.malusernameTextbox.setMaximumWidth(115)
        self.malusernameLabel = QLabel(getMessage("en", "mal-username-label"), self)
        
        self.malpasswordTextbox = QLineEdit(config['malPassword'],self)
        self.malpasswordTextbox.setEchoMode(QtGui.QLineEdit.Password)
        self.malpasswordLabel = QLabel(getMessage("en", "mal-password-label"), self)
        
        ### <MAL DISABLE>
        self.malpasswordTextbox.hide()
        self.malpasswordLabel.hide()
        self.malusernameTextbox.hide()
        self.malusernameLabel.hide()
        ### </MAL DISABLE>
        
        self.filenameprivacyLabel = QLabel(getMessage("en", "filename-privacy-label"), self)
        self.filenameprivacyButtonGroup = QButtonGroup()
        self.filenameprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option"))
        self.filenameprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option"))
        self.filenameprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option"))
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption)
        
        self.filesizeprivacyLabel = QLabel(getMessage("en", "filesize-privacy-label"), self)
        self.filesizeprivacyButtonGroup = QButtonGroup()
        self.filesizeprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option"))
        self.filesizeprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option"))
        self.filesizeprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option"))
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption)
        
        self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label"))
        self.pauseonleaveCheckbox = QCheckBox(getMessage("en", "pauseonleave-label"))
        self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label"))
        self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label"))
        
        filenamePrivacyMode = config['filenamePrivacyMode']
        if filenamePrivacyMode == constants.PRIVACY_DONTSEND_MODE:
            self.filenameprivacyDontSendOption.setChecked(True)
        elif filenamePrivacyMode == constants.PRIVACY_SENDHASHED_MODE:
            self.filenameprivacySendHashedOption.setChecked(True)
        else:
            self.filenameprivacySendRawOption.setChecked(True)
            
        filesizePrivacyMode = config['filesizePrivacyMode']
        if filesizePrivacyMode == constants.PRIVACY_DONTSEND_MODE:
            self.filesizeprivacyDontSendOption.setChecked(True)
        elif filesizePrivacyMode == constants.PRIVACY_SENDHASHED_MODE:
            self.filesizeprivacySendHashedOption.setChecked(True)
        else:
            self.filesizeprivacySendRawOption.setChecked(True)
        
        if config['slowOnDesync'] == True:
            self.slowdownCheckbox.setChecked(True)
        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True:
            self.rewindCheckbox.setChecked(True)
        if config['pauseOnLeave'] == True:
            self.pauseonleaveCheckbox.setChecked(True)
        
        if (constants.SHOW_TOOLTIPS == True):
            self.malusernameLabel.setToolTip(getMessage("en", "mal-username-tooltip"))
            self.malusernameTextbox.setToolTip(getMessage("en", "mal-username-tooltip"))
            self.malpasswordLabel.setToolTip(getMessage("en", "mal-password-tooltip"))
            self.malpasswordTextbox.setToolTip(getMessage("en", "mal-password-tooltip"))
            
            self.filenameprivacyLabel.setToolTip(getMessage("en", "filename-privacy-tooltip"))
            self.filenameprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip"))
            self.filenameprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip"))
            self.filenameprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip"))
            self.filesizeprivacyLabel.setToolTip(getMessage("en", "filesize-privacy-tooltip"))
            self.filesizeprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip"))
            self.filesizeprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip"))
            self.filesizeprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip"))
            
            self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip"))
            self.pauseonleaveCheckbox.setToolTip(getMessage("en", "pauseonleave-tooltip"))
            self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip"))
            self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip"))
            self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip"))
            
        self.moreSettingsLayout = QtGui.QGridLayout()
        
        self.privacySettingsLayout = QtGui.QGridLayout()
        self.privacyFrame = QtGui.QFrame()
        self.privacyFrame.setLineWidth(0)
        self.privacyFrame.setMidLineWidth(0)
        self.privacySettingsLayout.setContentsMargins(0,0,0,0)
        self.privacySettingsLayout.addWidget(self.filenameprivacyLabel, 0, 0)
        self.privacySettingsLayout.addWidget(self.filenameprivacySendRawOption, 0, 1, Qt.AlignRight) 
        self.privacySettingsLayout.addWidget(self.filenameprivacySendHashedOption, 0,2, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filenameprivacyDontSendOption, 0, 3, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacyLabel, 1, 0)
        self.privacySettingsLayout.addWidget(self.filesizeprivacySendRawOption, 1, 1, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 1, 2, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 1, 3, Qt.AlignRight)
        self.privacyFrame.setLayout(self.privacySettingsLayout)
        
        self.moreSettingsLayout.addWidget(self.privacyFrame, 0, 0, 1, 4)

        self.moreSettingsLayout.addWidget(self.malusernameLabel , 1, 0)
        self.moreSettingsLayout.addWidget(self.malusernameTextbox, 1, 1)
        self.moreSettingsLayout.addWidget(self.malpasswordLabel , 1, 2)
        self.moreSettingsLayout.addWidget(self.malpasswordTextbox, 1, 3)

        self.moreSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0,1,4)
        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            self.moreSettingsLayout.addWidget(self.rewindCheckbox, 3, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.pauseonleaveCheckbox, 4, 0, 1, 4)      
        self.moreSettingsLayout.addWidget(self.alwaysshowCheckbox, 5, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.donotstoreCheckbox, 6, 0, 1, 4)

        self.moreSettingsGroup.setLayout(self.moreSettingsLayout)
        
        self.showmoreCheckbox = QCheckBox(getMessage("en", "more-title"))
        
        if self.getMoreState() == False:
            self.showmoreCheckbox.setChecked(False)
            self.moreSettingsGroup.hide()
        else:
            self.showmoreCheckbox.hide()
        self.showmoreCheckbox.toggled.connect(self.moreToggled)            
        self.moreSettingsGroup.toggled.connect(self.moreToggled)
        
        if config['forceGuiPrompt'] == True:
            self.alwaysshowCheckbox.setChecked(True)
        
        if (constants.SHOW_TOOLTIPS == True):
            self.showmoreCheckbox.setToolTip(getMessage("en", "more-tooltip"))
               
        self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate)
                      
        self.mainLayout = QtGui.QVBoxLayout()
        if error:
            self.errorLabel = QLabel(error, self)
            self.errorLabel.setAlignment(Qt.AlignCenter)
            self.errorLabel.setStyleSheet("QLabel { color : red; }")
            self.mainLayout.addWidget(self.errorLabel)
        self.mainLayout.addWidget(self.connectionSettingsGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.mediaplayerSettingsGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.showmoreCheckbox)
        self.mainLayout.addWidget(self.moreSettingsGroup)
        self.mainLayout.addSpacing(12)
        
        self.topLayout = QtGui.QHBoxLayout()
        self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'),getMessage("en", "help-label"))
        if (constants.SHOW_TOOLTIPS == True):
            self.helpButton.setToolTip(getMessage("en", "help-tooltip"))
        self.helpButton.setMaximumSize(self.helpButton.sizeHint())
        self.helpButton.pressed.connect(self.openHelp)
        self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'),getMessage("en", "storeandrun-label"))
        self.runButton.pressed.connect(self._saveDataAndLeave)
        if config['noStore'] == True:
            self.donotstoreCheckbox.setChecked(True)
            self.runButton.setText(getMessage("en", "run-label"))
        self.topLayout.addWidget(self.helpButton, Qt.AlignLeft)
        self.topLayout.addWidget(self.runButton, Qt.AlignRight)
        self.mainLayout.addLayout(self.topLayout)
        
        self.mainLayout.addStretch(1)
        self.setLayout(self.mainLayout)
        self.runButton.setFocus()        
        self.setFixedSize(self.sizeHint())
        self.setAcceptDrops(True)
        
        if self.datacleared == True:
            QtGui.QMessageBox.information(self,"Syncplay", getMessage("en", "gui-data-cleared-notification"))
class NetworkPane(BasePane):
    def __init__(self, setting_dict):
        BasePane.__init__( self )

        networkLayout = QFormLayout()

        matchAlgorithmBox = QGroupBox()
        self.ccRadio = QRadioButton('Cross-correlation')
        self.dtwRadio = QRadioButton('DTW')
        self.dctRadio = QRadioButton('DCT')

        hbox = QHBoxLayout()
        hbox.addWidget(self.ccRadio)
        hbox.addWidget(self.dtwRadio)
        hbox.addWidget(self.dctRadio)
        matchAlgorithmBox.setLayout(hbox)

        networkLayout.addRow(QLabel('Similarity algorithm:'),matchAlgorithmBox)

        clusterBox = QGroupBox()
        self.completeRadio = QRadioButton('Complete')
        self.thresholdRadio = QRadioButton('Threshold')
        self.apRadio = QRadioButton('Affinity propagation')
        self.scRadio = QRadioButton('Spectral clustering')

        hbox = QHBoxLayout()
        hbox.addWidget(self.completeRadio)
        hbox.addWidget(self.thresholdRadio)
        hbox.addWidget(self.apRadio)
        hbox.addWidget(self.scRadio)
        clusterBox.setLayout(hbox)

        networkLayout.addRow(QLabel('Cluster algorithm:'),clusterBox)

        self.oneClusterCheck = QCheckBox()
        networkLayout.addRow(QLabel('Enforce single cluster:'),self.oneClusterCheck)

        self.thresholdEdit = QLineEdit()
        networkLayout.addRow(QLabel('Similarity threshold:'),self.thresholdEdit)

        self.setLayout(networkLayout)

        #set up defaults

        matchAlgorithm = setting_dict['dist_func']
        clustAlgorithm = setting_dict['cluster_alg']
        oneCluster = setting_dict['one_cluster']

        if matchAlgorithm == 'xcorr':
            self.ccRadio.setChecked(True)
        elif matchAlgorithm == 'dct':
            self.dctRadio.setChecked(True)
        else:
            self.dtwRadio.setChecked(True)

        if clustAlgorithm == 'complete':
            self.completeRadio.setChecked(True)
        elif clustAlgorithm == 'threshold':
            self.thresholdRadio.setChecked(True)
        elif clustAlgorithm == 'affinity':
            self.apRadio.setChecked(True)
        elif clustAlgorithm == 'spectral':
            self.scRadio.setChecked(True)

        if oneCluster:
            self.oneClusterCheck.setChecked(True)
        self.thresholdEdit.setText(str(setting_dict['threshold']))

        self.prev_state = setting_dict

    def get_current_state(self):
        setting_dict = {}

        if self.ccRadio.isChecked():
            setting_dict['dist_func'] = 'xcorr'
        elif self.dctRadio.isChecked():
            setting_dict['dist_func'] = 'dct'
        elif self.dtwRadio.isChecked():
            setting_dict['dist_func'] = 'dtw'

        if self.completeRadio.isChecked():
            setting_dict['cluster_alg'] = 'complete'
        elif self.thresholdRadio.isChecked():
            setting_dict['cluster_alg'] = 'threshold'
        elif self.apRadio.isChecked():
            setting_dict['cluster_alg'] = 'affinity'
        elif self.scRadio.isChecked():
            setting_dict['cluster_alg'] = 'spectral'

        setting_dict['one_cluster'] = int(self.oneClusterCheck.isChecked())
        setting_dict['threshold'] = float(self.thresholdEdit.text())

        return setting_dict

    def is_changed(self):
        cur_state = self.get_current_state()
        if self.prev_state['dist_func'] != cur_state['dist_func']:
            return True
        return False
        for k in ['dist_func','cluster_alg']:
            if self.prev_state[k] != cur_state[k]:
                return True
        if cur_state['cluster_alg'] == 'threshold':
            if self.prev_state['threshold'] != cur_state['threshold']:
                return True
        elif cur_state['cluster_alg'] in {'affinity','spectral'}:
            if self.prev_state['one_cluster'] != cur_state['one_cluster']:
                return True
        return False
Exemple #49
0
class PostViewWidget(HorsePanel):
    def __init__(self, parent, order_overview_widget, find_order_slot):
        global configuration

        super(PostViewWidget, self).__init__(parent)

        self.set_panel_title(_("Post overview"))
        self.bold_font = QFont(self.font())
        self.bold_font.setBold(True)
        self.nb_cols = 8  # Number of columns in the operation definition table

        self.order_overview_widget = order_overview_widget

        self.button = QPushButton(_("Refresh"), self)
        self.button.clicked.connect(self.refresh_action)
        self.sort_by_deadline_button = QRadioButton(_("By deadline"), self)
        self.sort_by_deadline_button.toggled.connect(self.sort_by_deadline)
        self.sort_by_size_button = QRadioButton(_("By hours left to do"), self)
        self.sort_by_size_button.toggled.connect(self.sort_by_size)

        # hlayout = QHBoxLayout()
        # hlayout.setObjectName("halyout")
        # hlayout.setContentsMargins(0,0,0,0)
        # hlayout.addWidget(self.sort_by_deadline_button)
        # hlayout.addWidget(self.sort_by_size_button)
        # hlayout.addWidget(self.button)
        # hlayout.addStretch()

        self.navbar = NavBar(self, [(self.sort_by_deadline_button, None),
                                    (self.sort_by_size_button, None),
                                    (self.button, None),
                                    (_("Find"), find_order_slot)])
        self.navbar.buttons[3].setObjectName("specialMenuButton")

        self.vlayout = QVBoxLayout(self)
        self.vlayout.setObjectName("Vlayout")
        self.vlayout.addWidget(
            TitleWidget(_("Posts Overview"), self, self.navbar))

        self._table_model = QStandardItemModel(1, self.nb_cols, self)
        self.table_view = QTableView(None)
        self.table_view.setModel(self._table_model)
        self.table_view.selectionModel().currentChanged.connect(
            self.operation_selected)

        self.table_view.verticalHeader().hide()
        self.table_view.horizontalHeader().hide()
        self.table_view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows)

        # This forces Qt to expand layout once I fill data in
        # FIXME dirty but I really don't get why setting
        # the mini width to something smaller (that happens at
        # startup, on first refresh) doesn't work
        self.table_view.setMinimumWidth(1)
        self.table_view.setMaximumWidth(1)

        self.post_view_scene = PostViewScene(self, order_overview_widget)
        self.post_view_scene_view = QGraphicsView(self)
        self.post_view_scene_view.setScene(self.post_view_scene)
        self.post_view_scene_view.setSizePolicy(QSizePolicy.Expanding,
                                                QSizePolicy.Expanding)

        self.splitter = QSplitter(Qt.Horizontal)
        self.splitter.addWidget(
            SubFrame(_("Posts"), self.table_view, self.splitter))
        self.splitter.addWidget(
            SubFrame(_("Workload"), self.post_view_scene_view, self.splitter))
        # self.splitter.setStretchFactor(0,1)
        self.splitter.setStretchFactor(1, 1)
        self.vlayout.addWidget(self.splitter)

        # hlayout = QHBoxLayout()
        # hlayout.addWidget(SubFrame(_("Posts"),self.table_view,self))
        # hlayout.addWidget(SubFrame(_("Workload"),self.post_view_scene_view,self))
        # hlayout.setStretch(1,1)
        # self.vlayout.addLayout(hlayout)

        self.vlayout.setStretch(0, 0)
        self.vlayout.setStretch(1, 1)

        self.setLayout(self.vlayout)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.slidePostsScene)

        self.current_view_y = 0

    def _data_load(self):
        global dao

        all_operations = dao.operation_dao.load_all_operations_ready_for_production(
        )
        operation_definitions = dao.operation_definition_dao.all_direct_frozen(
        )

        return operation_definitions, all_operations

    def _reset_operation_definitions(self, operations):
        self._table_model.setColumnCount(1)
        self._table_model.setRowCount(len(operations))

        # BUG This should be refreshed on reload() too

        row = col = 0
        first_active = None

        for opdef in operations:

            if opdef.operation_definition_id in self.post_view_scene.drawn_operations_data:
                # currently total planned time
                t = self.post_view_scene.drawn_operations_data[
                    opdef.operation_definition_id]
                ndx = self._table_model.index(row, col)
                if not first_active:
                    first_active = ndx
                self._table_model.setData(
                    ndx, u"{} {}".format(opdef.description, t), Qt.DisplayRole)
                # self._table_model.setData(ndx,self.bold_font,Qt.FontRole)

                self._table_model.setData(self._table_model.index(row, col),
                                          opdef.operation_definition_id,
                                          Qt.UserRole)
                row += 1

            else:
                pass
                # self._table_model.setData(self._table_model.index(row,col),opdef.description,Qt.DisplayRole)

            # = col + 1
            # if col == self.nb_cols:
            #     col = 0
            #     row += 1

        self._table_model.setRowCount(row)

        # self.table_view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        # self.vlayout.setStretch(0,0)
        # self.vlayout.setStretch(1,10)
        # self.vlayout.setStretch(2,10000)

        # height = 0
        # for c in range(self.table_view.model().rowCount()):
        #     height += self.table_view.rowHeight(c) + 1 # +1 for cell border
        # self.table_view.setMinimumHeight(height)
        # self.table_view.setMaximumHeight(height)
        for i in range(self.nb_cols):
            self.table_view.resizeColumnToContents(i)
        self.table_view.setMaximumWidth(self.table_view.columnWidth(0))
        self.table_view.setMinimumWidth(self.table_view.columnWidth(0))
        self.table_view.setSizePolicy(QSizePolicy.Maximum,
                                      QSizePolicy.Preferred)

        self.table_view.update()
        self.splitter.update()

        return first_active

    def slide_to_operation(self, opdef_id):
        if opdef_id in self.post_view_scene.posts_offsets:
            self.slide_target_opdef_id = opdef_id
            # mainlog.debug("Target y = {}".format(self.post_view_scene.posts_offsets[self.slide_target_opdef]))
            self.timer.start(20)

    @Slot()
    def slidePostsScene(self):
        if self.slide_target_opdef_id is None:
            return

        # self.post_view_scene_view
        self.post_view_scene.set_cursor_on(
            self.slide_target_opdef_id
        )  # This done here also aviod some screen trashing

        v = self.post_view_scene_view.verticalScrollBar().value()
        # mainlog.debug( "slidePostsScene : {}".format(v))

        r = self.post_view_scene.posts_offsets[self.slide_target_opdef_id]
        target_y = r.y() + r.height() / 2
        delta = (target_y - self.current_view_y) * 0.4
        self.current_view_y = self.current_view_y + delta
        self.post_view_scene_view.centerOn(0, self.current_view_y)
        # mainlog.debug( "slidePostsScene : {} / {}".format(target_y, self.current_view_y))

        if self.post_view_scene_view.verticalScrollBar().value() == v:
            # Close enough => stop moving
            # FIXME not correct because we must stop when the view stops moving, not when the goal we set for centerOn is reached
            self.timer.stop()

    @Slot(QModelIndex, QModelIndex)
    def operation_selected(self, ndx_cur, ndx_old):
        if ndx_cur.isValid():
            opdef = self._table_model.data(ndx_cur, Qt.UserRole)
            if opdef:
                self.slide_to_operation(
                    self._table_model.data(ndx_cur, Qt.UserRole))

    @Slot()
    def refresh_action(self):
        # FIXME reload operations as well

        operation_definitions, all_operations = self._data_load()

        # mainlog.debug("reload")
        if self.sort_by_deadline_button.isChecked():
            self.post_view_scene.reload(self, operation_definitions,
                                        all_operations, 1)
        elif self.sort_by_size_button.isChecked():
            self.post_view_scene.reload(self, operation_definitions,
                                        all_operations, 2)
        else:
            self.post_view_scene.reload(self, operation_definitions,
                                        all_operations, 0)

        # mainlog.debug("reset")
        first_active = self._reset_operation_definitions(operation_definitions)
        # self.table_view.selectionModel().currentChanged.connect(self.operation_selected)
        if first_active:
            self.table_view.setCurrentIndex(first_active)

        # mainlog.debug("done reset")

    @Slot(bool)
    def sort_by_deadline(self, checked):
        if checked:
            self.refresh_action()

    @Slot(bool)
    def sort_by_size(self, checked):
        if checked:
            self.refresh_action()

    order_part_double_clicked = Signal(int)

    # Callback that will be called by HooverBar
    def set_on_order_part(self, order_part_id):
        self.order_part_double_clicked.emit(order_part_id)
class OptionsContainer(QWidget):
    def __init__(self,main_window):
        QWidget.__init__(self)
        self.main_window = main_window
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        
        self.lr = numpy.zeros(2)
        
        self.fps = QSpinBox()
        self.fps.setValue(25)
        self.fps.setMinimum(1)
        self.fps.setMaximum(1000)
        self.layout.addWidget(QLabel("FPS:"),10,10)
        self.layout.addWidget(self.fps,10,11)
        
        self.capture_area_group = QButtonGroup()
        self.capture_area_fs = QRadioButton("Full Screen")
        self.connect(self.capture_area_fs, SIGNAL("clicked()"),self.capture_area_change)
        self.capture_area_fs.setChecked(True)
        self.capture_area_sa = QRadioButton("Selected Area")
        self.connect(self.capture_area_sa, SIGNAL("clicked()"),self.capture_area_change)
        self.capture_area_group.addButton(self.capture_area_fs)
        self.capture_area_group.addButton(self.capture_area_sa)
        self.capture_area_group.setExclusive(True)
        
        self.layout.addWidget(self.capture_area_fs,12,10)
        self.layout.addWidget(self.capture_area_sa,12,11)
        
        self.sa_group = QGroupBox()
        self.sa_grid = QGridLayout()
        self.sa_group.setLayout(self.sa_grid)
        
        
        self.sa_ul_bt = QPushButton("Select Upper Left")
        self.connect(self.sa_ul_bt, SIGNAL("clicked()"), self.select_ul)
        self.sa_lr_bt = QPushButton("Select Lower Right")
        self.connect(self.sa_lr_bt, SIGNAL("clicked()"), self.select_lr)

        self.sa_x = QSpinBox()
        self.sa_y = QSpinBox()
        self.sa_w = QSpinBox()
        self.sa_h = QSpinBox()
        for sb in [self.sa_h,self.sa_w,self.sa_x,self.sa_y]:
            sb.setMaximum(999999)
            sb.setMinimum(0)
        
        self.sa_grid.addWidget(self.sa_ul_bt,14,10,1,1)
        self.sa_grid.addWidget(self.sa_lr_bt,15,10,1,1)
        self.sa_grid.addWidget(QLabel("x"),14,11,1,1)
        self.sa_grid.addWidget(self.sa_x,14,12,1,1)
        self.sa_grid.addWidget(QLabel("y"),15,11,1,1)
        self.sa_grid.addWidget(self.sa_y,15,12,1,1)
        self.sa_grid.addWidget(QLabel("w"),16,11,1,1)
        self.sa_grid.addWidget(self.sa_w,16,12,1,1)
        self.sa_grid.addWidget(QLabel("h"),17,11,1,1)
        self.sa_grid.addWidget(self.sa_h,17,12,1,1)
        
        self.sa_show_bt = QPushButton("Show Area")
        self.sa_show_bt.setCheckable(True)
        self.connect(self.sa_show_bt, SIGNAL("clicked()"), self.show_selected_area)

        
        self.sa_grid.addWidget(self.sa_show_bt,18,10,1,10)
        
        self.sa_group.hide()
        
        self.layout.addWidget(self.sa_group,14,10,1,10)
        
        self.capture_delay = QSpinBox()
        self.capture_delay.setMinimum(0)
        self.capture_delay.setMaximum(10000)
        
        self.layout.addWidget(QLabel("Capture Delay"),18,10,1,1)
        self.layout.addWidget(self.capture_delay,18,11,1,1)
        
        self.capture_bt = QPushButton("Capture")
        self.stop_capture_bt = QPushButton("Stop")
        self.stop_capture_bt.hide()
        self.layout.addWidget(self.capture_bt,20,10,1,10)
        self.layout.addWidget(self.stop_capture_bt,30,10,1,10)
        
        self.ffmpeg_flags = QLineEdit()
        self.ffmpeg_flags.setText("-qscale 0 -vcodec mpeg4")
        self.layout.addWidget(QLabel("FFMPEG Flags:"),40,10)
        self.layout.addWidget(self.ffmpeg_flags,50,10,1,10)
        
        self.encode_bt = QPushButton("Encode Video")
        self.layout.addWidget(self.encode_bt,60,10,1,10)
        
        self.open_dir_bt = QPushButton("Open Directory")
        self.layout.addWidget(self.open_dir_bt,80,10,1,10)
        
        self.connect(self.open_dir_bt, SIGNAL("clicked()"),self.open_cwd)
    
        self.selected_area = SelectedArea()
    
    def show_selected_area(self):
        x = self.sa_x.value()
        y = self.sa_y.value()
        w = self.sa_w.value()
        h = self.sa_h.value()
        
        self.selected_area.setGeometry(x,y,w,h)
        self.selected_area.activateWindow()
        self.selected_area.raise_()
        if(self.sa_show_bt.isChecked()):
            self.selected_area.show()
        else:self.selected_area.hide()
        
    def select_ul(self):
        print "select_ul"
        self.clicked  = False
        self.tw = TransWindow()
        self.tw.mouse_press = False
        self.tw.show()
        
        self.connect(self.tw, SIGNAL("mouse_press()"),self.set_ul)
        
    def select_lr(self):
        print "select_lr"
        self.clicked  = False
        self.tw = TransWindow()
        self.tw.mouse_press = False
        self.tw.show()
        
        self.connect(self.tw, SIGNAL("mouse_press()"),self.set_lr)
    
    def set_ul(self):
        self.sa_x.setValue( self.tw.pos[0])       
        self.sa_y.setValue( self.tw.pos[1])
        self.sa_w.setValue( self.lr[0] - self.sa_x.value())       
        self.sa_h.setValue( self.lr[1] - self.sa_y.value())
        self.show_selected_area()
        
    
    def set_lr(self):
        self.lr = numpy.array([self.tw.pos[0],self.tw.pos[1]])
        self.sa_w.setValue( self.tw.pos[0] - self.sa_x.value())       
        self.sa_h.setValue( self.tw.pos[1] - self.sa_y.value())     
        self.show_selected_area()
        
    
    def capture_area_change(self):
        print "capture_area_change"
        if(self.capture_area_fs.isChecked()):
            self.sa_group.hide()
        else:
            self.sa_group.show()
            
        self.adjustSize()
        self.main_window.adjustSize()
    
    def open_cwd(self):
        #will need to detect os and change accordingly
        os.system("open {}".format(os.getcwd()))
Exemple #51
0
class ConfigDialog(QtGui.QDialog):

    pressedclosebutton = False
    moreToggling = False

    def automaticUpdatePromptCheck(self):
        if self.automaticupdatesCheckbox.checkState() == Qt.PartiallyChecked and not self.nostoreCheckbox.isChecked():
            reply = QtGui.QMessageBox.question(self, "Syncplay",
                    getMessage("promptforupdate-label"), QtGui.QMessageBox.StandardButton.Yes | QtGui.QMessageBox.StandardButton.No)
            if reply == QtGui.QMessageBox.Yes:
                self.automaticupdatesCheckbox.setChecked(True)
            else:
                self.automaticupdatesCheckbox.setChecked(False)

    def moreToggled(self):
        if self.moreToggling == False:
            self.moreToggling = True

            if self.showmoreCheckbox.isChecked():
                self.tabListFrame.show()
                self.resetButton.show()
                self.nostoreCheckbox.show()
                self.saveMoreState(True)
                self.tabListWidget.setCurrentRow(0)
                self.ensureTabListIsVisible()
            else:
                self.tabListFrame.hide()
                self.resetButton.hide()
                self.nostoreCheckbox.hide()
                self.saveMoreState(False)
                self.stackedLayout.setCurrentIndex(0)

            self.adjustSize()
            self.setFixedSize(self.sizeHint())
        self.moreToggling = False
        self.setFixedWidth(self.minimumSizeHint().width())
        self.executablepathCombobox.setFixedWidth(self.mediapathTextbox.width())

    def runButtonTextUpdate(self):
        if self.nostoreCheckbox.isChecked():
            self.runButton.setText(getMessage("run-label"))
        else:
            self.runButton.setText(getMessage("storeandrun-label"))

    def openHelp(self):
        self.QtGui.QDesktopServices.openUrl(QUrl("http://syncplay.pl/guide/client/"))

    def _isURL(self, path):
        if path is None:
            return False

        if "http://" in path:
            return True

    def safenormcaseandpath(self, path):
        if self._isURL(path):
            return path
        else:
            return os.path.normcase(os.path.normpath(path))

    def _tryToFillPlayerPath(self, playerpath, playerpathlist):
        settings = QSettings("Syncplay", "PlayerList")
        settings.beginGroup("PlayerList")
        savedPlayers = settings.value("PlayerList", [])
        if not isinstance(savedPlayers, list):
            savedPlayers = []
        else:
            for i, savedPlayer in enumerate(savedPlayers):
                savedPlayers[i] = self.safenormcaseandpath(savedPlayer)
        playerpathlist = list(set(playerpathlist + savedPlayers))
        settings.endGroup()
        foundpath = ""

        if playerpath != None and playerpath != "":
            if self._isURL(playerpath):
                foundpath = playerpath
                self.executablepathCombobox.addItem(foundpath)

            else:
                if not os.path.isfile(playerpath):
                    expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath)
                    if expandedpath != None and os.path.isfile(expandedpath):
                        playerpath = expandedpath

                if os.path.isfile(playerpath):
                    foundpath = playerpath
                    self.executablepathCombobox.addItem(foundpath)

        for path in playerpathlist:
            if self._isURL(path):
                if foundpath == "":
                    foundpath = path
                if path != playerpath:
                    self.executablepathCombobox.addItem(path)

            elif os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath)):
                self.executablepathCombobox.addItem(path)
                if foundpath == "":
                    foundpath = path

        if foundpath != "":
            settings.beginGroup("PlayerList")
            playerpathlist.append(self.safenormcaseandpath(foundpath))
            settings.setValue("PlayerList", list(set(playerpathlist)))
            settings.endGroup()
        return foundpath

    def updateExecutableIcon(self):
        currentplayerpath = unicode(self.executablepathCombobox.currentText())
        iconpath = PlayerFactory().getPlayerIconByPath(currentplayerpath)
        if iconpath != None and iconpath != "":
            self.executableiconImage.load(self.resourcespath + iconpath)
            self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(self.executableiconImage))
        else:
            self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage()))

    def languageChanged(self):
        setLanguage(unicode(self.languageCombobox.itemData(self.languageCombobox.currentIndex())))
        QtGui.QMessageBox.information(self, "Syncplay", getMessage("language-changed-msgbox-label"))

    def browsePlayerpath(self):
        options = QtGui.QFileDialog.Options()
        defaultdirectory = ""
        browserfilter = "All files (*)"

        if os.name == 'nt':
            browserfilter = "Executable files (*.exe);;All files (*)"
            if "PROGRAMFILES(X86)" in os.environ:
                defaultdirectory = os.environ["ProgramFiles(x86)"]
            elif "PROGRAMFILES" in os.environ:
                defaultdirectory = os.environ["ProgramFiles"]
            elif "PROGRAMW6432" in os.environ:
                defaultdirectory = os.environ["ProgramW6432"]
        elif sys.platform.startswith('linux'):
            defaultdirectory = "/usr/bin"
        elif sys.platform.startswith('darwin'):
            defaultdirectory = "/Applications/"
        elif "bsd" in sys.platform or sys.platform.startswith('dragonfly'):
            defaultdirectory = "/usr/local/bin"

        fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,
                "Browse for media player executable",
                defaultdirectory,
                browserfilter, "", options)
        if fileName:
            self.executablepathCombobox.setEditText(os.path.normpath(fileName))

    def loadLastUpdateCheckDate(self):
        settings = QSettings("Syncplay", "Interface")
        settings.beginGroup("Update")
        self.lastCheckedForUpdates = settings.value("lastChecked", None)
        if self.lastCheckedForUpdates:
            if self.config["lastCheckedForUpdates"] is not None and self.config["lastCheckedForUpdates"] is not "":
                if self.lastCheckedForUpdates > datetime.strptime(self.config["lastCheckedForUpdates"], "%Y-%m-%d %H:%M:%S.%f"):
                    self.config["lastCheckedForUpdates"] = str(self.lastCheckedForUpdates)
            else:
                self.config["lastCheckedForUpdates"] = str(self.lastCheckedForUpdates)

    def loadMediaBrowseSettings(self):
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.beginGroup("MediaBrowseDialog")
        self.mediadirectory = settings.value("mediadir", "")
        settings.endGroup()

    def saveMediaBrowseSettings(self):
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.beginGroup("MediaBrowseDialog")
        settings.setValue("mediadir", self.mediadirectory)
        settings.endGroup()

    def getMoreState(self):
        settings = QSettings("Syncplay", "MoreSettings")
        settings.beginGroup("MoreSettings")
        morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false")))
        settings.endGroup()
        if morestate == "true":
            return True
        else:
            return False

    def saveMoreState(self, morestate):
        settings = QSettings("Syncplay", "MoreSettings")
        settings.beginGroup("MoreSettings")
        settings.setValue("ShowMoreSettings", morestate)
        settings.endGroup()

    def browseMediapath(self):
        self.loadMediaBrowseSettings()
        options = QtGui.QFileDialog.Options()
        if os.path.isdir(self.mediadirectory):
            defaultdirectory = self.mediadirectory
        elif os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)):
            defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
        elif os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation)):
            defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        else:
            defaultdirectory = ""
        browserfilter = "All files (*)"
        fileName, filtr = QtGui.QFileDialog.getOpenFileName(self, "Browse for media files", defaultdirectory,
                browserfilter, "", options)
        if fileName:
            self.mediapathTextbox.setText(os.path.normpath(fileName))
            self.mediadirectory = os.path.dirname(fileName)
            self.saveMediaBrowseSettings()

    def _saveDataAndLeave(self):
        self.automaticUpdatePromptCheck()
        self.loadLastUpdateCheckDate()

        self.processWidget(self, lambda w: self.saveValues(w))
        if self.hostTextbox.text():
            self.config['host'] = self.hostTextbox.text() if ":" in self.hostTextbox.text() else self.hostTextbox.text() + ":" + unicode(constants.DEFAULT_PORT)
        else:
            self.config['host'] = None
        self.config['playerPath'] = unicode(self.safenormcaseandpath(self.executablepathCombobox.currentText()))
        self.config['language'] = unicode(self.languageCombobox.itemData(self.languageCombobox.currentIndex()))
        if self.mediapathTextbox.text() == "":
            self.config['file'] = None
        elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())):
            self.config['file'] = os.path.abspath(self.mediapathTextbox.text())
        else:
            self.config['file'] = unicode(self.mediapathTextbox.text())

        self.pressedclosebutton = True
        self.close()
        return

    def closeEvent(self, event):
        if self.pressedclosebutton == False:
            sys.exit()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
           sys.exit()

    def dragEnterEvent(self, event):
        data = event.mimeData()
        urls = data.urls()
        if urls and urls[0].scheme() == 'file':
            event.acceptProposedAction()

    def dropEvent(self, event):
        data = event.mimeData()
        urls = data.urls()
        if urls and urls[0].scheme() == 'file':
            dropfilepath = os.path.abspath(unicode(event.mimeData().urls()[0].toLocalFile()))
            if dropfilepath[-4:].lower() == ".exe":
                self.executablepathCombobox.setEditText(dropfilepath)
            else:
                self.mediapathTextbox.setText(dropfilepath)

    def processWidget(self, container, torun):
        for widget in container.children():
            self.processWidget(widget, torun)
            if hasattr(widget, 'objectName') and widget.objectName() and widget.objectName()[:3] != "qt_":
                torun(widget)

    def loadTooltips(self, widget):
        tooltipName = widget.objectName().lower().split(constants.CONFIG_NAME_MARKER)[0] + "-tooltip"
        if tooltipName[:1] == constants.INVERTED_STATE_MARKER or tooltipName[:1] == constants.LOAD_SAVE_MANUALLY_MARKER:
            tooltipName = tooltipName[1:]
        widget.setToolTip(getMessage(tooltipName))

    def loadValues(self, widget):
        valueName = str(widget.objectName())
        if valueName[:1] == constants.LOAD_SAVE_MANUALLY_MARKER:
            return

        if isinstance(widget, QCheckBox) and widget.objectName():
            if valueName[:1] == constants.INVERTED_STATE_MARKER:
                valueName = valueName[1:]
                inverted = True
            else:
                inverted = False
            if self.config[valueName] is None:
                widget.setTristate(True)
                widget.setCheckState(Qt.PartiallyChecked)
                widget.stateChanged.connect(lambda: widget.setTristate(False))
            else:
                widget.setChecked(self.config[valueName] != inverted)
        elif isinstance(widget, QRadioButton):
            radioName, radioValue  = valueName.split(constants.CONFIG_NAME_MARKER)[1].split(constants.CONFIG_VALUE_MARKER)
            if self.config[radioName] == radioValue:
                widget.setChecked(True)
        elif isinstance(widget, QLineEdit):
            widget.setText(self.config[valueName])

    def saveValues(self, widget):
        valueName = str(widget.objectName())
        if valueName[:1] == constants.LOAD_SAVE_MANUALLY_MARKER:
            return

        if isinstance(widget, QCheckBox) and widget.objectName():
            if widget.checkState() == Qt.PartiallyChecked:
                self.config[valueName] = None
            else:
                if valueName[:1] == constants.INVERTED_STATE_MARKER:
                    valueName = valueName[1:]
                    inverted = True
                else:
                    inverted = False
                self.config[valueName] = widget.isChecked() != inverted
        elif isinstance(widget, QRadioButton):
            radioName, radioValue  = valueName.split(constants.CONFIG_NAME_MARKER)[1].split(constants.CONFIG_VALUE_MARKER)
            if widget.isChecked():
                self.config[radioName] = radioValue
        elif isinstance(widget, QLineEdit):
            self.config[valueName] = widget.text()

    def connectChildren(self, widget):
        widgetName = str(widget.objectName())
        if self.subitems.has_key(widgetName) and isinstance(widget, QCheckBox):
            widget.stateChanged.connect(lambda: self.updateSubwidgets(self, widget))
            self.updateSubwidgets(self, widget)

    def updateSubwidgets(self, container, parentwidget, subwidgets=None):
        widgetName = parentwidget.objectName()
        if not subwidgets:
            subwidgets = self.subitems[widgetName]
        for widget in container.children():
            self.updateSubwidgets(widget, parentwidget, subwidgets)
            if hasattr(widget, 'objectName') and widget.objectName() and widget.objectName() in subwidgets:
                widget.setDisabled(not parentwidget.isChecked())

    def addBasicTab(self):
        config = self.config
        playerpaths = self.playerpaths
        resourcespath = self.resourcespath
        error = self.error
        if self.datacleared == True:
            error = constants.ERROR_MESSAGE_MARKER + "{}".format(getMessage("gui-data-cleared-notification"))
        if config['host'] == None:
            host = ""
        elif ":" in config['host']:
            host = config['host']
        else:
            host = config['host'] + ":" + str(config['port'])

        self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("connection-group-title"))
        self.hostTextbox = QLineEdit(host, self)
        self.hostLabel = QLabel(getMessage("host-label"), self)
        self.usernameTextbox = QLineEdit(self)
        self.usernameTextbox.setObjectName("name")
        self.serverpassLabel = QLabel(getMessage("password-label"), self)
        self.defaultroomTextbox = QLineEdit(self)
        self.usernameLabel = QLabel(getMessage("name-label"), self)
        self.serverpassTextbox = QLineEdit(self)
        self.defaultroomLabel = QLabel(getMessage("room-label"), self)

        self.hostLabel.setObjectName("host")
        self.hostTextbox.setObjectName(constants.LOAD_SAVE_MANUALLY_MARKER + "host")
        self.usernameLabel.setObjectName("name")
        self.usernameTextbox.setObjectName("name")
        self.serverpassLabel.setObjectName("password")
        self.serverpassTextbox.setObjectName("password")
        self.defaultroomLabel.setObjectName("room")
        self.defaultroomTextbox.setObjectName("room")

        self.connectionSettingsLayout = QtGui.QGridLayout()
        self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0)
        self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1)
        self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0)
        self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1)
        self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0)
        self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1)
        self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0)
        self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1)
        self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout)
        self.connectionSettingsGroup.setMaximumHeight(self.connectionSettingsGroup.minimumSizeHint().height())

        self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("media-setting-title"))
        self.executableiconImage = QtGui.QImage()
        self.executableiconLabel = QLabel(self)
        self.executableiconLabel.setMinimumWidth(16)
        self.executablepathCombobox = QtGui.QComboBox(self)
        self.executablepathCombobox.setEditable(True)
        self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon)
        self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths))
        self.executablepathCombobox.setFixedWidth(165)
        self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon)

        self.executablepathLabel = QLabel(getMessage("executable-path-label"), self)
        self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("browse-label"))
        self.executablebrowseButton.clicked.connect(self.browsePlayerpath)
        self.mediapathTextbox = QLineEdit(config['file'], self)
        self.mediapathLabel = QLabel(getMessage("media-path-label"), self)
        self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'), getMessage("browse-label"))
        self.mediabrowseButton.clicked.connect(self.browseMediapath)

        self.executablepathLabel.setObjectName("executable-path")
        self.executablepathCombobox.setObjectName("executable-path")
        self.mediapathLabel.setObjectName("media-path")
        self.mediapathTextbox.setObjectName(constants.LOAD_SAVE_MANUALLY_MARKER + "media-path")

        self.mediaplayerSettingsLayout = QtGui.QGridLayout()
        self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0)
        self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1)
        self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2)
        self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2)
        self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3)
        self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout)

        self.showmoreCheckbox = QCheckBox(getMessage("more-title"))
        self.showmoreCheckbox.setObjectName(constants.LOAD_SAVE_MANUALLY_MARKER + "more")

        self.basicOptionsFrame = QtGui.QFrame()
        self.basicOptionsLayout = QtGui.QVBoxLayout()
        if error:
            self.errorLabel = QLabel(self)
            if error[:1] != constants.ERROR_MESSAGE_MARKER:
                self.errorLabel.setStyleSheet(constants.STYLE_ERRORLABEL)
            else:
                error = error[1:]
                self.errorLabel.setStyleSheet(constants.STYLE_SUCCESSLABEL)
            self.errorLabel.setText(error)
            self.errorLabel.setAlignment(Qt.AlignCenter)

            self.basicOptionsLayout.addWidget(self.errorLabel, 0, 0)
        self.connectionSettingsGroup.setMaximumHeight(self.connectionSettingsGroup.minimumSizeHint().height())
        self.basicOptionsLayout.setAlignment(Qt.AlignTop)
        self.basicOptionsLayout.addWidget(self.connectionSettingsGroup)
        self.basicOptionsLayout.addSpacing(5)
        self.mediaplayerSettingsGroup.setMaximumHeight(self.mediaplayerSettingsGroup.minimumSizeHint().height())
        self.basicOptionsLayout.addWidget(self.mediaplayerSettingsGroup)

        self.basicOptionsFrame.setLayout(self.basicOptionsLayout)
        self.stackedLayout.addWidget(self.basicOptionsFrame)

    def addReadinessTab(self):
        self.readyFrame = QtGui.QFrame()
        self.readyLayout = QtGui.QVBoxLayout()
        self.readyFrame.setLayout(self.readyLayout)

        # Initial state

        self.readyInitialGroup = QtGui.QGroupBox(u"Initial readiness state")
        self.readyInitialLayout = QtGui.QVBoxLayout()
        self.readyInitialGroup.setLayout(self.readyInitialLayout)
        self.readyatstartCheckbox = QCheckBox(getMessage("readyatstart-label"))
        self.readyatstartCheckbox.setObjectName("readyAtStart")
        self.readyInitialLayout.addWidget(self.readyatstartCheckbox)
        self.readyLayout.addWidget(self.readyInitialGroup)

        # Automatically pausing
        self.readyPauseGroup = QtGui.QGroupBox(u"Pausing")
        self.readyPauseLayout = QtGui.QVBoxLayout()
        self.readyPauseGroup.setLayout(self.readyPauseLayout)
        self.pauseonleaveCheckbox = QCheckBox(getMessage("pauseonleave-label"))
        self.pauseonleaveCheckbox.setObjectName("pauseOnLeave")
        self.readyPauseLayout.addWidget(self.pauseonleaveCheckbox)
        self.readyLayout.addWidget(self.readyPauseGroup)

        # Unpausing
        self.readyUnpauseGroup = QtGui.QGroupBox(getMessage("unpause-title"))
        self.readyUnpauseLayout = QtGui.QVBoxLayout()
        self.readyUnpauseGroup.setLayout(self.readyUnpauseLayout)
        self.readyUnpauseButtonGroup = QButtonGroup()
        self.unpauseIfAlreadyReadyOption = QRadioButton(getMessage("unpause-ifalreadyready-option"))
        self.readyUnpauseButtonGroup.addButton(self.unpauseIfAlreadyReadyOption)
        self.unpauseIfAlreadyReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.unpauseIfAlreadyReadyOption.setObjectName("unpause-ifalreadyready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFALREADYREADY_MODE)
        self.readyUnpauseLayout.addWidget(self.unpauseIfAlreadyReadyOption)
        self.unpauseIfOthersReadyOption = QRadioButton(getMessage("unpause-ifothersready-option"))
        self.readyUnpauseButtonGroup.addButton(self.unpauseIfOthersReadyOption)
        self.unpauseIfOthersReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.unpauseIfOthersReadyOption.setObjectName("unpause-ifothersready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFOTHERSREADY_MODE)
        self.readyUnpauseLayout.addWidget(self.unpauseIfOthersReadyOption)
        self.unpauseIfMinUsersReadyOption = QRadioButton(getMessage("unpause-ifminusersready-option"))
        self.readyUnpauseButtonGroup.addButton(self.unpauseIfMinUsersReadyOption)
        self.unpauseIfMinUsersReadyOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.unpauseIfMinUsersReadyOption.setObjectName("unpause-ifminusersready" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_IFMINUSERSREADY_MODE)
        self.readyUnpauseLayout.addWidget(self.unpauseIfMinUsersReadyOption)
        self.unpauseAlwaysUnpauseOption = QRadioButton(getMessage("unpause-always"))
        self.readyUnpauseButtonGroup.addButton(self.unpauseAlwaysUnpauseOption)
        self.unpauseAlwaysUnpauseOption.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.unpauseAlwaysUnpauseOption.setObjectName("unpause-always" + constants.CONFIG_NAME_MARKER + "unpauseAction" + constants.CONFIG_VALUE_MARKER + constants.UNPAUSE_ALWAYS_MODE)
        self.readyUnpauseLayout.addWidget(self.unpauseAlwaysUnpauseOption)
        self.readyLayout.addWidget(self.readyUnpauseGroup)

        self.readyLayout.setAlignment(Qt.AlignTop)
        self.stackedLayout.addWidget(self.readyFrame)

    def addMiscTab(self):
        self.miscFrame = QtGui.QFrame()
        self.miscLayout = QtGui.QVBoxLayout()
        self.miscFrame.setLayout(self.miscLayout)

        self.coreSettingsGroup = QtGui.QGroupBox(getMessage("core-behaviour-title"))
        self.coreSettingsLayout = QtGui.QGridLayout()
        self.coreSettingsGroup.setLayout(self.coreSettingsLayout)

        ### Privacy:

        self.filenameprivacyLabel = QLabel(getMessage("filename-privacy-label"), self)
        self.filenameprivacyButtonGroup = QButtonGroup()
        self.filenameprivacySendRawOption = QRadioButton(getMessage("privacy-sendraw-option"))
        self.filenameprivacySendHashedOption = QRadioButton(getMessage("privacy-sendhashed-option"))
        self.filenameprivacyDontSendOption = QRadioButton(getMessage("privacy-dontsend-option"))
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption)

        self.filesizeprivacyLabel = QLabel(getMessage("filesize-privacy-label"), self)
        self.filesizeprivacyButtonGroup = QButtonGroup()
        self.filesizeprivacySendRawOption = QRadioButton(getMessage("privacy-sendraw-option"))
        self.filesizeprivacySendHashedOption = QRadioButton(getMessage("privacy-sendhashed-option"))
        self.filesizeprivacyDontSendOption = QRadioButton(getMessage("privacy-dontsend-option"))
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption)

        self.filenameprivacyLabel.setObjectName("filename-privacy")
        self.filenameprivacySendRawOption.setObjectName("privacy-sendraw" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDRAW_MODE)
        self.filenameprivacySendHashedOption.setObjectName("privacy-sendhashed" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDHASHED_MODE)
        self.filenameprivacyDontSendOption.setObjectName("privacy-dontsend" + constants.CONFIG_NAME_MARKER + "filenamePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_DONTSEND_MODE)
        self.filesizeprivacyLabel.setObjectName("filesize-privacy")
        self.filesizeprivacySendRawOption.setObjectName("privacy-sendraw" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDRAW_MODE)
        self.filesizeprivacySendHashedOption.setObjectName("privacy-sendhashed" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_SENDHASHED_MODE)
        self.filesizeprivacyDontSendOption.setObjectName("privacy-dontsend" + constants.CONFIG_NAME_MARKER + "filesizePrivacyMode" + constants.CONFIG_VALUE_MARKER + constants.PRIVACY_DONTSEND_MODE)

        self.coreSettingsLayout.addWidget(self.filenameprivacyLabel, 3, 0)
        self.coreSettingsLayout.addWidget(self.filenameprivacySendRawOption, 3, 1, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filenameprivacySendHashedOption, 3, 2, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filenameprivacyDontSendOption, 3, 3, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filesizeprivacyLabel, 4, 0)
        self.coreSettingsLayout.addWidget(self.filesizeprivacySendRawOption, 4, 1, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 4, 2, Qt.AlignLeft)
        self.coreSettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 4, 3, Qt.AlignLeft)

        ## Syncplay internals

        self.internalSettingsGroup = QtGui.QGroupBox(getMessage("syncplay-internals-title"))
        self.internalSettingsLayout = QtGui.QVBoxLayout()
        self.internalSettingsGroup.setLayout(self.internalSettingsLayout)

        self.alwaysshowCheckbox = QCheckBox(getMessage("forceguiprompt-label"))
        self.alwaysshowCheckbox.setObjectName(constants.INVERTED_STATE_MARKER + "forceGuiPrompt")
        self.internalSettingsLayout.addWidget(self.alwaysshowCheckbox)

        self.automaticupdatesCheckbox = QCheckBox(getMessage("checkforupdatesautomatically-label"))
        self.automaticupdatesCheckbox.setObjectName("checkForUpdatesAutomatically")
        self.internalSettingsLayout.addWidget(self.automaticupdatesCheckbox)

        self.miscLayout.addWidget(self.coreSettingsGroup)
        self.miscLayout.addWidget(self.internalSettingsGroup)
        self.miscLayout.setAlignment(Qt.AlignTop)
        self.stackedLayout.addWidget(self.miscFrame)

    def addSyncTab(self):
        self.syncSettingsFrame = QtGui.QFrame()
        self.syncSettingsLayout = QtGui.QVBoxLayout()

        self.desyncSettingsGroup = QtGui.QGroupBox(getMessage("sync-otherslagging-title"))
        self.desyncOptionsFrame = QtGui.QFrame()
        self.desyncSettingsOptionsLayout = QtGui.QHBoxLayout()
        config = self.config

        self.slowdownCheckbox = QCheckBox(getMessage("slowondesync-label"))
        self.slowdownCheckbox.setObjectName("slowOnDesync")
        self.rewindCheckbox = QCheckBox(getMessage("rewindondesync-label"))
        self.rewindCheckbox.setObjectName("rewindOnDesync")
        self.fastforwardCheckbox = QCheckBox(getMessage("fastforwardondesync-label"))
        self.fastforwardCheckbox.setObjectName("fastforwardOnDesync")

        self.desyncSettingsLayout = QtGui.QGridLayout()
        self.desyncSettingsLayout.setSpacing(2)
        self.desyncFrame = QtGui.QFrame()
        self.desyncFrame.setLineWidth(0)
        self.desyncFrame.setMidLineWidth(0)

        self.desyncSettingsLayout.addWidget(self.slowdownCheckbox, 0, 0, 1, 2, Qt.AlignLeft)
        self.desyncSettingsLayout.addWidget(self.rewindCheckbox, 1, 0,1,2, Qt.AlignLeft)

        self.desyncSettingsLayout.setAlignment(Qt.AlignLeft)
        self.desyncSettingsGroup.setLayout(self.desyncSettingsLayout)
        self.desyncSettingsOptionsLayout.addWidget(self.desyncFrame)

        self.desyncFrame.setLayout(self.syncSettingsLayout)

        self.othersyncSettingsGroup = QtGui.QGroupBox(getMessage("sync-youlaggging-title"))
        self.othersyncOptionsFrame = QtGui.QFrame()
        self.othersyncSettingsLayout = QtGui.QGridLayout()

        self.dontslowwithmeCheckbox = QCheckBox(getMessage("dontslowdownwithme-label"))
        self.dontslowwithmeCheckbox.setObjectName("dontSlowDownWithMe")

        self.othersyncSettingsLayout.addWidget(self.dontslowwithmeCheckbox, 2, 0, 1, 2, Qt.AlignLeft)

        self.othersyncSettingsLayout.setAlignment(Qt.AlignLeft)
        self.othersyncSettingsLayout.addWidget(self.fastforwardCheckbox, 3, 0,1,2, Qt.AlignLeft)

        self.othersyncSettingsGroup.setLayout(self.othersyncSettingsLayout)
        self.othersyncSettingsGroup.setMaximumHeight(self.othersyncSettingsGroup.minimumSizeHint().height())
        self.syncSettingsLayout.addWidget(self.othersyncSettingsGroup)
        self.syncSettingsLayout.addWidget(self.desyncSettingsGroup)
        self.syncSettingsFrame.setLayout(self.syncSettingsLayout)
        self.desyncSettingsGroup.setMaximumHeight(self.desyncSettingsGroup.minimumSizeHint().height())
        self.syncSettingsLayout.setAlignment(Qt.AlignTop)
        self.stackedLayout.addWidget(self.syncSettingsFrame)

    def addMessageTab(self):
        self.messageFrame = QtGui.QFrame()
        self.messageLayout = QtGui.QVBoxLayout()
        self.messageLayout.setAlignment(Qt.AlignTop)

        # OSD
        self.osdSettingsGroup = QtGui.QGroupBox(getMessage("messages-osd-title"))
        self.osdSettingsLayout = QtGui.QVBoxLayout()
        self.osdSettingsFrame = QtGui.QFrame()

        self.showOSDCheckbox = QCheckBox(getMessage("showosd-label"))
        self.showOSDCheckbox.setObjectName("showOSD")
        self.osdSettingsLayout.addWidget(self.showOSDCheckbox)

        self.showSameRoomOSDCheckbox = QCheckBox(getMessage("showsameroomosd-label"))
        self.showSameRoomOSDCheckbox.setObjectName("showSameRoomOSD")
        self.showSameRoomOSDCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.osdSettingsLayout.addWidget(self.showSameRoomOSDCheckbox)

        self.showNonControllerOSDCheckbox = QCheckBox(getMessage("shownoncontrollerosd-label"))
        self.showNonControllerOSDCheckbox.setObjectName("showNonControllerOSD")
        self.showNonControllerOSDCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.osdSettingsLayout.addWidget(self.showNonControllerOSDCheckbox)

        self.showDifferentRoomOSDCheckbox = QCheckBox(getMessage("showdifferentroomosd-label"))
        self.showDifferentRoomOSDCheckbox.setObjectName("showDifferentRoomOSD")
        self.showDifferentRoomOSDCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.osdSettingsLayout.addWidget(self.showDifferentRoomOSDCheckbox)

        self.slowdownOSDCheckbox = QCheckBox(getMessage("showslowdownosd-label"))
        self.slowdownOSDCheckbox.setObjectName("showSlowdownOSD")
        self.slowdownOSDCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.osdSettingsLayout.addWidget(self.slowdownOSDCheckbox)

        self.showOSDWarningsCheckbox = QCheckBox(getMessage("showosdwarnings-label"))
        self.showOSDWarningsCheckbox.setObjectName("showOSDWarnings")
        self.showOSDWarningsCheckbox.setStyleSheet(constants.STYLE_SUBCHECKBOX.format(self.posixresourcespath + "chevrons_right.png"))
        self.osdSettingsLayout.addWidget(self.showOSDWarningsCheckbox)

        self.subitems['showOSD'] = ["showSameRoomOSD", "showDifferentRoomOSD", "showSlowdownOSD", "showOSDWarnings", "showNonControllerOSD"]

        self.osdSettingsGroup.setLayout(self.osdSettingsLayout)
        self.osdSettingsGroup.setMaximumHeight(self.osdSettingsGroup.minimumSizeHint().height())
        self.osdSettingsLayout.setAlignment(Qt.AlignTop)
        self.messageLayout.addWidget(self.osdSettingsGroup)

        # Other display

        self.displaySettingsGroup = QtGui.QGroupBox(getMessage("messages-other-title"))
        self.displaySettingsLayout = QtGui.QVBoxLayout()
        self.displaySettingsLayout.setAlignment(Qt.AlignTop & Qt.AlignLeft)
        self.displaySettingsFrame = QtGui.QFrame()

        self.showDurationNotificationCheckbox = QCheckBox(getMessage("showdurationnotification-label"))
        self.showDurationNotificationCheckbox.setObjectName("showDurationNotification")
        self.displaySettingsLayout.addWidget(self.showDurationNotificationCheckbox)

        self.languageFrame = QtGui.QFrame()
        self.languageLayout = QtGui.QHBoxLayout()
        self.languageLayout.setContentsMargins(0, 0, 0, 0)
        self.languageFrame.setLayout(self.languageLayout)
        self.languageFrame.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        self.languageLayout.setAlignment(Qt.AlignTop & Qt.AlignLeft)
        self.languageLabel = QLabel(getMessage("language-label"), self)
        self.languageCombobox = QtGui.QComboBox(self)
        self.languageCombobox.addItem(getMessage("automatic-language").format(getMessage("LANGUAGE", getInitialLanguage())))

        self.languages = getLanguages()
        for lang in self.languages:
            self.languageCombobox.addItem(self.languages[lang], lang)
            if lang == self.config['language']:
                self.languageCombobox.setCurrentIndex(self.languageCombobox.count()-1)
        self.languageCombobox.currentIndexChanged.connect(self.languageChanged)
        self.languageLayout.addWidget(self.languageLabel, 1, 0)
        self.languageLayout.addWidget(self.languageCombobox, 1, 1)
        self.displaySettingsLayout.addWidget(self.languageFrame)

        self.languageLabel.setObjectName("language")
        self.languageCombobox.setObjectName("language")
        self.languageFrame.setMaximumWidth(self.languageFrame.minimumSizeHint().width())

        self.displaySettingsGroup.setLayout(self.displaySettingsLayout)
        self.displaySettingsGroup.setMaximumHeight(self.displaySettingsGroup.minimumSizeHint().height())
        self.displaySettingsLayout.setAlignment(Qt.AlignTop & Qt.AlignLeft)
        self.messageLayout.addWidget(self.displaySettingsGroup)

        # messageFrame
        self.messageFrame.setLayout(self.messageLayout)
        self.stackedLayout.addWidget(self.messageFrame)

    def addBottomLayout(self):
        config = self.config
        resourcespath = self.resourcespath

        self.bottomButtonFrame = QtGui.QFrame()
        self.bottomButtonLayout = QtGui.QHBoxLayout()
        self.helpButton = QtGui.QPushButton(QtGui.QIcon(self.resourcespath + 'help.png'), getMessage("help-label"))
        self.helpButton.setObjectName("help")
        self.helpButton.setMaximumSize(self.helpButton.sizeHint())
        self.helpButton.pressed.connect(self.openHelp)

        self.resetButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'cog_delete.png'),getMessage("reset-label"))
        self.resetButton.setMaximumSize(self.resetButton.sizeHint())
        self.resetButton.setObjectName("reset")
        self.resetButton.pressed.connect(self.resetSettings)

        self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'), getMessage("storeandrun-label"))
        self.runButton.pressed.connect(self._saveDataAndLeave)
        self.bottomButtonLayout.addWidget(self.helpButton)
        self.bottomButtonLayout.addWidget(self.resetButton)
        self.bottomButtonLayout.addWidget(self.runButton)
        self.bottomButtonFrame.setLayout(self.bottomButtonLayout)
        if config['noStore'] == True:
            self.runButton.setText(getMessage("run-label"))
        self.bottomButtonLayout.setContentsMargins(5,0,5,0)
        self.mainLayout.addWidget(self.bottomButtonFrame, 1, 0, 1, 2)

        self.bottomCheckboxFrame = QtGui.QFrame()
        self.bottomCheckboxFrame.setContentsMargins(0,0,0,0)
        self.bottomCheckboxLayout = QtGui.QGridLayout()
        self.alwaysshowCheckbox = QCheckBox(getMessage("forceguiprompt-label"))

        self.nostoreCheckbox = QCheckBox(getMessage("nostore-label"))
        self.bottomCheckboxLayout.addWidget(self.showmoreCheckbox)
        self.bottomCheckboxLayout.addWidget(self.nostoreCheckbox, 0, 2, Qt.AlignRight)
        self.alwaysshowCheckbox.setObjectName(constants.INVERTED_STATE_MARKER + "forceGuiPrompt")
        self.nostoreCheckbox.setObjectName("noStore")
        self.nostoreCheckbox.toggled.connect(self.runButtonTextUpdate)
        self.bottomCheckboxFrame.setLayout(self.bottomCheckboxLayout)

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

    def tabList(self):
        self.tabListLayout = QtGui.QHBoxLayout()
        self.tabListFrame = QtGui.QFrame()
        self.tabListWidget = QtGui.QListWidget()
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "house.png"),getMessage("basics-label")))
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "control_pause_blue.png"),getMessage("readiness-label")))
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "film_link.png"),getMessage("sync-label")))
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "comments.png"),getMessage("messages-label")))
        self.tabListWidget.addItem(QtGui.QListWidgetItem(QtGui.QIcon(self.resourcespath + "cog.png"),getMessage("misc-label")))
        self.tabListLayout.addWidget(self.tabListWidget)
        self.tabListFrame.setLayout(self.tabListLayout)
        self.tabListFrame.setFixedWidth(self.tabListFrame.minimumSizeHint().width())
        self.tabListWidget.setStyleSheet(constants.STYLE_TABLIST)

        self.tabListWidget.currentItemChanged.connect(self.tabChange)
        self.tabListWidget.itemClicked.connect(self.tabChange)
        self.tabListWidget.itemPressed.connect(self.tabChange)
        self.mainLayout.addWidget(self.tabListFrame, 0, 0, 1, 1)

    def ensureTabListIsVisible(self):
        self.stackedFrame.setFixedWidth(self.stackedFrame.width())
        while self.tabListWidget.horizontalScrollBar().isVisible() and self.tabListFrame.width() < 200:
            self.tabListFrame.setFixedWidth(self.tabListFrame.width()+1)

    def tabChange(self):
        self.setFocus()
        self.stackedLayout.setCurrentIndex(self.tabListWidget.currentRow())

    def resetSettings(self):
        self.clearGUIData(leaveMore=True)
        self.config['resetConfig'] = True
        self.pressedclosebutton = True
        self.close()

    def showEvent(self, *args, **kwargs):
        self.ensureTabListIsVisible()
        self.setFixedWidth(self.minimumSizeHint().width())
        self.executablepathCombobox.setFixedWidth(self.mediapathTextbox.width())

    def clearGUIData(self, leaveMore=False):
        settings = QSettings("Syncplay", "PlayerList")
        settings.clear()
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.clear()
        settings = QSettings("Syncplay", "MainWindow")
        settings.clear()
        settings = QSettings("Syncplay", "Interface")
        settings.beginGroup("Update")
        settings.setValue("lastChecked", None)
        settings.endGroup()
        if not leaveMore:
            settings = QSettings("Syncplay", "MoreSettings")
            settings.clear()
        self.datacleared = True

    def __init__(self, config, playerpaths, error, defaultConfig):

        from syncplay import utils
        self.config = config
        self.defaultConfig = defaultConfig
        self.playerpaths = playerpaths
        self.datacleared = False
        self.config['resetConfig'] = False
        self.subitems = {}

        if self.config['clearGUIData'] == True:
            self.config['clearGUIData'] = False
            self.clearGUIData()

        self.QtGui = QtGui
        self.error = error
        if sys.platform.startswith('win'):
            resourcespath = utils.findWorkingDir() + "\\resources\\"
        else:
            resourcespath = utils.findWorkingDir() + "/resources/"
        self.posixresourcespath = utils.findWorkingDir().replace("\\","/") + "/resources/"
        self.resourcespath = resourcespath

        super(ConfigDialog, self).__init__()

        self.setWindowTitle(getMessage("config-window-title"))
        self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
        self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png"))

        self.stackedLayout = QtGui.QStackedLayout()
        self.stackedFrame = QtGui.QFrame()
        self.stackedFrame.setLayout(self.stackedLayout)

        self.mainLayout = QtGui.QGridLayout()
        self.mainLayout.setSpacing(0)
        self.mainLayout.setContentsMargins(0,0,0,0)

        self.addBasicTab()
        self.addReadinessTab()
        self.addSyncTab()
        self.addMessageTab()
        self.addMiscTab()
        self.tabList()

        self.mainLayout.addWidget(self.stackedFrame, 0, 1)
        self.addBottomLayout()


        if self.getMoreState() == False:
            self.tabListFrame.hide()
            self.nostoreCheckbox.hide()
            self.resetButton.hide()
        else:
            self.showmoreCheckbox.setChecked(True)
            self.tabListWidget.setCurrentRow(0)

        self.showmoreCheckbox.toggled.connect(self.moreToggled)

        self.setLayout(self.mainLayout)
        self.runButton.setFocus()
        self.setFixedSize(self.sizeHint())
        self.setAcceptDrops(True)

        if constants.SHOW_TOOLTIPS:
            self.processWidget(self, lambda w: self.loadTooltips(w))
        self.processWidget(self, lambda w: self.loadValues(w))
        self.processWidget(self, lambda w: self.connectChildren(w))
Exemple #52
0
class ConfigDialog(QtGui.QDialog):
    
    pressedclosebutton = False
    moreToggling = False
    
    def moreToggled(self):
        if self.moreToggling == False:
            self.moreToggling = True
            
            if self.showmoreCheckbox.isChecked() and self.showmoreCheckbox.isVisible():
                self.showmoreCheckbox.setChecked(False)
                self.moreSettingsGroup.setChecked(True)
                self.moreSettingsGroup.show()
                self.showmoreCheckbox.hide()
                self.saveMoreState(True)
            else:
                self.moreSettingsGroup.setChecked(False)
                self.moreSettingsGroup.hide()
                self.showmoreCheckbox.show()
                self.saveMoreState(False)
                
            self.moreToggling = False
            self.adjustSize()
            self.setFixedSize(self.sizeHint())
            
    def runButtonTextUpdate(self):
        if (self.donotstoreCheckbox.isChecked()):
            self.runButton.setText(getMessage("en", "run-label"))
        else:
            self.runButton.setText(getMessage("en", "storeandrun-label"))
            
    def openHelp(self):
        self.QtGui.QDesktopServices.openUrl("http://syncplay.pl/guide/client/")

    def _tryToFillPlayerPath(self, playerpath, playerpathlist):
        settings = QSettings("Syncplay", "PlayerList")
        settings.beginGroup("PlayerList")
        savedPlayers = settings.value("PlayerList", [])
        if(not isinstance(savedPlayers, list)):
            savedPlayers = []
        playerpathlist = list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist + savedPlayers)))
        settings.endGroup()
        foundpath = ""

        if playerpath != None and playerpath != "":
            if not os.path.isfile(playerpath):
                expandedpath = PlayerFactory().getExpandedPlayerPathByPath(playerpath)
                if expandedpath != None and os.path.isfile(expandedpath):
                    playerpath = expandedpath

            if os.path.isfile(playerpath):
                foundpath = playerpath
                self.executablepathCombobox.addItem(foundpath)

        for path in playerpathlist:
            if(os.path.isfile(path) and os.path.normcase(os.path.normpath(path)) != os.path.normcase(os.path.normpath(foundpath))):
                self.executablepathCombobox.addItem(path)
                if foundpath == "":
                    foundpath = path

        if foundpath != "":
            settings.beginGroup("PlayerList")
            playerpathlist.append(os.path.normcase(os.path.normpath(foundpath)))
            settings.setValue("PlayerList",  list(set(os.path.normcase(os.path.normpath(path)) for path in set(playerpathlist))))
            settings.endGroup()
        return(foundpath)
    
    def updateExecutableIcon(self):
        currentplayerpath = unicode(self.executablepathCombobox.currentText())
        iconpath = PlayerFactory().getPlayerIconByPath(currentplayerpath)
        if iconpath != None and iconpath != "":
            self.executableiconImage.load(self.resourcespath + iconpath)
            self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(self.executableiconImage))
        else:
            self.executableiconLabel.setPixmap(QtGui.QPixmap.fromImage(QtGui.QImage()))
        
    
    def browsePlayerpath(self):
        options = QtGui.QFileDialog.Options()
        defaultdirectory = ""
        browserfilter = "All files (*)"
        
        if os.name == 'nt':
            browserfilter =  "Executable files (*.exe);;All files (*)"
            if "PROGRAMFILES(X86)" in os.environ: 
                defaultdirectory = os.environ["ProgramFiles(x86)"]
            elif "PROGRAMFILES" in os.environ:
                defaultdirectory = os.environ["ProgramFiles"]
            elif "PROGRAMW6432" in os.environ:
                defaultdirectory = os.environ["ProgramW6432"]
        elif sys.platform.startswith('linux'):
            defaultdirectory = "/usr/bin"
        
        fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,
                "Browse for media player executable",
                defaultdirectory,
                browserfilter, "", options)
        if fileName:
            self.executablepathCombobox.setEditText(os.path.normpath(fileName))
            
    def loadMediaBrowseSettings(self):
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.beginGroup("MediaBrowseDialog")
        self.mediadirectory = settings.value("mediadir", "")
        settings.endGroup()
                        
    def saveMediaBrowseSettings(self):
        settings = QSettings("Syncplay", "MediaBrowseDialog")
        settings.beginGroup("MediaBrowseDialog")
        settings.setValue("mediadir", self.mediadirectory)
        settings.endGroup()
        
    def getMoreState(self):
        settings = QSettings("Syncplay", "MoreSettings")
        settings.beginGroup("MoreSettings")
        morestate = unicode.lower(unicode(settings.value("ShowMoreSettings", "false")))
        settings.endGroup()
        if morestate == "true":
            return(True)
        else:
            return(False)
                        
    def saveMoreState(self, morestate):
        settings = QSettings("Syncplay", "MoreSettings")
        settings.beginGroup("MoreSettings")
        settings.setValue("ShowMoreSettings", morestate)
        settings.endGroup()
        
    def browseMediapath(self):
        self.loadMediaBrowseSettings()
        options = QtGui.QFileDialog.Options()
        if (os.path.isdir(self.mediadirectory)):
            defaultdirectory = self.mediadirectory
        elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.MoviesLocation))):
            defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.MoviesLocation)
        elif (os.path.isdir(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))):
            defaultdirectory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation)
        else:
            defaultdirectory = ""
        browserfilter = "All files (*)"       
        fileName, filtr = QtGui.QFileDialog.getOpenFileName(self,"Browse for media files",defaultdirectory,
                browserfilter, "", options)
        if fileName:
            self.mediapathTextbox.setText(os.path.normpath(fileName))
            self.mediadirectory = os.path.dirname(fileName)
            self.saveMediaBrowseSettings()
        
    def _saveDataAndLeave(self):
        self.config['host'] = self.hostTextbox.text() if ":" in self.hostTextbox.text() else self.hostTextbox.text() + ":" + unicode(constants.DEFAULT_PORT) 
        self.config['name'] = self.usernameTextbox.text()
        self.config['room'] = self.defaultroomTextbox.text()
        self.config['password'] = self.serverpassTextbox.text()
        self.config['playerPath'] = unicode(self.executablepathCombobox.currentText())
        if self.mediapathTextbox.text() == "":
            self.config['file'] = None
        elif os.path.isfile(os.path.abspath(self.mediapathTextbox.text())):
            self.config['file'] = os.path.abspath(self.mediapathTextbox.text())
        else:
            self.config['file'] = unicode(self.mediapathTextbox.text()) 
        if self.alwaysshowCheckbox.isChecked() == True:
            self.config['forceGuiPrompt'] = True
        else:
            self.config['forceGuiPrompt'] = False
        if self.donotstoreCheckbox.isChecked() == True:
            self.config['noStore'] = True
        else:
            self.config['noStore'] = False
        if self.slowdownCheckbox.isChecked() == True:
            self.config['slowOnDesync'] = True
        else:
            self.config['slowOnDesync'] = False
        if self.pauseonleaveCheckbox.isChecked() == True:
            self.config['pauseOnLeave'] = True
        else:
            self.config['pauseOnLeave'] = False


        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            if self.rewindCheckbox.isChecked() == True:
                self.config['rewindOnDesync'] = True
            else:
                self.config['rewindOnDesync'] = False
        self.config['malUsername'] = self.malusernameTextbox.text()
        self.config['malPassword'] = self.malpasswordTextbox.text()
        
        if self.filenameprivacySendRawOption.isChecked() == True:
            self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE
        elif self.filenameprivacySendHashedOption.isChecked() == True:
            self.config['filenamePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE
        elif self.filenameprivacyDontSendOption.isChecked() == True:
            self.config['filenamePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE

        if self.filesizeprivacySendRawOption.isChecked() == True:
            self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDRAW_MODE
        elif self.filesizeprivacySendHashedOption.isChecked() == True:
            self.config['filesizePrivacyMode'] = constants.PRIVACY_SENDHASHED_MODE
        elif self.filesizeprivacyDontSendOption.isChecked() == True:
            self.config['filesizePrivacyMode'] = constants.PRIVACY_DONTSEND_MODE

        self.pressedclosebutton = True
        self.close()
        return
    
    def closeEvent(self, event):
        if self.pressedclosebutton == False:
            sys.exit()
            raise GuiConfiguration.WindowClosed
            event.accept()

    def dragEnterEvent(self, event):
        data = event.mimeData()
        urls = data.urls()
        if (urls and urls[0].scheme() == 'file'):
            event.acceptProposedAction()
            
    def dropEvent(self, event):
        data = event.mimeData()
        urls = data.urls()
        if (urls and urls[0].scheme() == 'file'):
            if sys.platform.startswith('linux'):
                dropfilepath = unicode(urls[0].path())
            else:
                dropfilepath = unicode(urls[0].path())[1:] # Removes starting slash 
            if dropfilepath[-4:].lower() == ".exe":
                self.executablepathCombobox.setEditText(dropfilepath)
            else:
                self.mediapathTextbox.setText(dropfilepath)

    def __init__(self, config, playerpaths, error):
        
        from syncplay import utils
        self.config = config
        self.datacleared = False
        if config['clearGUIData'] == True:
            settings = QSettings("Syncplay","PlayerList")
            settings.clear()
            settings = QSettings("Syncplay","MediaBrowseDialog")
            settings.clear()
            settings = QSettings("Syncplay","MainWindow")
            settings.clear()
            settings = QSettings("Syncplay","MoreSettings")
            settings.clear()
            self.datacleared = True
        self.QtGui = QtGui
        self.error = error
        if sys.platform.startswith('linux'):
            resourcespath = utils.findWorkingDir() + "/resources/"
        else:
            resourcespath = utils.findWorkingDir() + "\\resources\\"
        self.resourcespath = resourcespath

        super(ConfigDialog, self).__init__()
        
        self.setWindowTitle(getMessage("en", "config-window-title"))
        self.setWindowFlags(self.windowFlags() & Qt.WindowCloseButtonHint & ~Qt.WindowContextHelpButtonHint)
        self.setWindowIcon(QtGui.QIcon(resourcespath + "syncplay.png"))
              
        if(config['host'] == None):
            host = ""
        elif(":" in config['host']):
            host = config['host']
        else:
            host = config['host']+":"+str(config['port'])
            
        self.connectionSettingsGroup = QtGui.QGroupBox(getMessage("en", "connection-group-title"))
        self.hostTextbox = QLineEdit(host, self)
        self.hostLabel = QLabel(getMessage("en", "host-label"), self)
        self.usernameTextbox = QLineEdit(config['name'],self)
        self.serverpassLabel = QLabel(getMessage("en", "password-label"), self)
        self.defaultroomTextbox = QLineEdit(config['room'],self)
        self.usernameLabel = QLabel(getMessage("en", "username-label"), self)
        self.serverpassTextbox = QLineEdit(config['password'],self)
        self.defaultroomLabel = QLabel(getMessage("en", "room-label"), self)

        if (constants.SHOW_TOOLTIPS == True):
            self.hostLabel.setToolTip(getMessage("en", "host-tooltip"))
            self.hostTextbox.setToolTip(getMessage("en", "host-tooltip"))
            self.usernameLabel.setToolTip(getMessage("en", "username-tooltip"))
            self.usernameTextbox.setToolTip(getMessage("en", "username-tooltip"))
            self.serverpassLabel.setToolTip(getMessage("en", "password-tooltip"))
            self.serverpassTextbox.setToolTip(getMessage("en", "password-tooltip"))
            self.defaultroomLabel.setToolTip(getMessage("en", "room-tooltip"))
            self.defaultroomTextbox.setToolTip(getMessage("en", "room-tooltip"))
            
        self.connectionSettingsLayout = QtGui.QGridLayout()
        self.connectionSettingsLayout.addWidget(self.hostLabel, 0, 0)
        self.connectionSettingsLayout.addWidget(self.hostTextbox, 0, 1)
        self.connectionSettingsLayout.addWidget(self.serverpassLabel, 1, 0)
        self.connectionSettingsLayout.addWidget(self.serverpassTextbox, 1, 1)
        self.connectionSettingsLayout.addWidget(self.usernameLabel, 2, 0)
        self.connectionSettingsLayout.addWidget(self.usernameTextbox, 2, 1)
        self.connectionSettingsLayout.addWidget(self.defaultroomLabel, 3, 0)
        self.connectionSettingsLayout.addWidget(self.defaultroomTextbox, 3, 1)
        self.connectionSettingsGroup.setLayout(self.connectionSettingsLayout)
        
        self.mediaplayerSettingsGroup = QtGui.QGroupBox(getMessage("en", "media-setting-title"))
        self.executableiconImage = QtGui.QImage()
        self.executableiconLabel = QLabel(self)
        self.executableiconLabel.setMinimumWidth(16)
        self.executablepathCombobox = QtGui.QComboBox(self)
        self.executablepathCombobox.setEditable(True)
        self.executablepathCombobox.currentIndexChanged.connect(self.updateExecutableIcon)
        self.executablepathCombobox.setEditText(self._tryToFillPlayerPath(config['playerPath'], playerpaths))
        self.executablepathCombobox.setMinimumWidth(200)
        self.executablepathCombobox.setMaximumWidth(200)
        self.executablepathCombobox.editTextChanged.connect(self.updateExecutableIcon)
        
        self.executablepathLabel = QLabel(getMessage("en", "executable-path-label"), self)
        self.executablebrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label"))
        self.executablebrowseButton.clicked.connect(self.browsePlayerpath)
        self.mediapathTextbox = QLineEdit(config['file'], self)
        self.mediapathLabel = QLabel(getMessage("en", "media-path-label"), self)
        self.mediabrowseButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'folder_explore.png'),getMessage("en", "browse-label"))
        self.mediabrowseButton.clicked.connect(self.browseMediapath)
        
        if (constants.SHOW_TOOLTIPS == True):
            self.executablepathLabel.setToolTip(getMessage("en", "executable-path-tooltip"))
            self.executablepathCombobox.setToolTip(getMessage("en", "executable-path-tooltip"))
            self.mediapathLabel.setToolTip(getMessage("en", "media-path-tooltip"))
            self.mediapathTextbox.setToolTip(getMessage("en", "media-path-tooltip"))
        
        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            self.rewindCheckbox = QCheckBox(getMessage("en", "rewind-label"))
            if (constants.SHOW_TOOLTIPS == True):
                self.rewindCheckbox.setToolTip(getMessage("en", "rewind-tooltip"))
        self.mediaplayerSettingsLayout = QtGui.QGridLayout()
        self.mediaplayerSettingsLayout.addWidget(self.executablepathLabel, 0, 0)
        self.mediaplayerSettingsLayout.addWidget(self.executableiconLabel, 0, 1)
        self.mediaplayerSettingsLayout.addWidget(self.executablepathCombobox, 0, 2)
        self.mediaplayerSettingsLayout.addWidget(self.executablebrowseButton, 0, 3)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathLabel, 1, 0)
        self.mediaplayerSettingsLayout.addWidget(self.mediapathTextbox , 1, 2)
        self.mediaplayerSettingsLayout.addWidget(self.mediabrowseButton , 1, 3)
        self.mediaplayerSettingsGroup.setLayout(self.mediaplayerSettingsLayout)

        self.moreSettingsGroup = QtGui.QGroupBox(getMessage("en", "more-title"))

        self.moreSettingsGroup.setCheckable(True)
        self.malSettingsSplit = QtGui.QSplitter(self)
        self.malusernameTextbox = QLineEdit(config['malUsername'],self)
        self.malusernameTextbox.setMaximumWidth(115)
        self.malusernameLabel = QLabel(getMessage("en", "mal-username-label"), self)
        
        self.malpasswordTextbox = QLineEdit(config['malPassword'],self)
        self.malpasswordTextbox.setEchoMode(QtGui.QLineEdit.Password)
        self.malpasswordLabel = QLabel(getMessage("en", "mal-password-label"), self)
        
        ### <MAL DISABLE>
        self.malpasswordTextbox.hide()
        self.malpasswordLabel.hide()
        self.malusernameTextbox.hide()
        self.malusernameLabel.hide()
        ### </MAL DISABLE>
        
        self.filenameprivacyLabel = QLabel(getMessage("en", "filename-privacy-label"), self)
        self.filenameprivacyButtonGroup = QButtonGroup()
        self.filenameprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option"))
        self.filenameprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option"))
        self.filenameprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option"))
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendRawOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacySendHashedOption)
        self.filenameprivacyButtonGroup.addButton(self.filenameprivacyDontSendOption)
        
        self.filesizeprivacyLabel = QLabel(getMessage("en", "filesize-privacy-label"), self)
        self.filesizeprivacyButtonGroup = QButtonGroup()
        self.filesizeprivacySendRawOption = QRadioButton(getMessage("en", "privacy-sendraw-option"))
        self.filesizeprivacySendHashedOption = QRadioButton(getMessage("en", "privacy-sendhashed-option"))
        self.filesizeprivacyDontSendOption = QRadioButton(getMessage("en", "privacy-dontsend-option"))
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendRawOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacySendHashedOption)
        self.filesizeprivacyButtonGroup.addButton(self.filesizeprivacyDontSendOption)
        
        self.slowdownCheckbox = QCheckBox(getMessage("en", "slowdown-label"))
        self.pauseonleaveCheckbox = QCheckBox(getMessage("en", "pauseonleave-label"))
        self.alwaysshowCheckbox = QCheckBox(getMessage("en", "alwayshow-label"))
        self.donotstoreCheckbox = QCheckBox(getMessage("en", "donotstore-label"))
        
        filenamePrivacyMode = config['filenamePrivacyMode']
        if filenamePrivacyMode == constants.PRIVACY_DONTSEND_MODE:
            self.filenameprivacyDontSendOption.setChecked(True)
        elif filenamePrivacyMode == constants.PRIVACY_SENDHASHED_MODE:
            self.filenameprivacySendHashedOption.setChecked(True)
        else:
            self.filenameprivacySendRawOption.setChecked(True)
            
        filesizePrivacyMode = config['filesizePrivacyMode']
        if filesizePrivacyMode == constants.PRIVACY_DONTSEND_MODE:
            self.filesizeprivacyDontSendOption.setChecked(True)
        elif filesizePrivacyMode == constants.PRIVACY_SENDHASHED_MODE:
            self.filesizeprivacySendHashedOption.setChecked(True)
        else:
            self.filesizeprivacySendRawOption.setChecked(True)
        
        if config['slowOnDesync'] == True:
            self.slowdownCheckbox.setChecked(True)
        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True and config['rewindOnDesync'] == True:
            self.rewindCheckbox.setChecked(True)
        if config['pauseOnLeave'] == True:
            self.pauseonleaveCheckbox.setChecked(True)
        
        if (constants.SHOW_TOOLTIPS == True):
            self.malusernameLabel.setToolTip(getMessage("en", "mal-username-tooltip"))
            self.malusernameTextbox.setToolTip(getMessage("en", "mal-username-tooltip"))
            self.malpasswordLabel.setToolTip(getMessage("en", "mal-password-tooltip"))
            self.malpasswordTextbox.setToolTip(getMessage("en", "mal-password-tooltip"))
            
            self.filenameprivacyLabel.setToolTip(getMessage("en", "filename-privacy-tooltip"))
            self.filenameprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip"))
            self.filenameprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip"))
            self.filenameprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip"))
            self.filesizeprivacyLabel.setToolTip(getMessage("en", "filesize-privacy-tooltip"))
            self.filesizeprivacySendRawOption.setToolTip(getMessage("en", "privacy-sendraw-tooltip"))
            self.filesizeprivacySendHashedOption.setToolTip(getMessage("en", "privacy-sendhashed-tooltip"))
            self.filesizeprivacyDontSendOption.setToolTip(getMessage("en", "privacy-dontsend-tooltip"))
            
            self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip"))
            self.pauseonleaveCheckbox.setToolTip(getMessage("en", "pauseonleave-tooltip"))
            self.alwaysshowCheckbox.setToolTip(getMessage("en", "alwayshow-tooltip"))
            self.donotstoreCheckbox.setToolTip(getMessage("en", "donotstore-tooltip"))
            self.slowdownCheckbox.setToolTip(getMessage("en", "slowdown-tooltip"))
            
        self.moreSettingsLayout = QtGui.QGridLayout()
        
        self.privacySettingsLayout = QtGui.QGridLayout()
        self.privacyFrame = QtGui.QFrame()
        self.privacyFrame.setLineWidth(0)
        self.privacyFrame.setMidLineWidth(0)
        self.privacySettingsLayout.setContentsMargins(0,0,0,0)
        self.privacySettingsLayout.addWidget(self.filenameprivacyLabel, 0, 0)
        self.privacySettingsLayout.addWidget(self.filenameprivacySendRawOption, 0, 1, Qt.AlignRight) 
        self.privacySettingsLayout.addWidget(self.filenameprivacySendHashedOption, 0,2, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filenameprivacyDontSendOption, 0, 3, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacyLabel, 1, 0)
        self.privacySettingsLayout.addWidget(self.filesizeprivacySendRawOption, 1, 1, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacySendHashedOption, 1, 2, Qt.AlignRight)
        self.privacySettingsLayout.addWidget(self.filesizeprivacyDontSendOption, 1, 3, Qt.AlignRight)
        self.privacyFrame.setLayout(self.privacySettingsLayout)
        
        self.moreSettingsLayout.addWidget(self.privacyFrame, 0, 0, 1, 4)

        self.moreSettingsLayout.addWidget(self.malusernameLabel , 1, 0)
        self.moreSettingsLayout.addWidget(self.malusernameTextbox, 1, 1)
        self.moreSettingsLayout.addWidget(self.malpasswordLabel , 1, 2)
        self.moreSettingsLayout.addWidget(self.malpasswordTextbox, 1, 3)

        self.moreSettingsLayout.addWidget(self.slowdownCheckbox, 2, 0,1,4)
        if constants.SHOW_REWIND_ON_DESYNC_CHECKBOX == True:
            self.moreSettingsLayout.addWidget(self.rewindCheckbox, 3, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.pauseonleaveCheckbox, 4, 0, 1, 4)      
        self.moreSettingsLayout.addWidget(self.alwaysshowCheckbox, 5, 0, 1, 4)
        self.moreSettingsLayout.addWidget(self.donotstoreCheckbox, 6, 0, 1, 4)

        self.moreSettingsGroup.setLayout(self.moreSettingsLayout)
        
        self.showmoreCheckbox = QCheckBox(getMessage("en", "more-title"))
        
        if self.getMoreState() == False:
            self.showmoreCheckbox.setChecked(False)
            self.moreSettingsGroup.hide()
        else:
            self.showmoreCheckbox.hide()
        self.showmoreCheckbox.toggled.connect(self.moreToggled)            
        self.moreSettingsGroup.toggled.connect(self.moreToggled)
        
        if config['forceGuiPrompt'] == True:
            self.alwaysshowCheckbox.setChecked(True)
        
        if (constants.SHOW_TOOLTIPS == True):
            self.showmoreCheckbox.setToolTip(getMessage("en", "more-tooltip"))
               
        self.donotstoreCheckbox.toggled.connect(self.runButtonTextUpdate)
                      
        self.mainLayout = QtGui.QVBoxLayout()
        if error:
            self.errorLabel = QLabel(error, self)
            self.errorLabel.setAlignment(Qt.AlignCenter)
            self.errorLabel.setStyleSheet("QLabel { color : red; }")
            self.mainLayout.addWidget(self.errorLabel)
        self.mainLayout.addWidget(self.connectionSettingsGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.mediaplayerSettingsGroup)
        self.mainLayout.addSpacing(12)
        self.mainLayout.addWidget(self.showmoreCheckbox)
        self.mainLayout.addWidget(self.moreSettingsGroup)
        self.mainLayout.addSpacing(12)
        
        self.topLayout = QtGui.QHBoxLayout()
        self.helpButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'help.png'),getMessage("en", "help-label"))
        if (constants.SHOW_TOOLTIPS == True):
            self.helpButton.setToolTip(getMessage("en", "help-tooltip"))
        self.helpButton.setMaximumSize(self.helpButton.sizeHint())
        self.helpButton.pressed.connect(self.openHelp)
        self.runButton = QtGui.QPushButton(QtGui.QIcon(resourcespath + 'accept.png'),getMessage("en", "storeandrun-label"))
        self.runButton.pressed.connect(self._saveDataAndLeave)
        if config['noStore'] == True:
            self.donotstoreCheckbox.setChecked(True)
            self.runButton.setText(getMessage("en", "run-label"))
        self.topLayout.addWidget(self.helpButton, Qt.AlignLeft)
        self.topLayout.addWidget(self.runButton, Qt.AlignRight)
        self.mainLayout.addLayout(self.topLayout)
        
        self.mainLayout.addStretch(1)
        self.setLayout(self.mainLayout)
        self.runButton.setFocus()        
        self.setFixedSize(self.sizeHint())
        self.setAcceptDrops(True)
        
        if self.datacleared == True:
            QtGui.QMessageBox.information(self,"Syncplay", getMessage("en", "gui-data-cleared-notification"))
    def __init__(self,main_window):
        QWidget.__init__(self)
        self.main_window = main_window
        self.layout = QGridLayout()
        self.setLayout(self.layout)
        
        self.lr = numpy.zeros(2)
        
        self.fps = QSpinBox()
        self.fps.setValue(25)
        self.fps.setMinimum(1)
        self.fps.setMaximum(1000)
        self.layout.addWidget(QLabel("FPS:"),10,10)
        self.layout.addWidget(self.fps,10,11)
        
        self.capture_area_group = QButtonGroup()
        self.capture_area_fs = QRadioButton("Full Screen")
        self.connect(self.capture_area_fs, SIGNAL("clicked()"),self.capture_area_change)
        self.capture_area_fs.setChecked(True)
        self.capture_area_sa = QRadioButton("Selected Area")
        self.connect(self.capture_area_sa, SIGNAL("clicked()"),self.capture_area_change)
        self.capture_area_group.addButton(self.capture_area_fs)
        self.capture_area_group.addButton(self.capture_area_sa)
        self.capture_area_group.setExclusive(True)
        
        self.layout.addWidget(self.capture_area_fs,12,10)
        self.layout.addWidget(self.capture_area_sa,12,11)
        
        self.sa_group = QGroupBox()
        self.sa_grid = QGridLayout()
        self.sa_group.setLayout(self.sa_grid)
        
        
        self.sa_ul_bt = QPushButton("Select Upper Left")
        self.connect(self.sa_ul_bt, SIGNAL("clicked()"), self.select_ul)
        self.sa_lr_bt = QPushButton("Select Lower Right")
        self.connect(self.sa_lr_bt, SIGNAL("clicked()"), self.select_lr)

        self.sa_x = QSpinBox()
        self.sa_y = QSpinBox()
        self.sa_w = QSpinBox()
        self.sa_h = QSpinBox()
        for sb in [self.sa_h,self.sa_w,self.sa_x,self.sa_y]:
            sb.setMaximum(999999)
            sb.setMinimum(0)
        
        self.sa_grid.addWidget(self.sa_ul_bt,14,10,1,1)
        self.sa_grid.addWidget(self.sa_lr_bt,15,10,1,1)
        self.sa_grid.addWidget(QLabel("x"),14,11,1,1)
        self.sa_grid.addWidget(self.sa_x,14,12,1,1)
        self.sa_grid.addWidget(QLabel("y"),15,11,1,1)
        self.sa_grid.addWidget(self.sa_y,15,12,1,1)
        self.sa_grid.addWidget(QLabel("w"),16,11,1,1)
        self.sa_grid.addWidget(self.sa_w,16,12,1,1)
        self.sa_grid.addWidget(QLabel("h"),17,11,1,1)
        self.sa_grid.addWidget(self.sa_h,17,12,1,1)
        
        self.sa_show_bt = QPushButton("Show Area")
        self.sa_show_bt.setCheckable(True)
        self.connect(self.sa_show_bt, SIGNAL("clicked()"), self.show_selected_area)

        
        self.sa_grid.addWidget(self.sa_show_bt,18,10,1,10)
        
        self.sa_group.hide()
        
        self.layout.addWidget(self.sa_group,14,10,1,10)
        
        self.capture_delay = QSpinBox()
        self.capture_delay.setMinimum(0)
        self.capture_delay.setMaximum(10000)
        
        self.layout.addWidget(QLabel("Capture Delay"),18,10,1,1)
        self.layout.addWidget(self.capture_delay,18,11,1,1)
        
        self.capture_bt = QPushButton("Capture")
        self.stop_capture_bt = QPushButton("Stop")
        self.stop_capture_bt.hide()
        self.layout.addWidget(self.capture_bt,20,10,1,10)
        self.layout.addWidget(self.stop_capture_bt,30,10,1,10)
        
        self.ffmpeg_flags = QLineEdit()
        self.ffmpeg_flags.setText("-qscale 0 -vcodec mpeg4")
        self.layout.addWidget(QLabel("FFMPEG Flags:"),40,10)
        self.layout.addWidget(self.ffmpeg_flags,50,10,1,10)
        
        self.encode_bt = QPushButton("Encode Video")
        self.layout.addWidget(self.encode_bt,60,10,1,10)
        
        self.open_dir_bt = QPushButton("Open Directory")
        self.layout.addWidget(self.open_dir_bt,80,10,1,10)
        
        self.connect(self.open_dir_bt, SIGNAL("clicked()"),self.open_cwd)
    
        self.selected_area = SelectedArea()
Exemple #54
0
class Panel(QWidget):

    def __init__(self, state, config, parent):
        super().__init__(parent)
        self.state = state
        self.config = config
        self.form = parent
        self.createWidgets()
        self.layoutWidgets()
        self.createConnections()


    def createWidgets(self):
        settings = QSettings()

        self.txtGroupBox = QGroupBox("Plain Text Format (.txt)")
        self.indentLabel = QLabel("&Indent")
        self.indentComboBox = QComboBox()
        self.indentLabel.setBuddy(self.indentComboBox)
        oldIndent = IndentKind.TAB
        oldIndent = self.config.get(Gconf.Key.Indent, oldIndent)
        index = -1
        for i, indent in enumerate(IndentKind):
            text = indent.name.replace("_", " ").title()
            self.indentComboBox.addItem(text, indent.value)
            if indent is oldIndent:
                index = i
        self.indentComboBox.setCurrentIndex(index)
        self.form.tooltips.append((self.indentComboBox, """\
<p><b>Indent</b></p>
<p>The indentation to use when outputting an indented-style index in
plain text format for each level of indentation.</p>"""))

        self.rtfGroupBox = QGroupBox("Rich Text Format (.rtf)")
        self.rtfIndentLabel = QLabel("I&ndent")
        self.rtfIndentComboBox = QComboBox()
        self.rtfIndentLabel.setBuddy(self.rtfIndentComboBox)
        oldIndent = IndentKind(int(settings.value(Gopt.Key.IndentRTF,
                                                  Gopt.Default.IndentRTF)))
        index = -1
        for i, indent in enumerate(IndentKind):
            text = ("Indent" if i == 0 else
                    indent.name.replace("_", " ").title())
            self.rtfIndentComboBox.addItem(text, indent.value)
            if indent is oldIndent:
                index = i
        self.rtfIndentComboBox.setCurrentIndex(index)
        self.form.tooltips.append((self.rtfIndentComboBox, """\
<p><b>Indent</b></p>
<p>The indentation to use when outputting an indented-style index in
rich text format for each level of indentation.</p>"""))

        self.pdfGroupBox = QGroupBox("Portable Document Format (.pdf)")
        self.paperSizeLabel = QLabel("Paper Size")
        self.letterRadioButton = QRadioButton("&Letter")
        self.a4RadioButton = QRadioButton("&A4")
        size = PaperSizeKind(int(settings.value(Gopt.Key.PaperSize,
                                                Gopt.Default.PaperSize)))
        if size is PaperSizeKind.LETTER:
            self.letterRadioButton.setChecked(True)
        else:
            self.a4RadioButton.setChecked(True)
        self.form.tooltips.append((self.letterRadioButton, """\
<p><b>Paper Size, Letter</b></p>
<p>If checked, when outputting a PDF of the index, US Letter
8.5"x11"-sized pages will be used.</p>"""))
        self.form.tooltips.append((self.a4RadioButton, """\
<p><b>Paper Size, A4</b></p>
<p>If checked, when outputting a PDF of the index, European A4-sized
pages will be used.</p>"""))


    def layoutWidgets(self):
        hbox = QHBoxLayout()
        hbox.addWidget(self.indentLabel)
        hbox.addWidget(self.indentComboBox)
        hbox.addStretch()
        self.txtGroupBox.setLayout(hbox)

        hbox = QHBoxLayout()
        hbox.addWidget(self.rtfIndentLabel)
        hbox.addWidget(self.rtfIndentComboBox)
        hbox.addStretch()
        self.rtfGroupBox.setLayout(hbox)

        hbox = QHBoxLayout()
        hbox.addWidget(self.paperSizeLabel)
        hbox.addWidget(self.letterRadioButton)
        hbox.addWidget(self.a4RadioButton)
        hbox.addStretch()
        self.pdfGroupBox.setLayout(hbox)

        vbox = QVBoxLayout()
        vbox.addWidget(self.rtfGroupBox)
        vbox.addWidget(self.txtGroupBox)
        vbox.addWidget(self.pdfGroupBox)
        vbox.addStretch()

        self.setLayout(vbox)


    def createConnections(self):
        self.indentComboBox.currentIndexChanged.connect(self.setIndent)
        self.rtfIndentComboBox.currentIndexChanged.connect(
            self.setIndentRTF)


    def setIndent(self, index):
        index = self.indentComboBox.currentIndex()
        indent = int(self.indentComboBox.itemData(index))
        if bool(self.state.model):
            self.state.model.setConfig(Gconf.Key.Indent, indent)


    def setIndentRTF(self, index):
        index = self.rtfIndentComboBox.currentIndex()
        indent = int(self.rtfIndentComboBox.itemData(index))
        settings = QSettings()
        settings.setValue(Gopt.Key.IndentRTF, indent)
Exemple #55
0
    def __init__(self, parent, order_overview_widget, find_order_slot):
        global configuration

        super(PostViewWidget, self).__init__(parent)

        self.set_panel_title(_("Post overview"))
        self.bold_font = QFont(self.font())
        self.bold_font.setBold(True)
        self.nb_cols = 8  # Number of columns in the operation definition table

        self.order_overview_widget = order_overview_widget

        self.button = QPushButton(_("Refresh"), self)
        self.button.clicked.connect(self.refresh_action)
        self.sort_by_deadline_button = QRadioButton(_("By deadline"), self)
        self.sort_by_deadline_button.toggled.connect(self.sort_by_deadline)
        self.sort_by_size_button = QRadioButton(_("By hours left to do"), self)
        self.sort_by_size_button.toggled.connect(self.sort_by_size)

        # hlayout = QHBoxLayout()
        # hlayout.setObjectName("halyout")
        # hlayout.setContentsMargins(0,0,0,0)
        # hlayout.addWidget(self.sort_by_deadline_button)
        # hlayout.addWidget(self.sort_by_size_button)
        # hlayout.addWidget(self.button)
        # hlayout.addStretch()

        self.navbar = NavBar(self, [(self.sort_by_deadline_button, None),
                                    (self.sort_by_size_button, None),
                                    (self.button, None),
                                    (_("Find"), find_order_slot)])
        self.navbar.buttons[3].setObjectName("specialMenuButton")

        self.vlayout = QVBoxLayout(self)
        self.vlayout.setObjectName("Vlayout")
        self.vlayout.addWidget(
            TitleWidget(_("Posts Overview"), self, self.navbar))

        self._table_model = QStandardItemModel(1, self.nb_cols, self)
        self.table_view = QTableView(None)
        self.table_view.setModel(self._table_model)
        self.table_view.selectionModel().currentChanged.connect(
            self.operation_selected)

        self.table_view.verticalHeader().hide()
        self.table_view.horizontalHeader().hide()
        self.table_view.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.table_view.setSelectionBehavior(QAbstractItemView.SelectRows)

        # This forces Qt to expand layout once I fill data in
        # FIXME dirty but I really don't get why setting
        # the mini width to something smaller (that happens at
        # startup, on first refresh) doesn't work
        self.table_view.setMinimumWidth(1)
        self.table_view.setMaximumWidth(1)

        self.post_view_scene = PostViewScene(self, order_overview_widget)
        self.post_view_scene_view = QGraphicsView(self)
        self.post_view_scene_view.setScene(self.post_view_scene)
        self.post_view_scene_view.setSizePolicy(QSizePolicy.Expanding,
                                                QSizePolicy.Expanding)

        self.splitter = QSplitter(Qt.Horizontal)
        self.splitter.addWidget(
            SubFrame(_("Posts"), self.table_view, self.splitter))
        self.splitter.addWidget(
            SubFrame(_("Workload"), self.post_view_scene_view, self.splitter))
        # self.splitter.setStretchFactor(0,1)
        self.splitter.setStretchFactor(1, 1)
        self.vlayout.addWidget(self.splitter)

        # hlayout = QHBoxLayout()
        # hlayout.addWidget(SubFrame(_("Posts"),self.table_view,self))
        # hlayout.addWidget(SubFrame(_("Workload"),self.post_view_scene_view,self))
        # hlayout.setStretch(1,1)
        # self.vlayout.addLayout(hlayout)

        self.vlayout.setStretch(0, 0)
        self.vlayout.setStretch(1, 1)

        self.setLayout(self.vlayout)

        self.timer = QTimer(self)
        self.timer.timeout.connect(self.slidePostsScene)

        self.current_view_y = 0
Exemple #56
0
class RateView(QGroupBox):
    '''The box containing the rate value'''

    def __init__(self, title = 'Rate', parent = None):
        '''Initialize'''
        super(RateView, self).__init__(parent)
        self.setTitle(title)
        self._createWidgets()

    def _createWidgets(self):
        '''Create the widgets contained in this box'''

        # Rate or lifetime chooser
        self.rate = QRadioButton('Rate', self)
        self.rate.setToolTip(ttt('Choose this to express exchange as rate'))
        self.lifetime = QRadioButton('Lifetime', self)
        self.lifetime.setToolTip(ttt('Choose this to express exchange as '
                                     'lifetime'))

        # Box containing value
        self.rate_value = QLineEdit(self)
        validate = QDoubleValidator(self.rate_value)
        validate.setDecimals(3)
        validate.setBottom(0.0)
        self.rate_value.setValidator(validate)
        self.rate_value.setToolTip(ttt('The rate or lifetime value'))

        # Unit
        self.unit = QComboBox(self)
        self.unit.setToolTip(ttt('Selects the input unit for the rate '
                                 'or lifetime'))

    def initUI(self):
        '''Lays out the widgets'''
        radios = QVBoxLayout()
        radios.addWidget(self.rate)
        radios.addWidget(self.lifetime)
        rate = QGridLayout()
        rate.addWidget(QLabel("Unit: "), 1, 1)
        rate.addWidget(self.unit, 1, 2)
        rate.addWidget(QLabel("Value: "), 2, 1)
        rate.addWidget(self.rate_value, 2, 2)
        total = QHBoxLayout()
        total.addLayout(radios)
        total.addStretch()
        total.addLayout(rate)
        self.setLayout(total)

    def makeConnections(self):
        '''Connect the widgets together'''

        # When one radio button is checked, change the combo box model
        # and un-check the other radio button
        self.rate.clicked.connect(self.setRateModel)
        self.lifetime.clicked.connect(self.setLifetimeModel)

        # If the text changes, emit that rate
        self.rate_value.editingFinished.connect(self.emitRate)

        # If the underlying model changes, adjust the text
        self.model.rateChanged.connect(self.updateRate)

        # If the unit changes, update rate
        self.unit.currentIndexChanged.connect(self.updateUnit)

    def setModel(self, model):
        '''Attaches models to the views'''
        self.model = model

    def setRate(self, rate):
        '''Set the rate manually'''
        self.rate_value.setText(str(rate))
        self.rate_value.editingFinished.emit()

    def setUnit(self, unit):
        '''Set the unit manually'''
        if unit == 's':
            self.lifetime.click()
            self.unit.setCurrentIndex(0)
        elif unit == 'ns':
            self.lifetime.click()
            self.unit.setCurrentIndex(1)
        elif unit == 'ps':
            self.lifetime.click()
            self.unit.setCurrentIndex(2)
        elif unit == 'fs':
            self.lifetime.click()
            self.unit.setCurrentIndex(3)
        elif unit in ('Hz', 'hz'):
            self.rate.click()
            self.unit.setCurrentIndex(0)
        elif unit in ('GHz', 'ghz'):
            self.rate.click()
            self.unit.setCurrentIndex(1)
        elif unit in ('THz', 'thz'):
            self.rate.click()
            self.unit.setCurrentIndex(2)
        elif unit in ('PHz', 'phz'):
            self.rate.click()
            self.unit.setCurrentIndex(3)
        else:
            error.showMessage('Invalid unit: {0}'.format(unit))

    #######
    # SLOTS
    #######

    def updateRate(self):
        '''Updates the rate of the text box'''
        # Do nothing if rate is not yet defined
        try:
            rate = self.model.rate
        except AttributeError:
            return
        if 0.1 > rate or rate > 100:
            self.rate_value.setText('{0:.3E}'.format(rate))
        else:
            self.rate_value.setText('{0:.3F}'.format(rate))

    def emitRate(self):
        '''Converts the text to a float and emits'''
        # Do nothing if there is no number
        try:
            self.model.setRate(float(self.rate_value.text()))
        except ValueError:
            pass

    def updateUnit(self):
        '''Update for a change of unit'''
        # If there is no unit yet, just set it
        try:
            unit = self.model.unit
        except AttributeError:
            self.model.setConverter(str(self.unit.currentText()))
            try:
                self.model.setRate(float(self.rate_value.text()))
            except ValueError:
                pass
            return
        # Convert unit appropriately
        if self.rate.isChecked():
            if unit == 'Hz':
                conv = { 'GHz' : 1E-9,
                         'THz' : 1E-12,
                         'PHz' : 1E-15 }
            elif unit == 'GHz':
                conv = { 'Hz'  : 1E9,
                         'THz' : 1E-3,
                         'PHz' : 1E-6 }
            elif unit == 'THz':
                conv = { 'Hz'  : 1E12,
                         'GHz' : 1E3,
                         'PHz' : 1E-3 }
            elif unit == 'PHz':
                conv = { 'Hz'  : 1E15,
                         'GHz' : 1E6,
                         'THz' : 1E3 }
            else:
                conv = { ''    : 1,
                         'Hz'  : 1, 
                         'GHz' : 1, 
                         'THz' : 1, 
                         'PHz' : 1, }
        else:
            if unit == 's':
                conv = { 'ns' : 1E9,
                         'ps' : 1E12,
                         'fs' : 1E15 }
            elif unit == 'ns':
                conv = { 's'  : 1E-9,
                         'ps' : 1E3,
                         'fs' : 1E6 }
            elif unit == 'ps':
                conv = { 's'  : 1E-12,
                         'ns' : 1E-3,
                         'fs' : 1E3 }
            elif unit == 'fs':
                conv = { 's'  : 1E-15,
                         'ns' : 1E-6,
                         'ps' : 1E-3 }
            else:
                conv = { ''   : 1,
                         's'  : 1, 
                         'ns' : 1, 
                         'ps' : 1, 
                         'fs' : 1, }
        try:
            # Set the new converter, then change the rate
            self.model.setConverter(str(self.unit.currentText()))
            try:
                self.model.setRate(float(self.rate_value.text())
                                 * conv[str(self.unit.currentText())])
            except ValueError:
                pass
        except KeyError:
            pass

        # Save the new unit
        self.model.unit = str(self.unit.currentText())

    def setRateModel(self):
        '''Change the model to use the rate'''
        if self.model.method == 'rate':
            return
        self.model.method = 'rate'
        indx = self.unit.currentIndex()
        self.unit.setModel(self.model.runits)
        self.model.unit = str(self.unit.itemText(indx))
        self.unit.setCurrentIndex(indx)
        self.model.setConverter(self.model.unit)
        try:
            self.model.setRate(1 / float(self.rate_value.text()))
        except (ZeroDivisionError, ValueError):
            pass

    def setLifetimeModel(self):
        '''Change the model to use the lifetime'''
        if self.model.method == 'lifetime':
            return
        self.model.method = 'lifetime'
        indx = self.unit.currentIndex()
        self.unit.setModel(self.model.lunits)
        self.model.unit = str(self.unit.itemText(indx))
        self.unit.setCurrentIndex(indx)
        self.model.setConverter(self.model.unit)
        try:
            self.model.setRate(1 / float(self.rate_value.text()))
        except (ZeroDivisionError, ValueError):
            pass
    def __init__(self, setting_dict):
        BasePane.__init__( self )

        repLayout = QVBoxLayout()

        genLayout = QFormLayout()
        self.winLenEdit = QLineEdit()
        genLayout.addRow(QLabel('Window length (s):'),self.winLenEdit)
        self.timeStepEdit = QLineEdit()
        genLayout.addRow(QLabel('Time step (s):'),self.timeStepEdit)
        self.minFreqEdit = QLineEdit()
        genLayout.addRow(QLabel('Minimum frequency (Hz):'),self.minFreqEdit)
        self.maxFreqEdit = QLineEdit()
        genLayout.addRow(QLabel('Maximum frequency (Hz):'),self.maxFreqEdit)
        self.numCoresEdit = QLineEdit()
        genLayout.addRow(QLabel('Number of cores (multiprocessing):'),self.numCoresEdit)

        repBox = QGroupBox()
        self.envelopeRadio = QRadioButton('Amplitude envelopes')
        self.mfccRadio = QRadioButton('MFCCs')
        self.mhecRadio = QRadioButton('MHECs')
        self.prosodyRadio = QRadioButton('Prosody')
        self.formantRadio = QRadioButton('Formants')
        hbox = QHBoxLayout()
        hbox.addWidget(self.envelopeRadio)
        hbox.addWidget(self.mfccRadio)
        #hbox.addWidget(self.mhecRadio)
        #hbox.addWidget(self.prosodyRadio)
        #hbox.addWidget(self.formantRadio)
        repBox.setLayout(hbox)

        genLayout.addRow(QLabel('Token representation:'),repBox)

        genWidget = QGroupBox('General')
        genWidget.setLayout(genLayout)
        repLayout.addWidget(genWidget)

        envLayout = QFormLayout()
        self.bandEdit = QLineEdit()
        envLayout.addRow(QLabel('Number of bands:'),self.bandEdit)
        self.gammatoneCheck = QCheckBox()
        envLayout.addRow(QLabel('Gammatone:'),self.gammatoneCheck)
        self.windowCheck = QCheckBox()
        envLayout.addRow(QLabel('Windowed:'),self.windowCheck)


        envWidget = QGroupBox('Amplitude envelopes')
        envWidget.setLayout(envLayout)
        repLayout.addWidget(envWidget)

        mfccLayout = QFormLayout()
        self.numCCEdit = QLineEdit()
        mfccLayout.addRow(QLabel('Number of coefficents:'),self.numCCEdit)
        self.numFiltersEdit = QLineEdit()
        mfccLayout.addRow(QLabel('Number of filters:'),self.numFiltersEdit)
        self.powerCheck = QCheckBox()
        mfccLayout.addRow(QLabel('Use power (first coefficient):'),self.powerCheck)

        mfccWidget = QGroupBox('MFCC')
        mfccWidget.setLayout(mfccLayout)

        repLayout.addWidget(mfccWidget)

        self.setLayout(repLayout)

        self.winLenEdit.setText(str(setting_dict['win_len']))
        self.timeStepEdit.setText(str(setting_dict['time_step']))
        freq_lims = setting_dict['freq_lims']
        self.minFreqEdit.setText(str(freq_lims[0]))
        self.maxFreqEdit.setText(str(freq_lims[1]))
        self.numCoresEdit.setText(str(setting_dict['num_cores']))

        rep = setting_dict['rep']
        if rep == 'mfcc':
            self.mfccRadio.setChecked(True)
        elif rep == 'mhec':
            self.mhecRadio.setChecked(True)
        elif rep == 'prosody':
            self.prosodyRadio.setChecked(True)
        elif rep == 'formant':
            self.formantRadio.setChecked(True)
        elif rep == 'envelopes':
            self.envelopeRadio.setChecked(True)

        self.bandEdit.setText(str(setting_dict['envelope_bands']))

        if setting_dict['use_gammatone']:
            self.gammatoneCheck.setChecked(True)
        if setting_dict['use_window']:
            self.windowCheck.setChecked(True)

        self.numFiltersEdit.setText(str(setting_dict['mfcc_filters']))
        self.numCCEdit.setText(str(setting_dict['num_coeffs']))
        if setting_dict['use_power']:
            self.powerCheck.setChecked(True)

        self.prev_state = setting_dict
Exemple #58
0
    def setupUi(self):

        scene = QGraphicsScene(self)
        self.view = QGraphicsView(scene, self)
        self.view.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.view.setVisible(True)
        self.view.setInteractive(True)

        self.createPixmapIcon()

        self.mapWidget = MapWidget(self.mapManager)
        scene.addItem(self.mapWidget)
        self.mapWidget.setCenter(QGeoCoordinate(-8.1, -34.95))
        self.mapWidget.setZoomLevel(5)

        #...
        self.slider = QSlider(Qt.Vertical, self)
        self.slider.setTickInterval(1)
        self.slider.setTickPosition(QSlider.TicksBothSides)
        self.slider.setMaximum(self.mapManager.maximumZoomLevel())
        self.slider.setMinimum(self.mapManager.minimumZoomLevel())

        self.slider.valueChanged[int].connect(self.sliderValueChanged)
        self.mapWidget.zoomLevelChanged[float].connect(self.mapZoomLevelChanged)

        mapControlLayout = QVBoxLayout()

        self.mapWidget.mapTypeChanged.connect(self.mapTypeChanged)

        for mapType in self.mapWidget.supportedMapTypes():
            radio = QRadioButton(self)
            if mapType == QGraphicsGeoMap.StreetMap:
                radio.setText('Street')
            elif mapType == QGraphicsGeoMap.SatelliteMapDay:
                radio.setText('Sattelite')
            elif mapType == QGraphicsGeoMap.SatelliteMapNight:
                radio.setText('Sattelite - Night')
            elif mapType == QGraphicsGeoMap.TerrainMap:
                radio.setText('Terrain')

            if mapType == self.mapWidget.mapType():
                radio.setChecked(True)

            radio.toggled[bool].connect(self.mapTypeToggled)

            self.mapControlButtons.append(radio)
            self.mapControlTypes.append(mapType)
            mapControlLayout.addWidget(radio)

        self.latitudeEdit = QLineEdit()
        self.longitudeEdit = QLineEdit()

        formLayout = QFormLayout()
        formLayout.addRow('Latitude', self.latitudeEdit)
        formLayout.addRow('Longitude', self.longitudeEdit)

        self.captureCoordsButton = QToolButton()
        self.captureCoordsButton.setText('Capture coordinates')
        self.captureCoordsButton.setCheckable(True)

        self.captureCoordsButton.toggled[bool].connect(
                self.mapWidget.setMouseClickCoordQuery)
        self.mapWidget.coordQueryResult.connect(self.updateCoords)

        self.setCoordsButton = QPushButton()
        self.setCoordsButton.setText('Set coordinates')
        self.setCoordsButton.clicked.connect(self.setCoordsClicked)

        buttonLayout = QHBoxLayout()

        buttonLayout.addWidget(self.captureCoordsButton)
        buttonLayout.addWidget(self.setCoordsButton)

        coordControlLayout = QVBoxLayout()
        coordControlLayout.addLayout(formLayout)
        coordControlLayout.addLayout(buttonLayout)

        widget = QWidget(self)
        layout = QGridLayout()
        layout.setRowStretch(0, 1)
        layout.setRowStretch(1, 0)

        topLayout = QGridLayout()
        bottomLayout = QGridLayout()

        topLayout.setColumnStretch(0, 0)
        topLayout.setColumnStretch(1, 1)

        bottomLayout.setColumnStretch(0, 0)
        bottomLayout.setColumnStretch(1, 1)

        topLayout.addWidget(self.slider, 0, 0)
        topLayout.addWidget(self.view, 0, 1)

        bottomLayout.addLayout(mapControlLayout, 0, 0)
        bottomLayout.addLayout(coordControlLayout, 0, 1)

        layout.addLayout(topLayout, 0, 0)
        layout.addLayout(bottomLayout, 1, 0)

        self.layout = layout
        widget.setLayout(layout)
        self.setCentralWidget(widget)

        self.view.setContextMenuPolicy(Qt.CustomContextMenu)

        self.view.customContextMenuRequested.connect(self.customContextMenuRequest)
Exemple #59
0
    def createWidgets(self):
        selectedEid = self.state.viewAllPanel.view.selectedEid
        self.selectedEntry = self.state.model.entry(selectedEid)
        self.entry1Label = QLabel("cross-reference from ")
        self.termLabel = Widgets.Label.HtmlLabel("“{}”".format(
            Lib.elidePatchHtml(self.selectedEntry.term, self.state)))
        self.entry2Label = QLabel(" to")
        self.seeRadioButton = QRadioButton("&See")
        self.seeRadioButton.setChecked(True)
        self.tooltips.append((self.seeRadioButton, """<p><b>See</b></p>
<p>Check to create a <i>see</i> cross-reference.</p>"""))
        self.alsoRadioButton = QRadioButton("See &Also")
        self.tooltips.append((self.alsoRadioButton, """<p><b>See
Also</b></p>
<p>Check to create a <i>see also</i> cross-reference.</p>"""))
        self.whichGroup = QGroupBox("Add")
        self.filteredEntry = self.circledEntry = None
        filteredEid = self.state.viewFilteredPanel.view.selectedEid
        if filteredEid is not None:
            self.filteredEntry = self.state.model.entry(filteredEid)
        circledEid = self.state.viewAllPanel.view.circledEid
        if circledEid is not None:
            self.circledEntry = self.state.model.entry(circledEid)
        self.filteredRadioButton = QRadioButton("&Filtered")
        self.circledRadioButton = QRadioButton("C&ircled")
        self.recentRadioButton = QRadioButton("&Recent")
        self.tooltips.append((self.recentRadioButton, """<p><b>Recent</b></p>
<p>Create a cross-reference to a recently visited entry.</p>"""))
        self.filteredLabel = Widgets.Label.HtmlLabel()
        self.circledLabel = Widgets.Label.HtmlLabel()
        seen = {selectedEid}
        buttons = (self.filteredRadioButton, self.circledRadioButton,
                   self.recentRadioButton)
        Forms.Util.setUpRadioButton(
            self, self.filteredEntry, self.filteredRadioButton,
            self.filteredLabel, buttons, seen, """<p><b>Filtered</b></p>
<p>Create a cross-reference to the filtered entry “{}”.</p>""")
        Forms.Util.setUpRadioButton(
            self, self.circledEntry, self.circledRadioButton,
            self.circledLabel, buttons, seen, """<p><b>Circled</b></p>
<p>Create a cross-reference to the circled entry “{}”.</p>""")
        self.recentComboBox = Forms.Util.createTermsComboBox(
            self.state, self.state.gotoEids, ignore=seen, maximum=MAX_RECENT)
        self.groupRadioButton = QRadioButton("All in &Group")
        self.groupComboBox = QComboBox()
        for i, (gid, name, linked) in enumerate(self.state.model.allGroups()):
            self.groupComboBox.addItem(
                QIcon(":/grouplink.svg" if linked else ":/groups.svg"), name,
                gid)
        if not self.groupComboBox.count():
            self.groupRadioButton.setEnabled(False)
            self.groupComboBox.setEnabled(False)
        self.eidGroup = QGroupBox()
        self.genericTermRadioButton = QRadioButton("Generic &Term")
        self.tooltips.append((self.genericTermRadioButton, """\
<p><b>Generic Term</b></p>
<p>Create a cross-reference to the given generic term.</p>"""))
        self.genericTermLineEdit = EnableOnClickLineEdit(
            self.state, self.genericTermRadioButton, self)
        self.tooltips.append((self.genericTermLineEdit, """\
<p><b>Generic Term text</b></p>
<p>The generic term text styled (e.g., <b>bold</b>, <i>italic</i>), as
it should appear in the final index.</p>"""))
        self.formatPanel = Widgets.FormatPanel.Panel(self.state, self)
        self.formatPanel.state.editors = [self.genericTermLineEdit]
        self.formatActions = self.formatPanel.formatActions
        self.buttonBox = QDialogButtonBox()
        self.addButton = QPushButton(QIcon(":/xref-add.svg"), "A&dd")
        self.tooltips.append((self.addButton, """<p><b>Add</b></p>
<p>Add the specified cross-reference to the <b>Entry</b> {}.</p>""".format(
            self.termLabel.text())))
        self.buttonBox.addButton(self.addButton, QDialogButtonBox.AcceptRole)
        self.closeButton = QPushButton(QIcon(":/dialog-close.svg"), "&Cancel")
        self.tooltips.append((self.closeButton, """<p><b>Cancel</b></p>
<p>Close the dialog without making any changes to the index.</p>"""))
        self.buttonBox.addButton(self.closeButton, QDialogButtonBox.RejectRole)
        self.helpButton = QPushButton(QIcon(":/help.svg"), "Help")
        self.tooltips.append(
            (self.helpButton, "Help on the Add Cross-reference dialog"))
        self.buttonBox.addButton(self.helpButton, QDialogButtonBox.HelpRole)
        if (not self.filteredRadioButton.isChecked()
                and not self.circledRadioButton.isChecked()):
            if self.recentComboBox.count():
                self.recentRadioButton.setChecked(True)
            else:
                self.genericTermRadioButton.setChecked(True)
                self.genericTermLineEdit.setFocus()