示例#1
0
    def __init__(self, choices, help_texts=[], parent=None):
        super(ChoiceDialog, 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)

        # 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)
示例#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
示例#3
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
示例#4
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
示例#5
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
 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)
示例#7
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
示例#8
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
示例#9
0
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
示例#10
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"))
示例#11
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()
示例#12
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)
示例#13
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()
class RepresentationPane(BasePane):
    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

    def get_current_state(self):
        setting_dict = {}

        if self.mfccRadio.isChecked():
            setting_dict['rep'] = 'mfcc'
        elif self.mhecRadio.isChecked():
            setting_dict['rep'] = 'mhec'
        elif self.prosodyRadio.isChecked():
            setting_dict['rep'] = 'prosody'
        elif self.formantRadio.isChecked():
            setting_dict['rep'] = 'formant'
        elif self.envelopeRadio.isChecked():
            setting_dict['rep'] = 'envelopes'

        setting_dict['win_len'] = float(self.winLenEdit.text())
        setting_dict['time_step'] = float(self.timeStepEdit.text())
        setting_dict['freq_lims'] = (int(self.minFreqEdit.text()),
                                    int(self.maxFreqEdit.text()))
        setting_dict['num_cores'] = int(self.numCoresEdit.text())

        setting_dict['envelope_bands'] = int(self.bandEdit.text())
        setting_dict['use_gammatone'] = int(self.gammatoneCheck.isChecked())
        setting_dict['use_window'] = int(self.windowCheck.isChecked())

        setting_dict['num_coeffs'] = int(self.numCCEdit.text())
        setting_dict['mfcc_filters'] = int(self.numFiltersEdit.text())
        setting_dict['use_power'] = int(self.powerCheck.isChecked())

        return setting_dict

    def is_changed(self):
        cur_state = self.get_current_state()
        if self.prev_state['rep'] != cur_state['rep']:
            return True
        if cur_state['rep'] == 'mfcc':
            for k in ['win_len','time_step','freq_lims',
                    'num_coeffs','mfcc_filters','use_power']:
                if cur_state[k] != self.prev_state[k]:
                    return True
        elif cur_state['rep'] == 'envelopes':
            for k in ['freq_lims','envelope_bands',
                        'use_gammatone', 'use_window']:
                if cur_state[k] != self.prev_state[k]:
                    return True
            if cur_state['use_window']:
                for k in ['win_len','time_step']:
                    if cur_state[k] != self.prev_state[k]:
                        return True
        return False
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(810, 492)

        lbMinWidth = 65
        lbMinWidthLogin = 110
        # leMinWidth = 200

        # 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_presets_layout = QHBoxLayout()
        login_gbox_server_layout = QHBoxLayout()
        login_gbox_ssl_layout = QHBoxLayout()
        login_gbox_address_layout = QHBoxLayout()
        login_gbox_pass_layout = QHBoxLayout()
        login_gbox_connect_layout = QHBoxLayout()
        login_gbox_layout.addLayout(login_gbox_presets_layout)
        login_gbox_layout.addLayout(login_gbox_server_layout)
        login_gbox_layout.addLayout(login_gbox_ssl_layout)
        login_gbox_layout.addLayout(login_gbox_address_layout)
        login_gbox_layout.addLayout(login_gbox_pass_layout)
        login_gbox_layout.addLayout(login_gbox_connect_layout)

        self.lb_presets = QLabel(self.login_gbox)
        self.lb_presets.setObjectName("lb_presets")
        self.lb_presets.setMinimumWidth(lbMinWidthLogin)
        self.lb_presets.setMaximumWidth(lbMinWidthLogin)
        self.presets_cbox = QComboBox(self.login_gbox)
        self.presets_cbox.setObjectName("presets_cbox")
        self.add_preset_btn = QPushButton(self.login_gbox)
        self.add_preset_btn.setObjectName("add_preset_btn")
        self.add_preset_btn.setMaximumWidth(30)
        self.remove_preset_btn = QPushButton(self.login_gbox)
        self.remove_preset_btn.setObjectName("remove_preset_btn")
        self.remove_preset_btn.setMaximumWidth(20)
        login_gbox_presets_layout.addWidget(self.lb_presets)
        login_gbox_presets_layout.addWidget(self.presets_cbox)
        login_gbox_presets_layout.addWidget(self.add_preset_btn)
        login_gbox_presets_layout.addWidget(self.remove_preset_btn)

        self.lb_imap_server = QLabel(self.login_gbox)
        self.lb_imap_server.setObjectName("lb_imap_server")
        self.lb_imap_server.setMinimumWidth(lbMinWidthLogin)
        self.imap_server_le = QLineEdit(self.login_gbox)
        self.imap_server_le.setObjectName("imap_server_le")
        login_gbox_server_layout.addWidget(self.lb_imap_server)
        login_gbox_server_layout.addWidget(self.imap_server_le)

        self.lb_ssl = QLabel(self.login_gbox)
        self.lb_ssl.setObjectName("lb_ssl")
        self.lb_ssl.setMinimumWidth(lbMinWidthLogin)
        self.lb_ssl.setMaximumWidth(lbMinWidthLogin)
        self.ssl_cb = QCheckBox(self.login_gbox)
        self.ssl_cb.setEnabled(False)
        self.ssl_cb.setCheckable(True)
        self.ssl_cb.setChecked(True)
        self.ssl_cb.setObjectName("ssl_cb")
        login_gbox_ssl_layout.addWidget(self.lb_ssl)
        login_gbox_ssl_layout.addWidget(self.ssl_cb)

        self.lb_adress = QLabel(self.login_gbox)
        self.lb_adress.setObjectName("lb_adress")
        self.lb_adress.setMinimumWidth(lbMinWidthLogin)
        self.adress_le = QLineEdit(self.login_gbox)
        self.adress_le.setInputMethodHints(Qt.ImhNone)
        self.adress_le.setObjectName("adress_le")
        login_gbox_address_layout.addWidget(self.lb_adress)
        login_gbox_address_layout.addWidget(self.adress_le)

        self.lb_pass = QLabel(self.login_gbox)
        self.lb_pass.setObjectName("lb_pass")
        self.lb_pass.setMinimumWidth(lbMinWidthLogin)
        self.pass_le = QLineEdit(self.login_gbox)
        self.pass_le.setText("")
        self.pass_le.setEchoMode(QLineEdit.Password)
        self.pass_le.setObjectName("pass_le")
        login_gbox_pass_layout.addWidget(self.lb_pass)
        login_gbox_pass_layout.addWidget(self.pass_le)

        self.connect_btn = QPushButton(self.login_gbox)
        self.connect_btn.setObjectName("connect_btn")
        login_gbox_connect_layout.addStretch()
        login_gbox_connect_layout.addWidget(self.connect_btn)

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

        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.since_date_cb = QCheckBox(self.search_gbox)
        self.since_date_cb.setObjectName("since_date_cb")
        self.since_date_cb.setMinimumWidth(lbMinWidth)
        self.since_date_cb.setMaximumWidth(lbMinWidth)
        self.since_date_edit = QDateEdit(self.search_gbox)
        self.since_date_edit.setCalendarPopup(True)
        self.since_date_edit.setObjectName("since_date_edit")
        self.since_date_edit.setDate(QDate.currentDate().addDays(-365))
        self.since_date_edit.setMaximumDate(QDate.currentDate())
        self.since_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.since_date_cb)
        search_gbox_date_layout.addWidget(self.since_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.addStretch()
        search_gbox_threads_layout.addWidget(self.html_radio)
        search_gbox_threads_layout.addWidget(self.text_radio)
        # search_gbox_threads_layout.addStretch()
        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")
        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.setObjectName("menubar")
        self.menu_file = QMenu(self.menubar)
        self.menu_file.setObjectName("menu_file")
        self.menu_about = QMenu(self.menubar)
        self.menu_about.setObjectName("menu_about")
        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.menu_file.addAction(self.action_exit)
        self.menu_about.addAction(self.action_about)
        self.menu_about.addAction(self.action_About_Qt)
        self.menubar.addAction(self.menu_file.menuAction())
        self.menubar.addAction(self.menu_about.menuAction())

        self.retranslateUi(MainWindow)
        QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.setTabOrder(self.presets_cbox, self.imap_server_le)
        MainWindow.setTabOrder(self.imap_server_le, self.adress_le)
        MainWindow.setTabOrder(self.adress_le, self.pass_le)
        MainWindow.setTabOrder(self.pass_le, self.connect_btn)
        MainWindow.setTabOrder(self.connect_btn, self.log_te)
        MainWindow.setTabOrder(self.log_te, self.since_date_cb)
        MainWindow.setTabOrder(self.since_date_cb, self.since_date_edit)
        MainWindow.setTabOrder(self.since_date_edit, self.before_date_cb)
        MainWindow.setTabOrder(self.before_date_cb, self.before_date_edit)
        MainWindow.setTabOrder(self.before_date_edit, self.mailboxes_lw)
        MainWindow.setTabOrder(self.mailboxes_lw, 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.search_btn)
        MainWindow.setTabOrder(self.search_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.disconnect_btn)
        MainWindow.setTabOrder(self.disconnect_btn, self.add_preset_btn)
        MainWindow.setTabOrder(self.add_preset_btn, self.remove_preset_btn)
        MainWindow.setTabOrder(self.remove_preset_btn, self.ssl_cb)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(QApplication.translate("MainWindow", "Email Link Extractor", None, QApplication.UnicodeUTF8))
        self.login_gbox.setTitle(QApplication.translate("MainWindow", "  Login", None, QApplication.UnicodeUTF8))
        self.lb_presets.setText(QApplication.translate("MainWindow", "Server Presets", None, QApplication.UnicodeUTF8))
        self.add_preset_btn.setText(QApplication.translate("MainWindow", "+", None, QApplication.UnicodeUTF8))
        self.remove_preset_btn.setText(QApplication.translate("MainWindow", "-", None, QApplication.UnicodeUTF8))
        self.lb_imap_server.setText(QApplication.translate("MainWindow", "IMAP Server", None, QApplication.UnicodeUTF8))
        self.lb_ssl.setText(QApplication.translate("MainWindow", "SSL", None, QApplication.UnicodeUTF8))
        self.ssl_cb.setText(QApplication.translate("MainWindow", "Port : 993", None, QApplication.UnicodeUTF8))
        self.lb_adress.setText(QApplication.translate("MainWindow", "Adress", None, QApplication.UnicodeUTF8))
        self.lb_pass.setText(QApplication.translate("MainWindow", "Password", None, QApplication.UnicodeUTF8))
        self.connect_btn.setText(QApplication.translate("MainWindow", "Connect", None, QApplication.UnicodeUTF8))
        self.lb_select_mailbox.setText(QApplication.translate("MainWindow", "Select Mailbox", None, QApplication.UnicodeUTF8))

        self.search_gbox.setTitle(QApplication.translate("MainWindow", "  Search Parameters", None, QApplication.UnicodeUTF8))
        self.since_date_cb.setText(QApplication.translate("MainWindow", "Since", None, QApplication.UnicodeUTF8))
        self.since_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "dd-MMM-yyyy", None, QApplication.UnicodeUTF8))
        self.before_date_cb.setText(QApplication.translate("MainWindow", "Before", None, QApplication.UnicodeUTF8))
        self.before_date_edit.setDisplayFormat(QApplication.translate("MainWindow", "dd-MMM-yyyy", 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.lb_from.setText(QApplication.translate("MainWindow", "From", None, QApplication.UnicodeUTF8))
        self.lb_to.setText(QApplication.translate("MainWindow", "To", 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.links_gbox.setTitle(QApplication.translate("MainWindow", "  Links", None, QApplication.UnicodeUTF8))
        self.export_html_btn.setText(QApplication.translate("MainWindow", "Export as HTML", None, QApplication.UnicodeUTF8))
        self.export_txt_btn.setText(QApplication.translate("MainWindow", "Export as txt", None, QApplication.UnicodeUTF8))
        self.log_gbox.setTitle(QApplication.translate("MainWindow", "  Log", None, QApplication.UnicodeUTF8))
        self.disconnect_btn.setText(QApplication.translate("MainWindow", "Disconnect", None, QApplication.UnicodeUTF8))
        self.menu_file.setTitle(QApplication.translate("MainWindow", "File", None, QApplication.UnicodeUTF8))
        self.menu_about.setTitle(QApplication.translate("MainWindow", "About", 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))
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)
示例#17
0
class Mixin:
    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."))

    def layoutWidgets(self):
        form = QFormLayout()
        hbox = QHBoxLayout()
        hbox.addWidget(self.searchLineEdit)
        hbox.addWidget(self.closeButton)
        form.addRow(self.searchLabel, hbox)
        hbox = QHBoxLayout()
        hbox.addWidget(self.replaceLineEdit)
        hbox.addWidget(self.helpButton)
        form.addRow(self.replaceLabel, hbox)
        hbox = QHBoxLayout()
        hbox.addWidget(self.allEntriesRadioButton)
        hbox.addWidget(self.filteredEntriesRadioButton)
        hbox.addStretch()
        form.addRow(self.considerLabel, hbox)
        hbox = QHBoxLayout()
        hbox.addWidget(self.literalRadioButton)
        hbox.addWidget(self.regexRadioButton)
        hbox.addStretch(1)
        hbox.addWidget(self.ignoreCaseCheckBox)
        hbox.addWidget(self.wholeWordsCheckBox)
        hbox.addStretch(5)
        form.addRow(QLabel("Match"), hbox)
        hbox = QHBoxLayout()
        hbox.addWidget(self.replaceInTermsCheckBox)
        hbox.addWidget(self.replaceInPagesCheckBox)
        hbox.addWidget(self.replaceInNotesCheckBox)
        hbox.addStretch()
        form.addRow(self.replaceInLabel, hbox)
        hbox = QHBoxLayout()
        hbox.addWidget(self.startButton)
        hbox.addWidget(self.replaceButton)
        hbox.addWidget(self.skipButton)
        hbox.addWidget(self.stopButton)
        hbox.addStretch()
        form.addRow(hbox)
        self.setLayout(form)

    def createConnections(self):
        self.helpButton.clicked.connect(self.help)
        self.stopButton.clicked.connect(self.stop)
        self.startButton.clicked.connect(self.start)
        self.replaceButton.clicked.connect(self.replace)
        self.skipButton.clicked.connect(self.skip)
        self.searchLineEdit.textChanged.connect(self.updateUi)
        self.searchLineEdit.returnPressed.connect(self.doAction)
        self.replaceLineEdit.textChanged.connect(self.updateUi)
        self.replaceLineEdit.returnPressed.connect(self.doAction)
        for button in (self.literalRadioButton, self.regexRadioButton,
                       self.ignoreCaseCheckBox, self.wholeWordsCheckBox,
                       self.replaceInTermsCheckBox,
                       self.replaceInPagesCheckBox,
                       self.replaceInNotesCheckBox):
            button.clicked.connect(self.updateUi)

    def doAction(self):
        button = None
        if self.skipButton.isEnabled():
            button = self.skipButton
        elif self.startButton.isEnabled():
            button = self.startButton
        if button is not None:
            button.setFocus()
            button.click()
        if self.skipButton.isEnabled():
            self.skipButton.setFocus()

    def help(self):
        self.state.help("xix_ref_panel_replace.html")
示例#18
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
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))
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
示例#21
0
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
示例#22
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)
示例#23
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.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"))
示例#24
0
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)
示例#25
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)
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()))
示例#27
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)
示例#28
0
class Form(QDialog):
    def __init__(self, state, parent=None):
        super().__init__(parent)
        Lib.prepareModalDialog(self)
        self.state = state
        self.setWindowTitle("Add Cross-reference — {}".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.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()

    def layoutWidgets(self):
        layout = QVBoxLayout()
        whichLayout = QHBoxLayout()
        whichLayout.addWidget(self.seeRadioButton)
        whichLayout.addWidget(self.alsoRadioButton)
        whichLayout.addStretch()
        self.whichGroup.setLayout(whichLayout)
        layout.addWidget(self.whichGroup)
        entryLayout = QHBoxLayout()
        entryLayout.setSpacing(0)
        entryLayout.addWidget(self.entry1Label)
        entryLayout.addWidget(self.termLabel)
        entryLayout.addWidget(self.entry2Label)
        entryLayout.addStretch()
        layout.addLayout(entryLayout)
        eidLayout = QVBoxLayout()
        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)
        hbox = QHBoxLayout()
        hbox.addWidget(self.groupRadioButton)
        hbox.addWidget(self.groupComboBox, 1)
        eidLayout.addLayout(hbox)
        grid = QGridLayout()
        grid.addWidget(self.formatPanel, 0, 0, 1, 2, Qt.AlignRight)
        grid.addWidget(self.genericTermRadioButton, 1, 0)
        grid.addWidget(self.genericTermLineEdit, 1, 1)
        eidLayout.addLayout(grid)
        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.addXRef)
        self.buttonBox.rejected.connect(self.reject)
        self.helpButton.clicked.connect(self.help)
        self.filteredRadioButton.clicked.connect(self.updateUi)
        self.circledRadioButton.clicked.connect(self.updateUi)
        self.recentRadioButton.clicked.connect(self.updateUi)
        self.recentRadioButton.toggled.connect(self.moveFocus)
        self.recentComboBox.currentIndexChanged[int].connect(
            self.recentChanged)
        self.groupRadioButton.clicked.connect(self.updateUi)
        self.groupRadioButton.toggled.connect(self.moveFocus)
        self.groupComboBox.currentIndexChanged[int].connect(self.groupChanged)
        self.genericTermRadioButton.clicked.connect(self.updateUi)
        self.genericTermRadioButton.clicked.connect(
            self.genericTermLineEdit.setFocus)
        self.genericTermLineEdit.textChanged.connect(self.updateUi)
        self.genericTermLineEdit.enterPressed.connect(self.maybeAdd)

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

    def groupChanged(self):
        self.groupRadioButton.setChecked(True)
        self.updateUi()

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

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

    def updateUi(self):
        enable = (self.genericTermRadioButton.isChecked()
                  or (self.groupRadioButton.isChecked()
                      and self.groupComboBox.count()))
        for widget in (self.genericTermLineEdit, self.formatPanel):
            widget.setEnabled(enable)
        self.recentRadioButton.setEnabled(self.recentComboBox.count())
        self.recentComboBox.setEnabled(self.recentComboBox.count())
        enable = True
        if (self.filteredRadioButton.isChecked()
                and self.filteredEntry is None):
            enable = False
        if (self.circledRadioButton.isChecked() and self.circledEntry is None):
            enable = False
        if (self.recentRadioButton.isChecked()
                and self.recentComboBox.currentIndex() < 0):
            enable = False
        if (self.groupRadioButton.isChecked()
                and not self.groupComboBox.count()):
            enable = False
        if (self.genericTermRadioButton.isChecked()
                and self.genericTermLineEdit.isEmpty()):
            enable = False
        self.addButton.setEnabled(enable)

    def maybeAdd(self):
        if (self.genericTermRadioButton.isChecked()
                and not self.genericTermLineEdit.isEmpty()):
            self.addXRef()

    def addXRef(self):
        from_eid = self.selectedEntry.eid
        assert from_eid is not None
        kind = (XrefKind.SEE
                if self.seeRadioButton.isChecked() else XrefKind.SEE_ALSO)
        if self.groupRadioButton.isChecked():
            gid = int(
                self.groupComboBox.itemData(self.groupComboBox.currentIndex()))
            for to_eid in tuple(self.state.model.eidsForGid(gid)):
                self.state.model.addXRef(from_eid, to_eid, kind)
        elif not self.genericTermRadioButton.isChecked():
            to_eid = None
            if self.filteredRadioButton.isChecked():
                to_eid = self.filteredEntry.eid
            elif self.circledRadioButton.isChecked():
                to_eid = self.circledEntry.eid
            elif self.recentRadioButton.isChecked():
                to_eid = self.recentComboBox.itemData(
                    self.recentComboBox.currentIndex())
            assert to_eid is not None
            self.state.model.addXRef(from_eid, to_eid, kind)
        else:
            term = self.genericTermLineEdit.toHtml()
            kind = (XrefKind.SEE_GENERIC if self.seeRadioButton.isChecked()
                    else XrefKind.SEE_ALSO_GENERIC)
            self.state.model.addGenericXRef(from_eid, term, kind)
        say("Added cross-reference", SAY_TIMEOUT)
        self.accept()