コード例 #1
0
ファイル: gui.py プロジェクト: lucarebuffi/OASYS1
    def __init__(self, parent, message, title, options, default):
        super(OptionDialog, self).__init__(parent)

        self.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        self.setIcon(QMessageBox.Question)
        self.setText(message)
        self.setWindowTitle(title)

        self.selection = default

        box = QWidget()
        box.setLayout(QGridLayout())
        box.setFixedHeight(40)

        box_combo = QWidget()
        combo = QComboBox(box_combo)
        combo.setEditable(False)
        combo.box = box_combo
        for item in options:
            combo.addItem(str(item))
        combo.setCurrentIndex(default)
        combo.currentIndexChanged.connect(self.set_selection)

        box.layout().addWidget(QLabel("Select Option"), 0, 0, 1, 1)
        box.layout().addWidget(box_combo, 0, 1, 1, 1)

        self.layout().addWidget(box, 1, 1, 1, 2)
コード例 #2
0
ファイル: featureform.py プロジェクト: vpicavet/Roam
def buildfromauto(formconfig):
    widgetsconfig = formconfig['widgets']

    outlayout = QFormLayout()
    outwidget = QWidget()
    outwidget.setLayout(outlayout)
    for config in widgetsconfig:
        widgettype = config['widget']
        field = config['field']
        name = config.get('name', field)
        label = QLabel(name)
        label.setObjectName(field + "_label")
        widgetwrapper = WidgetsRegistry.createwidget(widgettype,
                                                    layer=None,
                                                    field=field,
                                                    widget=None,
                                                    label=label,
                                                    config=None)
        widget = widgetwrapper.widget
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            layoutwidget.layout().addWidget(savebutton)

        hidden = config.get('hidden', False)
        if not hidden:
            outlayout.addRow(label, layoutwidget)

    outlayout.addItem(QSpacerItem(10,10))
    return outwidget
コード例 #3
0
def buildfromauto(formconfig, base):
    widgetsconfig = formconfig['widgets']

    outlayout = QFormLayout()
    outlayout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
    outwidget = base
    outwidget.setLayout(outlayout)
    for config in widgetsconfig:
        widgettype = config['widget']
        field = config['field']
        name = config.get('name', field)
        if not field:
            utils.warning("Field can't be null for {}".format(name))
            utils.warning("Skipping widget")
            continue
        label = QLabel(name)
        label.setObjectName(field + "_label")
        widget = roam.editorwidgets.core.createwidget(widgettype, parent=base)
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            layoutwidget.layout().addWidget(savebutton)

        outlayout.addRow(label, layoutwidget)

    outlayout.addItem(QSpacerItem(10, 10))
    installflickcharm(outwidget)
    return outwidget
コード例 #4
0
ファイル: test_dropshadow.py プロジェクト: 675801717/orange3
    def test1(self):
        class FT(QToolBar):
            def paintEvent(self, e):
                pass

        w = QMainWindow()
        ftt, ftb = FT(), FT()
        ftt.setFixedHeight(15)
        ftb.setFixedHeight(15)

        w.addToolBar(Qt.TopToolBarArea, ftt)
        w.addToolBar(Qt.BottomToolBarArea, ftb)

        f = dropshadow.DropShadowFrame()
        te = QTextEdit()
        c = QWidget()
        c.setLayout(QVBoxLayout())
        c.layout().setContentsMargins(20, 0, 20, 0)
        c.layout().addWidget(te)
        w.setCentralWidget(c)
        f.setWidget(te)
        f.radius = 15
        f.color = QColor(Qt.blue)
        w.show()

        self.singleShot(3000, lambda: f.setColor(Qt.red))
        self.singleShot(4000, lambda: f.setRadius(30))
        self.singleShot(5000, lambda: f.setRadius(40))

        self.app.exec_()
コード例 #5
0
ファイル: blankpaper.py プロジェクト: Alwnikrotikz/lilykde
 def createWidget(self):
     w = QWidget()
     w.setLayout(QVBoxLayout())
     self.squareBracket = QCheckBox(i18n("Square Bracket"))
     w.layout().addWidget(self.squareBracket)
     self.connectBarLines = QCheckBox(i18n("Connect bar lines"))
     self.connectBarLines.setChecked(True)
     w.layout().addWidget(self.connectBarLines)
     return w
コード例 #6
0
ファイル: PropertyView.py プロジェクト: Andrej-CMS/cmssw
 def appendAddRow(self):
     """ Append a row with a field to add new properties.
     """
     self.insertRow(self.lastRow()+1)
     lineedit=QLineEdit()
     lineedit.setFrame(False)
     lineedit.setContentsMargins(0, 0, 0, 0)
     self.setCellWidget(self.lastRow(), 0, lineedit)
     widget=QWidget()
     widget.setContentsMargins(0, 0, 0, 0)
     widget.setLayout(QHBoxLayout())
     widget.layout().setSpacing(0)
     widget.layout().setContentsMargins(0, 0, 0, 0)
     typelist=ComboBoxReturn()
     types=["String","Boolean","Integer","Double","File","FileVector"]
     for type in types:
         typelist.addItem(type)
     widget.layout().addWidget(typelist)
     addButton=QToolButton()
     addButton.setText("+")
     widget.layout().addWidget(addButton)
     self.setCellWidget(self.lastRow(), 1, widget)
     self.verticalHeader().resizeSection(self.lastRow(), Property.DEFAULT_HEIGHT)
     self.connect(addButton, SIGNAL('clicked(bool)'), self.addProperty)
     self.connect(lineedit, SIGNAL('returnPressed()'), self.addProperty)
     self.connect(typelist, SIGNAL('returnPressed()'), self.addProperty)
     addButton._lineedit=lineedit
     addButton._typelist=typelist
     lineedit._lineedit=lineedit
     lineedit._typelist=typelist
     typelist._lineedit=lineedit
     typelist._typelist=typelist
コード例 #7
0
class ProjectTreeColumn(QScrollArea):
    def __init__(self, *args, **kwargs):
        super(ProjectTreeColumn, self).__init__(*args, **kwargs)
        self._widget = QWidget()
        self._widget.setLayout(QVBoxLayout())
        self.setWidget(self._widget)
        self.setWidgetResizable(True)
        self.setEnabled(True)
        self.projects = []

        #connections = (
            #{'target': 'main_container',
            #'signal_name': 'openProject(QString)',
            #'slot': self.open_project_folder},
                #)
        #IDE.register_signals('tree_projects_widget', connections)

    def install(self):
        ide = IDE.get_service('ide')
        ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide)

    def open_project_folder(self):
        if settings.WORKSPACE:
            directory = settings.WORKSPACE
        else:
            directory = os.path.expanduser("~")

        folderName = QFileDialog.getExistingDirectory(self,
                self.tr("Open Project Directory"), directory)
        logger.debug("Choosing Foldername")
        if folderName:
            logger.debug("Opening %s" % folderName)
            ninjaide = IDE.get_service("ide")
            project = NProject(folderName)
            qfsm = ninjaide.filesystem.open_project(project)
            if qfsm:
                self.add_project(project)

    def add_project(self, project):
        if project not in self.projects:
            self.projects.append(project)
            ptree = TreeProjectsWidget()
            pmodel = project.model
            ptree.setModel(pmodel)
            pindex = pmodel.index(pmodel.rootPath())
            ptree.setRootIndex(pindex)
            self._widget.layout().addWidget(scrollable_wrapper(ptree))
コード例 #8
0
    def populate_main_area(self):
        grid = QWidget()
        grid.setLayout(QGridLayout(grid))
        self.mainArea.layout().addWidget(grid)

        col_type = gui.label(None, self, '%(col_type)s')

        grid.layout().addWidget(col_type, 0, 1)
        grid.layout().setAlignment(col_type, Qt.AlignHCenter)

        row_type = gui.label(None, self, '%(row_type)s')
        grid.layout().addWidget(row_type, 1, 0)
        grid.layout().setAlignment(row_type, Qt.AlignVCenter)

        self.view = QTableView()
        self.model = None
        grid.layout().addWidget(self.view, 1, 1)
コード例 #9
0
ファイル: main.py プロジェクト: brunoabud/ic
    def init_plugin(self, gui_interface, rack_interface):
        self.analyzer.filter_rack = rack_interface
        gui            = gui_interface
        self.rack_interface = rack_interface

        self.skip      = gui.int_parameter(1 , (0,  self.analyzer.max_frameskip), "Quantidade mínima de frames a serem pulados")
        self.params = {"skip": self.skip}

        self.mplcanvas = FigureCanvas(Figure(figsize=(6, 5), dpi=100))
        self.gui       = gui

        tab_plots      = gui_interface.load_ui("tab_plots", "tab_plots.ui")
        plots_widget   = QWidget()
        xplot          = PlotCanvas()
        yplot          = PlotCanvas()

        self.analyzer.axes_x    = xplot.figure.add_subplot(111)
        self.analyzer.axes_y    = yplot.figure.add_subplot(111)

        self.analyzer.line_x    = self.analyzer.axes_x.plot(self.analyzer.time, self.analyzer.data_x)[0]
        self.analyzer.line_y    = self.analyzer.axes_y.plot(self.analyzer.time, self.analyzer.data_y)[0]

        self.analyzer.line_x.set_linestyle("None")
        self.analyzer.line_y.set_linestyle("None")
        self.analyzer.line_x.set_marker(".")
        self.analyzer.line_y.set_marker(".")

        tab_plots.layout().addWidget(plots_widget, 0, 0, 1, 1)

        # Add the widgets containing the plots
        plots_widget.setLayout(QGridLayout())
        plots_widget.layout().addWidget(xplot, 0, 0, 1, 1)
        plots_widget.layout().addWidget(yplot, 1, 0, 1, 1)

        gui_interface.add_main_tab("tab_plots", "Plots")

        self.tab_plots     = tab_plots
        self.plots_widget  = plots_widget
        self.xplot = xplot
        self.yplot = yplot
        return True
コード例 #10
0
ファイル: StartupScreen.py プロジェクト: Moanwar/cmssw
 def createPrototypingWidget(self):
     self._prototypingDescriptionWidget = self.createDescriptionWidget(VispaWidget.ARROW_SHAPE_BOTTOM, self.PROTOTYPING_DESCRIPTION)
     
     bodyWidget = QWidget(self._prototypingDescriptionWidget)
     bodyWidget.setLayout(QGridLayout())
     bodyWidget.layout().setContentsMargins(0, 0, 0, 0)
     
     bodyWidget.layout().addWidget(QLabel("Design physics analysis:"), 0, 0)
     analysisDesignerButton = QToolButton()
     analysisDesignerButton.setText("Analysis Designer")
     analysisDesignerButton.setIcon(self._filenewIcon)
     self.connect(analysisDesignerButton, SIGNAL("clicked(bool)"), self.parent().newAnalysisDesignerSlot)
     bodyWidget.layout().addWidget(analysisDesignerButton, 0, 1)
     bodyWidget.layout().addWidget(QLabel("Create physics event:"), 1, 0)
     pxlButton = QToolButton()
     pxlButton.setText("PXL Editor")
     pxlButton.setIcon(self._filenewIcon)
     self.connect(pxlButton, SIGNAL("clicked(bool)"), self.parent().newPxlSlot)
     bodyWidget.layout().addWidget(pxlButton, 1, 1)
 
     self._prototypingDescriptionWidget.setBodyWidget(bodyWidget)
コード例 #11
0
class MinimumSizeScrollArea(QScrollArea):
    def __init__(self, parent=None):
        QScrollArea.__init__(self, parent)
        self.s = 100
        self.setMinimumSize(0, 0)
        self.__max = 250
        self.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum))
        self.__w = QWidget()
        self.setWidget(self.__w)
        self.setWidgetResizable(True)
        self.__w.setLayout(QVBoxLayout())
        self.__w.layout().setContentsMargins(0, 0, 0, 0)
        self.setFrameShape(QFrame.NoFrame)
        self.__recalcSize()

    def sizeHint(self):
        return self.__w.layout().minimumSize()

    def __recalcSize(self):
        self.setMaximumSize(self.maximumSize().width(), min(self.__max, self.__w.layout().minimumSize().height()))

    def addWidget(self, widget):
        self.__w.layout().addWidget(widget)

    def event(self, e):
        if e.type() == QEvent.LayoutRequest:
            self.__recalcSize()
        return QScrollArea.event(self, e)
コード例 #12
0
ファイル: gui_interface.py プロジェクト: brunoabud/ic
    def __init__(self, show_title, value_range,  default_value, slider_type, adjust_function):
        # The parent widget
        widget = QWidget();
        # Create a slider using based on the type provided
        slider = create_slider(slider_type, value_range, default_value)
        # Create the labels that will hold the title and the current value
        title  = QLabel(str(show_title));
        value  = QLabel(str(default_value))

        # Center the text of the title label
        title.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        title.setWordWrap(True)

        # Center the text of the value label
        value.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

        # Create and set a new Vertical BoxLayout
        widget.setLayout(QBoxLayout(QBoxLayout.TopToBottom))

        # Inserts the widget into the layout
        widget.layout().addWidget(title , 1)
        widget.layout().addWidget(slider, 2)
        widget.layout().addWidget(value , 1)

        # Remove the vertical spacing
        widget.layout().setSpacing(0)

        # A function that will clip the value to the range
        def clip(v):
            v = max(v, value_range[0])
            v = min(v, value_range[1])
            return v

        # No adjust_function is given, uses only the clip
        if adjust_function is None:
            adjust_func = clip
        # If adjust_func is given, use it and the clip
        else:
            def adjust_func(v):
                v = adjust_function(v)
                v = clip(v)
                return v
        # This function will receive the sliderMoved signal from the slider.
        # It should pass it to the adjust_func and show the returned value to
        # the user through the `value` label, so the value that user sees is
        # always correct. It also changes the _value member to the value return'
        def slider_moved(v):
            self._value = int(adjust_func(v))
            value.setText(str(self._value))

        slider.sliderMoved.connect(slider_moved)

        self._widget  = widget
        self._slider  = slider
        self._title   = title
        self._range   = value_range
        self._default = int(default_value)
        self._value   = int(default_value)
        self._adjust  = adjust_func
        self._native_title = show_title
コード例 #13
0
ファイル: blankpaper.py プロジェクト: Alwnikrotikz/lilykde
 def createWidget(self):
     w = QWidget()
     w.setLayout(QGridLayout())
     self.clef = ClefSelector(noclef=True, tab=True)
     l = QLabel(i18n("Clef:"))
     l.setBuddy(self.clef)
     w.layout().addWidget(l, 0, 0, Qt.AlignRight)
     w.layout().addWidget(self.clef, 0, 1)
     self.clef.currentIndexChanged.connect(self.clefChanged)
     self.spaceBelow = QSpinBox()
     self.spaceBelow.setRange(0, 25)
     self.spaceBelow.setValue(5)
     w.layout().addWidget(self.spaceBelow, 2, 1)
     l = QLabel(i18n("Space below:"))
     l.setBuddy(self.spaceBelow)
     w.layout().addWidget(l, 2, 0, Qt.AlignRight)
     return w
コード例 #14
0
ファイル: mainwindow.py プロジェクト: ales-erjavec/OASYS1
class OASYSSchemeInfoDialog(schemeinfo.SchemeInfoDialog):
    def __init__(self, parent=None, **kwargs):
        super().__init__(parent, **kwargs)
        # Insert a 'Working Directory' row in the editor form.
        layout = self.editor.layout()

        self.working_dir_edit = QWidget(self)
        self.working_dir_edit.setLayout(QHBoxLayout())
        self.working_dir_edit.layout().setContentsMargins(0, 0, 0, 0)

        settings = QSettings()
        self.working_dir_line = QLineEdit(self)
        self.working_dir_line.setReadOnly(True)

        cur_wd = (settings.value("output/default-working-directory",
                                 "", type=str) or
                  os.path.expanduser("~/Oasys"))

        self.working_dir_line.setText(cur_wd)
        pb = QPushButton("Change ...")
        pb.clicked.connect(self.__change_working_directory)

        self.working_dir_edit.layout().addWidget(self.working_dir_line)
        self.working_dir_edit.layout().addWidget(pb)

        layout.insertRow(
            2, self.tr("Working directory"), self.working_dir_edit)

        # Fix the widget tab order.
        item = layout.itemAt(1, QFormLayout.FieldRole)
        if item.widget() is not None:
            QWidget.setTabOrder(item.widget(), self.working_dir_line)
            QWidget.setTabOrder(self.working_dir_line, pb)

    def setScheme(self, scheme):
        super().setScheme(scheme)
        self.working_dir_line.setText(scheme.working_directory)

    def __change_working_directory(self):
        cur_wd = self.working_dir_line.text()
        new_wd = QFileDialog.getExistingDirectory(
            self, self.tr("Set working directory"), cur_wd,
        )
        if new_wd:
            self.working_dir_line.setText(new_wd)

    def title(self):
        return self.editor.title()

    def description(self):
        return self.editor.description()

    def workingDirectory(self):
        return self.working_dir_line.text()
コード例 #15
0
ファイル: StartupScreen.py プロジェクト: Moanwar/cmssw
 def createVerifyingWidget(self):
     self._verifyingDescriptionWidget = self.createDescriptionWidget(VispaWidget.ARROW_SHAPE_LEFT, self.VERIFYING_DESCRIPTION)
     
     bodyWidget = QWidget(self._verifyingDescriptionWidget)
     bodyWidget.setLayout(QGridLayout())
     bodyWidget.layout().setContentsMargins(0, 0, 0, 0)
     
     label=QLabel("Browse an existing PXL data file:")
     bodyWidget.layout().addWidget(label, 0, 0)
     analysisDesignerButton = QToolButton()
     analysisDesignerButton.setText("Open PXL file")
     analysisDesignerButton.setIcon(self._fileopenIcon)
     self.connect(analysisDesignerButton, SIGNAL("clicked(bool)"), self.parent().openPxlFileSlot)
     bodyWidget.layout().addWidget(analysisDesignerButton, 0, 1)
     self._pxlEditorRecentFilesList=QListWidget()
     self._pxlEditorRecentFilesList.setFixedSize(label.sizeHint().width()+analysisDesignerButton.sizeHint().width(),150)
     self.connect(self._pxlEditorRecentFilesList, SIGNAL("doubleClicked(QModelIndex)"), self.parent().openPxlFileSlot)
     bodyWidget.layout().addWidget(self._pxlEditorRecentFilesList, 1, 0, 1, 2)
     
     self._verifyingDescriptionWidget.setBodyWidget(bodyWidget)
コード例 #16
0
ファイル: StartupScreen.py プロジェクト: Moanwar/cmssw
 def createExecutionWidget(self):
     self._executionDescriptionWidget = self.createDescriptionWidget(VispaWidget.ARROW_SHAPE_RIGHT, self.EXECUTING_DESCRIPTION)
     
     bodyWidget = QWidget(self._executionDescriptionWidget)
     bodyWidget.setLayout(QGridLayout())
     bodyWidget.layout().setContentsMargins(0, 0, 0, 0)
     
     label=QLabel("Open and run existing analysis:")
     bodyWidget.layout().addWidget(label, 0, 0)
     analysisDesignerButton = QToolButton()
     analysisDesignerButton.setText("Open analysis file")
     analysisDesignerButton.setIcon(self._fileopenIcon)
     self.connect(analysisDesignerButton, SIGNAL("clicked(bool)"), self.parent().openAnalysisFileSlot)
     bodyWidget.layout().addWidget(analysisDesignerButton, 0, 1)
     self._analysisDesignerRecentFilesList=QListWidget()
     self._analysisDesignerRecentFilesList.setFixedSize(label.sizeHint().width()+analysisDesignerButton.sizeHint().width(),150)
     self.connect(self._analysisDesignerRecentFilesList, SIGNAL("doubleClicked(QModelIndex)"), self.parent().openAnalysisFileSlot)
     bodyWidget.layout().addWidget(self._analysisDesignerRecentFilesList, 1, 0, 1, 2)
     
     self._executionDescriptionWidget.setBodyWidget(bodyWidget)
コード例 #17
0
class ProjectTreeColumn(QWidget):

    def __init__(self, *args, **kwargs):
        super(ProjectTreeColumn, self).__init__(*args, **kwargs)
        #self._widget = QWidget()
        self._layout = QVBoxLayout()
        self._layout.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
        self.setLayout(self._layout)
        self._vbox = QVBoxLayout()
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)
        self._vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        self._buttons = []
        
        self._projects_area = QWidget()
        logger.debug("This is the projects area")
        logger.debug(self._projects_area)
        self._projects_area.setLayout(self._vbox)
        
        self._scroll_area = QScrollArea()
        self.layout().addWidget(self._scroll_area)
        self._scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self._scroll_area.setWidgetResizable(True)
        self._scroll_area.setEnabled(True)
        self._scroll_area.setWidget(self._projects_area)
        self._scroll_area.setGeometry(self.geometry())
        #self._projects_area.setGeometry(self.geometry())
        self._vbox.setGeometry(self.geometry())
        self.projects = []
        self._active_project = None
        #for each_test in range(50):
        #    button = QPushButton('Test%d' % each_test)
        #    self._buttons.append(button)
        #    self._projects_area.layout().addWidget(button)

        connections = (
            {'target': 'main_container',
            'signal_name': 'addToProject(QString)',
            'slot': self._add_file_to_project},
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)

        #TODO: check this:
        #self.connect(ide, SIGNAL("goingDown()"),
            #self.tree_projects.shutdown)
        #self.connect(self.tree_projects,
            #SIGNAL("addProjectToConsole(QString)"),
            #self._add_project_to_console)
        #self.connect(self.tree_projects,
            #SIGNAL("removeProjectFromConsole(QString)"),
            #self._remove_project_from_console)

        #def close_project_signal():
            #self.emit(SIGNAL("updateLocator()"))

        #def close_files_related_to_closed_project(project):
            #if project:
                #self.emit(SIGNAL("projectClosed(QString)"), project)
        #self.connect(self.tree_projects, SIGNAL("closeProject(QString)"),
            #close_project_signal)
        #self.connect(self.tree_projects, SIGNAL("refreshProject()"),
            #close_project_signal)
        #self.connect(self.tree_projects,
            #SIGNAL("closeFilesFromProjectClosed(QString)"),
            #close_files_related_to_closed_project)


    def install_tab(self):
        ide = IDE.get_service('ide')
        ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide)

    def open_project_folder(self):
        if settings.WORKSPACE:
            directory = settings.WORKSPACE
        else:
            directory = os.path.expanduser("~")

        folderName = QFileDialog.getExistingDirectory(self,
                self.tr("Open Project Directory"), directory)
        logger.debug("Choosing Foldername")
        if folderName:
            logger.debug("Opening %s" % folderName)
            ninjaide = IDE.get_service("ide")
            project = NProject(folderName)
            qfsm = ninjaide.filesystem.open_project(project)
            if qfsm:
                self.add_project(project)

    def _add_file_to_project(self, path):
        """Add the file for 'path' in the project the user choose here."""
        if self._active_project:
            pathProject = [self._active_project.project]
            addToProject = add_to_project.AddToProject(pathProject, self)
            addToProject.exec_()
            if not addToProject.pathSelected:
                return
            main_container = IDE.get_service('main_container')
            if not main_container:
                return
            editorWidget = main_container.get_current_editor()
            if not editorWidget.file_path:
                name = QInputDialog.getText(None,
                    self.tr("Add File To Project"), self.tr("File Name:"))[0]
                if not name:
                    QMessageBox.information(self, self.tr("Invalid Name"),
                        self.tr("The file name is empty, please enter a name"))
                    return
            else:
                name = file_manager.get_basename(editorWidget.file_path)
            path = file_manager.create_path(addToProject.pathSelected, name)
            try:
                #FIXME
                path = file_manager.store_file_content(
                    path, editorWidget.get_text(), newFile=True)
                editorWidget.nfile = path
                self.emit(SIGNAL("changeWindowTitle(QString)"), path)
                name = file_manager.get_basename(path)
                main_container.actualTab.setTabText(
                    main_container.actualTab.currentIndex(), name)
                editorWidget._file_saved()
            except file_manager.NinjaFileExistsException as ex:
                QMessageBox.information(self, self.tr("File Already Exists"),
                    (self.tr("Invalid Path: the file '%s' already exists.") %
                        ex.filename))
        else:
            pass
            # Message about no project

    def add_project(self, project):
        if project not in self.projects:
            ptree = TreeProjectsWidget(project)
            self.connect(ptree, SIGNAL("setActiveProject(PyQt_PyObject)"),
                self._set_active_project)
            self.connect(ptree, SIGNAL("closeProject(PyQt_PyObject)"),
                self._close_project)
            pmodel = project.model
            ptree.setModel(pmodel)
            ptree.header().title = project.name
            pindex = pmodel.index(pmodel.rootPath())
            ptree.setRootIndex(pindex)
            #self._widget.layout().addWidget(scrollable_wrapper(ptree))
            self._projects_area.layout().addWidget(ptree)
            if self._active_project is None:
                ptree.set_default_project()
            self.projects.append(ptree)
            ptree.setGeometry(self.geometry())

    def _close_project(self, widget):
        """Close the project related to the tree widget."""
        self.projects.remove(widget)
        if self._active_project == widget and len(self.projects) > 0:
            self.projects[0].set_default_project()
        self._widget.layout().removeWidget(widget)
        widget.deleteLater()

    def _set_active_project(self, tree_proj):
        if self._active_project is not None:
            self._active_project.set_default_project(False)
        self._active_project = tree_proj

    def close_opened_projects(self):
        for project in reversed(self.projects):
            self._close_project(project)

    def save_project(self):
        """Save all the opened files that belongs to the actual project."""
        path = self._active_project.project.path
        main_container = IDE.get_service('main_container')
        if path and main_container:
            main_container.save_project(path)

    def create_new_project(self):
        if not self.tree_projects:
            QMessageBox.information(self, self.tr("Projects Disabled"),
                self.tr("Project support has been disabled from Preferences"))
            return
        wizard = wizard_new_project.WizardNewProject(self)
        wizard.show()
