Пример #1
1
class DialogSaveFiles(QDialog):
    def __init__(self, files, editor_container, parent):
        QDialog.__init__(self, parent)
        self.setWindowTitle(self.tr("Archivos no guardados!"))
        self._event_ignore = False
        self._editor_container = editor_container
        vLayout = QVBoxLayout(self)
        label = QLabel(self.tr("Los siguientes archivos se han modificado. " "Guardarlos?"))
        vLayout.addWidget(label)

        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        for e, _file in enumerate(files):
            if not _file:
                _file = "Untitled"
            self.list_widget.addItem(_file)
            self.list_widget.item(e).setSelected(True)
        vLayout.addWidget(self.list_widget)

        box_buttons = QHBoxLayout()
        btn_nothing = QPushButton(self.tr("Ninguno"))
        btn_save = QPushButton(self.tr("Guardar Selección"))
        btn_cancel = QPushButton(self.tr("Cancelar"))
        box_buttons.addWidget(btn_nothing)
        box_buttons.addWidget(btn_save)
        box_buttons.addWidget(btn_cancel)

        vLayout.addLayout(box_buttons)

        self.key_scape = QShortcut(QKeySequence(Qt.Key_Escape), self)

        # Conexiones
        self.connect(self.key_scape, SIGNAL("activated()"), self._ignore)
        self.connect(btn_nothing, SIGNAL("clicked()"), self.close)
        self.connect(btn_save, SIGNAL("clicked()"), self._save)
        self.connect(btn_cancel, SIGNAL("clicked()"), self._ignore)

    def _ignore(self):
        self._event_ignore = True
        self.hide()

    def ignorado(self):
        return self._event_ignore

    def _save(self):
        selected_files = self.list_widget.selectedItems()
        for _file in selected_files:
            filename = _file.text()
            self._editor_container.save_selected(filename)
        self.close()
Пример #2
0
class GanttConfigure(QDialog):
    def __init__(self, sim, start, end):
        QDialog.__init__(self)
        #self.setCaption("Gantt configuration")
        self.layout = QVBoxLayout(self)

#        self._slider = QxtSpanSliderWidget(
#            sim.observe_window[0] // sim.cycles_per_ms,
#            min(sim.now(), sim.observe_window[1]) // sim.cycles_per_ms,
#            self)
        self._slider = QxtSpanSliderWidget(
            0,
            min(sim.now(), sim.duration) // sim.cycles_per_ms,
            self)
        self._slider.setSpan(start, end)
        self.layout.addWidget(self._slider)

        self._list_elements = QListWidget(self)
        for processor in sim.processors:
            item = QListWidgetItem(processor.name, self._list_elements)
            item.setData(Qt.UserRole, processor)
            self._list_elements.addItem(item)
        for task in sim.task_list:
            item = QListWidgetItem(task.name, self._list_elements)
            item.setData(Qt.UserRole, task)
            self._list_elements.addItem(item)
        #self._list_elements.setDragDropMode(QListWidget.InternalMove)
        for row in range(0, self._list_elements.count()):
            self._list_elements.item(row).setCheckState(Qt.Checked)
        self.layout.addWidget(self._list_elements)

        buttons = QWidget(self)
        buttons_layout = QHBoxLayout()
        buttons.setLayout(buttons_layout)
        buttons_layout.addStretch()
        ok_button = QPushButton("Ok")
        cancel_button = QPushButton("Cancel")
        ok_button.clicked.connect(self.accept)
        cancel_button.clicked.connect(self.reject)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        self.layout.addWidget(buttons)

    def get_start_date(self):
        return self._slider.lowerValue

    def get_end_date(self):
        return self._slider.upperValue

    def get_selected_items(self):
        res = []
        for row in range(0, self._list_elements.count()):
            if self._list_elements.item(row).checkState() == Qt.Checked:
                try:
                    data = self._list_elements.item(row).data(Qt.UserRole).toPyObject()
                except AttributeError:
                    data = self._list_elements.item(row).data(Qt.UserRole)

                res.append(data)
        return res
Пример #3
0
 def __init__(self, mainwin, pdfs):
     KDialog.__init__(self, mainwin)
     self.mainwin = mainwin
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setButtons(KDialog.ButtonCode(
         KDialog.User1 | KDialog.Ok | KDialog.Cancel))
     self.setButtonGuiItem(KDialog.Ok, KStandardGuiItem.print_())
     self.setButtonIcon(KDialog.User1, KIcon("edit-select-all"))
     self.setButtonText(KDialog.User1, i18n("Select all"))
     self.setCaption(i18n("Print documents"))
     b = KVBox(self)
     b.setSpacing(4)
     QLabel(i18n("Please select the files you want to print:"), b)
     fileList = QListWidget(b)
     fileList.setIconSize(QSize(22, 22))
     fileList.setWhatsThis(i18n(
         "These are the PDF documents that are up-to-date (i.e. newer than "
         "the LilyPond source document). "
         "Check the documents you want to send to the printer."))
     
     for pdf in pdfs:
         i = QListWidgetItem(KIcon("application-pdf"), os.path.basename(pdf),
             fileList)
         i.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable |
             Qt.ItemIsUserCheckable)
         i.setCheckState(Qt.Unchecked)
     
     fileList.item(0).setCheckState(Qt.Checked)
     self.fileList = fileList
     self.setMainWidget(b)
     self.resize(350, 200)
     self.pdfs = pdfs
     self.user1Clicked.connect(self.selectAll)
Пример #4
0
class SnappingDock(DockWidget):
    def __init__(self, iface, parent=None):
        super(SnappingDock, self).__init__(parent)
        self._iface = iface

        self.setWindowTitle(u'Snapping Panel')
        self.setObjectName(u'snappingDock')

        self._listWidget = QListWidget(self)
        self._listWidget.setSelectionMode(QAbstractItemView.NoSelection)
        self._listWidget.setDropIndicatorShown(False)

        self._dockLayout = QVBoxLayout(self)
        self._dockLayout.setObjectName(u'dockLayout')
        self._dockLayout.addWidget(self._listWidget)

        self._dockContents = QWidget(self)
        self._dockContents.setObjectName(u'dockContents')
        self._dockContents.setLayout(self._dockLayout)
        self.setWidget(self._dockContents)

        # Keep up-to-date with layers added and removed
        QgsMapLayerRegistry.instance().layersAdded.connect(self._layersAdded)
        QgsMapLayerRegistry.instance().layersRemoved.connect(
            self._layersRemoved)

    def refresh(self):
        self._listWidget.clear()
        layers = QgsMapLayerRegistry.instance().mapLayers()
        layerIds = layers.keys()
        sorted(layerIds)
        for layerId in layerIds:
            self.addLayer(layers[layerId])

    def addLayer(self, layer):
        if (layer is None or not layer.isValid()
                or layer.type() != QgsMapLayer.VectorLayer):
            return
        newItem = QListWidgetItem()
        newItem.setData(Qt.UserRole, layer.id())
        # newItem.setSizeHint(layerWidget.minimumSizeHint())
        self._listWidget.addItem(newItem)
        self._listWidget.setItemWidget(newItem,
                                       LayerSnappingWidget(layer, self))

    def removeLayer(self, layerId):
        for idx in range(0, self._listWidget.count() - 1):
            if self._listWidget.item(idx).data() == layerId:
                self._listWidget.takeItem(idx)
                return

    def _layersAdded(self, layers):
        for layer in layers:
            self.addLayer(layer)

    def _layersRemoved(self, layerIds):
        for idx in range(self._listWidget.count() - 1, 0):
            if self._listWidget.item(idx).data() in layerIds:
                self._listWidget.takeItem(idx)
Пример #5
0
class SnappingDock(DockWidget):

    def __init__(self, iface, parent=None):
        super(SnappingDock, self).__init__(parent)
        self._iface = iface

        self.setWindowTitle(u'Snapping Panel')
        self.setObjectName(u'snappingDock')

        self._listWidget = QListWidget(self)
        self._listWidget.setSelectionMode(QAbstractItemView.NoSelection)
        self._listWidget.setDropIndicatorShown(False)

        self._dockLayout = QVBoxLayout(self)
        self._dockLayout.setObjectName(u'dockLayout')
        self._dockLayout.addWidget(self._listWidget)

        self._dockContents = QWidget(self)
        self._dockContents.setObjectName(u'dockContents')
        self._dockContents.setLayout(self._dockLayout)
        self.setWidget(self._dockContents)

        # Keep up-to-date with layers added and removed
        QgsMapLayerRegistry.instance().layersAdded.connect(self._layersAdded)
        QgsMapLayerRegistry.instance().layersRemoved.connect(self._layersRemoved)

    def refresh(self):
        self._listWidget.clear()
        layers = QgsMapLayerRegistry.instance().mapLayers()
        layerIds = layers.keys()
        sorted(layerIds)
        for layerId in layerIds:
            self.addLayer(layers[layerId])

    def addLayer(self, layer):
        if (layer is None or not layer.isValid() or layer.type() != QgsMapLayer.VectorLayer):
            return
        newItem = QListWidgetItem()
        newItem.setData(Qt.UserRole, layer.id())
        # newItem.setSizeHint(layerWidget.minimumSizeHint())
        self._listWidget.addItem(newItem)
        self._listWidget.setItemWidget(newItem, LayerSnappingWidget(layer, self))

    def removeLayer(self, layerId):
        for idx in range(0, self._listWidget.count() - 1):
            if self._listWidget.item(idx).data() == layerId:
                self._listWidget.takeItem(idx)
                return

    def _layersAdded(self, layers):
        for layer in layers:
            self.addLayer(layer)

    def _layersRemoved(self, layerIds):
        for idx in range(self._listWidget.count() - 1, 0):
            if self._listWidget.item(idx).data() in layerIds:
                self._listWidget.takeItem(idx)
Пример #6
0
class TagsWidget(QWidget):
    tagsChanged = pyqtSignal(list)

    def __init__(self, parent=None):
        super(TagsWidget, self).__init__(parent)
        self.lineEdit = TagLineEdit(self)
        self.lineEdit.returnPressed.connect(
            lambda: QTimer.singleShot(0, self.addTag))
        self.listWidget = QListWidget(self)
        l = QVBoxLayout(self)
        l.addWidget(self.lineEdit)
        l.addWidget(self.listWidget)

        self.availableTags = []
        self.reload()

    def reload(self):
        tags = Session.query(Tag.name, Tag.id).all()
        self.tagsdict = dict(tags)
        self.availableTags = self.tagsdict.keys()
        for i in xrange(self.listWidget.count()):
            tag = self.listWidget.item(i).text()
            if tag in self.availableTags:
                self.availableTags.remove(tag)
        self.lineEdit.completer().model().setStringList(self.availableTags)

    def addTag(self):
        text = self.lineEdit.text()
        if text in self.availableTags:
            self.availableTags.remove(text)
            self.lineEdit.completer().model().setStringList(self.availableTags)
            self.listWidget.addItem(text)
            self.lineEdit.clear()
            self.tagsChanged.emit(self.tags())

    def tags(self):
        tags = [
            self.tagsdict[self.listWidget.item(i).text()]
            for i in xrange(self.listWidget.count())
        ]
        return tags

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Delete:
            self.listWidget.takeItem(self.listWidget.currentRow())
            self.tagsChanged.emit(self.tags())
        else:
            super(TagsWidget, self).keyPressEvent(event)
Пример #7
0
class TagsWidget(QWidget):
    tagsChanged = pyqtSignal(list)

    def __init__(self, parent=None):
        super(TagsWidget, self).__init__(parent)
        self.lineEdit = TagLineEdit(self)
        self.lineEdit.returnPressed.connect(
            lambda: QTimer.singleShot(0, self.addTag))
        self.listWidget = QListWidget(self)
        l = QVBoxLayout(self)
        l.addWidget(self.lineEdit)
        l.addWidget(self.listWidget)

        self.availableTags = []
        self.reload()

    def reload(self):
        tags = Session.query(Tag.name, Tag.id).all()
        self.tagsdict = dict(tags)
        self.availableTags = self.tagsdict.keys()
        for i in xrange(self.listWidget.count()):
            tag = self.listWidget.item(i).text()
            if tag in self.availableTags:
                self.availableTags.remove(tag)
        self.lineEdit.completer().model().setStringList(self.availableTags)

    def addTag(self):
        text = self.lineEdit.text()
        if text in self.availableTags:
            self.availableTags.remove(text)
            self.lineEdit.completer().model().setStringList(self.availableTags)
            self.listWidget.addItem(text)
            self.lineEdit.clear()
            self.tagsChanged.emit(self.tags())

    def tags(self):
        tags = [self.tagsdict[self.listWidget.item(i).text()]
                for i in xrange(self.listWidget.count())]
        return tags

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Delete:
            self.listWidget.takeItem(self.listWidget.currentRow())
            self.tagsChanged.emit(self.tags())
        else:
            super(TagsWidget, self).keyPressEvent(event)
Пример #8
0
class InterfacePage(QWizardPage):

    def __init__(self):
        super(InterfacePage,self).__init__()
        self.completed = False
        self.setTitle('接口设置')
        self.setSubTitle('设置需要实现的接口')
        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(20, 30, 20, 30)

        self.lw_interface = QListWidget()
        rootLayout.addWidget(self.lw_interface)
        self.setLayout(rootLayout)

    def initializePage(self):
        super(InterfacePage, self).initializePage()
        exsits = []
        for key in app.g_configurations.interfaces:
            if app.g_configurations.interfaces[key]:
                exsits.append(key)

        for interface in app.g_configurations.config['interfaces']:
            litem = QListWidgetItem(interface['name'])
            litem.setToolTip(interface['description'])
            litem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            if app.g_configurations.initialized:
                if interface['name'] in exsits:
                    litem.setCheckState(Qt.Checked)
                else:
                    litem.setCheckState(Qt.Unchecked)
            else:
                isdefault = False
                if app.g_configurations.component_type == "window":
                    if interface['default'] & 2:
                        isdefault = True
                else:
                    if interface['default'] & 1:
                        isdefault = True
                if isdefault:
                    litem.setCheckState(Qt.Checked)
                else:
                    litem.setCheckState(Qt.Unchecked)
            self.lw_interface.addItem(litem)

    def validatePage(self):
        interfaces = {}
        for i in range(self.lw_interface.count()):
            litem = self.lw_interface.item(i)
            key = app.QString2str(litem.text())
            if litem.checkState() == 2:
                interfaces[key] = True;
            else:
                interfaces[key] = False;

        app.g_configurations.interfaces = interfaces
        return True
Пример #9
0
class InterfacePage(QWizardPage):
    def __init__(self):
        super(InterfacePage, self).__init__()
        self.completed = False
        self.setTitle('接口设置')
        self.setSubTitle('设置需要实现的接口')
        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(20, 30, 20, 30)

        self.lw_interface = QListWidget()
        rootLayout.addWidget(self.lw_interface)
        self.setLayout(rootLayout)

    def initializePage(self):
        super(InterfacePage, self).initializePage()
        exsits = []
        for key in app.g_configurations.interfaces:
            if app.g_configurations.interfaces[key]:
                exsits.append(key)

        for interface in app.g_configurations.config['interfaces']:
            litem = QListWidgetItem(interface['name'])
            litem.setToolTip(interface['description'])
            litem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            if app.g_configurations.initialized:
                if interface['name'] in exsits:
                    litem.setCheckState(Qt.Checked)
                else:
                    litem.setCheckState(Qt.Unchecked)
            else:
                isdefault = False
                if app.g_configurations.component_type == "window":
                    if interface['default'] & 2:
                        isdefault = True
                else:
                    if interface['default'] & 1:
                        isdefault = True
                if isdefault:
                    litem.setCheckState(Qt.Checked)
                else:
                    litem.setCheckState(Qt.Unchecked)
            self.lw_interface.addItem(litem)

    def validatePage(self):
        interfaces = {}
        for i in range(self.lw_interface.count()):
            litem = self.lw_interface.item(i)
            key = app.QString2str(litem.text())
            if litem.checkState() == 2:
                interfaces[key] = True
            else:
                interfaces[key] = False

        app.g_configurations.interfaces = interfaces
        return True
class TraceWindow(QMainWindow):

    def __init__(self, params_pipe, number_pipe, data_pipe, mads_pipe, peaks_pipe,
                 probe_path=None, screen_resolution=None):

        QMainWindow.__init__(self)

        # Receive parameters.
        params = params_pipe[0].recv()
        self.probe = load_probe(probe_path)
        self._nb_samples = params['nb_samples']
        self._sampling_rate = params['sampling_rate']
        self._display_list = list(range(self.probe.nb_channels))

        self._params = {
            'nb_samples': self._nb_samples,
            'sampling_rate': self._sampling_rate,
            'time': {
                'min': 10.0,  # ms
                'max': 1000.0,  # ms
                'init': 100.0,  # ms
            },
            'voltage': {
                'min': 10.0,  # µV
                'max': 10e+3,  # µV
                'init': 20.0,  # µV
            },
            'mads': {
                'min': 0.0,  # µV
                'max': 100,  # µV
                'init': 3,  # µV
            },
            'channels': self._display_list
        }

        self._canvas = TraceCanvas(probe_path=probe_path, params=self._params)

        central_widget = self._canvas.native

        # Create controls widgets.
        label_time = QLabel()
        label_time.setText(u"time")
        label_time_unit = QLabel()
        label_time_unit.setText(u"ms")

        self._dsp_time = QDoubleSpinBox()
        self._dsp_time.setMinimum(self._params['time']['min'])
        self._dsp_time.setMaximum(self._params['time']['max'])
        self._dsp_time.setValue(self._params['time']['init'])
        self._dsp_time.valueChanged.connect(self._on_time_changed)

        label_display_mads = QLabel()
        label_display_mads.setText(u"Display Mads")
        self._display_mads = QCheckBox()
        self._display_mads.stateChanged.connect(self._on_mads_display)

        label_display_peaks = QLabel()
        label_display_peaks.setText(u"Display Peaks")
        self._display_peaks = QCheckBox()
        self._display_peaks.stateChanged.connect(self._on_peaks_display)

        label_mads = QLabel()
        label_mads.setText(u"Mads")
        label_mads_unit = QLabel()
        label_mads_unit.setText(u"unit")
        self._dsp_mads = QDoubleSpinBox()
        self._dsp_mads.setMinimum(self._params['mads']['min'])
        self._dsp_mads.setMaximum(self._params['mads']['max'])
        self._dsp_mads.setValue(self._params['mads']['init'])
        self._dsp_mads.valueChanged.connect(self._on_mads_changed)

        label_voltage = QLabel()
        label_voltage.setText(u"voltage")
        label_voltage_unit = QLabel()
        label_voltage_unit.setText(u"µV")
        self._dsp_voltage = QDoubleSpinBox()
        self._dsp_voltage.setMinimum(self._params['voltage']['min'])
        self._dsp_voltage.setMaximum(self._params['voltage']['max'])
        self._dsp_voltage.setValue(self._params['voltage']['init'])
        self._dsp_voltage.valueChanged.connect(self._on_voltage_changed)

        # Color spikes
        self._color_spikes = QCheckBox()
        self._color_spikes.setText('See Spikes color')
        self._color_spikes.setCheckState(Qt.Checked)
        self._color_spikes.stateChanged.connect(self.display_spikes_color)



        # self._selection_channels.setGeometry(QtCore.QRect(10, 10, 211, 291))

        spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)

        # Create controls grid.
        grid = QGridLayout()
        # # Add time row.
        grid.addWidget(label_time, 0, 0)
        grid.addWidget(self._dsp_time, 0, 1)
        grid.addWidget(label_time_unit, 0, 2)
        # # Add voltage row.
        grid.addWidget(label_voltage, 1, 0)
        grid.addWidget(self._dsp_voltage, 1, 1)
        grid.addWidget(label_voltage_unit, 1, 2)
        # # Add Mads widgets

        grid.addWidget(label_display_mads, 3, 0)
        grid.addWidget(self._display_mads, 3, 1)

        grid.addWidget(label_mads, 4, 0)
        grid.addWidget(self._dsp_mads, 4, 1)
        grid.addWidget(label_mads_unit, 4, 2)

        grid.addWidget(self._color_spikes, 5, 0)

        # # Add spacer.
        grid.addItem(spacer)

        # # Create info group.
        controls_group = QGroupBox()
        controls_group.setLayout(grid)


        self._selection_channels = QListWidget()
        self._selection_channels.setSelectionMode(
            QAbstractItemView.ExtendedSelection
        )

        for i in range(self.probe.nb_channels):
            item = QListWidgetItem("Channel %i" % i)
            self._selection_channels.addItem(item)
            self._selection_channels.item(i).setSelected(True)

        def add_channel():
            items = self._selection_channels.selectedItems()
            self._display_list = []
            for i in range(len(items)):
                self._display_list.append(i)
            self._on_channels_changed()

        # self._selection_channels.itemClicked.connect(add_channel)

        nb_channel = self.probe.nb_channels
        self._selection_channels.itemSelectionChanged.connect(lambda: self.selected_channels(nb_channel))

        # Create info grid.
        channels_grid = QGridLayout()
        # # Add Channel selection
        # grid.addWidget(label_selection, 3, 0)
        channels_grid.addWidget(self._selection_channels, 0, 1)

        # # Add spacer.
        channels_grid.addItem(spacer)

        # Create controls group.
        channels_group = QGroupBox()
        channels_group.setLayout(channels_grid)

        # # Create controls dock.
        channels_dock = QDockWidget()
        channels_dock.setWidget(channels_group)
        channels_dock.setWindowTitle("Channels selection")

        # # Create controls dock.
        control_dock = QDockWidget()
        control_dock.setWidget(controls_group)
        control_dock.setWindowTitle("Controls")

        # Create info widgets.
        label_time = QLabel()
        label_time.setText(u"time")
        self._label_time_value = QLineEdit()
        self._label_time_value.setText(u"0")
        self._label_time_value.setReadOnly(True)
        self._label_time_value.setAlignment(Qt.AlignRight)
        label_time_unit = QLabel()
        label_time_unit.setText(u"s")
        info_buffer_label = QLabel()
        info_buffer_label.setText(u"buffer")
        self._info_buffer_value_label = QLineEdit()
        self._info_buffer_value_label.setText(u"0")
        self._info_buffer_value_label.setReadOnly(True)
        self._info_buffer_value_label.setAlignment(Qt.AlignRight)
        info_buffer_unit_label = QLabel()
        info_buffer_unit_label.setText(u"")
        info_probe_label = QLabel()
        info_probe_label.setText(u"probe")
        info_probe_value_label = QLineEdit()
        info_probe_value_label.setText(u"{}".format(probe_path))
        info_probe_value_label.setReadOnly(True)
        # TODO place the following info in another grid?
        info_probe_unit_label = QLabel()
        info_probe_unit_label.setText(u"")

        info_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)

        # Create info grid.
        info_grid = QGridLayout()
        # # Time row.
        info_grid.addWidget(label_time, 0, 0)
        info_grid.addWidget(self._label_time_value, 0, 1)
        info_grid.addWidget(label_time_unit, 0, 2)
        # # Buffer row.
        info_grid.addWidget(info_buffer_label, 1, 0)
        info_grid.addWidget(self._info_buffer_value_label, 1, 1)
        info_grid.addWidget(info_buffer_unit_label, 1, 2)
        # # Probe row.
        info_grid.addWidget(info_probe_label, 2, 0)
        info_grid.addWidget(info_probe_value_label, 2, 1)
        info_grid.addWidget(info_probe_unit_label, 2, 2)
        # # Spacer.
        info_grid.addItem(info_spacer)

        # Create info group.
        info_group = QGroupBox()
        info_group.setLayout(info_grid)

        # Create info dock.
        info_dock = QDockWidget()
        info_dock.setWidget(info_group)
        info_dock.setWindowTitle("Info")

        # Create thread.
        thread = Thread(number_pipe, data_pipe, mads_pipe, peaks_pipe)
        thread.number_signal.connect(self._number_callback)
        thread.reception_signal.connect(self._reception_callback)
        thread.start()

        # Add dockable windows.
        self.addDockWidget(Qt.LeftDockWidgetArea, control_dock)
        self.addDockWidget(Qt.LeftDockWidgetArea, info_dock)
        self.addDockWidget(Qt.LeftDockWidgetArea, channels_dock)
        # Set central widget.
        self.setCentralWidget(central_widget)
        # Set window size.
        if screen_resolution is not None:
            screen_width = screen_resolution.width()
            screen_height = screen_resolution.height()
            self.resize(screen_width, screen_height)
        # Set window title.
        self.setWindowTitle("SpyKING Circus ORT - Read 'n' Qt display")

        print(" ")  # TODO remove?

    def _number_callback(self, number):

        text = u"{}".format(number)
        self._info_buffer_value_label.setText(text)

        text = u"{:8.3f}".format(float(number) * float(self._nb_samples) / self._sampling_rate)
        self._label_time_value.setText(text)

        return

    def _reception_callback(self, data, mads, peaks):

        self._canvas.on_reception(data, mads, peaks)

        return

    def _on_time_changed(self):

        time = self._dsp_time.value()
        self._canvas.set_time(time)

        return

    def _on_voltage_changed(self):

        voltage = self._dsp_voltage.value()
        self._canvas.set_voltage(voltage)

        return

    def _on_mads_changed(self):

        mads = self._dsp_mads.value()
        self._canvas.set_mads(mads)

        return

    def _on_mads_display(self):

        value = self._display_mads.isChecked()
        self._canvas.show_mads(value)

        return

    def _on_peaks_display(self):

        value = self._display_peaks.isChecked()
        self._canvas.show_peaks(value)

        return

    def _on_channels_changed(self):
        self._canvas.set_channels(self._display_list)

        return

    def display_spikes_color(self, s):
        self._canvas.color_spikes(s)

    def selected_channels(self, max_channel):
        # print(self._selection_channels.selectedItems())
        list_channel = []
        for i in range(max_channel):
            if self._selection_channels.item(i).isSelected():
                list_channel.append(i)
        self._canvas.selected_channels(list_channel)
        return
Пример #11
0
class NotebookSettingsDialog(QDialog):
    """GUI for adjusting notebook settings"""
    def __init__(self, parent=None):
        super(NotebookSettingsDialog, self).__init__(parent)
        #widgets for tab 1
        self.mdExts = QListWidget()
        self.mjEdit = QLineEdit()
        self.moveUp = QPushButton('<<')
        self.moveDown = QPushButton('>>')
        self.configureExtension = QPushButton('Edit Settings for this extension')
        self.tmpdict = deepcopy(self.parent().settings.extcfg)
        
        #widgets for tab 2
        self.fExtEdit = QLineEdit()
        self.attImgEdit = QLineEdit()
        self.attDocEdit = QLineEdit()
        # mandatory button box
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        
        #tab panels
        tabs = QTabWidget()
        markupTab = QWidget()
        fileExtsTab = QWidget()
        tabs.addTab(markupTab, "Markdown")
        tabs.addTab(fileExtsTab, "File extensions")
        
        #initialization functions
        self.initExtList()
        self.mdExts.setDragDropMode(QAbstractItemView.InternalMove)
        self.mjEdit.setText(self.parent().settings.mathjax)
        self.attImgEdit.setText(', '.join(self.parent().settings.attachmentImage))
        self.attDocEdit.setText(', '.join(self.parent().settings.attachmentDocument))
        self.fExtEdit.setText(self.parent().settings.fileExt)
        
        #set up tab 1
        layout=QGridLayout(markupTab)
        layout.addWidget(QLabel("Markdown extensions"),0,0,1,4)
        layout.addWidget(self.mdExts,1,0,1,4)
        layout.addWidget(self.moveUp,2,0,1,1)
        layout.addWidget(self.moveDown,2,1,1,1)
        layout.addWidget(self.configureExtension,2,2,1,2)
        layout.addWidget(QLabel("MathJax Location"),3,0,1,1)
        layout.addWidget(self.mjEdit,3,1,1,3)
        
        #set up tab 2
        layout=QGridLayout(fileExtsTab)
        layout.addWidget(QLabel("Note file extension"),0,0,1,1)
        layout.addWidget(QLabel("Image file extension"),1,0,1,1)
        layout.addWidget(QLabel("Document file extension"),2,0,1,1)
        layout.addWidget(self.fExtEdit,0,1,1,1)
        layout.addWidget(self.attImgEdit,1,1,1,1)
        layout.addWidget(self.attDocEdit,2,1,1,1)
        
        #put it together
        vlayout = QVBoxLayout(self)
        vlayout.addWidget(tabs)
        vlayout.addWidget(self.buttonBox)

        #setup signal handlers
        self.moveUp.clicked.connect(self.moveItemUp)
        self.configureExtension.clicked.connect(self.configExt)
        self.moveDown.clicked.connect(self.moveItemDown)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def configExt(self, checked=False, ext=None):
        if ext is None:
            ext = self.mdExts.currentItem().text()
        cfg = self.tmpdict.get(ext,[])
        dialog = NotebookExtSettingsDialog(cfg_list=cfg)
        done = dialog.exec()
        if done:
            self.tmpdict[ext] = dialog.configToList()

    def initExtList(self):
        extset=set(self.parent().settings.extensions)
        #for easier performance in checking
        for ext in self.parent().settings.extensions:
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Checked)

        for ext in self.parent().settings.faulty_exts:
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setBackground(QBrush(QColor('red')))
            item.setForeground(QBrush(QColor('black')))
            item.setCheckState(Qt.Checked)

        for ext in allMDExtensions():
            if ext in extset: continue
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            #self.mdExts.addItem(item)

    def moveItemUp(self):
        item = self.mdExts.currentItem()
        row = self.mdExts.currentRow()
        if row != 0:
            # self.mdExts.removeItemWidget(item)
            self.mdExts.takeItem(row)
            self.mdExts.insertItem(row-1, item)
            self.mdExts.setCurrentRow(row-1)

    def moveItemDown(self):
        item = self.mdExts.currentItem()
        row = self.mdExts.currentRow()
        count = self.mdExts.count()
        if row != count-1:
            self.mdExts.takeItem(row)
            self.mdExts.insertItem(row+1, item)
            self.mdExts.setCurrentRow(row+1)


    def accept(self):
        #write to settings first
        msettings = self.parent().settings
        nbsettings = msettings.qsettings
        
        nbsettings.setValue('mathJax', self.mjEdit.text())
        extlist = []
        for i in range(self.mdExts.count()):
            item = self.mdExts.item(i)
            if item.checkState() == Qt.Checked:
                extlist.append(item.text())
        writeListToSettings(nbsettings, 'extensions', extlist)
        writeListToSettings(nbsettings, 'attachmentImage', self.attImgEdit.text().split(", "))
        writeListToSettings(nbsettings, 'attachmentDocument', self.attDocEdit.text().split(", "))
        writeDictToSettings(nbsettings, 'extensionsConfig', self.tmpdict)
        
        #then to memory
        msettings.extensions = extlist
        msettings.mathjax = self.mjEdit.text()
        msettings.attachmentDocument = readListFromSettings(nbsettings, 'attachmentDocument')
        msettings.attachmentImage = readListFromSettings(nbsettings, 'attachmentImage')
        msettings.extcfg.update(self.tmpdict)
        msettings.md = markdown.Markdown(msettings.extensions, extension_configs=msettings.extcfg)
        
        #then make mikidown use these settings NOW
        curitem=self.parent().notesTree.currentItem()
        self.parent().currentItemChangedWrapper(curitem, curitem)
        QDialog.accept(self)
Пример #12
0
class StringListDlg(QDialog):

    acceptedList = Signal(QStringList)

    def __init__(self, name, stringlist=None, parent=None):
        super(StringListDlg, self).__init__(parent)
        self.name = name
        self.create_widgets(stringlist)
        self.layout_widgets()
        self.setWindowTitle("Edit {0} List".format(self.name))

    def create_widgets(self, stringlist):
        self.listWidget = QListWidget()
        if stringlist is not None:
            self.listWidget.addItems(stringlist)
            self.listWidget.setCurrentRow(0)

    def layout_widgets(self):
        buttonLayout = QVBoxLayout()
        for text, slot in (("&Add...", self.add), ("&Edit...", self.edit),
                           ("&Remove...", self.remove), ("&Up", self.up),
                           ("&Down", self.down), ("&Sort",
                                                  self.listWidget.sortItems),
                           ("Close", self.accept)):
            button = QPushButton(text)
            if not MAC:
                button.setFocusPolicy(Qt.NoFocus)
            if text == "Close":
                buttonLayout.addStretch()
            buttonLayout.addWidget(button)
            button.clicked.connect(slot)
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(buttonLayout)
        self.setLayout(layout)

    def add(self):
        row = self.listWidget.currentRow()
        title = "Add {0}".format(self.name)
        string, ok = QInputDialog.getText(self, title, title)
        if ok and not string.isEmpty():
            self.listWidget.insertItem(row, string)

    def edit(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is not None:
            title = "Edit {0}".format(self.name)
            string, ok = QInputDialog.getText(self, title, title,
                                              QLineEdit.Normal, item.text())
            if ok and not string.isEmpty():
                item.setText(string)

    def remove(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is None:
            return
        reply = QMessageBox.question(
            self, "Remove {0}".format(self.name),
            "Remove {0} `{1}'?".format(self.name, unicode(item.text())),
            QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            item = self.listWidget.takeItem(row)
            del item

    def up(self):
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row - 1, item)
            self.listWidget.setCurrentItem(item)

    def down(self):
        row = self.listWidget.currentRow()
        if row < self.listWidget.count() - 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row + 1, item)
            self.listWidget.setCurrentItem(item)

    def reject(self):
        self.accept()

    def accept(self):
        self.stringlist = QStringList()
        for row in range(self.listWidget.count()):
            self.stringlist.append(self.listWidget.item(row).text())
        self.acceptedList.emit(self.stringlist)
        QDialog.accept(self)
Пример #13
0
class Dialogo(QDialog):

    def __init__(self, archivos, principal):
        super(Dialogo, self).__init__(principal)
        self.setWindowTitle(self.tr("Archivos sin guardar!"))
        self.principal = principal
        self.evento_ignorado = False

        vLayout = QVBoxLayout(self)
        label = QLabel(self.tr("Algunos archivos no se han guardado, "
                       "selecciona los que \ndeseas guardar:"))
        vLayout.addWidget(label)
        hLayout = QHBoxLayout()

        self.lista = QListWidget()
        [self.lista.addItem(item) for item in archivos]
        self.lista.setSelectionMode(QAbstractItemView.ExtendedSelection)
        hLayout.addWidget(self.lista)

        layoutBotones = QVBoxLayout()
        botonTodo = QPushButton(self.tr("Todo"))
        botonNinguno = QPushButton(self.tr("Ninguno"))
        botonGuardar = QPushButton(self.tr("Guardar"))
        botonCancelar = QPushButton(self.tr("Cancelar"))
        botonNoGuardar = QPushButton(self.tr("No guardar"))
        layoutBotones.addWidget(botonTodo)
        layoutBotones.addWidget(botonNinguno)
        layoutBotones.addWidget(botonGuardar)
        layoutBotones.addWidget(botonNoGuardar)
        layoutBotones.addWidget(botonCancelar)

        hLayout.addLayout(layoutBotones)
        vLayout.addLayout(hLayout)

        self.tecla_escape = QShortcut(QKeySequence(Qt.Key_Escape), self)

        self.connect(self.tecla_escape, SIGNAL("activated()"), self.ignorar)
        self.connect(botonTodo, SIGNAL("clicked()"), self.seleccionar_todo)
        self.connect(botonNinguno, SIGNAL("clicked()"), self.deseleccionar)
        self.connect(botonGuardar, SIGNAL("clicked()"), self.guardar)
        self.connect(botonNoGuardar, SIGNAL("clicked()"), self.close)
        self.connect(botonCancelar, SIGNAL("clicked()"), self.ignorar)

    def ignorar(self):
        self.evento_ignorado = True
        self.hide()

    def ignorado(self):
        return self.evento_ignorado

    def seleccionar_todo(self):
        for item in range(self.lista.count()):
            self.lista.item(item).setSelected(True)

    def deseleccionar(self):
        for item in range(self.lista.count()):
            self.lista.item(item).setSelected(False)

    def guardar(self):
        archivos_seleccionados = self.lista.selectedItems()
        for archivo in archivos_seleccionados:
            nombre = archivo.text()
            self.principal.guardar_seleccionado(nombre)
        self.close()
Пример #14
0
class GroupsModify(QDialog):
    """
    +--------------------------+
    |     Groups : Modify      |
    +--------------------------+
    |                          |
    |  Name        xxx Default |
    |  Coords      xxx Default |
    |  Elements    xxx Default |
    |  Color       xxx Default |
    |  Add         xxx Add     |
    |  Remove      xxx Remove  |
    |                          |
    |      Set  OK Cancel      |
    +--------------------------+
    """
    def __init__(self, data, win_parent=None, group_active='main'):
        self.win_parent = win_parent
        QDialog.__init__(self, win_parent)

        self.win_parent = win_parent
        self.out_data = data

        #print(data)
        self.keys = [group.name for key, group in sorted(iteritems(data))]
        self.active_key = self.keys.index(group_active)

        group_obj = data[self.active_key]
        name = group_obj.name

        self.imain = 0
        self.nrows = len(self.keys)

        self._default_name = group_obj.name
        self._default_elements = group_obj.element_str
        self.elements_pound = group_obj.elements_pound

        self.table = QListWidget(parent=None)
        self.table.clear()
        self.table.addItems(self.keys)

        # table
        self.setWindowTitle('Groups: Modify')
        self.create_widgets()
        self.create_layout()
        self.set_connections()

        self.on_set_as_main()
        #self.show()

    def create_widgets(self):
        # Name
        self.name = QLabel("Name:")
        self.name_set = QPushButton("Set")
        self.name_edit = QLineEdit(str(self._default_name).strip())
        self.name_button = QPushButton("Default")

        # elements
        self.elements = QLabel("Element IDs:")
        self.elements_edit = QLineEdit(str(self._default_elements).strip())
        self.elements_button = QPushButton("Default")

        # add
        self.add = QLabel("Add:")
        self.add_edit = QLineEdit(str(''))
        self.add_button = QPushButton("Add")

        # remove
        self.remove = QLabel("Remove:")
        self.remove_edit = QLineEdit(str(''))
        self.remove_button = QPushButton("Remove")

        # applies a unique implicitly
        self.eids = parse_patran_syntax(str(self._default_elements), pound=self.elements_pound)

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

        self.set_as_main_button = QPushButton("Set As Main")
        self.create_group_button = QPushButton('Create New Group')
        self.delete_group_button = QPushButton('Delete Group')

        self.name.setEnabled(False)
        self.name_set.setEnabled(False)
        self.name_edit.setEnabled(False)
        self.name_button.setEnabled(False)
        self.elements.setEnabled(False)
        self.elements_button.setEnabled(False)
        self.elements_edit.setEnabled(False)
        self.add.setEnabled(False)
        self.add_button.setEnabled(False)
        self.add_edit.setEnabled(False)
        self.remove.setEnabled(False)
        self.remove_button.setEnabled(False)
        self.remove_edit.setEnabled(False)
        self.delete_group_button.setEnabled(False)
        #self.apply_button.setEnabled(False)
        #self.ok_button.setEnabled(False)


    def create_layout(self):
        grid = QGridLayout()
        grid.addWidget(self.name, 0, 0)
        grid.addWidget(self.name_edit, 0, 1)
        grid.addWidget(self.name_set, 0, 2)
        grid.addWidget(self.name_button, 0, 3)

        grid.addWidget(self.elements, 2, 0)
        grid.addWidget(self.elements_edit, 2, 1)
        grid.addWidget(self.elements_button, 2, 2)

        grid.addWidget(self.add, 4, 0)
        grid.addWidget(self.add_edit, 4, 1)
        grid.addWidget(self.add_button, 4, 2)

        grid.addWidget(self.remove, 5, 0)
        grid.addWidget(self.remove_edit, 5, 1)
        grid.addWidget(self.remove_button, 5, 2)


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


        main_create_delete = QHBoxLayout()
        main_create_delete.addWidget(self.set_as_main_button)
        main_create_delete.addWidget(self.create_group_button)
        main_create_delete.addWidget(self.delete_group_button)

        vbox = QVBoxLayout()
        vbox.addWidget(self.table)
        vbox.addLayout(grid)
        vbox.addLayout(main_create_delete)
        vbox.addStretch()
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)

    def on_set_name(self):
        name = str(self.name_edit.text()).strip()
        if name not in self.keys:
            self.name_edit.setStyleSheet("QLineEdit{background: white;}")
            group = self.out_data[self.active_key]
            group.name = name
            self.keys[self.active_key] = name
            self.recreate_table()
        elif name != self.keys[self.active_key]:
            self.name_edit.setStyleSheet("QLineEdit{background: red;}")
        elif name == self.keys[self.active_key]:
            self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    def set_connections(self):
        if qt_version == 4:
            self.connect(self.name_set, QtCore.SIGNAL('clicked()'), self.on_set_name)
            self.connect(self.name_button, QtCore.SIGNAL('clicked()'), self.on_default_name)
            self.connect(self.elements_button, QtCore.SIGNAL('clicked()'), self.on_default_elements)

            self.connect(self.add_button, QtCore.SIGNAL('clicked()'), self.on_add)
            self.connect(self.remove_button, QtCore.SIGNAL('clicked()'), self.on_remove)
            self.connect(self.table, QtCore.SIGNAL('itemClicked(QListWidgetItem *)'), self.on_update_active_key)

            #self.connect(self.apply_button, QtCore.SIGNAL('clicked()'), self.on_apply)
            self.connect(self.ok_button, QtCore.SIGNAL('clicked()'), self.on_ok)
            #self.connect(self.cancel_button, QtCore.SIGNAL('clicked()'), self.on_cancel)

            self.connect(self.set_as_main_button, QtCore.SIGNAL('clicked()'), self.on_set_as_main)
            self.connect(self.create_group_button, QtCore.SIGNAL('clicked()'), self.on_create_group)
            self.connect(self.delete_group_button, QtCore.SIGNAL('clicked()'), self.on_delete_group)
        else:
            self.name_set.clicked.connect(self.on_set_name)
            self.name_button.clicked.connect(self.on_default_name)
            self.elements_button.clicked.connect(self.on_default_elements)

            self.add_button.clicked.connect(self.on_add)
            self.remove_button.clicked.connect(self.on_remove)
            self.table.itemClicked.connect(self.on_update_active_key)
            self.ok_button.clicked.connect(self.on_ok)

            self.set_as_main_button.clicked.connect(self.on_set_as_main)
            self.create_group_button.clicked.connect(self.on_create_group)
            self.delete_group_button.clicked.connect(self.on_delete_group)

    def on_create_group(self):
        irow = self.nrows
        new_key = 'Group %s' % irow
        while new_key in self.keys:
            irow += 1
            new_key = 'Group %s' % irow
        irow = self.nrows

        self.keys.append(new_key)
        group = Group(
            new_key,
            element_str='',
            elements_pound=self.elements_pound,
            editable=True)
        self.out_data[irow] = group

        self.table.reset()
        self.table.addItems(self.keys)
        self.nrows += 1

        #----------------------------------
        # update internal parameters
        #self.out_data = items
        if self.imain > self.active_key:
            self.imain += 1

        #make the new group the default
        self.active_key = self.nrows - 1

        self.keys = [group.name for key, group in sorted(iteritems(self.out_data))]
        self.recreate_table()

    def recreate_table(self):
        # update gui
        self.table.clear()
        self.table.addItems(self.keys)
        item = self.table.item(self.imain)

        bold = QtGui.QFont()
        bold.setBold(True)
        bold.setItalic(True)
        item.setFont(bold)
        self.table.update()

        # update key
        name = self.keys[self.active_key]
        self._update_active_key_by_name(name)

    def on_delete_group(self):
        if self.active_key == 0:
            return

        #self.deleted_groups.add(self.imain)
        items = {}
        j = 0
        for i, key in sorted(iteritems(self.out_data)):
            if i != self.active_key:
                items[j] = key
                j += 1

        # update internal parameters
        self.out_data = items
        if self.imain >= self.active_key:
            self.imain = max(0, self.imain - 1)
        self.active_key = max(0, self.active_key - 1)
        self.nrows -= 1
        self.keys = [group.name for key, group in sorted(iteritems(items))]

        self.recreate_table()

        # update key
        name = self.keys[self.active_key]
        self._update_active_key_by_name(name)

    def on_set_as_main(self):
        bold = QtGui.QFont()
        bold.setBold(True)
        bold.setItalic(True)

        normal = QtGui.QFont()
        normal.setBold(False)
        normal.setItalic(False)

        obj = self.table.item(self.imain)
        obj.setFont(normal)

        self.imain = self.active_key
        obj = self.table.item(self.imain)
        obj.setFont(bold)
        group = self.out_data[self.imain]
        self._default_elements = group.element_str
        self._default_name = group.name
        if self.win_parent is not None:
            # we're not testing the menu
            self.win_parent.post_group(group)

    def closeEvent(self, event):
        event.accept()

    def on_add(self):
        eids, is_valid = self.check_patran_syntax(self.add_edit, pound=self.elements_pound)
        #adict, is_valid = self.check_patran_syntax_dict(self.add_edit)
        if not is_valid:
            #self.add_edit.setStyleSheet("QLineEdit{background: red;}")
            return

        self.eids = unique(hstack([self.eids, eids]))
        #self.eids = _add(adict, ['e', 'elem', 'element'], self.eids)
        #self.cids = _add(adict, ['c', 'cid', 'coord'], self.cids)
        self._apply_cids_eids()

        self.add_edit.clear()
        self.add_edit.setStyleSheet("QLineEdit{background: white;}")

    def _apply_cids_eids(self):
        #ctext = _get_collapsed_text(self.cids)
        etext = _get_collapsed_text(self.eids)

        #self.coords_edit.setText(str(ctext.lstrip()))
        self.elements_edit.setText(str(etext.lstrip()))
        self.out_data[self.active_key].element_ids = self.eids

    def on_remove(self):
        eids, is_valid = self.check_patran_syntax(self.remove_edit)
        #adict, is_valid = self.check_patran_syntax_dict(self.remove_edit)
        if not is_valid:
            #self.remove_edit.setStyleSheet("QLineEdit{background: red;}")
            return

        #self.eids = _remove(adict, ['e', 'elem', 'element'], self.eids)
        #self.cids = _remove(adict, ['c', 'cid', 'coord'], self.cids)
        self.eids = setdiff1d(self.eids, eids)
        self._apply_cids_eids()

        self.remove_edit.clear()
        self.remove_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_name(self):
        name = str(self._default_name)
        self.name_edit.setText(name)
        self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_elements(self):
        element_str = str(self._default_elements)
        self.elements_edit.setText(element_str)
        self.elements_edit.setStyleSheet("QLineEdit{background: white;}")
        group = self.out_data[self.active_key]
        group.element_str = element_str

    def check_patran_syntax(self, cell, pound=None):
        text = str(cell.text())
        try:
            values = parse_patran_syntax(text, pound=pound)
            cell.setStyleSheet("QLineEdit{background: white;}")
            return values, True
        except ValueError as e:
            cell.setStyleSheet("QLineEdit{background: red;}")
            cell.setToolTip(str(e))
            return None, False

    def check_patran_syntax_dict(self, cell, pound=None):
        text = str(cell.text())
        try:
            value = parse_patran_syntax_dict(text)
            cell.setStyleSheet("QLineEdit{background: white;}")
            cell.setToolTip('')
            return value, True
        except (ValueError, SyntaxError, KeyError) as e:
            cell.setStyleSheet("QLineEdit{background: red;}")
            cell.setToolTip(str(e))
            return None, False

    def check_float(self, cell):
        text = cell.text()
        try:
            value = float(text)
            cell.setStyleSheet("QLineEdit{background: white;}")
            cell.setToolTip('')
            return value, True
        except ValueError:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

    def check_name(self, cell):
        text = str(cell.text()).strip()
        if len(text):
            cell.setStyleSheet("QLineEdit{background: white;}")
            return text, True
        else:
            cell.setStyleSheet("QLineEdit{background: red;}")
            return None, False

        if self._default_name != text:
            if self._default_name in self.out_data:
                cell.setStyleSheet("QLineEdit{background: white;}")
                return text, True
            else:
                cell.setStyleSheet("QLineEdit{background: red;}")
                return None, False

    def check_format(self, cell):
        text = str(cell.text())

        is_valid = True
        if len(text) < 2:
            is_valid = False
        elif 's' in text.lower():
            is_valid = False
        elif '%' not in text[0]:
            is_valid = False
        elif text[-1].lower() not in ['g', 'f', 'i', 'e']:
            is_valid = False

        try:
            text % 1
            text % .2
            text % 1e3
            text % -5.
            text % -5
        except ValueError:
            is_valid = False

        try:
            text % 's'
            is_valid = False
        except TypeError:
            pass

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

    def on_validate(self):
        name, flag0 = self.check_name(self.name_edit)
        elements, flag1 = self.check_patran_syntax(self.elements_edit,
                                                         pound=self.elements_pound)
        #coords_value, flag2 = self.check_patran_syntax(self.coords_edit,
        #pound=self.coords_pound)

        if flag0 and flag1:
            self._default_name = name
            self._default_elements = self.eids
            self.out_data['clicked_ok'] = True
            return True
        return False

    def on_apply(self, force=False):
        passed = self.on_validate()
        if passed or force:
            self.win_parent.on_modify_group(self.out_data)

    def on_ok(self):
        passed = self.on_validate()
        if passed:
            self.out_data['close'] = True
            self.out_data['clicked_ok'] = True
            self.out_data['clicked_cancel'] = False
            self.close()
            #self.destroy()

    def on_cancel(self):
        self.out_data['close'] = True
        self.out_data['clicked_cancel'] = True
        self.close()

    def keyPressEvent(self, event):
        if event.key() == QtCore.Qt.Key_Escape:
            self.on_cancel()

    def on_update_active_key(self, index):
        self.update_active_key(index)
        #str(index.text())

    def update_active_key(self, index):
        #old_obj = self.out_data[self.imain]
        name = str(index.text())
        self._update_active_key_by_name(name)

    def _update_active_key_by_name(self, name):
        if name in self.keys:
            self.active_key = self.keys.index(name)
        else:
            # we (hopefully) just removed a row
            #self.active_key = self.keys[self.active_key]
            pass

        self.name_edit.setText(name)
        obj = self.out_data[self.active_key]

        self.eids = parse_patran_syntax(obj.element_str, pound=obj.elements_pound)
        self._default_elements = obj.element_str
        self._default_name = name
        self._apply_cids_eids()

        self.set_as_main_button.setEnabled(True)
        if name in ['main', 'anti-main']:
            self.name.setEnabled(False)
            self.name_set.setEnabled(False)
            self.name_edit.setEnabled(False)
            self.name_button.setEnabled(False)
            self.elements.setEnabled(False)
            self.elements_button.setEnabled(False)
            self.elements_edit.setEnabled(False)
            self.add.setEnabled(False)
            self.add_button.setEnabled(False)
            self.add_edit.setEnabled(False)
            self.remove.setEnabled(False)
            self.remove_button.setEnabled(False)
            self.remove_edit.setEnabled(False)
            self.delete_group_button.setEnabled(False)
            if name == 'anti-main':
                self.set_as_main_button.setEnabled(False)
            #self.apply_button.setEnabled(False)
            #self.ok_button.setEnabled(False)
        else:
            self.name.setEnabled(True)
            self.name_set.setEnabled(True)
            self.name_edit.setEnabled(True)
            self.name_button.setEnabled(True)
            self.elements.setEnabled(True)
            self.elements_button.setEnabled(True)

            self.add.setEnabled(True)
            self.add_button.setEnabled(True)
            self.add_edit.setEnabled(True)
            self.remove.setEnabled(True)
            self.remove_button.setEnabled(True)
            self.remove_edit.setEnabled(True)
            self.delete_group_button.setEnabled(True)
Пример #15
0
class Img2GifWidget(QDialog):
    AppName = u"GIF生成工具"
    
    def __init__(self, parent=None):
        super(Img2GifWidget, self).__init__(parent)
        self.setWindowTitle(Img2GifWidget.AppName)

        self.listWidget = QListWidget()
        self.listWidget.setMinimumSize(400, 300)
        self.btnAdd = QPushButton("&Add")
        self.btnUp = QPushButton("&Up")
        self.btnDown = QPushButton("&Down")
        self.btnDel = QPushButton("&Delete")
        self.btnClear = QPushButton("&Clear")
        topLeftLay = QVBoxLayout()
        topLeftLay.addWidget(self.btnAdd)
        topLeftLay.addWidget(self.btnUp)
        topLeftLay.addWidget(self.btnDown)
        topLeftLay.addWidget(self.btnDel)
        topLeftLay.addWidget(self.btnClear)
        topLeftLay.addStretch()
        topLay = QHBoxLayout()
        topLay.addWidget(self.listWidget)
        topLay.addLayout(topLeftLay)
        
        label = QLabel(u"Gif文件路径:")
        self.txtGifPath = QLineEdit()
        self.btnBrowser = QPushButton('...')
        midLay = QHBoxLayout()
        midLay.addWidget(label)
        midLay.addWidget(self.txtGifPath)
        midLay.addWidget(self.btnBrowser)

        timeLabel = QLabel(u"时间间隔:")
        self.spbTime = QDoubleSpinBox()
        self.spbTime.setRange(0.001, 10)
        self.spbTime.setSingleStep(0.001)
        self.spbTime.setValue(1)
        self.spbTime.setSuffix('s')
        loopLabel = QLabel(u"循环:")
        self.spbLoop = QDoubleSpinBox()
        self.spbLoop = QSpinBox()
        self.spbLoop.setRange(0, 1000)
        self.spbLoop.setSingleStep(1)
        self.spbLoop.setValue(0)
        self.spbLoop.setToolTip(u"0次循环表示永久循环")
        self.spbLoop.setSuffix(u"次")
        self.btnBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        bottomLay = QHBoxLayout()
        bottomLay.addWidget(timeLabel)
        bottomLay.addWidget(self.spbTime)
        bottomLay.addWidget(loopLabel)
        bottomLay.addWidget(self.spbLoop)
        bottomLay.addStretch()
        bottomLay.addWidget(self.btnBox)
        
        mainLay = QVBoxLayout()
        mainLay.addLayout(topLay)
        mainLay.addLayout(midLay)
        mainLay.addLayout(bottomLay)
        self.setLayout(mainLay)

        self.btnAdd.clicked.connect(self.itemAdd)
        self.btnUp.clicked.connect(self.itemUp)
        self.btnDown.clicked.connect(self.itemDown)
        self.btnDel.clicked.connect(self.itemDel)
        self.btnClear.clicked.connect(self.listWidget.clear)
        self.btnBrowser.clicked.connect(self.setGifPath)
        self.btnBox.rejected.connect(self.close)
        self.btnBox.accepted.connect(self.makeGif)

        self.txtGifPath.returnPressed.connect(self.updateGifPath)

    def itemAdd(self):
        fileNames = QFileDialog.getOpenFileNames(None, u"{0} -- {1}".format(qApp.applicationName(), Img2GifWidget.AppName),
                                                 '.', u'所有文件(*.*);;BMP文件(*.bmp);;PNG文件(*.png);;JPG文件(*.jpg *.jpeg)')
        for fn in fileNames:
            f = QFileInfo(fn)
            if unicode(f.suffix().toLower()) in ['jpg', 'png', 'bmp', 'jpeg']:
                self.listWidget.addItem(fn)

    def itemUp(self):
        row = self.listWidget.currentRow()
        if row <= 0:
            return
        item = self.listWidget.currentItem()
        self.listWidget.takeItem(row)
        self.listWidget.insertItem(row - 1, item)
        self.listWidget.setCurrentRow(row - 1)

    def itemDown(self):
        rows = self.listWidget.count()
        row = self.listWidget.currentRow()
        if (row < 0) or (row == rows - 1):
            return
        item = self.listWidget.currentItem()
        self.listWidget.takeItem(row)
        self.listWidget.insertItem(row + 1, item)
        self.listWidget.setCurrentRow(row + 1)

    def itemDel(self):
        row = self.listWidget.currentRow()
        if row >= 0:
            self.listWidget.takeItem(row)

    def setGifPath(self):
        filename = QFileDialog.getSaveFileName(self, u"{0} -- {1}".format(qApp.applicationName(), Img2GifWidget.AppName),
                                               ".", "Gif(*.gif)")
        self.txtGifPath.setText(filename)

    def updateGifPath(self):
        fileName = self.txtGifPath.text()
        f = QFileInfo(fileName)
        if f.dir().exists and not f.baseName().isEmpty() and not f.suffix().isEmpty():
            self.txtGifPath.setText(fileName)
            return True
        else:
            QMessageBox.warning(self, u"{0} -- warning".format(Img2GifWidget.AppName),
                                u"要生成的GIF存储路径{0}不是有效的GIF文件".format(unicode(fileName)))
            return False

    def makeGif(self):

        imgs = [unicode(self.listWidget.item(i).text()) for i in range(self.listWidget.count())]
        if len(imgs) <= 1:
            QMessageBox.warning(self, u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName),
                                u"GIF动画文件必须要给定大于一张图片。")
            return
        if not self.updateGifPath():
            return
        durations = self.spbTime.value()
        loops = self.spbLoop.value()
        ok, msg = img2gif.images2gif(imgs, self.txtGifPath.text(), durations=durations, loops=loops)
        if ok:
            QMessageBox.about(self, u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName),
                              u"Succeed!\n{0}".format(msg))
            qApp.processEvents()
        else:
            QMessageBox.about(u"{0} - {1}".format(qApp.applicationName(), Img2GifWidget.AppName),
                              u"sorry! Failed to generate the {0}".format(unicode(self.txtGifPath)))
Пример #16
0
class GitStatus(QDialog):
    def __init__(self, plugin, git, path):
        QDialog.__init__(self)
        self.git = git
        self.plugin = plugin
        self.setWindowTitle('Git status')

        layout = QGridLayout(self)

        branches = self.git.branch(unicode(path))

        self.s_branches = QListWidget()

        if len(branches) > 0:
            self.s_branches.addItems(branches[1:])
            self.actual_branch = QLabel("<h2>{0}</h2>".format(branches[0]))
        else:
            self.actual_branch = QLabel()

        branch = QLabel("<h2>Branches</h2>")
        change_branch = QPushButton("Change to")
        merge_branches = QPushButton("Merge branch")

        H = QHBoxLayout()
        delete_branch = QPushButton("Delete branch")
        add_branch = QPushButton("Add branch")
        H.addWidget(add_branch)
        H.addWidget(delete_branch)

        self.lists = []

        no_staged = QLabel("<h2>No staged</h2>")

        untracked_files = QLabel("Untracked files")
        self.untracked_files = QListWidget()
        self.lists.append(self.untracked_files)

        modified_files = QLabel("Modified files")
        self.modified_files = QListWidget()
        self.lists.append(self.modified_files)

        deleted_files = QLabel("Deleted files")
        self.deleted_files = QListWidget()
        self.lists.append(self.deleted_files)

        staged = QLabel("<h2>Staged</h2>")

        added_files = QLabel("Added files")
        self.added_files = QListWidget()
        self.lists.append(self.added_files)

        s_modified_files = QLabel("Modified files")
        self.s_modified_files = QListWidget()
        self.lists.append(self.s_modified_files)

        s_deleted_files = QLabel("Deleted files")
        self.s_deleted_files = QListWidget()
        self.lists.append(self.s_deleted_files)

        layout.addWidget(self.actual_branch, 0, 0, Qt.AlignHCenter)
        layout.addWidget(change_branch, 1, 0)
        layout.addWidget(merge_branches, 2, 0)
        layout.addWidget(no_staged, 3, 0)
        layout.addWidget(untracked_files, 4, 0)
        layout.addWidget(self.untracked_files, 5, 0)
        layout.addWidget(modified_files, 6, 0)
        layout.addWidget(self.modified_files, 7, 0)
        layout.addWidget(deleted_files, 8, 0)
        layout.addWidget(self.deleted_files, 9, 0)

        layout.addWidget(branch, 0, 1)
        layout.addWidget(self.s_branches, 1, 1)
        layout.addLayout(H, 2, 1)
        layout.addWidget(staged, 3, 1)
        layout.addWidget(added_files, 4, 1)
        layout.addWidget(self.added_files, 5, 1)
        layout.addWidget(s_modified_files, 6, 1)
        layout.addWidget(self.s_modified_files, 7, 1)
        layout.addWidget(s_deleted_files, 8, 1)
        layout.addWidget(self.s_deleted_files, 9, 1)

        self.fill(self.git.no_staged["?"], self.untracked_files)
        self.fill(self.git.no_staged["M"], self.modified_files)
        self.fill(self.git.no_staged["D"], self.deleted_files)

        self.fill(self.git.staged["A"], self.added_files)
        self.fill(self.git.staged["M"], self.s_modified_files)
        self.fill(self.git.staged["D"], self.s_deleted_files)

        self.staged_b = QPushButton('Stage files', self)
        self.unstage_b = QPushButton("Unstage files", self)
        self.commit_b = QPushButton('Commit files', self)
        self.uncommit_b = QPushButton("Uncommit files", self)

        layout.addWidget(self.staged_b, 10, 0)
        layout.addWidget(self.unstage_b, 11, 0)
        layout.addWidget(self.commit_b, 10, 1)
        layout.addWidget(self.uncommit_b, 11, 1)

        self.setLayout(layout)

        self.connect(self.staged_b, SIGNAL('clicked()'), self.add)
        self.connect(self.unstage_b, SIGNAL('clicked()'), self.unstage)
        self.connect(self.commit_b, SIGNAL('clicked()'), self.commit)
        self.connect(self.uncommit_b, SIGNAL('clicked()'), self.uncommit)
        self.connect(change_branch, SIGNAL("clicked()"), self.change_branch)
        self.connect(add_branch, SIGNAL("clicked()"), self.add_branch)
        self.connect(delete_branch, SIGNAL("clicked()"), self.delete_branch)
        self.connect(merge_branches, SIGNAL("clicked()"), self.merge_branches)

    def fill(self, a_list, widget_list):
        for x in a_list:

            item = QListWidgetItem()
            widget_list.addItem(item)
            check_box = QCheckBox(x)
            widget_list.setItemWidget(item, check_box)

    def add(self):
        path = self.plugin.editor.get_project_owner()
        for pos in reversed(xrange(self.untracked_files.count())):

            item = self.untracked_files.item(pos)
            widget = self.untracked_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.add(path, text)
                self.untracked_files.removeItemWidget(item)
                self.untracked_files.takeItem(pos)
                item = QListWidgetItem()
                self.added_files.addItem(item)
                check_box = QCheckBox(text)
                self.added_files.setItemWidget(item, check_box)

        for pos in reversed(xrange(self.modified_files.count())):

            item = self.modified_files.item(pos)
            widget = self.modified_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.add(path, widget.text())
                self.modified_files.removeItemWidget(item)
                self.modified_files.takeItem(pos)
                item = QListWidgetItem()
                self.s_modified_files.addItem(item)
                check_box = QCheckBox(text)
                self.s_modified_files.setItemWidget(item, check_box)

        for pos in reversed(xrange(self.deleted_files.count())):

            item = self.deleted_files.item(pos)
            widget = self.deleted_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.add(path, widget.text())
                self.deleted_files.removeItemWidget(item)
                self.deleted_files.takeItem(pos)
                item = QListWidgetItem()
                self.s_deleted_files.addItem(item)
                check_box = QCheckBox(text)
                self.s_deleted_files.setItemWidget(item, check_box)

    def unstage(self):

        path = self.plugin.editor.get_project_owner()
        for pos in reversed(xrange(self.untracked_files.count())):

            item = self.untracked_files.item(pos)
            widget = self.untracked_files.itemWidget(item)

            if widget.isChecked():
                self.git.unstage(path, widget.text())
                self.untracked_files.removeItemWidget(item)
                self.untracked_files.takeItem(pos)

        for pos in reversed(xrange(self.modified_files.count())):

            item = self.modified_files.item(pos)
            widget = self.modified_files.itemWidget(item)

            if widget.isChecked():
                self.git.unstage(path, widget.text())
                self.modified_files.removeItemWidget(item)
                self.modified_files.takeItem(pos)

        for pos in reversed(xrange(self.deleted_files.count())):

            item = self.deleted_files.item(pos)
            widget = self.deleted_files.itemWidget(item)

            if widget.isChecked():
                self.git.unstage(path, widget.text())
                self.deleted_files.removeItemWidget(item)
                self.deleted_files.takeItem(pos)

    def commit(self):

        msg = QInputDialog.getText(self, "Commit message", "Commit Message:")

        if msg[1] == False:
            return (0)

        path = self.plugin.editor.get_project_owner()
        for pos in reversed(xrange(self.added_files.count())):

            item = self.added_files.item(pos)
            widget = self.added_files.itemWidget(item)

            if widget.isChecked():
                self.git.commit(path, str(widget.text()), msg[0])
                self.added_files.removeItemWidget(item)
                self.added_files.takeItem(pos)

        for pos in reversed(xrange(self.s_modified_files.count())):

            item = self.s_modified_files.item(pos)
            widget = self.s_modified_files.itemWidget(item)

            if widget.isChecked():
                self.git.commit(path, widget.text(), msg[0])
                self.s_modified_files.removeItemWidget(item)
                self.s_modified_files.takeItem(pos)

        for pos in reversed(xrange(self.s_deleted_files.count())):

            item = self.s_deleted_files.item(pos)
            widget = self.s_deleted_files.itemWidget(item)

            if widget.isChecked():
                self.git.commit(path, widget.text(), msg[0])
                self.s_deleted_files.takeItem(pos)
                self.s_deleted_files.removeItemWidget(item)

    def uncommit(self):
        path = self.plugin.editor.get_project_owner()
        for pos in reversed(xrange(self.added_files.count())):

            item = self.added_files.item(pos)
            widget = self.added_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.uncommit(path, str(widget.text()))
                self.added_files.removeItemWidget(item)
                self.added_files.takeItem(pos)
                item = QListWidgetItem()
                self.untracked_files.addItem(item)
                check_box = QCheckBox(text)
                self.untracked_files.setItemWidget(item, check_box)

        for pos in reversed(xrange(self.s_modified_files.count())):

            item = self.s_modified_files.item(pos)
            widget = self.s_modified_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.uncommit(path, widget.text())
                self.s_modified_files.removeItemWidget(item)
                self.s_modified_files.takeItem(pos)
                item = QListWidgetItem()
                self.modified_files.addItem(item)
                check_box = QCheckBox(text)
                self.modified_files.setItemWidget(item, check_box)

        for pos in reversed(xrange(self.s_deleted_files.count())):

            item = self.s_deleted_files.item(pos)
            widget = self.s_deleted_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.uncommit(path, widget.text())
                self.s_deleted_files.removeItemWidget(item)
                self.s_deleted_files.takeItem(pos)
                item = QListWidgetItem()
                self.deleted_files.addItem(item)
                check_box = QCheckBox(text)
                self.deleted_files.setItemWidget(item, check_box)

    def change_branch(self):

        path = self.plugin.editor.get_project_owner()

        item = self.s_branches.currentItem()

        if item and not self.something():
            text = item.text()
            self.git.change_branch(path, text)
            self.s_branches.clear()
            self.s_branches.addItems(self.git.branch(unicode(path))[1:])
            self.actual_branch.setText("<h2>{0}<h2>".format(text))
        if self.something():
            v = QMessageBox()
            v.setText("Error: you have unsaved changes")
            v.setIcon(v.Warning)
            v.exec_()

    def add_branch(self):

        path = self.plugin.editor.get_project_owner()

        msg = QInputDialog.getText(self, "New branch", "Branch Name:")

        if msg[1] == False:
            return (0)

        self.git.add_branch(path, msg[0])
        self.s_branches.clear()
        self.s_branches.addItems(self.git.branch(unicode(path))[1:])

    def delete_branch(self):
        path = self.plugin.editor.get_project_owner()
        item = self.s_branches.currentItem()
        if item:
            text = str(item.text())
            call = self.git.delete_branch(path, text)

            if not call:
                self.s_branches.clear()
                self.s_branches.addItems(self.git.branch(unicode(path))[1:])

            else:
                m = QMessageBox()
                m.setText("<h2>" + call + "</h2>")
                m.setInformativeText("Force deletion?")
                m.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
                m.setDefaultButton(QMessageBox.Cancel)
                c = m.exec_()
                if c == QMessageBox.Ok:

                    self.git.force_delete_branch(path, text)
                    self.s_branches.clear()

                    self.s_branches.addItems(
                        self.git.branch(unicode(path))[1:])

    def merge_branches(self):
        path = self.plugin.editor.get_project_owner()
        item = self.s_branches.currentItem()
        if item:
            text = str(item.text())
            call = self.git.merge_branches(path, text)
            if call:
                m = QMessageBox()
                m.setText(call)
                m.setInformativeText("Unknown")
                m.setIcon(m.Critical)
                m.exec_()

    def something(self):
        for x in self.lists:
            if x.count() > 0:
                return True
        return False
Пример #17
0
class NotebookSettingsDialog(QDialog):
    """GUI for adjusting notebook settings"""
    def __init__(self, parent=None):
        super(NotebookSettingsDialog, self).__init__(parent)
        #widgets for tab 1
        self.mdExts = QListWidget()
        self.mjEdit = QLineEdit()
        self.moveUp = QPushButton('<<')
        self.moveDown = QPushButton('>>')
        self.configureExtension = QPushButton(
            'Edit Settings for this extension')
        self.tmpdict = deepcopy(self.parent().settings.extcfg)

        #widgets for tab 2
        self.fExtEdit = QLineEdit()
        self.attImgEdit = QLineEdit()
        self.attDocEdit = QLineEdit()
        # mandatory button box
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)

        #tab panels
        tabs = QTabWidget()
        markupTab = QWidget()
        fileExtsTab = QWidget()
        tabs.addTab(markupTab, "Markdown")
        tabs.addTab(fileExtsTab, "File extensions")

        #initialization functions
        self.initExtList()
        self.mdExts.setDragDropMode(QAbstractItemView.InternalMove)
        self.mjEdit.setText(self.parent().settings.mathjax)
        self.attImgEdit.setText(', '.join(
            self.parent().settings.attachmentImage))
        self.attDocEdit.setText(', '.join(
            self.parent().settings.attachmentDocument))
        self.fExtEdit.setText(self.parent().settings.fileExt)

        #set up tab 1
        layout = QGridLayout(markupTab)
        layout.addWidget(QLabel("Markdown extensions"), 0, 0, 1, 4)
        layout.addWidget(self.mdExts, 1, 0, 1, 4)
        layout.addWidget(self.moveUp, 2, 0, 1, 1)
        layout.addWidget(self.moveDown, 2, 1, 1, 1)
        layout.addWidget(self.configureExtension, 2, 2, 1, 2)
        layout.addWidget(QLabel("MathJax Location"), 3, 0, 1, 1)
        layout.addWidget(self.mjEdit, 3, 1, 1, 3)

        #set up tab 2
        layout = QGridLayout(fileExtsTab)
        layout.addWidget(QLabel("Note file extension"), 0, 0, 1, 1)
        layout.addWidget(QLabel("Image file extension"), 1, 0, 1, 1)
        layout.addWidget(QLabel("Document file extension"), 2, 0, 1, 1)
        layout.addWidget(self.fExtEdit, 0, 1, 1, 1)
        layout.addWidget(self.attImgEdit, 1, 1, 1, 1)
        layout.addWidget(self.attDocEdit, 2, 1, 1, 1)

        #put it together
        vlayout = QVBoxLayout(self)
        vlayout.addWidget(tabs)
        vlayout.addWidget(self.buttonBox)

        #setup signal handlers
        self.moveUp.clicked.connect(self.moveItemUp)
        self.configureExtension.clicked.connect(self.configExt)
        self.moveDown.clicked.connect(self.moveItemDown)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

    def configExt(self, checked=False, ext=None):
        if ext is None:
            ext = self.mdExts.currentItem().text()
        cfg = self.tmpdict.get(ext, [])
        dialog = NotebookExtSettingsDialog(cfg_list=cfg)
        done = dialog.exec()
        if done:
            self.tmpdict[ext] = dialog.configToList()

    def initExtList(self):
        extset = set(self.parent().settings.extensions)
        #for easier performance in checking
        for ext in self.parent().settings.extensions:
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Checked)

        for ext in self.parent().settings.faulty_exts:
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setBackground(QBrush(QColor('red')))
            item.setForeground(QBrush(QColor('black')))
            item.setCheckState(Qt.Checked)

        for ext in allMDExtensions():
            if ext in extset: continue
            item = QListWidgetItem(ext, self.mdExts)
            item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
            item.setCheckState(Qt.Unchecked)
            #self.mdExts.addItem(item)

    def moveItemUp(self):
        item = self.mdExts.currentItem()
        row = self.mdExts.currentRow()
        if row != 0:
            # self.mdExts.removeItemWidget(item)
            self.mdExts.takeItem(row)
            self.mdExts.insertItem(row - 1, item)
            self.mdExts.setCurrentRow(row - 1)

    def moveItemDown(self):
        item = self.mdExts.currentItem()
        row = self.mdExts.currentRow()
        count = self.mdExts.count()
        if row != count - 1:
            self.mdExts.takeItem(row)
            self.mdExts.insertItem(row + 1, item)
            self.mdExts.setCurrentRow(row + 1)

    def accept(self):
        #write to settings first
        msettings = self.parent().settings
        nbsettings = msettings.qsettings

        nbsettings.setValue('mathJax', self.mjEdit.text())
        extlist = []
        for i in range(self.mdExts.count()):
            item = self.mdExts.item(i)
            if item.checkState() == Qt.Checked:
                extlist.append(item.text())
        writeListToSettings(nbsettings, 'extensions', extlist)
        writeListToSettings(nbsettings, 'attachmentImage',
                            self.attImgEdit.text().split(", "))
        writeListToSettings(nbsettings, 'attachmentDocument',
                            self.attDocEdit.text().split(", "))
        writeDictToSettings(nbsettings, 'extensionsConfig', self.tmpdict)

        #then to memory
        msettings.extensions = extlist
        msettings.mathjax = self.mjEdit.text()
        msettings.attachmentDocument = readListFromSettings(
            nbsettings, 'attachmentDocument')
        msettings.attachmentImage = readListFromSettings(
            nbsettings, 'attachmentImage')
        msettings.extcfg.update(self.tmpdict)
        msettings.md = markdown.Markdown(msettings.extensions,
                                         extension_configs=msettings.extcfg)

        #then make mikidown use these settings NOW
        curitem = self.parent().notesTree.currentItem()
        self.parent().currentItemChangedWrapper(curitem, curitem)
        QDialog.accept(self)
Пример #18
0
class urlgroup(QGroupBox):
    def __init__(self, parent=None):
        super(urlgroup, self).__init__(parent)
        self.setGeometry(10, 30, 500, 80)
        self.setObjectName('urlgroup')
        self.urlbar = QLineEdit()
        self.urlbar.setObjectName('urlbar')
        self.urlbar.setText('Collez votre URL i�i')
        self.urlbar.setStyleSheet('font-weight:lighter;color:gray;')
        self.urlbar.show()
        self.parsebutton = QPushButton('Go !!')
        self.parsebutton.setObjectName('parsebutton')
        self.parsebutton.show()
        layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        layout.addWidget(self.urlbar)
        layout.addWidget(self.parsebutton)
        self.show()
        self.group2 = QGroupBox(parent)
        self.group2.setObjectName('core')
        self.group2.setGeometry(10, 120, 500, 280)
        self.group2.show()
        self.group3 = QGroupBox(self.group2)
        self.group3.setObjectName('albuminfos')
        self.group3.setGeometry(10, 15, 200, 245)
        self.group3.show()
        self.itemlist = QListWidget(self.group2)
        self.itemlist.setGeometry(250, 15, 230, 245)
        self.itemlist.show()
        self.dlgroup = QGroupBox(parent)
        self.dlgroup.setObjectName('dlgroup')
        self.dlgroup.setGeometry(10, 420, 500, 100)
        self.dlgroup.show()
        self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup)
        self.dlgroup.dlbutton.setObjectName('dlbutton')
        self.dlgroup.dlbutton.move(10, 20)
        self.dlgroup.dlbutton.show()
        self.dlgroup.progressbar = QProgressBar(self.dlgroup)
        self.dlgroup.progressbar.setObjectName('progressbar')
        self.dlgroup.progressbar.setGeometry(100, 21, 380, 21)
        self.dlgroup.progressbar.show()
        self.dlgroup.dlinfos = QLabel(self.dlgroup)
        self.dlgroup.dlinfos.setGeometry(100, 70, 200, 21)
        self.dlgroup.dlinfos.show()
        self.dlgroup.dledfile = QLabel(self.dlgroup)
        self.dlgroup.dledfile.setGeometry(300, 70, 200, 21)
        self.dlgroup.dledfile.show()
        self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup)
        self.dlgroup.dlto.setGeometry(100, 50, 350, 21)
        self.dlgroup.dlto.show()
        self.dlgroup.dlto.changebt = QToolButton(self.dlgroup)
        self.dlgroup.dlto.changebt.setObjectName('dltobt')
        self.dlgroup.dlto.changebt.setGeometry(10, 50, 75, 21)
        self.dlgroup.dlto.changebt.setText('To')
        self.dlgroup.dlto.changebt.show()
        self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup)
        self.dlgroup.dlto.openf.setGeometry(455, 50, 35, 21)
        self.dlgroup.dlto.openf.setObjectName('openfolder')
        self.dlgroup.dlto.openf.show()
        self.album = QLabel(self.group3)
        self.artist = QLabel(self.group3)
        self.year = QLabel(self.group3)
        self.tracks = QLabel(self.group3)
        self.coverart = QLabel(self.group3)
        self.urlbar.setFocus(True)
        self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked)
        self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl)
        self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'),
                     self.changedir)
        self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'),
                     self.openfolder)

    def parseclicked(self):
        self.itemlist.clear()
        url = str(self.urlbar.text())
        self.infos = getsonglist(url)
        if (self.infos == 'connexion impossible') or (self.infos
                                                      == 'unsupported'):
            self.error = QMessageBox()
            if self.infos == 'connexion impossible':
                self.error.setText('Connexion Impossible !')
            elif self.infos == 'unsupported':
                self.error.setText('Site Unsupported !!')
            self.error.setWindowTitle('Erreur!')
            self.error.setIcon(QMessageBox.Warning)
            self.icon = QIcon('images/mainwindowicon.png')
            self.error.setWindowIcon(self.icon)
            self.error.exec_()
        else:
            self.artist.setText('Artiste : ' + self.infos['artist'])
            self.artist.move(40, 175)
            self.artist.show()
            self.album.setText('Album : ' + self.infos['albumname'])
            self.album.move(40, 190)
            self.album.show()
            try:
                self.year.setText('Annee : ' + self.infos['year'])

            except KeyError:
                self.year.setText('Annee : ' + 'N/A')
            self.year.move(40, 205)
            self.year.show()
            self.tracks.setText('Tracks : ' + str(self.infos['tracks']))
            self.tracks.move(40, 220)
            self.tracks.show()
            coverartpix = QPixmap(self.infos['coverart'])
            coverartpix = coverartpix.scaled(
                178,
                135,
            )
            self.coverart.setPixmap(coverartpix)
            self.coverart.move(10, 10)
            self.coverart.show()
            self.list2 = []
            for item in self.infos['titles']:
                item = tracklistitems(item)
                self.list2.append(item)
            for item in self.list2:
                self.itemlist.addItem(item)

    def launchdl(self):
        if self.dlgroup.dlbutton.text() == 'Download':
            try:
                self.itemlist.item(self.currentitem).setText(self.text)
            except:
                pass
            self.dlgroup.dlbutton.setText('Stop')
            rmtree('tmpimg', True)
            i = 0
            dllist = []
            for item in self.list2:
                if item.eligible() == 'Checked':
                    dllist.append(i)
                i = i + 1
            self.stritemlist = []
            for i in range(0, self.infos['tracks']):
                #print i
                #print self.itemlist.item(i).text()
                #TODO: hamida album breaks, recheck regexes
                self.stritemlist.append(str(self.itemlist.item(i).text()))
            dlto = self.dlgroup.dlto.text()
            self.thread = dlThread(dllist, self.infos, dlto, self.stritemlist)
            self.connect(self.thread, SIGNAL('progress(PyQt_PyObject)'),
                         self.updateProgress)
            self.connect(self.thread, SIGNAL('dledfile(PyQt_PyObject)'),
                         self.updateDlednow)
            self.thread.start()
        else:
            self.dlgroup.dlbutton.setText('Download')
            self.thread.terminate()

    def updateProgress(self, progress):
        self.dlgroup.progressbar.setValue(progress['bar'])
        self.dlgroup.dlinfos.setText(progress['info'])
        self.text = self.stritemlist[progress['item']]
        self.currentitem = progress['item']
        self.percent = str(progress['bar']) + ' % - '
        self.percent = QString(self.percent)
        self.dlingicon = QIcon('images/dling.png')
        self.doneicon = QIcon('images/done.png')
        self.itemlist.item(progress['item']).setIcon(self.dlingicon)
        self.itemlist.item(progress['item']).setText(self.percent + self.text)
        if progress['bar'] >= 98:
            self.itemlist.item(progress['item']).setIcon(self.doneicon)
            self.itemlist.item(progress['item']).setText(self.text)
            self.itemlist.item(progress['item']).setCheckState(Qt.Unchecked)
            self.itemlist.item(
                progress['item']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable
                                           | Qt.ItemIsSelectable)

    def updateDlednow(self, dledfile):
        self.dlgroup.dledfile.setText(dledfile)

    def changedir(self):
        self.dir = QFileDialog.getExistingDirectory()
        self.dlgroup.dlto.setText(self.dir + '/')

    def openfolder(self):
        startfile(self.dlgroup.dlto.text())

    def stopdl(self):
        pass
Пример #19
0
class CheckList(QWidget):
    def __init__(self,
                 model,
                 label="",
                 help_link="",
                 custom_filter_button=None):
        """
        :param custom_filter_button:  if needed, add a button that opens a custom filter menu. Useful when search alone
        isn't enough to filter the list.
        :type custom_filter_button: QToolButton
        """
        QWidget.__init__(self)

        self._model = model

        if help_link != "":
            addHelpToWidget(self, help_link)

        layout = QVBoxLayout()

        self._createCheckButtons()

        self._list = QListWidget()
        self._list.setContextMenuPolicy(Qt.CustomContextMenu)
        self._list.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self._search_box = SearchBox()

        check_button_layout = QHBoxLayout()

        check_button_layout.setMargin(0)
        check_button_layout.setSpacing(0)
        check_button_layout.addWidget(QLabel(label))
        check_button_layout.addStretch(1)
        check_button_layout.addWidget(self._checkAllButton)
        check_button_layout.addWidget(self._uncheckAllButton)

        layout.addLayout(check_button_layout)
        layout.addWidget(self._list)
        """
        Inserts the custom filter button, if provided. The caller is responsible for all related actions.
        """
        if custom_filter_button is not None:
            search_bar_layout = QHBoxLayout()
            search_bar_layout.addWidget(self._search_box)
            search_bar_layout.addWidget(custom_filter_button)
            layout.addLayout(search_bar_layout)
        else:
            layout.addWidget(self._search_box)

        self.setLayout(layout)

        self._checkAllButton.clicked.connect(self.checkAll)
        self._uncheckAllButton.clicked.connect(self.uncheckAll)
        self._list.itemChanged.connect(self.itemChanged)
        self._search_box.filterChanged.connect(self.filterList)
        self._list.customContextMenuRequested.connect(self.showContextMenu)

        self._model.selectionChanged.connect(self.modelChanged)
        self._model.modelChanged.connect(self.modelChanged)

        self.modelChanged()

    def _createCheckButtons(self):
        self._checkAllButton = QToolButton()
        self._checkAllButton.setIcon(resourceIcon("checked"))
        self._checkAllButton.setIconSize(QSize(16, 16))
        self._checkAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self._checkAllButton.setAutoRaise(True)
        self._checkAllButton.setToolTip("Select all")
        self._uncheckAllButton = QToolButton()
        self._uncheckAllButton.setIcon(resourceIcon("notchecked"))
        self._uncheckAllButton.setIconSize(QSize(16, 16))
        self._uncheckAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self._uncheckAllButton.setAutoRaise(True)
        self._uncheckAllButton.setToolTip("Unselect all")

    def itemChanged(self, item):
        """@type item: QListWidgetItem"""
        if item.checkState() == Qt.Checked:
            self._model.selectValue(str(item.text()))
        elif item.checkState() == Qt.Unchecked:
            self._model.unselectValue(str(item.text()))
        else:
            raise AssertionError("Unhandled checkstate!")

    def modelChanged(self):
        self._list.clear()

        items = self._model.getList()

        for item in items:
            list_item = QListWidgetItem(item)
            list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)

            if self._model.isValueSelected(item):
                list_item.setCheckState(Qt.Checked)
            else:
                list_item.setCheckState(Qt.Unchecked)

            self._list.addItem(list_item)

        self.filterList(self._search_box.filter())

    def setSelectionEnabled(self, enabled):
        self.setEnabled(enabled)
        self._checkAllButton.setEnabled(enabled)
        self._uncheckAllButton.setEnabled(enabled)

    def filterList(self, filter):
        filter = filter.lower()

        for index in range(0, self._list.count()):
            item = self._list.item(index)
            text = str(item.text()).lower()

            if filter == "":
                item.setHidden(False)
            elif filter in text:
                item.setHidden(False)
            else:
                item.setHidden(True)

    def checkAll(self):
        """
        Checks all visible items in the list.
        """
        for index in range(0, self._list.count()):
            item = self._list.item(index)
            if not item.isHidden():
                self._model.selectValue(str(item.text()))

    def uncheckAll(self):
        """
        Unchecks all items in the list, visible or not
        """
        self._model.unselectAll()

    def checkSelected(self):
        items = []
        for item in self._list.selectedItems():
            items.append(str(item.text()))

        for item in items:
            self._model.selectValue(item)

    def uncheckSelected(self):
        items = []
        for item in self._list.selectedItems():
            items.append(str(item.text()))

        for item in items:
            self._model.unselectValue(item)

    def showContextMenu(self, point):
        p = self._list.mapToGlobal(point)
        menu = QMenu()
        check_selected = menu.addAction("Check selected")
        uncheck_selected = menu.addAction("Uncheck selected")
        menu.addSeparator()
        clear_selection = menu.addAction("Clear selection")

        selected_item = menu.exec_(p)

        if selected_item == check_selected:
            self.checkSelected()
        elif selected_item == uncheck_selected:
            self.uncheckSelected()
        elif selected_item == clear_selection:
            self._list.clearSelection()
Пример #20
0
class ListBox(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("ListBox" + str(len(parent.findChildren(ListBox))))

        self.hLayoutBoxPanel = QHBoxLayout(self)
        self.hLayoutBoxPanel.setSpacing(0)
        self.hLayoutBoxPanel.setContentsMargins(3, 3, 3, 3)
        self.hLayoutBoxPanel.setObjectName(("hLayoutBoxPanel"))
        self.frameBoxPanel = QFrame(self)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.frameBoxPanel.sizePolicy().hasHeightForWidth())
        self.frameBoxPanel.setSizePolicy(sizePolicy)
        self.frameBoxPanel.setFrameShape(QFrame.NoFrame)
        self.frameBoxPanel.setFrameShadow(QFrame.Raised)
        self.frameBoxPanel.setObjectName(("frameBoxPanel"))
        self.hLayoutframeBoxPanel = QHBoxLayout(self.frameBoxPanel)
        self.hLayoutframeBoxPanel.setSpacing(0)
        self.hLayoutframeBoxPanel.setMargin(0)
        self.hLayoutframeBoxPanel.setObjectName(("hLayoutframeBoxPanel"))
        self.captionLabel = QLabel(self.frameBoxPanel)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.captionLabel.sizePolicy().hasHeightForWidth())
        self.captionLabel.setSizePolicy(sizePolicy)
        self.captionLabel.setMinimumSize(QSize(200, 0))
        self.captionLabel.setMaximumSize(QSize(200, 16777215))
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.captionLabel.setFont(font)
        self.captionLabel.setObjectName(("captionLabel"))
        self.hLayoutframeBoxPanel.addWidget(self.captionLabel)

        self.listBox = QListWidget(self.frameBoxPanel)
        self.listBox.setEnabled(True)
        font = QFont()
        font.setBold(False)
        font.setWeight(50)
        self.listBox.setFont(font)
        self.listBox.setObjectName(("listBox"))
        # self.listBox.setText("0.0")
        self.hLayoutframeBoxPanel.addWidget(self.listBox)

        self.imageButton = QToolButton(self.frameBoxPanel)
        self.imageButton.setText((""))
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/convex_hull.png")), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setObjectName(("imageButton"))
        self.imageButton.setVisible(False)
        self.hLayoutframeBoxPanel.addWidget(self.imageButton)

        self.hLayoutBoxPanel.addWidget(self.frameBoxPanel)

        self.listBox.currentRowChanged.connect(self.listBoxChanged)
        self.imageButton.clicked.connect(self.imageButtonClicked)

        self.captionUnits = ""

        self.hasObject = False

        self.objectList = []
        self.captionLabel.setVisible(False)

    def get_Count(self):
        return self.listBox.count()

    Count = property(get_Count, None, None, None)

    def method_3(self, string_0):
        return self.listBox.row(self.listBox.findItems(string_0)[0])

    def method_11(self, string_0):
        if (self.IsEmpty):
            return "%s%s\t" % (string_0, self.Caption)
        return "%s%s\t%s %s" % (string_0, self.Caption, self.Value,
                                self.CaptionUnits)

    def listBoxChanged(self, index):
        i = index
        self.emit(SIGNAL("Event_0"), self)

    def IndexOf(self, item):
        if isinstance(item, str):
            return self.listBox.row(self.listBox.findItems(item)[0])
        else:
            return self.listBox.row(
                self.listBox.findItems(item.ToString())[0])

    def Contains(self, item):
        compStr = None
        if isinstance(item, str):
            compStr = item
        elif isinstance(item, float) or isinstance(item, int):
            compStr = str(item)
        else:
            compStr = item.ToString()
        for i in range(self.listBox.count()):
            comboItemstr = self.listBox.item(i).text()
            if compStr == comboItemstr:
                return True
        return False

    def Clear(self):
        self.listBox.clear()
        self.objectList = []
        self.hasObject = False

    def Add(self, item):
        if not isinstance(item, str) and not isinstance(item, QString):
            self.listBox.addItem(item.ToString())
            self.objectList.append(item)
            self.hasObject = True
            return
        self.listBox.addItem(item)
        self.hasObject = False
        return self.listBox.count() - 1

    def Insert(self, index, item):
        if not isinstance(item, str):
            self.listBox.insertItem(index, item.ToString())
            self.objectList.insert(index, item)
            self.hasObject = True
            return
        self.listBox.insertItem(index, item)
        self.hasObject = False

    def imageButtonClicked(self):
        self.emit(SIGNAL("Event_3"), self)

    def get_Caption(self):
        caption = self.captionLabel.text()
        findIndex = caption.indexOf("(")
        if findIndex > 0:
            val = caption.left(findIndex)
            return val
        return caption

    def set_Caption(self, captionStr):
        if captionStr == "":
            self.captionLabel.setText("")
            self.LabelWidth = 0
            return
        if self.CaptionUnits != "" and self.CaptionUnits != None:
            self.captionLabel.setText(captionStr + "(" +
                                      str(self.CaptionUnits) + ")" + ":")
        else:
            self.captionLabel.setText(captionStr + ":")

    Caption = property(get_Caption, set_Caption, None, None)

    def get_CaptionUnits(self):
        return self.captionUnits

    def set_CaptionUnits(self, captionUnits):
        self.captionUnits = captionUnits

    CaptionUnits = property(get_CaptionUnits, set_CaptionUnits, None, None)

    def set_ButtonVisible(self, bool):
        self.imageButton.setVisible(bool)

    ButtonVisible = property(None, set_ButtonVisible, None, None)

    # def get_Value(self):
    #     return self.listBox.currentIndex()
    #
    # def set_Value(self, value):
    #     try:
    #         self.listBox.setCurrentIndex(value)
    #     except:
    #         self.textBox.setText("")
    # Value = property(get_Value, set_Value, None, None)

    # def get_IsEmpty(self):
    #     return self.listBox.currentText() == "" or self.listBox.currentIndex() == -1
    # IsEmpty = property(get_IsEmpty, None, None, None)

    # def get_ReadOnly(self):
    #     return self.listBox.isReadOnly()
    # # def set_ReadOnly(self, bool):
    # #     self.listBox.setR.setReadOnly(bool)
    # # ReadOnly = property(get_ReadOnly, set_ReadOnly, None, None)

    def set_LabelWidth(self, width):
        self.captionLabel.setMinimumSize(QSize(width, 0))
        self.captionLabel.setMaximumSize(QSize(width, 16777215))

    LabelWidth = property(None, set_LabelWidth, None, None)

    def set_Width(self, width):
        self.listBox.setMinimumSize(QSize(width, 0))
        self.listBox.setMaximumSize(QSize(width, 16777215))

    Width = property(None, set_Width, None, None)

    def set_Button(self, imageName):
        if imageName == None or imageName == "":
            self.imageButton.setVisible(False)
            return
        icon = QIcon()
        icon.addPixmap(QPixmap(("Resource/" + imageName)), QIcon.Normal,
                       QIcon.Off)
        self.imageButton.setIcon(icon)
        self.imageButton.setVisible(True)

    Button = property(None, set_Button, None, None)

    def get_SelectedIndex(self):
        try:
            return self.listBox.currentRow()
        except:
            return 0

    def set_SelectedIndex(self, index):
        if self.listBox.count() == 0:
            return
        if index > self.listBox.count() - 1:
            self.listBox.setCurrentRow(0)
        else:
            self.listBox.setCurrentRow(index)

    SelectedIndex = property(get_SelectedIndex, set_SelectedIndex, None, None)

    # def get_Value(self):
    #     return self.listBox.currentIndex()
    # def set_Value(self, valueStr):
    #     if self.listBox.count() == 0:
    #         return
    #     self.listBox.setCurrentIndex(self.listBox.findText(valueStr))
    # Value = property(get_Value, set_Value, None, None)

    def get_Items(self):
        if self.hasObject:
            return self.objectList
        itemList = []
        if self.listBox.count() > 0:
            for i in range(self.listBox.count()):
                itemList.append(self.listBox.item(i).text())
        return itemList

    def set_AddItems(self, strList):
        if len(strList) != 0 and not isinstance(
                strList[0], str) and not isinstance(strList[0], QString):
            for obj in strList:
                self.listBox.addItem(obj.ToString())
                self.objectList.append(obj)
            self.hasObject = True
            return
        self.listBox.addItems(strList)

    Items = property(get_Items, set_AddItems, None, None)

    def get_Enabled(self):
        return self.listBox.isEnabled()

    def set_Enabled(self, bool):
        self.listBox.setEnabled(bool)

    Enabled = property(get_Enabled, set_Enabled, None, None)

    def get_Visible(self):
        return self.isVisible()

    def set_Visible(self, bool):
        self.setVisible(bool)

    Visible = property(get_Visible, set_Visible, None, None)

    def get_SelectedItem(self):
        if self.listBox.count() == 0:
            return None
        if self.hasObject:
            return self.objectList[self.SelectedIndex]
        return self.listBox.currentItem().text()

    # def set_SelectedItem(self, val):
    #     index = self.listBox.findText(val)
    #     self.listBox.setCurrentIndex(index)
    SelectedItem = property(get_SelectedItem, None, None, None)
class WellExportDialog(QDialog):
    def __init__(self):
        super(WellExportDialog, self).__init__()
        self.resize(400, 300)
        self.initUI()
        self.export_Button.clicked.connect(self.export_well)
        self.button_box.rejected.connect(self.close)
        self.select_Button.clicked.connect(self.select_file)
        self.well_comboBox.currentIndexChanged.connect(
            self.populate_log_listWidget)

        self.update_well_comboBox()

    def initUI(self):
        self.setWindowIcon(QIcon(':/icon/export'))
        self.setWindowTitle("Export Well")
        self.layout = QGridLayout(self)
        # add QLabel
        self.label_0 = QLabel(self)
        self.label_0.setGeometry(QRect(0, 24, 31, 20))
        self.label_0.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                  | Qt.AlignVCenter)
        self.label_0.setText("Well to export:")
        self.layout.addWidget(self.label_0, 0, 0)
        # add QComboBox
        self.well_comboBox = QComboBox(self)
        self.well_comboBox.setGeometry(QRect(10, 10, 101, 24))
        self.layout.addWidget(self.well_comboBox, 0, 1, 1, 1)
        # add QCheckBox
        self.checkbox = QCheckBox(self)
        self.checkbox.setText("Full LAS")
        self.checkbox.setCheckState(Qt.Unchecked)
        self.layout.addWidget(self.checkbox, 0, 2)
        # add QListWidget
        self.logs_listWidget = QListWidget(self)
        self.logs_listWidget.setGeometry(QRect(0, 0, 101, 201))
        # self.well_comboBox.setMaximumHeight(151)
        self.layout.addWidget(self.logs_listWidget, 1, 1)
        # add QLabel
        self.label_1 = QLabel(self)
        self.label_1.setGeometry(QRect(0, 24, 31, 20))
        self.label_1.setAlignment(Qt.AlignRight | Qt.AlignTrailing
                                  | Qt.AlignVCenter)
        self.label_1.setText("Output File:")
        self.layout.addWidget(self.label_1, 2, 0)
        # add QLineEdit
        self.file_path_lineEdit = QLineEdit(self)
        self.file_path_lineEdit.setGeometry(QRect(50, 24, 81, 20))
        self.layout.addWidget(self.file_path_lineEdit, 2, 1)
        # add Button
        self.select_Button = QPushButton(self)
        self.select_Button.setMaximumSize(QSize(61, 24))
        self.select_Button.setText("Select")
        self.layout.addWidget(self.select_Button, 2, 2)
        # add QDialogButtonBox
        self.button_box = QDialogButtonBox(self)
        self.export_Button = self.button_box.addButton(
            "Export", QDialogButtonBox.ApplyRole)
        self.button_box.addButton(QDialogButtonBox.Cancel)
        self.layout.addWidget(self.button_box, 3, 0, 1, 3)

    def update_well_comboBox(self):
        survey_file = CONF.survey_dir / '.survey'
        if survey_file.exists():
            dnames = get_data_files(CONF.well_dir)
            self.well_comboBox.addItems(dnames)

    def populate_log_listWidget(self):
        self.logs_listWidget.clear()
        well = ppp.Well(
            str(CONF.well_dir /
                ".{}".format(self.well_comboBox.currentText())))
        # self.logs_listWidget.addItems(well.logs)
        for name in well.logs:
            new_item = QListWidgetItem(name, self.logs_listWidget)
            new_item.setFlags(new_item.flags() | Qt.ItemIsUserCheckable)
            new_item.setCheckState(Qt.Unchecked)

    def export_well(self):
        file_name = str(self.file_path_lineEdit.text())
        if not file_name:
            QMessageBox().information(self, "Info",
                                      "Please select ouput file.")
            pass
        else:
            well = well = ppp.Well(
                str(CONF.well_dir /
                    ".{}".format(self.well_comboBox.currentText())))
            logs_to_export = []
            for i in range(self.logs_listWidget.count()):
                item = self.logs_listWidget.item(i)
                if item.checkState() == Qt.Checked:
                    logs_to_export.append(str(item.text()))
            full = True if self.checkbox.checkState() == Qt.Checked \
                else False
            well.export(file_name, logs_to_export, full)
            QMessageBox().information(self, "Info", "Succeed!")

    def select_file(self):
        fl = QFileDialog.getSaveFileName(self, 'Save File', str(CONF.well_dir))
        self.file_path_lineEdit.setText(fl)
Пример #22
0
class TracklistWidget(QWidget):

    requestUpload = pyqtSignal(list)


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

        self.tracklist = QListWidget(self)
        self.tracklist.setSelectionMode(QListWidget.NoSelection)

        self.upload_button = QPushButton(
            QIcon(resource_path('images/strava-button.png')),
                  'Upload to Strava', self)
        self.upload_button.setMinimumHeight(50)
        self.upload_button.setIconSize(QSize(40, 40))

        self.clear_password = QPushButton(
            QIcon(resource_path('images/cross.png')),
                  'Clear password', self)
        self.clear_password.setMinimumHeight(50)
        self.clear_password.setIconSize(QSize(20, 20))
        self.clear_password.hide()


        self.upload_button.clicked.connect(self._onUploadClicked)

        self._createLayout()



    def setTracks(self, tracks):
        self.tracklist.clear()
        self.tracklist.addItems(tracks)

        for i, name in enumerate(tracks):
            self.tracklist.item(i).setCheckState(Qt.Unchecked)
            self.tracklist.item(i).setSizeHint(QSize(200, 25))

        if tracks:
            self.tracklist.item(i).setCheckState(Qt.Checked)
            self.upload_button.setEnabled(True)
        else:
            self.upload_button.setEnabled(False)


    def _onUploadClicked(self):

        ids = []
        for i in range(self.tracklist.count()):

            item = self.tracklist.item(i)
            if item.checkState() == Qt.Checked:
                ids.append(i)


        if ids:
            self.requestUpload.emit(ids)



    def _createLayout(self):

        l = QVBoxLayout()
        l.addWidget(self.tracklist)

        h = QHBoxLayout()
        h.addWidget(self.upload_button)
        h.addWidget(self.clear_password)
        l.addLayout(h)

        self.setLayout(l)
Пример #23
0
class ChainComposerDialog(QDialog):
    def __init__(self, parent=None):
        super(ChainComposerDialog, self).__init__(parent)
        self.setWindowTitle("Composer Chain")

        layout = QVBoxLayout()

        mainLayout = QHBoxLayout()

        selectionLayout = QVBoxLayout()
        label = QLabel("Available Filters:")
        selectionLayout.addWidget(label)
        self.__selectionList = QListWidget()
        selectionLayout.addWidget(self.__selectionList)
        mainLayout.addLayout(selectionLayout)

        actionsLayout = QVBoxLayout()
        actionsLayout.addStretch()
        addButton = QPushButton("Add>>")
        addButton.clicked.connect(self.__handleAdd)
        actionsLayout.addWidget(addButton)
        removeButton = QPushButton("Remove")
        actionsLayout.addWidget(removeButton)
        removeAllButton = QPushButton("Remove All")
        actionsLayout.addWidget(removeAllButton)
        actionsLayout.addStretch()
        mainLayout.addLayout(actionsLayout)

        chainLayout = QVBoxLayout()
        chainLayout.addWidget(QLabel("Chain:"))
        self.__chainList = QListWidget()
        chainLayout.addWidget(self.__chainList)
        mainLayout.addLayout(chainLayout)

        layout.addLayout(mainLayout)

        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.okClick)
        buttonBox.rejected.connect(self.cancelClick)
        layout.addWidget(buttonBox)

        #         buttonLayout = QHBoxLayout()
        #         okButton = QPushButton('OK')
        #         okButton.clicked.connect(self.accept)
        #         buttonLayout.addWidget(okButton)
        #         cancelButton = QPushButton('Cancel')
        #         cancelButton.clicked.connect(self.reject)
        #         buttonLayout.addWidget(cancelButton)
        #         layout.addLayout(buttonLayout)

        self.setLayout(layout)

        self.__composer = None

    def okClick(self):
        print "OK!"
        self.accept()

    def cancelClick(self):
        print "Cancel"
        self.reject()

    def setComposer(self, composer):
        self.__composer = composer

    @property
    def selectionList(self):
        return self.__getStrings(self.__selectionList)

    @selectionList.setter
    def setSelectionList(self, filters):
        for i in xrange(self.__selectionList.count()):
            self.__selectionList.takeItem(i)
        self.__selectionList.addItems(filters)

    def filterAt(self, row):
        return self.__selectionList.item(row).text()

    def addToChain(self, filterName):
        self.__chainList.addItem(filterName)

    @property
    def composedFilter(self):
        return self.__getStrings(self.__chainList)

    @staticmethod
    def __getStrings(listWidget):
        return tuple(listWidget.item(i) for i in range(listWidget.count()))

    def __handleAdd(self):
        if self.__composer is None:
            return
        for item in self.__selectionList.selectedItems():
            row = self.__selectionList.row(item)
            self.__composer.add(row)
Пример #24
0
class CheckList(HelpedWidget):
    
    def __init__(self, model, label="", help_link=""):
        HelpedWidget.__init__(self, "", help_link)

        layout = QVBoxLayout()

        widget = QWidget()
        widget.setLayout(layout)

        self.checkAllButton = QToolButton()
        self.checkAllButton.setIcon(resourceIcon("checked"))
        self.checkAllButton.setIconSize(QSize(16, 16))
        self.checkAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.checkAllButton.setAutoRaise(True)
        self.checkAllButton.setToolTip("Select all")

        self.uncheckAllButton = QToolButton()
        self.uncheckAllButton.setIcon(resourceIcon("notchecked"))
        self.uncheckAllButton.setIconSize(QSize(16, 16))
        self.uncheckAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.uncheckAllButton.setAutoRaise(True)
        self.uncheckAllButton.setToolTip("Unselect all")

        self.list = QListWidget()
        self.list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.search_box = SearchBox()

        check_button_layout = QHBoxLayout()

        check_button_layout.setMargin(0)
        check_button_layout.setSpacing(0)
        check_button_layout.addWidget(QLabel(label))
        check_button_layout.addStretch(1)
        check_button_layout.addWidget(self.checkAllButton)
        check_button_layout.addWidget(self.uncheckAllButton)

        layout.addLayout(check_button_layout)
        layout.addWidget(self.list)
        layout.addWidget(self.search_box)

        self.addWidget(widget)

        self.connect(self.checkAllButton, SIGNAL('clicked()'), self.checkAll)
        self.connect(self.uncheckAllButton, SIGNAL('clicked()'), self.uncheckAll)
        self.connect(self.list, SIGNAL('itemChanged(QListWidgetItem*)'), self.itemChanged)
        self.search_box.filterChanged.connect(self.filterList)
        # self.connect(self.search_box, SIGNAL('filterChanged(str)'), self.filterList)

        self.connect(self.list, SIGNAL('customContextMenuRequested(QPoint)'), self.showContextMenu)

        assert isinstance(model, (SelectableModelMixin, ListModelMixin))
        self.model = model
        self.model.observable().attach(SelectableModelMixin.SELECTION_CHANGED_EVENT, self.modelChanged)
        self.model.observable().attach(ListModelMixin.LIST_CHANGED_EVENT, self.modelChanged)
        self.modelChanged()

    def itemChanged(self, item):
        """@type item: QListWidgetItem"""
        if item.checkState() == Qt.Checked:
            self.model.selectValue(str(item.text()))
        elif item.checkState() == Qt.Unchecked:
            self.model.unselectValue(str(item.text()))
        else:
            raise AssertionError("Unhandled checkstate!")

    def modelChanged(self):
        self.list.clear()

        items = self.model.getList()

        for item in items:
            list_item = QListWidgetItem(item)
            list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)

            if self.model.isValueSelected(item):
                list_item.setCheckState(Qt.Checked)
            else:
                list_item.setCheckState(Qt.Unchecked)

            self.list.addItem(list_item)

        self.filterList(self.search_box.filter())

    def setSelectionEnabled(self, enabled):
        self.setEnabled(enabled)
        self.checkAllButton.setEnabled(enabled)
        self.uncheckAllButton.setEnabled(enabled)

    def filterList(self, filter):
        filter = filter.lower()

        for index in range(0, self.list.count()):
            item = self.list.item(index)
            text = str(item.text()).lower()

            if filter == "":
                item.setHidden(False)
            elif filter in text:
                item.setHidden(False)
            else:
                item.setHidden(True)


    def checkAll(self):
        self.model.selectAll()

    def uncheckAll(self):
        self.model.unselectAll()

    def checkSelected(self):
        items = []
        for item in self.list.selectedItems():
            items.append(str(item.text()))

        for item in items:
            self.model.selectValue(item)

    def uncheckSelected(self):
        items = []
        for item in self.list.selectedItems():
            items.append(str(item.text()))

        for item in items:
            self.model.unselectValue(item)

    def showContextMenu(self, point):
        p = self.list.mapToGlobal(point)
        menu = QMenu()
        check_selected = menu.addAction("Check selected")
        uncheck_selected = menu.addAction("Uncheck selected")
        menu.addSeparator()
        clear_selection = menu.addAction("Clear selection")

        selected_item = menu.exec_(p)

        if selected_item == check_selected:
            self.checkSelected()
        elif selected_item == uncheck_selected:
            self.uncheckSelected()
        elif selected_item == clear_selection:
            self.list.clearSelection()
Пример #25
0
class StringListDlg(QDialog):

    acceptedList = Signal(QStringList)

    def __init__(self, name, stringlist=None, parent=None):
        super(StringListDlg, self).__init__(parent)
        self.name = name
        self.create_widgets(stringlist)
        self.layout_widgets()
        self.setWindowTitle("Edit {0} List".format(self.name))


    def create_widgets(self, stringlist):
        self.listWidget = QListWidget()
        if stringlist is not None:
            self.listWidget.addItems(stringlist)
            self.listWidget.setCurrentRow(0)


    def layout_widgets(self):
        buttonLayout = QVBoxLayout()
        for text, slot in (("&Add...", self.add),
                           ("&Edit...", self.edit),
                           ("&Remove...", self.remove),
                           ("&Up", self.up),
                           ("&Down", self.down),
                           ("&Sort", self.listWidget.sortItems),
                           ("Close", self.accept)):
            button = QPushButton(text)
            if not MAC:
                button.setFocusPolicy(Qt.NoFocus)
            if text == "Close":
                buttonLayout.addStretch()
            buttonLayout.addWidget(button)
            button.clicked.connect(slot)
        layout = QHBoxLayout()
        layout.addWidget(self.listWidget)
        layout.addLayout(buttonLayout)
        self.setLayout(layout)


    def add(self):
        row = self.listWidget.currentRow()
        title = "Add {0}".format(self.name)
        string, ok = QInputDialog.getText(self, title, title)
        if ok and not string.isEmpty():
            self.listWidget.insertItem(row, string)


    def edit(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is not None:
            title = "Edit {0}".format(self.name)
            string, ok = QInputDialog.getText(self, title, title,
                    QLineEdit.Normal, item.text())
            if ok and not string.isEmpty():
                item.setText(string)


    def remove(self):
        row = self.listWidget.currentRow()
        item = self.listWidget.item(row)
        if item is None:
            return
        reply = QMessageBox.question(self, "Remove {0}".format(
                self.name), "Remove {0} `{1}'?".format(
                self.name, unicode(item.text())),
                QMessageBox.Yes|QMessageBox.No)
        if reply == QMessageBox.Yes:
            item = self.listWidget.takeItem(row)
            del item


    def up(self):
        row = self.listWidget.currentRow()
        if row >= 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row - 1, item)
            self.listWidget.setCurrentItem(item)


    def down(self):
        row = self.listWidget.currentRow()
        if row < self.listWidget.count() - 1:
            item = self.listWidget.takeItem(row)
            self.listWidget.insertItem(row + 1, item)
            self.listWidget.setCurrentItem(item)


    def reject(self):
        self.accept()


    def accept(self):
        self.stringlist = QStringList()
        for row in range(self.listWidget.count()):
            self.stringlist.append(self.listWidget.item(row).text())
        self.acceptedList.emit(self.stringlist)
        QDialog.accept(self)
Пример #26
0
class ListEdit(QWidget):
    """A widget to edit a list of items (e.g. a list of directories)."""
    
    # emitted when anything changed in the listbox.
    changed = pyqtSignal()
    
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        layout = QGridLayout(self)
        self.setLayout(layout)
        
        self.addButton = QPushButton(icons.get('list-add'), '')
        self.editButton = QPushButton(icons.get('document-edit'), '')
        self.removeButton = QPushButton(icons.get('list-remove'), '')
        self.listBox = QListWidget()
        
        layout.setContentsMargins(1, 1, 1, 1)
        layout.setSpacing(0)
        layout.addWidget(self.listBox, 0, 0, 8, 1)
        layout.addWidget(self.addButton, 0, 1)
        layout.addWidget(self.editButton, 1, 1)
        layout.addWidget(self.removeButton, 2, 1)
        
        @self.addButton.clicked.connect
        def addClicked():
            item = self.createItem()
            if self.openEditor(item):
                self.addItem(item)
                
        @self.editButton.clicked.connect
        def editClicked():
            item = self.listBox.currentItem()
            item and self.editItem(item)
        
        @self.removeButton.clicked.connect
        def removeClicked():
            item = self.listBox.currentItem()
            if item:
                self.removeItem(item)
        
        @self.listBox.itemDoubleClicked.connect
        def itemDoubleClicked(item):
            item and self.editItem(item)
            
        self.listBox.model().layoutChanged.connect(self.changed)
    
        def updateSelection():
            selected = bool(self.listBox.currentItem())
            self.editButton.setEnabled(selected)
            self.removeButton.setEnabled(selected)
        
        self.changed.connect(updateSelection)
        self.listBox.itemSelectionChanged.connect(updateSelection)
        updateSelection()
        app.translateUI(self)
    
    def translateUI(self):
        self.addButton.setText(_("&Add..."))
        self.editButton.setText(_("&Edit..."))
        self.removeButton.setText(_("&Remove"))
    
    def createItem(self):
        return QListWidgetItem()
        
    def addItem(self, item):
        self.listBox.addItem(item)
        self.itemChanged(item)
        self.changed.emit()
        
    def removeItem(self, item):
        self.listBox.takeItem(self.listBox.row(item))
        self.changed.emit()
        
    def editItem(self, item):
        if self.openEditor(item):
            self.itemChanged(item)
            self.changed.emit()
            
    def setCurrentItem(self, item):
        self.listBox.setCurrentItem(item)
        
    def setCurrentRow(self, row):
        self.listBox.setCurrentRow(row)
        
    def openEditor(self, item):
        """Opens an editor (dialog) for the item.
        
        Returns True if the dialog was accepted and the item edited.
        Returns False if the dialog was cancelled (the item must be left
        unedited).
        """
        pass
    
    def itemChanged(self, item):
        """Called after an item has been added or edited.
        
        Re-implement to do something at this moment if needed, e.g. alter the
        text or display of other items.
        """
        pass
    
    def setValue(self, strings):
        """Sets the listbox to a list of strings."""
        self.listBox.clear()
        self.listBox.addItems(strings)
        self.changed.emit()
        
    def value(self):
        """Returns the list of paths in the listbox."""
        return [self.listBox.item(i).text()
            for i in range(self.listBox.count())]
    
    def setItems(self, items):
        """Sets the listbox to a list of items."""
        self.listBox.clear()
        for item in items:
            self.listBox.addItem(item)
            self.itemChanged(item)
        self.changed.emit()
    
    def items(self):
        """Returns the list of items in the listbox."""
        return [self.listBox.item(i)
            for i in range(self.listBox.count())]
        
    def clear(self):
        """Clears the listbox."""
        self.listBox.clear()
        self.changed.emit()
Пример #27
0
class RunsDialog(QtHelper.EnhancedQDialog):
    """
    Runs several dialog
    """
    RefreshRepository = pyqtSignal(str)
    def __init__(self, dialogName, parent = None, iRepo=None, lRepo=None, rRepo=None):
        """
        Constructor
        """
        QtHelper.EnhancedQDialog.__init__(self, parent)

        self.name = self.tr("Prepare a group of runs")
        self.projectReady = False
        self.iRepo = iRepo
        self.lRepo = lRepo
        self.rRepo = rRepo

        self.createDialog()
        self.createConnections()

    def createDialog(self):
        """
        Create qt dialog
        """
        self.setWindowTitle( self.name )

        mainLayout = QHBoxLayout()
        layoutTests = QHBoxLayout()
        layoutRepoTest = QVBoxLayout()

        self.prjCombo = QComboBox(self)
        self.prjCombo.setEnabled(False)

        self.repoTests = QTreeWidget(self)
        self.repoTests.setFrameShape(QFrame.NoFrame)
        if USE_PYQT5:
            self.repoTests.header().setSectionResizeMode(QHeaderView.Stretch)
        else:
            self.repoTests.header().setResizeMode(QHeaderView.Stretch)
        self.repoTests.setHeaderHidden(True)
        self.repoTests.setContextMenuPolicy(Qt.CustomContextMenu)
        self.repoTests.setIndentation(10)

        layoutRepoTest.addWidget(self.prjCombo)
        layoutRepoTest.addWidget(self.repoTests)

        self.testsList = QListWidget(self)

        layoutTests.addLayout( layoutRepoTest )
        layoutTests.addWidget( self.testsList )
        mainLayout.addLayout( layoutTests )

        buttonLayout = QVBoxLayout()

        self.okButton = QPushButton(self.tr("Execute All"), self)
        self.okButton.setEnabled(False)
        self.cancelButton = QPushButton(self.tr("Cancel"), self)
        self.upButton = QPushButton(self.tr("UP"), self)
        self.upButton.setEnabled(False)
        self.downButton = QPushButton(self.tr("DOWN"), self)
        self.downButton.setEnabled(False)
        self.clearButton = QPushButton(self.tr("Remove All"), self)
        self.delButton = QPushButton(self.tr("Remove"), self)
        self.delButton.setEnabled(False)

        self.runSimultaneous = QCheckBox(self.tr("Simultaneous Run"))
        
        self.schedImmed = QRadioButton(self.tr("Run Immediately"))
        self.schedImmed.setChecked(True)
        self.schedAt = QRadioButton(self.tr("Run At:"))
        self.schedAtDateTimeEdit = QDateTimeEdit(QDateTime.currentDateTime())
        self.schedAtDateTimeEdit.setEnabled(False)

        buttonLayout.addWidget(self.okButton)
        buttonLayout.addWidget(self.runSimultaneous)
        buttonLayout.addWidget(self.schedImmed)
        buttonLayout.addWidget(self.schedAt)
        buttonLayout.addWidget(self.schedAtDateTimeEdit)

        
        buttonLayout.addWidget( self.upButton )
        buttonLayout.addWidget( self.downButton )
        buttonLayout.addWidget( self.delButton )
        buttonLayout.addWidget( self.clearButton )

        buttonLayout.addWidget(self.cancelButton)

        mainLayout.addLayout(buttonLayout)

        self.setMinimumHeight(400)
        self.setMinimumWidth(750)
        self.setLayout(mainLayout)

    def initProjects(self, projects=[], defaultProject=1):
        """
        Initialize projects
        """
        # init date and time
        self.schedAtDateTimeEdit.setDateTime(QDateTime.currentDateTime()) 

        self.projectReady = False

        self.repoTests.clear()
        self.prjCombo.clear()
        self.testsList.clear()

        self.prjCombo.setEnabled(True)
        
        # insert data
        pname = ''
        for p in projects:
            self.prjCombo.addItem ( p['name']  )
            if defaultProject == p['project_id']:
                pname = p['name']
        
        for i in xrange(self.prjCombo.count()):
            item_text = self.prjCombo.itemText(i)
            if str(pname) == str(item_text):
                self.prjCombo.setCurrentIndex(i)

        self.projectReady = True
        self.RefreshRepository.emit(pname)

    def initializeTests(self, listing):
        """
        Initialize tests
        """
        self.repoTests.clear()
        self.testRoot = self.rRepo.Item(repo = self.iRepo.remote(), 
                                        parent = self.repoTests, txt = "Root", 
                                        type = QTreeWidgetItem.UserType+10, 
                                        isRoot = True )
        self.testRoot.setSelected(True)
        self.createRepository(listing=listing, parent=self.testRoot,fileincluded=True)
        self.repoTests.sortItems(0, Qt.AscendingOrder)

        self.hideItems(hideTsx=False, hideTpx=False, hideTcx=True, hideTdx=True, hideTxt=True, hidePy=True,
                                hideTux=False, hidePng=True, hideTgx=False, hideTax=False)

    def createRepository(self, listing, parent, fileincluded=True):
        """
        Create repository

        @param listing: 
        @type listing: list

        @param parent: 
        @type parent:

        @param fileincluded: 
        @type fileincluded: boolean
        """
        try:
            for dct in  listing:
                if dct["type"] == "folder":
                    item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, 
                                           txt = dct["name"], propertiesFile=dct )
                    self.createRepository(  dct["content"] , item, fileincluded )
                else:
                    if fileincluded:
                        if dct["type"] == "file":
                            pname = self.iRepo.remote().getProjectName(dct["project"])
                            # {'modification': 1342259500, 'type': 'file', 'name': '__init__.py', 'size': '562 }
                            item = self.rRepo.Item(repo = self.iRepo.remote(), parent = parent, txt = dct["name"] ,
                                                   propertiesFile=dct, type = QTreeWidgetItem.UserType+0, 
                                                   projectId=dct["project"], projectName=pname )

        except Exception as e:
            self.error( "unable to create tree for runs: %s" % e )

    def onProjectChanged(self, projectItem):
        """
        Called when the project changed on the combo box
        """
        if self.projectReady:
            item_text = self.prjCombo.itemText(projectItem)
            self.RefreshRepository.emit(item_text)

    def createConnections (self):
        """
        create qt connections
         * ok
         * cancel
        """
        self.prjCombo.currentIndexChanged.connect(self.onProjectChanged)
        self.okButton.clicked.connect( self.acceptClicked )
        self.cancelButton.clicked.connect( self.reject )
        self.upButton.clicked.connect(self.upTest)
        self.downButton.clicked.connect(self.downTest)
        self.clearButton.clicked.connect(self.clearList)
        self.delButton.clicked.connect(self.delTest)

        self.testsList.itemClicked.connect(self.onItemSelected)
        self.testsList.itemSelectionChanged.connect(self.onItemSelectionChanged)

        self.schedAt.toggled.connect(self.onSchedAtActivated)

        self.repoTests.itemDoubleClicked.connect( self.onTestDoucleClicked )

    def onSchedAtActivated(self, toggled):
        """
        On sched at button activated
        """
        if toggled:
            self.schedAtDateTimeEdit.setEnabled(True)
        else:
            self.schedAtDateTimeEdit.setEnabled(False)

    def onItemSelectionChanged(self):
        """
        Called on item selection changed
        """
        self.onItemSelected(itm=None)

    def onItemSelected(self, itm):
        """
        Call on item selected
        """
        selectedItems = self.testsList.selectedItems()
        if len(selectedItems):
            self.delButton.setEnabled(True)
            self.upButton.setEnabled(True)
            self.downButton.setEnabled(True)
        else:
            self.delButton.setEnabled(False)
            self.upButton.setEnabled(False)
            self.downButton.setEnabled(False)

        if not self.testsList.count():
            self.okButton.setEnabled(False)

    def upTest(self):
        """
        Up test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)
        self.testsList.insertItem(currentRow - 1, currentItem)

    def downTest(self):
        """
        Down test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)
        self.testsList.insertItem(currentRow + 1, currentItem)


    def delTest(self):
        """
        Del test
        """
        currentRow = self.testsList.currentRow()
        currentItem = self.testsList.takeItem(currentRow)

    def clearList(self):
        """
        Clear test
        """
        self.testsList.clear()
        self.delButton.setEnabled(False)
        self.upButton.setEnabled(False)
        self.downButton.setEnabled(False)

        self.okButton.setEnabled(False)

    def iterateTree(self, item, hideTsx, hideTpx, hideTcx, hideTdx, hideTxt, 
                          hidePy, hideTux, hidePng, hideTgx, hideTax):
        """
        Iterate tree
        """
        child_count = item.childCount()
        for i in range(child_count):
            subitem = item.child(i)
            subchild_count = subitem.childCount()
            if subchild_count > 0:
                self.iterateTree(item=subitem, hideTsx=hideTsx, 
                                 hideTpx=hideTpx, hideTcx=hideTcx, 
                                 hideTdx=hideTdx, hideTxt=hideTxt,
                                 hidePy=hidePy, hideTux=hideTux, 
                                 hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax)
            else:
                if hideTux and subitem.getExtension() == self.rRepo.EXTENSION_TUX:
                    subitem.setHidden (True)
                elif hideTpx and subitem.getExtension() == self.rRepo.EXTENSION_TPX:
                    subitem.setHidden (True)
                elif hideTgx and subitem.getExtension() == self.rRepo.EXTENSION_TGX:
                    subitem.setHidden (True)
                elif hideTcx and subitem.getExtension() == self.rRepo.EXTENSION_TCX:
                    subitem.setHidden (True)
                elif hideTsx and  subitem.getExtension() == self.rRepo.EXTENSION_TSX:
                    subitem.setHidden (True)
                elif hideTdx and  subitem.getExtension() == self.rRepo.EXTENSION_TDX:
                    subitem.setHidden (True)
                elif hideTxt and  subitem.getExtension() == self.rRepo.EXTENSION_TXT:
                    subitem.setHidden (True)
                elif hidePy and  subitem.getExtension() == self.rRepo.EXTENSION_PY:
                    subitem.setHidden (True)
                elif hidePng and  subitem.getExtension() == self.rRepo.EXTENSION_PNG:
                    subitem.setHidden (True)
                elif hideTax and  subitem.getExtension() == self.rRepo.EXTENSION_TAx:
                    subitem.setHidden (True)
                else:
                    subitem.setHidden(False)

    def hideItems(self, hideTsx=False, hideTpx=False, hideTcx=False, hideTdx=False, hideTxt=False, hidePy=False, 
                        hideTux=False, hidePng=False, hideTgx=False, hideTax=False):
        """
        Hide items
        """
        root = self.repoTests.invisibleRootItem()
        self.iterateTree(item=root, hideTsx=hideTsx, hideTpx=hideTpx, hideTcx=hideTcx, 
                         hideTdx=hideTdx, hideTxt=hideTxt, hidePy=hidePy,
                         hideTux=hideTux, hidePng=hidePng, hideTgx=hideTgx, hideTax=hideTax)

    def onTestDoucleClicked(self, testItem):
        """
        On tests double clicked
        """
        if testItem.type() != QTreeWidgetItem.UserType+0:
            return

        self.okButton.setEnabled(True)

        currentProject = self.prjCombo.currentText()

        testName = "%s:%s" % (str(currentProject),testItem.getPath(withFileName = True))
        testItem = QListWidgetItem(testName )

        if testName.endswith(self.rRepo.EXTENSION_TUX):
            testItem.setIcon(QIcon(":/tux.png"))
        if testName.endswith(self.rRepo.EXTENSION_TSX):
            testItem.setIcon(QIcon(":/tsx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TPX):
            testItem.setIcon(QIcon(":/tpx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TGX):
            testItem.setIcon(QIcon(":/tgx.png"))
        if testName.endswith(self.rRepo.EXTENSION_TAX):
            testItem.setIcon(QIcon(":/tax.png"))
            
        self.testsList.addItem( testItem )

    def acceptClicked (self):
        """
        Called on accept button
        """
        self.accept()
    
    def getTests(self):
        """
        Returns all tests in the list
        """
        tests = []
        for i in xrange(self.testsList.count()):
            testItem = self.testsList.item(i)
            tests.append( str(testItem.text()) )

        runSimultaneous = False
        if self.runSimultaneous.isChecked(): runSimultaneous = True
        
        if self.schedImmed.isChecked():
            runAt = (0,0,0,0,0,0)
            return (tests, False, runAt, runSimultaneous)
        else:
            pydt = self.schedAtDateTimeEdit.dateTime().toPyDateTime()
            runAt = (pydt.year, pydt.month, pydt.day, pydt.hour, pydt.minute, pydt.second)
            return (tests, True, runAt, runSimultaneous)
Пример #28
0
class RRepositoryBrowser(QDialog):

    def __init__(self, pipe, parent=None):
        QDialog.__init__(self, parent)
        mirror = robjects.r.getOption('repos')
        contrib_url = robjects.r.get('contrib.url', mode='function')
        available_packages = robjects.r.get('available.packages', mode='function')
        self.setWindowTitle("manageR - Install R Packages")
        self.setWindowIcon(QIcon(":icon"))
        p = available_packages()
        self.pipe = pipe
        self.names = QStringList(p.rownames)
        self.parent = parent
        self.packageList = QListWidget(self)
        self.packageList.setAlternatingRowColors(True)
        self.packageList.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self.packageList.setSortingEnabled(True)
        self.packageList.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.packageList.setToolTip("Select packages to install")
        self.packageList.setWhatsThis("List of packages available on CRAN")
        self.packageList.insertItems(0, self.names)
        self.dependCheckbox = QCheckBox(self)
        self.dependCheckbox.setText("Install all dependencies")
        self.dependCheckbox.setChecked(True)
        self.closeCheckbox = QCheckBox(self)
        self.closeCheckbox.setText("Close dialog on completion")
        self.closeCheckbox.setChecked(False)
        filterEdit = QLineEdit(self)
        filterLabel = QLabel("Filter packages", self)
        self.outputEdit = QTextEdit(self)
        self.outputEdit.setReadOnly(True)
        self.outputEdit.setVisible(False)
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Apply|QDialogButtonBox.Close)
        self.buttonBox.addButton("Details >>", QDialogButtonBox.ActionRole)
        vbox = QVBoxLayout(self)
        hbox = QHBoxLayout()
        hbox.addWidget(filterLabel)
        hbox.addWidget(filterEdit)
        vbox.addLayout(hbox)
        vbox.addWidget(self.dependCheckbox)
        vbox.addWidget(self.packageList)
        vbox.addWidget(self.closeCheckbox)
        vbox.addWidget(self.outputEdit)
        vbox.addWidget(self.buttonBox)
        self.started = False
        self.setMinimumSize(80,50)

        self.connect(filterEdit, SIGNAL("textChanged(QString)"), self.filterPackages)
        #self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.connect(self.buttonBox, SIGNAL("clicked(QAbstractButton*)"), self.buttonClicked)

    def buttonClicked(self, button):
        if button.text() == "Details >>":
            self.showDetails()
            button.setText("Details <<")
        elif button.text() == "Details <<":
            self.hideDetails()
            button.setText("Details >>")
        if not self.started:
            if self.buttonBox.standardButton(button) == QDialogButtonBox.Apply:
                self.installPackages()
            else:
                self.reject()

    def showDetails(self):
        self.outputEdit.setVisible(True)

    def hideDetails(self):
        self.outputEdit.setVisible(False)

    def filterPackages(self, text):
        self.packageList.clear()
        self.packageList.insertItems(0, self.names.filter(QRegExp(r"^%s" % text)))
        firstItem = self.packageList.item(0)
        if firstItem.text().startsWith(text):
            self.packageList.setCurrentItem(firstItem)
#        else:
#            self.packageList.clearSelection()

    def currentPackages(self):
        return [unicode(item.text()) for item in self.packageList.selectedItems()]

    def installPackages(self):
        pkgs = self.currentPackages()
        count = len(pkgs)
        if count < 1:
            QMessageBox.warning(self, "manageR - Warning",
            "Please choose at least one valid package")
            return False
        pkgs = QStringList(pkgs).join("','")
        checked = self.dependCheckbox.isChecked()
        if checked: depends = "TRUE"
        else: depends = "FALSE"
        self.pipe.send("install.packages(c('%s'), dependencies=%s, repos=%s)" 
            % (pkgs, depends, robjects.r.getOption("repos")))
        self.started = True
        self.startTimer(30)
        return True

    def timerEvent(self, e):
        if self.started:
            try:
                output = self.pipe.recv()
                if output is None:
                    self.started=False
                    self.killTimer(e.timerId())
                else:
                    self.printOutput(output)
            except EOFError:
                pass
        QApplication.processEvents()

    def printOutput(self, output):
        self.outputEdit.insertPlainText(output)
        self.outputEdit.ensureCursorVisible()
Пример #29
0
class EvtsFilesWidget(QSplitter):
    def __init__(self, manager, root="/"):
        """
     \returns a QSplitter() containing a QLIstWidget() listing all evt files,
     an EVtTableWIdget() and an EvtControlPannel
     """
        QSplitter.__init__(self, Qt.Horizontal)
        self.manager = manager

        self.evtFileListWidget = QListWidget()
        self.evtFileListWidget.itemClicked.connect(self.switchEventTable)
        fileLabel = QLabel('Windows events')

        w = QWidget()
        self.stackedWidget = QStackedWidget()
        vboxLayout = QVBoxLayout(w)
        vboxLayout.addWidget(fileLabel)
        vboxLayout.addWidget(self.evtFileListWidget)
        vboxLayout.setSpacing(2)
        vboxLayout.setContentsMargins(2, 2, 2, 2)

        for evt in self.manager.evts:
            try:
                events = self.manager.evts[evt]
                if events and len(events):
                    fileItem = self.getFileItems(evt, root)
                    if fileItem:
                        self.evtFileListWidget.addItem(fileItem)
                        currentTable = EvtWidget(None, fileItem.text(), events,
                                                 evt)
                        self.stackedWidget.addWidget(currentTable)
                        fileItem.table(currentTable)
            except Exception as e:
                pass

        self.addWidget(w)
        self.addWidget(self.stackedWidget)
        self.currentItem = self.evtFileListWidget.item(0)
        if self.currentItem:
            self.switchEventTable(self.currentItem)
        self.setStretchFactor(1, 2)

    def switchEventTable(self, fileItem):
        table = fileItem.table()
        self.currentItem = fileItem
        if table:
            self.stackedWidget.setCurrentWidget(table)

    def getFileItems(self, evt, root):
        node = VFS.Get().getNodeById(evt)
        if node is None:
            return None
        if node.absolute()[:len(root)] != root:
            return None
        fileItem = FileItem(QIcon(':/toggle_log'), node.name(), node)
        return fileItem

    def report(self):
        reportManager = ReportManager()
        for itemID in range(self.evtFileListWidget.count()):
            fileItem = self.evtFileListWidget.item(itemID)
            fileItem.table().report()
Пример #30
0
class NewSessionPagePermutations(QWizardPage):
    def __init__(self):
        super(NewSessionPagePermutations, self).__init__()
        self.setTitle(_('Configuration of permutations'))
        self.setSubTitle(_('Select the position of each question'
                           ' and its choices in every model of the exam.'))
        layout = QGridLayout()
        self.question_list = QListWidget()
        self.permutation_grid = QGridLayout()
        self.alternatives_rows = {}
        layout.addWidget(QLabel(_('Questions of model A')), 0, 0, 1, 1)
        layout.addWidget(self.question_list, 1, 0, 1, 1)
        layout.addWidget(QLabel(_('Model equivalence')), 0, 1, 1, 5)
        self.permutation_grid.setVerticalSpacing(20)
        layout.addLayout(self.permutation_grid, 1, 1, 1, 5)
        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 5)
        self.setLayout(layout)

    def initializePage(self):
        paramNAlts = int(self.field("paramNAlts").toString())
        paramNPerm = int(self.field("paramNPerm").toString())
        self.question_list.clear()
        # Creation of the list section
        paramNCols_array = self.field("paramNCols").toString().split(',')
        total_questions = 1 + (int(paramNCols_array[0]) \
                               if len(paramNCols_array) == 1 \
                               else reduce(lambda x, y: int(x) + int(y),
                                           paramNCols_array))
        for i in range(1,total_questions):
            questions_list = QListWidgetItem(_('Question ') + str(i))
            questions_list.setData(Qt.UserRole,
                        widgets.ItemList(optionName=_('Question ') + str(i),
                                         optionNumber=i)) # Custom item list
            self.question_list.addItem(questions_list)
        self.question_list.setCurrentRow(0)
        self.question_list.itemClicked.connect(self._on_item_changed)
        # Creation of the grid section
        add_header = True # Header of the columns (Name of alternatives)
        for j in range(0, paramNPerm):
            self.permutation_grid.addWidget( \
                                QLabel(_('Model ') + chr(97 + j).upper()), j, 1)
            self.alternatives_rows[j] = {}
            for k in range(0, paramNAlts):
                if add_header:
                    if k == 0:
                        self.permutation_grid.addWidget(QLabel(''), 0, 1)
                    self.permutation_grid.addWidget( \
                                        QLabel(chr(97 + k).upper()), 0, k + 2)
                self.alternatives_rows[j][k] = \
                    widgets.InputComboBox(self, c_type='alternative',
                                          form=j, alternative=k)
                self.alternatives_rows[j][k].addItems( \
                            [chr(97+x).upper() for x in range(0,paramNAlts)])
                self.alternatives_rows[j][k].setCurrentIndex(0)
                self.permutation_grid.addWidget(self.alternatives_rows[j][k],
                                                j, k + 2)
            add_header = False
            self.alternatives_rows[j][k + 1] = \
                widgets.InputComboBox(self, c_type='question', form=j,
                                      alternative=self.question_list.\
                                          currentItem().\
                                          data(Qt.UserRole).toPyObject().\
                                               get_question_number())
            self.alternatives_rows[j][k + 1].addItems( \
                                [str(x) for x in range(1,total_questions)])
            self.alternatives_rows[j][k + 1].setCurrentIndex(0)
            self.permutation_grid.addWidget(QLabel(_('Question Number')),
                                            j, k + 3)
            self.permutation_grid.addWidget(self.alternatives_rows[j][k + 1],
                                            j, k + 4)
        button_save = QPushButton(_('Save values'))
        self.permutation_grid.addWidget(button_save, j + 1, 1, 1, k + 4)
        button_save.clicked.connect(self._save_values)

    def _on_item_changed(self, arg=None):
        permutation = arg.data(Qt.UserRole).toPyObject().get_permutation()
        for k, v in self.alternatives_rows.iteritems():
            for sk, sv in v.iteritems():
                if not permutation:
                    sv.setCurrentIndex(0)
                else:
                    sv.setCurrentIndex( \
                        [x for x in permutation \
                         if (x['altr'] == sv.alternative
                             and x['form'] == sv.form
                             and x['c_type'] == sv.c_type)][0]['perm'] - 1)
        return True

    def _save_values(self):
        localItem = self.question_list.currentItem()
        formatted_grid  = self._get_formatted_permutation_grid()
        if self._validate_grid(formatted_grid):
            localItem.setBackgroundColor(QColor(0, 255, 68))
            localItem.data(Qt.UserRole).toPyObject()\
                     .set_permutation(formatted_grid)
            self._reset_permutation_grid()
            QMessageBox.information(self, _('Information status'),
                _('The values for the question have been successfully saved'))
            return True
        else:
            QMessageBox.critical(self, _('Error in grid'),
                _('There is an inconsistence in the options'))
            return False

    def _get_formatted_permutation_grid(self):
        local_alternatives_rows = []
        for k, v in self.alternatives_rows.iteritems():
            for sk, sv in v.iteritems():
                alternative = {
                    'c_type': sv.c_type,
                    'form': sv.form,
                    'altr': sv.alternative,
                    'perm': sv.currentIndex() + 1
                }
                local_alternatives_rows.append(alternative)
        return local_alternatives_rows

    def _validate_grid(self, grid):
        #validate current grid and questions number
        forms = {}
        for row in grid:
            if row['c_type'] == 'alternative':
                if row['form'] not in forms:
                    forms[row['form']] = []
                if row['perm'] in forms[row['form']]:
                    return False
                else:
                    forms[row['form']].append(row['perm'])
            if row['c_type'] == 'question':
                for i in xrange(self.question_list.count()):
                    if i == self.question_list.currentRow():
                        continue
                    perm = self.question_list.item(i).data(Qt.UserRole)\
                               .toPyObject().get_permutation()
                    for perm_row in perm:
                        if (perm_row['c_type'] == 'question'
                            and perm_row['form'] == row['form']
                            and perm_row['perm'] == row['perm']):
                            return False
        return True

    def _reset_permutation_grid(self):
        for k,v in self.alternatives_rows.iteritems():
            for sk, sv in v.iteritems():
                sv.setCurrentIndex(0)

    def _get_values(self):
        formated_permutation = {}
        formated_permutation_m = {}
        for i in xrange(self.question_list.count()):
            permutations = self.question_list.item(i).data(Qt.UserRole)\
                               .toPyObject().get_permutation()
            a = {}
            for p in permutations:
                if p['form'] not in formated_permutation:
                    formated_permutation[p['form']] = []
                if p['form'] not in a:
                    a[p['form']] = []
                if p['c_type'] == 'alternative':
                    a[p['form']].append(p['perm'])
                if p['c_type'] == 'question':
                    formated_permutation[p['form']].append( \
                        "%s{%s}" % (p['perm'], ','.join(str(x) \
                                                       for x in a[p['form']])))
        for k,v in formated_permutation.iteritems():
            formated_permutation_m[chr(97+k).upper()] = '/'.join(v)
        return formated_permutation_m

    def validatePage(self):
        valid = True
        msg = ''
        for i in xrange(self.question_list.count()):
            if not self.question_list.item(i).data(Qt.UserRole)\
                .toPyObject().get_permutation():
                valid = False
                msg = _('You must select all permutations for all questions')
                break
        if not valid:
            QMessageBox.critical(self, _('Error'), msg)
        else:
            current_permutations = self._get_values()
            for k, v in current_permutations.iteritems():
                self.wizard().exam_config.set_permutations(k, v)
        return valid

    def nextId(self):
        return WizardNewSession.PageIdFiles
Пример #31
0
class GitStatus(QDialog):

    def __init__(self, plugin, git, path):
        QDialog.__init__(self)
        self.git = git
        self.plugin = plugin
        self.setWindowTitle('Git status')

        layout = QGridLayout(self)

        branches = self.git.branch(unicode(path))

        self.s_branches = QListWidget()

        if len(branches) > 0:
            self.s_branches.addItems(branches[1:])
            self.actual_branch = QLabel("<h2>{0}</h2>".format(branches[0]))
        else:
            self.actual_branch = QLabel()

        branch = QLabel("<h2>Branches</h2>")
        change_branch = QPushButton("Change to")
        merge_branches = QPushButton("Merge branch")

        H = QHBoxLayout()
        delete_branch = QPushButton("Delete branch")
        add_branch = QPushButton("Add branch")
        H.addWidget(add_branch)
        H.addWidget(delete_branch)

        self.lists = []

        no_staged = QLabel("<h2>No staged</h2>")

        untracked_files = QLabel("Untracked files")
        self.untracked_files = QListWidget()
        self.lists.append(self.untracked_files)

        modified_files = QLabel("Modified files")
        self.modified_files = QListWidget()
        self.lists.append(self.modified_files)

        deleted_files = QLabel("Deleted files")
        self.deleted_files = QListWidget()
        self.lists.append(self.deleted_files)

        staged = QLabel("<h2>Staged</h2>")

        added_files = QLabel("Added files")
        self.added_files = QListWidget()
        self.lists.append(self.added_files)

        s_modified_files = QLabel("Modified files")
        self.s_modified_files = QListWidget()
        self.lists.append(self.s_modified_files)

        s_deleted_files = QLabel("Deleted files")
        self.s_deleted_files = QListWidget()
        self.lists.append(self.s_deleted_files)

        layout.addWidget(self.actual_branch, 0, 0, Qt.AlignHCenter)
        layout.addWidget(change_branch, 1, 0)
        layout.addWidget(merge_branches, 2, 0)
        layout.addWidget(no_staged, 3, 0)
        layout.addWidget(untracked_files, 4, 0)
        layout.addWidget(self.untracked_files, 5, 0)
        layout.addWidget(modified_files, 6, 0)
        layout.addWidget(self.modified_files, 7, 0)
        layout.addWidget(deleted_files, 8, 0)
        layout.addWidget(self.deleted_files, 9, 0)

        layout.addWidget(branch, 0, 1)
        layout.addWidget(self.s_branches, 1, 1)
        layout.addLayout(H, 2, 1)
        layout.addWidget(staged, 3, 1)
        layout.addWidget(added_files, 4, 1)
        layout.addWidget(self.added_files, 5, 1)
        layout.addWidget(s_modified_files, 6, 1)
        layout.addWidget(self.s_modified_files, 7, 1)
        layout.addWidget(s_deleted_files, 8, 1)
        layout.addWidget(self.s_deleted_files, 9, 1)

        self.fill(self.git.no_staged["?"], self.untracked_files)
        self.fill(self.git.no_staged["M"], self.modified_files)
        self.fill(self.git.no_staged["D"], self.deleted_files)

        self.fill(self.git.staged["A"], self.added_files)
        self.fill(self.git.staged["M"], self.s_modified_files)
        self.fill(self.git.staged["D"], self.s_deleted_files)

        self.staged_b = QPushButton('Stage files', self)
        self.unstage_b = QPushButton("Unstage files", self)
        self.commit_b = QPushButton('Commit files', self)
        self.uncommit_b = QPushButton("Uncommit files", self)

        layout.addWidget(self.staged_b, 10, 0)
        layout.addWidget(self.unstage_b, 11, 0)
        layout.addWidget(self.commit_b, 10, 1)
        layout.addWidget(self.uncommit_b, 11, 1)

        self.setLayout(layout)

        self.connect(self.staged_b, SIGNAL('clicked()'), self.add)
        self.connect(self.unstage_b, SIGNAL('clicked()'), self.unstage)
        self.connect(self.commit_b, SIGNAL('clicked()'), self.commit)
        self.connect(self.uncommit_b, SIGNAL('clicked()'), self.uncommit)
        self.connect(change_branch, SIGNAL("clicked()"), self.change_branch)
        self.connect(add_branch, SIGNAL("clicked()"), self.add_branch)
        self.connect(delete_branch, SIGNAL("clicked()"), self.delete_branch)
        self.connect(merge_branches, SIGNAL("clicked()"), self.merge_branches)

    def fill(self, a_list, widget_list):
        for x in a_list:

            item = QListWidgetItem()
            widget_list.addItem(item)
            check_box = QCheckBox(x)
            widget_list.setItemWidget(item, check_box)

    def add(self):
        path = self.plugin.editor.get_project_owner()
        for pos in reversed(xrange(self.untracked_files.count())):

            item = self.untracked_files.item(pos)
            widget = self.untracked_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.add(path, text)
                self.untracked_files.removeItemWidget(item)
                self.untracked_files.takeItem(pos)
                item = QListWidgetItem()
                self.added_files.addItem(item)
                check_box = QCheckBox(text)
                self.added_files.setItemWidget(item, check_box)

        for pos in reversed(xrange(self.modified_files.count())):

            item = self.modified_files.item(pos)
            widget = self.modified_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.add(path, widget.text())
                self.modified_files.removeItemWidget(item)
                self.modified_files.takeItem(pos)
                item = QListWidgetItem()
                self.s_modified_files.addItem(item)
                check_box = QCheckBox(text)
                self.s_modified_files.setItemWidget(item, check_box)

        for pos in reversed(xrange(self.deleted_files.count())):

            item = self.deleted_files.item(pos)
            widget = self.deleted_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.add(path, widget.text())
                self.deleted_files.removeItemWidget(item)
                self.deleted_files.takeItem(pos)
                item = QListWidgetItem()
                self.s_deleted_files.addItem(item)
                check_box = QCheckBox(text)
                self.s_deleted_files.setItemWidget(item, check_box)

    def unstage(self):

        path = self.plugin.editor.get_project_owner()
        for pos in reversed(xrange(self.untracked_files.count())):

            item = self.untracked_files.item(pos)
            widget = self.untracked_files.itemWidget(item)

            if widget.isChecked():
                self.git.unstage(path, widget.text())
                self.untracked_files.removeItemWidget(item)
                self.untracked_files.takeItem(pos)

        for pos in reversed(xrange(self.modified_files.count())):

            item = self.modified_files.item(pos)
            widget = self.modified_files.itemWidget(item)

            if widget.isChecked():
                self.git.unstage(path, widget.text())
                self.modified_files.removeItemWidget(item)
                self.modified_files.takeItem(pos)

        for pos in reversed(xrange(self.deleted_files.count())):

            item = self.deleted_files.item(pos)
            widget = self.deleted_files.itemWidget(item)

            if widget.isChecked():
                self.git.unstage(path, widget.text())
                self.deleted_files.removeItemWidget(item)
                self.deleted_files.takeItem(pos)

    def commit(self):

        msg = QInputDialog.getText(self, "Commit message", "Commit Message:")

        if msg[1] == False:
            return(0)

        path = self.plugin.editor.get_project_owner()
        for pos in reversed(xrange(self.added_files.count())):

            item = self.added_files.item(pos)
            widget = self.added_files.itemWidget(item)

            if widget.isChecked():
                self.git.commit(path, str(widget.text()), msg[0])
                self.added_files.removeItemWidget(item)
                self.added_files.takeItem(pos)

        for pos in reversed(xrange(self.s_modified_files.count())):

            item = self.s_modified_files.item(pos)
            widget = self.s_modified_files.itemWidget(item)

            if widget.isChecked():
                self.git.commit(path, widget.text(), msg[0])
                self.s_modified_files.removeItemWidget(item)
                self.s_modified_files.takeItem(pos)

        for pos in reversed(xrange(self.s_deleted_files.count())):

            item = self.s_deleted_files.item(pos)
            widget = self.s_deleted_files.itemWidget(item)

            if widget.isChecked():
                self.git.commit(path, widget.text(), msg[0])
                self.s_deleted_files.takeItem(pos)
                self.s_deleted_files.removeItemWidget(item)

    def uncommit(self):
        path = self.plugin.editor.get_project_owner()
        for pos in reversed(xrange(self.added_files.count())):

            item = self.added_files.item(pos)
            widget = self.added_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.uncommit(path, str(widget.text()))
                self.added_files.removeItemWidget(item)
                self.added_files.takeItem(pos)
                item = QListWidgetItem()
                self.untracked_files.addItem(item)
                check_box = QCheckBox(text)
                self.untracked_files.setItemWidget(item, check_box)

        for pos in reversed(xrange(self.s_modified_files.count())):

            item = self.s_modified_files.item(pos)
            widget = self.s_modified_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.uncommit(path, widget.text())
                self.s_modified_files.removeItemWidget(item)
                self.s_modified_files.takeItem(pos)
                item = QListWidgetItem()
                self.modified_files.addItem(item)
                check_box = QCheckBox(text)
                self.modified_files.setItemWidget(item, check_box)

        for pos in reversed(xrange(self.s_deleted_files.count())):

            item = self.s_deleted_files.item(pos)
            widget = self.s_deleted_files.itemWidget(item)
            text = widget.text()

            if widget.isChecked():
                self.git.uncommit(path, widget.text())
                self.s_deleted_files.removeItemWidget(item)
                self.s_deleted_files.takeItem(pos)
                item = QListWidgetItem()
                self.deleted_files.addItem(item)
                check_box = QCheckBox(text)
                self.deleted_files.setItemWidget(item, check_box)

    def change_branch(self):

        path = self.plugin.editor.get_project_owner()

        item = self.s_branches.currentItem()

        if item and not self.something():
            text = item.text()
            self.git.change_branch(path, text)
            self.s_branches.clear()
            self.s_branches.addItems(self.git.branch(unicode(path))[1:])
            self.actual_branch.setText("<h2>{0}<h2>".format(text))
        if self.something():
            v = QMessageBox()
            v.setText("Error: you have unsaved changes")
            v.setIcon(v.Warning)
            v.exec_()

    def add_branch(self):

        path = self.plugin.editor.get_project_owner()

        msg = QInputDialog.getText(self, "New branch", "Branch Name:")

        if msg[1] == False:
            return(0)

        self.git.add_branch(path, msg[0])
        self.s_branches.clear()
        self.s_branches.addItems(self.git.branch(unicode(path))[1:])

    def delete_branch(self):
        path = self.plugin.editor.get_project_owner()
        item = self.s_branches.currentItem()
        if item:
            text = str(item.text())
            call = self.git.delete_branch(path, text)

            if not call:
                self.s_branches.clear()
                self.s_branches.addItems(self.git.branch(unicode(path))[1:])

            else:
                m = QMessageBox()
                m.setText("<h2>" + call + "</h2>")
                m.setInformativeText("Force deletion?")
                m.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
                m.setDefaultButton(QMessageBox.Cancel)
                c = m.exec_()
                if c == QMessageBox.Ok:

                    self.git.force_delete_branch(path, text)
                    self.s_branches.clear()

                    self.s_branches.addItems(self.git.branch(unicode(path))[1:])

    def merge_branches(self):
        path = self.plugin.editor.get_project_owner()
        item = self.s_branches.currentItem()
        if item:
            text = str(item.text())
            call = self.git.merge_branches(path, text)
            if call:
                m = QMessageBox()
                m.setText(call)
                m.setInformativeText("Unknown")
                m.setIcon(m.Critical)
                m.exec_()

    def something(self):
        for x in self.lists:
            if x.count() > 0:
                return True
        return False
Пример #32
0
class urlgroup(QGroupBox):
    def __init__(self, parent=None):
        super(urlgroup, self).__init__(parent)
        self.setGeometry(10,30,500,80)
        self.setObjectName('urlgroup')
        self.urlbar = QLineEdit()
        self.urlbar.setObjectName('urlbar')
        self.urlbar.setText('Collez votre URL içi')
        self.urlbar.setStyleSheet('font-weight:lighter;color:gray;')
        self.urlbar.show()
        self.parsebutton = QPushButton('Go !!')
        self.parsebutton.setObjectName('parsebutton')
        self.parsebutton.show()
        layout = QBoxLayout(QBoxLayout.LeftToRight, self)
        layout.addWidget(self.urlbar)
        layout.addWidget(self.parsebutton)
        self.show()
        self.group2 = QGroupBox(parent)
        self.group2.setObjectName('core')
        self.group2.setGeometry(10,120,500,280)
        self.group2.show()
        self.group3 = QGroupBox(self.group2)
        self.group3.setObjectName('albuminfos')
        self.group3.setGeometry(10,15,200,245)
        self.group3.show()
        self.itemlist = QListWidget(self.group2)
        self.itemlist.setGeometry(250,15,230,245)
        self.itemlist.show()
        self.dlgroup = QGroupBox(parent)
        self.dlgroup.setObjectName('dlgroup')
        self.dlgroup.setGeometry(10,420,500,100)
        self.dlgroup.show()
        self.dlgroup.dlbutton = QPushButton('Download', self.dlgroup)
        self.dlgroup.dlbutton.setObjectName('dlbutton')
        self.dlgroup.dlbutton.move(10,20)
        self.dlgroup.dlbutton.show()
        self.dlgroup.progressbar = QProgressBar(self.dlgroup)
        self.dlgroup.progressbar.setObjectName('progressbar')
        self.dlgroup.progressbar.setGeometry(100,21,380,21)
        self.dlgroup.progressbar.show()
        self.dlgroup.dlinfos = QLabel(self.dlgroup)
        self.dlgroup.dlinfos.setGeometry(100,70,200,21)
        self.dlgroup.dlinfos.show()
        self.dlgroup.dledfile = QLabel(self.dlgroup)
        self.dlgroup.dledfile.setGeometry(300,70,200,21)
        self.dlgroup.dledfile.show()
        self.dlgroup.dlto = QLineEdit('C:\\', self.dlgroup)
        self.dlgroup.dlto.setGeometry(100,50,350,21)
        self.dlgroup.dlto.show()
        self.dlgroup.dlto.changebt = QToolButton(self.dlgroup)
        self.dlgroup.dlto.changebt.setObjectName('dltobt')
        self.dlgroup.dlto.changebt.setGeometry(10,50,75,21)
        self.dlgroup.dlto.changebt.setText('To')
        self.dlgroup.dlto.changebt.show()
        self.dlgroup.dlto.openf = QPushButton('Open', self.dlgroup)
        self.dlgroup.dlto.openf.setGeometry(455,50,35,21)
        self.dlgroup.dlto.openf.setObjectName('openfolder')
        self.dlgroup.dlto.openf.show()  
        self.album = QLabel(self.group3)
        self.artist = QLabel(self.group3)
        self.year = QLabel(self.group3)
        self.tracks = QLabel(self.group3)
        self.coverart = QLabel(self.group3)
        self.urlbar.setFocus(True)
        self.connect(self.parsebutton, SIGNAL('clicked()'), self.parseclicked )
        self.connect(self.dlgroup.dlbutton, SIGNAL('clicked()'), self.launchdl)
        self.connect(self.dlgroup.dlto.changebt, SIGNAL('clicked()'), self.changedir)
        self.connect(self.dlgroup.dlto.openf, SIGNAL('clicked()'), self.openfolder)
        
    def parseclicked(self):
        self.itemlist.clear()
        url = str(self.urlbar.text())
        self.infos = getsonglist(url)
        if (self.infos == 'connexion impossible') or (self.infos == 'unsupported'):
            self.error = QMessageBox()
            if self.infos == 'connexion impossible':
                self.error.setText('Connexion Impossible !')
            elif self.infos == 'unsupported':
                self.error.setText('Site Unsupported !!')
            self.error.setWindowTitle('Erreur!')
            self.error.setIcon(QMessageBox.Warning)
            self.icon = QIcon('images/mainwindowicon.png')
            self.error.setWindowIcon(self.icon)
            self.error.exec_()
        else:
            self.artist.setText('Artiste : ' + self.infos['artist'])
            self.artist.move(40,175)
            self.artist.show()
            self.album.setText('Album : ' + self.infos['albumname'])
            self.album.move(40,190)
            self.album.show()
            try:
                self.year.setText('Annee : ' + self.infos['year'])
                
            except KeyError:
                self.year.setText('Annee : ' + 'N/A')
            self.year.move(40,205)
            self.year.show()
            self.tracks.setText('Tracks : ' + str(self.infos['tracks']))
            self.tracks.move(40,220)
            self.tracks.show()
            coverartpix = QPixmap(self.infos['coverart'])
            coverartpix = coverartpix.scaled(178,135,)
            self.coverart.setPixmap(coverartpix) 
            self.coverart.move(10,10)
            self.coverart.show()
            self.list2 = []
            for item in self.infos['titles']:
                item = tracklistitems(item)
                self.list2.append(item)
            for item in self.list2:
                self.itemlist.addItem(item)
                
            
            
            

    def launchdl(self):
        if self.dlgroup.dlbutton.text() == 'Download':
            try:
                self.itemlist.item(self.currentitem).setText(self.text)
            except:
                pass
            self.dlgroup.dlbutton.setText('Stop')
            rmtree('tmpimg', True)
            i= 0
            dllist = []
            for item in self.list2:
                if item.eligible() =='Checked':
                    dllist.append(i)
                i= i+1
            self.stritemlist = []
            for i in range(0,self.infos['tracks']):
                #print i
                #print self.itemlist.item(i).text()
                #TODO: hamida album breaks, recheck regexes
                self.stritemlist.append(str(self.itemlist.item(i).text()))
            dlto =  self.dlgroup.dlto.text()
            self.thread = dlThread(dllist, self.infos, dlto, self.stritemlist) 
            self.connect(self.thread, SIGNAL('progress(PyQt_PyObject)'), self.updateProgress)
            self.connect(self.thread, SIGNAL('dledfile(PyQt_PyObject)'), self.updateDlednow)
            self.thread.start()
        else:
            self.dlgroup.dlbutton.setText('Download')
            self.thread.terminate()
      
    def updateProgress(self, progress):
        self.dlgroup.progressbar.setValue(progress['bar'])
        self.dlgroup.dlinfos.setText(progress['info'])
        self.text = self.stritemlist[progress['item']]
        self.currentitem = progress['item']
        self.percent = str(progress['bar']) + ' % - '
        self.percent = QString(self.percent)
        self.dlingicon = QIcon('images/dling.png')
        self.doneicon = QIcon('images/done.png')
        self.itemlist.item(progress['item']).setIcon(self.dlingicon)
        self.itemlist.item(progress['item']).setText(self.percent + self.text)
        if progress['bar'] >= 98:
            self.itemlist.item(progress['item']).setIcon(self.doneicon)
            self.itemlist.item(progress['item']).setText(self.text)
            self.itemlist.item(progress['item']).setCheckState(Qt.Unchecked)
            self.itemlist.item(progress['item']).setFlags(Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable)
            
    def updateDlednow(self, dledfile):
        self.dlgroup.dledfile.setText(dledfile)

    
    def changedir(self):
        self.dir = QFileDialog.getExistingDirectory()
        self.dlgroup.dlto.setText(self.dir + '/')
    def openfolder(self):
        startfile(self.dlgroup.dlto.text())
        
    def stopdl(self):
        pass
Пример #33
0
class FiltersDialog(Window):
    def __init__(self, base):
        Window.__init__(self, base, i18n.get('filters'))
        self.setFixedSize(280, 360)

        self.expression = QLineEdit()
        self.expression.returnPressed.connect(self.__new_filter)

        self.new_button = QPushButton(i18n.get('add_filter'))
        self.new_button.setToolTip(i18n.get('create_a_new_filter'))
        self.new_button.clicked.connect(self.__new_filter)

        expression_box = QHBoxLayout()
        expression_box.addWidget(self.expression)
        expression_box.addWidget(self.new_button)

        self.list_ = QListWidget()
        self.list_.clicked.connect(self.__filter_clicked)

        self.delete_button = QPushButton(i18n.get('delete'))
        self.delete_button.setEnabled(False)
        self.delete_button.setToolTip(i18n.get('delete_selected_filter'))
        self.delete_button.clicked.connect(self.__delete_filter)

        self.clear_button = QPushButton(i18n.get('delete_all'))
        self.clear_button.setEnabled(False)
        self.clear_button.setToolTip(i18n.get('delete_all_filters'))
        self.clear_button.clicked.connect(self.__delete_all)

        button_box = QHBoxLayout()
        button_box.addStretch(1)
        button_box.addWidget(self.clear_button)
        button_box.addWidget(self.delete_button)

        layout = QVBoxLayout()
        layout.addLayout(expression_box)
        layout.addWidget(self.list_, 1)
        layout.addLayout(button_box)
        layout.setSpacing(5)
        layout.setContentsMargins(5, 5, 5, 5)
        self.setLayout(layout)
        self.__update()
        self.show()

    def __update(self):
        row = 0
        self.expression.setText('')
        self.list_.clear()
        for expression in self.base.core.list_filters():
            self.list_.addItem(expression)
            row += 1

        self.__enable(True)
        self.delete_button.setEnabled(False)
        if row == 0:
            self.clear_button.setEnabled(False)
        self.expression.setFocus()

    def __filter_clicked(self, point):
        self.delete_button.setEnabled(True)
        self.clear_button.setEnabled(True)

    def __new_filter(self):
        expression = str(self.expression.text())
        self.list_.addItem(expression)
        self.__save_filters()

    def __delete_filter(self):
        self.list_.takeItem(self.list_.currentRow())
        self.__save_filters()

    def __delete_all(self):
        self.__enable(False)
        message = i18n.get('clear_filters_confirm')
        confirmation = self.base.show_confirmation_message(i18n.get('confirm_delete'),
            message)
        if not confirmation:
            self.__enable(True)
            return
        self.list_.clear()
        self.__save_filters()

    def __enable(self, value):
        self.list_.setEnabled(value)
        self.delete_button.setEnabled(value)
        self.clear_button.setEnabled(value)

    def __save_filters(self):
        filters = []
        for i in range(self.list_.count()):
            filters.append(str(self.list_.item(i).text()))
        self.base.save_filters(filters)
        self.__update()
Пример #34
0
class SolverGenerator(QWidget):
    def __init__(self):
        super().__init__()

        self._init_info_base()
        self._init_ui()

    def _init_info_base(self):
        f = open('base')
        lines = [line for line in f.readlines() if line.split()]
        count = int(lines[0])

        self._names = {}
        for line in lines[1:1 + count]:
            line = line.split(' ', 1)
            self._names[line[1].rstrip()] = line[0]

        model = [Formula(info=line1, code=line2) for line1, line2 in
                 zip(lines[1 + count::2], lines[2 + count::2])]
        self._info_base = InfoBase(model)

    def _init_ui(self):
        main = QVBoxLayout(self)

        up_label = QLabel('Входные параметры:')
        up_label.setAlignment(Qt.AlignCenter)
        main.addWidget(up_label)
        up = QHBoxLayout(self)
        self.up_left = QListWidget(self)
        self.up_left.addItems(list(self._names.keys()))
        self.up_left.sortItems()
        up.addWidget(self.up_left)

        up_buttons = QVBoxLayout(self)
        up_to_right = QPushButton('>')
        self.connect(up_to_right, SIGNAL('pressed()'), self._up_to_right)
        up_buttons.addWidget(up_to_right)
        up_to_left = QPushButton('<')
        self.connect(up_to_left, SIGNAL('pressed()'), self._up_to_left)
        up_buttons.addWidget(up_to_left)
        up_buttons.setAlignment(Qt.AlignCenter)
        up.addLayout(up_buttons)

        self.up_right = QListWidget(self)
        up.addWidget(self.up_right)
        self.up_right.sortItems()
        main.addLayout(up)

        down_label = QLabel('Выходные параметры:')
        down_label.setAlignment(Qt.AlignCenter)
        main.addWidget(down_label)

        down = QHBoxLayout(self)
        self.down_left = QListWidget(self)
        self.down_left.addItems(list(self._names.keys()))
        self.down_left.sortItems()
        down.addWidget(self.down_left)

        down_buttons = QVBoxLayout(self)
        down_to_right = QPushButton('>')
        self.connect(down_to_right, SIGNAL('pressed()'), self._down_to_right)
        down_buttons.addWidget(down_to_right)
        down_to_left = QPushButton('<')
        self.connect(down_to_left, SIGNAL('pressed()'), self._down_to_left)
        down_buttons.addWidget(down_to_left)
        down_buttons.setAlignment(Qt.AlignCenter)
        down.addLayout(down_buttons)

        self.down_right = QListWidget(self)
        down.addWidget(self.down_right)
        self.down_right.sortItems()
        main.addLayout(down)

        solve = QPushButton('Решить')
        self.connect(solve, SIGNAL('pressed()'), self._solve)
        main.addWidget(solve)

        self.setLayout(main)
        self.setWindowTitle('SolverGenerator')
        self.resize(600, 600)
        self._center()
        self.show()

    def _solve(self):
        input_definition = [self.up_right.item(i).text() for i in
                            range(self.up_right.count())]
        input_params = [self._names[item] for item in input_definition]
        output_definition = [self.down_right.item(i).text() for i in
                             range(self.down_right.count())]
        output_params = [self._names[item] for item in output_definition]

        algorithm = self._info_base.get_algorithm(input_params, output_params)
        if algorithm:
            self._generate_code(input_definition, input_params,
                                output_definition, output_params, algorithm)
        else:
            QMessageBox().warning(self, 'Решения нет',
                                  'Для выбранных данных решения нет')

    def _up_to_right(self):
        item = self.up_left.takeItem(self.up_left.currentRow())
        self.up_right.addItem(item)
        self.up_right.sortItems()

    def _up_to_left(self):
        item = self.up_right.takeItem(self.up_right.currentRow())
        self.up_left.addItem(item)
        self.up_left.sortItems()

    def _down_to_right(self):
        item = self.down_left.takeItem(self.down_left.currentRow())
        self.down_right.addItem(item)
        self.down_right.sortItems()

    def _down_to_left(self):
        item = self.down_right.takeItem(self.down_right.currentRow())
        self.down_left.addItem(item)
        self.down_left.sortItems()

    def _center(self):
        qr = self.frameGeometry()
        cp = QDesktopWidget().availableGeometry().center()
        qr.moveCenter(cp)
        self.move(qr.topLeft())

    @staticmethod
    def _generate_code(input_definition, input_params, output_definition,
                       output_params, algorithm):
        code = []
        if any('math' in formula.code for formula in algorithm):
            code.append('import math')
        for name, definition in zip(input_params, input_definition):
            code.append(
                    '{0} = float(input("Введите {0} ({1}): "))'.format(name,
                                                                       definition.lower()))

        for formula in algorithm:
            code.append(formula.code)

        for name, definition in zip(output_params, output_definition):
            code.append('print("{0} = %f" % {1})'.format(definition, name))

        code.append('input("Нажмите Enter для завершения.")')
        code.append('')

        code = '\n'.join(code)

        file = open('program.py', 'w')
        file.write(code)
        file.close()

        xterm = sh.Command('xterm')
        xterm('-e', 'python3 program.py')
class GroupSelectParameterWidget(GenericParameterWidget):

    """Widget class for Group Select Parameter."""

    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A GroupSelectParameter object.
        :type parameter: GroupSelectParameter
        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Store spin box
        self.spin_boxes = {}

        # Create elements
        # Label (name)
        self.label = QLabel(self._parameter.name)

        # Layouts
        self.main_layout = QVBoxLayout()
        self.input_layout = QVBoxLayout()

        # _inner_input_layout must be filled with widget in the child class
        self.inner_input_layout = QVBoxLayout()

        self.radio_button_layout = QGridLayout()

        # Create radio button group
        self.input_button_group = QButtonGroup()

        # List widget
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list_widget.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_widget.setDefaultDropAction(Qt.MoveAction)
        self.list_widget.setEnabled(False)
        self.list_widget.setSizePolicy(
            QSizePolicy.Maximum, QSizePolicy.Expanding)

        for i, key in enumerate(self._parameter.options):
            value = self._parameter.options[key]
            radio_button = QRadioButton(value.get('label'))
            self.radio_button_layout.addWidget(radio_button, i, 0)
            if value.get('type') == SINGLE_DYNAMIC:
                double_spin_box = QDoubleSpinBox()
                self.radio_button_layout.addWidget(double_spin_box, i, 1)
                double_spin_box.setValue(value.get('value', 0))
                double_spin_box.setMinimum(
                    value.get('constraint', {}).get('min', 0))
                double_spin_box.setMaximum(value.get(
                    'constraint', {}).get('max', 1))
                double_spin_box.setSingleStep(
                    value.get('constraint', {}).get('step', 0.01))
                step = double_spin_box.singleStep()
                if step > 1:
                    precision = 0
                else:
                    precision = len(str(step).split('.')[1])
                    if precision > 3:
                        precision = 3
                double_spin_box.setDecimals(precision)
                self.spin_boxes[key] = double_spin_box

                # Enable spin box depends on the selected option
                if self._parameter.selected == key:
                    double_spin_box.setEnabled(True)
                else:
                    double_spin_box.setEnabled(False)

            elif value.get('type') == STATIC:
                static_value = value.get('value', 0)
                if static_value is not None:
                    self.radio_button_layout.addWidget(
                        QLabel(str(static_value)), i, 1)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                selected_fields = value.get('value', [])
                if self._parameter.selected == key:
                    self.list_widget.setEnabled(True)
                else:
                    self.list_widget.setEnabled(False)

            self.input_button_group.addButton(radio_button, i)
            if self._parameter.selected == key:
                radio_button.setChecked(True)

        # Help text
        self.help_label = QLabel(self._parameter.help_text)
        self.help_label.setSizePolicy(
            QSizePolicy.Maximum, QSizePolicy.Expanding)
        self.help_label.setWordWrap(True)
        self.help_label.setAlignment(Qt.AlignTop)

        self.inner_input_layout.addLayout(self.radio_button_layout)
        self.inner_input_layout.addWidget(self.list_widget)

        # Put elements into layouts
        self.input_layout.addWidget(self.label)
        self.input_layout.addLayout(self.inner_input_layout)

        self.help_layout = QVBoxLayout()
        self.help_layout.addWidget(self.help_label)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        self.setLayout(self.main_layout)

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

        # Update list widget
        self.update_list_widget()

        # Connect signal
        self.input_button_group.buttonClicked.connect(
            self.radio_buttons_clicked)

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        # Set value for each key
        for key, value in self._parameter.options.items():
            if value.get('type') == STATIC:
                continue
            elif value.get('type') == SINGLE_DYNAMIC:
                new_value = self.spin_boxes.get(key).value()
                self._parameter.set_value_for_key(key, new_value)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                # Need to iterate through all items
                items = []
                for index in xrange(self.list_widget.count()):
                    items.append(self.list_widget.item(index))
                new_value = [i.text() for i in items]
                self._parameter.set_value_for_key(key, new_value)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.selected = None
        else:
            self._parameter.selected = self._parameter.options.keys()[
                radio_button_checked_id]

        return self._parameter

    def update_list_widget(self):
        """Update list widget when radio button is clicked."""
        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id > -1:
            selected_dict = self._parameter.options.values()[
                radio_button_checked_id]
            if selected_dict.get('type') == MULTIPLE_DYNAMIC:
                for field in selected_dict.get('value'):
                    # Update list widget
                    field_item = QListWidgetItem(self.list_widget)
                    field_item.setFlags(
                        Qt.ItemIsEnabled |
                        Qt.ItemIsSelectable |
                        Qt.ItemIsDragEnabled)
                    field_item.setData(Qt.UserRole, field)
                    field_item.setText(field)
                    self.list_widget.addItem(field_item)

    def radio_buttons_clicked(self):
        """Handler when selected radio button changed."""
        # Disable all spin boxes
        for spin_box in self.spin_boxes.values():
            spin_box.setEnabled(False)
        # Disable list widget
        self.list_widget.setEnabled(False)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()

        if radio_button_checked_id > -1:
            selected_value = self._parameter.options.values()[
                radio_button_checked_id]
            if selected_value.get('type') == MULTIPLE_DYNAMIC:
                # Enable list widget
                self.list_widget.setEnabled(True)
            elif selected_value.get('type') == SINGLE_DYNAMIC:
                selected_key = self._parameter.options.keys()[
                    radio_button_checked_id]
                self.spin_boxes[selected_key].setEnabled(True)

    def select_radio_button(self, key):
        """Helper to select a radio button with key.

        :param key: The key of the radio button.
        :type key: str
        """
        key_index = self._parameter.options.keys().index(key)
        radio_button = self.input_button_group.button(key_index)
        radio_button.click()
Пример #36
0
class ProjectPropertiesDialog( QDialog, object ):
    """ project properties dialog implementation """

    def __init__( self, project = None, parent = None ):

        QDialog.__init__( self, parent )

        # The dialog caller reads this member if the dialog was finished
        # successfully.
        self.absProjectFileName = None

        self.__createLayout()
        self.__project = project

        if project is None:
            # It a new project creation
            self.setWindowTitle( "New Project Properties" )

            userRecord = pwd.getpwuid( os.getuid() )

            if not userRecord[ 5 ].endswith( os.path.sep ):
                self.dirEdit.setText( userRecord[ 5 ] + os.path.sep )
            else:
                self.dirEdit.setText( userRecord[ 5 ] )
            self.initialDirName = self.dirEdit.text()
            self.lastProjectName = ""

            if userRecord[ 4 ] != "":
                self.authorEdit.setText( userRecord[ 4 ].split( ',' )[ 0 ].strip() )
            else:
                self.authorEdit.setText( userRecord[ 0 ] )

            try:
                self.emailEdit.setText( userRecord[ 0 ] +
                                        "@" + socket.gethostname() )
            except:
                pass

            self.versionEdit.setText( "0.0.1" )
            self.licenseEdit.setText( "GPL v3" )
            self.copyrightEdit.setText( "Copyright (c) " +
                                        self.authorEdit.text() + ", " +
                                        str( datetime.date.today().year ) )
            self.creationDateEdit.setText( getLocaleDate() )
            self.nameEdit.setFocus()

        elif type( project ) == type( "" ):
            self.setWindowTitle( "Viewing Project Properties" )

            # This is viewing properties and the argument is the path to the
            # project file
            scriptName, importDirs, creationDate, author, lic, \
            copy_right, description, \
            version, email, uuid = getProjectProperties( project )

            if not os.path.isabs( scriptName ) and scriptName != "":
                scriptName = os.path.normpath( os.path.dirname( project ) +
                                               os.path.sep + scriptName )

            self.nameEdit.setText( os.path.basename( project ) )
            self.nameEdit.setToolTip( "" )
            self.dirEdit.setText( os.path.dirname( project ) )
            self.dirEdit.setToolTip( "" )
            self.scriptEdit.setText( scriptName )
            self.versionEdit.setText( version )
            self.authorEdit.setText( author )
            self.emailEdit.setText( email )
            self.licenseEdit.setText( lic )
            self.copyrightEdit.setText( copy_right )
            self.descriptionEdit.setText( description )
            self.creationDateEdit.setText( creationDate )
            self.uuidEdit.setText( str( uuid ) )
            self.uuidEdit.setToolTip( settingsDir + str( uuid ) + os.path.sep +
                                      " (double click to copy path)"  )

            for item in importDirs:
                self.importDirList.addItem( item )

            self.disableEditing()

        else:
            self.setWindowTitle( "Editing Project Properties" )

            # This is editing the loaded project.
            self.nameEdit.setText( os.path.basename( project.fileName ) )
            self.nameEdit.setToolTip( "" )
            self.dirEdit.setText( project.getProjectDir() )
            self.dirEdit.setToolTip( "" )
            self.scriptEdit.setText( project.getProjectScript() )
            self.versionEdit.setText( project.version )
            self.authorEdit.setText( project.author )
            self.emailEdit.setText( project.email )
            self.licenseEdit.setText( project.license )
            self.copyrightEdit.setText( project.copyright )
            self.descriptionEdit.setText( project.description )
            self.creationDateEdit.setText( project.creationDate )
            self.uuidEdit.setText( str( project.uuid ) )
            self.uuidEdit.setToolTip( project.userProjectDir +
                                      " (double click to copy path)" )
            self.setReadOnly()

            for item in project.importDirs:
                self.importDirList.addItem( item )
            if self.importDirList.count() > 0:
                self.importDirList.setCurrentRow( 0 )
                self.delImportDirButton.setEnabled( True )

            # The project could be the one belonging to another user
            # so there might be no write permissions.
            if not os.access( project.fileName, os.W_OK ):
                # Disable editing
                self.setWindowTitle( "Viewing Project Properties (no write permissions)" )
                self.disableEditing()
            else:
                self.scriptEdit.setFocus()

        return

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

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

        verticalLayout = QVBoxLayout( self )
        gridLayout = QGridLayout()

        # Project name
        nameLabel = QLabel( self )
        nameLabel.setText( "Project name:" )
        gridLayout.addWidget( nameLabel, 0, 0, 1, 1 )
        self.nameEdit = QLineEdit( self )
        self.nameEdit.setToolTip( "Type a project name without a path" )
        self.nameEdit.installEventFilter( self )
        gridLayout.addWidget( self.nameEdit, 0, 1, 1, 1 )

        # Project dir
        dirLabel = QLabel( self )
        dirLabel.setText( "Project directory:" )
        gridLayout.addWidget( dirLabel, 1, 0, 1, 1 )
        self.dirEdit = QLineEdit( self )
        self.dirEdit.setToolTip( "Not existed directories will be created" )
        gridLayout.addWidget( self.dirEdit, 1, 1, 1, 1 )
        self.dirButton = QPushButton( self )
        self.dirButton.setText( "..." )
        gridLayout.addWidget( self.dirButton, 1, 2, 1, 1 )
        self.dirCompleter = DirCompleter( self.dirEdit )

        # Project script
        mainScriptLabel = QLabel( "Main script:", self )
        gridLayout.addWidget( mainScriptLabel, 2, 0, 1, 1 )
        self.scriptEdit = QLineEdit( self )
        self.scriptEdit.setToolTip( "Project main script, "
                                    "used when the project is run" )
        gridLayout.addWidget( self.scriptEdit, 2, 1, 1, 1 )
        self.scriptButton = QPushButton( "...", self )
        gridLayout.addWidget( self.scriptButton, 2, 2, 1, 1 )
        self.fileCompleter = FileCompleter( self.scriptEdit )

        # Import dirs
        importLabel = QLabel( self )
        importLabel.setText( "Import directories:" )
        importLabel.setAlignment( Qt.AlignTop )
        gridLayout.addWidget( importLabel, 3, 0, 1, 1 )
        self.importDirList = QListWidget( self )
        self.importDirList.setAlternatingRowColors( True )
        self.importDirList.setSelectionMode( QAbstractItemView.SingleSelection )
        self.importDirList.setSelectionBehavior( QAbstractItemView.SelectRows )
        self.importDirList.setItemDelegate( NoOutlineHeightDelegate( 4 ) )
        self.importDirList.setToolTip( "Directories where to look for "
                                       "project specific imports" )
        gridLayout.addWidget( self.importDirList, 3, 1, 1, 1 )

        self.addImportDirButton = QPushButton( self )
        self.addImportDirButton.setText( "Add dir" )
        self.delImportDirButton = QPushButton( self )
        self.delImportDirButton.setText( "Delete dir" )
        self.delImportDirButton.setEnabled( False )
        vLayout = QVBoxLayout()
        vLayout.addWidget( self.addImportDirButton )
        vLayout.addWidget( self.delImportDirButton )
        vLayout.addStretch( 0 )
        gridLayout.addLayout( vLayout, 3, 2, 1, 1 )

        # Version
        versionLabel = QLabel( self )
        versionLabel.setText( "Version:" )
        gridLayout.addWidget( versionLabel, 4, 0, 1, 1 )
        self.versionEdit = QLineEdit( self )
        gridLayout.addWidget( self.versionEdit, 4, 1, 1, 1 )

        # Author
        authorLabel = QLabel( self )
        authorLabel.setText( "Author:" )
        gridLayout.addWidget( authorLabel, 5, 0, 1, 1 )
        self.authorEdit = QLineEdit( self )
        gridLayout.addWidget( self.authorEdit, 5, 1, 1, 1 )

        # E-mail
        emailLabel = QLabel( self )
        emailLabel.setText( "E-mail:" )
        gridLayout.addWidget( emailLabel, 6, 0, 1, 1 )
        self.emailEdit = QLineEdit( self )
        gridLayout.addWidget( self.emailEdit, 6, 1, 1, 1 )

        # License
        licenseLabel = QLabel( self )
        licenseLabel.setText( "License:" )
        gridLayout.addWidget( licenseLabel, 7, 0, 1, 1 )
        self.licenseEdit = QLineEdit( self )
        gridLayout.addWidget( self.licenseEdit, 7, 1, 1, 1 )

        # Copyright
        copyrightLabel = QLabel( self )
        copyrightLabel.setText( "Copyright:" )
        gridLayout.addWidget( copyrightLabel, 8, 0, 1, 1 )
        self.copyrightEdit = QLineEdit( self )
        gridLayout.addWidget( self.copyrightEdit, 8, 1, 1, 1 )

        # Description
        descriptionLabel = QLabel( self )
        descriptionLabel.setText( "Description:" )
        descriptionLabel.setAlignment( Qt.AlignTop )
        gridLayout.addWidget( descriptionLabel, 9, 0, 1, 1 )
        self.descriptionEdit = QTextEdit( self )
        self.descriptionEdit.setTabChangesFocus( True )
        self.descriptionEdit.setAcceptRichText( False )
        gridLayout.addWidget( self.descriptionEdit, 9, 1, 1, 1 )

        # Creation date
        creationDateLabel = QLabel( self )
        creationDateLabel.setText( "Creation date:" )
        gridLayout.addWidget( creationDateLabel, 10, 0, 1, 1 )
        self.creationDateEdit = FramedLabelWithDoubleClick()
        self.creationDateEdit.setToolTip( "Double click to copy" )
        gridLayout.addWidget( self.creationDateEdit, 10, 1, 1, 1 )

        # Project UUID
        uuidLabel = QLabel( self )
        uuidLabel.setText( "UUID:" )
        gridLayout.addWidget( uuidLabel, 11, 0, 1, 1 )
        self.uuidEdit = FramedLabelWithDoubleClick( "", self.__copyProjectPath )
        gridLayout.addWidget( self.uuidEdit, 11, 1, 1, 1 )

        verticalLayout.addLayout( gridLayout )

        # Buttons at the bottom
        buttonBox = QDialogButtonBox( self )
        buttonBox.setOrientation( Qt.Horizontal )
        buttonBox.setStandardButtons( QDialogButtonBox.Cancel | \
                                      QDialogButtonBox.Ok )
        verticalLayout.addWidget( buttonBox )

        nameLabel.setBuddy( self.nameEdit )
        dirLabel.setBuddy( self.dirEdit )
        versionLabel.setBuddy( self.versionEdit )
        authorLabel.setBuddy( self.authorEdit )
        emailLabel.setBuddy( self.emailEdit )
        licenseLabel.setBuddy( self.licenseEdit )
        copyrightLabel.setBuddy( self.copyrightEdit )
        descriptionLabel.setBuddy( self.descriptionEdit )

        buttonBox.accepted.connect( self.onOKButton )
        buttonBox.rejected.connect( self.reject )
        self.dirButton.clicked.connect( self.onDirButton )
        self.scriptButton.clicked.connect( self.onScriptButton )
        self.importDirList.currentRowChanged.connect( self.onImportDirRowChanged )
        self.addImportDirButton.clicked.connect( self.onAddImportDir )
        self.delImportDirButton.clicked.connect( self.onDelImportDir )
        self.nameEdit.textEdited.connect( self.onProjectNameChanged )

        self.setTabOrder( self.nameEdit, self.dirEdit )
        self.setTabOrder( self.dirEdit, self.dirButton )
        self.setTabOrder( self.dirButton, self.scriptEdit )
        self.setTabOrder( self.scriptEdit, self.scriptButton )
        self.setTabOrder( self.scriptButton, self.importDirList )
        self.setTabOrder( self.importDirList, self.addImportDirButton )
        self.setTabOrder( self.addImportDirButton, self.delImportDirButton )
        self.setTabOrder( self.delImportDirButton, self.versionEdit )
        self.setTabOrder( self.versionEdit, self.authorEdit )
        self.setTabOrder( self.authorEdit, self.emailEdit )
        self.setTabOrder( self.emailEdit, self.licenseEdit )
        self.setTabOrder( self.licenseEdit, self.copyrightEdit )
        self.setTabOrder( self.copyrightEdit, self.descriptionEdit )
        self.setTabOrder( self.descriptionEdit, buttonBox )
        return

    def eventFilter( self, obj, event ):
        " Event filter for the project name field "

        # Do not allow path separators
        if event.type() == QEvent.KeyPress:
            if event.key() == ord( os.path.sep ):
                return True
        return QObject.eventFilter( self, obj, event )


    def onDirButton( self ):
        " Displays a directory selection dialog "

        dirName = QFileDialog.getExistingDirectory( self,
                    "Select project directory",
                    self.dirEdit.text(),
                    QFileDialog.Options( QFileDialog.ShowDirsOnly ) )

        if dirName:
            self.dirEdit.setText( os.path.normpath( dirName ) )
        return

    def onScriptButton( self ):
        " Displays a file selection dialog "
        scriptName = QFileDialog.getOpenFileName( self,
                        "Select project main script",
                        self.dirEdit.text() )

        if scriptName:
            self.scriptEdit.setText( os.path.normpath( scriptName ) )
        return

    def onImportDirRowChanged( self, row ):
        " Triggered when a current row in the import dirs is changed "
        self.delImportDirButton.setEnabled( row != -1 )
        return

    def onAddImportDir( self ):
        " Displays a directory selection dialog "

        dirName = QFileDialog.getExistingDirectory( self,
                    "Select import directory",
                    self.dirEdit.text(),
                    QFileDialog.Options( QFileDialog.ShowDirsOnly ) )

        if not dirName:
            return

        # There are 2 cases: new project or
        # editing the existed project properties
        if self.__project is None:
            # It a new project; the project path could be editedd
            dirToInsert = dirName
        else:
            # This is an existed project; no way the project path is changed
            # Let's decide it a relative path should be used here
            if self.__project.isProjectDir( dirName ):
                dirToInsert = relpath( dirName, self.dirEdit.text() )
            else:
                dirToInsert = dirName

        index = 0
        while index < self.importDirList.count():
            if self.importDirList.item( index ).text() == dirToInsert:
                logging.warning( "The directory '" + dirName +
                                 "' is already in the list of "
                                 "imported directories and is not added." )
                return
            index += 1

        self.importDirList.addItem( dirToInsert )
        self.importDirList.setCurrentRow( self.importDirList.count() - 1 )
        return

    def onDelImportDir( self ):
        " Triggered when an import dir should be deleted "

        rowToDelete = self.importDirList.currentRow()
        if  rowToDelete == -1:
            self.delImportDirButton.setEnabled( False )
            return

        self.importDirList.takeItem( rowToDelete )
        if self.importDirList.count() == 0:
            self.delImportDirButton.setEnabled( False )
        else:
            self.importDirList.setCurrentRow( self.importDirList.count() - 1 )
        return

    def onOKButton( self ):
        " Checks that the mandatory fields are filled properly "

        # The checks must be done for a new project only
        if not self.nameEdit.isEnabled():
            self.accept()
            return

        # Check that the project name does not have path separators and is not
        # empty
        if not self.nameEdit.text().strip():
            QMessageBox.critical( self, "Error",
                                  "The project name must not be empty" )
            return
        if os.path.sep in self.nameEdit.text():
            QMessageBox.critical( self, "Error",
                                  "The project name must not "
                                  "contain path separators" )
            return

        # Check that the project directory is given
        dirName = self.dirEdit.text().strip()
        if not dirName:
            QMessageBox.critical( self, "Error",
                                  "The project directory must not be empty" )
            return

        dirName = os.path.abspath( dirName )
        self.dirEdit.setText( dirName )
        # Check that the project file does not exist
        projectFileName = dirName
        if not projectFileName.endswith( os.path.sep ):
            projectFileName += os.path.sep
        projectFileName += self.nameEdit.text().strip()
        if not projectFileName.endswith( ".cdm" ):
            projectFileName += ".cdm"

        if os.path.exists( projectFileName ):
            QMessageBox.critical( self, "Error",
                                  "The project file " + projectFileName +
                                  " exists. Please provide another "
                                  "directory / project name." )
            return

        # Check that the project dir is not a file
        if os.path.exists( dirName ):
            # It might be a link, so read it first
            dirName = os.path.realpath( dirName )
            if not os.path.exists( dirName ):
                QMessageBox.critical( self, "Error",
                                      "Broken link: " + dirName )
                return
            if not os.path.isdir( dirName ):
                QMessageBox.critical( self, "Error",
                                      "The project directory "
                                      "may not be a file" )
                return
            # Check that the dir is writable
            if not os.access( dirName, os.W_OK ):
                QMessageBox.critical( self, "Error",
                                      "You don't have write permissions on " +
                                      dirName )
                return
        else:
            # Create the directory
            try:
                os.makedirs( dirName )
            except OSError:
                QMessageBox.critical( self, "Error",
                                      "Cannot create the project directory" )
                return

        # Save the absolute file name for further reading it by the caller
        self.absProjectFileName = projectFileName

        # The minimum is provided so we can accept it
        self.accept()
        return

    def onProjectNameChanged( self, newName ):
        " Called when the project name changed "

        if newName.endswith( ".cdm" ):
            newName = newName[ :-4 ]
        if self.dirEdit.text().strip() == (self.initialDirName +
                                           self.lastProjectName):
            self.dirEdit.setText( self.initialDirName + newName )
            self.lastProjectName = newName
        return

    def setReadOnly( self ):
        """ Disables editing some fields """

        self.dirEdit.setReadOnly( True )
        self.dirEdit.setFocusPolicy( Qt.NoFocus )
        self.dirEdit.setDisabled( True )
        self.dirButton.setDisabled( True )
        self.dirButton.setFocusPolicy( Qt.NoFocus )
        self.nameEdit.setReadOnly( True )
        self.nameEdit.setFocusPolicy( Qt.NoFocus )
        self.nameEdit.setDisabled( True )
        return

    def disableEditing( self ):
        " Disables all the editing "

        self.nameEdit.setDisabled( True )
        self.dirEdit.setDisabled( True )
        self.dirButton.setDisabled( True )
        self.scriptEdit.setDisabled( True )
        self.scriptButton.setDisabled( True )
        self.importDirList.setDisabled( True )
        self.addImportDirButton.setDisabled( True )
        self.delImportDirButton.setDisabled( True )
        self.versionEdit.setDisabled( True )
        self.authorEdit.setDisabled( True )
        self.emailEdit.setDisabled( True )
        self.licenseEdit.setDisabled( True )
        self.copyrightEdit.setDisabled( True )
        self.descriptionEdit.setDisabled( True )
        return

    def __copyProjectPath( self ):
        " Copies the project path when a label is double clicked "
        text = self.uuidEdit.text().strip()
        if text:
            path = settingsDir + text + os.path.sep
            QApplication.clipboard().setText( path )
        return
class AdvancedVisualizationForm(QWidget):
    def __init__(self, mainwindow, result_manager):
        QWidget.__init__(self, mainwindow)
        #mainwindow is an OpusGui
        self.mainwindow = mainwindow
        self.result_manager = result_manager
        self.toolboxBase = self.result_manager.mainwindow.toolboxBase

        self.inGui = False
        self.logFileKey = 0
        
        self.xml_helper = ResultsManagerXMLHelper(toolboxBase = self.toolboxBase)
        self.result_generator = OpusResultGenerator(
                                    toolboxBase = self.toolboxBase)
            
        self.result_generator.guiElement = self
        
        self.tabIcon = QIcon(':/Images/Images/cog.png')
        self.tabLabel = 'Advanced Visualization'

        self.widgetLayout = QVBoxLayout(self)
        self.widgetLayout.setAlignment(Qt.AlignTop)

        self.resultsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.resultsGroupBox)
        
        self.dataGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.dataGroupBox)
        
        self.optionsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.optionsGroupBox)
                
        self._setup_definition_widget()

        self._setup_buttons()
        self._setup_tabs()
        
    def _setup_buttons(self):
        # Add Generate button...
        self.pbn_go = QPushButton(self.resultsGroupBox)
        self.pbn_go.setObjectName('pbn_go')
        self.pbn_go.setText(QString('Go!'))
        
        QObject.connect(self.pbn_go, SIGNAL('released()'),
                        self.on_pbn_go_released)
        self.widgetLayout.addWidget(self.pbn_go)
        
        self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox)
        self.pbn_set_esri_storage_location.setObjectName('pbn_set_esri_storage_location')
        self.pbn_set_esri_storage_location.setText(QString('...'))
        self.pbn_set_esri_storage_location.hide()
        
        QObject.connect(self.pbn_set_esri_storage_location, SIGNAL('released()'),
                        self.on_pbn_set_esri_storage_location_released)
        
    def _setup_tabs(self):
        # Add a tab widget and layer in a tree view and log panel
        self.tabWidget = QTabWidget(self.resultsGroupBox)
    
        # Log panel
        self.logText = QTextEdit(self.resultsGroupBox)
        self.logText.setReadOnly(True)
        self.logText.setLineWidth(0)
        self.tabWidget.addTab(self.logText,'Log')

        # Finally add the tab to the model page
        self.widgetLayout.addWidget(self.tabWidget)
        
#
    def _setup_definition_widget(self):
        
        #### setup results group box ####
        
        self.gridlayout = QGridLayout(self.resultsGroupBox)
        self.gridlayout.setObjectName('gridlayout')

        self.lbl_results = QLabel(self.resultsGroupBox)
        self.lbl_results.setObjectName('lbl_results')
        self.lbl_results.setText(QString('Results'))
        self.gridlayout.addWidget(self.lbl_results,0,0,1,3)

        self._setup_co_results()
        self.gridlayout.addWidget(self.co_results,0,3,1,10)

        self.pbn_add = QPushButton(self.resultsGroupBox)
        self.pbn_add.setObjectName('pbn_add')
        self.pbn_add.setText(QString('+'))
        
        QObject.connect(self.pbn_add, SIGNAL('released()'),
                        self.on_pbn_add_released)
        self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1)

        self.lw_indicators = QListWidget(self.resultsGroupBox)
        self.lw_indicators.setObjectName('lw_indicators')
        self.gridlayout.addWidget(self.lw_indicators,1,1,1,13)

        self.pbn_remove = QPushButton(self.resultsGroupBox)
        self.pbn_remove.setObjectName('pbn_remove')
        self.pbn_remove.setText(QString('-'))
        
        QObject.connect(self.pbn_remove, SIGNAL('released()'),
                        self.on_pbn_remove_released)
        self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1)


        #### setup data group box ####

        self.gridlayout2 = QGridLayout(self.dataGroupBox)
        self.gridlayout2.setObjectName('gridlayout2')

        self._setup_co_result_style()
        self.gridlayout2.addWidget(self.co_result_style,1,0,1,2)
                
        self.lbl_result_style_sep = QLabel(self.resultsGroupBox)
        self.lbl_result_style_sep.setObjectName('lbl_result_style_sep')
        self.lbl_result_style_sep.setText(QString('<center>as</center>'))
        self.gridlayout2.addWidget(self.lbl_result_style_sep,1,2,1,1)

        self._setup_co_result_type()
        self.gridlayout2.addWidget(self.co_result_type,1,3,1,2)

        ##### setup options group box ####
        
        self.gridlayout3 = QGridLayout(self.optionsGroupBox)
        self.gridlayout3.setObjectName('gridlayout3')
        
        self.le_esri_storage_location = QLineEdit(self.optionsGroupBox)
        self.le_esri_storage_location.setObjectName('le_esri_storage_location')
        self.le_esri_storage_location.setText('[set path]')
        self.le_esri_storage_location.hide()
        self.optionsGroupBox.hide()

        
        QObject.connect(self.co_result_style, SIGNAL('currentIndexChanged(int)'),
                self.on_co_result_style_changed)
        QObject.connect(self.co_result_type, SIGNAL('currentIndexChanged(int)'),
                self.on_co_result_type_changed)

    def _setup_co_results(self):
        
        self.co_results = QComboBox(self.resultsGroupBox)
        self.co_results.setObjectName('co_results')
        self.co_results.addItem(QString('[select]'))
        
        results = self.xml_helper.get_available_results()
            
        for result in results:
            name = '%i.%s'%(result['run_id'],result['indicator_name'])
            self.co_results.addItem(QString(name))

    def _setup_co_result_style(self):
        available_styles = [
            'visualize',
            'export',
        ]
        self.co_result_style = QComboBox(self.dataGroupBox)
        self.co_result_style.setObjectName('co_result_style')
        
        for dataset in available_styles:
            self.co_result_style.addItem(QString(dataset))

    def _setup_co_result_type(self):
        available_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]
                
        self.co_result_type = QComboBox(self.dataGroupBox)
        self.co_result_type.setObjectName('co_result_type')
        
        for dataset in available_types:
            self.co_result_type.addItem(QString(dataset))
                    
    def on_pbnRemoveModel_released(self):
        self.result_manager.removeTab(self)
        self.result_manager.updateGuiElements()
        
    def on_pbn_add_released(self):
        cur_selected = self.co_results.currentText()        
        for i in range(self.lw_indicators.count()):
            if self.lw_indicators.item(i).text() == cur_selected:
                return
        
        self.lw_indicators.addItem(cur_selected)
        
    def on_pbn_remove_released(self):
        selected_idxs = self.lw_indicators.selectedIndexes()
        for idx in selected_idxs:
            self.lw_indicators.takeItem(idx.row())
        
    def on_co_result_style_changed(self, ind):
        available_viz_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]
        
        available_export_types = [
            'ESRI table (for loading in ArcGIS)'
        ]
                
        txt = self.co_result_style.currentText()
        if txt == 'visualize':
            available_types = available_viz_types
        else:
            available_types = available_export_types
            
        self.co_result_type.clear()
        for result_type in available_types:
            r_type = QString(result_type)
            self.co_result_type.addItem(r_type)
    
    def on_co_result_type_changed(self, ind):
        self.gridlayout3.removeWidget(self.le_esri_storage_location)
        self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location)
        self.optionsGroupBox.hide()
        
        self.pbn_set_esri_storage_location.hide()
        self.le_esri_storage_location.hide()
        
        txt = self.co_result_type.currentText()

        print txt
        if txt == 'ESRI table (for loading in ArcGIS)':
            self.pbn_set_esri_storage_location.show()   
            self.le_esri_storage_location.show()   
            self.gridlayout3.addWidget(self.le_esri_storage_location,0,1,1,6)
            self.gridlayout3.addWidget(self.pbn_set_esri_storage_location,0,7,1,1)   
            self.optionsGroupBox.show()   
            
    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(self,QString("Please select an ESRI geodatabase (*.gdb)..."), #, *.sde, *.mdb)..."),
                                          QString(start_dir), QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)
            
                
    def on_pbn_go_released(self):
        # Fire up a new thread and run the model
        print 'Go button pressed'

        # References to the GUI elements for status for this run...
        #self.statusLabel = self.runStatusLabel
        #self.statusLabel.setText(QString('Model initializing...'))
        
        indicator_names = []
        for i in range(self.lw_indicators.count()):
            indicator_names.append(str(self.lw_indicators.item(i).text()))
                
        if indicator_names == []:
            print 'no indicators selected'
            return
                
        indicator_type = str(self.co_result_type.currentText())
        indicator_type = {
            #'Map (per indicator per year)':'matplotlib_map',
            'Map (per indicator per year)':'mapnik_map',
            'Chart (per indicator, spans years)':'matplotlib_chart',
            'Table (per indicator, spans years)':'table_per_attribute',
            'Table (per year, spans indicators)':'table_per_year',
            'ESRI table (for loading in ArcGIS)':'table_esri'
        }[indicator_type]
        
        kwargs = {}
        if indicator_type == 'table_esri':
            storage_location = str(self.le_esri_storage_location.text())
            if not os.path.exists(storage_location):
                print 'Warning: %s does not exist!!'%storage_location
            kwargs['storage_location'] = storage_location
        
        self.result_manager.addIndicatorForm(indicator_type = indicator_type,
                                             indicator_names = indicator_names,
                                             kwargs = kwargs)

    def runUpdateLog(self):
        self.logFileKey = self.result_generator._get_current_log(self.logFileKey)


    def runErrorFromThread(self,errorMessage):
        QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)
Пример #38
0
class statisticsInfoWidget(infoWidget):
	__chart = None
	__mainLayout = None
	__statistics = None
	__projectsList = None
	__buttonsLayout = None
	__statisticGroupBox = None
	__statisticLayout = None
	__modeGroupBox = None
	__modeLayout = None
	__colors = [Qt.red, QColor(200, 160, 30), Qt.darkGreen, Qt.blue, Qt.black, Qt.darkRed, Qt.darkBlue]

	def __init__(self, client, parent = None):
		infoWidget.__init__(self, client, parent)
		self.__mainLayout = QHBoxLayout()
		self.__chart = LineChartFrame()

		self.__projectsList = QListWidget()
		self.__projectsList.setFixedWidth(200)

		self.__statisticGroupBox = QGroupBox(self.tr("Statistics type"))
		self.__statisticLayout = QVBoxLayout()
		self.__statisticGroupBox.setLayout(self.__statisticLayout)

		userTotalRadio   = QRadioButton(self.tr("User total"), self.__statisticGroupBox)
		userAverageRadio = QRadioButton(self.tr("User average"), self.__statisticGroupBox)
		hostTotalRadio   = QRadioButton(self.tr("Host total"), self.__statisticGroupBox)
		hostAverageRadio = QRadioButton(self.tr("Host average"), self.__statisticGroupBox)

		self.__statisticLayout.addWidget(userTotalRadio)
		self.__statisticLayout.addWidget(userAverageRadio)
		self.__statisticLayout.addWidget(hostTotalRadio)
		self.__statisticLayout.addWidget(hostAverageRadio)

		self.__buttonsLayout = QVBoxLayout()
		self.__buttonsLayout.addWidget(self.__projectsList)
		self.__buttonsLayout.addWidget(self.__statisticGroupBox)

		self.__mainLayout.addWidget(self.__chart)
		self.__mainLayout.addLayout(self.__buttonsLayout)
		self.setMainLayout(self.__mainLayout)

		userTotalRadio.setChecked(True)
		self.connect(userTotalRadio, SIGNAL("toggled(bool)"), self.__setUserTotalGraph)
		self.connect(userAverageRadio, SIGNAL("toggled(bool)"), self.__setUserAverageGraph)
		self.connect(hostTotalRadio, SIGNAL("toggled(bool)"), self.__setHostTotalGraph)
		self.connect(hostAverageRadio, SIGNAL("toggled(bool)"), self.__setHostAverageGraph)

		self.connect(self.__projectsList, SIGNAL("itemChanged(QListWidgetItem *)"), self.__updateStatisticsGraph)
		self.connect(client, SIGNAL("getStatisticsRecv(PyQt_PyObject)"), self.__updateStatistics)
		client.getStatistics()

	def __setUserTotalGraph(self, checked):
		if checked:
			self.__chart.setIndex(0)

	def __setUserAverageGraph(self, checked):
		if checked:
			self.__chart.setIndex(1)

	def __setHostTotalGraph(self, checked):
		if checked:
			self.__chart.setIndex(2)

	def __setHostAverageGraph(self, checked):
		if checked:
			self.__chart.setIndex(3)

	def __updateStatistics(self, statistics):
		self.disconnect(self.sender(), SIGNAL("getStatisticsRecv(PyQt_PyObject)"), self.__updateStatistics)
		self.__statistics = statistics
		self.__addListItems()
		self.__updateStatisticsGraph()

	def __addListItems(self):
		i = 0
		for key in self.__statistics.keys():
			name = self.sender().getProjectName(key)
			if name is None:
				name = key
			color = self.__colors[i]

			item = QListWidgetItem(name)
			item.setData(Qt.DecorationRole, QVariant(QColor(color)))
			item.setData(Qt.UserRole, QVariant(key))
			item.setFlags(Qt.ItemIsSelectable|Qt.ItemIsUserCheckable|Qt.ItemIsEnabled)
			item.setCheckState(Qt.Checked)
			self.__projectsList.addItem(item)

			i = i + 1
			if i >= len(self.__colors):
				i = 0

	def __updateStatisticsGraph(self):
		self.__chart.removeGraphs()
		for i in range(self.__projectsList.count()):
			item = self.__projectsList.item(i)
			color = item.data(Qt.DecorationRole)
			name = str(item.data(Qt.DisplayRole).toString())
			key = str(item.data(Qt.UserRole).toString())
			if item.checkState() == Qt.Checked:
				self.__chart.addGraph(self.__statistics[key], name, color)
Пример #39
0
class NotebookListDialog(QDialog):
    """ Funtions to display, create, remove, modify notebookList """

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

        self.notebookList = QListWidget()
        self.moveUp = QPushButton('<<')
        self.moveDown = QPushButton('>>')
        self.add = QPushButton('Add')
        self.remove = QPushButton('Remove')
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                          QDialogButtonBox.Cancel)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        layout = QGridLayout()
        layout.addWidget(self.notebookList, 0, 0, 4, 6)
        layout.addWidget(self.moveUp, 1, 6)
        layout.addWidget(self.moveDown, 2, 6)
        layout.addWidget(self.add, 4, 0)
        layout.addWidget(self.remove, 4, 1)
        layout.addWidget(self.buttonBox, 4, 5, 1, 2)
        self.setLayout(layout)

        self.notebookList.setItemDelegate(ListDelegate(self.notebookList))

        self.notebookList.currentRowChanged.connect(self.updateUi)
        self.add.clicked.connect(self.actionAdd)
        self.remove.clicked.connect(self.actionRemove)
        self.moveUp.clicked.connect(self.moveItemUp)
        self.moveDown.clicked.connect(self.moveItemDown)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.initList()

    def initList(self):
        self.notebookList.clear()
        notebooks = Mikibook.read()
        for nb in notebooks:
            item = QListWidgetItem()
            item.setData(Qt.DisplayRole, nb[0])
            item.setData(Qt.UserRole, nb[1])
            self.notebookList.addItem(item)

        self.updateUi(len(notebooks) != 0)
        self.notebookList.setCurrentRow(0)
            # QListWidgetItem(nb, self.notebookList)

    def updateUi(self, row):
        flag = (row != -1)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(flag)
        self.remove.setEnabled(flag)
        self.moveUp.setEnabled(flag)
        self.moveDown.setEnabled(flag)

    def actionAdd(self):
        Mikibook.create()
        self.initList()
        count = self.notebookList.count()
        self.notebookList.setCurrentRow(count-1)

    def actionRemove(self):
        item = self.notebookList.currentItem()
        row = self.notebookList.currentRow()
        name = item.data(Qt.DisplayRole)
        path = item.data(Qt.UserRole)
        self.notebookList.takeItem(row)

        Mikibook.remove(name, path)

    def moveItemUp(self):
        item = self.notebookList.currentItem()
        row = self.notebookList.currentRow()
        if row != 0:
            # self.notebookList.removeItemWidget(item)
            self.notebookList.takeItem(row)
            self.notebookList.insertItem(row-1, item)
            self.notebookList.setCurrentRow(row-1)

    def moveItemDown(self):
        item = self.notebookList.currentItem()
        row = self.notebookList.currentRow()
        count = self.notebookList.count()
        if row != count-1:
            self.notebookList.takeItem(row)
            self.notebookList.insertItem(row+1, item)
            self.notebookList.setCurrentRow(row+1)

    def accept(self):
        notebookPath = self.notebookList.currentItem().data(Qt.UserRole)
        notebookName = self.notebookList.currentItem().data(Qt.DisplayRole)
        settings = Setting([[notebookName, notebookPath]])
        window = mikidown.MikiWindow(settings)
        window.show()
        count = self.notebookList.count()
        notebooks = []
        for i in range(count):
            name = self.notebookList.item(i).data(Qt.DisplayRole)
            path = self.notebookList.item(i).data(Qt.UserRole)
            notebooks.append([name, path])
            Mikibook.write(notebooks)

        QDialog.accept(self)
class AdvancedVisualizationForm(QWidget):
    def __init__(self, mainwindow, result_manager):
        QWidget.__init__(self, mainwindow)
        #mainwindow is an OpusGui
        self.mainwindow = mainwindow
        self.result_manager = result_manager
        self.toolboxBase = self.result_manager.mainwindow.toolboxBase

        self.inGui = False
        self.logFileKey = 0

        self.xml_helper = ResultsManagerXMLHelper(toolboxBase=self.toolboxBase)
        self.result_generator = OpusResultGenerator(
            toolboxBase=self.toolboxBase)

        self.result_generator.guiElement = self

        self.tabIcon = QIcon(':/Images/Images/cog.png')
        self.tabLabel = 'Advanced Visualization'

        self.widgetLayout = QVBoxLayout(self)
        self.widgetLayout.setAlignment(Qt.AlignTop)

        self.resultsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.resultsGroupBox)

        self.dataGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.dataGroupBox)

        self.optionsGroupBox = QGroupBox(self)
        self.widgetLayout.addWidget(self.optionsGroupBox)

        self._setup_definition_widget()

        self._setup_buttons()
        self._setup_tabs()

    def _setup_buttons(self):
        # Add Generate button...
        self.pbn_go = QPushButton(self.resultsGroupBox)
        self.pbn_go.setObjectName('pbn_go')
        self.pbn_go.setText(QString('Go!'))

        QObject.connect(self.pbn_go, SIGNAL('released()'),
                        self.on_pbn_go_released)
        self.widgetLayout.addWidget(self.pbn_go)

        self.pbn_set_esri_storage_location = QPushButton(self.optionsGroupBox)
        self.pbn_set_esri_storage_location.setObjectName(
            'pbn_set_esri_storage_location')
        self.pbn_set_esri_storage_location.setText(QString('...'))
        self.pbn_set_esri_storage_location.hide()

        QObject.connect(self.pbn_set_esri_storage_location,
                        SIGNAL('released()'),
                        self.on_pbn_set_esri_storage_location_released)

    def _setup_tabs(self):
        # Add a tab widget and layer in a tree view and log panel
        self.tabWidget = QTabWidget(self.resultsGroupBox)

        # Log panel
        self.logText = QTextEdit(self.resultsGroupBox)
        self.logText.setReadOnly(True)
        self.logText.setLineWidth(0)
        self.tabWidget.addTab(self.logText, 'Log')

        # Finally add the tab to the model page
        self.widgetLayout.addWidget(self.tabWidget)

#

    def _setup_definition_widget(self):

        #### setup results group box ####

        self.gridlayout = QGridLayout(self.resultsGroupBox)
        self.gridlayout.setObjectName('gridlayout')

        self.lbl_results = QLabel(self.resultsGroupBox)
        self.lbl_results.setObjectName('lbl_results')
        self.lbl_results.setText(QString('Results'))
        self.gridlayout.addWidget(self.lbl_results, 0, 0, 1, 3)

        self._setup_co_results()
        self.gridlayout.addWidget(self.co_results, 0, 3, 1, 10)

        self.pbn_add = QPushButton(self.resultsGroupBox)
        self.pbn_add.setObjectName('pbn_add')
        self.pbn_add.setText(QString('+'))

        QObject.connect(self.pbn_add, SIGNAL('released()'),
                        self.on_pbn_add_released)
        self.gridlayout.addWidget(self.pbn_add, 0, 14, 1, 1)

        self.lw_indicators = QListWidget(self.resultsGroupBox)
        self.lw_indicators.setObjectName('lw_indicators')
        self.gridlayout.addWidget(self.lw_indicators, 1, 1, 1, 13)

        self.pbn_remove = QPushButton(self.resultsGroupBox)
        self.pbn_remove.setObjectName('pbn_remove')
        self.pbn_remove.setText(QString('-'))

        QObject.connect(self.pbn_remove, SIGNAL('released()'),
                        self.on_pbn_remove_released)
        self.gridlayout.addWidget(self.pbn_remove, 1, 14, 1, 1)

        #### setup data group box ####

        self.gridlayout2 = QGridLayout(self.dataGroupBox)
        self.gridlayout2.setObjectName('gridlayout2')

        self._setup_co_result_style()
        self.gridlayout2.addWidget(self.co_result_style, 1, 0, 1, 2)

        self.lbl_result_style_sep = QLabel(self.resultsGroupBox)
        self.lbl_result_style_sep.setObjectName('lbl_result_style_sep')
        self.lbl_result_style_sep.setText(QString('<center>as</center>'))
        self.gridlayout2.addWidget(self.lbl_result_style_sep, 1, 2, 1, 1)

        self._setup_co_result_type()
        self.gridlayout2.addWidget(self.co_result_type, 1, 3, 1, 2)

        ##### setup options group box ####

        self.gridlayout3 = QGridLayout(self.optionsGroupBox)
        self.gridlayout3.setObjectName('gridlayout3')

        self.le_esri_storage_location = QLineEdit(self.optionsGroupBox)
        self.le_esri_storage_location.setObjectName('le_esri_storage_location')
        self.le_esri_storage_location.setText('[set path]')
        self.le_esri_storage_location.hide()
        self.optionsGroupBox.hide()

        QObject.connect(self.co_result_style,
                        SIGNAL('currentIndexChanged(int)'),
                        self.on_co_result_style_changed)
        QObject.connect(self.co_result_type,
                        SIGNAL('currentIndexChanged(int)'),
                        self.on_co_result_type_changed)

    def _setup_co_results(self):

        self.co_results = QComboBox(self.resultsGroupBox)
        self.co_results.setObjectName('co_results')
        self.co_results.addItem(QString('[select]'))

        results = self.xml_helper.get_available_results()

        for result in results:
            name = '%i.%s' % (result['run_id'], result['indicator_name'])
            self.co_results.addItem(QString(name))

    def _setup_co_result_style(self):
        available_styles = [
            'visualize',
            'export',
        ]
        self.co_result_style = QComboBox(self.dataGroupBox)
        self.co_result_style.setObjectName('co_result_style')

        for dataset in available_styles:
            self.co_result_style.addItem(QString(dataset))

    def _setup_co_result_type(self):
        available_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]

        self.co_result_type = QComboBox(self.dataGroupBox)
        self.co_result_type.setObjectName('co_result_type')

        for dataset in available_types:
            self.co_result_type.addItem(QString(dataset))

    def on_pbnRemoveModel_released(self):
        self.result_manager.removeTab(self)
        self.result_manager.updateGuiElements()

    def on_pbn_add_released(self):
        cur_selected = self.co_results.currentText()
        for i in range(self.lw_indicators.count()):
            if self.lw_indicators.item(i).text() == cur_selected:
                return

        self.lw_indicators.addItem(cur_selected)

    def on_pbn_remove_released(self):
        selected_idxs = self.lw_indicators.selectedIndexes()
        for idx in selected_idxs:
            self.lw_indicators.takeItem(idx.row())

    def on_co_result_style_changed(self, ind):
        available_viz_types = [
            'Table (per year, spans indicators)',
            'Chart (per indicator, spans years)',
            'Map (per indicator per year)',
            'Chart (per indicator, spans years)',
        ]

        available_export_types = ['ESRI table (for loading in ArcGIS)']

        txt = self.co_result_style.currentText()
        if txt == 'visualize':
            available_types = available_viz_types
        else:
            available_types = available_export_types

        self.co_result_type.clear()
        for result_type in available_types:
            r_type = QString(result_type)
            self.co_result_type.addItem(r_type)

    def on_co_result_type_changed(self, ind):
        self.gridlayout3.removeWidget(self.le_esri_storage_location)
        self.gridlayout3.removeWidget(self.pbn_set_esri_storage_location)
        self.optionsGroupBox.hide()

        self.pbn_set_esri_storage_location.hide()
        self.le_esri_storage_location.hide()

        txt = self.co_result_type.currentText()

        print txt
        if txt == 'ESRI table (for loading in ArcGIS)':
            self.pbn_set_esri_storage_location.show()
            self.le_esri_storage_location.show()
            self.gridlayout3.addWidget(self.le_esri_storage_location, 0, 1, 1,
                                       6)
            self.gridlayout3.addWidget(self.pbn_set_esri_storage_location, 0,
                                       7, 1, 1)
            self.optionsGroupBox.show()

    def on_pbn_set_esri_storage_location_released(self):
        print 'pbn_set_esri_storage_location released'
        from opus_core.misc import directory_path_from_opus_path
        start_dir = directory_path_from_opus_path('opus_gui.projects')

        configDialog = QFileDialog()
        filter_str = QString("*.gdb")
        fd = configDialog.getExistingDirectory(
            self,
            QString("Please select an ESRI geodatabase (*.gdb)..."
                    ),  #, *.sde, *.mdb)..."),
            QString(start_dir),
            QFileDialog.ShowDirsOnly)
        if len(fd) != 0:
            fileName = QString(fd)
            fileNameInfo = QFileInfo(QString(fd))
            fileNameBaseName = fileNameInfo.completeBaseName()
            self.le_esri_storage_location.setText(fileName)

    def on_pbn_go_released(self):
        # Fire up a new thread and run the model
        print 'Go button pressed'

        # References to the GUI elements for status for this run...
        #self.statusLabel = self.runStatusLabel
        #self.statusLabel.setText(QString('Model initializing...'))

        indicator_names = []
        for i in range(self.lw_indicators.count()):
            indicator_names.append(str(self.lw_indicators.item(i).text()))

        if indicator_names == []:
            print 'no indicators selected'
            return

        indicator_type = str(self.co_result_type.currentText())
        indicator_type = {
            #'Map (per indicator per year)':'matplotlib_map',
            'Map (per indicator per year)': 'mapnik_map',
            'Chart (per indicator, spans years)': 'matplotlib_chart',
            'Table (per indicator, spans years)': 'table_per_attribute',
            'Table (per year, spans indicators)': 'table_per_year',
            'ESRI table (for loading in ArcGIS)': 'table_esri'
        }[indicator_type]

        kwargs = {}
        if indicator_type == 'table_esri':
            storage_location = str(self.le_esri_storage_location.text())
            if not os.path.exists(storage_location):
                print 'Warning: %s does not exist!!' % storage_location
            kwargs['storage_location'] = storage_location

        self.result_manager.addIndicatorForm(indicator_type=indicator_type,
                                             indicator_names=indicator_names,
                                             kwargs=kwargs)

    def runUpdateLog(self):
        self.logFileKey = self.result_generator._get_current_log(
            self.logFileKey)

    def runErrorFromThread(self, errorMessage):
        QMessageBox.warning(self.mainwindow, 'Warning', errorMessage)
Пример #41
0
class VeroMixPlasmoid(plasmascript.Applet):
    VERSION="0.18.3"

    nowplaying_player_added = pyqtSignal(QString, QObject)
    nowplaying_player_removed = pyqtSignal(QString)
    nowplaying_player_dataUpdated = pyqtSignal(QString, dict)

    def __init__(self,parent,args=None):
        self.engine = None
        self.now_playing_engine = None
        self.louder_action_editor = None
        self.lower_action_editor = None
        self.mute_action_editor = None
        self.card_settings = None
        self.messageDialog = None
        self.messageOverlay = None
        self.config_ui = None
        plasmascript.Applet.__init__(self,parent)

    def init(self):
        plasmascript.Applet.init(self)
        KGlobal.locale().insertCatalog("veromix");
        if "usr/share/kde4" not in os.path.realpath(__file__):
            out = commands.getstatusoutput("xdg-icon-resource install --size 128 " + unicode(self.package().path()) + "contents/icons/veromix-plasmoid-128.png veromix-plasmoid")
            if out[0] == 0:
                print "veromix icon installed"
            else:
                print "Error installing veromix icon:", out

        LADSPAPresetLoader().install_ladspa_presets_if_needed()
        if self.is_ladspa_enabled():
            # force singleton initialisation
            LADSPAPresetLoader().presets()
            LADSPAEffects().effects()

        createDbusServiceDescription(self.package().path() + "/dbus-service/VeromixServiceQt.py", True)

        KGlobal.locale().insertCatalog("veromix")

        self.setHasConfigurationInterface(True)
        self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
        self.theme = Plasma.Svg(self)

        self.widget = VeroMix(self)
        self.widget.init()

        defaultSize =  QVariant(QSize (0,0))
        size = self.config().readEntry("size", defaultSize).toSize()
        if self.formFactor() == Plasma.Planar:
            self.widget.setMinimumSize(275,125)
        elif (size != defaultSize) :
            self.widget.setPreferredSize(size.width(), size.height())
        else:
            self.widget.setPreferredSize(470 ,145)

        self.connect(self.widget, SIGNAL("resized()"), self.dialogResized)
        #try:
        self.setGraphicsWidget(self.widget)
        self.applet.setPassivePopup(True)
        ## FIXME: see fixPopupcion
        self.setPopupIcon(KIcon("audio-volume-high"))
        #self.setPopupIcon("audio-volume-muted")
        # dont know why but adding it a second time helps (otherwise it
        # wont popup when you add it directly to the panel)
        self.setGraphicsWidget(self.widget)
        self.connect(self.applet, SIGNAL("appletDestroyed(Plasma::Applet*)"), self.doExit)
        self.setBackgroundHints(Plasma.Applet.StandardBackground)
        self.applyConfig()
        #except AttributeError , e:
            #print e
            #updateMetadataDesktop(self)

        self.initTooltip()
        self.initShortcuts()
        QTimer.singleShot(1000, self.fixPopupIcon)

    def initShortcuts(self):
        self.actionCollection = KActionCollection(self)
        #self.actionCollection.setConfigGlobal(True)
        self.louder_action = self.actionCollection.addAction("VeromixVolumeUp")
        self.louder_action.setText( i18n("Veromix volume up"))
        self.louder_action.setGlobalShortcut(KShortcut())
        self.louder_action.triggered.connect(self.widget.on_step_volume_up)

        self.lower_action = self.actionCollection.addAction("VeromixVolumeDown")
        self.lower_action.setText(i18n("Veromix volume down"))
        self.lower_action.setGlobalShortcut(KShortcut())
        self.lower_action.triggered.connect(self.widget.on_step_volume_down)

        self.mute_action = self.actionCollection.addAction("VeromixVolumeMute")
        self.mute_action.setText(i18n("Veromix toggle mute"))
        self.mute_action.setGlobalShortcut(KShortcut())
        self.mute_action.triggered.connect(self.widget.on_toggle_mute)

    def initTooltip(self):
        if (self.formFactor() != Plasma.Planar):
            self.tooltip = Plasma.ToolTipContent()
            self.tooltip.setImage(pixmapFromSVG("audio-volume-high"))
            self.tooltip.setMainText(i18n( "Main Volume"))
            #self.tooltip.setSubText("")
            Plasma.ToolTipManager.self().setContent(self.applet, self.tooltip)
            Plasma.ToolTipManager.self().registerWidget(self.applet)

    def updateIcon(self):
        icon_state = "audio-volume-muted"
        sink = self.widget.getDefaultSink()
        if sink == None:
            QTimer.singleShot(2000, self.fixPopupIcon)
            return
        vol = sink.get_volume()
        if sink.isMuted() :
            icon_state= "audio-volume-muted"
        else:
            if  vol == 0:
                icon_state = "audio-volume-muted"
            elif vol < 30:
                icon_state= "audio-volume-low"
            elif vol < 70:
                icon_state= "audio-volume-medium"
            else:
                icon_state= "audio-volume-high"
        self.setPopupIcon(icon_state)
        if (self.formFactor() != Plasma.Planar):
            self.tooltip.setImage(pixmapFromSVG(icon_state))
            ## FIXME this should better go to toolTipAboutToShow but is not working:
            # https://bugs.kde.org/show_bug.cgi?id=254764
            self.tooltip.setMainText(sink.name())
            self.tooltip.setSubText( str(vol) + "%")
            Plasma.ToolTipManager.self().setContent(self.applet, self.tooltip)

    def showTooltip(self):
        if self.get_show_toolip():
            Plasma.ToolTipManager.self().show(self.applet)

    @pyqtSlot(name="toolTipAboutToShow")
    def toolTipAboutToShow(self):
        pass

    ## FIXME Looks like a bug in plasma: Only when sending a
    # KIcon instance PopUpApplet acts like a Poppupapplet...
    def fixPopupIcon(self):
        #sink = self.widget.getDefaultSink()
        #if sink:
        self.updateIcon()

    def doExit(self):
        # prevent crash in plasmoidviewer
        self.widget.doExit()
        self.widget.deleteLater()

    def dialogResized(self):
        if self.isPopupShowing():
            self.config().writeEntry("size", QVariant(self.widget.size()))

    def query_application(self, query):
        #print "query: ", query
        if not query :
            return None
        needle = query.lower()
        if self.engine == None:
            self.engine = self.dataEngine("apps")
        for source in self.engine.sources():
            key = unicode(source).replace(".desktop", "")
            if  (0<=  key.find(needle)) or  (0 <= needle.find(key))  :
                #print "found: ",key,  needle , source
                result = self.engine.query(source)
                if QString("iconName") in result:
                    iconname = result[QString("iconName")].toString()
                    return iconname
        return None

    def wheelEvent(self, event):
        if event.orientation() == Qt.Horizontal:
            self.widget.on_step_volume((event.delta() < 0))
        else:
            self.widget.on_step_volume((event.delta() > 0))

    def mousePressEvent(self, event):
        if event.button() == Qt.MidButton:
            self.widget.on_toggle_mute()

    def createConfigurationInterface(self, parent):
        self.pp = parent
        self.config_widget = QWidget(parent)
        self.connect(self.config_widget, SIGNAL('destroyed(QObject*)'), self.configWidgetDestroyed)

        self.config_ui = uic.loadUi(str(self.package().filePath('ui', 'appearance.ui')), self.config_widget)
        self.config_ui.showBackground.setCurrentIndex( self.config().readEntry("background","2").toInt() [0])
        self.config_ui.showBackground.currentIndexChanged.connect(parent.settingsModified)
        if self.formFactor() != Plasma.Planar:
            self.config_ui.showBackground.setEnabled(False)

        self.config_ui.popupMode.setCurrentIndex( self.config().readEntry("popupMode",False).toInt() [0])
        self.config_ui.popupMode.currentIndexChanged.connect(parent.settingsModified)
        if self.formFactor() == Plasma.Planar:
            self.config_ui.popupMode.setEnabled(False)

        self.config_ui.useTabs.setChecked(self.useTabs())
        self.config_ui.useTabs.stateChanged.connect(parent.settingsModified)

        self.config_ui.show_tooltip.setChecked(self.get_show_toolip())
        self.config_ui.show_tooltip.stateChanged.connect(parent.settingsModified)

        self.config_ui.always_show_sources.setChecked(self.get_always_show_sources())
        self.config_ui.always_show_sources.stateChanged.connect(parent.settingsModified)

        self.config_ui.meter_visible.setChecked(self.is_meter_visible())
        self.config_ui.meter_visible.stateChanged.connect(parent.settingsModified)

        self.config_ui.expander_enabled.setChecked(self.is_expander_enabled())
        self.config_ui.expander_enabled.stateChanged.connect(parent.settingsModified)

        self.config_ui.unitvalues_visible.setChecked(self.is_slider_unit_value_visible())
        self.config_ui.unitvalues_visible.stateChanged.connect(parent.settingsModified)

        self.config_ui.version.setText(VeroMixPlasmoid.VERSION)
        parent.addPage(self.config_widget, i18n("Appearance"), "preferences-desktop-theme")

        self.mediaplayer_settings_widget = QWidget(parent)
        self.mediaplayer_settings_ui = uic.loadUi(str(self.package().filePath('ui', 'nowplaying.ui')), self.mediaplayer_settings_widget)

        self.mediaplayer_settings_ui.mediaplayerBlacklist.setPlainText(self.get_mediaplayer_blacklist_string())
        self.mediaplayer_settings_ui.runningMediaplayers.setPlainText(self.get_running_mediaplayers())
        self.mediaplayer_settings_ui.runningMediaplayers.setReadOnly(True)

        self.mediaplayer_settings_ui.use_nowplaying.setChecked(self.is_nowplaying_enabled())
        self.mediaplayer_settings_ui.use_nowplaying.stateChanged.connect(self.update_mediaplayer_settings_ui)
        self.mediaplayer_settings_ui.use_nowplaying.stateChanged.connect(parent.settingsModified)

        self.mediaplayer_settings_ui.use_mpris2.setChecked(self.is_mpris2_enabled())
        self.mediaplayer_settings_ui.use_mpris2.stateChanged.connect(self.update_mediaplayer_settings_ui)
        self.mediaplayer_settings_ui.use_mpris2.stateChanged.connect(parent.settingsModified)

        self.mediaplayer_settings_ui.show_albumart.setChecked(self.is_albumart_enabled())
        self.mediaplayer_settings_ui.show_albumart.stateChanged.connect(parent.settingsModified)

        parent.addPage(self.mediaplayer_settings_widget, i18n("Media Player Controls"), "applications-multimedia")

        #self.about_widget = QWidget(parent)
        #self.about_ui = uic.loadUi(str(self.package().filePath('ui', 'about.ui')), self.about_widget)
        #self.about_ui.version.setText(VeroMixPlasmoid.VERSION)
        #parent.addPage(self.about_widget, "About", "help-about")
        self.add_audio_settings(parent)
        self.add_ladspa_settings(parent)
        self.add_global_shortcut_page(parent)

        # FIXME KDE 4.6 workaround
        self.connect(parent, SIGNAL("okClicked()"), self.configChanged)
        self.connect(parent, SIGNAL("applyClicked()"), self.configChanged)
        self.connect(parent, SIGNAL("cancelClicked()"), self.configDenied)
        return self.config_widget

    def add_audio_settings(self, dialog):
        self.audio_settings_page = QWidget()
        layout = QGridLayout()
        self.audio_settings_page.setLayout(layout)

        self.max_volume_spinbox = QSpinBox()
        self.max_volume_spinbox.setRange(1,255)
        self.max_volume_spinbox.setSingleStep(1)
        self.max_volume_spinbox.setValue(self.get_max_volume_value())
        self.max_volume_spinbox.valueChanged.connect(dialog.settingsModified)
        layout.addWidget(QLabel(i18n("Max volume value")), 0,0)
        layout.addWidget(self.max_volume_spinbox, 0,1)

        self.automute_checkbox = QCheckBox()
        self.automute_checkbox.setChecked(self.get_auto_mute())
        self.automute_checkbox.stateChanged.connect(dialog.settingsModified)
        layout.addWidget(QLabel(i18n("Mute if volume reaches zero")), 1,0)
        layout.addWidget(self.automute_checkbox, 1,1)

        layout.addItem(QSpacerItem(0,20, QSizePolicy.Minimum,QSizePolicy.Fixed), 2,0)
        layout.addWidget(QLabel("<b>"+i18n("Sound Card Profiles")+"</b>"), 3,0)
        index=4
        self.card_settings = {}
        for card in self.widget.card_infos.values():
            combo = QComboBox()
            #self.automute_checkbox.setChecked(self.get_auto_mute())
            #print card.properties
            layout.addWidget(QLabel(card.properties[dbus.String("device.description")]), index,0)
            layout.addWidget(combo, index,1)
            index = index + 1

            self.card_settings[combo] = card
            profiles = card.get_profiles()
            active = card.get_active_profile_name()
            active_index = 0
            for profile in profiles:
                combo.addItem(profile.description)
                if active == profile.name:
                    active_index = profiles.index(profile)
            combo.setCurrentIndex(active_index)

        layout.addItem(QSpacerItem(0,0, QSizePolicy.Minimum,QSizePolicy.Expanding), index,0)
        dialog.addPage(self.audio_settings_page, i18n("Pulseaudio"), "audio-card")

    def add_ladspa_settings(self, dialog):
        self.ladspa_settings_page = QWidget()
        layout = QGridLayout()
        self.ladspa_settings_page.setLayout(layout)

        text = i18n("LADSPA is a standard for handling audio filters and effects. Every linux software archive offers a large number of effects - search for LADSPA to get more.\
            Not every effect is supported by Pulseaudio and others simple don't make sense (or create only noise).<br/><br/>\
            The following list shows all available effects on your system: Only checked effects will appear in the context-menu.")

        if not LADSPAEffects().ladspa_sdk_available():
            text = text + i18n("<br/><br/><b>Warning:</b> Cannot find the executables 'listplugins' and 'analyseplugin' which are required for dynamically detecting installed effects.<br/>\
               In OpenSUSE, Fedora and Arch Linux the package is named 'ladspa', in Debian/Ubuntu 'ladspa-sdk'.<br/><br/>")

        ladspa_intro = QLabel(text)

        ladspa_intro.setWordWrap(True)
        layout.addWidget(ladspa_intro, 0,0)

        self.ladspa_enabled_checkbox = QCheckBox()
        self.ladspa_enabled_checkbox.setText(i18n("Enable LADSPA effects."))
        self.ladspa_enabled_checkbox.setChecked(self.is_ladspa_enabled())
        self.ladspa_enabled_checkbox.stateChanged.connect(dialog.settingsModified)
        layout.addWidget(self.ladspa_enabled_checkbox, 1,0)

        self.effects_list_widget = QListWidget()
        layout.addWidget(self.effects_list_widget,2,0)
        self.effects_list_widget.itemClicked.connect(dialog.settingsModified)

        blacklisted = LADSPAEffects().blacklist()
        effects = LADSPAEffects().all_effects()
        for effect in effects:
            item = QListWidgetItem(effect["preset_name"])
            item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            if effect["preset_name"] in blacklisted:
                item.setCheckState(Qt.Unchecked)
            else:
                item.setCheckState(Qt.Checked)
            self.effects_list_widget.addItem(item)

        layout.addItem(QSpacerItem(0,0, QSizePolicy.Minimum,QSizePolicy.Expanding), 3,0)
        dialog.addPage(self.ladspa_settings_page, i18n("Effects / Equalizer"), "preferences-desktop-sound")

    # anybody knows how to remove/extend the default shortcuts page?
    def add_global_shortcut_page(self,dialog):
        self.kb_settings_page = QWidget()

        layout = QGridLayout()
        self.kb_settings_page.setLayout(layout)

        self.louder_action_editor = KKeySequenceWidget()
        self.louder_action_editor.setKeySequence( self.louder_action.globalShortcut().primary())
        self.louder_action_editor.keySequenceChanged.connect(dialog.settingsModified)
        layout.addWidget(QLabel(i18n("Veromix volume up")), 0,0)
        layout.addWidget(self.louder_action_editor, 0,1)

        self.lower_action_editor = KKeySequenceWidget()
        self.lower_action_editor.setKeySequence( self.lower_action.globalShortcut().primary())
        self.lower_action_editor.keySequenceChanged.connect(dialog.settingsModified)
        layout.addWidget(QLabel(i18n("Veromix volume down")), 1, 0)
        layout.addWidget(self.lower_action_editor, 1, 1)

        self.mute_action_editor = KKeySequenceWidget()
        self.mute_action_editor.setKeySequence( self.mute_action.globalShortcut().primary())
        self.mute_action_editor.keySequenceChanged.connect(dialog.settingsModified)
        layout.addWidget(QLabel(i18n("Veromix toggle  mute")), 2, 0)
        layout.addWidget(self.mute_action_editor, 2, 1)

        layout.addItem(QSpacerItem(0,0, QSizePolicy.Minimum,QSizePolicy.Expanding), 3,0)
        dialog.addPage(self.kb_settings_page, i18n("Volume Keyboard Shortcuts"), "preferences-desktop-keyboard")

    def configDenied(self):
        self.apply_nowplaying(self.is_nowplaying_enabled())
        self.apply_mpris2(self.is_mpris2_enabled())

    def configChanged(self):
        if self.config_ui:
            self.config().writeEntry("background",str(self.config_ui.showBackground.currentIndex()))
            self.config().writeEntry("popupMode", str(self.config_ui.popupMode.currentIndex()))
            tabs = self.useTabs()
            self.config().writeEntry("useTabs", bool(self.config_ui.useTabs.isChecked()))
            self.config().writeEntry("show_tooltip", bool(self.config_ui.show_tooltip.isChecked()))
            self.config().writeEntry("always_show_sources", bool(self.config_ui.always_show_sources.isChecked()))

            self.config().writeEntry("meter_visible", bool(self.config_ui.meter_visible.isChecked()))
            self.config().writeEntry("expander_enabled", bool(self.config_ui.expander_enabled.isChecked()))
            self.config().writeEntry("unitvalues_visible", bool(self.config_ui.unitvalues_visible.isChecked()))

            self.config().writeEntry("use_nowplaying", str(self.mediaplayer_settings_ui.use_nowplaying.isChecked()))
            self.config().writeEntry("use_mpris2", str(self.mediaplayer_settings_ui.use_mpris2.isChecked()))
            self.config().writeEntry("show_albumart", str(self.mediaplayer_settings_ui.show_albumart.isChecked()))

            #self.config().writeEntry("mpris2List",str(self.mediaplayer_settings_ui.mpris2List.toPlainText()).strip())
            self.config().writeEntry("nowplayingBlacklist",str(self.mediaplayer_settings_ui.mediaplayerBlacklist.toPlainText()).strip())

            self.config().writeEntry("max_volume", str(self.max_volume_spinbox.value()))
            self.config().writeEntry("auto_mute", str(self.automute_checkbox.isChecked()))

            self.config().writeEntry("ladspa_enabled",str(self.ladspa_enabled_checkbox.isChecked()))
            self.ladspa_save_effects_blacklist()
            if tabs != self.useTabs():
                self.widget.switchView()
        self.applyConfig()
        self.widget.on_update_configuration()

    def update_mediaplayer_settings_ui(self):
        enable = ( self.mediaplayer_settings_ui.use_nowplaying.isChecked() or self.mediaplayer_settings_ui.use_mpris2.isChecked())
        self.mediaplayer_settings_ui.mediaplayerBlacklist.setEnabled(enable)
        self.mediaplayer_settings_ui.mediaplayerBlacklistLabel.setEnabled(enable)
        self.mediaplayer_settings_ui.runningMediaplayers.setEnabled(enable)
        self.mediaplayer_settings_ui.runningMediaplayersLabel.setEnabled(enable)
        self.mediaplayer_settings_ui.runningMediaplayers.setPlainText(self.get_running_mediaplayers())
        self.mediaplayer_settings_ui.show_albumart.setEnabled(enable)

    def apply_nowplaying(self, enabled):
        self.disable_nowplaying()
        if enabled:
            self.init_nowplaying()

    def apply_mpris2(self, enabled):
        self.widget.pa.disable_mpris2()
        self.remove_mpris2_widgets()
        if enabled:
            self.widget.pa.enable_mpris2()
            self.init_running_mpris2()

    def applyConfig(self):
        self.apply_nowplaying(self.is_nowplaying_enabled())
        self.apply_mpris2(self.is_mpris2_enabled())

        if self.formFactor() == Plasma.Planar:
            bg = self.config().readEntry("background","2").toInt()[0]
            if bg == 0:
                self.setBackgroundHints(Plasma.Applet.NoBackground)
            elif bg == 1:
                self.setBackgroundHints(Plasma.Applet.TranslucentBackground)
            else:
                self.setBackgroundHints(Plasma.Applet.StandardBackground)

        mode = self.config().readEntry("popupMode",False).toInt()[0]
        if  mode== 0:
            self.setPassivePopup(False)
        elif mode == 1:
            self.setPassivePopup(True)
        else:
            self.setPassivePopup(True)

        if self.louder_action_editor:
            sequence = self.louder_action_editor.keySequence()
            if sequence != self.louder_action.globalShortcut().primary():
                self.louder_action.setGlobalShortcut(KShortcut(sequence), KAction.ActiveShortcut, KAction.NoAutoloading)
        if self.lower_action_editor:
            sequence = self.lower_action_editor.keySequence()
            if sequence != self.lower_action.globalShortcut().primary():
                self.lower_action.setGlobalShortcut(KShortcut(sequence), KAction.ActiveShortcut, KAction.NoAutoloading)
        if self.mute_action_editor:
            sequence = self.mute_action_editor.keySequence()
            if sequence != self.mute_action.globalShortcut().primary():
                self.mute_action.setGlobalShortcut(KShortcut(sequence), KAction.ActiveShortcut, KAction.NoAutoloading)

        if self.card_settings:
            for combo in self.card_settings.keys():
                card = self.card_settings[combo]
                for profile in card.profiles:
                    if combo.currentText() == profile.description:
                        self.widget.pa.set_card_profile(card.index, profile.name)

        self.update()

    def configWidgetDestroyed(self):
        self.config_widget = None
        self.config_ui = None

    def useTabs(self):
        return self.config().readEntry("useTabs",True).toBool()

    def is_meter_visible(self):
        return self.config().readEntry("meter_visible",False).toBool()

    def get_auto_mute(self):
        return self.config().readEntry("auto_mute",False).toBool()

    def get_show_toolip(self):
        return self.config().readEntry("show_tooltip",True).toBool()

    def get_always_show_sources(self):
        return self.config().readEntry("always_show_sources",True).toBool()

    def get_max_volume_value(self):
        default = 100
        return self.config().readEntry("max_volume",default).toInt()[0]

    def is_slider_unit_value_visible(self):
        return self.config().readEntry("unitvalues_visible",True).toBool()

    def is_ladspa_enabled(self):
        return self.config().readEntry("ladspa_enabled",False).toBool()

    def ladspa_save_effects_blacklist(self):
        blacklisted = []
        for i in range(0,self.effects_list_widget.count()):
            item = self.effects_list_widget.item(i)
            if not item.checkState():
                blacklisted.append(str(item.text()))
        LADSPAEffects().write_blacklist(blacklisted)

### now playing

    def is_nowplaying_enabled(self):
        return self.config().readEntry("use_nowplaying",False).toBool()

    def is_mpris2_enabled(self):
        return self.config().readEntry("use_mpris2",True).toBool()

    def is_albumart_enabled(self):
        return self.config().readEntry("show_albumart",True).toBool()

    def is_expander_enabled(self):
        return self.config().readEntry("expander_enabled",True).toBool()

    def disable_nowplaying(self):
        for player in self.widget.get_mediaplayer_widgets():
            if player.is_nowplaying_player():
                self.on_nowplaying_player_removed(player.controller_name())
        self.now_playing_engine = None

    def remove_mpris2_widgets(self):
        for player in self.widget.get_mediaplayer_widgets():
            if player.is_mpris2_player():
                self.on_mpris2_removed(player.controller_name())

    def init_nowplaying(self):
        self.now_playing_engine = self.dataEngine('nowplaying')
        self.connect(self.now_playing_engine, SIGNAL('sourceAdded(QString)'), self.on_nowplaying_player_added)
        self.connect(self.now_playing_engine, SIGNAL('sourceRemoved(QString)'), self.on_nowplaying_player_removed)
        self.connect_to_nowplaying_engine()

    def init_running_mpris2(self):
        for controller in self.widget.pa.get_mpris2_players():
            v= controller.name()
            if self.in_mediaplayer_blacklist(v):
                return
            self.nowplaying_player_added.emit(controller.name(), controller)

    def connect_to_nowplaying_engine(self):
        # get sources and connect
        for source in self.now_playing_engine.sources():
            self.on_nowplaying_player_added(source)

    def on_nowplaying_player_added(self, player):
        if player == "players":
            # FIXME 4.6 workaround
            return
        if self.in_mediaplayer_blacklist(player):
            return
        self.now_playing_engine.disconnectSource(player, self)
        self.now_playing_engine.connectSource(player, self, 2000)
        controller = self.now_playing_engine.serviceForSource(player)
        self.nowplaying_player_added.emit(player, NowPlayingController(self.widget,controller))

    def in_mediaplayer_blacklist(self,player):
        for entry in self.get_mediaplayer_blacklist():
            if str(player).find(entry) == 0:
                return True
        return False

    def on_nowplaying_player_removed(self, player):
        if self.now_playing_engine:
            self.now_playing_engine.disconnectSource(player, self)
            self.nowplaying_player_removed.emit(player)

    def on_mpris2_removed(self, player):
        self.nowplaying_player_removed.emit(player)

    def get_running_mediaplayers(self):
        val = "nowplaying:\n"
        engine =  self.now_playing_engine
        if engine == None:
            engine = self.dataEngine('nowplaying')
        for source in engine.sources():
            val += source + "\n"
        val += "\nmpris2:\n"
        for controller in self.widget.pa.get_mpris2_players():
            val += controller.name() + "\n"
        return val

    def get_mediaplayer_blacklist(self):
        return self.get_mediaplayer_blacklist_string().split("\n")

    def get_mediaplayer_blacklist_string(self):
        default =  "org.mpris.bangarang"
        return self.config().readEntry("nowplayingBlacklist",default).toString()

    @pyqtSignature('dataUpdated(const QString&, const Plasma::DataEngine::Data&)')
    def dataUpdated(self, sourceName, data):
        self.nowplaying_player_dataUpdated.emit(sourceName, data)

## Modal Widget

    def showModalWidget(self,mainWidget):
        #mainWidget.widgetClose.connect(self.destroyMessageOverlay)
        if self.messageOverlay:
            return
        if self.messageDialog:
            return

        corona = self.scene()
        mainWidget.adjustSize()
        hint = mainWidget.preferredSize()
        if (hint.height() > self.widget.size().height()) or (hint.width() > self.widget.size().width()):
            ## either a collapsed popup in h/v form factor or just too small,
            ## so show it in a dialog associated with ourselves
            #pass
            if (corona):
                corona.addOffscreenWidget(mainWidget)

            if (self.messageDialog):
                pass
            else:
                self.messageDialog = Plasma.Dialog()

            self.messageDialog.setGraphicsWidget(mainWidget)
            mainWidget.setParentItem(self.messageDialog.graphicsWidget ())
        else:
            self.messageOverlay = self.createMessageOverlay()
            self.formatOverlay()
            self.messageOverlay.opacity = 0.8
            mainWidget.setParentItem(self.messageOverlay)
            l = QGraphicsLinearLayout(self.messageOverlay)
            l.addItem(mainWidget)

        if self.messageDialog:
            pos = self.geometry().topLeft().toPoint()
            if (corona):
                pos = corona.popupPosition(self.applet, self.messageDialog.size())

            self.messageDialog.move(pos)
            #self.locationToDirection(self.location())
            self.messageDialog.animatedShow(Plasma.Direction(0))
            self.hidePopup()
        else:
            self.messageOverlay.show()

    def createMessageOverlay(self):
        if self.messageOverlay == None:
            messageOverlay = QGraphicsWidget(self.widget)
            return messageOverlay

    def formatOverlay(self):
        self.messageOverlay.resize(self.widget.contentsRect().size())
        self.messageOverlay.setPos(self.widget.contentsRect().topLeft())

        zValue = 100
        for child in  self.widget.children():
            if (child.zValue() > zValue):
                zValue = child.zValue() + 1
        self.messageOverlay.setZValue(zValue)

    def destroyMessageOverlay(self):
        if self.messageDialog != None:
            #Plasma::locationToInverseDirection(q->location())
            self.messageDialog.animatedHide(Plasma.Direction(0))
            self.messageDialog.deleteLater()
            self.messageDialog.hide()
            self.messageDialog = None
            self.showPopup(0)

        if self.messageOverlay == None:
            return

        self.messageOverlay.hide()
        self.messageOverlay = None
Пример #42
0
class GroupsModify(PyDialog):
    """
    +--------------------------+
    |     Groups : Modify      |
    +--------------------------+
    |                          |
    |  Name        xxx Default |
    |  Coords      xxx Default |
    |  Elements    xxx Default |
    |  Color       xxx Default |
    |  Add         xxx Add     |
    |  Remove      xxx Remove  |
    |                          |
    |      Set  OK Cancel      |
    +--------------------------+
    """
    def __init__(self, data, win_parent=None, group_active='main'):
        PyDialog.__init__(self, data, win_parent)
        self.set_font_size(data['font_size'])
        self._updated_groups = False

        #self.out_data = data

        #print(data)
        keys = []
        self.keys = [
            group.name for key, group in sorted(iteritems(data))
            if isinstance(key, int)
        ]
        self.active_key = self.keys.index(group_active)

        group_obj = data[self.active_key]
        name = group_obj.name

        self.imain = 0
        self.nrows = len(self.keys)

        self._default_name = group_obj.name
        self._default_elements = group_obj.element_str
        self.elements_pound = group_obj.elements_pound

        self.table = QListWidget(parent=None)
        self.table.clear()
        self.table.addItems(self.keys)

        self.setWindowTitle('Groups: Modify')
        self.create_widgets()
        self.create_layout()
        self.set_connections()

        self.on_set_as_main()

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

        # elements
        self.elements = QLabel("Element IDs:")
        self.elements_edit = QLineEdit(str(self._default_elements).strip())
        self.elements_button = QPushButton("Default")

        # add
        self.add = QLabel("Add Elements:")
        self.add_edit = QElementEdit(self, str(''))
        self.add_button = QPushButton("Add")

        # remove
        self.remove = QLabel("Remove Elements:")
        self.remove_edit = QElementEdit(self, str(''))
        self.remove_button = QPushButton("Remove")

        # applies a unique implicitly
        self.eids = parse_patran_syntax(str(self._default_elements),
                                        pound=self.elements_pound)

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

        self.set_as_main_button = QPushButton("Set As Main")
        self.create_group_button = QPushButton('Create New Group')
        self.delete_group_button = QPushButton('Delete Group')

        self.name.setEnabled(False)
        self.name_set.setEnabled(False)
        self.name_edit.setEnabled(False)
        self.name_button.setEnabled(False)
        self.elements.setEnabled(False)
        self.elements_button.setEnabled(False)
        self.elements_edit.setEnabled(False)
        self.add.setEnabled(False)
        self.add_button.setEnabled(False)
        self.add_edit.setEnabled(False)
        self.remove.setEnabled(False)
        self.remove_button.setEnabled(False)
        self.remove_edit.setEnabled(False)
        self.delete_group_button.setEnabled(False)
        #self.apply_button.setEnabled(False)
        #self.ok_button.setEnabled(False)

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

        grid.addWidget(self.elements, 2, 0)
        grid.addWidget(self.elements_edit, 2, 1)
        grid.addWidget(self.elements_button, 2, 2)

        grid.addWidget(self.add, 4, 0)
        grid.addWidget(self.add_edit, 4, 1)
        grid.addWidget(self.add_button, 4, 2)

        grid.addWidget(self.remove, 5, 0)
        grid.addWidget(self.remove_edit, 5, 1)
        grid.addWidget(self.remove_button, 5, 2)

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

        main_create_delete = QHBoxLayout()
        main_create_delete.addWidget(self.set_as_main_button)
        main_create_delete.addWidget(self.create_group_button)
        main_create_delete.addWidget(self.delete_group_button)

        vbox = QVBoxLayout()
        vbox.addWidget(self.table)
        vbox.addLayout(grid)
        vbox.addLayout(main_create_delete)
        vbox.addStretch()
        vbox.addLayout(ok_cancel_box)
        self.setLayout(vbox)

    def on_set_name(self):
        name = str(self.name_edit.text()).strip()
        if name not in self.keys:
            self.name_edit.setStyleSheet("QLineEdit{background: white;}")
            group = self.out_data[self.active_key]
            group.name = name
            self.keys[self.active_key] = name
            self.recreate_table()
        elif name != self.keys[self.active_key]:
            self.name_edit.setStyleSheet("QLineEdit{background: red;}")
        elif name == self.keys[self.active_key]:
            self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    def set_connections(self):
        self.name_set.clicked.connect(self.on_set_name)
        self.name_button.clicked.connect(self.on_default_name)
        self.elements_button.clicked.connect(self.on_default_elements)

        self.add_button.clicked.connect(self.on_add)
        self.remove_button.clicked.connect(self.on_remove)
        self.table.itemClicked.connect(self.on_update_active_key)
        self.ok_button.clicked.connect(self.on_ok)

        self.set_as_main_button.clicked.connect(self.on_set_as_main)
        self.create_group_button.clicked.connect(self.on_create_group)
        self.delete_group_button.clicked.connect(self.on_delete_group)

    def on_create_group(self):
        irow = self.nrows
        new_key = 'Group %s' % irow
        while new_key in self.keys:
            irow += 1
            new_key = 'Group %s' % irow
        irow = self.nrows

        self.keys.append(new_key)
        group = Group(new_key,
                      element_str='',
                      elements_pound=self.elements_pound,
                      editable=True)
        self.out_data[irow] = group

        self.table.reset()
        self.table.addItems(self.keys)
        self.nrows += 1

        #----------------------------------
        # update internal parameters
        #self.out_data = items
        if self.imain > self.active_key:
            self.imain += 1

        #make the new group the default
        self.active_key = self.nrows - 1

        self.keys = [
            group.name for key, group in sorted(iteritems(self.out_data))
            if isinstance(key, int)
        ]
        self.recreate_table()

    def recreate_table(self):
        # update gui
        self.table.clear()
        self.table.addItems(self.keys)
        item = self.table.item(self.imain)

        bold = QtGui.QFont()
        bold.setBold(True)
        bold.setItalic(True)
        item.setFont(bold)
        self.table.update()

        # update key
        name = self.keys[self.active_key]
        self._update_active_key_by_name(name)

    def on_delete_group(self):
        if self.active_key == 0:
            return

        #self.deleted_groups.add(self.imain)
        items = {}
        j = 0
        for i, key in sorted(iteritems(self.out_data)):
            if isinstance(i, int):
                continue
            if i != self.active_key:
                items[j] = key
                j += 1

        # update internal parameters
        self.out_data = items
        if self.imain >= self.active_key:
            self.imain = max(0, self.imain - 1)
        self.active_key = max(0, self.active_key - 1)
        self.nrows -= 1
        self.keys = [group.name for key, group in sorted(iteritems(items))]

        self.recreate_table()

        # update key
        name = self.keys[self.active_key]
        self._update_active_key_by_name(name)

    def on_set_as_main(self):
        bold = QtGui.QFont()
        bold.setBold(True)
        bold.setItalic(True)

        normal = QtGui.QFont()
        normal.setBold(False)
        normal.setItalic(False)

        obj = self.table.item(self.imain)
        obj.setFont(normal)

        self.imain = self.active_key
        obj = self.table.item(self.imain)
        obj.setFont(bold)
        group = self.out_data[self.imain]
        self._default_elements = group.element_str
        self._default_name = group.name
        self.on_update_main()

    def on_update_main(self):
        """adds/removes the elements to the main actor when add/remove is pressed"""
        group = self.out_data[self.imain]
        if self._default_name == group.name and self.win_parent is not None:
            # we're not testing the menu
            self.win_parent.post_group(group)

    def closeEvent(self, event):
        self.out_data['close'] = True
        event.accept()

    def on_add(self):
        eids, is_valid = self.check_patran_syntax(self.add_edit,
                                                  pound=self.elements_pound)
        #adict, is_valid = self.check_patran_syntax_dict(self.add_edit)
        if not is_valid:
            #self.add_edit.setStyleSheet("QLineEdit{background: red;}")
            return

        self.eids = unique(hstack([self.eids, eids]))
        #self.eids = _add(adict, ['e', 'elem', 'element'], self.eids)
        #self.cids = _add(adict, ['c', 'cid', 'coord'], self.cids)
        self._apply_cids_eids()

        self.add_edit.clear()
        self.add_edit.setStyleSheet("QLineEdit{background: white;}")
        self.on_update_main()

    def _apply_cids_eids(self):
        #ctext = _get_collapsed_text(self.cids)
        etext = _get_collapsed_text(self.eids)

        #self.coords_edit.setText(str(ctext.lstrip()))
        self.elements_edit.setText(str(etext.lstrip()))
        self.out_data[self.active_key].element_ids = self.eids

    def on_remove(self):
        eids, is_valid = self.check_patran_syntax(self.remove_edit)
        #adict, is_valid = self.check_patran_syntax_dict(self.remove_edit)
        if not is_valid:
            #self.remove_edit.setStyleSheet("QLineEdit{background: red;}")
            return

        #self.eids = _remove(adict, ['e', 'elem', 'element'], self.eids)
        #self.cids = _remove(adict, ['c', 'cid', 'coord'], self.cids)
        self.eids = setdiff1d(self.eids, eids)
        self._apply_cids_eids()

        self.remove_edit.clear()
        self.remove_edit.setStyleSheet("QLineEdit{background: white;}")
        self.on_update_main()

    def on_default_name(self):
        name = str(self._default_name)
        self.name_edit.setText(name)
        self.name_edit.setStyleSheet("QLineEdit{background: white;}")

    def on_default_elements(self):
        element_str = str(self._default_elements)
        self.elements_edit.setText(element_str)
        self.elements_edit.setStyleSheet("QLineEdit{background: white;}")
        group = self.out_data[self.active_key]
        group.element_str = element_str

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

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

        if self._default_name != text:
            if self._default_name in self.out_data:
                cell.setStyleSheet("QLineEdit{background: white;}")
                return text, True
            else:
                cell.setStyleSheet("QLineEdit{background: red;}")
                return None, False

    def on_validate(self):
        name, flag0 = self.check_name(self.name_edit)
        elements, flag1 = self.check_patran_syntax(self.elements_edit,
                                                   pound=self.elements_pound)
        #coords_value, flag2 = self.check_patran_syntax(self.coords_edit,
        #pound=self.coords_pound)

        if all([flag0, flag1]):
            self._default_name = name
            self._default_elements = self.eids
            self.out_data['clicked_ok'] = True
            self.out_data['close'] = True
            return True
        return False

    def on_apply(self, force=False):
        passed = self.on_validate()
        if passed or force:
            self.win_parent._apply_modify_groups(self.out_data)
        return passed

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

    def on_cancel(self):
        self.out_data['close'] = True
        self.close()

    def on_update_active_key(self, index):
        self.update_active_key(index)
        #str(index.text())

    def update_active_key(self, index):
        #old_obj = self.out_data[self.imain]
        name = str(index.text())
        self._update_active_key_by_name(name)

    def _update_active_key_by_name(self, name):
        if name in self.keys:
            self.active_key = self.keys.index(name)
        else:
            # we (hopefully) just removed a row
            #self.active_key = self.keys[self.active_key]
            pass

        self.name_edit.setText(name)
        obj = self.out_data[self.active_key]

        self.eids = parse_patran_syntax(obj.element_str,
                                        pound=obj.elements_pound)
        self._default_elements = obj.element_str
        self._default_name = name
        self._apply_cids_eids()

        self.set_as_main_button.setEnabled(True)
        if name in ['main', 'anti-main']:
            self.name.setEnabled(False)
            self.name_set.setEnabled(False)
            self.name_edit.setEnabled(False)
            self.name_button.setEnabled(False)
            self.elements.setEnabled(False)
            self.elements_button.setEnabled(False)
            self.elements_edit.setEnabled(False)
            self.add.setEnabled(False)
            self.add_button.setEnabled(False)
            self.add_edit.setEnabled(False)
            self.remove.setEnabled(False)
            self.remove_button.setEnabled(False)
            self.remove_edit.setEnabled(False)
            self.delete_group_button.setEnabled(False)
            if name == 'anti-main':
                self.set_as_main_button.setEnabled(False)
            #self.apply_button.setEnabled(False)
            #self.ok_button.setEnabled(False)
        else:
            self.name.setEnabled(True)
            self.name_set.setEnabled(True)
            self.name_edit.setEnabled(True)
            self.name_button.setEnabled(True)
            self.elements.setEnabled(True)
            self.elements_button.setEnabled(True)

            self.add.setEnabled(True)
            self.add_button.setEnabled(True)
            self.add_edit.setEnabled(True)
            self.remove.setEnabled(True)
            self.remove_button.setEnabled(True)
            self.remove_edit.setEnabled(True)
            self.delete_group_button.setEnabled(True)
Пример #43
0
class CheckList(HelpedWidget):
    def __init__(self, model, label="", help_link=""):
        HelpedWidget.__init__(self, "", help_link)

        layout = QVBoxLayout()

        widget = QWidget()
        widget.setLayout(layout)

        self.checkAllButton = QToolButton()
        self.checkAllButton.setIcon(resourceIcon("checked"))
        self.checkAllButton.setIconSize(QSize(16, 16))
        self.checkAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.checkAllButton.setAutoRaise(True)
        self.checkAllButton.setToolTip("Select all")

        self.uncheckAllButton = QToolButton()
        self.uncheckAllButton.setIcon(resourceIcon("notchecked"))
        self.uncheckAllButton.setIconSize(QSize(16, 16))
        self.uncheckAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self.uncheckAllButton.setAutoRaise(True)
        self.uncheckAllButton.setToolTip("Unselect all")

        self.list = QListWidget()
        self.list.setContextMenuPolicy(Qt.CustomContextMenu)
        self.list.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.search_box = SearchBox()

        check_button_layout = QHBoxLayout()

        check_button_layout.setMargin(0)
        check_button_layout.setSpacing(0)
        check_button_layout.addWidget(QLabel(label))
        check_button_layout.addStretch(1)
        check_button_layout.addWidget(self.checkAllButton)
        check_button_layout.addWidget(self.uncheckAllButton)

        layout.addLayout(check_button_layout)
        layout.addWidget(self.list)
        layout.addWidget(self.search_box)

        self.addWidget(widget)

        self.connect(self.checkAllButton, SIGNAL('clicked()'), self.checkAll)
        self.connect(self.uncheckAllButton, SIGNAL('clicked()'),
                     self.uncheckAll)
        self.connect(self.list, SIGNAL('itemChanged(QListWidgetItem*)'),
                     self.itemChanged)
        self.search_box.filterChanged.connect(self.filterList)
        # self.connect(self.search_box, SIGNAL('filterChanged(str)'), self.filterList)

        self.connect(self.list, SIGNAL('customContextMenuRequested(QPoint)'),
                     self.showContextMenu)

        assert isinstance(model, (SelectableModelMixin, ListModelMixin))
        self.model = model
        self.model.observable().attach(
            SelectableModelMixin.SELECTION_CHANGED_EVENT, self.modelChanged)
        self.model.observable().attach(ListModelMixin.LIST_CHANGED_EVENT,
                                       self.modelChanged)
        self.modelChanged()

    def itemChanged(self, item):
        """@type item: QListWidgetItem"""
        if item.checkState() == Qt.Checked:
            self.model.selectValue(str(item.text()))
        elif item.checkState() == Qt.Unchecked:
            self.model.unselectValue(str(item.text()))
        else:
            raise AssertionError("Unhandled checkstate!")

    def modelChanged(self):
        self.list.clear()

        items = self.model.getList()

        for item in items:
            list_item = QListWidgetItem(item)
            list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)

            if self.model.isValueSelected(item):
                list_item.setCheckState(Qt.Checked)
            else:
                list_item.setCheckState(Qt.Unchecked)

            self.list.addItem(list_item)

        self.filterList(self.search_box.filter())

    def setSelectionEnabled(self, enabled):
        self.setEnabled(enabled)
        self.checkAllButton.setEnabled(enabled)
        self.uncheckAllButton.setEnabled(enabled)

    def filterList(self, filter):
        filter = filter.lower()

        for index in range(0, self.list.count()):
            item = self.list.item(index)
            text = str(item.text()).lower()

            if filter == "":
                item.setHidden(False)
            elif filter in text:
                item.setHidden(False)
            else:
                item.setHidden(True)

    def checkAll(self):
        self.model.selectAll()

    def uncheckAll(self):
        self.model.unselectAll()

    def checkSelected(self):
        items = []
        for item in self.list.selectedItems():
            items.append(str(item.text()))

        for item in items:
            self.model.selectValue(item)

    def uncheckSelected(self):
        items = []
        for item in self.list.selectedItems():
            items.append(str(item.text()))

        for item in items:
            self.model.unselectValue(item)

    def showContextMenu(self, point):
        p = self.list.mapToGlobal(point)
        menu = QMenu()
        check_selected = menu.addAction("Check selected")
        uncheck_selected = menu.addAction("Uncheck selected")
        menu.addSeparator()
        clear_selection = menu.addAction("Clear selection")

        selected_item = menu.exec_(p)

        if selected_item == check_selected:
            self.checkSelected()
        elif selected_item == uncheck_selected:
            self.uncheckSelected()
        elif selected_item == clear_selection:
            self.list.clearSelection()
Пример #44
0
class MiniCalculation(QDialog):
    AppName = u"迷你计算器"

    def __init__(self, parent=None):
        super(MiniCalculation, self).__init__(parent)
        self.btnHelpState = False
        self.setWindowTitle(MiniCalculation.AppName)
        self.txtBrower = QTextBrowser()
        self.txtLine = QLineEdit()
        self.txtLine.setPlaceholderText(u"请输入表达式,按回车结束...")

        self.btnCal = QPushButton(u"计算")
        self.btnClear = QPushButton(u"清空")
        self.btnHelp = QPushButton(u"特殊函数表>>")
        self.btnHelp.setCheckable(True)
        self.btnHelp.setChecked(True)

        mathList = [s for s in dir(math) if not s.startswith("__")]
        self.listWidget = QListWidget()
        self.listWidget.addItems(mathList)
        for i in range(len(mathList)):
            item = self.listWidget.item(i)
            strFun = item.text() + '.__doc__'
            item.setToolTip(eval(str(strFun)))
        self.listWidget.setMaximumWidth(100)

        midLay = QHBoxLayout()
        midLay.addWidget(self.btnCal)
        midLay.addWidget(self.btnClear)
        midLay.addStretch()
        midLay.addWidget(self.btnHelp)

        bottomLay = QHBoxLayout()
        bottomLay.addWidget(self.txtBrower)
        bottomLay.addWidget(self.listWidget)

        lay = QVBoxLayout()
        lay.addWidget(self.txtLine)
        lay.addItem(midLay)
        lay.addItem(bottomLay)

        self.resize(450, 300)
        self.setLayout(lay)
        self.updateUI()

        self.btnCal.clicked.connect(self.btnCalClicked)
        self.btnClear.clicked.connect(self.txtLine.clear)
        self.btnClear.clicked.connect(self.txtBrower.clear)
        self.btnHelp.clicked.connect(self.updateUI)
        self.listWidget.itemDoubleClicked.connect(self.listItemDoubleClicked)

    def updateUI(self):
        state = not self.btnHelp.isChecked()
        self.listWidget.setHidden(state)
        text = u"特殊函数表>>" if state else u"特殊函数表<<"
        self.btnHelp.setText(text)

    def btnCalClicked(self):
        try:
            txt = str(self.txtLine.text())
            self.txtBrower.append("%s = <b>%s</b>" % (txt, eval(txt)))
        except UnicodeEncodeError:
            QMessageBox.warning(self,u"QData -- 迷你计算机",
                    u"表达式中存在中文或全角字符\n",
                    QMessageBox.Ok)
        except:
            self.txtBrower.append("<font color=red>%s <b>is invalid</b>" % txt)

    def listItemDoubleClicked(self):
        item = self.listWidget.currentItem()
        self.txtLine.insert(item.text())
        self.txtLine.setFocus()
Пример #45
0
class NotebookListDialog(QDialog):
    """ Functions to display, create, remove, modify notebookList """
    def __init__(self, parent=None):
        super(NotebookListDialog, self).__init__(parent)

        self.notebookList = QListWidget()
        self.moveUp = QPushButton('<<')
        self.moveDown = QPushButton('>>')
        self.add = QPushButton('Add')
        self.remove = QPushButton('Remove')
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                          | QDialogButtonBox.Cancel)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        layout = QGridLayout()
        layout.addWidget(self.notebookList, 0, 0, 4, 6)
        layout.addWidget(self.moveUp, 1, 6)
        layout.addWidget(self.moveDown, 2, 6)
        layout.addWidget(self.add, 4, 0)
        layout.addWidget(self.remove, 4, 1)
        layout.addWidget(self.buttonBox, 4, 5, 1, 2)
        self.setLayout(layout)

        self.notebookList.setItemDelegate(ListDelegate(self.notebookList))

        self.notebookList.currentRowChanged.connect(self.updateUi)
        self.add.clicked.connect(self.actionAdd)
        self.remove.clicked.connect(self.actionRemove)
        self.moveUp.clicked.connect(self.moveItemUp)
        self.moveDown.clicked.connect(self.moveItemDown)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.initList()

    def initList(self):
        self.notebookList.clear()
        notebooks = Mikibook.read()
        for nb in notebooks:
            item = QListWidgetItem()
            item.setData(Qt.DisplayRole, nb[0])
            item.setData(Qt.UserRole, nb[1])
            self.notebookList.addItem(item)

        self.updateUi(len(notebooks) != 0)
        self.notebookList.setCurrentRow(0)
        # QListWidgetItem(nb, self.notebookList)

    def updateUi(self, row):
        flag = (row != -1)
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(flag)
        self.remove.setEnabled(flag)
        self.moveUp.setEnabled(flag)
        self.moveDown.setEnabled(flag)

    def actionAdd(self):
        Mikibook.create()
        self.initList()
        count = self.notebookList.count()
        self.notebookList.setCurrentRow(count - 1)

    def actionRemove(self):
        item = self.notebookList.currentItem()
        row = self.notebookList.currentRow()
        name = item.data(Qt.DisplayRole)
        path = item.data(Qt.UserRole)
        self.notebookList.takeItem(row)

        Mikibook.remove(name, path)

    def moveItemUp(self):
        item = self.notebookList.currentItem()
        row = self.notebookList.currentRow()
        if row != 0:
            # self.notebookList.removeItemWidget(item)
            self.notebookList.takeItem(row)
            self.notebookList.insertItem(row - 1, item)
            self.notebookList.setCurrentRow(row - 1)

    def moveItemDown(self):
        item = self.notebookList.currentItem()
        row = self.notebookList.currentRow()
        count = self.notebookList.count()
        if row != count - 1:
            self.notebookList.takeItem(row)
            self.notebookList.insertItem(row + 1, item)
            self.notebookList.setCurrentRow(row + 1)

    def accept(self):
        notebookPath = self.notebookList.currentItem().data(Qt.UserRole)
        notebookName = self.notebookList.currentItem().data(Qt.DisplayRole)
        settings = Setting([[notebookName, notebookPath]])
        window = mikidown.MikiWindow(settings)
        window.show()
        count = self.notebookList.count()
        notebooks = []
        for i in range(count):
            name = self.notebookList.item(i).data(Qt.DisplayRole)
            path = self.notebookList.item(i).data(Qt.UserRole)
            notebooks.append([name, path])
            Mikibook.write(notebooks)

        QDialog.accept(self)
Пример #46
0
class LoginListWindow(QDialog):
        class _Dialog(QDialog):
                def __init__(self,parent=None):
                        super(QDialog,self).__init__(parent)
                        self.value=''
                        self.edit=QLineEdit()
                        self.layout=QHBoxLayout(self)
                        self.button_layout=QVBoxLayout()
                        self.setWindowTitle(u"输入名字")
                        self.ok_button=QPushButton(u"确定")
                        self.cancel_button=QPushButton(u"取消")
                        self.layout.addWidget(self.edit)
                        self.layout.addLayout(self.button_layout)
                        self.button_layout.addWidget(self.ok_button)
                        self.button_layout.addWidget(self.cancel_button)
                        QObject.connect(self.ok_button,SIGNAL("clicked()"),self.ok)
                        QObject.connect(self.cancel_button,SIGNAL("clicked()"),self.close)
                def ok(self):
                        self.value=unicode(self.edit.text())
                        self.close()
                def getvalue(self,value):
                        self.value=value
                        self.edit.setText(value)
                        self.exec_()
                        return self.value
        class _Item(QListWidgetItem):
                def __init__(self,name,url,cookiefile=None,parent=None):
                        super(QListWidgetItem,self).__init__(name,parent)
                        #~ super(QObject,self).__init__(parent)
                        self.loggedin=False
                        #~ print name,cookiefile
                        self.cookiefile=cookiefile=name+".cookies" if cookiefile is None else cookiefile
                        self.name=name
                        self.cookiejar=None
                        self.view=LoginWindow(url,cookiefile)
                        self.view.setWindowTitle(u"登录:"+name)
                        self.dialog=LoginListWindow._Dialog(parent)
                        self.show_msg=pyqtSlot(unicode,unicode)
                        #~ self.connect(self,SIGNAL("show_msg(unicode,unicode)"),self,SLOT("showMessage(unicode,unicode)"))
                def login(self):
                        #~ print True
                        #~ self.emit(SIGNAL("send_msg"),u"logging")
                        self.showLogging()
                        #~ print self.cookiefile
                        cj=check_login(self.cookiefile)
                        if cj is None:
                                cj=self.view.login()
                        uname=get_username_by_cookiejar(cj,ignore=True)
                        if uname:
                                self.showSecceeded("%s<%s>"%(self.name,uname))
                                #~ self.emit(SIGNAL("send_msg"),u"succeeded",u"%s<%s>"%(self.name,uname))
                                self.loggedin=True
                                self.cookiejat=cj
                                return cj
                        else:
                                self.showFailed()
                                #~ self.emit(SIGNAL("send_msg"),u"failed")
                                return None
                def editName(self):
                        self.name=self.dialog.getvalue(self.name)
                        self.setText(self.name)
                        return self.name
                def editCookies(self):
                        self.cookiejar=self.view.login()
                        return self.cookiejar
                @pyqtSlot(unicode,unicode)
                def showMessage(self,type_,name):
                        print type_
                        {
                                'logging':self.showLogging,
                                'secceeded':self.showSecceeded,
                                'failed':self.showFailed,
                        }[type_](name)
                def showLogging(self,name=None):
                        self.setText((name if name is not None else self.name)+u"[登录中]")
                        self.setTextColor(QColor("yellow"))
                def showSecceeded(self,name=None):
                        self.setText((name if name is not None else self.name)+u"[成功]")
                        self.setTextColor(QColor("green"))
                def showFailed(self,name=None):
                        self.setText((name if name is not None else self.name)+u"[失败]")
                        self.setTextColor(QColor("red"))
        class _Thread(QThread):
                def __init__(self,func,*args,**kwargs):
                        self.func=func
                        self.args=args
                        self.kwargs=kwargs
                        super(QThread,self).__init__(None)
                def run(self):
                        self.func(*self.args,**self.kwargs)
                
                
        def __init__(self,url,dirpath=None,parent=None):
                super(QDialog,self).__init__(parent)
                if dirpath is not None and not os.path.exists(dirpath):os.mkdir(dirpath)
                self.url=url
                
                self.progress_dialog=QProgressDialog()
                self.progress_dialog.setWindowTitle(u"登录中")
                self.progress_dialog.setLabelText(u"登录中")
                self.loading_dialog=QDialog(self)
                
                self.dirpath=dirpath
                self.list=QListWidget()
                self.layout=QHBoxLayout(self)
                self.button_layout=QVBoxLayout()
                self.layout.addWidget(self.list)
                self.layout.addLayout(self.button_layout)
                self.add_button=QPushButton(u"添加")
                self.edit_name_button=QPushButton(u"设置名字")
                self.edit_cookies_button=QPushButton(u"设置Cookies")
                self.delete_button=QPushButton(u"删除")
                self.refresh_button=QPushButton(u"刷新")
                self.button_layout.addWidget(self.add_button)
                self.button_layout.addWidget(self.delete_button)
                self.button_layout.addWidget(self.refresh_button)
                self.button_layout.addWidget(self.edit_name_button)
                self.button_layout.addWidget(self.edit_cookies_button)
                QObject.connect(self.add_button,SIGNAL("clicked()"),self._add)
                QObject.connect(self.edit_name_button,SIGNAL("clicked()"),self.edit_name)
                QObject.connect(self.edit_cookies_button,SIGNAL("clicked()"),self.edit_cookies)
                QObject.connect(self.delete_button,SIGNAL("clicked()"),self._delete)
                QObject.connect(self.refresh_button,SIGNAL("clicked()"),self.login)
                #~ self.load()
        def edit_name(self):
                return [i.editName() for i in self.list.selectedItems()]
        def edit_cookies(self):
                return [i.editCookies() for i in self.list.selectedItems()]
        def login(self):
                return [self.list.item(i).login() for i in self.progress_iter(range(self.list.count()),u"登录")]
        def _add(self):
                self.add(self._Dialog(self).getvalue(unicode(self.list.count())),login=True)
        def _delete(self):
                i=self.list.currentRow()
                item=self.list.takeItem(i)
                if os.path.exists(item.cookiefile):
                        os.remove(item.cookiefile)
                
        def add(self,name,cookiefile=None,login=False):
                item=LoginListWindow._Item(name,self.url,('' if self.dirpath is None else self.dirpath+os.sep)+name+".cookies" if cookiefile is None else cookiefile)
                self.list.addItem(item)
                if login:
                        item.login()
        def load(self,list_=None,dir_=None):
                dir_=self.dirpath if dir_ is None else dir_
                list_=os.listdir(dir_) if list_ is None else list_
                for f in self.progress_iter(list_,u'载入文件'):
                        p=dir_+os.sep+f+".cookies"
                        n=os.path.splitext(f)[0]
                        self.add(n,p)
                self.login()
                #~ print list(self)
        def load_from_yaml(self,yaml_file,dir_=None):
                dt=yaml.load(open(yaml_file))
                self.load(dt["usernames"],dt["dir"])
        def load_asynchronously(self,dir_=None):
                self.thread=self._Thread(self.load,dir_)
                #~ print True
                self.thread.start()
        def progress_iter(self,list_,title=u'更新中'):
                len_=len(list_)
                self.loading_dialog.setWindowTitle(title)
                self.progress_dialog.setWindowTitle(title)
                self.progress_dialog.setLabelText(title)
                self.progress_dialog.setMaximum(len_)
                self.progress_dialog.show()
                #~ self.loading_dialog.show()
                #~ self.loading_dialog.close()
                for i in xrange(len_):
                        self.progress_dialog.setValue(i+1)
                        self.progress_dialog.show()
                        #~ print i,'/',len_
                        yield list_[i]
                self.progress_dialog.close()
        def load_and_show(self,list_=None,dir_=None):
                self.load(list_,dir_)
                self.show()
        def __iter__(self):
                return ( re.search(r"^(.+?)(<.*>)?(\[.*\])?$",unicode(self.list.item(i).text())).group(1) for i in range(self.list.count()))
Пример #47
0
class TagsDialog(QDialog):
    def __init__(self, dockwidget, parent, params):

        QDialog.__init__(self, parent)
        main_lay = QVBoxLayout(self)
        self.dockwidget = dockwidget
        self.params = params

        self.setWindowTitle('Tags editor')

        # Top frame
        self.fra_top = QFrame()
        fra_top_lay = QVBoxLayout(self.fra_top)

        self.lst_main = QListWidget(self)
        self.btn_add = QPushButton('Add tag')
        self.btn_add.clicked.connect(self.add_tag)
        self.btn_remove = QPushButton('Remove tag')
        self.btn_remove.clicked.connect(self.remove_tag)

        fra_top_lay.addWidget(self.lst_main)
        fra_top_lay.addWidget(self.btn_add)
        fra_top_lay.addWidget(self.btn_remove)

        # Bottom frame
        self.fra_bottom = QFrame()
        fra_bottom_lay = QHBoxLayout(self.fra_bottom)

        btb_main = QDialogButtonBox(QDialogButtonBox.Ok
                                    | QDialogButtonBox.Cancel)
        btb_main.accepted.connect(self.ok)
        btb_main.rejected.connect(self.reject)

        fra_bottom_lay.addWidget(btb_main)

        # Main
        main_lay.addWidget(self.fra_top)
        main_lay.addWidget(self.fra_bottom)

        self.initialize()

    def initialize(self):
        for tag_name in self.params.tag_names:
            self.lst_main.insertItem(self.lst_main.count(),
                                     QListWidgetItem(tag_name, self.lst_main))

    def ok(self):
        tag_names = []
        for r in range(self.lst_main.count()):
            tag_names.append(self.lst_main.item(r).text())

        self.params.tag_names = tag_names

        self.setVisible(False)

    def reject(self):
        self.setVisible(False)

    def add_tag(self):

        tag_name_dialog = TagNameDialog(self.dockwidget, self)
        tag_name_dialog.exec_()
        tag_name = tag_name_dialog.get_tag_name()

        if tag_name is not None:
            current_row = self.lst_main.currentRow()
            if current_row is None:
                current_row = self.lst_main.count()
            self.lst_main.insertItem(current_row,
                                     QListWidgetItem(tag_name, self.lst_main))

    def remove_tag(self):
        sel_items = self.lst_main.selectedItems()
        for sel_item in sel_items:
            self.lst_main.takeItem(self.lst_main.row(sel_item))
Пример #48
0
class InterfacePage(QWizardPage):
    def __init__(self):
        super(InterfacePage, self).__init__()
        self.completed = False
        self.setTitle('接口设置')
        self.setSubTitle('设置需要实现的接口')
        rootLayout = QVBoxLayout()
        rootLayout.setContentsMargins(14, 20, 10, 20)
        self.cb_component_type = self.field('component_type*')

        self.lw_interface = QListWidget()
        rootLayout.addWidget(self.lw_interface)
        self.setLayout(rootLayout)
        self.setStyleSheet(sheetstyle)
        #component_type = self.cb_component_type.currentIndex()
        #if component_type == 0:
        #    app.g_configurations.component_type = "server"
        #elif component_type == 1:
        #    app.g_configurations.component_type = "window"

    def initializePage(self):
        super(InterfacePage, self).initializePage()
        self.lw_interface.clear()
        exsits = []
        for key in app.g_configurations.interfaces:
            if app.g_configurations.interfaces[key]:
                exsits.append(key)

        for interface in app.g_configurations.config['interfaces']:
            # name + description
            display = interface['name'] + ' (' + interface['description'] + ')'
            # print display
            # litem = QListWidgetItem(interface['name'])
            litem = QListWidgetItem(display)
            litem.setToolTip(interface['description'])
            litem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)

            isdefault = False
            isUseable = True

            if app.g_configurations.component_type == "window":
                if interface['flag_win'] == 3:  #必须实现
                    isdefault = True
                    litem.setFlags(Qt.ItemIsUserCheckable)
                elif interface['flag_win'] == 2:  #可选并选中
                    isdefault = True
                elif interface['flag_win'] == 1:  #可选并不选
                    isdefault = False
                else:  #不需实现
                    isUseable = False
            else:
                if interface['flag_service'] == 3:
                    isdefault = True
                    litem.setFlags(Qt.ItemIsUserCheckable)
                elif interface['flag_service'] == 2:
                    isdefault = True
                elif interface['flag_service'] == 1:
                    isdefault = False
                else:
                    isUseable = False

            if app.g_configurations.initialized:
                if interface['name'] in exsits:
                    isdefault = True
                else:
                    isdefault = False

            if isdefault:
                litem.setCheckState(Qt.Checked)
            else:
                litem.setCheckState(Qt.Unchecked)
            if isUseable:
                self.lw_interface.addItem(litem)

    def validatePage(self):
        interfaces = {}
        for i in range(self.lw_interface.count()):
            litem = self.lw_interface.item(i)
            display = litem.text()
            key = app.QString2str(display.split(' (')[0])
            if litem.checkState() == 2:
                interfaces[key] = True
            else:
                interfaces[key] = False

        app.g_configurations.interfaces = interfaces
        return True

    def flush(self, text):
        self.initializePage(self)
Пример #49
0
class NewSessionPagePermutations(QWizardPage):
    def __init__(self):
        super(NewSessionPagePermutations, self).__init__()
        self.setTitle(_('Configuration of permutations'))
        self.setSubTitle(
            _('Select the position of each question'
              ' and its choices in every model of the exam.'))
        layout = QGridLayout()
        self.question_list = QListWidget()
        self.permutation_grid = QGridLayout()
        self.alternatives_rows = {}
        layout.addWidget(QLabel(_('Questions of model A')), 0, 0, 1, 1)
        layout.addWidget(self.question_list, 1, 0, 1, 1)
        layout.addWidget(QLabel(_('Model equivalence')), 0, 1, 1, 5)
        self.permutation_grid.setVerticalSpacing(20)
        layout.addLayout(self.permutation_grid, 1, 1, 1, 5)
        layout.setColumnStretch(0, 1)
        layout.setColumnStretch(1, 5)
        self.setLayout(layout)

    def initializePage(self):
        paramNAlts = int(self.field("paramNAlts").toString())
        paramNPerm = int(self.field("paramNPerm").toString())
        self.question_list.clear()
        # Creation of the list section
        paramNCols_array = self.field("paramNCols").toString().split(',')
        total_questions = 1 + (int(paramNCols_array[0]) \
                               if len(paramNCols_array) == 1 \
                               else reduce(lambda x, y: int(x) + int(y),
                                           paramNCols_array))
        for i in range(1, total_questions):
            questions_list = QListWidgetItem(_('Question ') + str(i))
            questions_list.setData(Qt.UserRole,
                                   widgets.ItemList(
                                       optionName=_('Question ') + str(i),
                                       optionNumber=i))  # Custom item list
            self.question_list.addItem(questions_list)
        self.question_list.setCurrentRow(0)
        self.question_list.itemClicked.connect(self._on_item_changed)
        # Creation of the grid section
        add_header = True  # Header of the columns (Name of alternatives)
        for j in range(0, paramNPerm):
            self.permutation_grid.addWidget( \
                                QLabel(_('Model ') + chr(97 + j).upper()), j, 1)
            self.alternatives_rows[j] = {}
            for k in range(0, paramNAlts):
                if add_header:
                    if k == 0:
                        self.permutation_grid.addWidget(QLabel(''), 0, 1)
                    self.permutation_grid.addWidget( \
                                        QLabel(chr(97 + k).upper()), 0, k + 2)
                self.alternatives_rows[j][k] = \
                    widgets.InputComboBox(self, c_type='alternative',
                                          form=j, alternative=k)
                self.alternatives_rows[j][k].addItems( \
                            [chr(97+x).upper() for x in range(0,paramNAlts)])
                self.alternatives_rows[j][k].setCurrentIndex(0)
                self.permutation_grid.addWidget(self.alternatives_rows[j][k],
                                                j, k + 2)
            add_header = False
            self.alternatives_rows[j][k + 1] = \
                widgets.InputComboBox(self, c_type='question', form=j,
                                      alternative=self.question_list.\
                                          currentItem().\
                                          data(Qt.UserRole).toPyObject().\
                                               get_question_number())
            self.alternatives_rows[j][k + 1].addItems( \
                                [str(x) for x in range(1,total_questions)])
            self.alternatives_rows[j][k + 1].setCurrentIndex(0)
            self.permutation_grid.addWidget(QLabel(_('Question Number')), j,
                                            k + 3)
            self.permutation_grid.addWidget(self.alternatives_rows[j][k + 1],
                                            j, k + 4)
        button_save = QPushButton(_('Save values'))
        self.permutation_grid.addWidget(button_save, j + 1, 1, 1, k + 4)
        button_save.clicked.connect(self._save_values)

    def _on_item_changed(self, arg=None):
        permutation = arg.data(Qt.UserRole).toPyObject().get_permutation()
        for k, v in self.alternatives_rows.iteritems():
            for sk, sv in v.iteritems():
                if not permutation:
                    sv.setCurrentIndex(0)
                else:
                    sv.setCurrentIndex( \
                        [x for x in permutation \
                         if (x['altr'] == sv.alternative
                             and x['form'] == sv.form
                             and x['c_type'] == sv.c_type)][0]['perm'] - 1)
        return True

    def _save_values(self):
        localItem = self.question_list.currentItem()
        formatted_grid = self._get_formatted_permutation_grid()
        if self._validate_grid(formatted_grid):
            localItem.setBackgroundColor(QColor(0, 255, 68))
            localItem.data(Qt.UserRole).toPyObject()\
                     .set_permutation(formatted_grid)
            self._reset_permutation_grid()
            QMessageBox.information(
                self, _('Information status'),
                _('The values for the question have been successfully saved'))
            return True
        else:
            QMessageBox.critical(self, _('Error in grid'),
                                 _('There is an inconsistence in the options'))
            return False

    def _get_formatted_permutation_grid(self):
        local_alternatives_rows = []
        for k, v in self.alternatives_rows.iteritems():
            for sk, sv in v.iteritems():
                alternative = {
                    'c_type': sv.c_type,
                    'form': sv.form,
                    'altr': sv.alternative,
                    'perm': sv.currentIndex() + 1
                }
                local_alternatives_rows.append(alternative)
        return local_alternatives_rows

    def _validate_grid(self, grid):
        #validate current grid and questions number
        forms = {}
        for row in grid:
            if row['c_type'] == 'alternative':
                if row['form'] not in forms:
                    forms[row['form']] = []
                if row['perm'] in forms[row['form']]:
                    return False
                else:
                    forms[row['form']].append(row['perm'])
            if row['c_type'] == 'question':
                for i in xrange(self.question_list.count()):
                    if i == self.question_list.currentRow():
                        continue
                    perm = self.question_list.item(i).data(Qt.UserRole)\
                               .toPyObject().get_permutation()
                    for perm_row in perm:
                        if (perm_row['c_type'] == 'question'
                                and perm_row['form'] == row['form']
                                and perm_row['perm'] == row['perm']):
                            return False
        return True

    def _reset_permutation_grid(self):
        for k, v in self.alternatives_rows.iteritems():
            for sk, sv in v.iteritems():
                sv.setCurrentIndex(0)

    def _get_values(self):
        formated_permutation = {}
        formated_permutation_m = {}
        for i in xrange(self.question_list.count()):
            permutations = self.question_list.item(i).data(Qt.UserRole)\
                               .toPyObject().get_permutation()
            a = {}
            for p in permutations:
                if p['form'] not in formated_permutation:
                    formated_permutation[p['form']] = []
                if p['form'] not in a:
                    a[p['form']] = []
                if p['c_type'] == 'alternative':
                    a[p['form']].append(p['perm'])
                if p['c_type'] == 'question':
                    formated_permutation[p['form']].append( \
                        "%s{%s}" % (p['perm'], ','.join(str(x) \
                                                       for x in a[p['form']])))
        for k, v in formated_permutation.iteritems():
            formated_permutation_m[chr(97 + k).upper()] = '/'.join(v)
        return formated_permutation_m

    def validatePage(self):
        valid = True
        msg = ''
        for i in xrange(self.question_list.count()):
            if not self.question_list.item(i).data(Qt.UserRole)\
                .toPyObject().get_permutation():
                valid = False
                msg = _('You must select all permutations for all questions')
                break
        if not valid:
            QMessageBox.critical(self, _('Error'), msg)
        else:
            current_permutations = self._get_values()
            for k, v in current_permutations.iteritems():
                self.wizard().exam_config.set_permutations(k, v)
        return valid

    def nextId(self):
        return WizardNewSession.PageIdFiles
Пример #50
0
class FileArgs(QtHelper.EnhancedQDialog, Logger.ClassLogger):
    """
    File arguments dialog
    """
    def __init__(self, dataArgs, parent=None):
        """
        Dialog to fill arguments for the file probe

        @param dataArgs: 
        @type dataArgs: 

        @param parent: 
        @type parent:
        """
        super(FileArgs, self).__init__(parent)
        self.dataArgs = dataArgs
        self.createDialog()
        self.createConnections()
        self.loadDefaultData()

    def createDialog(self):
        """
        Create qt dialog
        """
        mainLayout = QHBoxLayout()

        dataLayout = QVBoxLayout()
        self.labelHelp = QLabel("Path of the file to retrieve:")
        self.lineEdit = QLineEdit()
        self.listBox = QListWidget()
        dataLayout.addWidget(self.labelHelp)
        dataLayout.addWidget(self.lineEdit)
        dataLayout.addWidget(self.listBox)

        buttonLayout = QVBoxLayout()
        self.addButton = QPushButton("Add", self)
        self.delButton = QPushButton("Remove", self)
        self.delButton.setEnabled(False)
        self.editButton = QPushButton("Edit", self)
        self.editButton.setEnabled(False)
        self.clearButton = QPushButton("Clear", self)
        self.okButton = QPushButton("Ok", self)
        self.cancelButton = QPushButton("Cancel", self)
        buttonLayout.addWidget(self.addButton)
        buttonLayout.addWidget(self.delButton)
        buttonLayout.addWidget(self.editButton)
        buttonLayout.addWidget(self.clearButton)
        buttonLayout.addWidget(self.okButton)
        buttonLayout.addWidget(self.cancelButton)

        mainLayout.addLayout(dataLayout)
        mainLayout.addLayout(buttonLayout)

        self.setLayout(mainLayout)

        self.setWindowTitle("File Probe > Arguments")

    def createConnections(self):
        """
        Create qt connections
        """
        self.okButton.clicked.connect(self.accept)
        self.cancelButton.clicked.connect(self.reject)
        self.addButton.clicked.connect(self.addItem)
        self.delButton.clicked.connect(self.delItem)
        self.editButton.clicked.connect(self.editItem)
        self.clearButton.clicked.connect(self.clearList)
        self.listBox.itemClicked.connect(self.onItemSelected)

    def clearList(self):
        """
        Clear the list
        """
        self.listBox.clear()

    def onItemSelected(self, itm):
        """
        Called when an item is selected
        """
        self.delButton.setEnabled(True)
        self.editButton.setEnabled(True)

    def editItem(self):
        """
        Edit the selected item
        """
        self.delButton.setEnabled(False)
        self.editButton.setEnabled(False)
        # retrieve value to put it in the line edit and then remove item
        model = self.listBox.model()
        for selectedItem in self.listBox.selectedItems():
            qIndex = self.listBox.indexFromItem(selectedItem)
            if sys.version_info > (3, ):
                self.lineEdit.setText(model.data(qIndex))
            else:
                self.lineEdit.setText(model.data(qIndex).toString())
            model.removeRow(qIndex.row())

    def delItem(self):
        """
        Delete the selected item
        """
        self.delButton.setEnabled(False)
        self.editButton.setEnabled(False)
        # remove item
        model = self.listBox.model()
        for selectedItem in self.listBox.selectedItems():
            qIndex = self.listBox.indexFromItem(selectedItem)
            model.removeRow(qIndex.row())

    def addItem(self):
        """
        Add item
        """
        txt = self.lineEdit.text()
        if txt != '':
            self.listBox.insertItem(0, txt)
            self.lineEdit.setText('')

    def loadDefaultData(self):
        """
        Load the default data
        """
        try:
            if len(self.dataArgs) == 0:
                return
            dat = eval(self.dataArgs)
            if 'files' in dat:
                list_files = dat['files']
                self.listBox.insertItems(0, list_files)
        except Exception as e:
            self.error(e)

    def getArgs(self):
        """
        Returns arguments
        Examples: {'files': [ '/etc/init.d/ntpd', '/root/wmi-1.3.14-2.el5.art.x86_64.rpm' ] }
        """
        listFiles = []
        model = self.listBox.model()
        # iterate all items in a QListWidget
        for index in xrange(self.listBox.count()):
            itm = self.listBox.item(index)
            qIndex = self.listBox.indexFromItem(itm)
            if sys.version_info > (3, ):
                listFiles.append(model.data(qIndex))
            else:
                listFiles.append(str(model.data(qIndex).toString()))
        ret = {'files': listFiles}
        if len(listFiles) == 0:
            ret = ''
        return str(ret)
Пример #51
0
class GroupSelectParameterWidget(GenericParameterWidget):
    """Widget class for Group Select Parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A GroupSelectParameter object.
        :type parameter: GroupSelectParameter
        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Store spin box
        self.spin_boxes = {}

        # Create elements
        # Label (name)
        self.label = QLabel(self._parameter.name)

        # Layouts
        self.main_layout = QVBoxLayout()
        self.input_layout = QVBoxLayout()

        # _inner_input_layout must be filled with widget in the child class
        self.inner_input_layout = QVBoxLayout()

        self.radio_button_layout = QGridLayout()

        # Create radio button group
        self.input_button_group = QButtonGroup()

        # List widget
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list_widget.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_widget.setDefaultDropAction(Qt.MoveAction)
        self.list_widget.setEnabled(False)
        self.list_widget.setSizePolicy(QSizePolicy.Maximum,
                                       QSizePolicy.Expanding)

        for i, key in enumerate(self._parameter.options):
            value = self._parameter.options[key]
            radio_button = QRadioButton(value.get('label'))
            self.radio_button_layout.addWidget(radio_button, i, 0)
            if value.get('type') == SINGLE_DYNAMIC:
                double_spin_box = QDoubleSpinBox()
                self.radio_button_layout.addWidget(double_spin_box, i, 1)
                double_spin_box.setValue(value.get('value', 0))
                double_spin_box.setMinimum(
                    value.get('constraint', {}).get('min', 0))
                double_spin_box.setMaximum(
                    value.get('constraint', {}).get('max', 1))
                double_spin_box.setSingleStep(
                    value.get('constraint', {}).get('step', 0.01))
                step = double_spin_box.singleStep()
                if step > 1:
                    precision = 0
                else:
                    precision = len(str(step).split('.')[1])
                    if precision > 3:
                        precision = 3
                double_spin_box.setDecimals(precision)
                self.spin_boxes[key] = double_spin_box

                # Enable spin box depends on the selected option
                if self._parameter.selected == key:
                    double_spin_box.setEnabled(True)
                else:
                    double_spin_box.setEnabled(False)

            elif value.get('type') == STATIC:
                static_value = value.get('value', 0)
                if static_value is not None:
                    self.radio_button_layout.addWidget(
                        QLabel(str(static_value)), i, 1)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                selected_fields = value.get('value', [])
                if self._parameter.selected == key:
                    self.list_widget.setEnabled(True)
                else:
                    self.list_widget.setEnabled(False)

            self.input_button_group.addButton(radio_button, i)
            if self._parameter.selected == key:
                radio_button.setChecked(True)

        # Help text
        self.help_label = QLabel(self._parameter.help_text)
        self.help_label.setSizePolicy(QSizePolicy.Maximum,
                                      QSizePolicy.Expanding)
        self.help_label.setWordWrap(True)
        self.help_label.setAlignment(Qt.AlignTop)

        self.inner_input_layout.addLayout(self.radio_button_layout)
        self.inner_input_layout.addWidget(self.list_widget)

        # Put elements into layouts
        self.input_layout.addWidget(self.label)
        self.input_layout.addLayout(self.inner_input_layout)

        self.help_layout = QVBoxLayout()
        self.help_layout.addWidget(self.help_label)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        self.setLayout(self.main_layout)

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

        # Update list widget
        self.update_list_widget()

        # Connect signal
        self.input_button_group.buttonClicked.connect(
            self.radio_buttons_clicked)

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        # Set value for each key
        for key, value in self._parameter.options.items():
            if value.get('type') == STATIC:
                continue
            elif value.get('type') == SINGLE_DYNAMIC:
                new_value = self.spin_boxes.get(key).value()
                self._parameter.set_value_for_key(key, new_value)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                # Need to iterate through all items
                items = []
                for index in xrange(self.list_widget.count()):
                    items.append(self.list_widget.item(index))
                new_value = [i.text() for i in items]
                self._parameter.set_value_for_key(key, new_value)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.selected = None
        else:
            self._parameter.selected = self._parameter.options.keys(
            )[radio_button_checked_id]

        return self._parameter

    def update_list_widget(self):
        """Update list widget when radio button is clicked."""
        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id > -1:
            selected_dict = self._parameter.options.values(
            )[radio_button_checked_id]
            if selected_dict.get('type') == MULTIPLE_DYNAMIC:
                for field in selected_dict.get('value'):
                    # Update list widget
                    field_item = QListWidgetItem(self.list_widget)
                    field_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                        | Qt.ItemIsDragEnabled)
                    field_item.setData(Qt.UserRole, field)
                    field_item.setText(field)
                    self.list_widget.addItem(field_item)

    def radio_buttons_clicked(self):
        """Handler when selected radio button changed."""
        # Disable all spin boxes
        for spin_box in self.spin_boxes.values():
            spin_box.setEnabled(False)
        # Disable list widget
        self.list_widget.setEnabled(False)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()

        if radio_button_checked_id > -1:
            selected_value = self._parameter.options.values(
            )[radio_button_checked_id]
            if selected_value.get('type') == MULTIPLE_DYNAMIC:
                # Enable list widget
                self.list_widget.setEnabled(True)
            elif selected_value.get('type') == SINGLE_DYNAMIC:
                selected_key = self._parameter.options.keys(
                )[radio_button_checked_id]
                self.spin_boxes[selected_key].setEnabled(True)

    def select_radio_button(self, key):
        """Helper to select a radio button with key.

        :param key: The key of the radio button.
        :type key: str
        """
        key_index = self._parameter.options.keys().index(key)
        radio_button = self.input_button_group.button(key_index)
        radio_button.click()
Пример #52
0
class settingsDlg(QDialog):
    def __init__(self, settings, parent=None):
        super(settingsDlg, self).__init__(parent)
        self.setAttribute(
            Qt.WA_DeleteOnClose)  #dialog will be deleted rather than hidden
        self.settingsDialog = self
        self.settings = settings
        self.create_widgets()
        self.layout_widgets()
        self.dump_dirSettingFrame.hide()
        self.barSettingFrame.hide()

        self.create_connections()
        self.readSettingsData()
        self.setWindowTitle("yavol settings")

    def create_widgets(self):

        self.TableLabel1 = QLabel("Settings")
        self.ListOfSettings = QListWidget()
        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Apply
                                          | QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.layout().setDirection(QBoxLayout.RightToLeft)
        #yara scan settings frame
        self.yaraSettingFrame = QFrame()
        self.dump_dirSettingFrame = QFrame()
        self.barSettingFrame = QFrame()

        self.labelRulesPath = QLabel('Path to YARA rules:')
        self.inputRulesPath = QLineEdit()

        self.labelFoo = QLabel('Path to dumps:')
        self.inputDumpDirPath = QLineEdit()
        self.labelBar = QLabel('Just BAR as usual')

    def layout_widgets(self):
        hLayoutButton = QHBoxLayout()
        hLayoutButton.addWidget(self.buttonBox)
        hLayoutButton.addStretch()

        vLayoutSettingsLeft = QVBoxLayout()
        vLayoutSettingsLeft.addWidget(self.TableLabel1)
        vLayoutSettingsLeft.addWidget(self.ListOfSettings)

        #yara setting frame layout
        frameLayout = QGridLayout()
        frameLayout.addWidget(self.labelRulesPath, 0, 0)
        frameLayout.addWidget(self.inputRulesPath, 0, 1)
        self.yaraSettingFrame.setLayout(frameLayout)

        #foo settings frame
        frameLayoutFoo = QGridLayout()
        frameLayoutFoo.addWidget(self.labelFoo, 0, 0)
        frameLayoutFoo.addWidget(self.inputDumpDirPath, 0, 1)
        self.dump_dirSettingFrame.setLayout(frameLayoutFoo)

        #bar settings frame
        frameLayoutBar = QVBoxLayout()
        frameLayoutBar.addWidget(self.labelBar)
        self.barSettingFrame.setLayout(frameLayoutBar)

        settingWindowsLayout = QGridLayout()

        settingWindowsLayout.addLayout(vLayoutSettingsLeft, 0, 0)
        settingWindowsLayout.addWidget(self.yaraSettingFrame, 0, 1)
        settingWindowsLayout.addWidget(self.dump_dirSettingFrame, 0, 1)
        settingWindowsLayout.addWidget(self.barSettingFrame, 0, 1)
        settingWindowsLayout.addLayout(hLayoutButton, 1, 0)
        '''
        ################################################# <-|
        #   vbox    #    vbox                           #   |
        # listOption# yaraframe                         #   | grid
        #           #                                   #   |
        #           #                                   #   |
        #################################################   |
        #            vbox     button                    #   |
        ################################################# <-|

        '''

        self.setLayout(settingWindowsLayout)

    def create_connections(self):
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.buttonBox.button(QDialogButtonBox.Apply).clicked.connect(
            self.apply)
        self.ListOfSettings.selectionModel().currentChanged.connect(
            self.setFrameVisibility)

    def accept(self):
        self.saveSettingsData()
        QDialog.accept(self)

    def apply(self):
        self.saveSettingsData()

    def setFrameVisibility(self, current, previous):

        if not previous.row() == -1:
            #hide previous frame and set current visible
            previous = str(self.ListOfSettings.item(
                previous.row()).text()) + "SettingFrame"
            previous = getattr(self, previous)
            previous.hide()

            #set the current visible
            current = str(self.ListOfSettings.item(
                current.row()).text()) + "SettingFrame"
            current = getattr(self, current)
            current.show()
            #print "Current: ", str(current.row()), self.ListOfSettings.item(current.row()).text()
            #print "Previous: ", str(previous.row()), self.ListOfSettings.item(previous.row()).text()
            #self.yaraSettingFrame.setVisible(False)

    def readSettingsData(self):
        settings = QSettings()
        settings_dict = settings.value('dictionary').toPyObject()
        # DEBUG
        #pp = pprint.PrettyPrinter(indent=4)
        #pp.pprint(settings_dict)

        for key in settings_dict:

            item = QListWidgetItem((QString("%1").arg(key)))
            self.ListOfSettings.addItem(item)
            if key == "yara":
                #set yara option to be 'pre-selected'
                self.ListOfSettings.setItemSelected(item, True)
                path_to_rules = settings_dict[QString('yara')][QString(
                    'rules_dir')][QString('path')]
                self.inputRulesPath.setText(path_to_rules)

            if key == "dump_dir":
                path_to_dump = settings_dict[QString('dump_dir')]
                self.inputDumpDirPath.setText(path_to_dump)

    def saveSettingsData(self):
        settings = QSettings()
        #get values of yara setting
        path_to_rules = self.inputRulesPath.text()

        #get value of the dump_dir input
        path_to_dump_dir = self.inputDumpDirPath.text()

        settings.setValue(
            'dictionary', {
                'yara': {
                    'rules_dir': {
                        'path': path_to_rules
                    }
                },
                'dump_dir': path_to_dump_dir,
                'bar': 2
            })
Пример #53
0
class CheckList(QWidget):
    def __init__(self, model, label="", help_link="", custom_filter_button=None):
        """
        :param custom_filter_button:  if needed, add a button that opens a custom filter menu. Useful when search alone
        isn't enough to filter the list.
        :type custom_filter_button: QToolButton
        """
        QWidget.__init__(self)

        self._model = model

        if help_link != "":
            addHelpToWidget(self, help_link)

        layout = QVBoxLayout()

        self._createCheckButtons()

        self._list = QListWidget()
        self._list.setContextMenuPolicy(Qt.CustomContextMenu)
        self._list.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self._search_box = SearchBox()

        check_button_layout = QHBoxLayout()

        check_button_layout.setMargin(0)
        check_button_layout.setSpacing(0)
        check_button_layout.addWidget(QLabel(label))
        check_button_layout.addStretch(1)
        check_button_layout.addWidget(self._checkAllButton)
        check_button_layout.addWidget(self._uncheckAllButton)

        layout.addLayout(check_button_layout)
        layout.addWidget(self._list)

        """
        Inserts the custom filter button, if provided. The caller is responsible for all related actions.
        """
        if custom_filter_button is not None:
            search_bar_layout = QHBoxLayout()
            search_bar_layout.addWidget(self._search_box)
            search_bar_layout.addWidget(custom_filter_button)
            layout.addLayout(search_bar_layout)
        else:
            layout.addWidget(self._search_box)

        self.setLayout(layout)

        self._checkAllButton.clicked.connect(self.checkAll)
        self._uncheckAllButton.clicked.connect(self.uncheckAll)
        self._list.itemChanged.connect(self.itemChanged)
        self._search_box.filterChanged.connect(self.filterList)
        self._list.customContextMenuRequested.connect(self.showContextMenu)

        self._model.selectionChanged.connect(self.modelChanged)
        self._model.modelChanged.connect(self.modelChanged)

        self.modelChanged()

    def _createCheckButtons(self):
        self._checkAllButton = QToolButton()
        self._checkAllButton.setIcon(resourceIcon("checked"))
        self._checkAllButton.setIconSize(QSize(16, 16))
        self._checkAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self._checkAllButton.setAutoRaise(True)
        self._checkAllButton.setToolTip("Select all")
        self._uncheckAllButton = QToolButton()
        self._uncheckAllButton.setIcon(resourceIcon("notchecked"))
        self._uncheckAllButton.setIconSize(QSize(16, 16))
        self._uncheckAllButton.setToolButtonStyle(Qt.ToolButtonIconOnly)
        self._uncheckAllButton.setAutoRaise(True)
        self._uncheckAllButton.setToolTip("Unselect all")

    def itemChanged(self, item):
        """@type item: QListWidgetItem"""
        if item.checkState() == Qt.Checked:
            self._model.selectValue(str(item.text()))
        elif item.checkState() == Qt.Unchecked:
            self._model.unselectValue(str(item.text()))
        else:
            raise AssertionError("Unhandled checkstate!")

    def modelChanged(self):
        self._list.clear()

        items = self._model.getList()

        for item in items:
            list_item = QListWidgetItem(item)
            list_item.setFlags(list_item.flags() | Qt.ItemIsUserCheckable)

            if self._model.isValueSelected(item):
                list_item.setCheckState(Qt.Checked)
            else:
                list_item.setCheckState(Qt.Unchecked)

            self._list.addItem(list_item)

        self.filterList(self._search_box.filter())

    def setSelectionEnabled(self, enabled):
        self.setEnabled(enabled)
        self._checkAllButton.setEnabled(enabled)
        self._uncheckAllButton.setEnabled(enabled)

    def filterList(self, filter):
        filter = filter.lower()

        for index in range(0, self._list.count()):
            item = self._list.item(index)
            text = str(item.text()).lower()

            if filter == "":
                item.setHidden(False)
            elif filter in text:
                item.setHidden(False)
            else:
                item.setHidden(True)

    def checkAll(self):
        """
        Checks all visible items in the list.
        """
        for index in range(0, self._list.count()):
            item = self._list.item(index)
            if not item.isHidden():
                self._model.selectValue(str(item.text()))

    def uncheckAll(self):
        """
        Unchecks all items in the list, visible or not
        """
        self._model.unselectAll()

    def checkSelected(self):
        items = []
        for item in self._list.selectedItems():
            items.append(str(item.text()))

        for item in items:
            self._model.selectValue(item)

    def uncheckSelected(self):
        items = []
        for item in self._list.selectedItems():
            items.append(str(item.text()))

        for item in items:
            self._model.unselectValue(item)

    def showContextMenu(self, point):
        p = self._list.mapToGlobal(point)
        menu = QMenu()
        check_selected = menu.addAction("Check selected")
        uncheck_selected = menu.addAction("Uncheck selected")
        menu.addSeparator()
        clear_selection = menu.addAction("Clear selection")

        selected_item = menu.exec_(p)

        if selected_item == check_selected:
            self.checkSelected()
        elif selected_item == uncheck_selected:
            self.uncheckSelected()
        elif selected_item == clear_selection:
            self._list.clearSelection()
Пример #54
0
class ListEdit(QWidget):
    """A widget to edit a list of items (e.g. a list of directories)."""

    # emitted when anything changed in the listbox.
    changed = pyqtSignal()

    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        layout = QGridLayout(self)
        self.setLayout(layout)

        self.addButton = QPushButton(icons.get('list-add'), '')
        self.editButton = QPushButton(icons.get('document-edit'), '')
        self.removeButton = QPushButton(icons.get('list-remove'), '')
        self.listBox = QListWidget()

        layout.setContentsMargins(1, 1, 1, 1)
        layout.setSpacing(0)
        layout.addWidget(self.listBox, 0, 0, 4, 1)
        layout.addWidget(self.addButton, 0, 1)
        layout.addWidget(self.editButton, 1, 1)
        layout.addWidget(self.removeButton, 2, 1)

        @self.addButton.clicked.connect
        def addClicked():
            item = self.createItem()
            if self.openEditor(item):
                self.addItem(item)

        @self.editButton.clicked.connect
        def editClicked():
            item = self.listBox.currentItem()
            item and self.editItem(item)

        @self.removeButton.clicked.connect
        def removeClicked():
            item = self.listBox.currentItem()
            if item:
                self.removeItem(item)

        @self.listBox.itemDoubleClicked.connect
        def itemDoubleClicked(item):
            item and self.editItem(item)

        self.listBox.model().layoutChanged.connect(self.changed)

        def updateSelection():
            selected = bool(self.listBox.currentItem())
            self.editButton.setEnabled(selected)
            self.removeButton.setEnabled(selected)

        self.changed.connect(updateSelection)
        self.listBox.itemSelectionChanged.connect(updateSelection)
        updateSelection()
        app.translateUI(self)

    def translateUI(self):
        self.addButton.setText(_("&Add..."))
        self.editButton.setText(_("&Edit..."))
        self.removeButton.setText(_("&Remove"))

    def createItem(self):
        return QListWidgetItem()

    def addItem(self, item):
        self.listBox.addItem(item)
        self.itemChanged(item)
        self.changed.emit()

    def removeItem(self, item):
        self.listBox.takeItem(self.listBox.row(item))
        self.changed.emit()

    def editItem(self, item):
        if self.openEditor(item):
            self.itemChanged(item)
            self.changed.emit()

    def setCurrentItem(self, item):
        self.listBox.setCurrentItem(item)

    def setCurrentRow(self, row):
        self.listBox.setCurrentRow(row)

    def openEditor(self, item):
        """Opens an editor (dialog) for the item.
        
        Returns True if the dialog was accepted and the item edited.
        Returns False if the dialog was cancelled (the item must be left
        unedited).
        """
        pass

    def itemChanged(self, item):
        """Called after an item has been added or edited.
        
        Re-implement to do something at this moment if needed, e.g. alter the
        text or display of other items.
        """
        pass

    def setValue(self, strings):
        """Sets the listbox to a list of strings."""
        self.listBox.clear()
        self.listBox.addItems(strings)
        self.changed.emit()

    def value(self):
        """Returns the list of paths in the listbox."""
        return [
            self.listBox.item(i).text() for i in range(self.listBox.count())
        ]

    def setItems(self, items):
        """Sets the listbox to a list of items."""
        self.listBox.clear()
        for item in items:
            self.listBox.addItem(item)
            self.itemChanged(item)
        self.changed.emit()

    def items(self):
        """Returns the list of items in the listbox."""
        return [self.listBox.item(i) for i in range(self.listBox.count())]

    def clear(self):
        """Clears the listbox."""
        self.listBox.clear()
        self.changed.emit()
Пример #55
0
class ChainComposerDialog(QDialog):
 
    def __init__(self, parent=None):
        super(ChainComposerDialog, self).__init__(parent)
        self.setWindowTitle('Composer Chain')
 
        layout = QVBoxLayout()
 
        mainLayout = QHBoxLayout()
 
        selectionLayout = QVBoxLayout()
        label = QLabel('Available Filters:')
        selectionLayout.addWidget(label)
        self.__selectionList = QListWidget()
        selectionLayout.addWidget(self.__selectionList)
        mainLayout.addLayout(selectionLayout)
 
        actionsLayout = QVBoxLayout()
        actionsLayout.addStretch()
        addButton = QPushButton('Add>>')
        addButton.clicked.connect(self.__handleAdd)
        actionsLayout.addWidget(addButton)
        removeButton = QPushButton('Remove')
        actionsLayout.addWidget(removeButton)
        removeAllButton = QPushButton('Remove All')
        actionsLayout.addWidget(removeAllButton)
        actionsLayout.addStretch()
        mainLayout.addLayout(actionsLayout)
 
        chainLayout = QVBoxLayout()
        chainLayout.addWidget(QLabel('Chain:'))
        self.__chainList = QListWidget()
        chainLayout.addWidget(self.__chainList)
        mainLayout.addLayout(chainLayout)
 
        layout.addLayout(mainLayout)
        
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttonBox.accepted.connect(self.okClick)
        buttonBox.rejected.connect(self.cancelClick)
        layout.addWidget(buttonBox)
 
#         buttonLayout = QHBoxLayout()
#         okButton = QPushButton('OK')
#         okButton.clicked.connect(self.accept)
#         buttonLayout.addWidget(okButton)
#         cancelButton = QPushButton('Cancel')
#         cancelButton.clicked.connect(self.reject)
#         buttonLayout.addWidget(cancelButton)
#         layout.addLayout(buttonLayout)
 
        self.setLayout(layout)
 
        self.__composer = None
    
    def okClick(self):
        print "OK!"
        self.accept()
    
    def cancelClick(self):
        print "Cancel"
        self.reject()
 
    def setComposer(self, composer):
        self.__composer = composer
 
    @property
    def selectionList(self):
        return self.__getStrings(self.__selectionList)
 
    @selectionList.setter
    def setSelectionList(self, filters):
        for i in xrange(self.__selectionList.count()):
            self.__selectionList.takeItem(i)
        self.__selectionList.addItems(filters)
 
    def filterAt(self, row):
        return self.__selectionList.item(row).text()
 
    def addToChain(self, filterName):
        self.__chainList.addItem(filterName)
 
    @property
    def composedFilter(self):
        return self.__getStrings(self.__chainList)
 
    @staticmethod
    def __getStrings(listWidget):
        return tuple(listWidget.item(i) for i in
                     range(listWidget.count()))
 
    def __handleAdd(self):
        if self.__composer is None:
            return
        for item in self.__selectionList.selectedItems():
            row = self.__selectionList.row(item)
            self.__composer.add(row)
Пример #56
0
class FiltersDialog(Window):
    def __init__(self, base):
        Window.__init__(self, base, i18n.get('filters'))
        self.setFixedSize(280, 360)

        self.expression = QLineEdit()
        self.expression.returnPressed.connect(self.__new_filter)

        self.new_button = QPushButton(i18n.get('add_filter'))
        self.new_button.setToolTip(i18n.get('create_a_new_filter'))
        self.new_button.clicked.connect(self.__new_filter)

        expression_box = QHBoxLayout()
        expression_box.addWidget(self.expression)
        expression_box.addWidget(self.new_button)

        self.list_ = QListWidget()
        self.list_.clicked.connect(self.__filter_clicked)

        self.delete_button = QPushButton(i18n.get('delete'))
        self.delete_button.setEnabled(False)
        self.delete_button.setToolTip(i18n.get('delete_selected_filter'))
        self.delete_button.clicked.connect(self.__delete_filter)

        self.clear_button = QPushButton(i18n.get('delete_all'))
        self.clear_button.setEnabled(False)
        self.clear_button.setToolTip(i18n.get('delete_all_filters'))
        self.clear_button.clicked.connect(self.__delete_all)

        button_box = QHBoxLayout()
        button_box.addStretch(1)
        button_box.addWidget(self.clear_button)
        button_box.addWidget(self.delete_button)

        layout = QVBoxLayout()
        layout.addLayout(expression_box)
        layout.addWidget(self.list_, 1)
        layout.addLayout(button_box)
        layout.setSpacing(5)
        layout.setContentsMargins(5, 5, 5, 5)
        self.setLayout(layout)
        self.__update()
        self.show()

    def __update(self):
        row = 0
        self.expression.setText('')
        self.list_.clear()
        for expression in self.base.core.list_filters():
            self.list_.addItem(expression)
            row += 1

        self.__enable(True)
        self.delete_button.setEnabled(False)
        if row == 0:
            self.clear_button.setEnabled(False)
        self.expression.setFocus()

    def __filter_clicked(self, point):
        self.delete_button.setEnabled(True)
        self.clear_button.setEnabled(True)

    def __new_filter(self):
        expression = str(self.expression.text())
        self.list_.addItem(expression)
        self.__save_filters()

    def __delete_filter(self):
        self.list_.takeItem(self.list_.currentRow())
        self.__save_filters()

    def __delete_all(self):
        self.__enable(False)
        message = i18n.get('clear_filters_confirm')
        confirmation = self.base.show_confirmation_message(
            i18n.get('confirm_delete'), message)
        if not confirmation:
            self.__enable(True)
            return
        self.list_.clear()
        self.__save_filters()

    def __enable(self, value):
        self.list_.setEnabled(value)
        self.delete_button.setEnabled(value)
        self.clear_button.setEnabled(value)

    def __save_filters(self):
        filters = []
        for i in range(self.list_.count()):
            filters.append(str(self.list_.item(i).text()))
        self.base.save_filters(filters)
        self.__update()