예제 #1
0
파일: BettyGUI.py 프로젝트: Whatang/QBetty
 def makeOddsButton(name, oddsDisplayer):
     bname = "%sButton" % name
     button = QRadioButton(self.oddsGroupBox)
     setattr(self, bname, button)
     def buttonClicked():
         self.__oddsDisplay = name
         self.model.setOddsDisplay(oddsDisplayer)
     self.connect(button, SIGNAL("clicked()"),
                  buttonClicked)
     button.setEnabled(oddsDisplayer.implemented)
     self.oddsLayout.addWidget(button)
     button.setText(name.capitalize())
예제 #2
0
        def makeOddsButton(name, oddsDisplayer):
            bname = "%sButton" % name
            button = QRadioButton(self.oddsGroupBox)
            setattr(self, bname, button)

            def buttonClicked():
                self.__oddsDisplay = name
                self.model.setOddsDisplay(oddsDisplayer)

            self.connect(button, SIGNAL("clicked()"), buttonClicked)
            button.setEnabled(oddsDisplayer.implemented)
            self.oddsLayout.addWidget(button)
            button.setText(name.capitalize())
예제 #3
0
class CADOptionsToolbar_Modify(CADOptionsToolbar):
    def __init__(self, layerType):
        super(CADOptionsToolbar_Modify, self).__init__()

        self.add_btn = QRadioButton(
            tr(u"Add"), self.optionsToolBar)
        self.add_btn.setToolTip(
            tr(u"Add extension"))
        self.add_btn.setObjectName("add_rbtn")
        self.modify_btn = QRadioButton(
            tr(u"Modify"), self.optionsToolBar)
        self.modify_btn.setToolTip(
            tr(u"Modify the entity"))
        self.modify_btn.setObjectName("modify_rbtn")
        self.extend_btn = QRadioButton(
            tr(u"Add opposite"), self.optionsToolBar)
        self.extend_btn.setToolTip(
            tr(u"Add an extended line"))
        self.extend_btn.setObjectName("extend_rbtn")
        self.optionsToolBar.addWidget(self.add_btn)
        self.optionsToolBar.addWidget(self.modify_btn)
        self.optionsToolBar.addWidget(self.extend_btn)
        self.add_btn.setChecked(True)

        if layerType == QGis.Polygon:
            self.modify_btn.setChecked(True)
            self.add_btn.setEnabled(False)
            self.extend_btn.setEnabled(False)
        else:
            self.add_btn.setEnabled(True)
            self.extend_btn.setEnabled(True)
예제 #4
0
    def createDialog(self):
        """
        Create qt dialog
        """
        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setStyleSheet("""QDialogButtonBox { 
            dialogbuttonbox-buttons-have-icons: 1;
            dialog-ok-icon: url(:/ok.png);
            dialog-cancel-icon: url(:/test-close-black.png);
        }""")
        self.buttonBox.setStandardButtons(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)

        self.stepIdLabel = QLabel("%s" % self.stepId)
        stepTitleLayout = QGridLayout()

        # mandatory args
        self.argsLayout = QGridLayout()
        for i in xrange(len(self.stepData['obj'])):
            self.argsLayout.addWidget(QLabel(self.stepData['obj'][i]['name']),
                                      i, 0)
            typeParam = QRadioButton(self.stepData['obj'][i]['type'])
            typeParam.setEnabled(False)
            self.argsLayout.addWidget(typeParam, i, 1)
            if self.stepData['obj'][i]['type'] == 'string':
                typeParam.setChecked(True)
                self.argsLayout.addWidget(QTextEdit(), i, 2)
            if self.stepData['obj'][i]['type'] == "boolean":
                boolCombo = QComboBox()
                valBool = ["True", "False"]
                boolCombo.addItems(valBool)
                boolCombo.setEnabled(
                    False)  # feature not yet available in abstract mode
                typeParam.setChecked(True)
                self.argsLayout.addWidget(boolCombo, i, 2)

        mainLayout = QVBoxLayout()
        mainLayout.addLayout(stepTitleLayout)
        mainLayout.addLayout(self.argsLayout)
        mainLayout.addWidget(self.buttonBox)
        self.setLayout(mainLayout)

        self.setWindowTitle(self.tr("Step configuration"))
        self.resize(450, 250)
        self.center()
예제 #5
0
class CADOptionsToolbar_ModifyOffset(CADOptionsToolbar):
    def __init__(self, layerType):
        super(CADOptionsToolbar_ModifyOffset, self).__init__()

        self.segmentChoice = QRadioButton(
            tr(u"Segment"))
        self.segmentChoice.setChecked(Qt.Checked)
        self.featureChoice = QRadioButton(
            tr(u"Feature"))
        self.optionsToolBar.addWidget(self.segmentChoice)
        self.optionsToolBar.addWidget(self.featureChoice)

        if layerType == QGis.Polygon:
            self.segmentChoice.setChecked(Qt.Unchecked)
            self.featureChoice.setChecked(Qt.Checked)
            self.segmentChoice.setEnabled(False)
            self.featureChoice.setEnabled(False)
        elif layerType == QGis.Line:
            self.segmentChoice.setEnabled(True)
            self.featureChoice.setEnabled(True)