コード例 #18
0
    def __setupUi(self):
        """Set up the UI.
        """
        if self.__macUnified:
            self.tab = QToolBar()

            self.addToolBar(Qt.TopToolBarArea, self.tab)
            self.setUnifiedTitleAndToolBarOnMac(True)

            # This does not seem to work
            self.setWindowFlags(self.windowFlags() & \
                                ~Qt.MacWindowToolBarButtonHint)

            self.tab.actionTriggered[QAction].connect(
                self.__macOnToolBarAction
            )

            central = QStackedWidget()

            central.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        else:
            self.tab = central = QTabWidget(self)

        self.stack = central

        self.setCentralWidget(central)

        # General Tab
        tab = QWidget()
        self.addTab(tab, self.tr("General"),
                    toolTip=self.tr("General Options"))

        form = QFormLayout()
        tab.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        nodes = QWidget(self, objectName="nodes")
        nodes.setLayout(QVBoxLayout())
        nodes.layout().setContentsMargins(0, 0, 0, 0)

        cb_anim = QCheckBox(
            self.tr("Enable node animations"),
            objectName="enable-node-animations",
            toolTip=self.tr("Enable shadow and ping animations for node "
                            "items in the scheme.")
        )
        self.bind(cb_anim, "checked", "schemeedit/enable-node-animations")
        nodes.layout().addWidget(cb_anim)

        form.addRow(self.tr("Nodes"), nodes)

        links = QWidget(self, objectName="links")
        links.setLayout(QVBoxLayout())
        links.layout().setContentsMargins(0, 0, 0, 0)

        cb_show = QCheckBox(
            self.tr("Show channel names between widgets"),
            objectName="show-channel-names",
            toolTip=self.tr("Show source and sink channel names "
                            "over the links.")
        )

        self.bind(cb_show, "checked", "schemeedit/show-channel-names")

        links.layout().addWidget(cb_show)

        form.addRow(self.tr("Links"), links)

        quickmenu = QWidget(self, objectName="quickmenu-options")
        quickmenu.setLayout(QVBoxLayout())
        quickmenu.layout().setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("On double click"),
                        toolTip=self.tr("Open quick menu on a double click "
                                        "on an empty spot in the canvas"))

        cb2 = QCheckBox(self.tr("On right click"),
                        toolTip=self.tr("Open quick menu on a right click "
                                        "on an empty spot in the canvas"))

        cb3 = QCheckBox(self.tr("On space key press"),
                        toolTip=self.tr("On Space key press while the mouse"
                                        "is hovering over the canvas."))

        cb4 = QCheckBox(self.tr("On any key press"),
                        toolTip=self.tr("On any key press while the mouse"
                                        "is hovering over the canvas."))

        self.bind(cb1, "checked", "quickmenu/trigger-on-double-click")
        self.bind(cb2, "checked", "quickmenu/trigger-on-right-click")
        self.bind(cb3, "checked", "quickmenu/trigger-on-space-key")
        self.bind(cb4, "checked", "quickmenu/trigger-on-any-key")

        quickmenu.layout().addWidget(cb1)
        quickmenu.layout().addWidget(cb2)
        quickmenu.layout().addWidget(cb3)
        quickmenu.layout().addWidget(cb4)

        form.addRow(self.tr("Open quick menu on"), quickmenu)

        startup = QWidget(self, objectName="startup-group")
        startup.setLayout(QVBoxLayout())
        startup.layout().setContentsMargins(0, 0, 0, 0)

        cb_splash = QCheckBox(self.tr("Show splash screen"), self,
                              objectName="show-splash-screen")

        cb_welcome = QCheckBox(self.tr("Show welcome screen"), self,
                                objectName="show-welcome-screen")

        self.bind(cb_splash, "checked", "startup/show-splash-screen")
        self.bind(cb_welcome, "checked", "startup/show-welcome-screen")

        startup.layout().addWidget(cb_splash)
        startup.layout().addWidget(cb_welcome)

        form.addRow(self.tr("On startup"), startup)

        toolbox = QWidget(self, objectName="toolbox-group")
        toolbox.setLayout(QVBoxLayout())
        toolbox.layout().setContentsMargins(0, 0, 0, 0)

        exclusive = QCheckBox(self.tr("Only one tab can be open at a time"))

        self.bind(exclusive, "checked", "mainwindow/toolbox-dock-exclusive")

        toolbox.layout().addWidget(exclusive)

        form.addRow(self.tr("Tool box"), toolbox)
        tab.setLayout(form)

        # Output Tab
        tab = QWidget()
        self.addTab(tab, self.tr("Output"),
                    toolTip="Output Redirection")

        form = QFormLayout()
        box = QWidget(self, objectName="streams")
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("Standard output"))
        cb2 = QCheckBox(self.tr("Standard error"))

        self.bind(cb1, "checked", "output/redirect-stdout")
        self.bind(cb2, "checked", "output/redirect-stderr")

        layout.addWidget(cb1)
        layout.addWidget(cb2)
        box.setLayout(layout)

        form.addRow(self.tr("Redirect output"), box)

        box = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        combo = QComboBox()
        combo.addItems([self.tr("Critical"),
                        self.tr("Error"),
                        self.tr("Warn"),
                        self.tr("Info"),
                        self.tr("Debug")])

        cb = QCheckBox(self.tr("Show output on 'Error'"),
                       objectName="focus-on-error")

        self.bind(combo, "currentIndex", "logging/level")
        self.bind(cb, "checked", "output/show-on-error")

        layout.addWidget(combo)
        layout.addWidget(cb)
        box.setLayout(layout)

        form.addRow(self.tr("Logging"), box)

        box = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("Stay on top"),
                        objectName="stay-on-top")

        cb2 = QCheckBox(self.tr("Dockable"),
                        objectName="output-dockable")

        self.bind(cb1, "checked", "output/stay-on-top")
        self.bind(cb2, "checked", "output/dockable")

        layout.addWidget(cb1)
        layout.addWidget(cb2)
        box.setLayout(layout)

        form.addRow(self.tr("Output window"), box)

        box = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("Open in external browser"),
                        objectName="open-in-external-browser")

        cb2 = QCheckBox(self.tr("Stay on top"),
                        objectName="help-stay-on-top")

        cb3 = QCheckBox(self.tr("Dockable"),
                        objectName="help-dockable")

        self.bind(cb1, "checked", "help/open-in-external-browser")
        self.bind(cb2, "checked", "help/stay-on-top")
        self.bind(cb3, "checked", "help/dockable")

        layout.addWidget(cb1)
        layout.addWidget(cb2)
        layout.addWidget(cb3)
        box.setLayout(layout)

        form.addRow(self.tr("Help window"), box)

        tab.setLayout(form)

        if self.__macUnified:
            # Need some sensible size otherwise mac unified toolbar 'takes'
            # the space that should be used for layout of the contents
            self.adjustSize()
コード例 #19
0
ファイル: featureform.py プロジェクト: skeenp/Roam
 def make_tab(tabwidget, name):
     widget = QWidget()
     widget.setLayout(make_layout())
     tabwidget.addTab(widget, name)
     return widget, widget.layout()
コード例 #20
0
ファイル: featureform.py プロジェクト: skeenp/Roam
def buildfromauto(formconfig, base):
    widgetsconfig = copy.deepcopy(formconfig['widgets'])

    try:
        widgetsconfig = base.get_widgets(widgetsconfig)
    except AttributeError:
        pass

    newstyle = formconfig.get("newstyle", False)
    hassections = any(config['widget'] == "Section" for config in widgetsconfig)

    def make_layout():
        if newstyle:
            return QVBoxLayout()
        else:
            layout = QFormLayout()
            layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
            return layout

    def make_tab(tabwidget, name):
        widget = QWidget()
        widget.setLayout(make_layout())
        tabwidget.addTab(widget, name)
        return widget, widget.layout()

    if hassections:
        outwidget = QTabWidget(base)
        outlayout = None
        base.setLayout(QVBoxLayout())
        base.layout().setContentsMargins(0,0,0,0)
        base.layout().addWidget(outwidget)
    else:
        outwidget = base
        outlayout = make_layout()
        outwidget.setLayout(outlayout)

    if roam.config.settings.get("form_geom_edit", False):
        geomwidget = GeomWidget()
        geomwidget.setObjectName("__geomwidget")
        outlayout.addRow("Geometry", geomwidget)

    insection = False
    for config in widgetsconfig:
        widgettype = config['widget']

        ## Make the first tab if one isn't defined already and we have other sections in the config
        if not insection and hassections and not widgettype == "Section":
            name = formconfig['label']
            tabwidget, outlayout = make_tab(outwidget, name)
            insection = True

        if widgettype == 'Section':
            # Add a spacer to the last widget
            if outlayout:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
                outlayout.addItem(QSpacerItem(10, 500))
                outlayout.addWidget(spacer)

            name = config['name']
            tabwidget, outlayout = make_tab(outwidget, name)
            installflickcharm(tabwidget)
            insection = True
            continue

        field = config['field']
        name = config.get('name', field)
        if not field:
            utils.warning("Field can't be null for {}".format(name))
            utils.warning("Skipping widget")
            continue

        label = QLabel(name)
        label.setObjectName(field + "_label")
        labelwidget = QWidget()
        labelwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        labelwidget.layout().addWidget(label)
        labelwidget.layout().setContentsMargins(0,0,0,0)

        widget = roam.editorwidgets.core.createwidget(widgettype, parent=base)
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        layoutwidget.layout().setContentsMargins(0,0,0,10)

        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            if newstyle:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
                labelwidget.layout().addWidget(spacer)
                labelwidget.layout().addWidget(savebutton)
            else:
                layoutwidget.layout().addWidget(savebutton)

        if newstyle:
            outlayout.addWidget(labelwidget)
            outlayout.addWidget(layoutwidget)
        else:
            outlayout.addRow(labelwidget, layoutwidget)

    spacer = QWidget()
    spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
    outlayout.addWidget(spacer)
    if not hassections:
        outlayout.addItem(QSpacerItem(10, 500))
        installflickcharm(outwidget)
    return base
コード例 #21
0
class preferencesDialog(QDialog):
    newMailerMessage = QtCore.Signal(str, str)
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.tmpPref = {}
        self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref'])
        self.currLocale = self.parent().prm['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
        self.audioManager = parent.audioManager
        self.mailer = emailSender(self)
        self.newMailerMessage.connect(self.popMailerMessage)
        
        self.tabWidget = QTabWidget()
        self.tabWidget.currentChanged.connect(self.tabChanged)
        self.appPrefWidget = QWidget()
        self.soundPrefWidget = QWidget()
        self.notificationPrefWidget = QWidget()
        self.eegPrefWidget = QWidget()

        #the gui widget for these are in an external dialog
        self.wavsPref = {}
        self.wavsPref['endMessageFiles'] = self.tmpPref['pref']['general']['endMessageFiles']
        self.wavsPref['endMessageFilesUse'] = self.tmpPref['pref']['general']['endMessageFilesUse']
        self.wavsPref['endMessageFilesID'] = self.tmpPref['pref']['general']['endMessageFilesID']
        self.wavsPref['endMessageLevels'] = self.tmpPref['pref']['general']['endMessageLevels']
        #GENERAL PREF
        appPrefGrid = QGridLayout()
        n = 0
        self.languageChooserLabel = QLabel(self.tr('Language (requires restart):'))
        appPrefGrid.addWidget(self.languageChooserLabel, n, 0)
        self.languageChooser = QComboBox()
        self.languageChooser.addItems(self.parent().prm['appData']['available_languages'])
        self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language']))
        self.languageChooser.currentIndexChanged[int].connect(self.onLanguageChooserChange)
        appPrefGrid.addWidget(self.languageChooser, n, 1)
        n = n+1
        self.countryChooserLabel = QLabel(self.tr('Country (requires restart):'))
        appPrefGrid.addWidget(self.countryChooserLabel, n, 0)
        self.countryChooser = QComboBox()
        self.countryChooser.addItems(self.parent().prm['appData']['available_countries'][self.tmpPref['pref']['language']])
        self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country']))
        appPrefGrid.addWidget(self.countryChooser, n, 1)
        n = n+1

        self.responseBoxLanguageChooserLabel = QLabel(self.tr('Response Box Language (requires restart):'))
        appPrefGrid.addWidget(self.responseBoxLanguageChooserLabel, n, 0)
        self.responseBoxLanguageChooser = QComboBox()
        self.responseBoxLanguageChooser.addItems(self.parent().prm['appData']['available_languages'])
        self.responseBoxLanguageChooser.setCurrentIndex(self.responseBoxLanguageChooser.findText(self.tmpPref['pref']['responseBoxLanguage']))
        self.responseBoxLanguageChooser.currentIndexChanged[int].connect(self.onResponseBoxLanguageChooserChange)
        appPrefGrid.addWidget(self.responseBoxLanguageChooser, n, 1)
        n = n+1
        self.responseBoxCountryChooserLabel = QLabel(self.tr('Response Box Country (requires restart):'))
        appPrefGrid.addWidget(self.responseBoxCountryChooserLabel, n, 0)
        self.responseBoxCountryChooser = QComboBox()
        self.responseBoxCountryChooser.addItems(self.parent().prm['appData']['available_countries'][self.tmpPref['pref']['responseBoxLanguage']])
        self.responseBoxCountryChooser.setCurrentIndex(self.responseBoxCountryChooser.findText(self.tmpPref['pref']['responseBoxCountry']))
        appPrefGrid.addWidget(self.responseBoxCountryChooser, n, 1)
        
        n = n+1
        self.csvSeparatorLabel = QLabel(self.tr('csv separator:'))
        appPrefGrid.addWidget(self.csvSeparatorLabel, n, 0)
        self.csvSeparatorWidget = QLineEdit(self.tmpPref['pref']["general"]["csvSeparator"])
        appPrefGrid.addWidget(self.csvSeparatorWidget, n, 1)
        n = n+1
        self.listenerNameWarnCheckBox = QCheckBox(self.tr('Warn if listener name missing'))
        self.listenerNameWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["listenerNameWarn"])
        appPrefGrid.addWidget(self.listenerNameWarnCheckBox, n, 0)
        n = n+1
        self.sessionLabelWarnCheckBox = QCheckBox(self.tr('Warn if session label missing'))
        self.sessionLabelWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["sessionLabelWarn"])
        appPrefGrid.addWidget(self.sessionLabelWarnCheckBox, n, 0)

        n = n+1
        self.dpCorrCheckBox = QCheckBox(self.tr('d-prime correction'))
        self.dpCorrCheckBox.setChecked(self.tmpPref['pref']['general']['dprimeCorrection'])
        self.dpCorrCheckBox.setWhatsThis(self.tr("If checked, when automatically processing result files, convert hit rates of 0 and 1 to 1/2N and 1-1/(2N) respectively, where N is the number of trials, to avoid infinite values of d'"))
        appPrefGrid.addWidget(self.dpCorrCheckBox, n, 0)

        n = n+1
        self.recursionLimitLabel = QLabel(self.tr('Max Recursion Depth (requires restart):'))
        appPrefGrid.addWidget(self.recursionLimitLabel, n, 0)
        self.recursionLimitWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["maxRecursionDepth"]))
        self.recursionLimitWidget.setValidator(QIntValidator(self))
        appPrefGrid.addWidget(self.recursionLimitWidget, n, 1)
        n = n+1

        n = n+1
        self.startupCommandLabel = QLabel(self.tr('Execute command at startup:'))
        appPrefGrid.addWidget(self.startupCommandLabel, n, 0)
        self.startupCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["startupCommand"])
        appPrefGrid.addWidget(self.startupCommandWidget, n, 1)
        n = n+1
        
        self.appPrefWidget.setLayout(appPrefGrid)
        self.appPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize)
        
        
        #SOUND PREF
        soundPrefGrid = QGridLayout()
        n = 0
        self.playChooser = QComboBox()
        self.playChooser.addItems(self.parent().prm['appData']['available_play_commands'])
        self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['sound']['playCommandType']))
        self.playChooser.currentIndexChanged[int].connect(self.onPlayChooserChange)
        self.playChooserLabel = QLabel(self.tr('Play Command:'))
        soundPrefGrid.addWidget(self.playChooserLabel, 0, 0)
        soundPrefGrid.addWidget(self.playChooser, 0, 1)
        n = n+1

        self.playCommandLabel = QLabel(self.tr('Command:'))
        soundPrefGrid.addWidget(self.playCommandLabel, n, 0)
        self.playCommandWidget = QLineEdit(self.tmpPref['pref']['sound']['playCommand'])
        if self.playChooser.currentText() != self.tr('custom'):
            self.playCommandWidget.setReadOnly(True)
        soundPrefGrid.addWidget(self.playCommandWidget, n, 1)
        n = n+1
        foo = self.playChooser.currentText()
        if foo != self.tr('custom'):
            self.playCommandLabel.hide()
            self.playCommandWidget.hide()

        #if alsaaudio is selected, provide device list chooser
        if self.parent().prm["appData"]["alsaaudioAvailable"] == True:
            self.alsaaudioPlaybackCardList = self.listAlsaaudioPlaybackCards()
            self.alsaaudioDeviceLabel = QLabel(self.tr('Device:'))
            soundPrefGrid.addWidget(self.alsaaudioDeviceLabel, n, 0)
            self.alsaaudioDeviceChooser = QComboBox()
            self.alsaaudioDeviceChooser.addItems(self.alsaaudioPlaybackCardList)
            self.alsaaudioDeviceChooser.setCurrentIndex(self.alsaaudioDeviceChooser.findText(self.tmpPref["pref"]["sound"]["alsaaudioDevice"]))
            soundPrefGrid.addWidget(self.alsaaudioDeviceChooser, n, 1)
            n = n+1
            if self.tmpPref['pref']['sound']['playCommandType'] != "alsaaudio":
                self.alsaaudioDeviceLabel.hide()
                self.alsaaudioDeviceChooser.hide()

        #if pyaudio is selected, provide device list chooser
        if self.parent().prm["appData"]["pyaudioAvailable"] == True:
            self.listPyaudioPlaybackDevices()
            self.pyaudioDeviceLabel = QLabel(self.tr('Device:'))
            soundPrefGrid.addWidget(self.pyaudioDeviceLabel, n, 0)
            self.pyaudioDeviceChooser = QComboBox()
            self.pyaudioDeviceChooser.addItems(self.pyaudioDeviceListName)
            try:
                self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref["pref"]["sound"]["pyaudioDevice"]))
            except:
                self.tmpPref["pref"]["sound"]["pyaudioDevice"] = self.pyaudioDeviceListIdx[0]
                self.parent().prm["pref"]["sound"]["pyaudioDevice"] = self.pyaudioDeviceListIdx[0]
                self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref["pref"]["sound"]["pyaudioDevice"]))
            soundPrefGrid.addWidget(self.pyaudioDeviceChooser, n, 1)
            n = n+1
            if self.tmpPref['pref']['sound']['playCommandType'] != "pyaudio":
                self.pyaudioDeviceLabel.hide()
                self.pyaudioDeviceChooser.hide()

        if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True:
            self.bufferSizeLabel = QLabel(self.tr('Buffer Size (samples):'))
            soundPrefGrid.addWidget(self.bufferSizeLabel, n, 0)
            self.bufferSizeWidget =  QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["sound"]["bufferSize"]))
            self.bufferSizeWidget.setValidator(QIntValidator(self))
            soundPrefGrid.addWidget(self.bufferSizeWidget, n, 1)
            n = n+1
            if self.tmpPref['pref']['sound']['playCommandType'] not in ["alsaaudio", "pyaudio"]:
                self.bufferSizeLabel.hide()
                self.bufferSizeWidget.hide()

        self.samplerateLabel = QLabel(self.tr('Default Sampling Rate:'))
        soundPrefGrid.addWidget(self.samplerateLabel, n, 0)
        self.samplerateWidget = QLineEdit(self.tmpPref["pref"]["sound"]["defaultSampleRate"])
        #self.samplerateWidget.setValidator(QIntValidator(self))
        soundPrefGrid.addWidget(self.samplerateWidget, n, 1)
        n = n+1

        self.nbitsLabel = QLabel(self.tr('Default Bits:'))
        self.nbitsChooser = QComboBox()
        self.nbitsChooser.addItems(self.parent().prm["nBitsChoices"])
        self.nbitsChooser.setCurrentIndex(self.parent().prm["nBitsChoices"].index(self.tmpPref["pref"]["sound"]["defaultNBits"])) 
        soundPrefGrid.addWidget(self.nbitsLabel, n, 0)
        soundPrefGrid.addWidget(self.nbitsChooser, n, 1)
        n = n+1

        self.wavmanagerLabel = QLabel(self.tr('Wav Manager (requires restart):'))
        self.wavmanagerChooser = QComboBox()
        self.wavmanagerChooser.addItems(self.parent().prm['appData']['wavmanagers'])
        self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager']))
        soundPrefGrid.addWidget(self.wavmanagerLabel, n, 0)
        soundPrefGrid.addWidget(self.wavmanagerChooser, n, 1)
        n = n+1
        
        self.writewav = QCheckBox(self.tr('Write wav file'))
        self.writewav.setChecked(self.tmpPref["pref"]["sound"]["writewav"])
        soundPrefGrid.addWidget(self.writewav, n, 0)
        n = n+1
        self.writeSndSeqSegments = QCheckBox(self.tr('Write sound sequence segments wavs'))
        self.writeSndSeqSegments.setChecked(self.tmpPref["pref"]["sound"]["writeSndSeqSegments"])
        soundPrefGrid.addWidget(self.writeSndSeqSegments, n, 0)
        n = n+1

        self.appendSilenceLabel = QLabel(self.tr('Append silence to each sound (ms):'))
        soundPrefGrid.addWidget(self.appendSilenceLabel, n, 0)
        self.appendSilenceWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["sound"]["appendSilence"]))
        soundPrefGrid.addWidget(self.appendSilenceWidget, n, 1)
        n = n+1
        
        self.soundPrefWidget.setLayout(soundPrefGrid)
        self.soundPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize)
        # NOTIFICATION PREF
        notificationPrefGrid = QGridLayout()
        
        n = 0
        
        self.playEndMessage = QCheckBox(self.tr('Play End Message'))
        self.playEndMessage.setChecked(self.tmpPref["pref"]["general"]["playEndMessage"])
        notificationPrefGrid.addWidget(self.playEndMessage, n, 0)

        self.endMessageButton = QPushButton(self.tr("Choose Wav"), self)
        self.endMessageButton.clicked.connect(self.onClickEndMessageButton)
        notificationPrefGrid.addWidget(self.endMessageButton, n, 1)
        n = n+1

        notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0)
        n = n+1
        
        self.nBlocksLabel = QLabel(self.tr('blocks before end of experiment:'))
        notificationPrefGrid.addWidget(self.nBlocksLabel, n, 1)
        self.nBlocksWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['email']['nBlocksNotify']))
        notificationPrefGrid.addWidget(self.nBlocksWidget, n, 0)
        n = n+1

        self.emailNotify = QCheckBox(self.tr('Send Notification e-mail'))
        self.emailNotify.setChecked(self.tmpPref["pref"]["email"]["notifyEnd"])
        notificationPrefGrid.addWidget(self.emailNotify, n, 0)
        n = n+1

        self.nBlocksCustomCommandLabel = QLabel(self.tr('Execute custom command:'))
        notificationPrefGrid.addWidget(self.nBlocksCustomCommandLabel, n, 0)
        self.nBlocksCustomCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["nBlocksCustomCommand"])
        notificationPrefGrid.addWidget(self.nBlocksCustomCommandWidget, n, 1)
        n = n+1


        notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0)
        n = n+1
        self.atEndLabel = QLabel(self.tr('At the end of the experiment:'))
        notificationPrefGrid.addWidget(self.atEndLabel, n, 0)
        n = n+1
        
        self.sendData = QCheckBox(self.tr('Send data via e-mail'))
        self.sendData.setChecked(self.tmpPref["pref"]["email"]["sendData"])
        notificationPrefGrid.addWidget(self.sendData, n, 0)
        n = n+1

        self.atEndCustomCommandLabel = QLabel(self.tr('Execute custom command:'))
        notificationPrefGrid.addWidget(self.atEndCustomCommandLabel, n, 0)
        self.atEndCustomCommandWidget = QLineEdit(self.tmpPref["pref"]["general"]["atEndCustomCommand"])
        notificationPrefGrid.addWidget(self.atEndCustomCommandWidget, n, 1)
        n = n+1

        notificationPrefGrid.addItem(QSpacerItem(20,20,QSizePolicy.Expanding), n, 0)
        n = n+1
        self.serverLabel = QLabel(self.tr('Outgoing server (SMTP):'))
        notificationPrefGrid.addWidget(self.serverLabel, n, 0)
        self.serverWidget = QLineEdit(self.tmpPref['pref']['email']['SMTPServer'])
        notificationPrefGrid.addWidget(self.serverWidget, n, 1)
        n = n+1

        self.serverPortLabel = QLabel(self.tr('Port:'))
        notificationPrefGrid.addWidget(self.serverPortLabel, n, 0)
        self.serverPortWidget = QLineEdit(self.currLocale.toString(self.tmpPref['pref']['email']['SMTPServerPort']))
        self.serverPortWidget.setValidator(QIntValidator(self))
        notificationPrefGrid.addWidget(self.serverPortWidget, n, 1)
        n = n+1

        self.serverSecurityLabel = QLabel(self.tr('Security:'))
        notificationPrefGrid.addWidget(self.serverSecurityLabel, n, 0)
        self.serverSecurityChooser = QComboBox()
        self.serverSecurityChooser.addItems(["TLS/SSL (a)", "TLS/SSL (b)", "none"])
        self.serverSecurityChooser.setCurrentIndex(self.serverSecurityChooser.findText(self.tmpPref['pref']['email']['SMTPServerSecurity']))
        notificationPrefGrid.addWidget(self.serverSecurityChooser, n, 1)
        n = n+1

        self.serverRequiresAuthCheckBox = QCheckBox(self.tr('Server requires authentication'))
        self.serverRequiresAuthCheckBox.setChecked(self.tmpPref["pref"]["email"]["serverRequiresAuthentication"])
        notificationPrefGrid.addWidget(self.serverRequiresAuthCheckBox, n, 0, 1, 2)
        n = n+1
        
        self.usernameLabel = QLabel(self.tr('Username:'******'pref']['email']['fromUsername'])
        notificationPrefGrid.addWidget(self.usernameWidget, n, 1)
        n = n+1
        
        self.passwordLabel = QLabel(self.tr('Password:'******'pref']['email']['fromPassword'])
        self.passwordWidget.setEchoMode(QLineEdit.Password)
        notificationPrefGrid.addWidget(self.passwordWidget, n, 1)

        n = n+1
        self.passwordWarningLabel = QLabel(self.tr('Password is NOT stored safely (see manual), use at your own risk!'))
        notificationPrefGrid.addWidget(self.passwordWarningLabel, n, 0, 1, 2)
        n = n+1
        self.testEmailButton = QPushButton(self.tr("Send test e-mail"), self)
        self.testEmailButton.clicked.connect(self.onClickTestEmailButton)
        self.testEmailButton.setToolTip(self.tr("Send a test e-mail"))
        notificationPrefGrid.addWidget(self.testEmailButton, n, 0, 1, 2)
        
        self.notificationPrefWidget.setLayout(notificationPrefGrid)
        self.notificationPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize)


        ##--#--#--#--#--
        # EEG PREF GRID
        eegPrefGrid = QGridLayout()
        
        n = 0
        self.ONTriggerLabel = QLabel(self.tr('ON Trigger:'))
        eegPrefGrid.addWidget(self.ONTriggerLabel, n, 0)
        self.ONTriggerWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["ONTrigger"]))
        eegPrefGrid.addWidget(self.ONTriggerWidget, n, 1)

        n = n+1
        self.OFFTriggerLabel = QLabel(self.tr('OFF Trigger:'))
        eegPrefGrid.addWidget(self.OFFTriggerLabel, n, 0)
        self.OFFTriggerWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["OFFTrigger"]))
        eegPrefGrid.addWidget(self.OFFTriggerWidget, n, 1)

        n = n+1
        self.triggerDurLabel = QLabel(self.tr('Trigger Duration (ms):'))
        eegPrefGrid.addWidget(self.triggerDurLabel, n, 0)
        self.triggerDurWidget = QLineEdit(self.currLocale.toString(self.tmpPref["pref"]["general"]["triggerDur"]))
        eegPrefGrid.addWidget(self.triggerDurWidget, n, 1)
      
        
        self.eegPrefWidget.setLayout(eegPrefGrid)
        self.eegPrefWidget.layout().setSizeConstraint(QLayout.SetFixedSize)

        # ........................
        self.tabWidget.addTab(self.appPrefWidget, self.tr("Genera&l"))
        self.tabWidget.addTab(self.soundPrefWidget, self.tr("Soun&d"))
        self.tabWidget.addTab(self.notificationPrefWidget, self.tr("Notification&s"))
        self.tabWidget.addTab(self.eegPrefWidget, self.tr("EE&G"))

        buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        buttonBox.button(QDialogButtonBox.Apply).clicked.connect(self.permanentApply)
        
        layout = QVBoxLayout()
        layout.addWidget(self.tabWidget)
        layout.addWidget(buttonBox)
        self.setLayout(layout)
       
    def onLanguageChooserChange(self):
        for i in range(self.countryChooser.count()):
            self.countryChooser.removeItem(0)
        self.countryChooser.addItems(self.parent().prm['appData']['available_countries'][self.languageChooser.currentText()])

    def onResponseBoxLanguageChooserChange(self):
        for i in range(self.responseBoxCountryChooser.count()):
            self.responseBoxCountryChooser.removeItem(0)
        self.responseBoxCountryChooser.addItems(self.parent().prm['appData']['available_countries'][self.responseBoxLanguageChooser.currentText()])

    def onPlayChooserChange(self):
        foo = self.playChooser.currentText()
        if foo != self.tr('custom'):
            self.playCommandLabel.hide()
            self.playCommandWidget.hide()
            self.playCommandWidget.setText(foo)
            self.playCommandWidget.setReadOnly(True)
        else:
            self.playCommandWidget.show()
            self.playCommandLabel.show()
            self.playCommandWidget.setReadOnly(False)

        if self.parent().prm["appData"]["alsaaudioAvailable"] == True:
            if foo == "alsaaudio":
                self.alsaaudioDeviceLabel.show()
                self.alsaaudioDeviceChooser.show()
               
            else:
                self.alsaaudioDeviceLabel.hide()
                self.alsaaudioDeviceChooser.hide()
             

        if self.parent().prm["appData"]["pyaudioAvailable"] == True:
            if foo == "pyaudio":
                self.pyaudioDeviceLabel.show()
                self.pyaudioDeviceChooser.show()
            else:
                self.pyaudioDeviceLabel.hide()
                self.pyaudioDeviceChooser.hide()


        if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True:
            if foo in ["alsaaudio", "pyaudio"]:
                self.bufferSizeLabel.show()
                self.bufferSizeWidget.show()
            else:
                self.bufferSizeLabel.hide()
                self.bufferSizeWidget.hide()
            
    def onClickEndMessageButton(self):
        dialog = wavListDialog(self)
        if dialog.exec_():
            self.wavsList = dialog.wavsList
            self.wavsPref = {}
            self.wavsPref['endMessageFiles'] = []
            self.wavsPref['endMessageFilesUse'] = []
            self.wavsPref['endMessageFilesID'] = []
            self.wavsPref['endMessageLevels'] = []
            keys = sorted(self.wavsList.keys())
            for key in keys:
                self.wavsPref['endMessageFiles'].append(str(self.wavsList[key]['file']))
                self.wavsPref['endMessageFilesUse'].append(self.wavsList[key]['use'])
                self.wavsPref['endMessageLevels'].append(self.wavsList[key]['level'])
                self.wavsPref['endMessageFilesID'].append(key)

    def onClickTestEmailButton(self):
        self.mailer.sendTestEmail()
        
    def popMailerMessage(self, msg, msgtype):
        if msgtype == 'critical':
            QMessageBox.critical(self, self.tr("Error"), msg)
        elif msgtype == 'warning':
            QMessageBox.warning(self, self.tr("Warning"), msg)
        elif msgtype == 'information':
            QMessageBox.information(self, self.tr("Information"), msg)
            
    def tryApply(self):
        self.tmpPref['pref']['language'] = self.tr(self.languageChooser.currentText())
        self.tmpPref['pref']['country'] = self.tr(self.countryChooser.currentText())
        self.tmpPref['pref']['responseBoxLanguage'] = self.tr(self.responseBoxLanguageChooser.currentText())
        self.tmpPref['pref']['responseBoxCountry'] = self.tr(self.responseBoxCountryChooser.currentText())
        self.tmpPref['pref']['general']['csvSeparator'] = self.csvSeparatorWidget.text()
        self.tmpPref['pref']['general']['ONTrigger'] = self.currLocale.toInt(self.ONTriggerWidget.text())[0]
        self.tmpPref['pref']['general']['OFFTrigger'] = self.currLocale.toInt(self.OFFTriggerWidget.text())[0]
        self.tmpPref['pref']['general']['triggerDur'] = self.currLocale.toDouble(self.triggerDurWidget.text())[0]
        self.tmpPref['pref']['general']['maxRecursionDepth'] = self.currLocale.toInt(self.recursionLimitWidget.text())[0]
        self.tmpPref['pref']['general']['startupCommand'] = self.startupCommandWidget.text()
        
        self.tmpPref['pref']['sound']['playCommand'] = self.tr(self.playCommandWidget.text())
        self.tmpPref['pref']['sound']['playCommandType'] = self.tr(self.playChooser.currentText())
        if self.parent().prm["appData"]["alsaaudioAvailable"] == True:
            self.tmpPref['pref']['sound']['alsaaudioDevice'] = self.alsaaudioDeviceChooser.currentText()
        if self.parent().prm["appData"]["pyaudioAvailable"] == True:
            self.tmpPref['pref']['sound']['pyaudioDevice'] =  self.pyaudioDeviceListIdx[self.pyaudioDeviceChooser.currentIndex()]
        self.tmpPref['pref']['sound']['wavmanager'] = str(self.wavmanagerChooser.currentText())
        if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True:
            self.tmpPref['pref']['sound']['bufferSize'] = self.currLocale.toInt(self.bufferSizeWidget.text())[0]
        self.tmpPref['pref']['sound']['defaultSampleRate'] = self.samplerateWidget.text()
        self.tmpPref['pref']['sound']['defaultNBits'] = self.nbitsChooser.currentText()
        self.tmpPref['pref']['sound']['appendSilence'] = self.currLocale.toInt(self.appendSilenceWidget.text())[0]
        
        self.tmpPref["pref"]["email"]["nBlocksNotify"] = self.currLocale.toInt(self.nBlocksWidget.text())[0]
        self.tmpPref["pref"]["general"]["nBlocksCustomCommand"] = self.nBlocksCustomCommandWidget.text()
        self.tmpPref["pref"]["general"]["atEndCustomCommand"] = self.atEndCustomCommandWidget.text()
        self.tmpPref["pref"]["email"]['SMTPServer'] = self.serverWidget.text()
        self.tmpPref["pref"]["email"]['SMTPServerPort'] = self.currLocale.toInt(self.serverPortWidget.text())[0]
        self.tmpPref["pref"]["email"]['fromUsername'] = self.usernameWidget.text()
        self.tmpPref["pref"]["email"]['SMTPServerSecurity'] = self.serverSecurityChooser.currentText()

        self.tmpPref["pref"]["general"]["endMessageFiles"] = self.wavsPref['endMessageFiles']
        self.tmpPref["pref"]["general"]["endMessageFilesUse"] = self.wavsPref['endMessageFilesUse']
        self.tmpPref["pref"]["general"]["endMessageFilesID"] = self.wavsPref['endMessageFilesID']
        self.tmpPref["pref"]["general"]["endMessageLevels"] = self.wavsPref['endMessageLevels']

        self.tmpPref["pref"]["email"]['fromPassword'] = self.passwordWidget.text()
        
        if self.writewav.isChecked():
            self.tmpPref['pref']['sound']['writewav'] = True
        else:
            self.tmpPref['pref']['sound']['writewav'] = False

        if self.writeSndSeqSegments.isChecked():
            self.tmpPref['pref']['sound']['writeSndSeqSegments'] = True
        else:
            self.tmpPref['pref']['sound']['writeSndSeqSegments'] = False

        if self.dpCorrCheckBox.isChecked():
            self.tmpPref['pref']['general']['dprimeCorrection'] = True
        else:
            self.tmpPref['pref']['general']['dprimeCorrection'] = False

        if self.listenerNameWarnCheckBox.isChecked():
            self.tmpPref['pref']['general']['listenerNameWarn'] = True
        else:
            self.tmpPref['pref']['general']['listenerNameWarn'] = False

        if self.sessionLabelWarnCheckBox.isChecked():
            self.tmpPref['pref']['general']['sessionLabelWarn'] = True
        else:
            self.tmpPref['pref']['general']['sessionLabelWarn'] = False

        if self.emailNotify.isChecked():
            self.tmpPref['pref']['email']['notifyEnd'] = True
        else:
            self.tmpPref['pref']['email']['notifyEnd'] = False

        if self.sendData.isChecked():
            self.tmpPref['pref']['email']['sendData'] = True
        else:
            self.tmpPref['pref']['email']['sendData'] = False

        if self.serverRequiresAuthCheckBox.isChecked():
            self.tmpPref['pref']['email']['serverRequiresAuthentication'] = True
        else:
            self.tmpPref['pref']['email']['serverRequiresAuthentication'] = False

        if self.playEndMessage.isChecked():
            self.tmpPref['pref']['general']['playEndMessage'] = True
        else:
            self.tmpPref['pref']['general']['playEndMessage'] = False

        if self.tmpPref['pref']['email']['notifyEnd'] == True or self.tmpPref['pref']['email']['sendData'] == True:
            if checkUsernameValid(self.tmpPref["pref"]["email"]['fromUsername']) == False:
                errMsg = self.tr("Username invalid. Disabling sending e-mails.")
                QMessageBox.warning(self, self.tr("Warning"), errMsg)
                self.emailNotify.setChecked(False)
                self.sendData.setChecked(False)
                self.tmpPref['pref']['email']['notifyEnd'] = False
                self.tmpPref['pref']['email']['sendData'] = False
            elif checkServerValid(self.tmpPref["pref"]["email"]['SMTPServer']) == False:
                errMsg = self.tr("SMTP server name invalid. Disabling sending e-mails.")
                QMessageBox.warning(self, self.tr("Warning"), errMsg)
                self.emailNotify.setChecked(False)
                self.sendData.setChecked(False)
                self.tmpPref['pref']['email']['notifyEnd'] = False
                self.tmpPref['pref']['email']['sendData'] = False
            
    def revertChanges(self):
        self.languageChooser.setCurrentIndex(self.languageChooser.findText(self.tmpPref['pref']['language']))
        self.countryChooser.setCurrentIndex(self.countryChooser.findText(self.tmpPref['pref']['country']))
        self.responseBoxLanguageChooser.setCurrentIndex(self.responseBoxLanguageChooser.findText(self.tmpPref['pref']['responseBoxLanguage']))
        self.responseBoxCountryChooser.setCurrentIndex(self.responseBoxCountryChooser.findText(self.tmpPref['pref']['responseBoxCountry']))
        self.csvSeparatorWidget.setText(self.tmpPref['pref']['general']['csvSeparator'])
        self.ONTriggerWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['ONTrigger']))
        self.OFFTriggerWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['OFFTrigger']))
        self.triggerDurWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['triggerDur']))
        self.recursionLimitWidget.setText(self.currLocale.toString(self.tmpPref['pref']['general']['maxRecursionDepth']))
        self.startupCommandWidget.setText(self.tmpPref['pref']['general']['startupCommand'])
        
        self.playChooser.setCurrentIndex(self.playChooser.findText(self.tmpPref['pref']['sound']['playCommandType']))
        if self.parent().prm["appData"]["alsaaudioAvailable"] == True:
            self.alsaaudioDeviceChooser.setCurrentIndex(self.alsaaudioDeviceChooser.findText(self.tmpPref['pref']['sound']['alsaaudioDevice']))
        if self.parent().prm["appData"]["pyaudioAvailable"] == True:
            self.pyaudioDeviceChooser.setCurrentIndex(self.pyaudioDeviceListIdx.index(self.tmpPref['pref']['sound']['pyaudioDevice']))
        self.wavmanagerChooser.setCurrentIndex(self.wavmanagerChooser.findText(self.tmpPref['pref']['sound']['wavmanager']))
        self.playCommandWidget.setText(self.tmpPref['pref']['sound']['playCommand'])
        if self.parent().prm["appData"]["alsaaudioAvailable"] == True or self.parent().prm["appData"]["pyaudioAvailable"] == True:
            self.bufferSizeWidget.setText(self.currLocale.toString(self.tmpPref['pref']['sound']['bufferSize']))
        self.samplerateWidget.setText(self.tmpPref['pref']['sound']['defaultSampleRate'])
        self.nbitsChooser.setCurrentIndex(self.nbitsChooser.findText(self.tmpPref['pref']['sound']['defaultNBits']))
        self.appendSilenceWidget.setText(self.currLocale.toString(self.tmpPref['pref']['sound']['appendSilence']))
       

        self.nBlocksWidget.setText(self.currLocale.toString(self.tmpPref['pref']['email']['nBlocksNotify']))
        self.nBlocksCustomCommandWidget.setText( self.tmpPref["pref"]["general"]["nBlocksCustomCommand"])
        self.atEndCustomCommandWidget.setText( self.tmpPref["pref"]["general"]["nBlocksCustomCommand"])
        self.serverWidget.setText(self.tmpPref['pref']['email']['SMTPServer'])
        self.serverPortWidget.setText(self.currLocale.toString(self.tmpPref['pref']['email']['SMTPServerPort']))
        self.usernameWidget.setText(self.tmpPref['pref']['email']['fromUsername'])
        self.passwordWidget.setText(self.tmpPref['pref']['email']['fromPassword'])
        self.serverSecurityChooser.setCurrentIndex(self.serverSecurityChooser.findText(self.tmpPref['pref']['email']['SMTPServerSecurity']))

        self.wavsPref["endMessageFiles"] = self.tmpPref["pref"]["general"]["endMessageFiles"]
        self.wavsPref["endMessageFilesUse"] = self.tmpPref["pref"]["general"]["endMessageFilesUse"]
        self.wavsPref["endMessageFilesID"] = self.tmpPref["pref"]["general"]["endMessageFilesID"]
        self.wavsPref["endMessageLevels"] = self.tmpPref["pref"]["general"]["endMessageLevels"]

        if self.playChooser.currentText() != self.tr('custom'):
            self.playCommandWidget.setReadOnly(True)
        self.writewav.setChecked(self.tmpPref["pref"]["sound"]["writewav"])
        self.writeSndSeqSegments.setChecked(self.tmpPref["pref"]["sound"]["writeSndSeqSegments"])
        self.dpCorrCheckBox.setChecked(self.tmpPref["pref"]["general"]["dprimeCorrection"])
        self.listenerNameWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["listenerNameWarn"])
        self.sessionLabelWarnCheckBox.setChecked(self.tmpPref["pref"]["general"]["sessionLabelWarn"])

        self.emailNotify.setChecked(self.tmpPref["pref"]["email"]["notifyEnd"])
        self.sendData.setChecked(self.tmpPref["pref"]["email"]["sendData"])
        self.serverRequiresAuthCheckBox.setChecked(self.tmpPref["pref"]["email"]["serverRequiresAuthentication"])
        self.playEndMessage.setChecked(self.tmpPref["pref"]["general"]["playEndMessage"])
        
    def permanentApply(self):
        self.tryApply()
        if self.parent().prm['pref']['email']['fromPassword'] != self.tmpPref['pref']['email']['fromPassword']:
            passwd = bytes(self.passwordWidget.text(),'utf-8')
            encoded_passwd = base64.b64encode(passwd)
            encoded_passwd = str(encoded_passwd, "utf-8")
            #passwd = hashlib.sha1(passwd).hexdigest()
            self.tmpPref["pref"]["email"]['fromPassword'] = encoded_passwd
            self.passwordWidget.setText(self.tmpPref['pref']['email']['fromPassword'])
        
        self.parent().prm['pref'] = copy.deepcopy(self.tmpPref['pref'])
        f = open(self.parent().prm['prefFile'], 'wb')
        pickle.dump(self.parent().prm['pref'], f)
        f.close()
        
    def tabChanged(self):
        self.tryApply()
        if self.tmpPref['pref'] != self.parent().prm['pref']:
            reply = QMessageBox.warning(self, self.tr("Warning"), self.tr('There are unsaved changes. Apply Changes?'), QMessageBox.Yes | 
                                            QMessageBox.No, QMessageBox.Yes)
            if reply == QMessageBox.Yes:
                self.permanentApply()
            else:
                self.tmpPref['pref'] = copy.deepcopy(self.parent().prm['pref'])
                self.revertChanges()

    def listAlsaaudioPlaybackCards(self):
        playbackCardList = []
        for card in alsaaudio.cards():
            try:
                alsaaudio.PCM(type=alsaaudio.PCM_PLAYBACK, mode=alsaaudio.PCM_NORMAL, card=card)
                playbackCardList.append(card)
            except:
                pass
        return playbackCardList
    
    def listPyaudioPlaybackDevices(self):
        self.pyaudioHostApiListName = []
        self.pyaudioHostApiListIdx = []
        self.pyaudioDeviceListName = []
        self.pyaudioDeviceListIdx = []
        paManager = pyaudio.PyAudio()
        nDevices = paManager.get_device_count()
        nApi = paManager.get_host_api_count()
        for i in range(nApi):
            self.pyaudioHostApiListName.append(paManager.get_host_api_info_by_index(i)['name'])
            self.pyaudioHostApiListIdx.append(paManager.get_host_api_info_by_index(i)['index'])
        for i in range(nDevices):
            thisDevInfo = paManager.get_device_info_by_index(i)
            if thisDevInfo["maxOutputChannels"] > 0:
                self.pyaudioDeviceListName.append(thisDevInfo["name"] + ' - ' + self.pyaudioHostApiListName[thisDevInfo["hostApi"]])
                self.pyaudioDeviceListIdx.append(thisDevInfo["index"])
        return 
コード例 #22
0
ファイル: snmpd.py プロジェクト: maximerobin/Ufwi
class SnmpdWidget(QFrame):
    def __init__(self, parent):
        QFrame.__init__(self, parent)
        self.parent = parent

        form = QVBoxLayout(self)
        title = QLabel("<H1>%s</H1>" % self.tr('SNMP Server Configuration'))
        form.addWidget(title)

        # Enable:
        self.enable_line = QWidget()
        self.enable_line.setLayout(QFormLayout())
        self.enable_server = QCheckBox()
        self.connect(self.enable_server, SIGNAL('stateChanged(int)'),
                     parent.setEnabled)
        self.enable_line.layout().addRow(self.tr("Enable SNMP server"),
                                         self.enable_server)
        form.addWidget(self.enable_line)
        parent.main_window.writeAccessNeeded(self.enable_server)

        # V2c list (source network, community):
        self.v2c_list_groupbox = QGroupBox()
        self.v2c_list_groupbox.setTitle(self.tr("SNMPv2c access list"))
        self.v2c_list_groupbox.setLayout(QVBoxLayout())
        self.v2c_list_edit = ListEdit()
        self.v2c_list_edit.headers = self.getColumnLabelsV2c()
        self.v2c_list_edit.readOnly = self.parent.main_window.readonly
        self.v2c_list_edit.editInPopup = True
        self.v2c_list_edit.displayUpDown = False
        self.v2c_list_edit.setColDelegate(self.createDelegateForColumnV2c)
        self.connect(self.v2c_list_edit, SIGNAL('itemDeleted'),
                     self.setModified)
        self.connect(self.v2c_list_edit, SIGNAL('itemAdded'),
                     self.setModified)
        self.connect(self.v2c_list_edit, SIGNAL('itemModified'),
                     self.setModified)
        self.v2c_list_groupbox.layout().addWidget(self.v2c_list_edit)
        parent.main_window.writeAccessNeeded(self.v2c_list_edit)
        form.addWidget(self.v2c_list_groupbox)

        # V3 list (username, auth passphrase, auth proto, privacy key, algo):
        self.v3_list_groupbox = QGroupBox()
        self.v3_list_groupbox.setTitle(self.tr("SNMPv3 access list"))
        self.v3_list_groupbox.setLayout(QVBoxLayout())
        self.v3_list_edit = ListEdit()
        self.v3_list_edit.readOnly = self.parent.main_window.readonly
        self.v3_list_edit.headers = self.getColumnLabelsV3()
        self.v3_list_edit.displayUpDown = False
        self.v3_list_edit.editInPopup = True
        self.v3_list_edit.setColDelegate(self.createDelegateForColumnV3)
        self.connect(self.v3_list_edit, SIGNAL('itemDeleted'),
                     self.setModified)
        self.connect(self.v3_list_edit, SIGNAL('itemAdded'),
                     self.setModified)
        self.connect(self.v3_list_edit, SIGNAL('itemModified'),
                     self.setModified)
        self.v3_list_groupbox.layout().addWidget(self.v3_list_edit)
        parent.main_window.writeAccessNeeded(self.v3_list_edit)
        form.addWidget(self.v3_list_groupbox)

    def createDelegateForColumnV2c(self, column):
        if column == INDEX_V2C_SOURCE:
            return EditColumnDelegate(NetworkEdit)
        return EditColumnDelegate(CommunityEdit)

    def createDelegateForColumnV3(self, column):
        if column == INDEX_V3_USERNAME:
            return EditColumnDelegate(UsernameEdit)
        elif column == INDEX_V3_AUTHENTICATION_PASS:
            return PasswordColumnDelegate(PassEdit)
        elif column == INDEX_V3_AUTHENTICATION_PROTO:
            return ComboBoxColumnDelegate(("SHA", "MD5"))
        elif column == INDEX_V3_ENCRYPTION_PASS:
            return PasswordColumnDelegate(PassEdit)
        elif column == INDEX_V3_ENCRYPTION_ALGO:
            return ComboBoxColumnDelegate(("AES", "DES"))
        return EditColumnDelegate(PassEdit)

    def getColumnLabelsV2c(self):
        return [self.tr("Source host or network"), self.tr("Community")]

    def getColumnLabelsV3(self):
        return [self.tr("Username"), self.tr("Passphrase"),
                self.tr("Protocol"), self.tr("Privacy key"),
                self.tr("Encrypting algorithm")]

    def setModified(self, *unused):
        self.parent.setModified()
コード例 #23
0
class XQueryBuilderWidget(QWidget):
    """ """
    saveRequested   = Signal()
    resetRequested  = Signal()
    cancelRequested = Signal()
    
    def __init__( self, parent = None ):
        super(XQueryBuilderWidget, self).__init__( parent )
        
        # load the user interface
        projexui.loadUi(__file__, self)
        
        self.setMinimumWidth(470)
        
        # define custom properties
        self._rules           = {}
        self._defaultQuery    = []
        self._completionTerms = []
        self._minimumCount    = 1
        
        # set default properties
        self._container = QWidget(self)
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(2)
        layout.addStretch(1)
        self._container.setLayout(layout)
        self.uiQueryAREA.setWidget(self._container)
        
        # create connections
        self.uiResetBTN.clicked.connect(  self.emitResetRequested )
        self.uiSaveBTN.clicked.connect(   self.emitSaveRequested )
        self.uiCancelBTN.clicked.connect( self.emitCancelRequested )
        
        self.resetRequested.connect(      self.reset )
    
    def addLineWidget( self, query = None ):
        """
        Adds a new line widget to the system with the given values.
        
        :param      query | (<str> term, <str> operator, <str> vlaue) || None
        """
        widget = XQueryLineWidget(self)
        widget.setTerms(sorted(self._rules.keys()))
        widget.setQuery(query)
        
        index = self._container.layout().count() - 1
        self._container.layout().insertWidget(index, widget)
        
        widget.addRequested.connect(     self.addLineWidget )
        widget.removeRequested.connect(  self.removeLineWidget )
        
        # update the remove enabled options for these widgets
        self.updateRemoveEnabled()
    
    def addRule( self, rule ):
        """
        Adds a rule to the system.
        
        :param      rule | <XQueryRule>
        """
        self._rules[rule.term()] = rule
        self.updateRules()
    
    def clear( self ):
        """
        Clears out all the widgets from the system.
        """
        for lineWidget in self.lineWidgets():
            lineWidget.setParent(None)
            lineWidget.deleteLater()
    
    def completionTerms( self ):
        """
        Returns the list of terms that will be used as a global override
        for completion terms when the query rule generates a QLineEdit instance.
        
        :return     [<str>, ..]
        """
        return self._completionTerms
    
    def count( self ):
        """
        Returns the count of the line widgets in the system.
        
        :return     <int>
        """
        return len(self.lineWidgets())
    
    def currentQuery( self ):
        """
        Returns the current query string for this widget.
        
        :return     [(<str> term, <str> operator, <str> value), ..]
        """
        widgets = self.lineWidgets()
        output = []
        for widget in widgets:
            output.append(widget.query())
        return output
    
    def defaultQuery( self ):
        """
        Returns the default query for the system.
        
        :return     [(<str> term, <str> operator, <str> value), ..]
        """
        return self._defaultQuery
    
    def keyPressEvent( self, event ):
        """
        Emits the save requested signal for this builder for when the enter
        or return press is clicked.
        
        :param      event | <QKeyEvent>
        """
        if ( event.key() in (Qt.Key_Enter, Qt.Key_Return) ):
            self.emitSaveRequested()
        
        super(XQueryBuilderWidget, self).keyPressEvent(event)
    
    def emitCancelRequested( self ):
        """
        Emits the cancel requested signal.
        """
        if ( not self.signalsBlocked() ):
            self.cancelRequested.emit()
            
    def emitResetRequested( self ):
        """
        Emits the reste requested signal.
        """
        if ( not self.signalsBlocked() ):
            self.resetRequested.emit()
            
    def emitSaveRequested( self ):
        """
        Emits the save requested signal.
        """
        if ( not self.signalsBlocked() ):
            self.saveRequested.emit()
    
    def findRule( self, term ):
        """
        Looks up a rule by the inputed term.
        
        :param      term | <str>
        
        :return     <XQueryRule> || None
        """
        return self._rules.get(str(term))
    
    def removeLineWidget( self, widget ):
        """
        Removes the line widget from the query.
        
        :param      widget | <XQueryLineWidget>
        """
        widget.setParent(None)
        widget.deleteLater()
        
        self.updateRemoveEnabled()
    
    def minimumCount( self ):
        """
        Defines the minimum number of query widgets that are allowed.
        
        :return     <int>
        """
        return self._minimumCount
    
    def lineWidgets( self ):
        """
        Returns a list of line widgets for this system.
        
        :return     [<XQueryLineWidget>, ..]
        """
        return self.findChildren(XQueryLineWidget)
    
    def reset( self ):
        """
        Resets the system to the default query.
        """
        self.setCurrentQuery(self.defaultQuery())
    
    def setCompletionTerms( self, terms ):
        """
        Sets the list of terms that will be used as a global override
        for completion terms when the query rule generates a QLineEdit instance.
        
        :param     terms | [<str>, ..]
        """
        self._completionTerms = terms
    
    def setCurrentQuery( self, query ):
        """
        Sets the query for this system to the inputed query.
        
        :param      query | [(<str> term, <str> operator, <str> value), ..]
        """
        self.clear()
        
        for entry in query:
            self.addLineWidget(entry)
        
        # make sure we have the minimum number of widgets
        for i in range(self.minimumCount() - len(query)):
            self.addLineWidget()
    
    def setDefaultQuery( self, query ):
        """
        Sets the default query that will be used when the user clicks on the \
        reset button or the reset method is called.
        
        :param      query | [(<str> term, <str> operator, <str> value), ..]
        """
        self._defaultQuery = query[:]
    
    def setMinimumCount( self, count ):
        """
        Sets the minimum number of line widgets that are allowed at any \
        given time.
        
        :param      count | <int>
        """
        self._minimumCount = count
    
    def setRules( self, rules ):
        """
        Sets all the rules for this builder.
        
        :param      rules | [<XQueryRule>, ..]
        """
        if ( type(rules) in (list, tuple) ):
            self._rules = dict([(x.term(), x) for x in rules])
            self.updateRules()
            return True
            
        elif ( type(rules) == dict ):
            self._rules = rules.copy()
            self.updateRules()
            return True
            
        else:
            return False
    
    def setTerms( self, terms ):
        """
        Sets a simple rule list by accepting a list of strings for terms.  \
        This is a convenience method for the setRules method.
        
        :param      rules | [<str> term, ..]
        """
        return self.setRules([XQueryRule(term = term) for term in terms])
    
    def updateRemoveEnabled( self ):
        """
        Updates the remove enabled baesd on the current number of line widgets.
        """
        lineWidgets = self.lineWidgets()
        count       = len(lineWidgets)
        state       = self.minimumCount() < count
        
        for widget in lineWidgets:
            widget.setRemoveEnabled(state)
    
    def updateRules( self ):
        """
        Updates the query line items to match the latest rule options.
        """
        terms = sorted(self._rules.keys())
        for child in self.lineWidgets():
            child.setTerms(terms)