예제 #6
0
class FindInFilesDialog(QDialog):

    """Dialog to configure and trigger the search in the files."""

    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"), translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(QCompleter(
            ["*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(
            translations.TR_TEXT_FOR_REPLACE + "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
            self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
            self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
            self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
            self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
            self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
            self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
            self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(self, translations.TR_OPEN,
            self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(
            self.dir_combo.currentText(), file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join(
                [word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
            by_phrase)
예제 #7
0
class FindOptions(QWidget):
    """
    Find widget with options
    """
    def __init__(self, parent, search_text, search_text_regexp, search_path,
                 include, include_regexp, exclude, exclude_regexp,
                 supported_encodings):
        QWidget.__init__(self, parent)
        
        if search_path is None:
            search_path = os.getcwdu()
        
        if not isinstance(search_text, (list, tuple)):
            search_text = [search_text]
        if not isinstance(search_path, (list, tuple)):
            search_path = [search_path]
        if not isinstance(include, (list, tuple)):
            include = [include]
        if not isinstance(exclude, (list, tuple)):
            exclude = [exclude]

        self.supported_encodings = supported_encodings

        # Layout 1
        hlayout1 = QHBoxLayout()
        self.search_text = PatternComboBox(self, search_text,
                                    translate('FindInFiles', "Search pattern"))
        search_label = QLabel(translate('FindInFiles', "Search text:"))
        search_label.setBuddy(self.search_text)
        self.edit_regexp = create_toolbutton(self, get_icon("advanced.png"),
                         tip=translate('FindInFiles', "Regular expression"))
        self.edit_regexp.setCheckable(True)
        self.edit_regexp.setChecked(search_text_regexp)
        self.ok_button = create_toolbutton(self,
                                text=translate('FindInFiles', "Search"),
                                triggered=lambda: self.emit(SIGNAL('find()')),
                                icon=get_std_icon("DialogApplyButton"),
                                tip=translate('FindInFiles', "Start search"))
        self.connect(self.ok_button, SIGNAL('clicked()'), self.update_combos)
        self.stop_button = create_toolbutton(self,
                                text=translate('FindInFiles', "Stop"),
                                triggered=lambda: self.emit(SIGNAL('stop()')),
                                icon=get_icon("terminate.png"),
                                tip=translate('FindInFiles', "Stop search"))
        self.stop_button.setEnabled(False)
        for widget in [search_label, self.search_text, self.edit_regexp,
                       self.ok_button, self.stop_button]:
            hlayout1.addWidget(widget)

        # Layout 2
        hlayout2 = QHBoxLayout()
        self.include_pattern = PatternComboBox(self, include,
                        translate('FindInFiles', "Included filenames pattern"))
        self.include_regexp = create_toolbutton(self, get_icon("advanced.png"),
                                            tip=translate('FindInFiles',
                                                          "Regular expression"))
        self.include_regexp.setCheckable(True)
        self.include_regexp.setChecked(include_regexp)
        include_label = QLabel(translate('FindInFiles', "Include:"))
        include_label.setBuddy(self.include_pattern)
        self.exclude_pattern = PatternComboBox(self, exclude,
                        translate('FindInFiles', "Excluded filenames pattern"))
        self.exclude_regexp = create_toolbutton(self, get_icon("advanced.png"),
                                            tip=translate('FindInFiles',
                                                          "Regular expression"))
        self.exclude_regexp.setCheckable(True)
        self.exclude_regexp.setChecked(exclude_regexp)
        exclude_label = QLabel(translate('FindInFiles', "Exclude:"))
        exclude_label.setBuddy(self.exclude_pattern)
        for widget in [include_label, self.include_pattern,
                       self.include_regexp,
                       exclude_label, self.exclude_pattern,
                       self.exclude_regexp]:
            hlayout2.addWidget(widget)

        # Layout 3
        hlayout3 = QHBoxLayout()
        searchin_label = QLabel(translate('FindInFiles', "Search in:"))
        self.python_path = QRadioButton(translate('FindInFiles',
                                        "PYTHONPATH"), self)
        self.python_path.setToolTip(translate('FindInFiles',
                          "Search in all directories listed in sys.path which"
                          " are outside the Python installation directory"))        
        self.hg_manifest = QRadioButton(translate('FindInFiles',
                                                  "Hg repository"), self)
        self.detect_hg_repository()
        self.hg_manifest.setToolTip(translate('FindInFiles',
                              "Search in current directory hg repository"))
        searchin_label.setBuddy(self.hg_manifest)
        self.custom_dir = QRadioButton(translate('FindInFiles',
                                                 "Directory:"), self)
        self.custom_dir.setChecked(True)
        self.dir_combo = PathComboBox(self)
        self.dir_combo.addItems(search_path)
        self.dir_combo.setToolTip(translate('FindInFiles',
                                    "Search recursively in this directory"))
        self.connect(self.dir_combo, SIGNAL("open_dir(QString)"),
                     self.set_directory)
        self.connect(self.python_path, SIGNAL('toggled(bool)'),
                     self.dir_combo.setDisabled)
        self.connect(self.hg_manifest, SIGNAL('toggled(bool)'),
                     self.dir_combo.setDisabled)
        browse = create_toolbutton(self, get_std_icon('DirOpenIcon'),
                                   tip=translate('FindInFiles',
                                                 'Browse a search directory'),
                                   triggered=self.select_directory)
        for widget in [searchin_label, self.python_path, self.hg_manifest,
                       self.custom_dir, self.dir_combo, browse]:
            hlayout3.addWidget(widget)
            
        vlayout = QVBoxLayout()
        vlayout.addLayout(hlayout1)
        vlayout.addLayout(hlayout2)
        vlayout.addLayout(hlayout3)
        self.setLayout(vlayout)
                
        self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Minimum)
        
    def update_combos(self):
        self.search_text.lineEdit().emit(SIGNAL('returnPressed()'))
        self.include_pattern.lineEdit().emit(SIGNAL('returnPressed()'))
        self.exclude_pattern.lineEdit().emit(SIGNAL('returnPressed()'))
        
    def detect_hg_repository(self, path=None):
        if path is None:
            path = os.getcwdu()
        hg_repository = is_hg_installed() and get_hg_root(path) is not None
        self.hg_manifest.setEnabled(hg_repository)
        if not hg_repository and self.hg_manifest.isChecked():
            self.custom_dir.setChecked(True)
        
    def set_search_text(self, text):
        self.search_text.setEditText(text)
        self.search_text.lineEdit().selectAll()
        self.search_text.setFocus()
        
    def get_options(self, all=False):
        # Getting options
        utext = unicode(self.search_text.currentText())
        if not utext:
            return
        try:
            texts = [str(utext)]
        except UnicodeDecodeError:
            texts = []
            for encoding in self.supported_encodings:
                try:
                    texts.append( utext.encode(encoding) )
                except UnicodeDecodeError:
                    pass
        text_re = self.edit_regexp.isChecked()
        include = unicode(self.include_pattern.currentText())
        include_re = self.include_regexp.isChecked()
        exclude = unicode(self.exclude_pattern.currentText())
        exclude_re = self.exclude_regexp.isChecked()
        python_path = self.python_path.isChecked()
        hg_manifest = self.hg_manifest.isChecked()
        path = osp.abspath( unicode( self.dir_combo.currentText() ) )
        
        # Finding text occurences
        if not include_re:
            include = fnmatch.translate(include)
        if not exclude_re:
            exclude = fnmatch.translate(exclude)
            
        if all:
            search_text = [unicode(self.search_text.itemText(index)) \
                           for index in range(self.search_text.count())]
            search_path = [unicode(self.dir_combo.itemText(index)) \
                           for index in range(self.dir_combo.count())]
            include = [unicode(self.include_pattern.itemText(index)) \
                       for index in range(self.include_pattern.count())]
            exclude = [unicode(self.exclude_pattern.itemText(index)) \
                       for index in range(self.exclude_pattern.count())]
            return (search_text, text_re, search_path,
                    include, include_re,
                    exclude, exclude_re)
        else:
            return (path, python_path, hg_manifest,
                    include, exclude, texts, text_re)
        
    def select_directory(self):
        """Select directory"""
        self.parent().emit(SIGNAL('redirect_stdio(bool)'), False)
        directory = QFileDialog.getExistingDirectory(self,
                                translate('FindInFiles', "Select directory"),
                                self.dir_combo.currentText())
        if not directory.isEmpty():
            self.set_directory(directory)
        self.parent().emit(SIGNAL('redirect_stdio(bool)'), True)
        
    def set_directory(self, directory):
        path = unicode(osp.abspath(unicode(directory)))
        self.dir_combo.setEditText(path)
        self.detect_hg_repository(path)
        
    def keyPressEvent(self, event):
        """Reimplemented to handle key events"""
        ctrl = event.modifiers() & Qt.ControlModifier
        shift = event.modifiers() & Qt.ShiftModifier
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.emit(SIGNAL('find()'))
        elif event.key() == Qt.Key_F and ctrl and shift:
            # Toggle find widgets
            self.parent().emit(SIGNAL('toggle_visibility(bool)'),
                               not self.isVisible())
            event.accept()
        else:
            event.ignore()
예제 #8
0
class LegendPropertiesWindow(PyDialog):
    """
    +-------------------+
    | Legend Properties |
    +-----------------------+
    | Title  ______ Default |
    | Min    ______ Default |
    | Max    ______ Default |
    | Format ______ Default |
    | Scale  ______ Default |
    | Phase  ______ Default |
    | Number of Colors ____ |
    | Number of Labels ____ |
    | Label Size       ____ | (TODO)
    | ColorMap         ____ | (TODO)
    |                       |
    | x Min/Max (Blue->Red) |
    | o Max/Min (Red->Blue) |
    |                       |
    | x Vertical/Horizontal |
    | x Show/Hide           |
    |                       |
    |        Animate        |
    |    Apply OK Cancel    |
    +-----------------------+
    """
    def __init__(self, data, win_parent=None):
        PyDialog.__init__(self, data, win_parent)

        self._updated_legend = False
        self._animation_window_shown = False

        self._icase = data['icase']
        self._default_icase = self._icase

        self._default_name = data['name']
        self._default_min = data['min']
        self._default_max = data['max']

        self._default_scale = data['default_scale']
        self._scale = data['scale']

        self._default_phase = data['default_phase']
        self._phase = data['phase']

        self._default_format = data['default_format']
        self._format = data['format']

        self._default_labelsize = data['default_labelsize']
        self._labelsize = data['labelsize']

        self._default_nlabels = data['default_nlabels']
        self._nlabels = data['nlabels']

        self._default_ncolors = data['default_ncolors']
        self._ncolors = data['ncolors']

        self._default_colormap = data['default_colormap']
        self._colormap = data['colormap']

        self._default_is_low_to_high = data['is_low_to_high']

        self._default_is_discrete = data['is_discrete']
        self._default_is_horizontal = data['is_horizontal']
        self._default_is_shown = data['is_shown']
        self._is_normals = data['is_normals']

        self._update_defaults_to_blank()

        #self.setupUi(self)
        self.setWindowTitle('Legend Properties')
        self.create_widgets()
        self.create_layout()
        self.set_connections()
        self.set_font_size(data['font_size'])

    def _update_defaults_to_blank(self):
        """Changes the default (None) to a blank string"""
        if self._default_colormap is None:
            self._default_colormap = 'jet'
        if self._default_labelsize is None:
            self._default_labelsize = ''
        if self._default_ncolors is None:
            self._default_ncolors = ''
        if self._default_nlabels is None:
            self._default_nlabels = ''

        if self._colormap is None:
            self._colormap = 'jet'
        if self._labelsize is None:
            self._labelsize = ''
        if self._ncolors is None:
            self._ncolors = ''
        if self._nlabels is None:
            self._nlabels = ''

    def update_legend(self,
                      icase,
                      name,
                      min_value,
                      max_value,
                      data_format,
                      scale,
                      phase,
                      nlabels,
                      labelsize,
                      ncolors,
                      colormap,
                      default_title,
                      default_min_value,
                      default_max_value,
                      default_data_format,
                      default_scale,
                      default_phase,
                      default_nlabels,
                      default_labelsize,
                      default_ncolors,
                      default_colormap,
                      is_low_to_high,
                      is_horizontal_scalar_bar,
                      is_normals,
                      font_size=8):
        """
        We need to update the legend if there's been a result change request
        """
        self.set_font_size(font_size)
        if icase != self._default_icase:
            self._icase = icase
            self._default_icase = icase
            self._default_name = default_title
            self._default_min = default_min_value
            self._default_max = default_max_value
            self._default_format = default_data_format
            self._default_is_low_to_high = is_low_to_high
            self._default_is_discrete = True
            self._default_is_horizontal = is_horizontal_scalar_bar
            self._default_scale = default_scale
            self._default_phase = default_phase
            self._default_nlabels = default_nlabels
            self._default_labelsize = default_labelsize
            self._default_ncolors = default_ncolors
            self._default_colormap = default_colormap
            self._is_normals = is_normals

            if colormap is None:
                colormap = 'jet'
            if labelsize is None:
                labelsize = ''
            if ncolors is None:
                ncolors = ''
            if nlabels is None:
                nlabels = ''

            self._update_defaults_to_blank()

            assert isinstance(scale, float), 'scale=%r' % scale
            assert isinstance(default_scale,
                              float), 'default_scale=%r' % default_scale
            if self._default_scale == 0.0:
                self.scale.setEnabled(False)
                self.scale_edit.setEnabled(False)
                self.scale_button.setEnabled(False)
            else:
                self.scale.setEnabled(True)
                self.scale_edit.setEnabled(True)
                self.scale_button.setEnabled(True)

            if self._default_phase is None:
                self._phase = None
                self.phase.setEnabled(False)
                self.phase_edit.setEnabled(False)
                self.phase_button.setEnabled(False)
                self.phase_edit.setText('0.0')
                self.phase_edit.setStyleSheet("QLineEdit{background: white;}")
            else:
                self._phase = phase
                self.phase.setEnabled(True)
                self.phase_edit.setEnabled(True)
                self.phase_button.setEnabled(True)
                self.phase_edit.setText(str(phase))
                self.phase_edit.setStyleSheet("QLineEdit{background: white;}")

            #self.on_default_name()
            #self.on_default_min()
            #self.on_default_max()
            #self.on_default_format()
            #self.on_default_scale()
            # reset defaults
            self._name = name
            self.name_edit.setText(name)
            self.name_edit.setStyleSheet("QLineEdit{background: white;}")

            self.min_edit.setText(str(min_value))
            self.min_edit.setStyleSheet("QLineEdit{background: white;}")

            self.max_edit.setText(str(max_value))
            self.max_edit.setStyleSheet("QLineEdit{background: white;}")

            self.format_edit.setText(str(data_format))
            self.format_edit.setStyleSheet("QLineEdit{background: white;}")

            self._scale = scale
            self.scale_edit.setText(str(scale))
            self.scale_edit.setStyleSheet("QLineEdit{background: white;}")

            self.nlabels_edit.setText(str(nlabels))
            self.nlabels_edit.setStyleSheet("QLineEdit{background: white;}")

            self.labelsize_edit.setText(str(labelsize))
            self.labelsize_edit.setStyleSheet("QLineEdit{background: white;}")

            self.ncolors_edit.setText(str(ncolors))
            self.ncolors_edit.setStyleSheet("QLineEdit{background: white;}")

            self.colormap_edit.setCurrentIndex(
                colormap_keys.index(str(colormap)))

            # lots of hacking for the Normal vectors
            enable = True
            if self._is_normals:
                enable = False

            self.max.setVisible(enable)
            self.min.setVisible(enable)
            self.max_edit.setVisible(enable)
            self.min_edit.setVisible(enable)
            self.max_button.setVisible(enable)
            self.min_button.setVisible(enable)

            self.show_radio.setVisible(enable)
            self.hide_radio.setVisible(enable)
            self.low_to_high_radio.setVisible(enable)
            self.high_to_low_radio.setVisible(enable)

            self.format.setVisible(enable)
            self.format_edit.setVisible(enable)
            self.format_edit.setVisible(enable)
            self.format_button.setVisible(enable)

            self.nlabels.setVisible(enable)
            self.nlabels_edit.setVisible(enable)
            self.nlabels_button.setVisible(enable)

            self.ncolors.setVisible(enable)
            self.ncolors_edit.setVisible(enable)
            self.ncolors_button.setVisible(enable)

            self.grid2_title.setVisible(enable)
            self.vertical_radio.setVisible(enable)
            self.horizontal_radio.setVisible(enable)

            self.colormap.setVisible(enable)
            self.colormap_edit.setVisible(enable)
            self.colormap_button.setVisible(enable)

            self.on_apply()

    def create_widgets(self):
        """creates the menu objects"""
        # Name
        self.name = QLabel("Title:")
        self.name_edit = QLineEdit(str(self._default_name))
        self.name_button = QPushButton("Default")

        # Min
        self.min = QLabel("Min:")
        self.min_edit = QLineEdit(str(self._default_min))
        self.min_button = QPushButton("Default")

        # Max
        self.max = QLabel("Max:")
        self.max_edit = QLineEdit(str(self._default_max))
        self.max_button = QPushButton("Default")

        #---------------------------------------
        # Format
        self.format = QLabel("Format (e.g. %.3f, %g, %.6e):")
        self.format_edit = QLineEdit(str(self._format))
        self.format_button = QPushButton("Default")

        #---------------------------------------
        # Scale
        self.scale = QLabel("Scale:")
        self.scale_edit = QLineEdit(str(self._scale))
        self.scale_button = QPushButton("Default")
        if self._default_scale == 0.0:
            self.scale.setVisible(False)
            self.scale_edit.setVisible(False)
            self.scale_button.setVisible(False)

        # Phase
        self.phase = QLabel("Phase (deg):")
        self.phase_edit = QLineEdit(str(self._phase))
        self.phase_button = QPushButton("Default")
        if self._default_phase is None:
            self.phase.setVisible(False)
            self.phase_edit.setVisible(False)
            self.phase_button.setVisible(False)
            self.phase_edit.setText('0.0')
        #tip = QtGui.QToolTip()
        #tip.setTe
        #self.format_edit.toolTip(tip)

        #---------------------------------------
        # nlabels
        self.nlabels = QLabel("Number of Labels:")
        self.nlabels_edit = QLineEdit(str(self._nlabels))
        self.nlabels_button = QPushButton("Default")

        self.labelsize = QLabel("Label Size:")
        self.labelsize_edit = QLineEdit(str(self._labelsize))
        self.labelsize_button = QPushButton("Default")

        self.ncolors = QLabel("Number of Colors:")
        self.ncolors_edit = QLineEdit(str(self._ncolors))
        self.ncolors_button = QPushButton("Default")

        self.colormap = QLabel("Color Map:")
        self.colormap_edit = QComboBox(self)
        self.colormap_button = QPushButton("Default")
        for key in colormap_keys:
            self.colormap_edit.addItem(key)
        self.colormap_edit.setCurrentIndex(colormap_keys.index(self._colormap))

        # --------------------------------------------------------------
        # the header
        self.grid2_title = QLabel("Color Scale:")

        # red/blue or blue/red
        self.low_to_high_radio = QRadioButton('Low -> High')
        self.high_to_low_radio = QRadioButton('High -> Low')
        widget = QWidget(self)
        low_to_high_group = QButtonGroup(widget)
        low_to_high_group.addButton(self.low_to_high_radio)
        low_to_high_group.addButton(self.high_to_low_radio)
        self.low_to_high_radio.setChecked(self._default_is_low_to_high)
        self.high_to_low_radio.setChecked(not self._default_is_low_to_high)

        # horizontal / vertical
        self.horizontal_radio = QRadioButton("Horizontal")
        self.vertical_radio = QRadioButton("Vertical")
        widget = QWidget(self)
        horizontal_vertical_group = QButtonGroup(widget)
        horizontal_vertical_group.addButton(self.horizontal_radio)
        horizontal_vertical_group.addButton(self.vertical_radio)
        self.horizontal_radio.setChecked(self._default_is_horizontal)
        self.vertical_radio.setChecked(not self._default_is_horizontal)

        # on / off
        self.show_radio = QRadioButton("Show")
        self.hide_radio = QRadioButton("Hide")
        widget = QWidget(self)
        show_hide_group = QButtonGroup(widget)
        show_hide_group.addButton(self.show_radio)
        show_hide_group.addButton(self.hide_radio)
        self.show_radio.setChecked(self._default_is_shown)
        self.hide_radio.setChecked(not self._default_is_shown)

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

        if self._is_normals:
            self.max.hide()
            self.min.hide()
            self.max_edit.hide()
            self.min_edit.hide()
            self.max_button.hide()
            self.min_button.hide()

            self.format.hide()
            self.format_edit.hide()
            self.format_button.hide()

            self.nlabels.hide()
            self.nlabels_edit.hide()
            self.nlabels_button.hide()

            self.ncolors.hide()
            self.ncolors_edit.hide()
            self.ncolors_button.hide()

            self.grid2_title.hide()
            self.vertical_radio.hide()
            self.horizontal_radio.hide()
            self.show_radio.hide()
            self.hide_radio.hide()
            self.low_to_high_radio.hide()
            self.high_to_low_radio.hide()

            self.colormap.hide()
            self.colormap_edit.hide()
            self.colormap_button.hide()

        self.animate_button = QPushButton('Create Animation')

        if self._default_scale == 0.0:
            self.animate_button.setEnabled(False)
            self.animate_button.setToolTip(
                'This must be a displacement-like result to animate')

        # closing
        self.apply_button = QPushButton("Apply")
        self.ok_button = QPushButton("OK")
        self.cancel_button = QPushButton("Cancel")

    def create_layout(self):
        """displays the menu objects"""
        grid = QGridLayout()
        grid.addWidget(self.name, 0, 0)
        grid.addWidget(self.name_edit, 0, 1)
        grid.addWidget(self.name_button, 0, 2)

        grid.addWidget(self.min, 1, 0)
        grid.addWidget(self.min_edit, 1, 1)
        grid.addWidget(self.min_button, 1, 2)

        grid.addWidget(self.max, 2, 0)
        grid.addWidget(self.max_edit, 2, 1)
        grid.addWidget(self.max_button, 2, 2)

        grid.addWidget(self.format, 3, 0)
        grid.addWidget(self.format_edit, 3, 1)
        grid.addWidget(self.format_button, 3, 2)

        grid.addWidget(self.scale, 4, 0)
        grid.addWidget(self.scale_edit, 4, 1)
        grid.addWidget(self.scale_button, 4, 2)

        grid.addWidget(self.phase, 5, 0)
        grid.addWidget(self.phase_edit, 5, 1)
        grid.addWidget(self.phase_button, 5, 2)

        grid.addWidget(self.nlabels, 6, 0)
        grid.addWidget(self.nlabels_edit, 6, 1)
        grid.addWidget(self.nlabels_button, 6, 2)

        #grid.addWidget(self.labelsize, 6, 0)
        #grid.addWidget(self.labelsize_edit, 6, 1)
        #grid.addWidget(self.labelsize_button, 6, 2)

        grid.addWidget(self.ncolors, 7, 0)
        grid.addWidget(self.ncolors_edit, 7, 1)
        grid.addWidget(self.ncolors_button, 7, 2)

        grid.addWidget(self.colormap, 8, 0)
        grid.addWidget(self.colormap_edit, 8, 1)
        grid.addWidget(self.colormap_button, 8, 2)

        ok_cancel_box = QHBoxLayout()
        ok_cancel_box.addWidget(self.apply_button)
        ok_cancel_box.addWidget(self.ok_button)
        ok_cancel_box.addWidget(self.cancel_button)

        grid2 = QGridLayout()
        grid2.addWidget(self.grid2_title, 0, 0)
        grid2.addWidget(self.low_to_high_radio, 1, 0)
        grid2.addWidget(self.high_to_low_radio, 2, 0)

        grid2.addWidget(self.vertical_radio, 1, 1)
        grid2.addWidget(self.horizontal_radio, 2, 1)

        grid2.addWidget(self.show_radio, 1, 2)
        grid2.addWidget(self.hide_radio, 2, 2)

        grid2.addWidget(self.animate_button, 3, 1)

        #grid2.setSpacing(0)

        vbox = QVBoxLayout()
        vbox.addLayout(grid)
        #vbox.addLayout(checkboxes)
        vbox.addLayout(grid2)
        vbox.addStretch()
        vbox.addLayout(ok_cancel_box)

        #Create central widget, add layout and set
        #central_widget = QtGui.QWidget()
        #central_widget.setLayout(vbox)
        #self.setCentralWidget(central_widget)
        self.setLayout(vbox)

    def set_connections(self):
        """creates the actions for the buttons"""
        self.name_button.clicked.connect(self.on_default_name)
        self.min_button.clicked.connect(self.on_default_min)
        self.max_button.clicked.connect(self.on_default_max)
        self.format_button.clicked.connect(self.on_default_format)
        self.scale_button.clicked.connect(self.on_default_scale)
        self.phase_button.clicked.connect(self.on_default_phase)

        self.nlabels_button.clicked.connect(self.on_default_nlabels)
        self.labelsize_button.clicked.connect(self.on_default_labelsize)
        self.ncolors_button.clicked.connect(self.on_default_ncolors)
        self.colormap_button.clicked.connect(self.on_default_colormap)

        self.animate_button.clicked.connect(self.on_animate)

        self.show_radio.clicked.connect(self.on_show_hide)
        self.hide_radio.clicked.connect(self.on_show_hide)

        self.apply_button.clicked.connect(self.on_apply)
        self.ok_button.clicked.connect(self.on_ok)
        self.cancel_button.clicked.connect(self.on_cancel)

        if qt_version == 4:
            self.connect(self, QtCore.SIGNAL('triggered()'), self.closeEvent)
            #self.colormap_edit.activated[str].connect(self.onActivated)
        #else:
        # closeEvent???

    def set_font_size(self, font_size):
        """
        Updates the font size of the objects

        Parameters
        ----------
        font_size : int
            the font size
        """
        if self.font_size == font_size:
            return
        self.font_size = font_size
        font = QFont()
        font.setPointSize(font_size)
        self.setFont(font)
        self.name_edit.setFont(font)
        self.min_edit.setFont(font)
        self.max_edit.setFont(font)
        self.format_edit.setFont(font)
        self.scale_edit.setFont(font)
        self.phase_edit.setFont(font)
        self.nlabels_edit.setFont(font)
        self.labelsize_edit.setFont(font)
        self.ncolors_edit.setFont(font)

    def on_animate(self):
        """opens the animation window"""
        name, flag0 = self.check_name(self.name_edit)
        if not flag0:
            return

        scale, flag1 = self.check_float(self.scale_edit)
        if not flag1:
            scale = self._scale

        data = {
            'font_size': self.out_data['font_size'],
            'icase': self._icase,
            'name': name,
            'time': 2,
            'frames/sec': 30,
            'resolution': 1,
            'iframe': 0,
            'scale': scale,
            'default_scale': self._default_scale,
            'is_scale': self._default_phase is None,
            'phase': self._phase,
            'default_phase': self._default_phase,
            'dirname': os.path.abspath(os.getcwd()),
            'clicked_ok': False,
            'close': False,
        }
        if not self._animation_window_shown:
            self._animation_window = AnimationWindow(data, win_parent=self)
            self._animation_window.show()
            self._animation_window_shown = True
            self._animation_window.exec_()
        else:
            self._animation_window.activateWindow()

        if data['close']:
            if not self._animation_window._updated_animation:
                #self._apply_animation(data)
                pass
            self._animation_window_shown = False
            del self._animation_window
        else:
            self._animation_window.activateWindow()

    def on_default_name(self):
        """action when user clicks 'Default' for name"""
        name = str(self._default_name)
        self.name_edit.setText(name)
        self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_min(self):
        """action when user clicks 'Default' for min value"""
        self.min_edit.setText(str(self._default_min))
        self.min_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_max(self):
        """action when user clicks 'Default' for max value"""
        self.max_edit.setText(str(self._default_max))
        self.max_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_format(self):
        """action when user clicks 'Default' for the number format"""
        self.format_edit.setText(str(self._default_format))
        self.format_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_scale(self):
        """action when user clicks 'Default' for scale factor"""
        self.scale_edit.setText(str(self._default_scale))
        self.scale_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_phase(self):
        """action when user clicks 'Default' for phase angle"""
        self.phase_edit.setText(str(self._default_phase))
        self.phase_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_ncolors(self):
        """action when user clicks 'Default' for number of colors"""
        self.ncolors_edit.setText(str(self._default_ncolors))
        self.ncolors_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_colormap(self):
        """action when user clicks 'Default' for the color map"""
        self.colormap_edit.setCurrentIndex(
            colormap_keys.index(self._default_colormap))

    def on_default_nlabels(self):
        """action when user clicks 'Default' for number of labels"""
        self.nlabels_edit.setStyleSheet("QLineEdit{background: white;}")
        self.nlabels_edit.setText(str(self._default_nlabels))

    def on_default_labelsize(self):
        """action when user clicks 'Default' for number of labelsize"""
        self.labelsize_edit.setText(str(self._default_labelsize))
        self.labelsize_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_show_hide(self):
        """action when user clicks the 'Show/Hide' radio button"""
        self.colormap_edit.setCurrentIndex(
            colormap_keys.index(self._default_colormap))
        is_shown = self.show_radio.isChecked()
        self.vertical_radio.setEnabled(is_shown)
        self.horizontal_radio.setEnabled(is_shown)

    @staticmethod
    def check_name(cell):
        cell_value = cell.text()
        try:
            text = str(cell_value).strip()
        except UnicodeEncodeError:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

        if len(text):
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    @staticmethod
    def check_colormap(cell):
        text = str(cell.text()).strip()
        if text in colormap_keys:
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    def on_validate(self):
        name_value, flag0 = self.check_name(self.name_edit)
        min_value, flag1 = self.check_float(self.min_edit)
        max_value, flag2 = self.check_float(self.max_edit)
        format_value, flag3 = self.check_format(self.format_edit)
        scale, flag4 = self.check_float(self.scale_edit)
        phase, flag5 = self.check_float(self.phase_edit)

        nlabels, flag6 = self.check_positive_int_or_blank(self.nlabels_edit)
        ncolors, flag7 = self.check_positive_int_or_blank(self.ncolors_edit)
        labelsize, flag8 = self.check_positive_int_or_blank(
            self.labelsize_edit)
        colormap = str(self.colormap_edit.currentText())

        if all([flag0, flag1, flag2, flag3, flag4, flag5, flag6, flag7,
                flag8]):
            if 'i' in format_value:
                format_value = '%i'

            assert isinstance(scale, float), scale
            self.out_data['name'] = name_value
            self.out_data['min'] = min_value
            self.out_data['max'] = max_value
            self.out_data['format'] = format_value
            self.out_data['scale'] = scale
            self.out_data['phase'] = phase

            self.out_data['nlabels'] = nlabels
            self.out_data['ncolors'] = ncolors
            self.out_data['labelsize'] = labelsize
            self.out_data['colormap'] = colormap

            self.out_data['is_low_to_high'] = self.low_to_high_radio.isChecked(
            )
            self.out_data['is_horizontal'] = self.horizontal_radio.isChecked()
            self.out_data['is_shown'] = self.show_radio.isChecked()

            self.out_data['clicked_ok'] = True
            self.out_data['close'] = True
            #print('self.out_data = ', self.out_data)
            #print("name = %r" % self.name_edit.text())
            #print("min = %r" % self.min_edit.text())
            #print("max = %r" % self.max_edit.text())
            #print("format = %r" % self.format_edit.text())
            return True
        return False

    def on_apply(self):
        passed = self.on_validate()
        if passed:
            self.win_parent._apply_legend(self.out_data)
        return passed

    def on_ok(self):
        passed = self.on_apply()
        if passed:
            self.close()
            #self.destroy()

    def on_cancel(self):
        self.out_data['close'] = True
        self.close()
예제 #9
0
class FindInFilesDialog(QDialog):

    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
            self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
            self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
            self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
            self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
            self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
            self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
            self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
            self._words_radio_pressed)

    def _replace_activated(self):
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        self._kill_thread()
        # Crazy hack to avoid circular imports
        self.result_widget.parent().parent().parent().hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(self,
            self.tr("Open Directory"),
            self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(
            self.dir_combo.currentText(), file_name, items)

    def _kill_thread(self):
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        # Version of PyQt API 1
        # filters = self.filters_line_edit.text().split(QRegExp("[,;]"),
        #     QString.SkipEmptyParts)

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join(
                [word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
            by_phrase)
예제 #10
0
    def initDownloadTab(self):
        # # # Download Tab# # # 
        download_tab = QWidget()
        download_tab_layout = QVBoxLayout()
        self.tabWidget.addTab(download_tab, "Download HITs")

        # Status
        status_box = QGroupBox()
        status_box.setTitle("Status")
        status_layout = QGridLayout()
        self.table_turk = ContextTable(0, 4, self)
        self.table_turk.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.table_turk.setColumnWidth(0, 160)
        self.table_turk.setColumnWidth(1, 50)
        self.table_turk.setColumnWidth(2, 90)
        self.table_turk.setColumnWidth(3, 90)
        # self.table_turk.verticalHeader().setVisible(False)

        # Set Headers
        header_0 = QTableWidgetItem()
        header_0.setText("Turker")
        self.table_turk.setHorizontalHeaderItem(0, header_0)

        header_1 = QTableWidgetItem()
        header_1.setText("HITs")
        self.table_turk.setHorizontalHeaderItem(1, header_1)

        header_2 = QTableWidgetItem()
        header_2.setText("Rejected")
        self.table_turk.setHorizontalHeaderItem(2, header_2)

        header_3 = QTableWidgetItem()
        header_3.setText("Approved")
        self.table_turk.setHorizontalHeaderItem(3, header_3)

        status_layout.addWidget(self.table_turk, 0, 0, 1, 2)

        # Status Button
        status_button = QPushButton('Update Status')
        status_button.clicked.connect(self.getStatus)

        status_layout.addWidget(status_button, 1, 1)
        status_box.setLayout(status_layout)
        download_tab_layout.addWidget(status_box) 

        # Download Button
        download_button = QPushButton("Download Results")
        download_button.clicked.connect(self.download)
        status_layout.addWidget(download_button, 1, 0)

        # Options Box
        options_box = QGroupBox()
        options_box.setTitle("Import results")
        options_box_layout = QGridLayout()
        matching = QRadioButton("Choose best matching Outlines")
        matching.setEnabled(False)
        review = QRadioButton("Review by hand")
        review.setChecked(True)
        review_button = QPushButton("Review Results")
        review_button.clicked.connect(self.review)

        # Import Button
        import_button = QPushButton("Import results")
        import_button.clicked.connect(self.importResults)

        options_box_layout.addWidget(review, 0, 0)
        options_box_layout.addWidget(review_button, 0, 1)
        options_box_layout.addWidget(matching, 1, 0)
        options_box_layout.addWidget(import_button, 2, 0, 1, 2)

        options_box.setLayout(options_box_layout)
        download_tab_layout.addWidget(options_box)
        download_tab.setLayout(download_tab_layout)
예제 #11
0
class SettingsPage(QWidget):
    """
    """
    ReloadSettings = pyqtSignal()
    TestSettings = pyqtSignal(dict) 
    def __init__(self, parent):
        """
        """
        super(SettingsPage, self).__init__()
        self.__core = parent
        self.config = None

        self.createWidgets()
        self.createConnections()
        
        self.loadCfg()
        
    def core(self):
        """
        """
        return self.__core

    def createConnections(self):
        """
        """
        self.saveButton.clicked.connect( self.__saveCfg )
        self.testButton.clicked.connect( self.testConnection )
        
    def createWidgets(self):
        """
        """
        qcCredGroup = QGroupBox(self.tr("HP ALM server credentials"))
        self.hpCredLogin = QLineEdit()
        self.hpCredPwd = QLineEdit()
        self.hpCredPwd.setEchoMode(QLineEdit.Password)
        qcCredLayout = QGridLayout()
        qcCredLayout.addWidget( QLabel("Login"), 0, 0)
        qcCredLayout.addWidget( self.hpCredLogin, 0, 1)
        qcCredLayout.addWidget( QLabel("Password"), 1, 0)
        qcCredLayout.addWidget( self.hpCredPwd, 1, 1)
        qcCredGroup.setLayout(qcCredLayout)
        
        qcSvrGroup = QGroupBox(self.tr("HP ALM server informations"))
        self.hpSvrURL = QLineEdit()
        self.hpSvrDomain = QLineEdit()
        self.hpSvrProject = QLineEdit()

        self.comAPI = QRadioButton("COM")
        self.comAPI.setChecked(False)
        self.comAPI.setEnabled(False)
        
        self.restAPI = QRadioButton("REST")
        self.restAPI.setChecked(True)
        
        layoutApi = QHBoxLayout()
        layoutApi.addWidget(self.comAPI)
        layoutApi.addWidget(self.restAPI)
        
        qcSvrLayout = QGridLayout()
        qcSvrLayout.addWidget( QLabel("URL"), 0, 0)
        qcSvrLayout.addWidget( self.hpSvrURL, 0, 1)
        qcSvrLayout.addWidget( QLabel("Domain"), 1, 0)
        qcSvrLayout.addWidget( self.hpSvrDomain, 1, 1)
        qcSvrLayout.addWidget( QLabel("Project"), 2, 0)
        qcSvrLayout.addWidget( self.hpSvrProject, 2, 1)
        qcSvrLayout.addWidget( QLabel("API"), 3, 0)
        qcSvrLayout.addLayout( layoutApi, 3, 1)
        
        qcSvrGroup.setLayout(qcSvrLayout)

        # begin export result settings
        qcExportResultGroup = QGroupBox(self.tr("Export results"))
        self.ignoreTcCheckBox = QCheckBox(self.tr("Ignore testcase(s)"))
        self.ignoreUncompleteCheckBox = QCheckBox(self.tr("Ignore uncomplete test(s)"))
        self.addFoldersTlCheckBox = QCheckBox(self.tr("Create missing folders in test lab"))
        self.addTestsetCheckBox = QCheckBox(self.tr("Create testset if missing in test lab"))
        self.addTestinstanceCheckBox = QCheckBox(self.tr("Create test instance in test set"))
        self.cfgsTestsetTable = DesignPage.ConfigsTableView(self, core=self.core())
        qcExportResultLayout = QVBoxLayout()
        qcExportResultLayout.addWidget( self.ignoreTcCheckBox )
        qcExportResultLayout.addWidget( self.ignoreUncompleteCheckBox )
        qcExportResultLayout.addWidget( self.addFoldersTlCheckBox )
        qcExportResultLayout.addWidget( self.addTestsetCheckBox )
        qcExportResultLayout.addWidget( self.addTestinstanceCheckBox )
        qcExportResultLayout.addWidget( QLabel("Custom TestSet Fields"))
        qcExportResultLayout.addWidget( self.cfgsTestsetTable )
        qcExportResultLayout.addStretch(1)
        qcExportResultGroup.setLayout(qcExportResultLayout)
        # end 
        
        # begin export test settings
        qcExportGroup = QGroupBox(self.tr("Export tests"))
        
        self.mergeCheckBox = QCheckBox(self.tr("Merge all tests in one"))
        self.mergeStepsCheckBox = QCheckBox(self.tr("Merge all steps in one"))
        self.showTcNameCheckBox = QCheckBox(self.tr("Load with original test name"))
        self.replaceTcCheckBox = QCheckBox(self.tr("Replace testcase with testname"))
        self.addFoldersTpCheckBox = QCheckBox(self.tr("Create missing folders in test plan"))
        self.overwriteTcCheckBox = QCheckBox(self.tr("Overwrite testcases in test plan"))
        self.cfgsTable = DesignPage.ConfigsTableView(self, core=self.core())

        qcExportLayout = QGridLayout()
        qcExportLayout.addWidget( self.mergeCheckBox, 0, 0)
        qcExportLayout.addWidget( self.mergeStepsCheckBox, 1, 0)
        qcExportLayout.addWidget( self.showTcNameCheckBox, 2, 0)
        qcExportLayout.addWidget( self.replaceTcCheckBox, 3, 0)
        qcExportLayout.addWidget( self.addFoldersTpCheckBox, 4, 0)
        qcExportLayout.addWidget( self.overwriteTcCheckBox, 5, 0)
        qcExportLayout.addWidget( QLabel("Custom Test Fields"), 6, 0)
        qcExportLayout.addWidget( self.cfgsTable, 7, 0)
        qcExportGroup.setLayout(qcExportLayout)
        # end 
        
        layoutCtrls = QHBoxLayout()
        self.saveButton = QPushButton(self.tr("Save Settings"), self)
        self.testButton = QPushButton(self.tr("Test Connection"), self)
        layoutCtrls.addWidget(self.saveButton)
        layoutCtrls.addWidget(self.testButton)
        
        mainLayout = QGridLayout()
        mainLayout.addWidget(qcSvrGroup, 0, 0)
        mainLayout.addWidget(qcCredGroup, 0, 1)
        mainLayout.addWidget(qcExportGroup, 2, 0)
        mainLayout.addWidget(qcExportResultGroup, 2, 1)
        mainLayout.addLayout(layoutCtrls, 3, 1)
        self.setLayout(mainLayout)
        
    def loadCfg(self):
        """
        """
        with open( "%s/config.json" % (QtHelper.dirExec()) ) as f:
            CONFIG_RAW = f.read()
        self.config = json.loads(CONFIG_RAW)

        self.hpCredLogin.setText(self.config["credentials"]["login"])
        self.hpSvrURL.setText(self.config["qc-server"]["url"])
        self.hpSvrDomain.setText(self.config["qc-server"]["domain"])
        self.hpSvrProject.setText(self.config["qc-server"]["project"])

        self.restAPI.setChecked(True) 
        
        if self.config["export-tests"]["merge-all-tests"]: 
            self.mergeCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["merge-all-steps"]: 
            self.mergeStepsCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["original-test"]: 
            self.showTcNameCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["replace-testcase"]: 
            self.replaceTcCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["add-folders"]: 
            self.addFoldersTpCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-tests"]["overwrite-tests"]: 
            self.overwriteTcCheckBox.setCheckState(Qt.Checked) 
        self.cfgsTable.loadTable(data=self.config["custom-test-fields"])
        
        if self.config["export-results"]["ignore-testcase"]: 
            self.ignoreTcCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["ignore-uncomplete"]: 
            self.ignoreUncompleteCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-folders"]: 
            self.addFoldersTlCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-testset"]: 
            self.addTestsetCheckBox.setCheckState(Qt.Checked) 
        if self.config["export-results"]["add-testinstance"]: 
            self.addTestinstanceCheckBox.setCheckState(Qt.Checked) 
        self.cfgsTestsetTable.loadTable(data=self.config["custom-testset-fields"])
        
        # decrypt password
        if len(self.config["credentials"]["password"]):
            decrypted = self.decryptPwd(
                                        key=bytes(self.config["credentials"]["login"], "utf8" ),
                                        ciphertext=bytes(self.config["credentials"]["password"], "utf8" )
                                        )
            self.config["credentials"]["password"] = decrypted
            self.hpCredPwd.setText(decrypted)

    def __saveCfg(self):
        """
        """
        self.saveCfg(successMsg=True)
        
    def saveCfg(self, successMsg=True):
        """
        """
        # if successMsg:
        if not len(self.hpSvrURL.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server url") )
            return
        if not len(self.hpSvrDomain.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server domain") )
            return
        if not len(self.hpSvrProject.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set the server project") )
            return

        if not len(self.hpCredLogin.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set a login") )
            return
        if not len(self.hpCredPwd.text()):
            QMessageBox.warning(self, self.tr("Save Settings") , self.tr("Please to set a password") )
            return
            
        self.config["credentials"]["login"] = self.hpCredLogin.text()
        # encrypt password
        encryptPwd = self.encryptPwd(
                                    key=self.hpCredLogin.text(),
                                    plaintext=self.hpCredPwd.text()
                                   )
        self.config["credentials"]["password"] = str(encryptPwd, "utf8")
        
        self.config["qc-server"]["url"] = self.hpSvrURL.text()
        self.config["qc-server"]["domain"] = self.hpSvrDomain.text()
        self.config["qc-server"]["project"] = self.hpSvrProject.text()
        self.config["qc-server"]["use-rest"] = False
        if self.restAPI.isChecked(): self.config["qc-server"]["use-rest"] = True
        
        self.config["export-tests"]["merge-all-tests"] = False
        self.config["export-tests"]["merge-all-steps"] = False
        self.config["export-tests"]["original-test"] = False
        self.config["export-tests"]["replace-testcase"] = False
        self.config["export-tests"]["add-folders"] = False
        self.config["export-tests"]["overwrite-tests"] = False
        if self.mergeCheckBox.isChecked(): self.config["export-tests"]["merge-all-tests"] = True
        if self.mergeStepsCheckBox.isChecked(): self.config["export-tests"]["merge-all-steps"] = True
        if self.showTcNameCheckBox.isChecked(): self.config["export-tests"]["original-test"] = True
        if self.replaceTcCheckBox.isChecked(): self.config["export-tests"]["replace-testcase"] = True
        if self.addFoldersTpCheckBox.isChecked(): self.config["export-tests"]["add-folders"] = True
        if self.overwriteTcCheckBox.isChecked(): self.config["export-tests"]["overwrite-tests"] = True
        self.config["custom-test-fields"] = self.cfgsTable.model.getData()
        
        self.config["export-results"]["add-folders"] = False
        self.config["export-results"]["ignore-testcase"] = False
        self.config["export-results"]["ignore-uncomplete"] = False
        self.config["export-results"]["add-testset"] = False
        self.config["export-results"]["add-testinstance"] = False
        if self.ignoreTcCheckBox.isChecked(): self.config["export-results"]["ignore-testcase"] = True
        if self.ignoreUncompleteCheckBox.isChecked(): self.config["export-results"]["ignore-uncomplete"] = True
        if self.addFoldersTlCheckBox.isChecked(): self.config["export-results"]["add-folders"] = True
        if self.addTestsetCheckBox.isChecked(): self.config["export-results"]["add-testset"] = True
        if self.addTestinstanceCheckBox.isChecked(): self.config["export-results"]["add-testinstance"] = True
        self.config["custom-testset-fields"] = self.cfgsTestsetTable.model.getData()
        
        with open( "%s/config.json" % (QtHelper.dirExec()), "w" ) as f:
            f.write( json.dumps(self.config) )
            
        if len(self.config["credentials"]["password"]):
            self.config["credentials"]["password"] = self.decryptPwd(
                                            key=bytes(self.config["credentials"]["login"], "utf8" ),
                                            ciphertext=bytes(self.config["credentials"]["password"], "utf8" )
                                  )
                
        self.ReloadSettings.emit()
        
        if successMsg: QMessageBox.information(self, self.tr("Save Settings") ,  self.tr("Settings saved.") )
                                
    def cfg(self):
        """
        """
        return self.config
        
    def encryptPwd(self, key, plaintext):
        """
        """
        return base64.b64encode( bytes( plaintext, "utf8" ) )

    def decryptPwd(self, key, ciphertext):
        """
        """
        return str( base64.b64decode(ciphertext) , "utf8")
    
    def testConnection(self):
        """
        """
        self.TestSettings.emit(self.config)
예제 #12
0
파일: gui_base.py 프로젝트: Ptaah/Ekd
class Base(QWidget):
    """
        Module des cadres de l'onglet animation
    """

    Audio = 1
    Video = 2

    def __init__(self, boite='grid', nomReglage=None, nomSource=None, titre="None", parent=None):
        super(Base, self).__init__(parent)
        # Taille du widget mplayer
        self.tailleMplayer = (240,216)

        # Définition du titre
        self.Titre =  QLabel()
        self.setTitle(titre)

        # Définition des tabs
        #----------------------------------------------------------------
        self.Source =  QLabel("<h1>Source</h1>")
        self.Reglage =  QLabel("<h1>Reglage</h1>")
        self.Preview = QLabel("<h1>Preview</h1>")
        self.Logs = QLabel("<h1>Logs</h1>")

        self.tab = QTabWidget()
        self.scroll = QScrollArea()
        self.scroll.setWidget(self.tab)
        self.scroll.setWidgetResizable(True)

        self.connect(self.tab, SIGNAL("currentChanged (int)"), self.activateTab)

        # Definition du layout :
        #| Titre                            |
        # ----------------------------------
        #| tabOuvrir | tabReglage | ... |   |
        #|----------------------------------|
        #|...                               |
        #|----------------------------------|
        #|Aide|                   |Appliquer|
        #'----------------------------------'
        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.Titre)
        #self.layout.addWidget(self.tab)
        self.layout.addWidget(self.scroll)
        #----------------------------------------------------------------

        self.boutAide=QPushButton(_(u"Aide"))
        self.boutAide.setIcon(QIcon("Icones" + os.sep + "icone_aide_128.png"))
        self.connect(self.boutAide, SIGNAL("clicked()"), self.afficherAide)

        #self.tamponBut = QPushButton(QIcon("Icones"+os.sep+"icone_load_128.png"), _(u"Tampon test"))
        #self.connect(self.tamponBut, SIGNAL("clicked()"), self.tamponAction)

        # On ajoute des bouton pour forcer l'utilisateur à vérifier ses réglages
        self.Next = QPushButton(_(u"Réglages"))
        ####################################################################
        self.Next.setIcon(QIcon("Icones" + os.sep + "droite.png"))
        ####################################################################
        self.connect(self.Next, SIGNAL("clicked()"), self.next)

        self.boutApp=QPushButton(_(u"Appliquer"))
        self.boutApp.setIcon(QIcon("Icones" + os.sep + "icone_appliquer_128.png"))
        ## Le bouton doit toujours être désactivé à l'initialisation
        self.boutApp.setEnabled(False)

        self.connect(self.boutApp, SIGNAL("clicked()"), self.appliquer)

        # ligne de séparation juste au dessus des boutons
        ligne = QFrame()
        ligne.setFrameShape(QFrame.HLine)
        ligne.setFrameShadow(QFrame.Sunken)
        self.layout.addWidget(ligne)
        self.layout.addSpacing(-5)      # la ligne doit être plus près des boutons

        hbox=QHBoxLayout()
        hbox.addWidget(self.boutAide)
        #hbox.addWidget(self.tamponBut)
        hbox.addStretch()       # espace entre les 2 boutons
        hbox.addWidget(self.Next)
        hbox.addWidget(self.boutApp)

        self.layout.addLayout(hbox)

    def tamponAction(self) :
      """Fonction à définir dans chaque tableau pour importer les données du tampon"""
      #print u"[DEBUG] Fonction tamponAction non implémentée dans le tableau ", self.idSection
      EkdPrint(u"[DEBUG] Fonction tamponAction non implémentée dans le tableau %s" % self.idSection)

    def setTitle(self, titre=_(u"Title")):
        titre=u"<h2>" + titre + u"</h2>"
        self.Titre.setText(titre)

    def add(self, objet, nom=_(u"Onglet")):
        self.tab.addTab(objet, nom)

    def activateTab(self, index):
        tabCount = self.tab.count()
        if 0 == index :
            self.Next.setText(_(u"Réglages"))
        elif ( tabCount - 1 ) == index :
            self.Next.setText(_(u"Recommencer"))
        elif (tabCount - 2) == index :
            self.Next.setText(_(u"Infos supplémentaires"))
        else:
            self.Next.setText(_(u"Suivant"))

    def next(self):
        tabCount = self.tab.count()
        index = self.tab.currentIndex()
        index = (index + 1) % tabCount
        self.tab.setCurrentIndex(index)

    #----------------
    # Meta-widgets
    #----------------


    def addSource(self, type, nomSource=None):
        """ Boîte de groupe : "Fichier vidéo source" """
        if type == Base.Video :
            if not nomSource: nomSource=_(u'Vidéo source')
            self.ligneEditionSource=QLineEdit()
            self.ligneEditionSource.setReadOnly(True)
            boutParcourir=QPushButton(_(u'Parcourir...'))
            boutParcourir.setIcon(QIcon("Icones/ouvrir.png"))
            self.connect(boutParcourir, SIGNAL("clicked()"), self.ouvrirSource)

            groupSource=QGroupBox(nomSource)
            hbox=QHBoxLayout(groupSource)
            hbox.addWidget(self.ligneEditionSource)
            hbox.addWidget(boutParcourir)
            self.Source = groupSource
            self.tabOuvrirVideo  = self.tab.addTab(self.Source, nomSource)

        else :
            if not nomSource: nomSource=_(u"Fichier audio source")
            self.ligneEditionSourceAudio=QLineEdit()
            self.ligneEditionSourceAudio.setReadOnly(True)

            boutParcourir=QPushButton(_(u'Parcourir...'))
            boutParcourir.setIcon(QIcon("Icones/ouvrir.png"))
            self.connect(boutParcourir, SIGNAL("clicked()"), self.ouvrirSource)

            groupSource=QGroupBox(nomSource)
            hbox=QHBoxLayout(groupSource)
            hbox.addWidget(self.ligneEditionSourceAudio)
            hbox.addWidget(boutParcourir)
            self.Source = groupSource
            self.tabOuvrirAudio = self.tab.addTab(self.Source, nomSource)


    def addReglage(self, boite='hbox', nomReglage = None):
        """ Boîte de groupe de réglage """
        if not nomReglage: nomReglage=_(u"Réglages")
        self.groupReglage=QGroupBox()

        if boite=='vbox':
            self.layoutReglage = QVBoxLayout(self.groupReglage)
        elif boite=='hbox':
            self.layoutReglage = QHBoxLayout(self.groupReglage)
        elif boite=='grid':
            self.layoutReglage = QGridLayout(self.groupReglage)

        self.Reglage = self.groupReglage
        self.add(self.Reglage, nomReglage)



    def addPreview(self, boite='vbox', nomPreview = None, light = False, mode = "Video"):
        # ----------------------------
        # Boite de groupe de mplayer
        # ----------------------------
        group=QGroupBox("")
        if nomPreview == None : nomPreview=_(u'Visionner vidéo')
        else : nomPreview=_(nomPreview)
        vboxMplayer = QVBoxLayout(group)
        if mode =="Video+Audio" :
            vidtitre = QLabel(_(u"Vidéo"))
            vidtitre.setAlignment(Qt.AlignHCenter)
            vboxMplayer.addWidget(vidtitre)

        self.mplayer=Mplayer(taille=(250, 225), choixWidget=(Mplayer.RATIO, Mplayer.PAS_PRECEDENT_SUIVANT,Mplayer.CURSEUR_SUR_UNE_LIGNE,Mplayer.PAS_PARCOURIR, Mplayer.LIST))
        ## On utilise la nouvelle interface de récupération des vidéos
        self.mplayer.listeVideos = []
        self.mplayer.setEnabled(False)
        hbox = QHBoxLayout()
        hbox.addStretch()
        hbox.addWidget(self.mplayer)
        hbox.addStretch()
        vboxMplayer.addLayout(hbox)
        hbox = QHBoxLayout()
        if not light :
            self.radioSource = QRadioButton(_(u"vidéo(s) source(s)"))
            self.radioSource.setChecked(True)
            self.radioSource.setEnabled(False)
            self.connect(self.radioSource, SIGNAL("toggled(bool)"), self.fctRadioSource)
            self.radioConvert = QRadioButton(_(u"vidéo(s) convertie(s)"))
            self.radioConvert.setEnabled(False)
            self.connect(self.radioConvert, SIGNAL("toggled(bool)"), self.fctRadioConvert)
            self.boutCompare = QPushButton(_(u"Comparateur de vidéos"))
            self.boutCompare.setEnabled(False)

            self.connect(self.boutCompare, SIGNAL("clicked()"), self.widget2Mplayer)
            hbox.addWidget(self.radioSource)
            hbox.addWidget(self.radioConvert)
            hbox.addWidget(self.boutCompare)
            if self.idSection == "animation_filtresvideo":
                self.boutApercu = QPushButton(_(u"Aperçu"))
                self.connect(self.boutApercu, SIGNAL("clicked()"), self.apercu)
                self.boutApercu.setEnabled(False)
                hbox.addWidget(self.boutApercu)

        if mode =="Video+Audio" :
            self.mplayerA=Mplayer(taille=(250, 225), choixWidget=(Mplayer.RATIO,Mplayer.PAS_PRECEDENT_SUIVANT,Mplayer.CURSEUR_SUR_UNE_LIGNE,Mplayer.PAS_PARCOURIR))
            self.mplayerA.setAudio(True)
            self.mplayerA.listeVideos = []
            self.mplayerA.setEnabled(False)
            hboxA = QHBoxLayout()
            hboxA.addStretch()
            hboxA.addWidget(self.mplayerA)
            hboxA.addStretch()

        hbox.setAlignment(Qt.AlignHCenter)
        vboxMplayer.addLayout(hbox)
        if mode =="Video+Audio" :
            audtitre = QLabel(_(u"Audio"))
            audtitre.setAlignment(Qt.AlignHCenter)
            vboxMplayer.addWidget(audtitre)
            vboxMplayer.addLayout(hboxA)
        vboxMplayer.addStretch()
        group.setAlignment(Qt.AlignHCenter)
        self.add(group, nomPreview)

    def addLog(self):
        self.Logs = QTextEdit()
        self.tabLog = self.add(self.Logs, _(u'Infos'))



    def infoLog(self, image=None, video=None, audio=None, sortie=None) :
        """Fonction pour la mise à jour des informations de log données à l'utilisateur en fin de process sur les données entrées, et le résultat du process"""
        if image != None :
            if type(image) == list :
                msgIm = _(u"<p>####################################<br># Images chargées<br>####################################</p>")
                for im in image :
                    msgIm += unicode(im)+u"<br>"
            else :
                msgIm = _(u"<p>####################################<br># Image chargée<br>####################################</p>")+unicode(image)+u"<br>"
        else :
            msgIm = u""

        if video != None :
            if type(video) == list :
                msgVid = _(u"<p>####################################<br># Vidéos chargées<br>####################################</p>")
                for vid in video :
                    msgVid += unicode(vid)+u"<br>"
            else :
                msgVid = _(u"<p>####################################<br># Vidéo chargée<br>####################################</p>")+unicode(video)+u"<br>"
        else :
            msgVid = u""

        if audio != None :
            if type(audio) == list :
                msgAu = _(u"<p>####################################<br># Fichiers audio chargés<br>####################################</p>")
                for au in audio :
                    msgAu += unicode(au)+u"<br>"
            else :
                msgAu = _(u"<p>####################################<br># Fichier audio chargé<br>####################################</p>")+unicode(audio)+u"<br>"
        else :
            msgAu = u""

        if sortie != None :
            if type(sortie) == list :
                msgOut = _(u"<p>####################################<br># Fichiers de sortie<br>####################################</p>")
                for out in sortie :
                    msgOut += unicode(out)+u"<br>"
            else :
                msgOut = _(u"<p>####################################<br># Fichier de sortie<br>####################################</p>")+unicode(sortie)+u"<br>"
        else :
            msgOut = _(u"<p>Sortie non définie ???</br>")
        messageLog = QString(msgIm+msgVid+msgAu+msgOut)
        self.Logs.setHtml(messageLog)

    def widget2Mplayer(self):
        """Boite de dialogue de comparaison de vidéos"""

        if type(self.chemin) == list :
            chemin = self.chemin
        else :
            chemin = [self.chemin]

        mplayerAvantConv=Mplayer(chemin, (350,262), (Mplayer.RATIO, Mplayer.PAS_PRECEDENT_SUIVANT,Mplayer.CURSEUR_SUR_UNE_LIGNE,Mplayer.PAS_PARCOURIR, Mplayer.LIST))

        # Widget-mplayer après encodage: lecture du fichier de sortie

        mplayerApresConv=Mplayer(self.lstFichiersSortie, (350,262), (Mplayer.RATIO, Mplayer.PAS_PRECEDENT_SUIVANT,Mplayer.CURSEUR_SUR_UNE_LIGNE,Mplayer.PAS_PARCOURIR, Mplayer.LIST))

        #print "Affichage de la meta-barre mplayer"
	EkdPrint(u"Affichage de la meta-barre mplayer")
        metaMPlayer = MetaMPlayer(mplayerAvantConv,mplayerApresConv)
        metaMPlayer.exec_()

    #---------------------
    # Fonctions communes
    #---------------------

    def fctRadioSource(self, bool=None):
        """"Communique la vidéo appropriée à mplayer"""
        if bool:
            self.mplayer.setVideos(self.chemin)
            self.mplayer.arretMPlayer()
            try :
                self.radioConvert.setChecked(False)
            except : None

    def fctRadioConvert(self, bool=None):
        """"Communique la vidéo résultat appropriée à mplayer"""
        if bool:
            self.mplayer.arretMPlayer()
            self.mplayer.setVideos(self.lstFichiersSortie)
            try :
                self.radioSource.setChecked(False)
            except : None


    def repSortieProv(self):
        """Répertoire sur lequel s'ouvrira la boite de dialogue de sauvegarde"""
        rep = os.path.dirname(unicode(self.chemin))

        if os.path.exists(rep): return rep
        else: return '~'


    def recupSources(self, nomEntree=None):
        """Récupère les fichiers sources vidéo via une boite de dialogue. Utilise et modifie les paramètres de configuration"""

        if not self.lstFichiersSource: listePleine = False
        else:
            listePleine = True
            fichier = self.lstFichiersSource[0]
            path = os.path.dirname(fichier)

        if listePleine and os.path.exists(path):
            repEntree = path
        else:
            try:
                repEntree = EkdConfig.get('general','video_input_path').decode("UTF8")
            except Exception, e:
                repEntree = '~'
                EkdConfig.set('general','video_input_path', repEntree.encode("UTF8"))
            if not os.path.exists(repEntree):
                repEntree = '~'
                EkdConfig.set('general','video_input_path', repEntree.encode("UTF8"))

        txt = _(u"Fichiers vidéo")
        if not nomEntree:
            liste=QFileDialog.getOpenFileNames(None, _(u"Ouvrir"), os.path.expanduser(repEntree),
                    "%s (*.avi *.mpg *.mpeg *.mjpeg *.flv *.mp4 *.h264 *.dv *.vob)\n*" %txt)
            liste = [unicode(i) for i in liste]
        else: # module séquentiel
            liste = nomEntree

        if len(liste)==0: return
        EkdConfig.set('general','video_input_path',os.path.dirname(liste[0]).encode("UTF8"))

        return liste
예제 #13
0
class ApplicationWindow(QMainWindow):
    def __init__(self):

        super(ApplicationWindow, self).__init__()

        self._init_ui()
        self._set_defaults()

    def _init_ui(self):

        # Styles
        self.setStyleSheet("""QRadioButton {
                max-width: 40px;
            }""")

        bold_font = QFont()
        bold_font.setBold(True)

        title_label = QLabel(self)
        title_label.setText("PyPass3")
        title_label.move(10, 0)
        title_label.setMinimumSize(300, 20)
        title_label.setFont(bold_font)

        length_label = QLabel(self)
        length_label.setText("Length")
        length_label.move(192, 185)
        length_label.setMinimumSize(200, 20)
        length_label.setFont(bold_font)

        main_label = QLabel(self)
        main_label.setText("Make robust secrets with random characters,\n"
                           "words, or numbers. Or choose number of dice\n"
                           "and rolls for words type passphrase. Defaults\n"
                           "to 5 dice and 5 rolls.\n")
        main_label.setMinimumSize(280, 100)
        main_label.move(10, 15)

        type_label = QLabel(self)
        type_label.setText("Secret type")
        type_label.move(10, 87)
        type_label.setFont(bold_font)

        dice_label = QLabel(self)
        dice_label.setText("Number of dice")
        dice_label.move(10, 138)
        dice_label.setMinimumSize(280, 20)
        dice_label.setFont(bold_font)

        rolls_label = QLabel(self)
        rolls_label.setText("Number of rolls")
        rolls_label.move(10, 190)
        rolls_label.setMinimumSize(280, 20)
        rolls_label.setFont(bold_font)

        self.textbox = QTextEdit(self)
        self.textbox.setMinimumSize(280, 100)
        self.textbox.move(10, 245)
        self.textbox.setFontFamily("Courier New")

        self.length_textline = QLineEdit(self)
        self.length_textline.setMinimumSize(100, 20)
        self.length_textline.move(190, 210)

        min_width = 125
        # max_width = 150

        # Add Generate button
        generate_btn = QPushButton('Generate', self)
        generate_btn.setToolTip('Click to generate secret')
        # generate_btn.clicked.connect(on_click)
        generate_btn.clicked.connect(self._on_click)
        generate_btn.move(10, 355)
        generate_btn.setMinimumWidth(min_width)

        # Add Quit button
        quit_btn = QPushButton('Quit', self)
        quit_btn.setToolTip('Quit this application')
        quit_btn.clicked.connect(exit)
        quit_btn.move(165, 355)
        quit_btn.setMinimumWidth(min_width)

        # Add Copy button
        copy_btn = QPushButton('Copy', self)
        copy_btn.setToolTip('Copy your secret')
        copy_btn.clicked.connect(self._copy_textbox)
        copy_btn.move(250, 320)
        copy_btn.setMaximumWidth(35)
        copy_btn.setMaximumHeight(20)
        copy_btn.setStyleSheet('font-size: 11px;')

        # Add Help button
        help_btn = QPushButton('Help', self)
        help_btn.setToolTip('Get help about this application')
        help_btn.clicked.connect(self._open_help)
        help_btn.move(240, 80)
        help_btn.setMaximumWidth(35)
        help_btn.setMaximumHeight(20)
        help_btn.setStyleSheet('font-size: 11px;')

        hr1 = QFrame(self)
        hr1.setFrameShape(QFrame.HLine)
        hr1.move(10, 125)
        hr1.setMinimumWidth(280)
        hr1.setStyleSheet("color: #d0d0d0;")

        hr2 = QFrame(self)
        hr2.setFrameShape(QFrame.HLine)
        hr2.move(10, 175)
        hr2.setMinimumWidth(100)
        hr2.setStyleSheet("color: #d0d0d0;")

        # Add secret type radio buttons
        self.words_radio_btn = QRadioButton('words', self)
        self.words_radio_btn.move(10, 110)
        self.words_radio_btn.clicked.connect(self._set_word_defaults)
        self.words_radio_btn.setStyleSheet('max-width: 80px;')

        self.mixed_radio_btn = QRadioButton('mixed', self)
        self.mixed_radio_btn.move(90, 110)
        self.mixed_radio_btn.clicked.connect(self._disabled_unused)
        self.mixed_radio_btn.setStyleSheet('max-width: 80px;')

        self.numbers_radio_btn = QRadioButton('numbers', self)
        self.numbers_radio_btn.move(170, 110)
        self.numbers_radio_btn.clicked.connect(self._disabled_unused)
        self.numbers_radio_btn.setStyleSheet('max-width: 100px;')

        # Add dice roll radio buttons
        self.num_dice4 = QRadioButton('4', self)
        self.num_dice4.move(10, 160)

        self.num_dice5 = QRadioButton('5', self)
        self.num_dice5.move(60, 160)

        self.num_rolls3 = QRadioButton('3', self)
        self.num_rolls3.move(10, 212)

        self.num_rolls4 = QRadioButton('4', self)
        self.num_rolls4.move(60, 212)

        self.num_rolls5 = QRadioButton('5', self)
        self.num_rolls5.move(110, 212)

        self.radio_type_group = QButtonGroup(self)
        self.radio_type_group.addButton(self.words_radio_btn)
        self.radio_type_group.addButton(self.mixed_radio_btn)
        self.radio_type_group.addButton(self.numbers_radio_btn)

        self.radio_dice_group = QButtonGroup(self)
        self.radio_dice_group.addButton(self.num_dice4)
        self.radio_dice_group.addButton(self.num_dice5)

        self.radio_rolls_group = QButtonGroup(self)
        self.radio_rolls_group.addButton(self.num_rolls3)
        self.radio_rolls_group.addButton(self.num_rolls4)
        self.radio_rolls_group.addButton(self.num_rolls5)

        self.setGeometry(100, 100, 300, 400)
        self.setWindowTitle('Password Generator')
        self.setWindowIcon(QIcon('../images/lock_icon_bkgrd.png'))

    def _set_defaults(self):

        self.words_radio_btn.setChecked(True)
        self.num_dice5.setChecked(True)
        self.num_rolls5.setChecked(True)
        self.length_textline.setText('')

    def _run_generate(self):

        logging.info('[{0}]\n{1}'.format(utils.get_timestamp(),
                                         self._get_args()))

        return generate_secret(int(self._get_args()['number_rolls']),
                               int(self._get_args()['number_dice']),
                               int(self._get_args()['how_many']),
                               str(self._get_args()['output_type']),
                               int(self._get_args()['password_length']))

        # def generate_secret(number_rolls: int = 5, number_dice: int = 5,
        #                       how_many: int = 1, output_type: str = 'words',
        #                       password_length: int = 20)

        # output_type=self._get_args()['output_type'],
        # password_length=int(self._get_args()['password_length']),
        # number_dice=int(self._get_args()['number_dice']),
        # number_rolls=int(self._get_args()['number_rolls'])

    def _on_click(self):

        self.textbox.setFontFamily("Courier New")

        return self.textbox.setText(self._run_generate())

    def _get_args(self):

        args = {'password_length': 20, 'how_many': 1}

        # Type
        if self.numbers_radio_btn.isChecked():
            args['output_type'] = self.numbers_radio_btn.text()

        elif self.mixed_radio_btn.isChecked():
            args['output_type'] = self.mixed_radio_btn.text()

        else:
            args['output_type'] = self.words_radio_btn.text()

        # Length
        if self.length_textline.text():
            args['password_length'] = self.length_textline.text()

        # Dice
        if self.num_dice4.isChecked():
            args['number_dice'] = self.num_dice4.text()

        else:
            args['number_dice'] = self.num_dice5.text()

        # Rolls
        if self.num_rolls3.isChecked():
            args['number_rolls'] = self.num_rolls3.text()

        elif self.num_rolls4.isChecked():
            args['number_rolls'] = self.num_rolls4.text()

        else:
            args['number_rolls'] = self.num_rolls5.text()

        return args

    def _disabled_unused(self):

        tmp_text = self.length_textline.text()

        if tmp_text:
            self.length_textline.setText(tmp_text)
        else:
            self.length_textline.setText('20')

        self.radio_dice_group.setExclusive(False)
        self.radio_rolls_group.setExclusive(False)

        self.num_dice4.setChecked(False)
        self.num_dice4.setCheckable(False)
        self.num_dice4.setEnabled(False)

        self.num_dice5.setChecked(False)
        self.num_dice5.setCheckable(False)
        self.num_dice5.setEnabled(False)

        self.num_rolls3.setChecked(False)
        self.num_rolls3.setCheckable(False)
        self.num_rolls3.setEnabled(False)

        self.num_rolls4.setChecked(False)
        self.num_rolls4.setCheckable(False)
        self.num_rolls4.setEnabled(False)

        self.num_rolls5.setChecked(False)
        self.num_rolls5.setCheckable(False)
        self.num_rolls5.setEnabled(False)

        self.radio_dice_group.setExclusive(True)
        self.radio_rolls_group.setExclusive(True)

    def _set_word_defaults(self):

        self.length_textline.setText('')

        self.num_dice4.setCheckable(True)
        self.num_dice4.setEnabled(True)

        self.num_dice5.setCheckable(True)
        self.num_dice5.setEnabled(True)

        self.num_rolls3.setCheckable(True)
        self.num_rolls3.setEnabled(True)

        self.num_rolls4.setCheckable(True)
        self.num_rolls4.setEnabled(True)

        self.num_rolls5.setCheckable(True)
        self.num_rolls5.setEnabled(True)

        self.num_dice5.setChecked(True)
        self.num_rolls5.setChecked(True)

    def _copy_textbox(self):

        self.textbox.selectAll()
        self.textbox.copy()

    def _open_help(self):

        message = QMessageBox(self)

        with open('../assets/help/_main.txt', 'r') as help_text:
            message.setText(help_text.read())

        message.setIcon(QMessageBox.Question)

        with open('../assets/help/_inform.txt', 'r') as help_inform:
            message.setInformativeText(help_inform.read())

        message.setWindowTitle('PyPass3 Help')
        message.setStandardButtons(QMessageBox.Close)
        message.exec_()
예제 #14
0
class lTabOptions(QGroupBox):
    state_change = pyqtSignal()

    def __init__(self, parent, run_data_dir):
        self.block_state_change = False
        self.run_data_dir = run_data_dir
        QGroupBox.__init__(self, "Global Tab Options", parent)
        self.grid_layout = QGridLayout(self)
        title = QLabel('Lovell')
        font = QFont()
        title.setAlignment(Qt.AlignHCenter)
        font.setPointSize(20)
        font.setBold(True)
        title.setFont(font)
        self.setMinimumWidth(275)

        self.grid_layout.addWidget(title, self.rowCount(), 0, 1, 2)
        setPadding(self.grid_layout)
        self.add_group_selector()
        self.add_ID_selector()
        self.add_next_prev_buttons()
        self.add_notify_box()
        self.add_reference_buttons()
        self.add_run_num_buttons()

    def add_notify_box(self):
        notifyFont = QFont()
        notifyFont.setPointSize(8)
        self.grid_layout.addWidget(QLabel("Notifcations:"), self.rowCount(), 0,
                                   1, 2)
        self.notifyBox = QTextEdit("Hello world! :)", self)
        self.notifyBox.setFont(notifyFont)
        self.grid_layout.addWidget(self.notifyBox, self.rowCount(), 0, 1, 2)

    def notify(self, text, textHighlight=None):
        # highlightRange is range in passed text.
        length = len(self.notifyBox.toPlainText())
        self.notifyBox.append(text)
        self.notifyBox.verticalScrollBar().setValue(
            self.notifyBox.verticalScrollBar().maximum())

        if textHighlight != None:
            begin = length + text.find(textHighlight) + 1
            end = begin + len(textHighlight)
            fmt = QTextCharFormat()
            col = QColor(Qt.red)
            col.setAlpha(130)
            fmt.setBackground(col)
            cursor = QTextCursor(self.notifyBox.document())
            cursor.setPosition(begin)
            cursor.setPosition(end, QTextCursor.KeepAnchor)
            cursor.setCharFormat(fmt)

    def add_group_selector(self):
        self.module_group_box = QComboBox(self)
        self.module_group_box.currentIndexChanged.connect(self.state_changed)
        lab = QLabel("Module Group:")
        lab.setAlignment(Qt.AlignRight)
        self.grid_layout.addWidget(lab, self.rowCount(), 0)
        self.grid_layout.addWidget(self.module_group_box,
                                   self.rowCount() - 1, 1)
        lab.hide()
        self.module_group_box.hide()
        self.module_group_box.addItem("R (0)")
        self.module_group_box.addItem("Phi (1)")

    def add_ID_selector(self):
        self.module_ID_box = QComboBox(self)
        self.module_ID_box.currentIndexChanged.connect(self.state_changed)
        lab = QLabel("Sensor ID:")
        lab.setAlignment(Qt.AlignRight)
        self.grid_layout.addWidget(lab, self.rowCount(), 0)
        self.grid_layout.addWidget(self.module_ID_box, self.rowCount() - 1, 1)
        for i in range(0, 42):
            self.module_ID_box.addItem(str(i))
        for i in range(64, 106):
            self.module_ID_box.addItem(str(i))

    def add_next_prev_buttons(self):
        self.next_button = QPushButton("Next")
        self.grid_layout.addWidget(self.next_button, self.rowCount(), 1)
        self.prev_button = QPushButton("Prev")
        self.grid_layout.addWidget(self.prev_button, self.rowCount() - 1, 0)
        self.next_button.clicked.connect(self.next_clicked)
        self.prev_button.clicked.connect(self.prev_clicked)

        self.next_four_button = QPushButton("Next Four")
        self.grid_layout.addWidget(self.next_four_button, self.rowCount(), 1)
        self.prev_four_button = QPushButton("Prev Four")
        self.grid_layout.addWidget(self.prev_four_button,
                                   self.rowCount() - 1, 0)
        self.next_four_button.clicked.connect(self.next_four_clicked)
        self.prev_four_button.clicked.connect(self.prev_four_clicked)

    def add_run_num_buttons(self):
        self.add_bar()
        self.run_num_box = QComboBox(self)
        self.run_num_box.currentIndexChanged.connect(self.state_changed)
        self.grid_layout.addWidget(QLabel("Run number:"), self.rowCount(), 0,
                                   1, 2)
        self.grid_layout.addWidget(self.run_num_box, self.rowCount(), 0, 1, 2)

        # Reference
        self.run_numRef_box = QComboBox(self)
        self.run_numRef_box.currentIndexChanged.connect(self.state_changed)
        self.grid_layout.addWidget(QLabel("Reference number:"),
                                   self.rowCount(), 0, 1, 2)
        self.grid_layout.addWidget(self.run_numRef_box, self.rowCount(), 0, 1,
                                   2)

        self.run_numRef_box.addItem('Auto')
        for run in lInterfaces.run_list(self.run_data_dir):
            self.run_num_box.addItem(str(run))
            self.run_numRef_box.addItem(str(run))

    def add_bar(self):
        bar = QLabel('_______________________________')
        bar.setAlignment(Qt.AlignHCenter)
        bar.setAlignment(Qt.AlignVCenter)
        self.grid_layout.addWidget(bar, self.rowCount(), 0, 1, 2)

    def add_reference_buttons(self):
        self.add_bar()
        self.showing_ref_box = QCheckBox("Display References")
        self.showing_ref_box.stateChanged.connect(self.reference_button_fading)
        self.showing_ref_box.setChecked(True)
        self.overlay_ref_box = QRadioButton("Overlay", self)
        self.overlay_ref_box.setChecked(True)
        self.overlay_refDiff_box = QRadioButton("Data - Ref", self)
        self.overlay_refRatio_box = QRadioButton("Data/Ref", self)

        self.grid_layout.addWidget(self.showing_ref_box, self.rowCount(), 0, 1,
                                   2)
        self.grid_layout.addWidget(self.overlay_ref_box, self.rowCount(), 0, 1,
                                   2)
        self.grid_layout.addWidget(self.overlay_refDiff_box, self.rowCount(),
                                   0, 1, 2)
        self.grid_layout.addWidget(self.overlay_refRatio_box, self.rowCount(),
                                   0, 1, 2)

        # Slots.
        self.showing_ref_box.clicked.connect(self.state_changed)
        self.overlay_ref_box.clicked.connect(self.state_changed)
        self.overlay_refDiff_box.clicked.connect(self.state_changed)
        self.overlay_refRatio_box.clicked.connect(self.state_changed)
        self.reference_button_fading()

    def rowCount(self):
        return self.grid_layout.rowCount()

    def state_changed(self):
        if self.block_state_change == False:
            self.state_change.emit()

    def state(self):
        g = self.module_group_box.currentIndex()
        moduleID = int(self.module_ID_box.currentText())
        state = lTabOpsState(moduleID, self.showing_ref_box.isChecked(),
                             self.overlay_ref_box.isChecked(),
                             self.overlay_refDiff_box.isChecked(),
                             self.overlay_refRatio_box.isChecked(),
                             self.run_num_box.currentText(),
                             self.run_numRef_box.currentText(),
                             self.run_data_dir)
        return state

    def next_four_clicked(self):
        self.block_state_change = True
        for i in range(4):
            self.next_clicked()

        self.block_state_change = False
        self.state_changed()

    def prev_four_clicked(self):
        self.block_state_change = True
        for i in range(4):
            self.prev_clicked()

        self.block_state_change = False
        self.state_changed()

    def next_clicked(self):
        currentGroup = self.module_group_box.currentIndex()
        currentModule = self.module_ID_box.currentIndex()

        # Check if the last one.
        if currentModule != self.module_ID_box.count() - 1:
            self.module_ID_box.setCurrentIndex(currentModule + 1)
        else:
            if currentGroup != self.module_group_box.count() - 1:
                self.module_group_box.setCurrentIndex(currentGroup + 1)
            else:
                self.module_group_box.setCurrentIndex(0)
            self.module_ID_box.setCurrentIndex(0)

    def prev_clicked(self):
        currentGroup = self.module_group_box.currentIndex()
        currentModule = self.module_ID_box.currentIndex()

        # Check if the first one.
        if currentModule != 0:
            self.module_ID_box.setCurrentIndex(currentModule - 1)
        else:
            if currentGroup != 0:
                self.module_group_box.setCurrentIndex(currentGroup - 1)
            else:
                self.module_group_box.setCurrentIndex(
                    self.module_group_box.count() - 1)
            self.module_ID_box.setCurrentIndex(self.module_ID_box.count() - 1)

    def reference_button_fading(self):
        if self.showing_ref_box.isChecked():
            self.overlay_ref_box.setEnabled(True)
            self.overlay_refDiff_box.setEnabled(True)
            self.overlay_refRatio_box.setEnabled(True)

        else:
            self.overlay_ref_box.setEnabled(False)
            self.overlay_refDiff_box.setEnabled(False)
            self.overlay_refRatio_box.setEnabled(False)
예제 #15
0
class Preferences(QDialog):
    def __init__(self, parent=None, test = False):
        super(Preferences, self).__init__(parent)
        self.parent = parent
        self.home = os.getenv('HOME')

        saveLabel = QLabel('<html><b>' + self.tr('Save files') + '</b></html>')
        exist_Label = QLabel(self.tr('Existing files:'))
        self.exst_add_prefixRadioButton = QRadioButton(
                                                     self.tr("Add '~' prefix"))
        self.exst_overwriteRadioButton = QRadioButton(self.tr('Overwrite'))
        exist_layout = pyqttools.add_to_layout(QHBoxLayout(),
                                               self.exst_add_prefixRadioButton,
                                               self.exst_overwriteRadioButton)

        defaultLabel = QLabel(self.tr('Default output destination:'))
        self.defaultLineEdit = QLineEdit()
        self.defaultToolButton = QToolButton()
        self.defaultToolButton.setText('...')
        deafult_fol_layout = pyqttools.add_to_layout(QHBoxLayout(),
                                                     self.defaultLineEdit,
                                                     self.defaultToolButton)
        name_Label = QLabel('<html><b>' + self.tr('Name files') +'</b></html>')
        prefixLabel = QLabel(self.tr('Prefix:'))
        suffixLabel = QLabel(self.tr('Suffix:'))
        self.prefixLineEdit = QLineEdit()
        self.suffixLineEdit = QLineEdit()
        grid = pyqttools.add_to_grid(QGridLayout(),
                                     [prefixLabel, self.prefixLineEdit],
                                     [suffixLabel, self.suffixLineEdit])
        prefix_layout = pyqttools.add_to_layout(QHBoxLayout(), grid, None)

        tabwidget1_layout = pyqttools.add_to_layout(QVBoxLayout(), saveLabel,
               QSpacerItem(14, 13), exist_Label, exist_layout,
               QSpacerItem(14, 13), defaultLabel, deafult_fol_layout,
               QSpacerItem(13, 13), name_Label, QSpacerItem(14, 13),
               prefix_layout)

        ffmpegLabel = QLabel('<html><b>' + self.tr('FFmpeg') +'</b></html>')
        default_commandLabel = QLabel(self.tr('Default command:'))
        self.commandLineEdit = QLineEdit()
        useLabel = QLabel(self.tr('Use:'))
        self.ffmpegRadioButton = QRadioButton(self.tr('FFmpeg'))
        self.avconvRadioButton = QRadioButton(self.tr('avconv'))

        hlayout = pyqttools.add_to_layout(QHBoxLayout(),
                                          self.ffmpegRadioButton,
                                          self.avconvRadioButton)

        tabwidget2_layout = pyqttools.add_to_layout(QVBoxLayout(), ffmpegLabel,
                QSpacerItem(14, 13), useLabel, hlayout, QSpacerItem(14, 13),
                default_commandLabel, self.commandLineEdit, None)

        widget1 = QWidget()
        widget1.setLayout(tabwidget1_layout)
        widget2 = QWidget()
        widget2.setLayout(tabwidget2_layout)
        self.TabWidget = QTabWidget()
        self.TabWidget.addTab(widget1, self.tr('General'))
        self.TabWidget.addTab(widget2, self.tr('Audio/Video'))

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                          QDialogButtonBox.Cancel)

        final_layout = pyqttools.add_to_layout(QVBoxLayout(), self.TabWidget,
                                               None, self.buttonBox)
        self.setLayout(final_layout)

        self.defaultToolButton.clicked.connect(self.open_dir)
        self.buttonBox.accepted.connect(self.save_settings)
        self.buttonBox.rejected.connect(self.reject)

        settings = QSettings()
        overwrite_existing = settings.value('overwrite_existing').toBool()
        default_output = settings.value('default_output').toString()
        prefix = settings.value('prefix').toString()
        suffix = settings.value('suffix').toString()
        avconv_prefered = settings.value('avconv_prefered').toBool()
        default_command = settings.value('default_command').toString()

        if overwrite_existing:
            self.exst_overwriteRadioButton.setChecked(True)
        else:
            self.exst_add_prefixRadioButton.setChecked(True)
        if default_output:
            self.defaultLineEdit.setText(default_output)
        if prefix:
            self.prefixLineEdit.setText(prefix)
        if suffix:
            self.suffixLineEdit.setText(suffix)
        if avconv_prefered:
            self.avconvRadioButton.setChecked(True)
        else:
            self.ffmpegRadioButton.setChecked(True)
        if default_command:
            self.commandLineEdit.setText(default_command)
        else:
            self.commandLineEdit.setText('-ab 320k -ar 48000 -ac 2')

        if not test and not self.parent.ffmpeg:
            self.avconvRadioButton.setChecked(True)
            self.ffmpegRadioButton.setEnabled(False)
        if not test and not self.parent.avconv:
            self.ffmpegRadioButton.setChecked(True)
            self.avconvRadioButton.setEnabled(False)

        self.resize(400, 390)
        self.setWindowTitle(self.tr('Preferences'))

    def open_dir(self):
        """Get a directory name using a standard Qt dialog and update
        self.defaultLineEdit with dir's name."""
        if self.defaultLineEdit.isEnabled():
            _dir = QFileDialog.getExistingDirectory(self, 'FF Multi Converter '
                '- ' + self.tr('Choose default output destination'), self.home)
            #_dir = unicode(_dir)
            if _dir:
                self.defaultLineEdit.setText(_dir)

    def save_settings(self):
        """Set settings values, extracting the appropriate information from
        the graphical widgets."""
        overwrite_existing = self.exst_overwriteRadioButton.isChecked()
        default_output = unicode(self.defaultLineEdit.text())
        prefix = unicode(self.prefixLineEdit.text())
        suffix = unicode(self.suffixLineEdit.text())
        avconv_prefered = self.avconvRadioButton.isChecked()
        default_command = unicode(self.commandLineEdit.text())

        settings = QSettings()
        settings.setValue('overwrite_existing', overwrite_existing)
        settings.setValue('default_output', default_output)
        settings.setValue('prefix', prefix)
        settings.setValue('suffix', suffix)
        settings.setValue('avconv_prefered', avconv_prefered)
        settings.setValue('default_command', default_command)

        self.accept()
예제 #16
0
class Preferences(QDialog):
    def __init__(self, parent=None, test = False):
        super(Preferences, self).__init__(parent)
        self.parent = parent
        self.test = test

        self.default_videocodecs = [
                'flv', 'h263', 'libvpx', 'libx264', 'libxvid', 'mpeg2video',
                'mpeg4', 'msmpeg4', 'wmv2'
                ]

        self.default_audiocodecs = [
                'aac', 'ac3', 'copy', 'libfaac', 'libmp3lame', 'libvo_aacenc',
                'libvorbis', 'mp2', 'wmav2'
                ]

        saveQL = QLabel('<html><b>' + self.tr('Save files') + '</b></html>')
        existQL = QLabel(self.tr('Existing files:'))
        self.exst_prefixQRB = QRadioButton(self.tr("Add '~' prefix"))
        self.exst_overwriteQRB = QRadioButton(self.tr('Overwrite'))
        exist_layout = utils.add_to_layout(
                'h', self.exst_prefixQRB, self.exst_overwriteQRB)

        defaultQL = QLabel(self.tr('Default output destination:'))
        self.defaultQLE = QLineEdit()
        self.defaultQTB = QToolButton()
        self.defaultQTB.setText('...')
        deafult_fol_layout = utils.add_to_layout(
                'h', self.defaultQLE, self.defaultQTB)
        nameQL = QLabel('<html><b>' + self.tr('Name files') +'</b></html>')
        prefixQL = QLabel(self.tr('Prefix:'))
        suffixQL = QLabel(self.tr('Suffix:'))
        self.prefixQLE = QLineEdit()
        self.suffixQLE = QLineEdit()
        grid = utils.add_to_grid(
                [prefixQL, self.prefixQLE], [suffixQL, self.suffixQLE])
        prefix_layout = utils.add_to_layout('h', grid, None)

        tabwidget1_layout = utils.add_to_layout(
                'v', saveQL,
                QSpacerItem(14, 13), existQL, exist_layout,
                QSpacerItem(14, 13), defaultQL, deafult_fol_layout,
                QSpacerItem(13, 13), nameQL, QSpacerItem(14, 13),
                prefix_layout, None
                )

        ffmpegQL = QLabel('<html><b>' + self.tr('FFmpeg') +'</b></html>')
        default_cmdQL = QLabel(self.tr('Default command:'))
        self.cmdQLE = QLineEdit()
        useQL = QLabel(self.tr('Use:'))
        self.ffmpegQRB = QRadioButton(self.tr('FFmpeg'))
        self.avconvQRB = QRadioButton(self.tr('avconv'))

        hlayout = utils.add_to_layout('h', self.ffmpegQRB, self.avconvQRB)

        vidcodecsQL = QLabel(
                '<html><b>' + self.tr('Video codecs') +'</b></html>')
        self.vidcodecsQPTE = QPlainTextEdit()
        audcodecsQL = QLabel(
                '<html><b>' + self.tr('Audio codecs') +'</b></html>')
        self.audcodecsQPTE = QPlainTextEdit()
        extraformatsQL = QLabel(
                '<html><b>' + self.tr('Extra formats') +'</b></html>')
        self.extraformatsQPTE = QPlainTextEdit()

        gridlayout = utils.add_to_grid(
                [vidcodecsQL, audcodecsQL, extraformatsQL],
                [self.vidcodecsQPTE, self.audcodecsQPTE, self.extraformatsQPTE])

        defvidcodecsQPB = QPushButton(self.tr("Default video codecs"))
        defaudcodecsQPB = QPushButton(self.tr("Default audio codecs"))

        hlayout2 = utils.add_to_layout(
                'h', None, defvidcodecsQPB, defaudcodecsQPB)

        tabwidget2_layout = utils.add_to_layout(
                'v', ffmpegQL, QSpacerItem(14, 13), useQL,
                hlayout, QSpacerItem(14, 13), default_cmdQL,
                self.cmdQLE, QSpacerItem(20, 20), gridlayout, hlayout2,
                None
                )

        widget1 = QWidget()
        widget1.setLayout(tabwidget1_layout)
        widget2 = QWidget()
        widget2.setLayout(tabwidget2_layout)
        tabWidget = QTabWidget()
        tabWidget.addTab(widget1, self.tr('General'))
        tabWidget.addTab(widget2, self.tr('Audio/Video'))

        buttonBox = QDialogButtonBox(
                QDialogButtonBox.Ok|QDialogButtonBox.Cancel)

        final_layout = utils.add_to_layout('v', tabWidget, None, buttonBox)
        self.setLayout(final_layout)

        self.defaultQTB.clicked.connect(self.open_dir)
        buttonBox.accepted.connect(self.save_settings)
        buttonBox.rejected.connect(self.reject)
        defvidcodecsQPB.clicked.connect(self.set_default_videocodecs)
        defaudcodecsQPB.clicked.connect(self.set_default_audiocodecs)

        self.resize(400, 480)
        self.setWindowTitle(self.tr('Preferences'))

        QTimer.singleShot(0, self.load_settings)

    def load_settings(self):
        """Load settings and update graphical widgets with loaded values."""
        settings = QSettings()
        overwrite_existing = utils.str_to_bool(
                settings.value('overwrite_existing'))
        default_output = settings.value('default_output')
        prefix = settings.value('prefix')
        suffix = settings.value('suffix')
        avconv_prefered = utils.str_to_bool(settings.value('avconv_prefered'))
        default_command = settings.value('default_command')
        videocodecs = settings.value('videocodecs')
        audiocodecs = settings.value('audiocodecs')
        extraformats = settings.value('extraformats')

        # QSettings.value() returns str() in python3, not QVariant() as in p2
        if overwrite_existing:
            self.exst_overwriteQRB.setChecked(True)
        else:
            self.exst_prefixQRB.setChecked(True)
        if default_output:
            self.defaultQLE.setText(default_output)
        if prefix:
            self.prefixQLE.setText(prefix)
        if suffix:
            self.suffixQLE.setText(suffix)
        if avconv_prefered:
            self.avconvQRB.setChecked(True)
        else:
            self.ffmpegQRB.setChecked(True)
        if default_command:
            self.cmdQLE.setText(default_command)
        else:
            self.cmdQLE.setText(config.default_ffmpeg_cmd)

        if not self.test and not self.parent.ffmpeg:
            self.avconvQRB.setChecked(True)
            self.ffmpegQRB.setEnabled(False)
        if not self.test and not self.parent.avconv:
            self.ffmpegQRB.setChecked(True)
            self.avconvQRB.setEnabled(False)

        if not videocodecs:
            self.set_default_videocodecs()
        else:
            self.vidcodecsQPTE.setPlainText(videocodecs)
        if not audiocodecs:
            self.set_default_audiocodecs
        else:
            self.audcodecsQPTE.setPlainText(audiocodecs)
        self.extraformatsQPTE.setPlainText(extraformats)

    def set_default_videocodecs(self):
        self.vidcodecsQPTE.setPlainText("\n".join(self.default_videocodecs))

    def set_default_audiocodecs(self):
        self.audcodecsQPTE.setPlainText("\n".join(self.default_audiocodecs))

    def open_dir(self):
        """Get a directory name using a standard Qt dialog and update
        self.defaultQLE with dir's name."""
        if self.defaultQLE.isEnabled():
            _dir = QFileDialog.getExistingDirectory(
                    self, 'FF Multi Converter - ' +
                    self.tr('Choose default output destination'), config.home
                    )
            if _dir:
                self.defaultQLE.setText(_dir)

    def save_settings(self):
        """Set settings values, extracting the appropriate information from
        the graphical widgets."""
        # remove empty codecs
        videocodecs = []
        audiocodecs = []
        extraformats = []

        for i in self.vidcodecsQPTE.toPlainText().split("\n"):
            i = i.strip()
            if len(i.split()) == 1: # single word
                videocodecs.append(i)

        for i in self.audcodecsQPTE.toPlainText().split("\n"):
            i = i.strip()
            if len(i.split()) == 1:
                audiocodecs.append(i)

        for i in self.extraformatsQPTE.toPlainText().split("\n"):
            i = i.strip()
            if len(i.split()) == 1:
                extraformats.append(i)

        videocodecs = "\n".join(sorted(videocodecs))
        audiocodecs = "\n".join(sorted(audiocodecs))
        extraformats = "\n".join(sorted(extraformats))

        settings = QSettings()
        settings.setValue(
                'overwrite_existing', self.exst_overwriteQRB.isChecked())
        settings.setValue(
                'default_output', self.defaultQLE.text())
        settings.setValue(
                'prefix', self.prefixQLE.text())
        settings.setValue(
                'suffix', self.suffixQLE.text())
        settings.setValue(
                'avconv_prefered', self.avconvQRB.isChecked())
        settings.setValue(
                'default_command', self.cmdQLE.text())
        settings.setValue(
                'videocodecs', videocodecs)
        settings.setValue(
                'audiocodecs', audiocodecs)
        settings.setValue(
                'extraformats', extraformats)

        self.accept()
class Preferences(QDialog):
    def __init__(self, parent=None, test=False):
        super(Preferences, self).__init__(parent)
        self.parent = parent
        self.home = os.getenv("HOME")

        saveLabel = QLabel("<html><b>" + self.tr("Save files") + "</b></html>")
        exist_Label = QLabel(self.tr("Existing files:"))
        self.exst_add_prefixRadioButton = QRadioButton(self.tr("Add '~' prefix"))
        self.exst_overwriteRadioButton = QRadioButton(self.tr("Overwrite"))
        exist_layout = pyqttools.add_to_layout(
            QHBoxLayout(), self.exst_add_prefixRadioButton, self.exst_overwriteRadioButton
        )

        defaultLabel = QLabel(self.tr("Default output destination:"))
        self.defaultLineEdit = QLineEdit()
        self.defaultToolButton = QToolButton()
        self.defaultToolButton.setText("...")
        deafult_fol_layout = pyqttools.add_to_layout(QHBoxLayout(), self.defaultLineEdit, self.defaultToolButton)
        name_Label = QLabel("<html><b>" + self.tr("Name files") + "</b></html>")
        prefixLabel = QLabel(self.tr("Prefix:"))
        suffixLabel = QLabel(self.tr("Suffix:"))
        self.prefixLineEdit = QLineEdit()
        self.suffixLineEdit = QLineEdit()
        grid = pyqttools.add_to_grid(
            QGridLayout(), [prefixLabel, self.prefixLineEdit], [suffixLabel, self.suffixLineEdit]
        )
        prefix_layout = pyqttools.add_to_layout(QHBoxLayout(), grid, None)

        tabwidget1_layout = pyqttools.add_to_layout(
            QVBoxLayout(),
            saveLabel,
            QSpacerItem(14, 13),
            exist_Label,
            exist_layout,
            QSpacerItem(14, 13),
            defaultLabel,
            deafult_fol_layout,
            QSpacerItem(13, 13),
            name_Label,
            QSpacerItem(14, 13),
            prefix_layout,
        )

        ffmpegLabel = QLabel("<html><b>" + self.tr("FFmpeg") + "</b></html>")
        default_commandLabel = QLabel(self.tr("Default command:"))
        self.commandLineEdit = QLineEdit()
        useLabel = QLabel(self.tr("Use:"))
        self.ffmpegRadioButton = QRadioButton(self.tr("FFmpeg"))
        self.avconvRadioButton = QRadioButton(self.tr("avconv"))

        hlayout = pyqttools.add_to_layout(QHBoxLayout(), self.ffmpegRadioButton, self.avconvRadioButton)

        tabwidget2_layout = pyqttools.add_to_layout(
            QVBoxLayout(),
            ffmpegLabel,
            QSpacerItem(14, 13),
            useLabel,
            hlayout,
            QSpacerItem(14, 13),
            default_commandLabel,
            self.commandLineEdit,
            None,
        )

        widget1 = QWidget()
        widget1.setLayout(tabwidget1_layout)
        widget2 = QWidget()
        widget2.setLayout(tabwidget2_layout)
        self.TabWidget = QTabWidget()
        self.TabWidget.addTab(widget1, self.tr("General"))
        self.TabWidget.addTab(widget2, self.tr("Audio/Video"))

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)

        final_layout = pyqttools.add_to_layout(QVBoxLayout(), self.TabWidget, None, self.buttonBox)
        self.setLayout(final_layout)

        self.defaultToolButton.clicked.connect(self.open_dir)
        self.buttonBox.accepted.connect(self.save_settings)
        self.buttonBox.rejected.connect(self.reject)

        settings = QSettings()
        overwrite_existing = settings.value("overwrite_existing").toBool()
        default_output = settings.value("default_output").toString()
        prefix = settings.value("prefix").toString()
        suffix = settings.value("suffix").toString()
        avconv_prefered = settings.value("avconv_prefered").toBool()
        default_command = settings.value("default_command").toString()

        if overwrite_existing:
            self.exst_overwriteRadioButton.setChecked(True)
        else:
            self.exst_add_prefixRadioButton.setChecked(True)
        if default_output:
            self.defaultLineEdit.setText(default_output)
        if prefix:
            self.prefixLineEdit.setText(prefix)
        if suffix:
            self.suffixLineEdit.setText(suffix)
        if avconv_prefered:
            self.avconvRadioButton.setChecked(True)
        else:
            self.ffmpegRadioButton.setChecked(True)
        if default_command:
            self.commandLineEdit.setText(default_command)
        else:
            self.commandLineEdit.setText("-ab 320k -ar 48000 -ac 2")

        if not test and not self.parent.ffmpeg:
            self.avconvRadioButton.setChecked(True)
            self.ffmpegRadioButton.setEnabled(False)
        if not test and not self.parent.avconv:
            self.ffmpegRadioButton.setChecked(True)
            self.avconvRadioButton.setEnabled(False)

        self.resize(400, 390)
        self.setWindowTitle(self.tr("Preferences"))

    def open_dir(self):
        """Get a directory name using a standard Qt dialog and update
        self.defaultLineEdit with dir's name."""
        if self.defaultLineEdit.isEnabled():
            _dir = QFileDialog.getExistingDirectory(
                self, "FF Multi Converter " "- " + self.tr("Choose default output destination"), self.home
            )
            # _dir = unicode(_dir)
            if _dir:
                self.defaultLineEdit.setText(_dir)

    def save_settings(self):
        """Set settings values, extracting the appropriate information from
        the graphical widgets."""
        overwrite_existing = self.exst_overwriteRadioButton.isChecked()
        default_output = unicode(self.defaultLineEdit.text())
        prefix = unicode(self.prefixLineEdit.text())
        suffix = unicode(self.suffixLineEdit.text())
        avconv_prefered = self.avconvRadioButton.isChecked()
        default_command = unicode(self.commandLineEdit.text())

        settings = QSettings()
        settings.setValue("overwrite_existing", overwrite_existing)
        settings.setValue("default_output", default_output)
        settings.setValue("prefix", prefix)
        settings.setValue("suffix", suffix)
        settings.setValue("avconv_prefered", avconv_prefered)
        settings.setValue("default_command", default_command)

        self.accept()
예제 #18
0
    def initSettingTab(self):
        # ##Setting Tab###
        setting_tab = QWidget()
        setting_tab_layout = QVBoxLayout()
        self.tabWidget.addTab(setting_tab, "Settings")

        # Task Box
        task_box = QGroupBox()
        task_box.setTitle(QString("Task properties"))
        task_layout = QGridLayout()

        # Name
        name = QLabel("Name:")
        name_value = QLineEdit() 
        name_value.setText(self.task.hittypename)
        name_value.setEnabled(False)
        clickable(name_value).connect(self.enable)
        task_layout.addWidget(name, 0, 1)
        task_layout.addWidget(name_value, 0, 2, 1, 3)

        # Description
        description = QLabel("Description:")
        description_value = QLineEdit() 
        description_value.setText(self.task.description)
        description_value.setEnabled(False)
        clickable(description_value).connect(self.enable)
        task_layout.addWidget(description, 1, 1)
        task_layout.addWidget(description_value, 1, 2, 1, 3)

        # Keywords
        keywords = QLabel("Keywords:")
        keywords_value = QLineEdit()
        keywords_value.setText(','.join(self.task.keywords))
        keywords_value.setEnabled(False)
        clickable(keywords_value).connect(self.enable)
        task_layout.addWidget(keywords, 2, 1)
        task_layout.addWidget(keywords_value, 2, 2, 1, 3)

        # Qualification
        qualification = QLabel("Qualification [%]:")
        qualification_value = QSpinBox()
        qualification_value.setSuffix('%')
        qualification_value.setValue(int(self.task.qualification))
        qualification_value.setEnabled(False)
        clickable(qualification_value).connect(self.enable)
        task_layout.addWidget(qualification, 3, 1)
        task_layout.addWidget(qualification_value, 3, 4)

        # Assignments
        assignments = QLabel("Assignments:")
        assignments_value = QSpinBox()
        assignments_value.setSuffix('')
        assignments_value.setValue(int(self.task.assignments))
        assignments_value.setEnabled(False)
        clickable(assignments_value).connect(self.enable)
        task_layout.addWidget(assignments, 4, 1)
        task_layout.addWidget(assignments_value, 4, 4)

        # Duration
        duration = QLabel("Duration [min]:") 
        duration_value = QSpinBox()
        duration_value.setSuffix('min')
        duration_value.setValue(int(self.task.duration))
        duration_value.setEnabled(False)
        clickable(duration_value).connect(self.enable)
        task_layout.addWidget(duration, 5, 1)
        task_layout.addWidget(duration_value, 5, 4)

        # Reward
        reward = QLabel("Reward [0.01$]:")
        reward_value = QDoubleSpinBox()
        reward_value.setRange(0.01, 0.5)
        reward_value.setSingleStep(0.01)
        reward_value.setSuffix('$')
        reward_value.setValue(self.task.reward)
        reward_value.setEnabled(False)
        clickable(reward_value).connect(self.enable)
        task_layout.addWidget(reward, 6, 1)
        task_layout.addWidget(reward_value, 6, 4)

        # Lifetime
        lifetime = QLabel("Lifetime [d]:")
        lifetime_value = QSpinBox()
        lifetime_value.setSuffix('d')
        lifetime_value.setValue(self.task.lifetime)
        lifetime_value.setEnabled(False)
        clickable(lifetime_value).connect(self.enable)
        task_layout.addWidget(lifetime, 7, 1)
        task_layout.addWidget(lifetime_value, 7, 4)

        # sandbox
        sandbox = QCheckBox("Sandbox")
        sandbox.setChecked(self.task.sandbox)
        task_layout.addWidget(sandbox, 8, 1)
        task_box.setLayout(task_layout)
        task_layout.setColumnMinimumWidth(1, 120)

        # Image Storage Box
        storage_box = QGroupBox()
        storage_box.setTitle(QString("Image Storage"))
        storage_layout = QGridLayout()

        # Host URL
        host_url = QLabel("Host-URL:")
        host_url_value = QLineEdit()
        host_url_value.setText(self.task.host_url)
        host_url_value.setEnabled(False)
        clickable(host_url_value).connect(self.enable)

        # Dropbox Path
        dropbox_path = QLabel("Dropbox-Path:")
        dropbox_path_value = QLineEdit()
        dropbox_path_value.setText(self.task.dropbox_path)
        dropbox_path_value.setEnabled(False)
        clickable(dropbox_path_value).connect(self.enable)

        # Dropbox or S3
        usingS3 = QRadioButton("S3")
        usingS3.setChecked(self.task.usingS3)
        usingS3.setEnabled(False)
        usingDropbox = QRadioButton("Dropbox")
        usingDropbox.setChecked(self.task.usingDropbox)

        storage_layout.addWidget(host_url, 0, 1)
        storage_layout.addWidget(host_url_value, 0, 2, 1, 3)
        storage_layout.addWidget(dropbox_path, 1, 1)
        storage_layout.addWidget(dropbox_path_value, 1, 2, 1, 3)

        # Add Layouts
        save_button = QPushButton("Save Settings")
        setting_tab_layout.addWidget(task_box)
        setting_tab_layout.addWidget(storage_box)
        setting_tab.setLayout(setting_tab_layout)
        save_button.clicked.connect(self.SaveSettings)

        storage_layout.addWidget(usingS3, 2, 1)
        storage_layout.addWidget(usingDropbox, 3, 1)
        storage_layout.addWidget(save_button, 3, 4)

        # storage_layout.addStretch(1)
        storage_box.setLayout(storage_layout)
예제 #19
0
class FindOptions(QWidget):
    """
    Find widget with options
    """
    def __init__(self, parent, search_text, search_text_regexp, search_path,
                 include, include_regexp, exclude, exclude_regexp,
                 supported_encodings):
        QWidget.__init__(self, parent)

        if search_path is None:
            search_path = os.getcwdu()

        if not isinstance(search_text, (list, tuple)):
            search_text = [search_text]
        if not isinstance(search_path, (list, tuple)):
            search_path = [search_path]
        if not isinstance(include, (list, tuple)):
            include = [include]
        if not isinstance(exclude, (list, tuple)):
            exclude = [exclude]

        self.supported_encodings = supported_encodings

        # Layout 1
        hlayout1 = QHBoxLayout()
        self.search_text = PatternComboBox(
            self, search_text, translate('FindInFiles', "Search pattern"))
        search_label = QLabel(translate('FindInFiles', "Search text:"))
        search_label.setBuddy(self.search_text)
        self.edit_regexp = create_toolbutton(self,
                                             get_icon("advanced.png"),
                                             tip=translate(
                                                 'FindInFiles',
                                                 "Regular expression"))
        self.edit_regexp.setCheckable(True)
        self.edit_regexp.setChecked(search_text_regexp)
        self.ok_button = create_toolbutton(
            self,
            text=translate('FindInFiles', "Search"),
            triggered=lambda: self.emit(SIGNAL('find()')),
            icon=get_std_icon("DialogApplyButton"),
            tip=translate('FindInFiles', "Start search"))
        self.connect(self.ok_button, SIGNAL('clicked()'), self.update_combos)
        self.stop_button = create_toolbutton(
            self,
            text=translate('FindInFiles', "Stop"),
            triggered=lambda: self.emit(SIGNAL('stop()')),
            icon=get_icon("terminate.png"),
            tip=translate('FindInFiles', "Stop search"))
        self.stop_button.setEnabled(False)
        for widget in [
                search_label, self.search_text, self.edit_regexp,
                self.ok_button, self.stop_button
        ]:
            hlayout1.addWidget(widget)

        # Layout 2
        hlayout2 = QHBoxLayout()
        self.include_pattern = PatternComboBox(
            self, include,
            translate('FindInFiles', "Included filenames pattern"))
        self.include_regexp = create_toolbutton(self,
                                                get_icon("advanced.png"),
                                                tip=translate(
                                                    'FindInFiles',
                                                    "Regular expression"))
        self.include_regexp.setCheckable(True)
        self.include_regexp.setChecked(include_regexp)
        include_label = QLabel(translate('FindInFiles', "Include:"))
        include_label.setBuddy(self.include_pattern)
        self.exclude_pattern = PatternComboBox(
            self, exclude,
            translate('FindInFiles', "Excluded filenames pattern"))
        self.exclude_regexp = create_toolbutton(self,
                                                get_icon("advanced.png"),
                                                tip=translate(
                                                    'FindInFiles',
                                                    "Regular expression"))
        self.exclude_regexp.setCheckable(True)
        self.exclude_regexp.setChecked(exclude_regexp)
        exclude_label = QLabel(translate('FindInFiles', "Exclude:"))
        exclude_label.setBuddy(self.exclude_pattern)
        for widget in [
                include_label, self.include_pattern, self.include_regexp,
                exclude_label, self.exclude_pattern, self.exclude_regexp
        ]:
            hlayout2.addWidget(widget)

        # Layout 3
        hlayout3 = QHBoxLayout()
        searchin_label = QLabel(translate('FindInFiles', "Search in:"))
        self.python_path = QRadioButton(translate('FindInFiles', "PYTHONPATH"),
                                        self)
        self.python_path.setToolTip(
            translate(
                'FindInFiles',
                "Search in all directories listed in sys.path which"
                " are outside the Python installation directory"))
        self.hg_manifest = QRadioButton(
            translate('FindInFiles', "Hg repository"), self)
        self.detect_hg_repository()
        self.hg_manifest.setToolTip(
            translate('FindInFiles',
                      "Search in current directory hg repository"))
        searchin_label.setBuddy(self.hg_manifest)
        self.custom_dir = QRadioButton(translate('FindInFiles', "Directory:"),
                                       self)
        self.custom_dir.setChecked(True)
        self.dir_combo = PathComboBox(self)
        self.dir_combo.addItems(search_path)
        self.dir_combo.setToolTip(
            translate('FindInFiles', "Search recursively in this directory"))
        self.connect(self.dir_combo, SIGNAL("open_dir(QString)"),
                     self.set_directory)
        self.connect(self.python_path, SIGNAL('toggled(bool)'),
                     self.dir_combo.setDisabled)
        self.connect(self.hg_manifest, SIGNAL('toggled(bool)'),
                     self.dir_combo.setDisabled)
        browse = create_toolbutton(self,
                                   get_std_icon('DirOpenIcon'),
                                   tip=translate('FindInFiles',
                                                 'Browse a search directory'),
                                   triggered=self.select_directory)
        for widget in [
                searchin_label, self.python_path, self.hg_manifest,
                self.custom_dir, self.dir_combo, browse
        ]:
            hlayout3.addWidget(widget)

        vlayout = QVBoxLayout()
        vlayout.addLayout(hlayout1)
        vlayout.addLayout(hlayout2)
        vlayout.addLayout(hlayout3)
        self.setLayout(vlayout)

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

    def update_combos(self):
        self.search_text.lineEdit().emit(SIGNAL('returnPressed()'))
        self.include_pattern.lineEdit().emit(SIGNAL('returnPressed()'))
        self.exclude_pattern.lineEdit().emit(SIGNAL('returnPressed()'))

    def detect_hg_repository(self, path=None):
        if path is None:
            path = os.getcwdu()
        hg_repository = is_hg_installed() and get_hg_root(path) is not None
        self.hg_manifest.setEnabled(hg_repository)
        if not hg_repository and self.hg_manifest.isChecked():
            self.custom_dir.setChecked(True)

    def set_search_text(self, text):
        self.search_text.setEditText(text)
        self.search_text.lineEdit().selectAll()
        self.search_text.setFocus()

    def get_options(self, all=False):
        # Getting options
        utext = unicode(self.search_text.currentText())
        if not utext:
            return
        try:
            texts = [str(utext)]
        except UnicodeDecodeError:
            texts = []
            for encoding in self.supported_encodings:
                try:
                    texts.append(utext.encode(encoding))
                except UnicodeDecodeError:
                    pass
        text_re = self.edit_regexp.isChecked()
        include = unicode(self.include_pattern.currentText())
        include_re = self.include_regexp.isChecked()
        exclude = unicode(self.exclude_pattern.currentText())
        exclude_re = self.exclude_regexp.isChecked()
        python_path = self.python_path.isChecked()
        hg_manifest = self.hg_manifest.isChecked()
        path = osp.abspath(unicode(self.dir_combo.currentText()))

        # Finding text occurences
        if not include_re:
            include = fnmatch.translate(include)
        if not exclude_re:
            exclude = fnmatch.translate(exclude)

        if all:
            search_text = [unicode(self.search_text.itemText(index)) \
                           for index in range(self.search_text.count())]
            search_path = [unicode(self.dir_combo.itemText(index)) \
                           for index in range(self.dir_combo.count())]
            include = [unicode(self.include_pattern.itemText(index)) \
                       for index in range(self.include_pattern.count())]
            exclude = [unicode(self.exclude_pattern.itemText(index)) \
                       for index in range(self.exclude_pattern.count())]
            return (search_text, text_re, search_path, include, include_re,
                    exclude, exclude_re)
        else:
            return (path, python_path, hg_manifest, include, exclude, texts,
                    text_re)

    def select_directory(self):
        """Select directory"""
        self.parent().emit(SIGNAL('redirect_stdio(bool)'), False)
        directory = QFileDialog.getExistingDirectory(
            self, translate('FindInFiles', "Select directory"),
            self.dir_combo.currentText())
        if not directory.isEmpty():
            self.set_directory(directory)
        self.parent().emit(SIGNAL('redirect_stdio(bool)'), True)

    def set_directory(self, directory):
        path = unicode(osp.abspath(unicode(directory)))
        self.dir_combo.setEditText(path)
        self.detect_hg_repository(path)

    def keyPressEvent(self, event):
        """Reimplemented to handle key events"""
        ctrl = event.modifiers() & Qt.ControlModifier
        shift = event.modifiers() & Qt.ShiftModifier
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            self.emit(SIGNAL('find()'))
        elif event.key() == Qt.Key_F and ctrl and shift:
            # Toggle find widgets
            self.parent().emit(SIGNAL('toggle_visibility(bool)'),
                               not self.isVisible())
            event.accept()
        else:
            event.ignore()
예제 #20
0
class FindInFilesDialog(QDialog):
    def __init__(self, result_widget, parent):
        QDialog.__init__(self, parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle("Find in files")
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(resources.IMAGES['find']),
                                       self.tr("Open"))
        self.filters_line_edit = QLineEdit("*.py")
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.check_replace = QCheckBox(self.tr("Replace: "))
        self.case_checkbox = QCheckBox(self.tr("C&ase sensitive"))
        self.type_checkbox = QCheckBox(self.tr("R&egular Expression"))
        self.recursive_checkbox = QCheckBox(self.tr("Rec&ursive"))
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(
            self.tr("Search by Phrase (Exact Match)."))
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            self.tr("Search for all the words "
                    "(anywhere in the document, not together)."))
        self.find_button = QPushButton(self.tr("Find!"))
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(self.tr("Cancel"))
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(self.tr("Main"))
        grid = QGridLayout()
        grid.addWidget(QLabel(self.tr("Text: ")), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(self.tr("Directory: ")), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(self.tr("Filter: ")), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(self.tr("Options"))
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        self._kill_thread()
        # Crazy hack to avoid circular imports
        self.result_widget.parent().parent().parent().hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        dir_name = QFileDialog.getExistingDirectory(
            self, self.tr("Open Directory"), self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        # Version of PyQt API 1
        # filters = self.filters_line_edit.text().split(QRegExp("[,;]"),
        #     QString.SkipEmptyParts)

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
예제 #21
0
class FindInFilesDialog(QDialog, object):
    """ find in files dialog implementation """

    inProject = 0
    inDirectory = 1
    inOpenFiles = 2

    def __init__(self, where, what="", dirPath="", filters=[], parent=None):

        QDialog.__init__(self, parent)

        mainWindow = GlobalData().mainWindow
        self.editorsManager = mainWindow.editorsManagerWidget.editorsManager

        self.__cancelRequest = False
        self.__inProgress = False
        self.searchRegexp = None
        self.searchResults = []

        # Avoid pylint complains
        self.findCombo = None
        self.caseCheckBox = None
        self.wordCheckBox = None
        self.regexpCheckBox = None
        self.projectRButton = None
        self.openFilesRButton = None
        self.dirRButton = None
        self.dirEditCombo = None
        self.dirSelectButton = None
        self.filterCombo = None
        self.fileLabel = None
        self.progressBar = None
        self.findButton = None

        self.__createLayout()
        self.setWindowTitle("Find in files")

        # Restore the combo box values
        project = GlobalData().project
        if project.fileName != "":
            self.findFilesWhat = project.findFilesWhat
            self.findFilesDirs = project.findFilesDirs
            self.findFilesMasks = project.findFilesMasks
        else:
            settings = Settings()
            self.findFilesWhat = settings.findFilesWhat
            self.findFilesDirs = settings.findFilesDirs
            self.findFilesMasks = settings.findFilesMasks
        self.findCombo.addItems(self.findFilesWhat)
        self.findCombo.setEditText("")
        self.dirEditCombo.addItems(self.findFilesDirs)
        self.dirEditCombo.setEditText("")
        self.filterCombo.addItems(self.findFilesMasks)
        self.filterCombo.setEditText("")

        if where == self.inProject:
            self.setSearchInProject(what, filters)
        elif where == self.inDirectory:
            self.setSearchInDirectory(what, dirPath, filters)
        else:
            self.setSearchInOpenFiles(what, filters)

        return

    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(600, 300)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)
        gridLayout = QGridLayout()

        # Combo box for the text to search
        findLabel = QLabel(self)
        findLabel.setText("Find text:")
        self.findCombo = QComboBox(self)
        self.__tuneCombo(self.findCombo)
        self.findCombo.lineEdit().setToolTip(
            "Regular expression to search for")
        self.findCombo.editTextChanged.connect(self.__someTextChanged)

        gridLayout.addWidget(findLabel, 0, 0, 1, 1)
        gridLayout.addWidget(self.findCombo, 0, 1, 1, 1)
        verticalLayout.addLayout(gridLayout)

        # Check boxes
        horizontalCBLayout = QHBoxLayout()
        self.caseCheckBox = QCheckBox(self)
        self.caseCheckBox.setText("Match &case")
        horizontalCBLayout.addWidget(self.caseCheckBox)
        self.wordCheckBox = QCheckBox(self)
        self.wordCheckBox.setText("Match whole &word")
        horizontalCBLayout.addWidget(self.wordCheckBox)
        self.regexpCheckBox = QCheckBox(self)
        self.regexpCheckBox.setText("Regular &expression")
        horizontalCBLayout.addWidget(self.regexpCheckBox)

        verticalLayout.addLayout(horizontalCBLayout)

        # Files groupbox
        filesGroupbox = QGroupBox(self)
        filesGroupbox.setTitle("Find in")
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            filesGroupbox.sizePolicy().hasHeightForWidth())
        filesGroupbox.setSizePolicy(sizePolicy)

        gridLayoutFG = QGridLayout(filesGroupbox)
        self.projectRButton = QRadioButton(filesGroupbox)
        self.projectRButton.setText("&Project")
        gridLayoutFG.addWidget(self.projectRButton, 0, 0)
        self.projectRButton.clicked.connect(self.__projectClicked)

        self.openFilesRButton = QRadioButton(filesGroupbox)
        self.openFilesRButton.setText("&Opened files only")
        gridLayoutFG.addWidget(self.openFilesRButton, 1, 0)
        self.openFilesRButton.clicked.connect(self.__openFilesOnlyClicked)

        self.dirRButton = QRadioButton(filesGroupbox)
        self.dirRButton.setText("&Directory tree")
        gridLayoutFG.addWidget(self.dirRButton, 2, 0)
        self.dirRButton.clicked.connect(self.__dirClicked)

        self.dirEditCombo = QComboBox(filesGroupbox)
        self.__tuneCombo(self.dirEditCombo)
        self.dirEditCombo.lineEdit().setToolTip("Directory to search in")
        gridLayoutFG.addWidget(self.dirEditCombo, 2, 1)
        self.dirEditCombo.editTextChanged.connect(self.__someTextChanged)

        self.dirSelectButton = QPushButton(filesGroupbox)
        self.dirSelectButton.setText("...")
        gridLayoutFG.addWidget(self.dirSelectButton, 2, 2)
        self.dirSelectButton.clicked.connect(self.__selectDirClicked)

        filterLabel = QLabel(filesGroupbox)
        filterLabel.setText("Files filter:")
        gridLayoutFG.addWidget(filterLabel, 3, 0)
        self.filterCombo = QComboBox(filesGroupbox)
        self.__tuneCombo(self.filterCombo)
        self.filterCombo.lineEdit().setToolTip("File names regular expression")
        gridLayoutFG.addWidget(self.filterCombo, 3, 1)
        self.filterCombo.editTextChanged.connect(self.__someTextChanged)

        verticalLayout.addWidget(filesGroupbox)

        # File label
        self.fileLabel = FitPathLabel(self)
        self.fileLabel.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Fixed)
        verticalLayout.addWidget(self.fileLabel)

        # Progress bar
        self.progressBar = QProgressBar(self)
        self.progressBar.setValue(0)
        self.progressBar.setOrientation(Qt.Horizontal)
        verticalLayout.addWidget(self.progressBar)

        # Buttons at the bottom
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel)
        self.findButton = buttonBox.addButton("Find",
                                              QDialogButtonBox.AcceptRole)
        self.findButton.setDefault(True)
        self.findButton.clicked.connect(self.__process)
        verticalLayout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.__onClose)
        return

    @staticmethod
    def __tuneCombo(comboBox):
        " Sets the common settings for a combo box "
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth( \
                            comboBox.sizePolicy().hasHeightForWidth() )
        comboBox.setSizePolicy(sizePolicy)
        comboBox.setEditable(True)
        comboBox.setInsertPolicy(QComboBox.InsertAtTop)
        comboBox.setAutoCompletion(False)
        comboBox.setDuplicatesEnabled(False)
        return

    def __onClose(self):
        " Triggered when the close button is clicked "

        self.__cancelRequest = True
        if not self.__inProgress:
            self.close()
        return

    def setSearchInProject(self, what="", filters=[]):
        " Set search ready for the whole project "

        if GlobalData().project.fileName == "":
            # No project loaded, fallback to opened files
            self.setSearchInOpenFiles(what, filters)
            return

        # Select the project radio button
        self.projectRButton.setEnabled(True)
        self.projectRButton.setChecked(True)
        self.dirEditCombo.setEnabled(False)
        self.dirSelectButton.setEnabled(False)

        openedFiles = self.editorsManager.getTextEditors()
        self.openFilesRButton.setEnabled(len(openedFiles) != 0)

        self.setFilters(filters)

        self.findCombo.setEditText(what)
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return

    def setSearchInOpenFiles(self, what="", filters=[]):
        " Sets search ready for the opened files "

        openedFiles = self.editorsManager.getTextEditors()
        if len(openedFiles) == 0:
            # No opened files, fallback to search in dir
            self.setSearchInDirectory(what, "", filters)
            return

        # Select the radio buttons
        self.projectRButton.setEnabled(GlobalData().project.fileName != "")
        self.openFilesRButton.setEnabled(True)
        self.openFilesRButton.setChecked(True)
        self.dirEditCombo.setEnabled(False)
        self.dirSelectButton.setEnabled(False)

        self.setFilters(filters)

        self.findCombo.setEditText(what)
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return

    def setSearchInDirectory(self, what="", dirPath="", filters=[]):
        " Sets search ready for the given directory "

        # Select radio buttons
        self.projectRButton.setEnabled(GlobalData().project.fileName != "")
        openedFiles = self.editorsManager.getTextEditors()
        self.openFilesRButton.setEnabled(len(openedFiles) != 0)
        self.dirRButton.setEnabled(True)
        self.dirRButton.setChecked(True)
        self.dirEditCombo.setEnabled(True)
        self.dirSelectButton.setEnabled(True)
        self.dirEditCombo.setEditText(dirPath)

        self.setFilters(filters)

        self.findCombo.setEditText(what)
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return

    def setFilters(self, filters):
        " Sets up the filters "

        # Set filters if provided
        if filters:
            self.filterCombo.setEditText(";".join(filters))
        else:
            self.filterCombo.setEditText("")
        return

    def __testSearchability(self):
        " Tests the searchability and sets the Find button status "

        startTime = time.time()
        if self.findCombo.currentText().strip() == "":
            self.findButton.setEnabled(False)
            self.findButton.setToolTip("No text to search")
            return

        if self.dirRButton.isChecked():
            dirname = self.dirEditCombo.currentText().strip()
            if dirname == "":
                self.findButton.setEnabled(False)
                self.findButton.setToolTip("No directory path")
                return
            if not os.path.isdir(dirname):
                self.findButton.setEnabled(False)
                self.findButton.setToolTip("Path is not a directory")
                return

        # Now we need to match file names if there is a filter
        filtersText = self.filterCombo.currentText().strip()
        if filtersText == "":
            self.findButton.setEnabled(True)
            self.findButton.setToolTip("Find in files")
            return

        # Need to check the files match
        try:
            filterRe = re.compile(filtersText, re.IGNORECASE)
        except:
            self.findButton.setEnabled(False)
            self.findButton.setToolTip( "Incorrect files " \
                                        "filter regular expression" )
            return

        matched = False
        tooLong = False
        if self.projectRButton.isChecked():
            # Whole project
            for fname in GlobalData().project.filesList:
                if fname.endswith(sep):
                    continue
                matched = filterRe.match(fname)
                if matched:
                    break
                # Check the time, it might took too long
                if time.time() - startTime > 0.1:
                    tooLong = True
                    break

        elif self.openFilesRButton.isChecked():
            # Opened files
            openedFiles = self.editorsManager.getTextEditors()
            for record in openedFiles:
                matched = filterRe.match(record[1])
                if matched:
                    break
                # Check the time, it might took too long
                if time.time() - startTime > 0.1:
                    tooLong = True
                    break

        else:
            # Search in the dir
            if not dirname.endswith(sep):
                dirname += sep
            matched, tooLong = self.__matchInDir(dirname, filterRe, startTime)

        if matched:
            self.findButton.setEnabled(True)
            self.findButton.setToolTip("Find in files")
        else:
            if tooLong:
                self.findButton.setEnabled(True)
                self.findButton.setToolTip("Find in files")
            else:
                self.findButton.setEnabled(False)
                self.findButton.setToolTip("No files matched to search in")
        return

    @staticmethod
    def __matchInDir(path, filterRe, startTime):
        " Provides the 'match' and 'too long' statuses "
        matched = False
        tooLong = False
        for item in os.listdir(path):
            if time.time() - startTime > 0.1:
                tooLong = True
                return matched, tooLong
            if os.path.isdir(path + item):
                dname = path + item + sep
                matched, tooLong = FindInFilesDialog.__matchInDir(
                    dname, filterRe, startTime)
                if matched or tooLong:
                    return matched, tooLong
                continue
            if filterRe.match(path + item):
                matched = True
                return matched, tooLong
        return matched, tooLong

    def __projectClicked(self):
        " project radio button clicked "
        self.dirEditCombo.setEnabled(False)
        self.dirSelectButton.setEnabled(False)
        self.__testSearchability()
        return

    def __openFilesOnlyClicked(self):
        " open files only radio button clicked "
        self.dirEditCombo.setEnabled(False)
        self.dirSelectButton.setEnabled(False)
        self.__testSearchability()
        return

    def __dirClicked(self):
        " dir radio button clicked "
        self.dirEditCombo.setEnabled(True)
        self.dirSelectButton.setEnabled(True)
        self.dirEditCombo.setFocus()
        self.__testSearchability()
        return

    def __someTextChanged(self, text):
        " Text to search, filter or dir name has been changed "
        self.__testSearchability()
        return

    def __selectDirClicked(self):
        " The user selects a directory "
        dirName = QFileDialog.getExistingDirectory(
            self, "Select directory to search in",
            self.dirEditCombo.currentText(),
            QFileDialog.Options(QFileDialog.ShowDirsOnly))

        if dirName:
            self.dirEditCombo.setEditText(os.path.normpath(dirName))
        self.__testSearchability()
        return

    def __projectFiles(self, filterRe):
        " Project files list respecting the mask "
        mainWindow = GlobalData().mainWindow
        files = []
        for fname in GlobalData().project.filesList:
            if fname.endswith(sep):
                continue
            if filterRe is None or filterRe.match(fname):
                widget = mainWindow.getWidgetForFileName(fname)
                if widget is None:
                    # Do not check for broken symlinks
                    if isFileSearchable(fname, False):
                        files.append(ItemToSearchIn(fname, ""))
                else:
                    if widget.getType() in \
                                [ MainWindowTabWidgetBase.PlainTextEditor ]:
                        files.append(ItemToSearchIn(fname, widget.getUUID()))
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception("Cancel request")
        return files

    def __openedFiles(self, filterRe):
        " Currently opened editor buffers "

        files = []
        openedFiles = self.editorsManager.getTextEditors()
        for record in openedFiles:
            uuid = record[0]
            fname = record[1]
            if filterRe is None or filterRe.match(fname):
                files.append(ItemToSearchIn(fname, uuid))
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception("Cancel request")
        return files

    def __dirFiles(self, path, filterRe, files):
        " Files recursively for the dir "
        for item in os.listdir(path):
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception("Cancel request")
            if os.path.isdir(path + item):
                if item in [".svn", ".cvs"]:
                    # It does not make sense to search in revision control dirs
                    continue
                anotherDir, isLoop = resolveLink(path + item)
                if not isLoop:
                    self.__dirFiles(anotherDir + sep, filterRe, files)
                continue
            if not os.path.isfile(path + item):
                continue
            realItem, isLoop = resolveLink(path + item)
            if isLoop:
                continue
            if filterRe is None or filterRe.match(realItem):
                found = False
                for itm in files:
                    if itm.fileName == realItem:
                        found = True
                        break
                if not found:
                    mainWindow = GlobalData().mainWindow
                    widget = mainWindow.getWidgetForFileName(realItem)
                    if widget is None:
                        if isFileSearchable(realItem):
                            files.append(ItemToSearchIn(realItem, ""))
                    else:
                        if widget.getType() in \
                                    [ MainWindowTabWidgetBase.PlainTextEditor ]:
                            files.append(
                                ItemToSearchIn(realItem, widget.getUUID()))
        return

    def __buildFilesList(self):
        " Builds the list of files to search in "
        filtersText = self.filterCombo.currentText().strip()
        if filtersText != "":
            filterRe = re.compile(filtersText, re.IGNORECASE)
        else:
            filterRe = None

        if self.projectRButton.isChecked():
            return self.__projectFiles(filterRe)

        if self.openFilesRButton.isChecked():
            return self.__openedFiles(filterRe)

        dirname = os.path.realpath(self.dirEditCombo.currentText().strip())
        files = []
        self.__dirFiles(dirname + sep, filterRe, files)
        return files

    def __process(self):
        " Search process "

        # Add entries to the combo box if required
        regexpText = self.findCombo.currentText()
        if regexpText in self.findFilesWhat:
            self.findFilesWhat.remove(regexpText)
        self.findFilesWhat.insert(0, regexpText)
        if len(self.findFilesWhat) > 32:
            self.findFilesWhat = self.findFilesWhat[:32]
        self.findCombo.clear()
        self.findCombo.addItems(self.findFilesWhat)

        filtersText = self.filterCombo.currentText().strip()
        if filtersText in self.findFilesMasks:
            self.findFilesMasks.remove(filtersText)
        self.findFilesMasks.insert(0, filtersText)
        if len(self.findFilesMasks) > 32:
            self.findFilesMasks = self.findFilesMasks[:32]
        self.filterCombo.clear()
        self.filterCombo.addItems(self.findFilesMasks)

        if self.dirRButton.isChecked():
            dirText = self.dirEditCombo.currentText().strip()
            if dirText in self.findFilesDirs:
                self.findFilesDirs.remove(dirText)
            self.findFilesDirs.insert(0, dirText)
            if len(self.findFilesDirs) > 32:
                self.findFilesDirs = self.findFilesDirs[:32]
            self.dirEditCombo.clear()
            self.dirEditCombo.addItems(self.findFilesDirs)

        # Save the combo values for further usage
        if GlobalData().project.fileName != "":
            GlobalData().project.setFindInFilesHistory(self.findFilesWhat,
                                                       self.findFilesDirs,
                                                       self.findFilesMasks)
        else:
            Settings().findFilesWhat = self.findFilesWhat
            Settings().findFilesDirs = self.findFilesDirs
            Settings().findFilesMasks = self.findFilesMasks

        self.__inProgress = True
        numberOfMatches = 0
        self.searchResults = []
        self.searchRegexp = None

        # Form the regexp to search
        if not self.regexpCheckBox.isChecked():
            regexpText = re.escape(regexpText)
        if self.wordCheckBox.isChecked():
            regexpText = "\\b%s\\b" % regexpText
        flags = re.UNICODE | re.LOCALE
        if not self.caseCheckBox.isChecked():
            flags |= re.IGNORECASE

        try:
            self.searchRegexp = re.compile(regexpText, flags)
        except:
            logging.error("Invalid search expression")
            self.close()
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.fileLabel.setPath('Building list of files to search in...')
        QApplication.processEvents()
        try:
            files = self.__buildFilesList()
        except Exception, exc:
            if "Cancel request" in str(exc):
                QApplication.restoreOverrideCursor()
                self.close()
                return
            else:
                QApplication.restoreOverrideCursor()
                logging.error(str(exc))
                self.close()
                return
        QApplication.restoreOverrideCursor()
        QApplication.processEvents()

        if len(files) == 0:
            self.fileLabel.setPath('No files to search in')
            return

        self.progressBar.setRange(0, len(files))

        index = 1
        for item in files:

            if self.__cancelRequest:
                self.__inProgress = False
                self.close()
                return

            self.fileLabel.setPath( 'Matches: ' + str( numberOfMatches ) + \
                                    ' Processing: ' + item.fileName )

            item.search(self.searchRegexp)
            found = len(item.matches)
            if found > 0:
                numberOfMatches += found
                self.searchResults.append(item)

            self.progressBar.setValue(index)
            index += 1

            QApplication.processEvents()

        if numberOfMatches == 0:
            if len(files) == 1:
                self.fileLabel.setPath("No matches in 1 file.")
            else:
                self.fileLabel.setPath( "No matches in " + \
                                        str( len( files ) ) + " files." )
            self.__inProgress = False
        else:
            self.close()
        return
예제 #22
0
class FindInFilesDialog(QDialog):
    """Dialog to configure and trigger the search in the files."""
    def __init__(self, result_widget, parent):
        super(FindInFilesDialog, self).__init__(parent)
        self._find_thread = FindInFilesThread()
        self.setWindowTitle(translations.TR_FIND_IN_FILES)
        self.resize(400, 300)
        #MAIN LAYOUT
        main_vbox = QVBoxLayout(self)

        self.pattern_line_edit = QLineEdit()
        self.pattern_line_edit.setPlaceholderText(translations.TR_FIND + "...")
        self.dir_name_root = None
        self.user_home = os.path.expanduser('~')
        self.dir_combo = QComboBox()
        self.dir_combo.addItem(self.user_home)
        self.dir_combo.setEditable(True)
        self.open_button = QPushButton(QIcon(":img/find"),
                                       translations.TR_OPEN)
        self.filters_line_edit = QLineEdit("*.py")
        self.filters_line_edit.setPlaceholderText("*.py")
        self.filters_line_edit.setCompleter(
            QCompleter([
                "*{}".format(item) for item in settings.SUPPORTED_EXTENSIONS
            ]))
        self.replace_line = QLineEdit()
        self.replace_line.setEnabled(False)
        self.replace_line.setPlaceholderText(translations.TR_TEXT_FOR_REPLACE +
                                             "...")
        self.check_replace = QCheckBox(translations.TR_REPLACE)
        self.case_checkbox = QCheckBox(translations.TR_CASE_SENSITIVE)
        self.type_checkbox = QCheckBox(translations.TR_REGULAR_EXPRESSION)
        self.recursive_checkbox = QCheckBox(translations.TR_RECURSIVE)
        self.recursive_checkbox.setCheckState(Qt.Checked)
        self.phrase_radio = QRadioButton(translations.TR_SEARCH_BY_PHRASE)
        self.phrase_radio.setChecked(True)
        self.words_radio = QRadioButton(
            translations.TR_SEARCH_FOR_ALL_THE_WORDS)
        self.find_button = QPushButton(translations.TR_FIND + "!")
        self.find_button.setMaximumWidth(150)
        self.cancel_button = QPushButton(translations.TR_CANCEL)
        self.cancel_button.setMaximumWidth(150)
        self.result_widget = result_widget

        hbox = QHBoxLayout()
        hbox.addWidget(self.find_button)
        hbox.addWidget(self.cancel_button)

        #main section
        find_group_box = QGroupBox(translations.TR_MAIN)
        grid = QGridLayout()
        grid.addWidget(QLabel(translations.TR_TEXT), 0, 0)
        grid.addWidget(self.pattern_line_edit, 0, 1)
        grid.addWidget(QLabel(translations.TR_DIRECTORY), 1, 0)
        grid.addWidget(self.dir_combo, 1, 1)
        grid.addWidget(self.open_button, 1, 2)
        grid.addWidget(QLabel(translations.TR_FILTER), 2, 0)
        grid.addWidget(self.filters_line_edit, 2, 1)
        grid.addWidget(self.check_replace, 3, 0)
        grid.addWidget(self.replace_line, 3, 1)

        find_group_box.setLayout(grid)
        #add main section to MAIN LAYOUT
        main_vbox.addWidget(find_group_box)

        #options sections
        options_group_box = QGroupBox(translations.TR_OPTIONS)
        gridOptions = QGridLayout()
        gridOptions.addWidget(self.case_checkbox, 0, 0)
        gridOptions.addWidget(self.type_checkbox, 1, 0)
        gridOptions.addWidget(self.recursive_checkbox, 2, 0)
        gridOptions.addWidget(self.phrase_radio, 0, 1)
        gridOptions.addWidget(self.words_radio, 1, 1)

        options_group_box.setLayout(gridOptions)
        #add options sections to MAIN LAYOUT
        main_vbox.addWidget(options_group_box)

        #add buttons to MAIN LAYOUT
        main_vbox.addLayout(hbox)

        #Focus
        self.pattern_line_edit.setFocus()
        self.open_button.setFocusPolicy(Qt.NoFocus)

        #signal
        self.connect(self.open_button, SIGNAL("clicked()"), self._select_dir)
        self.connect(self.find_button, SIGNAL("clicked()"),
                     self._find_in_files)
        self.connect(self.cancel_button, SIGNAL("clicked()"),
                     self._kill_thread)
        self.connect(self._find_thread, SIGNAL("found_pattern(PyQt_PyObject)"),
                     self._found_match)
        self.connect(self._find_thread, SIGNAL("finished()"),
                     self._find_thread_finished)
        self.connect(self.type_checkbox, SIGNAL("stateChanged(int)"),
                     self._change_radio_enabled)
        self.connect(self.check_replace, SIGNAL("stateChanged(int)"),
                     self._replace_activated)
        self.connect(self.words_radio, SIGNAL("clicked(bool)"),
                     self._words_radio_pressed)

    def _replace_activated(self):
        """If replace is activated, display the replace widgets."""
        self.replace_line.setEnabled(self.check_replace.isChecked())
        self.phrase_radio.setChecked(True)

    def _words_radio_pressed(self, value):
        """If search by independent words is activated, replace is not."""
        self.replace_line.setEnabled(not value)
        self.check_replace.setChecked(not value)
        self.words_radio.setChecked(True)

    def _change_radio_enabled(self, val):
        """Control the state of the radio buttons."""
        enabled = not self.type_checkbox.isChecked()
        self.phrase_radio.setEnabled(enabled)
        self.words_radio.setEnabled(enabled)

    def show(self, actual_project=None, actual=None):
        """Display the dialog and load the projects."""
        self.dir_combo.clear()
        self.dir_name_root = actual_project if \
            actual_project else [self.user_home]
        self.dir_combo.addItems(self.dir_name_root)
        if actual:
            index = self.dir_combo.findText(actual)
            self.dir_combo.setCurrentIndex(index)
        super(FindInFilesDialog, self).show()
        self.pattern_line_edit.setFocus()

    def reject(self):
        """Close the dialog and hide the tools dock."""
        self._kill_thread()
        tools_dock = IDE.get_service('tools_dock')
        if tools_dock:
            tools_dock.hide()
        super(FindInFilesDialog, self).reject()

    def _find_thread_finished(self):
        """Wait on thread finished."""
        self.emit(SIGNAL("finished()"))
        self._find_thread.wait()

    def _select_dir(self):
        """When a new folder is selected, add to the combo if needed."""
        dir_name = QFileDialog.getExistingDirectory(
            self, translations.TR_OPEN, self.dir_combo.currentText(),
            QFileDialog.ShowDirsOnly)
        index = self.dir_combo.findText(dir_name)
        if index >= 0:
            self.dir_combo.setCurrentIndex(index)
        else:
            self.dir_combo.insertItem(0, dir_name)
            self.dir_combo.setCurrentIndex(0)

    def _found_match(self, result):
        """Update the tree for each match found."""
        file_name = result[0]
        items = result[1]
        self.result_widget.update_result(self.dir_combo.currentText(),
                                         file_name, items)

    def _kill_thread(self):
        """Kill the thread."""
        if self._find_thread.isRunning():
            self._find_thread.cancel()
        self.accept()

    def _find_in_files(self):
        """Trigger the search on the files."""
        self.emit(SIGNAL("findStarted()"))
        self._kill_thread()
        self.result_widget.clear()
        pattern = self.pattern_line_edit.text()
        dir_name = self.dir_combo.currentText()

        filters = re.split("[,;]", self.filters_line_edit.text())

        #remove the spaces in the words Ex. (" *.foo"--> "*.foo")
        filters = [f.strip() for f in filters]
        case_sensitive = self.case_checkbox.isChecked()
        type_ = QRegExp.RegExp if \
            self.type_checkbox.isChecked() else QRegExp.FixedString
        recursive = self.recursive_checkbox.isChecked()
        by_phrase = True
        if self.phrase_radio.isChecked() or self.type_checkbox.isChecked():
            regExp = QRegExp(pattern, case_sensitive, type_)
        elif self.words_radio.isChecked():
            by_phrase = False
            type_ = QRegExp.RegExp
            pattern = '|'.join([word.strip() for word in pattern.split()])
            regExp = QRegExp(pattern, case_sensitive, type_)
        #save a reference to the root directory where we find
        self.dir_name_root = dir_name
        self._find_thread.find_in_files(dir_name, filters, regExp, recursive,
                                        by_phrase)
예제 #23
0
class FindInFilesDialog( QDialog, object ):
    """ find in files dialog implementation """

    inProject = 0
    inDirectory = 1
    inOpenFiles = 2

    def __init__( self, where, what = "",
                  dirPath = "", filters = [],
                  parent = None ):

        QDialog.__init__( self, parent )

        mainWindow = GlobalData().mainWindow
        self.editorsManager = mainWindow.editorsManagerWidget.editorsManager

        self.__cancelRequest = False
        self.__inProgress = False
        self.searchRegexp = None
        self.searchResults = []

        # Avoid pylint complains
        self.findCombo = None
        self.caseCheckBox = None
        self.wordCheckBox = None
        self.regexpCheckBox = None
        self.projectRButton = None
        self.openFilesRButton = None
        self.dirRButton = None
        self.dirEditCombo = None
        self.dirSelectButton = None
        self.filterCombo = None
        self.fileLabel = None
        self.progressBar = None
        self.findButton = None

        self.__createLayout()
        self.setWindowTitle( "Find in files" )

        # Restore the combo box values
        project = GlobalData().project
        if project.fileName != "":
            self.findFilesWhat = project.findFilesWhat
            self.findFilesDirs = project.findFilesDirs
            self.findFilesMasks = project.findFilesMasks
        else:
            settings = Settings()
            self.findFilesWhat = settings.findFilesWhat
            self.findFilesDirs = settings.findFilesDirs
            self.findFilesMasks = settings.findFilesMasks
        self.findCombo.addItems( self.findFilesWhat )
        self.findCombo.setEditText( "" )
        self.dirEditCombo.addItems( self.findFilesDirs )
        self.dirEditCombo.setEditText( "" )
        self.filterCombo.addItems( self.findFilesMasks )
        self.filterCombo.setEditText( "" )

        if where == self.inProject:
            self.setSearchInProject( what, filters )
        elif where == self.inDirectory:
            self.setSearchInDirectory( what, dirPath, filters )
        else:
            self.setSearchInOpenFiles( what, filters )

        return

    def __createLayout( self ):
        """ Creates the dialog layout """

        self.resize( 600, 300 )
        self.setSizeGripEnabled( True )

        verticalLayout = QVBoxLayout( self )
        gridLayout = QGridLayout()

        # Combo box for the text to search
        findLabel = QLabel( self )
        findLabel.setText( "Find text:" )
        self.findCombo = QComboBox( self )
        self.__tuneCombo( self.findCombo )
        self.findCombo.lineEdit().setToolTip( "Regular expression to search for" )
        self.findCombo.editTextChanged.connect( self.__someTextChanged )

        gridLayout.addWidget( findLabel, 0, 0, 1, 1 )
        gridLayout.addWidget( self.findCombo, 0, 1, 1, 1 )
        verticalLayout.addLayout( gridLayout )

        # Check boxes
        horizontalCBLayout = QHBoxLayout()
        self.caseCheckBox = QCheckBox( self )
        self.caseCheckBox.setText( "Match &case" )
        horizontalCBLayout.addWidget( self.caseCheckBox )
        self.wordCheckBox = QCheckBox( self )
        self.wordCheckBox.setText( "Match whole &word" )
        horizontalCBLayout.addWidget( self.wordCheckBox )
        self.regexpCheckBox = QCheckBox( self )
        self.regexpCheckBox.setText( "Regular &expression" )
        horizontalCBLayout.addWidget( self.regexpCheckBox )

        verticalLayout.addLayout( horizontalCBLayout )

        # Files groupbox
        filesGroupbox = QGroupBox( self )
        filesGroupbox.setTitle( "Find in" )
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Preferred )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth(
                        filesGroupbox.sizePolicy().hasHeightForWidth() )
        filesGroupbox.setSizePolicy( sizePolicy )

        gridLayoutFG = QGridLayout( filesGroupbox )
        self.projectRButton = QRadioButton( filesGroupbox )
        self.projectRButton.setText( "&Project" )
        gridLayoutFG.addWidget( self.projectRButton, 0, 0 )
        self.projectRButton.clicked.connect( self.__projectClicked )

        self.openFilesRButton = QRadioButton( filesGroupbox )
        self.openFilesRButton.setText( "&Opened files only" )
        gridLayoutFG.addWidget( self.openFilesRButton, 1, 0 )
        self.openFilesRButton.clicked.connect( self.__openFilesOnlyClicked )

        self.dirRButton = QRadioButton( filesGroupbox )
        self.dirRButton.setText( "&Directory tree" )
        gridLayoutFG.addWidget( self.dirRButton, 2, 0 )
        self.dirRButton.clicked.connect( self.__dirClicked )

        self.dirEditCombo = QComboBox( filesGroupbox )
        self.__tuneCombo( self.dirEditCombo )
        self.dirEditCombo.lineEdit().setToolTip( "Directory to search in" )
        gridLayoutFG.addWidget( self.dirEditCombo, 2, 1 )
        self.dirEditCombo.editTextChanged.connect( self.__someTextChanged )

        self.dirSelectButton = QPushButton( filesGroupbox )
        self.dirSelectButton.setText( "..." )
        gridLayoutFG.addWidget( self.dirSelectButton, 2, 2 )
        self.dirSelectButton.clicked.connect( self.__selectDirClicked )

        filterLabel = QLabel( filesGroupbox )
        filterLabel.setText( "Files filter:" )
        gridLayoutFG.addWidget( filterLabel, 3, 0 )
        self.filterCombo = QComboBox( filesGroupbox )
        self.__tuneCombo( self.filterCombo )
        self.filterCombo.lineEdit().setToolTip( "File names regular expression" )
        gridLayoutFG.addWidget( self.filterCombo, 3, 1 )
        self.filterCombo.editTextChanged.connect( self.__someTextChanged )

        verticalLayout.addWidget( filesGroupbox )

        # File label
        self.fileLabel = FitPathLabel( self )
        self.fileLabel.setSizePolicy( QSizePolicy.Ignored, QSizePolicy.Fixed )
        verticalLayout.addWidget( self.fileLabel )

        # Progress bar
        self.progressBar = QProgressBar( self )
        self.progressBar.setValue( 0 )
        self.progressBar.setOrientation( Qt.Horizontal )
        verticalLayout.addWidget( self.progressBar )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Cancel )
        self.findButton = buttonBox.addButton( "Find",
                                               QDialogButtonBox.AcceptRole )
        self.findButton.setDefault( True )
        self.findButton.clicked.connect( self.__process )
        verticalLayout.addWidget( buttonBox )

        buttonBox.rejected.connect( self.__onClose )
        return

    @staticmethod
    def __tuneCombo( comboBox ):
        " Sets the common settings for a combo box "
        sizePolicy = QSizePolicy( QSizePolicy.Expanding, QSizePolicy.Fixed )
        sizePolicy.setHorizontalStretch( 0 )
        sizePolicy.setVerticalStretch( 0 )
        sizePolicy.setHeightForWidth( \
                            comboBox.sizePolicy().hasHeightForWidth() )
        comboBox.setSizePolicy( sizePolicy )
        comboBox.setEditable( True )
        comboBox.setInsertPolicy( QComboBox.InsertAtTop )
        comboBox.setAutoCompletion( False )
        comboBox.setDuplicatesEnabled( False )
        return

    def __onClose( self ):
        " Triggered when the close button is clicked "

        self.__cancelRequest = True
        if not self.__inProgress:
            self.close()
        return

    def setSearchInProject( self, what = "", filters = [] ):
        " Set search ready for the whole project "

        if GlobalData().project.fileName == "":
            # No project loaded, fallback to opened files
            self.setSearchInOpenFiles( what, filters )
            return

        # Select the project radio button
        self.projectRButton.setEnabled( True )
        self.projectRButton.setChecked( True )
        self.dirEditCombo.setEnabled( False )
        self.dirSelectButton.setEnabled( False )

        openedFiles = self.editorsManager.getTextEditors()
        self.openFilesRButton.setEnabled( len( openedFiles ) != 0 )

        self.setFilters( filters )

        self.findCombo.setEditText( what )
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return


    def setSearchInOpenFiles( self, what = "", filters = [] ):
        " Sets search ready for the opened files "

        openedFiles = self.editorsManager.getTextEditors()
        if len( openedFiles ) == 0:
            # No opened files, fallback to search in dir
            self.setSearchInDirectory( what, "", filters )
            return

        # Select the radio buttons
        self.projectRButton.setEnabled( GlobalData().project.fileName != "" )
        self.openFilesRButton.setEnabled( True )
        self.openFilesRButton.setChecked( True )
        self.dirEditCombo.setEnabled( False )
        self.dirSelectButton.setEnabled( False )

        self.setFilters( filters )

        self.findCombo.setEditText( what )
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return


    def setSearchInDirectory( self, what = "", dirPath = "", filters = [] ):
        " Sets search ready for the given directory "

        # Select radio buttons
        self.projectRButton.setEnabled( GlobalData().project.fileName != "" )
        openedFiles = self.editorsManager.getTextEditors()
        self.openFilesRButton.setEnabled( len( openedFiles ) != 0 )
        self.dirRButton.setEnabled( True )
        self.dirRButton.setChecked( True )
        self.dirEditCombo.setEnabled( True )
        self.dirSelectButton.setEnabled( True )
        self.dirEditCombo.setEditText( dirPath )

        self.setFilters( filters )

        self.findCombo.setEditText( what )
        self.findCombo.lineEdit().selectAll()
        self.findCombo.setFocus()

        # Check searchability
        self.__testSearchability()
        return


    def setFilters( self, filters ):
        " Sets up the filters "

        # Set filters if provided
        if filters:
            self.filterCombo.setEditText( ";".join( filters ) )
        else:
            self.filterCombo.setEditText( "" )
        return

    def __testSearchability( self ):
        " Tests the searchability and sets the Find button status "

        startTime = time.time()
        if self.findCombo.currentText().strip() == "":
            self.findButton.setEnabled( False )
            self.findButton.setToolTip( "No text to search" )
            return

        if self.dirRButton.isChecked():
            dirname = self.dirEditCombo.currentText().strip()
            if dirname == "":
                self.findButton.setEnabled( False )
                self.findButton.setToolTip( "No directory path" )
                return
            if not os.path.isdir( dirname ):
                self.findButton.setEnabled( False )
                self.findButton.setToolTip( "Path is not a directory" )
                return

        # Now we need to match file names if there is a filter
        filtersText = self.filterCombo.currentText().strip()
        if filtersText == "":
            self.findButton.setEnabled( True )
            self.findButton.setToolTip( "Find in files" )
            return

        # Need to check the files match
        try:
            filterRe = re.compile( filtersText, re.IGNORECASE )
        except:
            self.findButton.setEnabled( False )
            self.findButton.setToolTip( "Incorrect files " \
                                        "filter regular expression" )
            return

        matched = False
        tooLong = False
        if self.projectRButton.isChecked():
            # Whole project
            for fname in GlobalData().project.filesList:
                if fname.endswith( sep ):
                    continue
                matched = filterRe.match( fname )
                if matched:
                    break
                # Check the time, it might took too long
                if time.time() - startTime > 0.1:
                    tooLong = True
                    break

        elif self.openFilesRButton.isChecked():
            # Opened files
            openedFiles = self.editorsManager.getTextEditors()
            for record in openedFiles:
                matched = filterRe.match( record[ 1 ] )
                if matched:
                    break
                # Check the time, it might took too long
                if time.time() - startTime > 0.1:
                    tooLong = True
                    break

        else:
            # Search in the dir
            if not dirname.endswith( sep ):
                dirname += sep
            matched, tooLong = self.__matchInDir( dirname, filterRe, startTime )

        if matched:
            self.findButton.setEnabled( True )
            self.findButton.setToolTip( "Find in files" )
        else:
            if tooLong:
                self.findButton.setEnabled( True )
                self.findButton.setToolTip( "Find in files" )
            else:
                self.findButton.setEnabled( False )
                self.findButton.setToolTip( "No files matched to search in" )
        return

    @staticmethod
    def __matchInDir( path, filterRe, startTime ):
        " Provides the 'match' and 'too long' statuses "
        matched = False
        tooLong = False
        for item in os.listdir( path ):
            if time.time() - startTime > 0.1:
                tooLong = True
                return matched, tooLong
            if os.path.isdir( path + item ):
                dname = path + item + sep
                matched, tooLong = FindInFilesDialog.__matchInDir( dname,
                                                                   filterRe,
                                                                   startTime )
                if matched or tooLong:
                    return matched, tooLong
                continue
            if filterRe.match( path + item ):
                matched = True
                return matched, tooLong
        return matched, tooLong

    def __projectClicked( self ):
        " project radio button clicked "
        self.dirEditCombo.setEnabled( False )
        self.dirSelectButton.setEnabled( False )
        self.__testSearchability()
        return

    def __openFilesOnlyClicked( self ):
        " open files only radio button clicked "
        self.dirEditCombo.setEnabled( False )
        self.dirSelectButton.setEnabled( False )
        self.__testSearchability()
        return

    def __dirClicked( self ):
        " dir radio button clicked "
        self.dirEditCombo.setEnabled( True )
        self.dirSelectButton.setEnabled( True )
        self.dirEditCombo.setFocus()
        self.__testSearchability()
        return

    def __someTextChanged( self, text ):
        " Text to search, filter or dir name has been changed "
        self.__testSearchability()
        return

    def __selectDirClicked( self ):
        " The user selects a directory "
        dirName = QFileDialog.getExistingDirectory( self,
                    "Select directory to search in",
                    self.dirEditCombo.currentText(),
                    QFileDialog.Options( QFileDialog.ShowDirsOnly ) )

        if dirName:
            self.dirEditCombo.setEditText( os.path.normpath( dirName ) )
        self.__testSearchability()
        return


    def __projectFiles( self, filterRe ):
        " Project files list respecting the mask "
        mainWindow = GlobalData().mainWindow
        files = []
        for fname in GlobalData().project.filesList:
            if fname.endswith( sep ):
                continue
            if filterRe is None or filterRe.match( fname ):
                widget = mainWindow.getWidgetForFileName( fname )
                if widget is None:
                    # Do not check for broken symlinks
                    if isFileSearchable( fname, False ):
                        files.append( ItemToSearchIn( fname, "" ) )
                else:
                    if widget.getType() in \
                                [ MainWindowTabWidgetBase.PlainTextEditor ]:
                        files.append( ItemToSearchIn( fname,
                                                      widget.getUUID() ) )
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception( "Cancel request" )
        return files

    def __openedFiles( self, filterRe ):
        " Currently opened editor buffers "

        files = []
        openedFiles = self.editorsManager.getTextEditors()
        for record in openedFiles:
            uuid = record[ 0 ]
            fname = record[ 1 ]
            if filterRe is None or filterRe.match( fname ):
                files.append( ItemToSearchIn( fname, uuid ) )
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception( "Cancel request" )
        return files

    def __dirFiles( self, path, filterRe, files ):
        " Files recursively for the dir "
        for item in os.listdir( path ):
            QApplication.processEvents()
            if self.__cancelRequest:
                raise Exception( "Cancel request" )
            if os.path.isdir( path + item ):
                if item in [ ".svn", ".cvs" ]:
                    # It does not make sense to search in revision control dirs
                    continue
                anotherDir, isLoop = resolveLink( path + item )
                if not isLoop:
                    self.__dirFiles( anotherDir + sep,
                                     filterRe, files )
                continue
            if not os.path.isfile( path + item ):
                continue
            realItem, isLoop = resolveLink( path + item )
            if isLoop:
                continue
            if filterRe is None or filterRe.match( realItem ):
                found = False
                for itm in files:
                    if itm.fileName == realItem:
                        found = True
                        break
                if not found:
                    mainWindow = GlobalData().mainWindow
                    widget = mainWindow.getWidgetForFileName( realItem )
                    if widget is None:
                        if isFileSearchable( realItem ):
                            files.append( ItemToSearchIn( realItem, "" ) )
                    else:
                        if widget.getType() in \
                                    [ MainWindowTabWidgetBase.PlainTextEditor ]:
                            files.append( ItemToSearchIn( realItem,
                                                          widget.getUUID() ) )
        return


    def __buildFilesList( self ):
        " Builds the list of files to search in "
        filtersText = self.filterCombo.currentText().strip()
        if filtersText != "":
            filterRe = re.compile( filtersText, re.IGNORECASE )
        else:
            filterRe = None

        if self.projectRButton.isChecked():
            return self.__projectFiles( filterRe )

        if self.openFilesRButton.isChecked():
            return self.__openedFiles( filterRe )

        dirname = os.path.realpath( self.dirEditCombo.currentText().strip() )
        files = []
        self.__dirFiles( dirname + sep, filterRe, files )
        return files


    def __process( self ):
        " Search process "

        # Add entries to the combo box if required
        regexpText = self.findCombo.currentText()
        if regexpText in self.findFilesWhat:
            self.findFilesWhat.remove( regexpText )
        self.findFilesWhat.insert( 0, regexpText )
        if len( self.findFilesWhat ) > 32:
            self.findFilesWhat = self.findFilesWhat[ : 32 ]
        self.findCombo.clear()
        self.findCombo.addItems( self.findFilesWhat )

        filtersText = self.filterCombo.currentText().strip()
        if filtersText in self.findFilesMasks:
            self.findFilesMasks.remove( filtersText )
        self.findFilesMasks.insert( 0, filtersText )
        if len( self.findFilesMasks ) > 32:
            self.findFilesMasks = self.findFilesMasks[ : 32 ]
        self.filterCombo.clear()
        self.filterCombo.addItems( self.findFilesMasks )

        if self.dirRButton.isChecked():
            dirText = self.dirEditCombo.currentText().strip()
            if dirText in self.findFilesDirs:
                self.findFilesDirs.remove( dirText )
            self.findFilesDirs.insert( 0, dirText )
            if len( self.findFilesDirs ) > 32:
                self.findFilesDirs = self.findFilesDirs[ : 32 ]
            self.dirEditCombo.clear()
            self.dirEditCombo.addItems( self.findFilesDirs )

        # Save the combo values for further usage
        if GlobalData().project.fileName != "":
            GlobalData().project.setFindInFilesHistory( self.findFilesWhat,
                                                        self.findFilesDirs,
                                                        self.findFilesMasks )
        else:
            Settings().findFilesWhat = self.findFilesWhat
            Settings().findFilesDirs = self.findFilesDirs
            Settings().findFilesMasks = self.findFilesMasks


        self.__inProgress = True
        numberOfMatches = 0
        self.searchResults = []
        self.searchRegexp = None

        # Form the regexp to search
        if not self.regexpCheckBox.isChecked():
            regexpText = re.escape( regexpText )
        if self.wordCheckBox.isChecked():
            regexpText = "\\b%s\\b" % regexpText
        flags = re.UNICODE | re.LOCALE
        if not self.caseCheckBox.isChecked():
            flags |= re.IGNORECASE

        try:
            self.searchRegexp = re.compile( regexpText, flags )
        except:
            logging.error( "Invalid search expression" )
            self.close()
            return


        QApplication.setOverrideCursor( QCursor( Qt.WaitCursor ) )
        self.fileLabel.setPath( 'Building list of files to search in...' )
        QApplication.processEvents()
        try:
            files = self.__buildFilesList()
        except Exception, exc:
            if "Cancel request" in str( exc ):
                QApplication.restoreOverrideCursor()
                self.close()
                return
            else:
                QApplication.restoreOverrideCursor()
                logging.error( str( exc ) )
                self.close()
                return
        QApplication.restoreOverrideCursor()
        QApplication.processEvents()

        if len( files ) == 0:
            self.fileLabel.setPath( 'No files to search in' )
            return

        self.progressBar.setRange( 0, len( files ) )

        index = 1
        for item in files:

            if self.__cancelRequest:
                self.__inProgress = False
                self.close()
                return

            self.fileLabel.setPath( 'Matches: ' + str( numberOfMatches ) + \
                                    ' Processing: ' + item.fileName )

            item.search( self.searchRegexp )
            found = len( item.matches )
            if found > 0:
                numberOfMatches += found
                self.searchResults.append( item )

            self.progressBar.setValue( index )
            index += 1

            QApplication.processEvents()

        if numberOfMatches == 0:
            if len( files ) == 1:
                self.fileLabel.setPath( "No matches in 1 file." )
            else:
                self.fileLabel.setPath( "No matches in " + \
                                        str( len( files ) ) + " files." )
            self.__inProgress = False
        else:
            self.close()
        return