コード例 #24
0
class PythonConsoleWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle(
            QCoreApplication.translate("PythonConsole", "Python Console"))

        self.settings = QSettings()

        self.shell = ShellScintilla(self)
        self.setFocusProxy(self.shell)
        self.shellOut = ShellOutputScintilla(self)
        self.tabEditorWidget = EditorTabWidget(self)

        ##------------ UI -------------------------------

        self.splitterEditor = QSplitter(self)
        self.splitterEditor.setOrientation(Qt.Horizontal)
        self.splitterEditor.setHandleWidth(6)
        self.splitterEditor.setChildrenCollapsible(True)

        self.shellOutWidget = QWidget(self)
        self.shellOutWidget.setLayout(QVBoxLayout())
        self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0)
        self.shellOutWidget.layout().addWidget(self.shellOut)

        self.splitter = QSplitter(self.splitterEditor)
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setHandleWidth(3)
        self.splitter.setChildrenCollapsible(False)
        self.splitter.addWidget(self.shellOutWidget)
        self.splitter.addWidget(self.shell)

        #self.splitterEditor.addWidget(self.tabEditorWidget)

        self.splitterObj = QSplitter(self.splitterEditor)
        self.splitterObj.setHandleWidth(3)
        self.splitterObj.setOrientation(Qt.Horizontal)
        #self.splitterObj.setSizes([0, 0])
        #self.splitterObj.setStretchFactor(0, 1)

        self.widgetEditor = QWidget(self.splitterObj)
        self.widgetFind = QWidget(self)

        self.listClassMethod = QTreeWidget(self.splitterObj)
        self.listClassMethod.setColumnCount(2)
        objInspLabel = QCoreApplication.translate("PythonConsole",
                                                  "Object Inspector")
        self.listClassMethod.setHeaderLabels([objInspLabel, ''])
        self.listClassMethod.setColumnHidden(1, True)
        self.listClassMethod.setAlternatingRowColors(True)

        #self.splitterEditor.addWidget(self.widgetEditor)
        #self.splitterObj.addWidget(self.listClassMethod)
        #self.splitterObj.addWidget(self.widgetEditor)

        # Hide side editor on start up
        self.splitterObj.hide()
        self.listClassMethod.hide()
        # Hide search widget on start up
        self.widgetFind.hide()

        sizes = self.splitter.sizes()
        self.splitter.setSizes(sizes)

        ##----------------Restore Settings------------------------------------

        self.restoreSettingsConsole()

        ##------------------Toolbar Editor-------------------------------------

        ## Action for Open File
        openFileBt = QCoreApplication.translate("PythonConsole", "Open file")
        self.openFileButton = QAction(self)
        self.openFileButton.setCheckable(False)
        self.openFileButton.setEnabled(True)
        self.openFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconOpenConsole.png"))
        self.openFileButton.setMenuRole(QAction.PreferencesRole)
        self.openFileButton.setIconVisibleInMenu(True)
        self.openFileButton.setToolTip(openFileBt)
        self.openFileButton.setText(openFileBt)

        openExtEditorBt = QCoreApplication.translate(
            "PythonConsole", "Open in external editor")
        self.openInEditorButton = QAction(self)
        self.openInEditorButton.setCheckable(False)
        self.openInEditorButton.setEnabled(True)
        self.openInEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.openInEditorButton.setMenuRole(QAction.PreferencesRole)
        self.openInEditorButton.setIconVisibleInMenu(True)
        self.openInEditorButton.setToolTip(openExtEditorBt)
        self.openInEditorButton.setText(openExtEditorBt)
        ## Action for Save File
        saveFileBt = QCoreApplication.translate("PythonConsole", "Save")
        self.saveFileButton = QAction(self)
        self.saveFileButton.setCheckable(False)
        self.saveFileButton.setEnabled(False)
        self.saveFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveConsole.png"))
        self.saveFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveFileButton.setIconVisibleInMenu(True)
        self.saveFileButton.setToolTip(saveFileBt)
        self.saveFileButton.setText(saveFileBt)
        ## Action for Save File As
        saveAsFileBt = QCoreApplication.translate("PythonConsole",
                                                  "Save As...")
        self.saveAsFileButton = QAction(self)
        self.saveAsFileButton.setCheckable(False)
        self.saveAsFileButton.setEnabled(True)
        self.saveAsFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveAsConsole.png"))
        self.saveAsFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveAsFileButton.setIconVisibleInMenu(True)
        self.saveAsFileButton.setToolTip(saveAsFileBt)
        self.saveAsFileButton.setText(saveAsFileBt)
        ## Action Cut
        cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut")
        self.cutEditorButton = QAction(self)
        self.cutEditorButton.setCheckable(False)
        self.cutEditorButton.setEnabled(True)
        self.cutEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCutEditorConsole.png"))
        self.cutEditorButton.setMenuRole(QAction.PreferencesRole)
        self.cutEditorButton.setIconVisibleInMenu(True)
        self.cutEditorButton.setToolTip(cutEditorBt)
        self.cutEditorButton.setText(cutEditorBt)
        ## Action Copy
        copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy")
        self.copyEditorButton = QAction(self)
        self.copyEditorButton.setCheckable(False)
        self.copyEditorButton.setEnabled(True)
        self.copyEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png"))
        self.copyEditorButton.setMenuRole(QAction.PreferencesRole)
        self.copyEditorButton.setIconVisibleInMenu(True)
        self.copyEditorButton.setToolTip(copyEditorBt)
        self.copyEditorButton.setText(copyEditorBt)
        ## Action Paste
        pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste")
        self.pasteEditorButton = QAction(self)
        self.pasteEditorButton.setCheckable(False)
        self.pasteEditorButton.setEnabled(True)
        self.pasteEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png"))
        self.pasteEditorButton.setMenuRole(QAction.PreferencesRole)
        self.pasteEditorButton.setIconVisibleInMenu(True)
        self.pasteEditorButton.setToolTip(pasteEditorBt)
        self.pasteEditorButton.setText(pasteEditorBt)
        ## Action Run Script (subprocess)
        runScriptEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Run script")
        self.runScriptEditorButton = QAction(self)
        self.runScriptEditorButton.setCheckable(False)
        self.runScriptEditorButton.setEnabled(True)
        self.runScriptEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunScriptConsole.png"))
        self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole)
        self.runScriptEditorButton.setIconVisibleInMenu(True)
        self.runScriptEditorButton.setToolTip(runScriptEditorBt)
        self.runScriptEditorButton.setText(runScriptEditorBt)
        ## Action Run Script (subprocess)
        commentEditorBt = QCoreApplication.translate("PythonConsole",
                                                     "Comment")
        self.commentEditorButton = QAction(self)
        self.commentEditorButton.setCheckable(False)
        self.commentEditorButton.setEnabled(True)
        self.commentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconCommentEditorConsole.png"))
        self.commentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.commentEditorButton.setIconVisibleInMenu(True)
        self.commentEditorButton.setToolTip(commentEditorBt)
        self.commentEditorButton.setText(commentEditorBt)
        ## Action Run Script (subprocess)
        uncommentEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Uncomment")
        self.uncommentEditorButton = QAction(self)
        self.uncommentEditorButton.setCheckable(False)
        self.uncommentEditorButton.setEnabled(True)
        self.uncommentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconUncommentEditorConsole.png"))
        self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.uncommentEditorButton.setIconVisibleInMenu(True)
        self.uncommentEditorButton.setToolTip(uncommentEditorBt)
        self.uncommentEditorButton.setText(uncommentEditorBt)
        ## Action for Object browser
        objList = QCoreApplication.translate("PythonConsole",
                                             "Object Inspector")
        self.objectListButton = QAction(self)
        self.objectListButton.setCheckable(True)
        self.objectListButton.setEnabled(
            self.settings.value("pythonConsole/enableObjectInsp",
                                False,
                                type=bool))
        self.objectListButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png"))
        self.objectListButton.setMenuRole(QAction.PreferencesRole)
        self.objectListButton.setIconVisibleInMenu(True)
        self.objectListButton.setToolTip(objList)
        self.objectListButton.setText(objList)
        ## Action for Find text
        findText = QCoreApplication.translate("PythonConsole", "Find Text")
        self.findTextButton = QAction(self)
        self.findTextButton.setCheckable(True)
        self.findTextButton.setEnabled(True)
        self.findTextButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png"))
        self.findTextButton.setMenuRole(QAction.PreferencesRole)
        self.findTextButton.setIconVisibleInMenu(True)
        self.findTextButton.setToolTip(findText)
        self.findTextButton.setText(findText)

        ##----------------Toolbar Console-------------------------------------

        ## Action Show Editor
        showEditor = QCoreApplication.translate("PythonConsole", "Show editor")
        self.showEditorButton = QAction(self)
        self.showEditorButton.setEnabled(True)
        self.showEditorButton.setCheckable(True)
        self.showEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.showEditorButton.setMenuRole(QAction.PreferencesRole)
        self.showEditorButton.setIconVisibleInMenu(True)
        self.showEditorButton.setToolTip(showEditor)
        self.showEditorButton.setText(showEditor)
        ## Action for Clear button
        clearBt = QCoreApplication.translate("PythonConsole", "Clear console")
        self.clearButton = QAction(self)
        self.clearButton.setCheckable(False)
        self.clearButton.setEnabled(True)
        self.clearButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClearConsole.png"))
        self.clearButton.setMenuRole(QAction.PreferencesRole)
        self.clearButton.setIconVisibleInMenu(True)
        self.clearButton.setToolTip(clearBt)
        self.clearButton.setText(clearBt)
        ## Action for settings
        optionsBt = QCoreApplication.translate("PythonConsole", "Settings")
        self.optionsButton = QAction(self)
        self.optionsButton.setCheckable(False)
        self.optionsButton.setEnabled(True)
        self.optionsButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSettingsConsole.png"))
        self.optionsButton.setMenuRole(QAction.PreferencesRole)
        self.optionsButton.setIconVisibleInMenu(True)
        self.optionsButton.setToolTip(optionsBt)
        self.optionsButton.setText(optionsBt)
        ## Action menu for class
        actionClassBt = QCoreApplication.translate("PythonConsole",
                                                   "Import Class")
        self.actionClass = QAction(self)
        self.actionClass.setCheckable(False)
        self.actionClass.setEnabled(True)
        self.actionClass.setIcon(
            QgsApplication.getThemeIcon("console/iconClassConsole.png"))
        self.actionClass.setMenuRole(QAction.PreferencesRole)
        self.actionClass.setIconVisibleInMenu(True)
        self.actionClass.setToolTip(actionClassBt)
        self.actionClass.setText(actionClassBt)
        ## Import Processing class
        loadProcessingBt = QCoreApplication.translate(
            "PythonConsole", "Import Processing class")
        self.loadProcessingButton = QAction(self)
        self.loadProcessingButton.setCheckable(False)
        self.loadProcessingButton.setEnabled(True)
        self.loadProcessingButton.setIcon(
            QgsApplication.getThemeIcon("console/iconProcessingConsole.png"))
        self.loadProcessingButton.setMenuRole(QAction.PreferencesRole)
        self.loadProcessingButton.setIconVisibleInMenu(True)
        self.loadProcessingButton.setToolTip(loadProcessingBt)
        self.loadProcessingButton.setText(loadProcessingBt)
        ## Import QtCore class
        loadQtCoreBt = QCoreApplication.translate("PythonConsole",
                                                  "Import PyQt.QtCore class")
        self.loadQtCoreButton = QAction(self)
        self.loadQtCoreButton.setCheckable(False)
        self.loadQtCoreButton.setEnabled(True)
        self.loadQtCoreButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtCoreConsole.png"))
        self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtCoreButton.setIconVisibleInMenu(True)
        self.loadQtCoreButton.setToolTip(loadQtCoreBt)
        self.loadQtCoreButton.setText(loadQtCoreBt)
        ## Import QtGui class
        loadQtGuiBt = QCoreApplication.translate("PythonConsole",
                                                 "Import PyQt.QtGui class")
        self.loadQtGuiButton = QAction(self)
        self.loadQtGuiButton.setCheckable(False)
        self.loadQtGuiButton.setEnabled(True)
        self.loadQtGuiButton.setIcon(
            QgsApplication.getThemeIcon("console/iconQtGuiConsole.png"))
        self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtGuiButton.setIconVisibleInMenu(True)
        self.loadQtGuiButton.setToolTip(loadQtGuiBt)
        self.loadQtGuiButton.setText(loadQtGuiBt)
        ## Action for Run script
        runBt = QCoreApplication.translate("PythonConsole", "Run command")
        self.runButton = QAction(self)
        self.runButton.setCheckable(False)
        self.runButton.setEnabled(True)
        self.runButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunConsole.png"))
        self.runButton.setMenuRole(QAction.PreferencesRole)
        self.runButton.setIconVisibleInMenu(True)
        self.runButton.setToolTip(runBt)
        self.runButton.setText(runBt)
        ## Help action
        helpBt = QCoreApplication.translate("PythonConsole", "Help")
        self.helpButton = QAction(self)
        self.helpButton.setCheckable(False)
        self.helpButton.setEnabled(True)
        self.helpButton.setIcon(
            QgsApplication.getThemeIcon("console/iconHelpConsole.png"))
        self.helpButton.setMenuRole(QAction.PreferencesRole)
        self.helpButton.setIconVisibleInMenu(True)
        self.helpButton.setToolTip(helpBt)
        self.helpButton.setText(helpBt)

        self.toolBar = QToolBar()
        self.toolBar.setEnabled(True)
        self.toolBar.setFocusPolicy(Qt.NoFocus)
        self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBar.setLayoutDirection(Qt.LeftToRight)
        self.toolBar.setIconSize(QSize(16, 16))
        self.toolBar.setMovable(False)
        self.toolBar.setFloatable(False)
        self.toolBar.addAction(self.clearButton)
        self.toolBar.addAction(self.actionClass)
        self.toolBar.addAction(self.runButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.showEditorButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.optionsButton)
        self.toolBar.addAction(self.helpButton)

        self.toolBarEditor = QToolBar()
        self.toolBarEditor.setEnabled(False)
        self.toolBarEditor.setFocusPolicy(Qt.NoFocus)
        self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBarEditor.setLayoutDirection(Qt.LeftToRight)
        self.toolBarEditor.setIconSize(QSize(16, 16))
        self.toolBarEditor.setMovable(False)
        self.toolBarEditor.setFloatable(False)
        self.toolBarEditor.addAction(self.openFileButton)
        self.toolBarEditor.addAction(self.openInEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.saveFileButton)
        self.toolBarEditor.addAction(self.saveAsFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.findTextButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.cutEditorButton)
        self.toolBarEditor.addAction(self.copyEditorButton)
        self.toolBarEditor.addAction(self.pasteEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.commentEditorButton)
        self.toolBarEditor.addAction(self.uncommentEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.objectListButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.runScriptEditorButton)

        ## Menu Import Class
        self.classMenu = QMenu()
        self.classMenu.addAction(self.loadProcessingButton)
        self.classMenu.addAction(self.loadQtCoreButton)
        self.classMenu.addAction(self.loadQtGuiButton)
        cM = self.toolBar.widgetForAction(self.actionClass)
        cM.setMenu(self.classMenu)
        cM.setPopupMode(QToolButton.InstantPopup)

        self.widgetButton = QWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButton.sizePolicy().hasHeightForWidth())
        self.widgetButton.setSizePolicy(sizePolicy)

        self.widgetButtonEditor = QWidget(self.widgetEditor)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButtonEditor.sizePolicy().hasHeightForWidth())
        self.widgetButtonEditor.setSizePolicy(sizePolicy)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.shellOut.sizePolicy().hasHeightForWidth())
        self.shellOut.setSizePolicy(sizePolicy)

        self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        ##------------ Layout -------------------------------

        self.mainLayout = QGridLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1)
        self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1)

        self.shellOutWidget.layout().insertWidget(0, self.toolBar)

        self.layoutEditor = QGridLayout(self.widgetEditor)
        self.layoutEditor.setMargin(0)
        self.layoutEditor.setSpacing(0)
        self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1)
        self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1)

        ## Layout for the find widget
        self.layoutFind = QGridLayout(self.widgetFind)
        self.layoutFind.setContentsMargins(0, 0, 0, 0)
        self.lineEditFind = QgsFilterLineEdit()
        placeHolderTxt = QCoreApplication.translate("PythonConsole",
                                                    "Enter text to find...")

        if pyqtconfig.Configuration().qt_version >= 0x40700:
            self.lineEditFind.setPlaceholderText(placeHolderTxt)
        else:
            self.lineEditFind.setToolTip(placeHolderTxt)
        self.findNextButton = QToolButton()
        self.findNextButton.setEnabled(False)
        toolTipfindNext = QCoreApplication.translate("PythonConsole",
                                                     "Find Next")
        self.findNextButton.setToolTip(toolTipfindNext)
        self.findNextButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchNextEditorConsole.png"))
        self.findNextButton.setIconSize(QSize(24, 24))
        self.findNextButton.setAutoRaise(True)
        self.findPrevButton = QToolButton()
        self.findPrevButton.setEnabled(False)
        toolTipfindPrev = QCoreApplication.translate("PythonConsole",
                                                     "Find Previous")
        self.findPrevButton.setToolTip(toolTipfindPrev)
        self.findPrevButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchPrevEditorConsole.png"))
        self.findPrevButton.setIconSize(QSize(24, 24))
        self.findPrevButton.setAutoRaise(True)
        self.caseSensitive = QCheckBox()
        caseSensTr = QCoreApplication.translate("PythonConsole",
                                                "Case Sensitive")
        self.caseSensitive.setText(caseSensTr)
        self.wholeWord = QCheckBox()
        wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word")
        self.wholeWord.setText(wholeWordTr)
        self.wrapAround = QCheckBox()
        self.wrapAround.setChecked(True)
        wrapAroundTr = QCoreApplication.translate("PythonConsole",
                                                  "Wrap Around")
        self.wrapAround.setText(wrapAroundTr)
        self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1)
        self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1)
        self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1)
        self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1)
        self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1)
        self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1)

        ##------------ Add first Tab in Editor -------------------------------

        #self.tabEditorWidget.newTabEditor(tabName='first', filename=None)

        ##------------ Signal -------------------------------

        self.findTextButton.toggled.connect(self.findTextEditor)
        self.objectListButton.toggled.connect(self.toggleObjectListWidget)
        self.commentEditorButton.triggered.connect(self.commentCode)
        self.uncommentEditorButton.triggered.connect(self.uncommentCode)
        self.runScriptEditorButton.triggered.connect(self.runScriptEditor)
        self.cutEditorButton.triggered.connect(self.cutEditor)
        self.copyEditorButton.triggered.connect(self.copyEditor)
        self.pasteEditorButton.triggered.connect(self.pasteEditor)
        self.showEditorButton.toggled.connect(self.toggleEditor)
        self.clearButton.triggered.connect(self.shellOut.clearConsole)
        self.optionsButton.triggered.connect(self.openSettings)
        self.loadProcessingButton.triggered.connect(self.processing)
        self.loadQtCoreButton.triggered.connect(self.qtCore)
        self.loadQtGuiButton.triggered.connect(self.qtGui)
        self.runButton.triggered.connect(self.shell.entered)
        self.openFileButton.triggered.connect(self.openScriptFile)
        self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor)
        self.saveFileButton.triggered.connect(self.saveScriptFile)
        self.saveAsFileButton.triggered.connect(self.saveAsScriptFile)
        self.helpButton.triggered.connect(self.openHelp)
        self.connect(self.listClassMethod,
                     SIGNAL('itemClicked(QTreeWidgetItem*, int)'),
                     self.onClickGoToLine)
        self.lineEditFind.returnPressed.connect(self._findText)
        self.findNextButton.clicked.connect(self._findNext)
        self.findPrevButton.clicked.connect(self._findPrev)
        self.lineEditFind.textChanged.connect(self._textFindChanged)

    def _findText(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(True)

    def _findNext(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(True)

    def _findPrev(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(False)

    def _textFindChanged(self):
        if self.lineEditFind.text():
            self.findNextButton.setEnabled(True)
            self.findPrevButton.setEnabled(True)
        else:
            self.lineEditFind.setStyleSheet('')
            self.findNextButton.setEnabled(False)
            self.findPrevButton.setEnabled(False)

    def onClickGoToLine(self, item, column):
        tabEditor = self.tabEditorWidget.currentWidget().newEditor
        if item.text(1) == 'syntaxError':
            check = tabEditor.syntaxCheck(fromContextMenu=False)
            if check and not tabEditor.isReadOnly():
                self.tabEditorWidget.currentWidget().save()
            return
        linenr = int(item.text(1))
        itemName = str(item.text(0))
        charPos = itemName.find(' ')
        if charPos != -1:
            objName = itemName[0:charPos]
        else:
            objName = itemName
        tabEditor.goToLine(objName, linenr)

    def processing(self):
        self.shell.commandConsole('processing')

    def qtCore(self):
        self.shell.commandConsole('qtCore')

    def qtGui(self):
        self.shell.commandConsole('qtGui')

    def toggleEditor(self, checked):
        self.splitterObj.show() if checked else self.splitterObj.hide()
        if not self.tabEditorWidget:
            self.tabEditorWidget.enableToolBarEditor(checked)
            self.tabEditorWidget.restoreTabsOrAddNew()

    def toggleObjectListWidget(self, checked):
        self.listClassMethod.show() if checked else self.listClassMethod.hide()

    def findTextEditor(self, checked):
        self.widgetFind.show() if checked else self.widgetFind.hide()

    def pasteEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.paste()

    def cutEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.cut()

    def copyEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.copy()

    def runScriptEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.runScriptCode()

    def commentCode(self):
        self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(True)

    def uncommentCode(self):
        self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(False)

    def openScriptFileExtEditor(self):
        tabWidget = self.tabEditorWidget.currentWidget()
        path = tabWidget.path
        import subprocess
        try:
            subprocess.Popen([os.environ['EDITOR'], path])
        except KeyError:
            QDesktopServices.openUrl(QUrl.fromLocalFile(path))

    def openScriptFile(self):
        lastDirPath = self.settings.value("pythonConsole/lastDirPath",
                                          QDir.home())
        openFileTr = QCoreApplication.translate("PythonConsole", "Open File")
        fileList = QFileDialog.getOpenFileNames(self, openFileTr, lastDirPath,
                                                "Script file (*.py)")
        if fileList:
            for pyFile in fileList:
                for i in range(self.tabEditorWidget.count()):
                    tabWidget = self.tabEditorWidget.widget(i)
                    if tabWidget.path == pyFile:
                        self.tabEditorWidget.setCurrentWidget(tabWidget)
                        break
                else:
                    tabName = QFileInfo(pyFile).fileName()
                    self.tabEditorWidget.newTabEditor(tabName, pyFile)

                    lastDirPath = QFileInfo(pyFile).path()
                    self.settings.setValue("pythonConsole/lastDirPath", pyFile)
                    self.updateTabListScript(pyFile, action='append')

    def saveScriptFile(self):
        tabWidget = self.tabEditorWidget.currentWidget()
        try:
            tabWidget.save()
        except (IOError, OSError) as error:
            msgText = QCoreApplication.translate(
                'PythonConsole',
                'The file <b>{0}</b> could not be saved. Error: {1}').format(
                    tabWidget.path, error.strerror)
            self.callWidgetMessageBarEditor(msgText, 2, False)

    def saveAsScriptFile(self, index=None):
        tabWidget = self.tabEditorWidget.currentWidget()
        if not index:
            index = self.tabEditorWidget.currentIndex()
        if not tabWidget.path:
            fileName = self.tabEditorWidget.tabText(index) + '.py'
            folder = self.settings.value("pythonConsole/lastDirPath",
                                         QDir.home())
            pathFileName = os.path.join(folder, fileName)
            fileNone = True
        else:
            pathFileName = tabWidget.path
            fileNone = False
        saveAsFileTr = QCoreApplication.translate("PythonConsole",
                                                  "Save File As")
        filename = QFileDialog.getSaveFileName(self, saveAsFileTr,
                                               pathFileName,
                                               "Script file (*.py)")
        if filename:
            try:
                tabWidget.save(filename)
            except (IOError, OSError) as error:
                msgText = QCoreApplication.translate(
                    'PythonConsole',
                    'The file <b>{0}</b> could not be saved. Error: {1}'
                ).format(tabWidget.path, error.strerror)
                self.callWidgetMessageBarEditor(msgText, 2, False)
                if fileNone:
                    tabWidget.path = None
                else:
                    tabWidget.path = pathFileName
                return

            if not fileNone:
                self.updateTabListScript(pathFileName, action='remove')

    def openHelp(self):
        QgsContextHelp.run("PythonConsole")

    def openSettings(self):
        if optionsDialog(self).exec_():
            self.shell.refreshSettingsShell()
            self.shellOut.refreshSettingsOutput()
            self.tabEditorWidget.refreshSettingsEditor()

    def callWidgetMessageBar(self, text):
        self.shellOut.widgetMessageBar(iface, text)

    def callWidgetMessageBarEditor(self, text, level, timed):
        self.tabEditorWidget.widgetMessageBar(iface, text, level, timed)

    def updateTabListScript(self, script, action=None):
        if action == 'remove':
            self.tabListScript.remove(script)
        elif action == 'append':
            if not self.tabListScript:
                self.tabListScript = []
            if script not in self.tabListScript:
                self.tabListScript.append(script)
        else:
            self.tabListScript = []
        self.settings.setValue("pythonConsole/tabScripts", self.tabListScript)

    def saveSettingsConsole(self):
        self.settings.setValue("pythonConsole/splitterConsole",
                               self.splitter.saveState())
        self.settings.setValue("pythonConsole/splitterObj",
                               self.splitterObj.saveState())
        self.settings.setValue("pythonConsole/splitterEditor",
                               self.splitterEditor.saveState())

        self.shell.writeHistoryFile(True)

    def restoreSettingsConsole(self):
        storedTabScripts = self.settings.value("pythonConsole/tabScripts", [])
        self.tabListScript = storedTabScripts
        self.splitter.restoreState(
            self.settings.value("pythonConsole/splitterConsole", QByteArray()))
        self.splitterEditor.restoreState(
            self.settings.value("pythonConsole/splitterEditor", QByteArray()))
        self.splitterObj.restoreState(
            self.settings.value("pythonConsole/splitterObj", QByteArray()))
コード例 #25
0
class XOrbQueryContainer(QWidget):
    """ """
    entriesUpdated = qt.Signal()
    enterCompoundRequested = qt.Signal(object, object)
    exitCompoundRequested = qt.Signal()

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

        # load the user interface
        projexui.loadUi(__file__, self)

        # define custom properties
        self._queryWidget = parent
        self._entryWidget = QWidget(self)
        self._currentJoiner = QueryCompound.Op.And

        layout = QVBoxLayout()
        layout.addStretch(1)
        layout.setSpacing(3)
        self._entryWidget.setLayout(layout)
        self.uiQueryAREA.setWidget(self._entryWidget)

        # set default properties
        self.setContextMenuPolicy(Qt.CustomContextMenu)

        # create connections (use old-style syntax or PySide errors)
        self.connect(self.uiBackBTN, SIGNAL('clicked()'), self.exitCompound)
        self.entriesUpdated.connect(self.refreshEntries)

    def addEntry(self, query=None, entry=None):
        if query is None:
            query = Query()

        layout = self._entryWidget.layout()
        index = layout.count() - 1
        if entry:
            index = layout.indexOf(entry) + 1

        widget = XOrbQueryEntryWidget(self, self.tableType())
        layout.insertWidget(index, widget)

        widget.setQuery(query)

        if not self.signalsBlocked():
            self.entriesUpdated.emit()

        return widget

    def checkedEntries(self):
        """
        Returns the widgets that are checked for this widget.
        
        :return     [<XOrbQueryEntryWidget>, ..]
        """
        return [entry for entry in self.entries() if entry.isChecked()]

    def clear(self):
        """
        Clears out the widgets for this query builder.
        """
        layout = self._entryWidget.layout()
        for i in range(layout.count() - 1):
            widget = layout.itemAt(i).widget()
            widget.close()

    def createCompoundFromChecked(self):
        """
        Creates a new compound query from the checked entry list.
        
        :return     <orb.QueryCompound>
        """
        checked_entries = self.checkedEntries()

        if len(checked_entries) <= 1:
            return QueryCompound()

        self.setUpdatesEnabled(False)
        joiner = self.currentJoiner()
        query = Query()
        for entry in checked_entries:
            if joiner == QueryCompound.Op.And:
                query &= entry.query()
            else:
                query |= entry.query()

        # clear out the existing containers
        first = checked_entries[0]
        first.setQuery(query)
        first.setChecked(False)

        layout = self._entryWidget.layout()
        for i in range(len(checked_entries) - 1, 0, -1):
            w = checked_entries[i]
            layout.takeAt(layout.indexOf(w))
            w.close()

        self.refreshEntries()
        self.setUpdatesEnabled(True)

        if not self.signalsBlocked():
            self.enterCompound(first, query)

    def currentJoiner(self):
        return self._currentJoiner

    def enterCompound(self, entry, query):
        # enter an existing compound
        if QueryCompound.typecheck(query):
            self.enterCompoundRequested.emit(entry, query)

        # create a new compound from the checked entries
        else:
            self.createCompoundFromChecked()

    def entries(self):
        """
        Returns the entry widgets for this widget.
        
        :return     [<XOrbQueryEntryWidget>, ..]
        """
        layout = self._entryWidget.layout()
        output = []
        for i in range(layout.count() - 1):
            widget = layout.itemAt(i).widget()
            if not isinstance(widget, XOrbQueryEntryWidget):
                continue
            output.append(widget)
        return output

    def exitCompound(self):
        self.exitCompoundRequested.emit()

    def isNull(self):
        """
        Returns whether or not any widgets have been defined for this
        container yet.
        
        :return     <bool>
        """
        return self._entryWidget.layout().count() <= 1

    def moveDown(self, entry):
        """
        Moves the current query down one entry.
        """
        if not entry:
            return

        entries = self.entries()
        next = entries[entries.index(entry) + 1]

        entry_q = entry.query()
        next_q = next.query()

        next.setQuery(entry_q)
        entry.setQuery(next_q)

    def moveUp(self, entry):
        """
        Moves the current query down up one entry.
        """
        if not entry:
            return

        entries = self.entries()
        next = entries[entries.index(entry) - 1]

        entry_q = entry.query()
        next_q = next.query()

        next.setQuery(entry_q)
        entry.setQuery(next_q)

    def pluginFactory(self):
        """
        Returns the plugin factory for this widget.  You can define a custom
        factory for handling specific columns or column types based on your
        table type.
        
        :return     <XOrbQueryPluginFactory>
        """
        return self._queryWidget.pluginFactory()

    def query(self):
        """
        Returns the query that is defined by this current panel.
        
        :return     <orb.Query>
        """
        joiner = self.currentJoiner()
        query = Query()
        for entry in self.entries():
            if joiner == QueryCompound.Op.And:
                query &= entry.query()
            else:
                query |= entry.query()

        query.setName(self.uiNameTXT.text())

        return query

    def queryWidget(self):
        """
        Returns the query widget linked with this container.
        
        :return     <XOrbQueryWidget>
        """
        return self._queryWidget

    def removeEntry(self, entry):
        if not entry:
            return

        layout = self._entryWidget.layout()
        if layout.count() == 2:
            print 'clearing query'
            entry.setQuery(Query())
            return

        layout.takeAt(layout.indexOf(entry))
        entry.close()

        if not self.signalsBlocked():
            self.entriesUpdated.emit()

    def refreshEntries(self):
        layout = self._entryWidget.layout()
        for i in range(layout.count() - 1):
            widget = layout.itemAt(i).widget()
            widget.setFirst(i == 0)
            widget.setLast(i == (layout.count() - 2))

    def setCurrentJoiner(self, joiner):
        self._currentJoiner = joiner
        layout = self._entryWidget.layout()
        for i in range(layout.count() - 1):
            widget = layout.itemAt(i).widget()
            widget.setJoiner(joiner)

    def setQuery(self, query):
        """
        Sets the query for this wigdet to the inputed query instance.
        
        :param      query | <orb.Query> || <orb.QueryCompound>
        """
        if not self.isNull() and hash(query) == hash(self.query()):
            return

        # add entries
        table = self.tableType()

        self.setUpdatesEnabled(False)
        self.blockSignals(True)
        self.clear()

        if query is None or table is None:
            self.setEnabled(False)
            self.setUpdatesEnabled(True)
            self.blockSignals(False)
            return
        else:
            self.setEnabled(True)

        # load the queries for this item
        if QueryCompound.typecheck(query):
            queries = query.queries()
            self.setCurrentJoiner(query.operatorType())
        else:
            queries = [query]

        self.uiNameTXT.setText(query.name())

        layout = self._entryWidget.layout()
        for index, query in enumerate(queries):
            widget = self.addEntry(query)
            widget.setFirst(index == 0)
            widget.setLast(index == (len(queries) - 1))
            widget.setJoiner(self.currentJoiner())

        self.setUpdatesEnabled(True)
        self.blockSignals(False)

    def setShowBack(self, state):
        # check to see if we're working on the current query
        self.uiBackBTN.setVisible(state)
        self.uiNameTXT.setVisible(state)

    def tableType(self):
        """
        Returns the table type instance for this widget.
        
        :return     <subclass of orb.Table>
        """
        return self._queryWidget.tableType()
コード例 #26
0
ファイル: gui.py プロジェクト: hannesrauhe/lunchinator
class PrivacyGUI(QWidget):
    def __init__(self, parent, logger):
        super(PrivacyGUI, self).__init__(parent)
       
        self.logger = logger
        self._actionModel = PeerActionsModel(self, self.logger)
        
        self._initActionList()
        self._initSettingsWidget()
        mainWidget = self._initMainWidget()
        
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(mainWidget)
        
        get_notification_center().connectPeerActionsAdded(self._peerActionsAdded)
        get_notification_center().connectPeerActionsRemoved(self._peerActionsRemoved)
        
    def finish(self):
        get_notification_center().disconnectPeerActionsAdded(self._peerActionsAdded)
        get_notification_center().disconnectPeerActionsRemoved(self._peerActionsRemoved)
        self._clearSettingsWidget()
        
    @loggingSlot(object)
    def _peerActionsAdded(self, added):
        self._actionModel.addPeerActions(added)
    
    @loggingSlot(object)
    def _peerActionsRemoved(self, removed):
        self._actionModel.removePeerActions(removed)
        
    def _initActionList(self):  
        self._actionList = QTreeView(self)
        self._actionList.setAlternatingRowColors(True)
        self._actionList.setHeaderHidden(False)
        self._actionList.setItemsExpandable(True)
        self._actionList.setIndentation(15)
        self._actionList.setModel(self._actionModel)
        self._actionList.expandAll()
        self._actionList.setSelectionMode(QTreeView.SingleSelection)
        self._actionList.selectionModel().selectionChanged.connect(self._displaySettings)
        
        self._actionList.setObjectName(u"__action_list")
        self._actionList.setFrameShape(QFrame.StyledPanel)

    def _initSettingsWidget(self):        
        self._settingsWidget = QWidget(self)
        settingsLayout = QVBoxLayout(self._settingsWidget)
        settingsLayout.setContentsMargins(0, 0, 0, 0)

    def _initMainWidget(self):
        split = QSplitter(Qt.Horizontal, self)
        split.addWidget(self._actionList)
        split.addWidget(self._settingsWidget)
        split.setStretchFactor(0, 0)
        split.setStretchFactor(1, 1)
        return split
    
    def hideEvent(self, event):
        self._clearSettingsWidget()
        return QWidget.hideEvent(self, event)
    
    def showEvent(self, event):
        self._displaySettings(self._actionList.selectionModel().selection())
        return QWidget.showEvent(self, event)
    
    def _clearSettingsWidget(self):
        layout = self._settingsWidget.layout()
        
        child = layout.takeAt(0)
        while child != None:
            child.widget().finish()
            child.widget().deleteLater()
            child = layout.takeAt(0)
            
    @loggingSlot(QItemSelection, QItemSelection)
    def _displaySettings(self, newSelection, _oldSelection=None):
        self._clearSettingsWidget()
        if len(newSelection.indexes()) > 0:
            index = iter(newSelection.indexes()).next()
            action = index.data(PeerActionsModel.ACTION_ROLE).toPyObject()
            if action is None:
                return # root item
            if action.hasCategories():
                self._settingsWidget.layout().addWidget(MultipleCategoriesView(action, self._settingsWidget, self.logger))
            else:
                self._settingsWidget.layout().addWidget(SingleCategoryView(action, self._settingsWidget, self.logger))
コード例 #27
0
class generateSoundDialog(QDialog):
    def __init__(self, parent, sndType):
        QDialog.__init__(self, parent)

        self.prm = parent.prm
        self.currLocale = self.parent().prm['data']['currentLocale']
        self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator)
        self.vbl = QVBoxLayout()
        self.hbl = QHBoxLayout()
        self.grid_0 = QGridLayout()
        self.grid_1 = QGridLayout()

        if sndType == "Harmonic Complex":
            self.execString = "harm_compl"
        elif sndType == "Silence":
            self.execString = "silence"
        elif sndType == "FM Tone":
            self.execString = "fm_tone"
        elif sndType == "AM Tone":
            self.execString = "am_tone"

        self.nrows = 0
        #SOUND LABEL
        soundLabelLabel = QLabel(self.tr('Sound Label: '))
        self.soundLabelWidget = QLineEdit(self.tr(sndType))
        self.grid_0.addWidget(soundLabelLabel, self.nrows, 0)
        self.grid_0.addWidget(self.soundLabelWidget, self.nrows, 1)
        self.nrows = self.nrows + 1
        #SAMPLING RATE
        sampRateLabel = QLabel(self.tr('Sampling Rate'))
        defaultSampRate = 48000
        self.sampRateWidget = QLineEdit(self.currLocale.toString(defaultSampRate)) 
        self.sampRateWidget.setValidator(QIntValidator(self))
        self.grid_0.addWidget(sampRateLabel, self.nrows, 0)
        self.grid_0.addWidget(self.sampRateWidget, self.nrows, 1)
        self.nrows = self.nrows + 1
        
        methodToCall = getattr(self, "select_default_parameters_" + self.execString)
        self.sndPrm = methodToCall()
        self.setDefaultParameters()
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|
                                           QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        self.grid_0.setAlignment(Qt.AlignTop)
        self.grid_1.setAlignment(Qt.AlignTop)
        self.hbl.addLayout(self.grid_0)
        self.hbl.addLayout(self.grid_1)

        self.scrollAreaWidgetContents = QWidget()#QFrame()
        #self.scrollAreaWidgetContents.setFrameStyle(QFrame.StyledPanel|QFrame.Sunken)
        self.scrollAreaWidgetContents.setLayout(self.hbl)
        
        self.scrollArea = QScrollArea()
        #self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.scrollAreaWidgetContents.layout().setSizeConstraint(QLayout.SetFixedSize)

        self.vbl.addWidget(self.scrollArea)
        self.vbl.addWidget(buttonBox)
        self.setLayout(self.vbl)
        screen = QDesktopWidget().screenGeometry()
        self.resize(int(0.3*screen.width()), int(0.5*screen.height()))
        self.setWindowTitle(self.tr("Generate Sound"))

    
    ## def minimumSizeHint(self):
    ##     size = self.sizeHint()
    ##     fm = QFontMetrics(self.font())
    ##     size.setHeight(fm.height() * 3)
    ##     return size


    ## def sizeHint(self):
    ##     fm = QFontMetrics(self.font())
    ##     size = fm.height()
    ##     return QSize(size*50, size * 60)
        

    def setDefaultParameters(self):
    
        self.field = list(range(self.sndPrm['nFields']))
        self.fieldLabel = list(range(self.sndPrm['nFields']))
        fieldLabelColumn = 0
        fieldColumn = 1
        chooserLabelColumn = 2
        chooserColumn = 3
        fshift = self.nrows
        for f in range(self.sndPrm['nFields']):
            self.fieldLabel[f] = QLabel(self.tr(self.sndPrm['fieldLabel'][f]))
            self.grid_0.addWidget(self.fieldLabel[f], f+fshift, fieldLabelColumn)
            self.field[f] = QLineEdit()
            self.field[f].setText(str(self.sndPrm['field'][f]))
            self.field[f].setValidator(QDoubleValidator(self))
            self.grid_0.addWidget(self.field[f], f+fshift, fieldColumn)
         
        self.chooser = list(range(self.sndPrm['nChoosers']))
        self.chooserLabel = list(range(self.sndPrm['nChoosers']))
        self.chooserOptions = list(range(self.sndPrm['nChoosers']))
        for c in range(self.sndPrm['nChoosers']):
            self.chooserLabel[c] = QLabel(self.tr(self.sndPrm['chooserLabel'][c]))
            self.grid_1.addWidget(self.chooserLabel[c], c, chooserLabelColumn)
            self.chooserOptions[c] = self.sndPrm['chooserOptions'][c]
            self.chooser[c] = QComboBox()  
            self.chooser[c].addItems(self.chooserOptions[c])
            self.chooser[c].setCurrentIndex(self.chooserOptions[c].index(self.sndPrm['chooser'][c]))
            self.grid_1.addWidget(self.chooser[c], c, chooserColumn)
        for c in range(len(self.chooser)):
            self.chooser[c].activated[str].connect(self.onChooserChange)
            self.onChooserChange()
        self.sndPrm['nFields'] = len(self.field)
        self.sndPrm['nChoosers'] = len(self.chooser)

  
    def onChooserChange(self):
        self.fieldsToHide = []; self.fieldsToShow = []
        self.choosersToHide = []; self.choosersToShow = [];
        methodToCall = getattr(self, "get_fields_to_hide_" + self.execString)
        tmp = methodToCall()

        for i in range(len(self.fieldsToHide)):
            self.field[self.fieldsToHide[i]].hide()
            self.fieldLabel[self.fieldsToHide[i]].hide()
        for i in range(len(self.fieldsToShow)):
            self.field[self.fieldsToShow[i]].show()
            self.fieldLabel[self.fieldsToShow[i]].show()
        for i in range(len(self.choosersToHide)):
            self.chooser[self.choosersToHide[i]].hide()
            self.chooserLabel[self.choosersToHide[i]].hide()
        for i in range(len(self.choosersToShow)):
            self.chooser[self.choosersToShow[i]].show()
            self.chooserLabel[self.choosersToShow[i]].show()
    def select_default_parameters_harm_compl(self):
   
        field = []
        fieldLabel = []
        chooser = []
        chooserLabel = []
        chooserOptions = []
    
        fieldLabel.append( self.tr("F0 (Hz)"))
        field.append(440)
    
        fieldLabel.append(self.tr("Bandwidth (Hz)"))
        field.append(10)
    
        fieldLabel.append(self.tr("Bandwidth (Cents)"))
        field.append(150)
    
        fieldLabel.append(self.tr("Spacing (Cents)"))
        field.append(10)
    
        fieldLabel.append(self.tr("ITD (micro s)"))
        field.append(320)
    
        fieldLabel.append(self.tr("IPD (radians)"))
        field.append(3.14159)#265)
    
        fieldLabel.append(self.tr("Narrow Band Component Level (dB SPL)"))
        field.append(65)
    
        fieldLabel.append(self.tr("Iterations"))
        field.append(16)
    
        fieldLabel.append(self.tr("Gain"))
        field.append(1)
    
        fieldLabel.append( self.tr("Low Harmonic"))
        field.append(1)
    
        fieldLabel.append(self.tr("High Harmonic"))
        field.append(20)
    
        fieldLabel.append(self.tr("Low Freq. (Hz)"))
        field.append(0)
    
        fieldLabel.append( self.tr("High Freq. (Hz)"))
        field.append(2000)
    
        fieldLabel.append( self.tr("Low Stop"))
        field.append(0.8)
    
        fieldLabel.append( self.tr("High Stop"))
        field.append(1.2)
    
        fieldLabel.append(self.tr("Harmonic Level (dB SPL)"))
        field.append(50)
    
        fieldLabel.append(self.tr("Spectrum Level (dB SPL)"))
        field.append(50)
    
        fieldLabel.append(self.tr("Component Level (dB SPL)"))
        field.append(50)
    
        fieldLabel.append(self.tr("Duration (ms)"))
        field.append(980)
    
        fieldLabel.append(self.tr("Ramp (ms)"))
        field.append(10)
    
        fieldLabel.append(self.tr("No. 1 Low Freq. (Hz)"))
        field.append(0)
    
        fieldLabel.append( self.tr("No. 1 High Freq. (Hz)"))
        field.append(1000)
    
        fieldLabel.append(self.tr("No. 1 S. Level (dB SPL)"))
        field.append(-200)
    
        fieldLabel.append(self.tr("No. 2 Low Freq. (Hz)"))
        field.append(2000)
    
        fieldLabel.append(self.tr("No. 2 High Freq. (Hz)"))
        field.append(3000)
    
        fieldLabel.append(self.tr("No. 2 S. Level (dB SPL)"))
        field.append(-200)
    
        fieldLabel.append(self.tr("Stretch (%)"))
        field.append(0)
    
        fieldLabel.append(self.tr("Harmonic Spacing (Cents)"))
        field.append(500)
    

       
        chooserOptions.append([self.tr("Right"), self.tr("Left"), self.tr("Both"), self.tr("Odd Left"), self.tr("Odd Right")])
        chooserLabel.append(self.tr("Ear:"))
        chooser.append(self.tr("Both"))
        chooserOptions.append([self.tr("Sinusoid"), self.tr("Narrowband Noise"), self.tr("IRN"), self.tr("Huggins Pitch")])
        chooserLabel.append(self.tr("Type:"))
        chooser.append(self.tr("Sinusoid"))
        chooserOptions.append([self.tr("Sine"), self.tr("Cosine"), self.tr("Alternating"), self.tr("Schroeder"), self.tr("Random")])
        chooserLabel.append(self.tr("Phase:"))
        chooser.append(self.tr("Sine"))
        chooserOptions.append([self.tr("White"), self.tr("Pink"), self.tr("None")])
        chooserLabel.append(self.tr("Noise Type:"))
        chooser.append(self.tr("White"))

        chooserOptions.append([self.tr("White"), self.tr("Pink")])
        chooserLabel.append(self.tr("Dichotic Noise Type:"))
        chooser.append(self.tr("White"))
        chooserOptions.append([self.tr("Add Same"), self.tr("Add Original")])
        chooserLabel.append(self.tr("IRN Type:"))
        chooser.append(self.tr("Add Same"))
        chooserOptions.append([self.tr("NoSpi"), self.tr("NpiSo")])
        chooserLabel.append(self.tr("Phase relationship:"))
        chooser.append(self.tr("NoSpi"))
        chooserOptions.append([self.tr("IPD Linear"), self.tr("IPD Stepped"), self.tr("ITD")])
        chooserLabel.append(self.tr("Dichotic Difference:"))
        chooser.append( self.tr("IPD Stepped"))
        chooserOptions.append([self.tr("Harmonic"), self.tr("Harmonic Stretched")])
        chooserLabel.append(self.tr("Harmonicity:"))
        chooser.append(self.tr("Harmonic"))
        chooserOptions.append([self.tr("Hz"), self.tr("Cent"), self.tr("ERB")])
        chooserLabel.append(self.tr("Bandwidth Unit:"))
        chooser.append(self.tr("Hz"))
   
        x = {}
        x['nFields'] = len(fieldLabel)
        x['nChoosers'] = len(chooserLabel)
        x['field'] = field
        x['fieldLabel'] = fieldLabel
        x['chooser'] = chooser
        x['chooserLabel'] = chooserLabel
        x['chooserOptions'] =  chooserOptions

        return x
    def get_fields_to_hide_harm_compl(self):
        if self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Type:",""))].currentText() == QApplication.translate("","Sinusoid",""):
            self.fieldsToHide = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Hz)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Cents)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Spacing (Cents)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Narrow Band Component Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Iterations")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Gain")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Spectrum Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Component Level (dB SPL)"))]
            self.fieldsToShow = [self.sndPrm['fieldLabel'].index(self.tr("Harmonic Level (dB SPL)"))]
            self.choosersToHide = [self.sndPrm['chooserLabel'].index(self.tr("IRN Type:")),
                                     self.sndPrm['chooserLabel'].index(self.tr("Phase relationship:")),
                                     self.sndPrm['chooserLabel'].index(self.tr("Bandwidth Unit:")),
                                     self.sndPrm['chooserLabel'].index(self.tr("Dichotic Noise Type:")), #white, pink
                                     self.sndPrm['chooserLabel'].index(self.tr("Dichotic Difference:"))]
            self.choosersToShow = [self.sndPrm['chooserLabel'].index(self.tr("Ear:")),
                                     self.sndPrm['chooserLabel'].index(self.tr("Phase:")), #sine cos schroeder, etc
                                     self.sndPrm['chooserLabel'].index(self.tr("Noise Type:")), #white, pink
                                     self.sndPrm['chooserLabel'].index(self.tr("Harmonicity:"))] #Harmonic, equal cents spacing
          
        elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Type:",""))].currentText() == QApplication.translate("","Narrowband Noise",""): 
            self.fieldsToHide = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Cents)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Spacing (Cents)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Narrow Band Component Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Iterations")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Gain")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Harmonic Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Component Level (dB SPL)"))]
            self.fieldsToShow = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Hz)")),
                                self.sndPrm['fieldLabel'].index(self.tr("Spectrum Level (dB SPL)"))]
            self.choosersToHide = [self.sndPrm['chooserLabel'].index(self.tr("Phase:")), #sine cos schroeder, etc
                                     self.sndPrm['chooserLabel'].index(self.tr("IRN Type:")),
                                     self.sndPrm['chooserLabel'].index(self.tr("Phase relationship:")), #NoSpi, NpiSo
                                     self.sndPrm['chooserLabel'].index(self.tr("Dichotic Difference:"))] #IPD, ITD
            self.choosersToShow = [self.sndPrm['chooserLabel'].index(self.tr("Ear:")),
                                    self.sndPrm['chooserLabel'].index(self.tr("Noise Type:")), #white, pink
                                    self.sndPrm['chooserLabel'].index(self.tr("Dichotic Noise Type:")), #white, pink
                                    self.sndPrm['chooserLabel'].index(self.tr("Bandwidth Unit:")),
                                    self.sndPrm['chooserLabel'].index(self.tr("Harmonicity:"))] #Harmonic, equal cents spacing

        elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Type:",""))].currentText() == QApplication.translate("","IRN",""):
            self.fieldsToHide = [self.sndPrm['fieldLabel'].index(self.tr("Low Harmonic")),
                                   self.sndPrm['fieldLabel'].index(self.tr("High Harmonic")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Hz)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Cents)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Spacing (Cents)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Narrow Band Component Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Harmonic Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Component Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Stretch (%)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Harmonic Spacing (Cents)"))]
            self.fieldsToShow = [self.sndPrm['fieldLabel'].index(self.tr("Iterations")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Gain")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Spectrum Level (dB SPL)"))]
            self.choosersToShow = [self.sndPrm['chooserLabel'].index(self.tr("Ear:")), #left, right, both, odd left, odd right
                                     self.sndPrm['chooserLabel'].index(self.tr("Noise Type:")), #white, pink
                                     self.sndPrm['chooserLabel'].index(self.tr("IRN Type:"))]
            self.choosersToHide = [self.sndPrm['chooserLabel'].index(self.tr("Phase:")), #sine cos schroeder, etc
                                    self.sndPrm['chooserLabel'].index(self.tr("Phase relationship:")), #NoSpi, NpiSo
                                    self.sndPrm['chooserLabel'].index(self.tr("Dichotic Difference:")), #IPD, ITD
                                    self.sndPrm['chooserLabel'].index(self.tr("Bandwidth Unit:")),
                                    self.sndPrm['chooserLabel'].index(self.tr("Dichotic Noise Type:")), #white, pink
                                    self.sndPrm['chooserLabel'].index(self.tr("Harmonicity:"))] #Harmonic, equal cents spacing
                          
                          
        elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Type:",""))].currentText() == QApplication.translate("","Huggins Pitch",""):
            self.fieldsToHide = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Cents)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Spacing (Cents)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Narrow Band Component Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Iterations")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Gain")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Harmonic Level (dB SPL)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Component Level (dB SPL)"))]
            self.fieldsToShow = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Hz)")),
                                   self.sndPrm['fieldLabel'].index(self.tr("Spectrum Level (dB SPL)"))]
            self.choosersToShow = [self.sndPrm['chooserLabel'].index(self.tr("Phase relationship:")), #NoSpi, NpiSo
                                    self.sndPrm['chooserLabel'].index(self.tr("Bandwidth Unit:")),
                                    self.sndPrm['chooserLabel'].index(self.tr("Dichotic Difference:")), 
                                    self.sndPrm['chooserLabel'].index(self.tr("Dichotic Noise Type:")), #white, pink
                                    self.sndPrm['chooserLabel'].index(self.tr("Harmonicity:"))] #Harmonic, equal cents spacing
            self.choosersToHide = [self.sndPrm['chooserLabel'].index(self.tr("Ear:")), #left, right, both, odd left, odd right
                                     self.sndPrm['chooserLabel'].index(self.tr("Phase:")), #sine cos schroeder, etc
                                     self.sndPrm['chooserLabel'].index(self.tr("IRN Type:")),
                                     self.sndPrm['chooserLabel'].index(self.tr("Dichotic Difference:"))] #IPD, ITD
            if self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Dichotic Difference:",""))].currentText() in [QApplication.translate("","IPD Linear",""), QApplication.translate("","IPD Stepped","")]:
                 self.fieldsToHide.extend([self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)"))])
                 self.fieldsToShow.extend([self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)"))])
            elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Dichotic Difference:",""))].currentText() == QApplication.translate("","ITD",""):
                 self.fieldsToHide.extend([self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)"))])
                 self.fieldsToShow.extend([self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)"))])

            
        ## elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Type:",""))].currentText() == QApplication.translate("","Simple Dichotic",""):
        ##     self.fieldsToHide = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Hz)")),
        ##                            self.sndPrm['fieldLabel'].index(self.tr("Iterations")),
        ##                            self.sndPrm['fieldLabel'].index(self.tr("Gain")),
        ##                            self.sndPrm['fieldLabel'].index(self.tr("Harmonic Level (dB SPL)")),
        ##                            self.sndPrm['fieldLabel'].index(self.tr("Spectrum Level (dB SPL)")),
        ##                            self.sndPrm['fieldLabel'].index(self.tr("Narrow Band Component Level (dB SPL)"))]
        ##     self.fieldsToShow = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Cents)")),
        ##                            self.sndPrm['fieldLabel'].index(self.tr("Spacing (Cents)")),
        ##                            self.sndPrm['fieldLabel'].index(self.tr("Component Level (dB SPL)"))]
        ##     if self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Dichotic Difference:",""))].currentText() == QApplication.translate("","IPD",""):
        ##         self.fieldsToHide.extend([self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)"))])
        ##         self.fieldsToShow.extend([self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)"))])
        ##     elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Dichotic Difference:",""))].currentText() == QApplication.translate("","ITD",""):
        ##         self.fieldsToHide.extend([self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)"))])
        ##         self.fieldsToShow.extend([self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)"))])
        ##         self.choosersToShow = [self.sndPrm['chooserLabel'].index(self.tr("Phase relationship:")), #NoSpi, NpiSo
        ##                                  self.sndPrm['chooserLabel'].index(self.tr("Dichotic Difference:")), #IPD, ITD
        ##                                  self.sndPrm['chooserLabel'].index(self.tr("Bandwidth Unit:")),
        ##                                  self.sndPrm['chooserLabel'].index(self.tr("Harmonicity:"))]
        ##         self.choosersToHide = [self.sndPrm['chooserLabel'].index(self.tr("Ear:")), #left, right, both, odd left, odd right
        ##                                  self.sndPrm['chooserLabel'].index(self.tr("Phase:")), #sine cos schroeder, etc
        ##                                  self.sndPrm['chooserLabel'].index(self.tr("Noise Type:")), #white, pink
        ##                                  self.sndPrm['chooserLabel'].index(self.tr("Dichotic Noise Type:")), #white, pink
        ##                                  self.sndPrm['chooserLabel'].index(self.tr("IRN Type:"))]
        ## elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Type:",""))].currentText() == QApplication.translate("","Narrowband Noise 2",""):
        ##     self.fieldsToHide = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Hz)")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("Iterations")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("Gain")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("Harmonic Level (dB SPL)")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("Spectrum Level (dB SPL)")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("IPD (radians)")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("ITD (micro s)"))]
        ##     self.fieldsToShow = [self.sndPrm['fieldLabel'].index(self.tr("Bandwidth (Cents)")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("Spacing (Cents)")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("Narrow Band Component Level (dB SPL)")),
        ##                          self.sndPrm['fieldLabel'].index(self.tr("Component Level (dB SPL)"))]
                           
        ##     self.choosersToShow = [self.sndPrm['chooserLabel'].index(self.tr("Phase relationship:")), #NoSpi, NpiSo
        ##                            self.sndPrm['chooserLabel'].index(self.tr("Harmonicity:"))]
        ##     self.choosersToHide = [self.sndPrm['chooserLabel'].index(self.tr("Ear:")), #left, right, both, odd left, odd right
        ##                            self.sndPrm['chooserLabel'].index(self.tr("Dichotic Difference:")),
        ##                            self.sndPrm['chooserLabel'].index(self.tr("Phase:")), #sine cos schroeder, etc
        ##                            self.sndPrm['chooserLabel'].index(self.tr("Noise Type:")), #white, pink
        ##                            self.sndPrm['chooserLabel'].index(self.tr("IRN Type:"))]
                
        if self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Harmonicity:",""))].currentText() == QApplication.translate("","Harmonic",""):
            self.fieldsToHide.extend([self.sndPrm['fieldLabel'].index(self.tr("Harmonic Spacing (Cents)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("Stretch (%)"))])
        elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Harmonicity:",""))].currentText() == QApplication.translate("","Harmonic Stretched",""):
            self.fieldsToHide.extend([self.sndPrm['fieldLabel'].index(self.tr("Harmonic Spacing (Cents)"))])
            self.fieldsToShow.extend([self.sndPrm['fieldLabel'].index(self.tr("Stretch (%)"))])
        elif self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Harmonicity:",""))].currentText() == QApplication.translate("","Equal Cents Spacing",""):
            self.fieldsToShow.extend([self.sndPrm['fieldLabel'].index(self.tr("Harmonic Spacing (Cents)"))])


    #Noise Type
        if self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Noise Type:",""))].currentText() == QApplication.translate("","None",""):
            self.fieldsToHide.extend([self.sndPrm['fieldLabel'].index(self.tr("No. 1 Low Freq. (Hz)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 1 High Freq. (Hz)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 1 S. Level (dB SPL)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 2 Low Freq. (Hz)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 2 High Freq. (Hz)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 2 S. Level (dB SPL)"))])
        else:
            self.fieldsToShow.extend([self.sndPrm['fieldLabel'].index(self.tr("No. 1 Low Freq. (Hz)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 1 High Freq. (Hz)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 1 S. Level (dB SPL)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 2 Low Freq. (Hz)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 2 High Freq. (Hz)")),
                                      self.sndPrm['fieldLabel'].index(self.tr("No. 2 S. Level (dB SPL)"))])

        
        ## if (self.chooser[self.sndPrm['chooserLabel'].index(QApplication.translate("","Type:",""))].currentText() == QApplication.translate("","Simple Dichotic","") or QApplication.translate("","Narrowband Noise 2","")):
        ##     self.fieldsToHide.extend([self.sndPrm['fieldLabel'].index(self.tr("Low Stop")), self.sndPrm['fieldLabel'].index(self.tr("High Stop"))])
            
        ## else:
        ##     self.fieldsToShow.extend([self.sndPrm['fieldLabel'].index(self.tr("Low Stop")), self.sndPrm['fieldLabel'].index(self.tr("High Stop"))])
    def select_default_parameters_fm_tone(self):

        field = []
        fieldLabel = []
        chooser = []
        chooserLabel = []
        chooserOptions = []

        fieldLabel.append(self.tr("Carrier Frequency (Hz)"))
        field.append(1000)    

        fieldLabel.append(self.tr("Modulation Frequency (Hz)"))
        field.append(40)

        fieldLabel.append(self.tr("Modulation Index"))
        field.append(1)

        fieldLabel.append(self.tr("Carrier Phase (radians)"))
        field.append(0)    

        fieldLabel.append(self.tr("Duration (ms)"))
        field.append(980)    

        fieldLabel.append(self.tr("Ramp (ms)"))
        field.append(10)    

        fieldLabel.append(self.tr("Level (dB SPL)"))
        field.append(65)    


        chooserOptions.append([self.tr("Right"), self.tr("Left"), self.tr("Both")])
        chooserLabel.append(self.tr("Ear:"))
        chooser.append(self.tr("Both"))

        x = {}
        x['nFields'] = len(fieldLabel)
        x['nChoosers'] = len(chooserLabel)
        x['field'] = field
        x['fieldLabel'] = fieldLabel
        x['chooser'] = chooser
        x['chooserLabel'] = chooserLabel
        x['chooserOptions'] =  chooserOptions

        return x
    
    def get_fields_to_hide_fm_tone(self):
        pass

    def select_default_parameters_am_tone(self):

        field = []
        fieldLabel = []
        chooser = []
        chooserLabel = []
        chooserOptions = []

        fieldLabel.append(self.tr("Frequency (Hz)"))
        field.append(1000)    

        fieldLabel.append(self.tr("AM Frequency (Hz)"))
        field.append(10)

        fieldLabel.append(self.tr("AM Depth"))
        field.append(1)

        fieldLabel.append(self.tr("Carrier Phase (radians)"))
        field.append(0)    

        fieldLabel.append(self.tr("Modulation Phase (radians)"))
        field.append(0)    

        fieldLabel.append(self.tr("Duration (ms)"))
        field.append(980)    

        fieldLabel.append(self.tr("Ramp (ms)"))
        field.append(10)    

        fieldLabel.append(self.tr("Level (dB SPL)"))
        field.append(65)    


        chooserOptions.append([self.tr("Right"), self.tr("Left"), self.tr("Both")])
        chooserLabel.append(self.tr("Ear:"))
        chooser.append(self.tr("Both"))

        x = {}
        x['nFields'] = len(fieldLabel)
        x['nChoosers'] = len(chooserLabel)
        x['field'] = field
        x['fieldLabel'] = fieldLabel
        x['chooser'] = chooser
        x['chooserLabel'] = chooserLabel
        x['chooserOptions'] =  chooserOptions

        return x
    
    def get_fields_to_hide_am_tone(self):
        pass

        
    def select_default_parameters_silence(self):
   
        field = []
        fieldLabel = []
        chooser = []
        chooserLabel = []
        chooserOptions = []
    
        fieldLabel.append( self.tr("Duration (ms)"))
        field.append(1000)    

       
        chooserOptions.append([self.tr("Right"), self.tr("Left"), self.tr("Both")])
        chooserLabel.append(self.tr("Ear:"))
        chooser.append(self.tr("Both"))

        x = {}
        x['nFields'] = len(fieldLabel)
        x['nChoosers'] = len(chooserLabel)
        x['field'] = field
        x['fieldLabel'] = fieldLabel
        x['chooser'] = chooser
        x['chooserLabel'] = chooserLabel
        x['chooserOptions'] =  chooserOptions

        return x
    
    def get_fields_to_hide_silence(self):
        pass
コード例 #28
0
class ProjectTreeColumn(QScrollArea):
    def __init__(self, *args, **kwargs):
        super(ProjectTreeColumn, self).__init__(*args, **kwargs)
        self._widget = QWidget()
        vbox = QVBoxLayout()
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.setSpacing(0)
        self._widget.setLayout(vbox)
        self.setWidget(self._widget)
        self.setWidgetResizable(True)
        self.setEnabled(True)
        self.projects = []
        self._active_project = None

        #connections = (
        #{'target': 'main_container',
        #'signal_name': 'openProject(QString)',
        #'slot': self.open_project_folder},
        #)
        #IDE.register_signals('tree_projects_widget', connections)

    def install(self):
        ide = IDE.get_service('ide')
        ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide)

    def open_project_folder(self):
        if settings.WORKSPACE:
            directory = settings.WORKSPACE
        else:
            directory = os.path.expanduser("~")

        folderName = QFileDialog.getExistingDirectory(
            self, self.tr("Open Project Directory"), directory)
        logger.debug("Choosing Foldername")
        if folderName:
            logger.debug("Opening %s" % folderName)
            ninjaide = IDE.get_service("ide")
            project = NProject(folderName)
            qfsm = ninjaide.filesystem.open_project(project)
            if qfsm:
                self.add_project(project)

    def add_project(self, project):
        if project not in self.projects:
            ptree = TreeProjectsWidget(project)
            self.connect(ptree, SIGNAL("setActiveProject(PyQt_PyObject)"),
                         self._set_active_project)
            pmodel = project.model
            ptree.setModel(pmodel)
            ptree.header().title = project.name
            pindex = pmodel.index(pmodel.rootPath())
            ptree.setRootIndex(pindex)
            #self._widget.layout().addWidget(scrollable_wrapper(ptree))
            self._widget.layout().addWidget(ptree)
            if self._active_project is None:
                ptree.set_default_project()
            self.projects.append(ptree)

    def _set_active_project(self, tree_proj):
        if self._active_project is not None:
            self._active_project.set_default_project(False)
        self._active_project = tree_proj
コード例 #29
0
ファイル: settings.py プロジェクト: AutumnLight/orange
    def __setupUi(self):
        """Set up the UI.
        """
        if self.__macUnified:
            self.tab = QToolBar()

            self.addToolBar(Qt.TopToolBarArea, self.tab)
            self.setUnifiedTitleAndToolBarOnMac(True)

            # This does not seem to work
            self.setWindowFlags(self.windowFlags() & \
                                ~Qt.MacWindowToolBarButtonHint)

            self.tab.actionTriggered[QAction].connect(
                self.__macOnToolBarAction
            )

            central = QStackedWidget()

            central.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        else:
            self.tab = central = QTabWidget(self)

        # Add a close button to the bottom of the dialog
        # (to satisfy GNOME 3 which shows the dialog  without a title bar).
        container = container_widget_helper()
        container.layout().addWidget(central)
        buttonbox = QDialogButtonBox(QDialogButtonBox.Close)
        buttonbox.rejected.connect(self.close)
        container.layout().addWidget(buttonbox)

        self.setCentralWidget(container)

        self.stack = central

        # General Tab
        tab = QWidget()
        self.addTab(tab, self.tr("General"),
                    toolTip=self.tr("General Options"))

        form = QFormLayout()
        tab.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        nodes = QWidget(self, objectName="nodes")
        nodes.setLayout(QVBoxLayout())
        nodes.layout().setContentsMargins(0, 0, 0, 0)

        cb_anim = QCheckBox(
            self.tr("Enable node animations"),
            objectName="enable-node-animations",
            toolTip=self.tr("Enable shadow and ping animations for node "
                            "items in the scheme.")
        )
        self.bind(cb_anim, "checked", "schemeedit/enable-node-animations")
        nodes.layout().addWidget(cb_anim)

        form.addRow(self.tr("Nodes"), nodes)

        links = QWidget(self, objectName="links")
        links.setLayout(QVBoxLayout())
        links.layout().setContentsMargins(0, 0, 0, 0)

        cb_show = QCheckBox(
            self.tr("Show channel names between widgets"),
            objectName="show-channel-names",
            toolTip=self.tr("Show source and sink channel names "
                            "over the links.")
        )

        self.bind(cb_show, "checked", "schemeedit/show-channel-names")

        links.layout().addWidget(cb_show)

        form.addRow(self.tr("Links"), links)

        quickmenu = QWidget(self, objectName="quickmenu-options")
        quickmenu.setLayout(QVBoxLayout())
        quickmenu.layout().setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("On double click"),
                        toolTip=self.tr("Open quick menu on a double click "
                                        "on an empty spot in the canvas"))

        cb2 = QCheckBox(self.tr("On right click"),
                        toolTip=self.tr("Open quick menu on a right click "
                                        "on an empty spot in the canvas"))

        cb3 = QCheckBox(self.tr("On space key press"),
                        toolTip=self.tr("On Space key press while the mouse"
                                        "is hovering over the canvas."))

        cb4 = QCheckBox(self.tr("On any key press"),
                        toolTip=self.tr("On any key press while the mouse"
                                        "is hovering over the canvas."))

        self.bind(cb1, "checked", "quickmenu/trigger-on-double-click")
        self.bind(cb2, "checked", "quickmenu/trigger-on-right-click")
        self.bind(cb3, "checked", "quickmenu/trigger-on-space-key")
        self.bind(cb4, "checked", "quickmenu/trigger-on-any-key")

        quickmenu.layout().addWidget(cb1)
        quickmenu.layout().addWidget(cb2)
        quickmenu.layout().addWidget(cb3)
        quickmenu.layout().addWidget(cb4)

        form.addRow(self.tr("Open quick menu on"), quickmenu)

        startup = QWidget(self, objectName="startup-group")
        startup.setLayout(QVBoxLayout())
        startup.layout().setContentsMargins(0, 0, 0, 0)

        cb_splash = QCheckBox(self.tr("Show splash screen"), self,
                              objectName="show-splash-screen")

        cb_welcome = QCheckBox(self.tr("Show welcome screen"), self,
                                objectName="show-welcome-screen")

        self.bind(cb_splash, "checked", "startup/show-splash-screen")
        self.bind(cb_welcome, "checked", "startup/show-welcome-screen")

        startup.layout().addWidget(cb_splash)
        startup.layout().addWidget(cb_welcome)

        form.addRow(self.tr("On startup"), startup)

        toolbox = QWidget(self, objectName="toolbox-group")
        toolbox.setLayout(QVBoxLayout())
        toolbox.layout().setContentsMargins(0, 0, 0, 0)

        exclusive = QCheckBox(self.tr("Only one tab can be open at a time"))

        self.bind(exclusive, "checked", "mainwindow/toolbox-dock-exclusive")

        toolbox.layout().addWidget(exclusive)

        form.addRow(self.tr("Tool box"), toolbox)
        tab.setLayout(form)

        # Output Tab
        tab = QWidget()
        self.addTab(tab, self.tr("Output"),
                    toolTip="Output Redirection")

        form = QFormLayout()
        box = QWidget(self, objectName="streams")
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("Standard output"))
        cb2 = QCheckBox(self.tr("Standard error"))

        self.bind(cb1, "checked", "output/redirect-stdout")
        self.bind(cb2, "checked", "output/redirect-stderr")

        layout.addWidget(cb1)
        layout.addWidget(cb2)
        box.setLayout(layout)

        form.addRow(self.tr("Redirect output"), box)

        box = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        combo = QComboBox()
        combo.addItems([self.tr("Critical"),
                        self.tr("Error"),
                        self.tr("Warn"),
                        self.tr("Info"),
                        self.tr("Debug")])

        cb = QCheckBox(self.tr("Show output on 'Error'"),
                       objectName="focus-on-error")

        self.bind(combo, "currentIndex", "logging/level")
        self.bind(cb, "checked", "output/show-on-error")

        layout.addWidget(combo)
        layout.addWidget(cb)
        box.setLayout(layout)

        form.addRow(self.tr("Logging"), box)

        box = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("Stay on top"),
                        objectName="stay-on-top")

        cb2 = QCheckBox(self.tr("Dockable"),
                        objectName="output-dockable")

        self.bind(cb1, "checked", "output/stay-on-top")
        self.bind(cb2, "checked", "output/dockable")

        layout.addWidget(cb1)
        layout.addWidget(cb2)
        box.setLayout(layout)

        form.addRow(self.tr("Output window"), box)

        box = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("Open in external browser"),
                        objectName="open-in-external-browser")

        cb2 = QCheckBox(self.tr("Stay on top"),
                        objectName="help-stay-on-top")

        cb3 = QCheckBox(self.tr("Dockable"),
                        objectName="help-dockable")

        self.bind(cb1, "checked", "help/open-in-external-browser")
        self.bind(cb2, "checked", "help/stay-on-top")
        self.bind(cb3, "checked", "help/dockable")

        layout.addWidget(cb1)
        layout.addWidget(cb2)
        layout.addWidget(cb3)
        box.setLayout(layout)

        form.addRow(self.tr("Help window"), box)

        tab.setLayout(form)

        # Categories Tab
        tab = QWidget()
        layout = QVBoxLayout()
        view = QListView()
        from .. import registry
        reg = registry.global_registry()
        model = QStandardItemModel()
        settings = QSettings()
        for cat in reg.categories():
            item = QStandardItem()
            item.setText(cat.name)
            item.setCheckable(True)
            visible, _ = category_state(cat, settings)
            item.setCheckState(Qt.Checked if visible else Qt.Unchecked)
            model.appendRow([item])

        view.setModel(model)
        layout.addWidget(view)
        tab.setLayout(layout)
        model.itemChanged.connect(
            lambda item:
                save_category_state(
                    reg.category(str(item.text())),
                    _State(item.checkState() == Qt.Checked, -1),
                    settings
                )
        )

        self.addTab(tab, "Categories")

        if self.__macUnified:
            # Need some sensible size otherwise mac unified toolbar 'takes'
            # the space that should be used for layout of the contents
            self.adjustSize()
コード例 #30
0
ファイル: settings.py プロジェクト: tomazc/orange3
    def __setupUi(self):
        """Set up the UI.
        """
        if self.__macUnified:
            self.tab = QToolBar()

            self.addToolBar(Qt.TopToolBarArea, self.tab)
            self.setUnifiedTitleAndToolBarOnMac(True)

            # This does not seem to work
            self.setWindowFlags(self.windowFlags() & \
                                ~Qt.MacWindowToolBarButtonHint)

            self.tab.actionTriggered[QAction].connect(
                self.__macOnToolBarAction
            )

            central = QStackedWidget()

            central.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        else:
            self.tab = central = QTabWidget(self)

        self.stack = central

        self.setCentralWidget(central)

        # General Tab
        tab = QWidget()
        self.addTab(tab, self.tr("General"),
                    toolTip=self.tr("General Options"))

        form = QFormLayout()
        tab.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

        nodes = QWidget(self, objectName="nodes")
        nodes.setLayout(QVBoxLayout())
        nodes.layout().setContentsMargins(0, 0, 0, 0)

        cb_anim = QCheckBox(
            self.tr("Enable node animations"),
            objectName="enable-node-animations",
            toolTip=self.tr("Enable shadow and ping animations for nodes "
                            "in the workflow.")
        )
        self.bind(cb_anim, "checked", "schemeedit/enable-node-animations")
        nodes.layout().addWidget(cb_anim)

        form.addRow(self.tr("Nodes"), nodes)

        links = QWidget(self, objectName="links")
        links.setLayout(QVBoxLayout())
        links.layout().setContentsMargins(0, 0, 0, 0)

        cb_show = QCheckBox(
            self.tr("Show channel names between widgets"),
            objectName="show-channel-names",
            toolTip=self.tr("Show source and sink channel names "
                            "over the links.")
        )

        self.bind(cb_show, "checked", "schemeedit/show-channel-names")

        links.layout().addWidget(cb_show)

        form.addRow(self.tr("Links"), links)

        quickmenu = QWidget(self, objectName="quickmenu-options")
        quickmenu.setLayout(QVBoxLayout())
        quickmenu.layout().setContentsMargins(0, 0, 0, 0)

        cb1 = QCheckBox(self.tr("On double click"),
                        toolTip=self.tr("Open quick menu on a double click "
                                        "on an empty spot in the canvas"))

        cb2 = QCheckBox(self.tr("On right click"),
                        toolTip=self.tr("Open quick menu on a right click "
                                        "on an empty spot in the canvas"))

        cb3 = QCheckBox(self.tr("On space key press"),
                        toolTip=self.tr("On Space key press while the mouse"
                                        "is hovering over the canvas."))

        cb4 = QCheckBox(self.tr("On any key press"),
                        toolTip=self.tr("On any key press while the mouse"
                                        "is hovering over the canvas."))

        self.bind(cb1, "checked", "quickmenu/trigger-on-double-click")
        self.bind(cb2, "checked", "quickmenu/trigger-on-right-click")
        self.bind(cb3, "checked", "quickmenu/trigger-on-space-key")
        self.bind(cb4, "checked", "quickmenu/trigger-on-any-key")

        quickmenu.layout().addWidget(cb1)
        quickmenu.layout().addWidget(cb2)
        quickmenu.layout().addWidget(cb3)
        quickmenu.layout().addWidget(cb4)

        form.addRow(self.tr("Open quick menu on"), quickmenu)

        startup = QWidget(self, objectName="startup-group")
        startup.setLayout(QVBoxLayout())
        startup.layout().setContentsMargins(0, 0, 0, 0)

        cb_splash = QCheckBox(self.tr("Show splash screen"), self,
                              objectName="show-splash-screen")

        cb_welcome = QCheckBox(self.tr("Show welcome screen"), self,
                                objectName="show-welcome-screen")

        self.bind(cb_splash, "checked", "startup/show-splash-screen")
        self.bind(cb_welcome, "checked", "startup/show-welcome-screen")

        startup.layout().addWidget(cb_splash)
        startup.layout().addWidget(cb_welcome)

        form.addRow(self.tr("On startup"), startup)

        toolbox = QWidget(self, objectName="toolbox-group")
        toolbox.setLayout(QVBoxLayout())
        toolbox.layout().setContentsMargins(0, 0, 0, 0)

        exclusive = QCheckBox(self.tr("Only one tab can be open at a time"))

        self.bind(exclusive, "checked", "mainwindow/toolbox-dock-exclusive")

        toolbox.layout().addWidget(exclusive)

        form.addRow(self.tr("Tool box"), toolbox)
        tab.setLayout(form)

        # Output Tab
        tab = QWidget()
        self.addTab(tab, self.tr("Output"),
                    toolTip="Output Redirection")

        form = QFormLayout()

        box = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        combo = QComboBox()
        combo.addItems([self.tr("Critical"),
                        self.tr("Error"),
                        self.tr("Warn"),
                        self.tr("Info"),
                        self.tr("Debug")])
        self.bind(combo, "currentIndex", "logging/level")
        layout.addWidget(combo)
        box.setLayout(layout)
        form.addRow(self.tr("Logging"), box)

        box = QWidget()
        layout = QVBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        cb1 = QCheckBox(self.tr("Open in external browser"),
                        objectName="open-in-external-browser")
        self.bind(cb1, "checked", "help/open-in-external-browser")
        layout.addWidget(cb1)
        box.setLayout(layout)
        form.addRow(self.tr("Help window"), box)

        tab.setLayout(form)

        if self.__macUnified:
            # Need some sensible size otherwise mac unified toolbar 'takes'
            # the space that should be used for layout of the contents
            self.adjustSize()
コード例 #31
0
def buildfromauto(formconfig, base):
    widgetsconfig = copy.deepcopy(formconfig['widgets'])

    try:
        widgetsconfig = base.get_widgets(widgetsconfig)
    except AttributeError:
        pass

    newstyle = formconfig.get("newstyle", False)
    hassections = any(config['widget'] == "Section"
                      for config in widgetsconfig)

    def make_layout():
        if newstyle:
            return QVBoxLayout()
        else:
            layout = QFormLayout()
            layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
            return layout

    def make_tab(tabwidget, name):
        widget = QWidget()
        widget.setLayout(make_layout())
        tabwidget.addTab(widget, name)
        return widget, widget.layout()

    if hassections:
        outwidget = QTabWidget(base)
        outlayout = None
        base.setLayout(QVBoxLayout())
        base.layout().setContentsMargins(0, 0, 0, 0)
        base.layout().addWidget(outwidget)
    else:
        outwidget = base
        outlayout = make_layout()
        outwidget.setLayout(outlayout)

    if roam.config.settings.get("form_geom_edit", False):
        geomwidget = GeomWidget()
        geomwidget.setObjectName("__geomwidget")
        outlayout.addRow("Geometry", geomwidget)

    insection = False
    for config in widgetsconfig:
        widgettype = config['widget']

        ## Make the first tab if one isn't defined already and we have other sections in the config
        if not insection and hassections and not widgettype == "Section":
            name = formconfig['label']
            tabwidget, outlayout = make_tab(outwidget, name)
            insection = True

        if widgettype == 'Section':
            # Add a spacer to the last widget
            if outlayout:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
                outlayout.addItem(QSpacerItem(10, 500))
                outlayout.addWidget(spacer)

            name = config['name']
            tabwidget, outlayout = make_tab(outwidget, name)
            installflickcharm(tabwidget)
            insection = True
            continue

        field = config['field']
        name = config.get('name', field)
        if not field:
            utils.warning("Field can't be null for {}".format(name))
            utils.warning("Skipping widget")
            continue

        label = QLabel(name)
        label.setObjectName(field + "_label")
        labelwidget = QWidget()
        labelwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        labelwidget.layout().addWidget(label)
        labelwidget.layout().setContentsMargins(0, 0, 0, 0)

        widget = roam.editorwidgets.core.createwidget(widgettype, parent=base)
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        layoutwidget.layout().setContentsMargins(0, 0, 0, 10)

        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            if newstyle:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
                labelwidget.layout().addWidget(spacer)
                labelwidget.layout().addWidget(savebutton)
            else:
                layoutwidget.layout().addWidget(savebutton)

        if newstyle:
            outlayout.addWidget(labelwidget)
            outlayout.addWidget(layoutwidget)
        else:
            outlayout.addRow(labelwidget, layoutwidget)

    spacer = QWidget()
    spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
    outlayout.addWidget(spacer)
    if not hassections:
        outlayout.addItem(QSpacerItem(10, 500))
        installflickcharm(outwidget)
    return base
コード例 #32
0
ファイル: mainwindow.py プロジェクト: Python3pkg/OASYS1
class OASYSSchemeInfoDialog(schemeinfo.SchemeInfoDialog):
    def __init__(self, parent=None, existing_scheme=False, **kwargs):
        super().__init__(parent, **kwargs)
        # Insert a 'Working Directory' row in the editor form.
        layout = self.editor.layout()

        self.working_dir_edit = QWidget(self)
        self.working_dir_edit.setLayout(QHBoxLayout())
        self.working_dir_edit.layout().setContentsMargins(0, 0, 0, 0)

        settings = QSettings()

        self.working_dir_line = QLineEdit(self)
        self.working_dir_line.setReadOnly(True)

        cur_wd = (settings.value("output/default-working-directory",
                                 "", type=str) or
                  os.path.expanduser("~/Oasys"))

        self.working_dir_line.setText(cur_wd)
        pb = QPushButton("Change ...")
        pb.clicked.connect(self.__change_working_directory)

        self.working_dir_edit.layout().addWidget(self.working_dir_line)
        self.working_dir_edit.layout().addWidget(pb)

        layout.insertRow(
            2, self.tr("Working directory"), self.working_dir_edit)


        self.units_edit = QWidget(self)
        self.units_edit.setLayout(QGridLayout())
        self.units_edit.layout().setContentsMargins(0, 0, 0, 0)


        self.combo_units = QComboBox()
        self.combo_units.addItems([self.tr("m"),
                                   self.tr("cm"),
                                   self.tr("mm")])

        self.combo_units.setEnabled(not existing_scheme)

        label = QLabel("")

        richText = "<html><head><meta name=\"qrichtext\" content=\"1\" /></head>" + \
                       "<body style=\" white-space: pre-wrap; " + \
                       "font-size:9pt; font-weight:400; font-style:normal; text-decoration:none;\">" + \
                       "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; " +\
                       "margin-right:0px; -qt-block-indent:0; text-indent:0px; font-size:12pt;\">Units in use in the Scheme   </p>" "</body></html>"

        label.setText(richText)

        self.units_edit.layout().addWidget(label, 0, 0)
        self.units_edit.layout().addWidget(self.combo_units, 0, 1, Qt.AlignRight)

        layout.insertRow(
            2, self.tr("Units"), self.units_edit)

        # Fix the widget tab order.
        item = layout.itemAt(1, QFormLayout.FieldRole)
        if item.widget() is not None:
            QWidget.setTabOrder(item.widget(), self.combo_units)
            QWidget.setTabOrder(self.combo_units, self.working_dir_line)
            QWidget.setTabOrder(self.working_dir_line, pb)

    def setScheme(self, scheme):
        super().setScheme(scheme)
        self.working_dir_line.setText(scheme.working_directory)
        self.combo_units.setCurrentIndex(scheme.workspace_units)

    def __change_working_directory(self):
        cur_wd = self.working_dir_line.text()
        new_wd = QFileDialog.getExistingDirectory(
            self, self.tr("Set working directory"), cur_wd,
        )
        if new_wd:
            self.working_dir_line.setText(new_wd)

    def title(self):
        return self.editor.title()

    def description(self):
        return self.editor.description()

    def workingDirectory(self):
        return self.working_dir_line.text()

    def workspaceUnits(self):
        return self.combo_units.currentIndex()
コード例 #33
0
 def make_tab(tabwidget, name):
     widget = QWidget()
     widget.setLayout(make_layout())
     tabwidget.addTab(widget, name)
     return widget, widget.layout()
コード例 #34
0
class PreprocessorModule(QWidget):
    """The base widget for the pre-processing modules."""

    change_signal = Signal()  # Emitted when the settings are changed.
    # Emitted when the module has a message to display in the main widget.
    error_signal = Signal(str)
    enabled = False  # If the module is enabled.

    def __init__(self, title, toggle_enabled, is_enabled):
        super().__init__()

        # Title bar.
        title_holder = QWidget()
        title_holder.setSizePolicy(QSizePolicy.MinimumExpanding,
                                   QSizePolicy.Fixed)
        title_holder.setStyleSheet("""
        .QWidget {
        background: qlineargradient( x1:0 y1:0, x2:0 y2:1,
        stop:0 #F8F8F8, stop:1 #C8C8C8);
        border-bottom: 1px solid #B3B3B3;
        }
        """)
        self.titleArea = QHBoxLayout()
        self.titleArea.setContentsMargins(15, 10, 15, 10)
        self.titleArea.setSpacing(0)
        title_holder.setLayout(self.titleArea)

        self.title_label = QLabel(title)
        self.title_label.setStyleSheet('font-size: 12px;')
        self.titleArea.addWidget(self.title_label)

        self.off_label = QLabel('[disabled]')
        self.off_label.setStyleSheet('color: #B0B0B0; margin-left: 5px;')
        self.titleArea.addWidget(self.off_label)
        self.off_label.hide()

        self.titleArea.addStretch()

        # Root.
        self.rootArea = QVBoxLayout()
        self.rootArea.setContentsMargins(0, 0, 0, 0)
        self.rootArea.setSpacing(0)
        self.setLayout(self.rootArea)
        self.rootArea.addWidget(title_holder)

        self.contents = QWidget()
        contentArea = QVBoxLayout()
        contentArea.setContentsMargins(15, 10, 15, 10)
        self.contents.setLayout(contentArea)
        self.rootArea.addWidget(self.contents)

        self.enabled = is_enabled
        if toggle_enabled:
            self.toggle_module_switch = QCheckBox()
            switch_icon_on_resource = _i('on_button.png')
            switch_icon_off_resource = _i('off_button.png')
            style_sheet = '''
            QCheckBox::indicator {
                width: 23px;
                height: 23px;
            }
            QCheckBox::indicator:checked {
                image: url(%s);
            }
            QCheckBox::indicator:unchecked {
                image: url(%s);
            }
            ''' % (switch_icon_on_resource, switch_icon_off_resource)
            self.toggle_module_switch.setStyleSheet(style_sheet)
            self.toggle_module_switch.setChecked(self.enabled)
            self.toggle_module_switch.stateChanged.connect(self.on_toggle)

            # Change the view according to the flag.
            if self.enabled:
                self.off_label.hide()
                self.contents.show()
                self.title_label.setStyleSheet('color: #000000;')
            else:
                self.off_label.show()
                self.contents.hide()
                self.title_label.setStyleSheet('color: #B0B0B0;')

            self.titleArea.addWidget(self.toggle_module_switch)

    def add_to_content_area(self, new_widget):
        self.contents.layout().addWidget(new_widget)

    def add_layout_to_content_area(self, new_layout):
        self.contents.layout().addLayout(new_layout)

    def notify_on_change(self):
        # Emits signals corresponding to the changes done.
        self.change_signal.emit()

    def on_toggle(self):
        # Activated when the widget is enabled/disabled.
        self.enabled = not self.enabled
        if self.enabled:
            self.off_label.hide()
            self.contents.show()
            self.title_label.setStyleSheet('color: #000000;')
        else:
            self.off_label.show()
            self.contents.hide()
            self.title_label.setStyleSheet('color: #B0B0B0;')
        self.change_signal.emit()

    def restore_data(self, data):
        # Restores the widget state from the input data.
        raise NotImplementedError

    def export_data(self):
        # Export the settings for this module instance.
        return NotImplementedError

    @staticmethod
    def get_pp_settings():
        # Returns the dict representation of this portion of a pre-processor.
        return NotImplementedError
コード例 #35
0
ファイル: picomotor.py プロジェクト: ignamv/Laboratory
        self.gen.burst_cycles = nsteps
        self.gen.trigger()

if __name__ == '__main__':
    from PyQt4.QtGui import QApplication, QWidget,  QPushButton, QHBoxLayout, QVBoxLayout, QLineEdit, QLabel
    from PyQt4.QtCore import Qt
    from os import sys
    picomotor = Picomotor(1)
    pasos = [-10000, -1000, -100, 100, 1000, 10000]
    app = QApplication(sys.argv)
    # TODO: hacer interfase mas linda en QT designer
    ventana = QWidget()
    ventana.setLayout(QVBoxLayout())
    label = QLabel('CCW\tCW')
    label.setAlignment(Qt.AlignHCenter)
    ventana.layout().addWidget(label)
    pasos_fijos = QHBoxLayout()
    for paso in pasos:
        bot = QPushButton(str(paso))
        class closure():
            def __init__(self,paso):
                self.paso = paso
            def __call__(self):
                print('Moviendo {}'.format(self.paso))
                picomotor.move(self.paso)
        bot.clicked.connect(closure(paso))
        pasos_fijos.addWidget(bot)
    ventana.layout().addLayout(pasos_fijos)
    manual = QHBoxLayout()
    entrada_pasos = QLineEdit('250')
    manual.addWidget(entrada_pasos)
コード例 #36
0
class ProjectTreeColumn(QDialog):

    def __init__(self, parent=None):
        super(ProjectTreeColumn, self).__init__(parent,
                                                Qt.WindowStaysOnTopHint)
        self._layout = QVBoxLayout()
        self._layout.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        self._layout.setContentsMargins(0, 0, 0, 0)
        self._layout.setSpacing(0)
        self.setLayout(self._layout)
        self._vbox = QVBoxLayout()
        self._vbox.setContentsMargins(0, 0, 0, 0)
        self._vbox.setSpacing(0)
        self._vbox.setSizeConstraint(QVBoxLayout.SetDefaultConstraint)
        self._buttons = []

        self._projects_area = QWidget()
        logger.debug("This is the projects area")
        logger.debug(self._projects_area)
        self._projects_area.setLayout(self._vbox)

        self._scroll_area = QScrollArea()
        self.layout().addWidget(self._scroll_area)
        self._scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self._scroll_area.setWidgetResizable(True)
        self._scroll_area.setEnabled(True)
        self._scroll_area.setWidget(self._projects_area)
        self._scroll_area.setGeometry(self.geometry())
        self._vbox.setGeometry(self.geometry())
        self.projects = []
        self._active_project = None

        connections = (
            {'target': 'main_container',
             'signal_name': 'addToProject(QString)',
             'slot': self._add_file_to_project},
            {'target': 'main_container',
             'signal_name': 'showFileInExplorer(QString)',
             'slot': self._show_file_in_explorer},
        )
        IDE.register_service('projects_explorer', self)
        IDE.register_signals('projects_explorer', connections)
        ExplorerContainer.register_tab(translations.TR_TAB_PROJECTS, self)

        #FIXME: Should have a ninja settings object that stores tree state
        #FIXME: Or bettter, application data object
        #TODO: check this:
        #self.connect(ide, SIGNAL("goingDown()"),
            #self.tree_projects.shutdown)

        #def close_project_signal():
            #self.emit(SIGNAL("updateLocator()"))

    def install_tab(self):
        ide = IDE.get_service('ide')
        ui_tools.install_shortcuts(self, actions.PROJECTS_TREE_ACTIONS, ide)

        self.connect(ide, SIGNAL("goingDown()"), self.close)

    def load_session_projects(self, projects):
        for project in projects:
            if os.path.exists(project):
                self._open_project_folder(project)

    def open_project_folder(self, folderName=None):
        if settings.WORKSPACE:
            directory = settings.WORKSPACE
        else:
            directory = os.path.expanduser("~")

        if folderName is None:
            folderName = QFileDialog.getExistingDirectory(
                self, translations.TR_OPEN_PROJECT_DIRECTORY, directory)
            logger.debug("Choosing Foldername")
        if folderName:
            logger.debug("Opening %s" % folderName)
            self._open_project_folder(folderName)

    def _open_project_folder(self, folderName):
        ninjaide = IDE.get_service("ide")
        project = NProject(folderName)
        qfsm = ninjaide.filesystem.open_project(project)
        if qfsm:
            self.add_project(project)
            self.emit(SIGNAL("updateLocator()"))
            self.save_recent_projects(folderName)
            main_container = IDE.get_service('main_container')
            if main_container:
                main_container.show_editor_area()

    def _add_file_to_project(self, path):
        """Add the file for 'path' in the project the user choose here."""
        if self._active_project:
            pathProject = [self._active_project.project]
            addToProject = add_to_project.AddToProject(pathProject, self)
            addToProject.exec_()
            if not addToProject.pathSelected:
                return
            main_container = IDE.get_service('main_container')
            if not main_container:
                return
            editorWidget = main_container.get_current_editor()
            if not editorWidget.file_path:
                name = QInputDialog.getText(None,
                                            translations.TR_ADD_FILE_TO_PROJECT,
                                            translations.TR_FILENAME + ": ")[0]
                if not name:
                    QMessageBox.information(
                        self,
                        translations.TR_INVALID_FILENAME,
                        translations.TR_INVALID_FILENAME_ENTER_A_FILENAME)
                    return
            else:
                name = file_manager.get_basename(editorWidget.file_path)
            new_path = file_manager.create_path(addToProject.pathSelected, name)
            ide_srv = IDE.get_service("ide")
            old_file = ide_srv.get_or_create_nfile(path)
            new_file = old_file.save(editorWidget.get_text(), new_path)
            #FIXME: Make this file replace the original in the open tab
        else:
            pass
            # Message about no project

    def _show_file_in_explorer(self, path):
        '''Iterate through the list of available projects and show
        the current file in the explorer view for the first
        project that contains it (i.e. if the same file is
        included in multiple open projects, the path will be
        expanded for the first project only).
        Note: This slot is connected to the main container's
        "showFileInExplorer(QString)" signal.'''
        for project in self.projects:
            index = project.model().index(path)
            if index.isValid():
                # Show the explorer if it is currently hidden
                central = IDE.get_service('central_container')
                if central and not central.is_lateral_panel_visible():
                    central.change_lateral_visibility()
                # This highlights the index in the tree for us
                project.setCurrentIndex(index)
                # Loop through the parents to expand the tree
                # all the way up to the selected index.
                while index.isValid():
                    project.expand(index)
                    index = index.parent()
                break

    @property
    def children(self):
        return self._projects_area.layout().count()

    def add_project(self, project):
        if project not in self.projects:
            ptree = TreeProjectsWidget(project)
            ptree.setParent(self)
            self.connect(ptree, SIGNAL("setActiveProject(PyQt_PyObject)"),
                         self._set_active_project)
            self.connect(ptree, SIGNAL("closeProject(PyQt_PyObject)"),
                         self._close_project)
            pmodel = project.model
            ptree.setModel(pmodel)
            ptree.header().title = project.name
            ptree.header().path = project.path
            pindex = pmodel.index(pmodel.rootPath())
            ptree.setRootIndex(pindex)
            #self._widget.layout().addWidget(scrollable_wrapper(ptree))
            self._projects_area.layout().addWidget(ptree)
            if self._active_project is None:
                ptree.set_default_project()
            self.projects.append(ptree)
            ptree.setGeometry(self.geometry())

    def _close_project(self, widget):
        """Close the project related to the tree widget."""
        self.projects.remove(widget)
        if self._active_project == widget and len(self.projects) > 0:
            self.projects[0].set_default_project()
        self._layout.removeWidget(widget)
        ninjaide = IDE.get_service('ide')
        ninjaide.filesystem.close_project(widget.project.path)
        widget.deleteLater()

    def _set_active_project(self, tree_proj):
        if self._active_project is not None:
            self._active_project.set_default_project(False)
        self._active_project = tree_proj

    def close_opened_projects(self):
        for project in reversed(self.projects):
            self._close_project(project)

    def save_project(self):
        """Save all the opened files that belongs to the actual project."""
        if self._active_project:
            path = self._active_project.project.path
            main_container = IDE.get_service('main_container')
            if path and main_container:
                main_container.save_project(path)

    def create_new_project(self):
        wizard = new_project_manager.NewProjectManager(self)
        wizard.show()

    @property
    def current_project(self):
        if self._active_project:
            return self._active_project.project

    @property
    def current_tree(self):
        return self._active_project

    def save_recent_projects(self, folder):
        settings = IDE.data_settings()
        recent_project_list = settings.value('recentProjects', {})
        #if already exist on the list update the date time
        projectProperties = json_manager.read_ninja_project(folder)
        name = projectProperties.get('name', '')
        description = projectProperties.get('description', '')

        if name == '':
            name = file_manager.get_basename(folder)

        if description == '':
            description = translations.TR_NO_DESCRIPTION

        if folder in recent_project_list:
            properties = recent_project_list[folder]
            properties["lastopen"] = QDateTime.currentDateTime()
            properties["name"] = name
            properties["description"] = description
            recent_project_list[folder] = properties
        else:
            recent_project_list[folder] = {
                "name": name,
                "description": description,
                "isFavorite": False, "lastopen": QDateTime.currentDateTime()}
            #if the length of the project list it's high that 10 then delete
            #the most old
            #TODO: add the length of available projects to setting
            if len(recent_project_list) > 10:
                del recent_project_list[self.find_most_old_open(
                    recent_project_list)]
        settings.setValue('recentProjects', recent_project_list)

    def find_most_old_open(self, recent_project_list):
        listFounder = []
        for recent_project_path, content in list(recent_project_list.items()):
            listFounder.append((recent_project_path, int(
                content["lastopen"].toString("yyyyMMddHHmmzzz"))))
        listFounder = sorted(listFounder, key=lambda date: listFounder[1],
                             reverse=True)   # sort by date last used
        return listFounder[0][0]

    def reject(self):
        if self.parent() is None:
            self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self)

    def closeEvent(self, event):
        self.emit(SIGNAL("dockWidget(PyQt_PyObject)"), self)
        event.ignore()
コード例 #37
0
class XOrbQueryContainer(QWidget):
    """ """
    entriesUpdated = qt.Signal()
    enterCompoundRequested = qt.Signal(object, object)
    exitCompoundRequested = qt.Signal()
    
    def __init__( self, parent = None ):
        super(XOrbQueryContainer, self).__init__( parent )
        
        # load the user interface
        projexui.loadUi(__file__, self)
        
        # define custom properties
        self._queryWidget   = parent
        self._entryWidget   = QWidget(self)
        self._currentJoiner = QueryCompound.Op.And
        
        layout = QVBoxLayout()
        layout.addStretch(1)
        layout.setSpacing(3)
        self._entryWidget.setLayout(layout)
        self.uiQueryAREA.setWidget(self._entryWidget)
        
        # set default properties
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        
        # create connections (use old-style syntax or PySide errors)
        self.connect(self.uiBackBTN, SIGNAL('clicked()'), self.exitCompound)
        self.entriesUpdated.connect(self.refreshEntries)
    
    def addEntry(self, query=None, entry=None):
        if query is None:
            query = Query()
        
        layout = self._entryWidget.layout()
        index = layout.count() - 1
        if entry:
            index = layout.indexOf(entry) + 1
        
        widget = XOrbQueryEntryWidget(self, self.tableType())
        layout.insertWidget(index, widget)
        
        widget.setQuery(query)
        
        if not self.signalsBlocked():
            self.entriesUpdated.emit()
        
        return widget
    
    def checkedEntries(self):
        """
        Returns the widgets that are checked for this widget.
        
        :return     [<XOrbQueryEntryWidget>, ..]
        """
        return [entry for entry in self.entries() if entry.isChecked()]
    
    def clear(self):
        """
        Clears out the widgets for this query builder.
        """
        layout = self._entryWidget.layout()
        for i in range(layout.count() - 1):
            widget = layout.itemAt(i).widget()
            widget.close()
    
    def createCompoundFromChecked(self):
        """
        Creates a new compound query from the checked entry list.
        
        :return     <orb.QueryCompound>
        """
        checked_entries = self.checkedEntries()
        
        if len(checked_entries) <= 1:
            return QueryCompound()
        
        self.setUpdatesEnabled(False)
        joiner = self.currentJoiner()
        query = Query()
        for entry in checked_entries:
            if joiner == QueryCompound.Op.And:
                query &= entry.query()
            else:
                query |= entry.query()
        
        # clear out the existing containers
        first = checked_entries[0]
        first.setQuery(query)
        first.setChecked(False)
        
        layout = self._entryWidget.layout()
        for i in range(len(checked_entries) - 1, 0, -1):
            w = checked_entries[i]
            layout.takeAt(layout.indexOf(w))
            w.close()
        
        self.refreshEntries()
        self.setUpdatesEnabled(True)
        
        if not self.signalsBlocked():
            self.enterCompound(first, query)
    
    def currentJoiner(self):
        return self._currentJoiner
    
    def enterCompound(self, entry, query):
        # enter an existing compound
        if QueryCompound.typecheck(query):
            self.enterCompoundRequested.emit(entry, query)
        
        # create a new compound from the checked entries
        else:
            self.createCompoundFromChecked()
    
    def entries(self):
        """
        Returns the entry widgets for this widget.
        
        :return     [<XOrbQueryEntryWidget>, ..]
        """
        layout = self._entryWidget.layout()
        output = []
        for i in range(layout.count() - 1):
            widget = layout.itemAt(i).widget()
            if not isinstance(widget, XOrbQueryEntryWidget):
                continue
            output.append(widget)
        return output
    
    def exitCompound(self):
        self.exitCompoundRequested.emit()
    
    def isNull(self):
        """
        Returns whether or not any widgets have been defined for this
        container yet.
        
        :return     <bool>
        """
        return self._entryWidget.layout().count() <= 1
    
    def moveDown(self, entry):
        """
        Moves the current query down one entry.
        """
        if not entry:
            return
        
        entries = self.entries()
        next = entries[entries.index(entry) + 1]
        
        entry_q = entry.query()
        next_q  = next.query()
        
        next.setQuery(entry_q)
        entry.setQuery(next_q)
    
    def moveUp(self, entry):
        """
        Moves the current query down up one entry.
        """
        if not entry:
            return
        
        entries = self.entries()
        next = entries[entries.index(entry) - 1]
        
        entry_q = entry.query()
        next_q  = next.query()
        
        next.setQuery(entry_q)
        entry.setQuery(next_q)
    
    def pluginFactory(self):
        """
        Returns the plugin factory for this widget.  You can define a custom
        factory for handling specific columns or column types based on your
        table type.
        
        :return     <XOrbQueryPluginFactory>
        """
        return self._queryWidget.pluginFactory()
    
    def query(self):
        """
        Returns the query that is defined by this current panel.
        
        :return     <orb.Query>
        """
        joiner = self.currentJoiner()
        query = Query()
        for entry in self.entries():
            if joiner == QueryCompound.Op.And:
                query &= entry.query()
            else:
                query |= entry.query()
        
        query.setName(self.uiNameTXT.text())
        
        return query
    
    def queryWidget(self):
        """
        Returns the query widget linked with this container.
        
        :return     <XOrbQueryWidget>
        """
        return self._queryWidget
    
    def removeEntry(self, entry):
        if not entry:
            return
        
        layout = self._entryWidget.layout()
        if layout.count() == 2:
            print 'clearing query'
            entry.setQuery(Query())
            return
        
        layout.takeAt(layout.indexOf(entry))
        entry.close()
        
        if not self.signalsBlocked():
            self.entriesUpdated.emit()
    
    def refreshEntries(self):
        layout = self._entryWidget.layout()
        for i in range(layout.count() - 1):
            widget = layout.itemAt(i).widget()
            widget.setFirst(i == 0)
            widget.setLast(i == (layout.count() - 2))
    
    def setCurrentJoiner(self, joiner):
        self._currentJoiner = joiner
        layout = self._entryWidget.layout()
        for i in range(layout.count() - 1):
            widget = layout.itemAt(i).widget()
            widget.setJoiner(joiner)
    
    def setQuery(self, query):
        """
        Sets the query for this wigdet to the inputed query instance.
        
        :param      query | <orb.Query> || <orb.QueryCompound>
        """
        if not self.isNull() and hash(query) == hash(self.query()):
            return
        
        # add entries
        table = self.tableType()
        
        self.setUpdatesEnabled(False)
        self.blockSignals(True)
        self.clear()
        
        if query is None or table is None:
            self.setEnabled(False)
            self.setUpdatesEnabled(True)
            self.blockSignals(False)
            return
        else:
            self.setEnabled(True)
        
        # load the queries for this item
        if QueryCompound.typecheck(query):
            queries = query.queries()
            self.setCurrentJoiner(query.operatorType())
        else:
            queries = [query]
        
        self.uiNameTXT.setText(query.name())
        
        layout = self._entryWidget.layout()
        for index, query in enumerate(queries):
            widget = self.addEntry(query)
            widget.setFirst(index == 0)
            widget.setLast(index == (len(queries) - 1))
            widget.setJoiner(self.currentJoiner())
        
        self.setUpdatesEnabled(True)
        self.blockSignals(False)
    
    def setShowBack(self, state):
        # check to see if we're working on the current query
        self.uiBackBTN.setVisible(state)
        self.uiNameTXT.setVisible(state)
    
    def tableType(self):
        """
        Returns the table type instance for this widget.
        
        :return     <subclass of orb.Table>
        """
        return self._queryWidget.tableType()
コード例 #38
0
ファイル: console.py プロジェクト: Geoneer/QGIS
class PythonConsoleWidget(QWidget):

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console"))

        self.settings = QSettings()

        self.shell = ShellScintilla(self)
        self.setFocusProxy(self.shell)
        self.shellOut = ShellOutputScintilla(self)
        self.tabEditorWidget = EditorTabWidget(self)

        ##------------ UI -------------------------------

        self.splitterEditor = QSplitter(self)
        self.splitterEditor.setOrientation(Qt.Horizontal)
        self.splitterEditor.setHandleWidth(6)
        self.splitterEditor.setChildrenCollapsible(True)

        self.shellOutWidget = QWidget(self)
        self.shellOutWidget.setLayout(QVBoxLayout())
        self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0)
        self.shellOutWidget.layout().addWidget(self.shellOut)

        self.splitter = QSplitter(self.splitterEditor)
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setHandleWidth(3)
        self.splitter.setChildrenCollapsible(False)
        self.splitter.addWidget(self.shellOutWidget)
        self.splitter.addWidget(self.shell)

        #self.splitterEditor.addWidget(self.tabEditorWidget)

        self.splitterObj = QSplitter(self.splitterEditor)
        self.splitterObj.setHandleWidth(3)
        self.splitterObj.setOrientation(Qt.Horizontal)
        #self.splitterObj.setSizes([0, 0])
        #self.splitterObj.setStretchFactor(0, 1)

        self.widgetEditor = QWidget(self.splitterObj)
        self.widgetFind = QWidget(self)

        self.listClassMethod = QTreeWidget(self.splitterObj)
        self.listClassMethod.setColumnCount(2)
        objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector")
        self.listClassMethod.setHeaderLabels([objInspLabel, ''])
        self.listClassMethod.setColumnHidden(1, True)
        self.listClassMethod.setAlternatingRowColors(True)

        #self.splitterEditor.addWidget(self.widgetEditor)
        #self.splitterObj.addWidget(self.listClassMethod)
        #self.splitterObj.addWidget(self.widgetEditor)

        # Hide side editor on start up
        self.splitterObj.hide()
        self.listClassMethod.hide()
        # Hide search widget on start up
        self.widgetFind.hide()

        sizes = self.splitter.sizes()
        self.splitter.setSizes(sizes)

        ##----------------Restore Settings------------------------------------

        self.restoreSettingsConsole()

        ##------------------Toolbar Editor-------------------------------------

        ## Action for Open File
        openFileBt = QCoreApplication.translate("PythonConsole", "Open file")
        self.openFileButton = QAction(self)
        self.openFileButton.setCheckable(False)
        self.openFileButton.setEnabled(True)
        self.openFileButton.setIcon(QgsApplication.getThemeIcon("console/iconOpenConsole.png"))
        self.openFileButton.setMenuRole(QAction.PreferencesRole)
        self.openFileButton.setIconVisibleInMenu(True)
        self.openFileButton.setToolTip(openFileBt)
        self.openFileButton.setText(openFileBt)

        openExtEditorBt = QCoreApplication.translate("PythonConsole", "Open in external editor")
        self.openInEditorButton = QAction(self)
        self.openInEditorButton.setCheckable(False)
        self.openInEditorButton.setEnabled(True)
        self.openInEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.openInEditorButton.setMenuRole(QAction.PreferencesRole)
        self.openInEditorButton.setIconVisibleInMenu(True)
        self.openInEditorButton.setToolTip(openExtEditorBt)
        self.openInEditorButton.setText(openExtEditorBt)
        ## Action for Save File
        saveFileBt = QCoreApplication.translate("PythonConsole", "Save")
        self.saveFileButton = QAction(self)
        self.saveFileButton.setCheckable(False)
        self.saveFileButton.setEnabled(False)
        self.saveFileButton.setIcon(QgsApplication.getThemeIcon("console/iconSaveConsole.png"))
        self.saveFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveFileButton.setIconVisibleInMenu(True)
        self.saveFileButton.setToolTip(saveFileBt)
        self.saveFileButton.setText(saveFileBt)
        ## Action for Save File As
        saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As...")
        self.saveAsFileButton = QAction(self)
        self.saveAsFileButton.setCheckable(False)
        self.saveAsFileButton.setEnabled(True)
        self.saveAsFileButton.setIcon(QgsApplication.getThemeIcon("console/iconSaveAsConsole.png"))
        self.saveAsFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveAsFileButton.setIconVisibleInMenu(True)
        self.saveAsFileButton.setToolTip(saveAsFileBt)
        self.saveAsFileButton.setText(saveAsFileBt)
        ## Action Cut
        cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut")
        self.cutEditorButton = QAction(self)
        self.cutEditorButton.setCheckable(False)
        self.cutEditorButton.setEnabled(True)
        self.cutEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconCutEditorConsole.png"))
        self.cutEditorButton.setMenuRole(QAction.PreferencesRole)
        self.cutEditorButton.setIconVisibleInMenu(True)
        self.cutEditorButton.setToolTip(cutEditorBt)
        self.cutEditorButton.setText(cutEditorBt)
        ## Action Copy
        copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy")
        self.copyEditorButton = QAction(self)
        self.copyEditorButton.setCheckable(False)
        self.copyEditorButton.setEnabled(True)
        self.copyEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconCopyEditorConsole.png"))
        self.copyEditorButton.setMenuRole(QAction.PreferencesRole)
        self.copyEditorButton.setIconVisibleInMenu(True)
        self.copyEditorButton.setToolTip(copyEditorBt)
        self.copyEditorButton.setText(copyEditorBt)
        ## Action Paste
        pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste")
        self.pasteEditorButton = QAction(self)
        self.pasteEditorButton.setCheckable(False)
        self.pasteEditorButton.setEnabled(True)
        self.pasteEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconPasteEditorConsole.png"))
        self.pasteEditorButton.setMenuRole(QAction.PreferencesRole)
        self.pasteEditorButton.setIconVisibleInMenu(True)
        self.pasteEditorButton.setToolTip(pasteEditorBt)
        self.pasteEditorButton.setText(pasteEditorBt)
        ## Action Run Script (subprocess)
        runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run script")
        self.runScriptEditorButton = QAction(self)
        self.runScriptEditorButton.setCheckable(False)
        self.runScriptEditorButton.setEnabled(True)
        self.runScriptEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconRunScriptConsole.png"))
        self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole)
        self.runScriptEditorButton.setIconVisibleInMenu(True)
        self.runScriptEditorButton.setToolTip(runScriptEditorBt)
        self.runScriptEditorButton.setText(runScriptEditorBt)
        ## Action Run Script (subprocess)
        commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment")
        self.commentEditorButton = QAction(self)
        self.commentEditorButton.setCheckable(False)
        self.commentEditorButton.setEnabled(True)
        self.commentEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconCommentEditorConsole.png"))
        self.commentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.commentEditorButton.setIconVisibleInMenu(True)
        self.commentEditorButton.setToolTip(commentEditorBt)
        self.commentEditorButton.setText(commentEditorBt)
        ## Action Run Script (subprocess)
        uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment")
        self.uncommentEditorButton = QAction(self)
        self.uncommentEditorButton.setCheckable(False)
        self.uncommentEditorButton.setEnabled(True)
        self.uncommentEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconUncommentEditorConsole.png"))
        self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.uncommentEditorButton.setIconVisibleInMenu(True)
        self.uncommentEditorButton.setToolTip(uncommentEditorBt)
        self.uncommentEditorButton.setText(uncommentEditorBt)
        ## Action for Object browser
        objList = QCoreApplication.translate("PythonConsole", "Object Inspector")
        self.objectListButton = QAction(self)
        self.objectListButton.setCheckable(True)
        self.objectListButton.setEnabled(self.settings.value("pythonConsole/enableObjectInsp",
                                                             False, type=bool))
        self.objectListButton.setIcon(QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png"))
        self.objectListButton.setMenuRole(QAction.PreferencesRole)
        self.objectListButton.setIconVisibleInMenu(True)
        self.objectListButton.setToolTip(objList)
        self.objectListButton.setText(objList)
        ## Action for Find text
        findText = QCoreApplication.translate("PythonConsole", "Find Text")
        self.findTextButton = QAction(self)
        self.findTextButton.setCheckable(True)
        self.findTextButton.setEnabled(True)
        self.findTextButton.setIcon(QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png"))
        self.findTextButton.setMenuRole(QAction.PreferencesRole)
        self.findTextButton.setIconVisibleInMenu(True)
        self.findTextButton.setToolTip(findText)
        self.findTextButton.setText(findText)

        ##----------------Toolbar Console-------------------------------------

        ## Action Show Editor
        showEditor = QCoreApplication.translate("PythonConsole", "Show editor")
        self.showEditorButton = QAction(self)
        self.showEditorButton.setEnabled(True)
        self.showEditorButton.setCheckable(True)
        self.showEditorButton.setIcon(QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.showEditorButton.setMenuRole(QAction.PreferencesRole)
        self.showEditorButton.setIconVisibleInMenu(True)
        self.showEditorButton.setToolTip(showEditor)
        self.showEditorButton.setText(showEditor)
        ## Action for Clear button
        clearBt = QCoreApplication.translate("PythonConsole", "Clear console")
        self.clearButton = QAction(self)
        self.clearButton.setCheckable(False)
        self.clearButton.setEnabled(True)
        self.clearButton.setIcon(QgsApplication.getThemeIcon("console/iconClearConsole.png"))
        self.clearButton.setMenuRole(QAction.PreferencesRole)
        self.clearButton.setIconVisibleInMenu(True)
        self.clearButton.setToolTip(clearBt)
        self.clearButton.setText(clearBt)
        ## Action for settings
        optionsBt = QCoreApplication.translate("PythonConsole", "Settings")
        self.optionsButton = QAction(self)
        self.optionsButton.setCheckable(False)
        self.optionsButton.setEnabled(True)
        self.optionsButton.setIcon(QgsApplication.getThemeIcon("console/iconSettingsConsole.png"))
        self.optionsButton.setMenuRole(QAction.PreferencesRole)
        self.optionsButton.setIconVisibleInMenu(True)
        self.optionsButton.setToolTip(optionsBt)
        self.optionsButton.setText(optionsBt)
        ## Action menu for class
        actionClassBt = QCoreApplication.translate("PythonConsole", "Import Class")
        self.actionClass = QAction(self)
        self.actionClass.setCheckable(False)
        self.actionClass.setEnabled(True)
        self.actionClass.setIcon(QgsApplication.getThemeIcon("console/iconClassConsole.png"))
        self.actionClass.setMenuRole(QAction.PreferencesRole)
        self.actionClass.setIconVisibleInMenu(True)
        self.actionClass.setToolTip(actionClassBt)
        self.actionClass.setText(actionClassBt)
        ## Import Processing class
        loadProcessingBt = QCoreApplication.translate("PythonConsole", "Import Processing class")
        self.loadProcessingButton = QAction(self)
        self.loadProcessingButton.setCheckable(False)
        self.loadProcessingButton.setEnabled(True)
        self.loadProcessingButton.setIcon(QgsApplication.getThemeIcon("console/iconProcessingConsole.png"))
        self.loadProcessingButton.setMenuRole(QAction.PreferencesRole)
        self.loadProcessingButton.setIconVisibleInMenu(True)
        self.loadProcessingButton.setToolTip(loadProcessingBt)
        self.loadProcessingButton.setText(loadProcessingBt)
        ## Import QtCore class
        loadQtCoreBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore class")
        self.loadQtCoreButton = QAction(self)
        self.loadQtCoreButton.setCheckable(False)
        self.loadQtCoreButton.setEnabled(True)
        self.loadQtCoreButton.setIcon(QgsApplication.getThemeIcon("console/iconQtCoreConsole.png"))
        self.loadQtCoreButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtCoreButton.setIconVisibleInMenu(True)
        self.loadQtCoreButton.setToolTip(loadQtCoreBt)
        self.loadQtCoreButton.setText(loadQtCoreBt)
        ## Import QtGui class
        loadQtGuiBt = QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui class")
        self.loadQtGuiButton = QAction(self)
        self.loadQtGuiButton.setCheckable(False)
        self.loadQtGuiButton.setEnabled(True)
        self.loadQtGuiButton.setIcon(QgsApplication.getThemeIcon("console/iconQtGuiConsole.png"))
        self.loadQtGuiButton.setMenuRole(QAction.PreferencesRole)
        self.loadQtGuiButton.setIconVisibleInMenu(True)
        self.loadQtGuiButton.setToolTip(loadQtGuiBt)
        self.loadQtGuiButton.setText(loadQtGuiBt)
        ## Action for Run script
        runBt = QCoreApplication.translate("PythonConsole", "Run command")
        self.runButton = QAction(self)
        self.runButton.setCheckable(False)
        self.runButton.setEnabled(True)
        self.runButton.setIcon(QgsApplication.getThemeIcon("console/iconRunConsole.png"))
        self.runButton.setMenuRole(QAction.PreferencesRole)
        self.runButton.setIconVisibleInMenu(True)
        self.runButton.setToolTip(runBt)
        self.runButton.setText(runBt)
        ## Help action
        helpBt = QCoreApplication.translate("PythonConsole", "Help")
        self.helpButton = QAction(self)
        self.helpButton.setCheckable(False)
        self.helpButton.setEnabled(True)
        self.helpButton.setIcon(QgsApplication.getThemeIcon("console/iconHelpConsole.png"))
        self.helpButton.setMenuRole(QAction.PreferencesRole)
        self.helpButton.setIconVisibleInMenu(True)
        self.helpButton.setToolTip(helpBt)
        self.helpButton.setText(helpBt)

        self.toolBar = QToolBar()
        self.toolBar.setEnabled(True)
        self.toolBar.setFocusPolicy(Qt.NoFocus)
        self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBar.setLayoutDirection(Qt.LeftToRight)
        self.toolBar.setIconSize(QSize(16, 16))
        self.toolBar.setMovable(False)
        self.toolBar.setFloatable(False)
        self.toolBar.addAction(self.clearButton)
        self.toolBar.addAction(self.actionClass)
        self.toolBar.addAction(self.runButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.showEditorButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.optionsButton)
        self.toolBar.addAction(self.helpButton)

        self.toolBarEditor = QToolBar()
        self.toolBarEditor.setEnabled(False)
        self.toolBarEditor.setFocusPolicy(Qt.NoFocus)
        self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBarEditor.setLayoutDirection(Qt.LeftToRight)
        self.toolBarEditor.setIconSize(QSize(16, 16))
        self.toolBarEditor.setMovable(False)
        self.toolBarEditor.setFloatable(False)
        self.toolBarEditor.addAction(self.openFileButton)
        self.toolBarEditor.addAction(self.openInEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.saveFileButton)
        self.toolBarEditor.addAction(self.saveAsFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.runScriptEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.findTextButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.cutEditorButton)
        self.toolBarEditor.addAction(self.copyEditorButton)
        self.toolBarEditor.addAction(self.pasteEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.commentEditorButton)
        self.toolBarEditor.addAction(self.uncommentEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.objectListButton)

        ## Menu Import Class
        self.classMenu = QMenu()
        self.classMenu.addAction(self.loadProcessingButton)
        self.classMenu.addAction(self.loadQtCoreButton)
        self.classMenu.addAction(self.loadQtGuiButton)
        cM = self.toolBar.widgetForAction(self.actionClass)
        cM.setMenu(self.classMenu)
        cM.setPopupMode(QToolButton.InstantPopup)

        self.widgetButton = QWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.widgetButton.sizePolicy().hasHeightForWidth())
        self.widgetButton.setSizePolicy(sizePolicy)

        self.widgetButtonEditor = QWidget(self.widgetEditor)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.widgetButtonEditor.sizePolicy().hasHeightForWidth())
        self.widgetButtonEditor.setSizePolicy(sizePolicy)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.shellOut.sizePolicy().hasHeightForWidth())
        self.shellOut.setSizePolicy(sizePolicy)

        self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        ##------------ Layout -------------------------------

        self.mainLayout = QGridLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1)
        self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1)

        self.shellOutWidget.layout().insertWidget(0, self.toolBar)

        self.layoutEditor = QGridLayout(self.widgetEditor)
        self.layoutEditor.setMargin(0)
        self.layoutEditor.setSpacing(0)
        self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1)
        self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1)

        ## Layout for the find widget
        self.layoutFind = QGridLayout(self.widgetFind)
        self.layoutFind.setContentsMargins(0, 0, 0, 0)
        self.lineEditFind = QgsFilterLineEdit()
        placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find...")

        if pyqtconfig.Configuration().qt_version >= 0x40700:
            self.lineEditFind.setPlaceholderText(placeHolderTxt)
        else:
            self.lineEditFind.setToolTip(placeHolderTxt)
        self.findNextButton = QToolButton()
        self.findNextButton.setEnabled(False)
        toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next")
        self.findNextButton.setToolTip(toolTipfindNext)
        self.findNextButton.setIcon(QgsApplication.getThemeIcon("console/iconSearchNextEditorConsole.png"))
        self.findNextButton.setIconSize(QSize(24, 24))
        self.findNextButton.setAutoRaise(True)
        self.findPrevButton = QToolButton()
        self.findPrevButton.setEnabled(False)
        toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous")
        self.findPrevButton.setToolTip(toolTipfindPrev)
        self.findPrevButton.setIcon(QgsApplication.getThemeIcon("console/iconSearchPrevEditorConsole.png"))
        self.findPrevButton.setIconSize(QSize(24, 24))
        self.findPrevButton.setAutoRaise(True)
        self.caseSensitive = QCheckBox()
        caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive")
        self.caseSensitive.setText(caseSensTr)
        self.wholeWord = QCheckBox()
        wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word")
        self.wholeWord.setText(wholeWordTr)
        self.wrapAround = QCheckBox()
        self.wrapAround.setChecked(True)
        wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around")
        self.wrapAround.setText(wrapAroundTr)
        self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1)
        self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1)
        self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1)
        self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1)
        self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1)
        self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1)

        ##------------ Add first Tab in Editor -------------------------------

        #self.tabEditorWidget.newTabEditor(tabName='first', filename=None)

        ##------------ Signal -------------------------------

        self.findTextButton.toggled.connect(self.findTextEditor)
        self.objectListButton.toggled.connect(self.toggleObjectListWidget)
        self.commentEditorButton.triggered.connect(self.commentCode)
        self.uncommentEditorButton.triggered.connect(self.uncommentCode)
        self.runScriptEditorButton.triggered.connect(self.runScriptEditor)
        self.cutEditorButton.triggered.connect(self.cutEditor)
        self.copyEditorButton.triggered.connect(self.copyEditor)
        self.pasteEditorButton.triggered.connect(self.pasteEditor)
        self.showEditorButton.toggled.connect(self.toggleEditor)
        self.clearButton.triggered.connect(self.shellOut.clearConsole)
        self.optionsButton.triggered.connect(self.openSettings)
        self.loadProcessingButton.triggered.connect(self.processing)
        self.loadQtCoreButton.triggered.connect(self.qtCore)
        self.loadQtGuiButton.triggered.connect(self.qtGui)
        self.runButton.triggered.connect(self.shell.entered)
        self.openFileButton.triggered.connect(self.openScriptFile)
        self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor)
        self.saveFileButton.triggered.connect(self.saveScriptFile)
        self.saveAsFileButton.triggered.connect(self.saveAsScriptFile)
        self.helpButton.triggered.connect(self.openHelp)
        self.connect(self.listClassMethod, SIGNAL('itemClicked(QTreeWidgetItem*, int)'),
                     self.onClickGoToLine)
        self.lineEditFind.returnPressed.connect(self._findText)
        self.findNextButton.clicked.connect(self._findNext)
        self.findPrevButton.clicked.connect(self._findPrev)
        self.lineEditFind.textChanged.connect(self._textFindChanged)

    def _findText(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(True)

    def _findNext(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(True)

    def _findPrev(self):
        self.tabEditorWidget.currentWidget().newEditor.findText(False)

    def _textFindChanged(self):
        if self.lineEditFind.text():
            self.findNextButton.setEnabled(True)
            self.findPrevButton.setEnabled(True)
        else:
            self.lineEditFind.setStyleSheet('')
            self.findNextButton.setEnabled(False)
            self.findPrevButton.setEnabled(False)

    def onClickGoToLine(self, item, column):
        tabEditor = self.tabEditorWidget.currentWidget().newEditor
        if item.text(1) == 'syntaxError':
            check = tabEditor.syntaxCheck(fromContextMenu=False)
            if check and not tabEditor.isReadOnly():
                self.tabEditorWidget.currentWidget().save()
            return
        linenr = int(item.text(1))
        itemName = str(item.text(0))
        charPos = itemName.find(' ')
        if charPos != -1:
            objName = itemName[0:charPos]
        else:
            objName = itemName
        tabEditor.goToLine(objName, linenr)

    def processing(self):
        self.shell.commandConsole('processing')

    def qtCore(self):
        self.shell.commandConsole('qtCore')

    def qtGui(self):
        self.shell.commandConsole('qtGui')

    def toggleEditor(self, checked):
        self.splitterObj.show() if checked else self.splitterObj.hide()
        if not self.tabEditorWidget:
            self.tabEditorWidget.enableToolBarEditor(checked)
            self.tabEditorWidget.restoreTabsOrAddNew()

    def toggleObjectListWidget(self, checked):
        self.listClassMethod.show() if checked else self.listClassMethod.hide()

    def findTextEditor(self, checked):
        self.widgetFind.show() if checked else self.widgetFind.hide()

    def pasteEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.paste()

    def cutEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.cut()

    def copyEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.copy()

    def runScriptEditor(self):
        self.tabEditorWidget.currentWidget().newEditor.runScriptCode()

    def commentCode(self):
        self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(True)

    def uncommentCode(self):
        self.tabEditorWidget.currentWidget().newEditor.commentEditorCode(False)

    def openScriptFileExtEditor(self):
        tabWidget = self.tabEditorWidget.currentWidget()
        path = tabWidget.path
        import subprocess
        try:
            subprocess.Popen([os.environ['EDITOR'], path])
        except KeyError:
            QDesktopServices.openUrl(QUrl.fromLocalFile(path))

    def openScriptFile(self):
        lastDirPath = self.settings.value("pythonConsole/lastDirPath", QDir.homePath())
        openFileTr = QCoreApplication.translate("PythonConsole", "Open File")
        fileList = QFileDialog.getOpenFileNames(
            self, openFileTr, lastDirPath, "Script file (*.py)")
        if fileList:
            for pyFile in fileList:
                for i in range(self.tabEditorWidget.count()):
                    tabWidget = self.tabEditorWidget.widget(i)
                    if tabWidget.path == pyFile:
                        self.tabEditorWidget.setCurrentWidget(tabWidget)
                        break
                else:
                    tabName = QFileInfo(pyFile).fileName()
                    self.tabEditorWidget.newTabEditor(tabName, pyFile)

                    lastDirPath = QFileInfo(pyFile).path()
                    self.settings.setValue("pythonConsole/lastDirPath", pyFile)
                    self.updateTabListScript(pyFile, action='append')

    def saveScriptFile(self):
        tabWidget = self.tabEditorWidget.currentWidget()
        try:
            tabWidget.save()
        except (IOError, OSError) as error:
            msgText = QCoreApplication.translate('PythonConsole',
                                                 'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path,
                                                                                                              error.strerror)
            self.callWidgetMessageBarEditor(msgText, 2, False)

    def saveAsScriptFile(self, index=None):
        tabWidget = self.tabEditorWidget.currentWidget()
        if not index:
            index = self.tabEditorWidget.currentIndex()
        if not tabWidget.path:
            fileName = self.tabEditorWidget.tabText(index) + '.py'
            folder = self.settings.value("pythonConsole/lastDirPath", QDir.home())
            pathFileName = os.path.join(folder, fileName)
            fileNone = True
        else:
            pathFileName = tabWidget.path
            fileNone = False
        saveAsFileTr = QCoreApplication.translate("PythonConsole", "Save File As")
        filename = QFileDialog.getSaveFileName(self,
                                               saveAsFileTr,
                                               pathFileName, "Script file (*.py)")
        if filename:
            try:
                tabWidget.save(filename)
            except (IOError, OSError) as error:
                msgText = QCoreApplication.translate('PythonConsole',
                                                     'The file <b>{0}</b> could not be saved. Error: {1}').format(tabWidget.path,
                                                                                                                  error.strerror)
                self.callWidgetMessageBarEditor(msgText, 2, False)
                if fileNone:
                    tabWidget.path = None
                else:
                    tabWidget.path = pathFileName
                return

            if not fileNone:
                self.updateTabListScript(pathFileName, action='remove')

    def openHelp(self):
        QgsContextHelp.run("PythonConsole")

    def openSettings(self):
        if optionsDialog(self).exec_():
            self.shell.refreshSettingsShell()
            self.shellOut.refreshSettingsOutput()
            self.tabEditorWidget.refreshSettingsEditor()

    def callWidgetMessageBar(self, text):
        self.shellOut.widgetMessageBar(iface, text)

    def callWidgetMessageBarEditor(self, text, level, timed):
        self.tabEditorWidget.widgetMessageBar(iface, text, level, timed)

    def updateTabListScript(self, script, action=None):
        if action == 'remove':
            self.tabListScript.remove(script)
        elif action == 'append':
            if not self.tabListScript:
                self.tabListScript = []
            if script not in self.tabListScript:
                self.tabListScript.append(script)
        else:
            self.tabListScript = []
        self.settings.setValue("pythonConsole/tabScripts",
                               self.tabListScript)

    def saveSettingsConsole(self):
        self.settings.setValue("pythonConsole/splitterConsole", self.splitter.saveState())
        self.settings.setValue("pythonConsole/splitterObj", self.splitterObj.saveState())
        self.settings.setValue("pythonConsole/splitterEditor", self.splitterEditor.saveState())

        self.shell.writeHistoryFile(True)

    def restoreSettingsConsole(self):
        storedTabScripts = self.settings.value("pythonConsole/tabScripts", [])
        self.tabListScript = storedTabScripts
        self.splitter.restoreState(self.settings.value("pythonConsole/splitterConsole", QByteArray()))
        self.splitterEditor.restoreState(self.settings.value("pythonConsole/splitterEditor", QByteArray()))
        self.splitterObj.restoreState(self.settings.value("pythonConsole/splitterObj", QByteArray()))
コード例 #39
0
 def createWidget(self, parent):
     widget = QWidget(parent)
     widget.setLayout(QHBoxLayout())
     widget.layout().setContentsMargins(0, 0, 0, 0)
     return widget