class ComboTabWidget(QWidget):
    def __init__(self, parent):
        super(ComboTabWidget, self).__init__(parent)
        layout = QVBoxLayout(self)
        layout.setSpacing(0)
        
        self.switchCombo = QComboBox(self)
        layout.addWidget(self.switchCombo, 0, Qt.AlignCenter)
        
        groupBox = QGroupBox(self)
        groupBoxLayout = QVBoxLayout(groupBox)
        groupBoxLayout.setSpacing(0)
        
        self.pageArea = QStackedWidget(groupBox)
        groupBoxLayout.addWidget(self.pageArea)
        
        layout.addWidget(groupBox, 1)
        
        self.switchCombo.currentIndexChanged.connect(self.pageArea.setCurrentIndex)
        
    def setTabPosition(self, tabPos):
        pass
        
    def addTab(self, w, tabText):
        self.pageArea.addWidget(w)
        self.switchCombo.addItem(tabText)
    
    def insertTab(self, pos, w, tabText):
        self.pageArea.insertWidget(pos, w)
        self.switchCombo.insertItem(pos, tabText)
        
    def removeTab(self, index=-1):
        if index < 0:
            index = self.currentIndex()
        
        w = self.pageArea.widget(index)
        
        self.pageArea.removeWidget(w)
        self.switchCombo.removeItem(index)
        
    def updateTab(self, w, tabText, index=-1):
        if index < 0:
            index = self.switchCombo.currentIndex()
        
        self.removeTab(index)
        self.insertTab(index, w, tabText)
        self.setCurrentIndex(index)
        
    def setCurrentIndex(self, index):
        self.switchCombo.setCurrentIndex(index)
        
    def widget(self, index):
        return self.pageArea.widget(index)
        
    def currentIndex(self):
        return self.switchCombo.currentIndex()
    
    def count(self):
        return self.switchCombo.count()
Exemple #2
0
class SizeRequest(Request):
  def __init__(self, parent):
    Request.__init__(self, parent)
    self.setOperators()
    self.setContent()
    self.setSizeType()

  def setOperators(self):
    self.operatorCombo = OperatorCombo(self)
    self.hlayout.addWidget(self.operatorCombo)

  def setContent(self):
    self.content = QLineEdit(self)
    self.validator = QIntValidator(0,2147483647, self)
    self.content.setValidator(self.validator)
    self.hlayout.addWidget(self.content)

  def setSizeType(self):
    self.stype = QComboBox(self)
    self.stype.addItem(QString("KB"))
    self.stype.addItem(QString("MB"))
    self.stype.addItem(QString("GB"))
    self.hlayout.addWidget(self.stype)

  def request(self):
    operator = str(self.operatorCombo.currentText())
    factor = SIZE_T[self.stype.currentIndex()]
    size = self.content.text().toULongLong()[0]
    size = size * factor
    res = "(size " + operator + " " + str(size) + ")"
    return res
class GoogleFinanceUrlSetupDialog(QDialog):

    SETTING_GOOGLE_URL = 'googleUrl'
    SETTING_GOOGLE_COUNTRY = 'googleCountry'

    def __init__(self, parent):

        QDialog.__init__(self, parent)

        self.prop = MaeMoneyProperties.instance()
        self.urls = {}
        self.urls[self.prop.GOOGLE_COUNTRY_HK] = 'www.google.com.hk'
        self.urls[self.prop.GOOGLE_COUNTRY_CN] = 'www.google.com.cn'
        self.urls[self.prop.GOOGLE_COUNTRY_CAN] = 'www.google.ca'
        self.urls[self.prop.GOOGLE_COUNTRY_UK] = 'www.google.co.uk'
        self.urls[self.prop.GOOGLE_COUNTRY_US] = 'www.google.com'

        self.setupUi()

    def setupUi(self):
        self.setWindowModality(Qt.WindowModal)
        self.buttonBox = QDialogButtonBox(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)

        self.gridLayout = QGridLayout()
        self.setLayout(self.gridLayout)

        self.labelGFinanceUrl = QLabel(self.tr("Google URL"))
        self.gridLayout.addWidget(self.labelGFinanceUrl, 0, 1, 1, 1)
        self.comboBoxGFinanceUrl = QComboBox()
        for [country, url] in sorted(self.urls.iteritems()):
            self.comboBoxGFinanceUrl.addItem(country, url)

        googleCountry = self.prop.getGoogleCountry()
        index = self.comboBoxGFinanceUrl.findText(googleCountry)
        self.comboBoxGFinanceUrl.setCurrentIndex(index)
        self.gridLayout.addWidget(self.comboBoxGFinanceUrl, 0, 2, 1, 1)

        self.gridLayout.addWidget(QLabel(self.tr("Current setting")), 1, 1, 1, 1)
        self.gridLayout.addWidget(QLabel(self.prop.getGoogleCountry()),
                                  1, 2, 1, 1)

        self.setUrlButton = QPushButton(self.tr("Set URL"))
        self.gridLayout.addWidget(self.setUrlButton, 2, 1, 1, 2)

        self.loginErrorMsgLabel = QLabel("")
        self.gridLayout.addWidget(self.loginErrorMsgLabel, 3, 1, 1, 2)

        self.setWindowTitle(self.tr("Setup"))

        self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.connect(self.setUrlButton, SIGNAL("clicked()"), self.setUrl)

    def setUrl(self):
        indexSelected = self.comboBoxGFinanceUrl.currentIndex()
        country = self.comboBoxGFinanceUrl.itemText(indexSelected)
        url = self.comboBoxGFinanceUrl.itemData(indexSelected).toString().toAscii()
        self.prop.setGoogleCountryUrl(country, url)
        self.accept()
Exemple #4
0
class CodecSelector(QHBoxLayout):
    codecChanged = pyqtSignal(EnCoder)
    checked = pyqtSignal(int)
    List = []

    def __init__(self, cod=[], **kwargs):
        super(CodecSelector, self).__init__()
        ctitle = kwargs['CTitle']
        self.combo = QComboBox()
        self.check = QCheckBox(ctitle)
        self.combo.currentIndexChanged.connect(self.choiceCodec)
        self.check.stateChanged.connect(self.checked.emit)
        self.addWidget(self.combo)
        self.addWidget(self.check)
        self.setCodec(cod)

    def choiceCodec(self, a):
        self.codecChanged.emit(self.List[a])

    def addCodec(self, lst):
        for c in lst:
            self.List.append(c)
            self.combo.addItems([c.title])

    def setCodec(self, lst):
        self.List = lst
        for c in lst:
            self.combo.addItems([c.title])

    def get(self):
        return self.List[self.combo.currentIndex()]
Exemple #5
0
class SizeRequest(Request):
    def __init__(self, parent):
        Request.__init__(self, parent)
        self.setOperators()
        self.setContent()
        self.setSizeType()

    def setOperators(self):
        self.operatorCombo = OperatorCombo(self)
        self.hlayout.addWidget(self.operatorCombo)

    def setContent(self):
        self.content = QLineEdit(self)
        self.validator = QIntValidator(0, 2147483647, self)
        self.content.setValidator(self.validator)
        self.hlayout.addWidget(self.content)

    def setSizeType(self):
        self.stype = QComboBox(self)
        self.stype.addItem(QString("KB"))
        self.stype.addItem(QString("MB"))
        self.stype.addItem(QString("GB"))
        self.hlayout.addWidget(self.stype)

    def request(self):
        operator = str(self.operatorCombo.currentText())
        factor = SIZE_T[self.stype.currentIndex()]
        size = self.content.text().toULongLong()[0]
        size = size * factor
        res = "(size " + operator + " " + str(size) + ")"
        return res
Exemple #6
0
class ComboBox(QWidget):
    def __init__(self, caption, values, default_value, caption_size=None, expand_combo=False):
        QWidget.__init__(self)

        self.values = values

        description = QLabel(caption)
        description.setWordWrap(True)
        if caption_size:
            description.setMaximumWidth(caption_size)

        self.combo = QComboBox()
        for item in values:
            self.combo.addItem(item, item)

        for i in range(0, len(values)):
            if values[i] == default_value:
                self.combo.setCurrentIndex(i)
                break

        hbox = QHBoxLayout()
        hbox.addWidget(description)
        hbox.addSpacing(10)
        if expand_combo:
            hbox.addWidget(self.combo, 1)
        else:
            hbox.addWidget(self.combo)
        hbox.setMargin(0)
        self.setLayout(hbox)
        self.setContentsMargins(0, 0, 0, 0)

    def get_value(self):
        return str(self.values[self.combo.currentIndex()])
Exemple #7
0
class AddAddressColumnDialog(utils.Dialog):
    def __init__(self, parent, hex_widget, column):
        utils.Dialog.__init__(self, parent, name='add_address_column_dialog')
        self.hexWidget = hex_widget
        self.column = column
        self.setWindowTitle(utils.tr('Add address bar'))

        self.setLayout(QVBoxLayout())

        self.configWidget = AddressColumnConfigurationWidget(self, hex_widget, None)
        self.layout().addWidget(self.configWidget)

        self.txtName = QLineEdit(self)
        self.configWidget.layout().insertRow(0, utils.tr('Name:'), self.txtName)

        self.cmbAlignment = QComboBox(self)
        self.cmbAlignment.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.cmbAlignment.addItem(utils.tr('To the left'), Qt.AlignLeft)
        self.cmbAlignment.addItem(utils.tr('To the right'), Qt.AlignRight)
        self.configWidget.layout().insertRow(1, utils.tr('Position:'), self.cmbAlignment)

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, Qt.Horizontal, self)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        self.layout().addWidget(self.buttonBox)

    def addColumn(self):
        model = self.configWidget.createColumnModel(self.hexWidget)
        model.name = self.txtName.text()
        self.hexWidget.addAddressColumn(model, self.cmbAlignment.itemData(self.cmbAlignment.currentIndex()))
Exemple #8
0
class WidgetSelector(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self, parent)
        self.key_text = QLineEdit(self)
        self.widget_select = QComboBox(self)
        self.value_widget = None
        self.layout = QHBoxLayout(self)
        self.layout.addWidget(self.key_text)
        self.layout.addWidget(self.widget_select)

        self.options = NodeWidget.get_simple_widgets()
        for i, option in enumerate(self.options):
            self.widget_select.addItem(option.get_description(), i)

        self.widget_select.currentIndexChanged.connect(self.change_widget)


    def get_item(self):
        return {
            "key":unicode(self.key_text.text()),
            "value":self.value_widget.data
        }

    def change_widget(self):

        w_class = self.options[self.widget_select.currentIndex()]
        if self.value_widget:
            self.layout.removeWidget(self.value_widget)
            self.value_widget.setParent(None)
            self.value_widget = None

        element_scheme = StructuredNode({"Type":w_class.data_type})
        new_data = NodeWidget.get_default_data(element_scheme, None)
        self.value_widget = NodeWidget.create_node_widget("__not_exist", new_data, element_scheme)
        self.layout.addWidget(self.value_widget)
 def Get(self, widget : QtGui.QComboBox): # return val from enum
     if len(self.enum) != widget.count():
         raise GuiFieldEnumLenErr(self.enum, widget.count(), widget.count())
     
     i = widget.currentIndex()
     if i < 0: return ""
     return self.enum[i]
Exemple #10
0
class Widget(QWidget):
    def __init__(self, tool):
        super(Widget, self).__init__(tool)
        
        layout = QVBoxLayout()
        self.setLayout(layout)
        layout.setContentsMargins(0, 0, 0, 0)
        
        self.blockCombo = QComboBox()
        self.charmap = CharMapWidget()

        layout.addWidget(self.blockCombo)
        layout.addWidget(self.charmap)

        # size policy of combo
        p = self.blockCombo.sizePolicy()
        p.setHorizontalPolicy(QSizePolicy.Ignored)
        self.blockCombo.setSizePolicy(p)
        
        # size policy of combo popup
        p = self.blockCombo.view().sizePolicy()
        p.setHorizontalPolicy(QSizePolicy.MinimumExpanding)
        self.blockCombo.view().setSizePolicy(p)
        
        model = listmodel.ListModel(_blocks,
            display = lambda b: b.name)
        self.blockCombo.setModel(model)
        
        # load block setting
        name = QSettings().value("charmaptool/last_block", "", type(""))
        if name:
            for i, b in enumerate(_blocks):
                if b.name == name:
                    self.blockCombo.setCurrentIndex(i)
                    break
        
        self.blockCombo.activated[int].connect(self.updateBlock)
        self.updateBlock()
        
        self.loadSettings()
        app.settingsChanged.connect(self.loadSettings)
    
    def loadSettings(self):
        s = QSettings()
        s.beginGroup("charmaptool")
        font = self.font()
        family = s.value("fontfamily", "", type(""))
        if family:
            font.setFamily(family)
        self.charmap.charmap.setDisplayFont(font)
        size = s.value("fontsize", font.pointSizeF(), float)
        self.charmap.charmap.setDisplayFontSizeF(size)
    
    def updateBlock(self):
        i = self.blockCombo.currentIndex()
        if 0 <= i < len(_blocks):
            first, last, name = _blocks[i]
            self.charmap.charmap.setRange(first, last)
            QSettings().setValue("charmaptool/last_block", name)
Exemple #11
0
class AddressColumnConfigurationWidget(columnproviders.AbstractColumnConfigurationWidget, QWidget):
    def __init__(self, parent, hex_widget, column):
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        QWidget.__init__(self, parent)
        self.hexWidget = hex_widget
        self.column = column

        self.setLayout(QFormLayout())

        self.cmbBase = QComboBox(self)
        self.cmbBase.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addRow(utils.tr('Base:'), self.cmbBase)
        for base in ((utils.tr('Hex'), 16), (utils.tr('Dec'), 10), (utils.tr('Oct'), 8), (utils.tr('Bin'), 2)):
            self.cmbBase.addItem(base[0], base[1])
        if column is not None:
            self.cmbBase.setCurrentIndex(self.cmbBase.findData(column.formatter.base))

        self.cmbStyle = QComboBox(self)
        self.cmbStyle.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addRow(utils.tr('Style:'), self.cmbStyle)
        for style_data in ((utils.tr('No style'), 'none'), (utils.tr('C'), 'c'), (utils.tr('Assembler'), 'asm')):
            self.cmbStyle.addItem(style_data[0], style_data[1])
        if column is not None:
            self.cmbStyle.setCurrentIndex(self.cmbStyle.findData(column.formatter.styleName))

        self.intBaseAddress = integeredit.IntegerEdit(self)
        self.intBaseAddress.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addRow(utils.tr('Base address:'), self.intBaseAddress)
        self.intBaseAddress.minimum = -10000000000000
        if column is not None:
            self.intBaseAddress.number = column.baseAddress

    @property
    def _formatter(self):
        formatter = formatters.IntegerFormatter()
        formatter.base = self.cmbBase.itemData(self.cmbBase.currentIndex())
        formatter.style = self.cmbStyle.itemData(self.cmbStyle.currentIndex())
        return formatter

    def createColumnModel(self, hex_widget):
        return AddressColumnModel(None, self._formatter, self.intBaseAddress.number)

    def saveToColumn(self, column):
        column.formatter = self._formatter
        column.baseAddress = self.intBaseAddress.number
        column.reset()
Exemple #12
0
class FloatColumnConfigurationWidget(QWidget, columnproviders.AbstractColumnConfigurationWidget):
    def __init__(self, parent, hex_widget, column):
        QWidget.__init__(self, parent)
        columnproviders.AbstractColumnConfigurationWidget.__init__(self)
        self.hexWidget = hex_widget
        self.column = column

        self.cmbBinaryFormat = QComboBox(self)
        self.cmbBinaryFormat.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)

        for fmt in (valuecodecs.FloatCodec.FormatFloat, valuecodecs.FloatCodec.FormatDouble):
            self.cmbBinaryFormat.addItem(valuecodecs.FloatCodec.formatName(fmt), fmt)
            if column is not None and column.valuecodec.binaryFormat == fmt:
                self.cmbBinaryFormat.setCurrentIndex(self.cmbBinaryFormat.count() - 1)

        self.spnPrecision = QSpinBox(self)
        self.spnPrecision.setMinimum(0)
        self.spnPrecision.setMaximum(12)
        if column is not None:
            self.spnPrecision.setValue(column.formatter.precision)
        else:
            self.spnPrecision.setValue(6)

        self.spnColumnsOnRow = QSpinBox(self)
        self.spnColumnsOnRow.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.spnColumnsOnRow.setMinimum(1)
        self.spnColumnsOnRow.setMaximum(32)
        if column is not None:
            self.spnColumnsOnRow.setValue(column.columnsOnRow)
        else:
            self.spnColumnsOnRow.setValue(4)

        self.setLayout(QFormLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addRow(utils.tr('Binary format:'), self.cmbBinaryFormat)
        self.layout().addRow(utils.tr('Digits after point:'), self.spnPrecision)
        self.layout().addRow(utils.tr('Columns on row:'), self.spnColumnsOnRow)

    @property
    def _valueCodec(self):
        c = valuecodecs.FloatCodec()
        c.binaryFormat = self.cmbBinaryFormat.itemData(self.cmbBinaryFormat.currentIndex())
        return c

    @property
    def _formatter(self):
        f = formatters.FloatFormatter()
        f.precision = self.spnPrecision.value()
        return f

    def createColumnModel(self, hex_widget):
        return FloatColumnModel(hex_widget.document, self._valueCodec, self._formatter, self.spnColumnsOnRow.value())

    def saveToColumn(self, column):
        column.valuecodec = self._valueCodec
        column.formatter = self._formatter
        column.columnsOnRow = self.spnColumnsOnRow.value()
        column.reset()
Exemple #13
0
class DropDownRadioBooleanFilter(QWidget, Control):
    """Container for multiple boolean filters
    """

    def __init__(self, tree, dataset, master, parent=None):
        QWidget.__init__(self, parent)
        Control.__init__(self, tree, dataset, master)

        self.setLayout(QHBoxLayout())
        self.cb = QComboBox(self)

        self.layout().addWidget(self.cb)

        rblayout = QVBoxLayout()
        self.radioButtons = [QRadioButton("Only", self),
                             QRadioButton("Excluded", self)
                             ]

        for b in self.radioButtons:
            rblayout.addWidget(b)

        self.radioButtons[0].setChecked(True)

        self.layout().addLayout(rblayout)

        self.options = []

        self.setOptions(tree.subelements_top("Option"))

    def setOptions(self, options):
        self.cb.clear()
        self.options = []
        for option in options:
            self.cb.addItem(option.displayName)
            self.options.append(option)

        for op, rb in zip(self.options[0].subelements_top("Option"),
                          self.radioButtons):
            rb.setText(op.displayName)
            rb.setChecked(getattr(op, "default", "false") == "true")

    def value(self):
        return {"excluded": "0" if self.radioButtons[0].isChecked() else "1"}

    def query(self):
        filter = self.options[self.cb.currentIndex()]
        filter = biomart.FilterDescription(
            self.tree.registry, "FilterDescription",
            filter.attributes, filter.children)
        return [("Filter", filter, self.value())]

    def setControlValue(self, name, value):
        for i, option in enumerate(self.options):
            if option.internalName == name:
                self.cb.setCurrentIndex(i)
                if value == "Only":
                    self.radioButtons[0].setChecked(True)
class configWidget(QWidget):

    def __init__(self, parent=None):
        super(configWidget, self).__init__()
        self.setWindowFlags(Qt.FramelessWindowHint)
        self.setWindowTitle('LoL Server Status - Config')
        self.setMinimumWidth(parent.width())
        self.move(parent.pos())
        self.setFocus(False)

        #label_title
        label_title = QLabel('Configurations')
        label_title.setObjectName('label_title')
        label_title.setAlignment(Qt.AlignCenter)

        #combo_update_time
        self.combo_update_time = QComboBox()
        for item in ("1 minute", "2 minutes", "5 minutes", "10 minutes",
                     "20 minutes"):
            self.combo_update_time.addItem(item)

        #LAYOUTS
        #layout_update_time
        layout_update_time = QHBoxLayout()
        layout_update_time.addWidget(QLabel('Update time:'))
        layout_update_time.addWidget(self.combo_update_time)

        #General layout
        vbox = QVBoxLayout(self)
        vbox.addWidget(label_title)  # Add label_title
        vbox.addLayout(layout_update_time)  # Add layout_update_time

        self.load_config()

    def save_config(self):
        """This function save settings"""

        qsettings = QSettings()
        qsettings.setValue('configs/update_time',
                           self.combo_update_time.currentIndex())

    def load_config(self):
        """This function load settings"""

        qsettings = QSettings()
        self.combo_update_time.setCurrentIndex(
                    qsettings.value('configs/update_time', 0, type=int))

    def mouseDoubleClickEvent(self, event):
        if event.button() == Qt.LeftButton:
            self.save_config()
            self.close()

    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.save_config()
            self.close()
Exemple #15
0
class CurrentTaskView(QTableView):
    def __init__(self):
        super().__init__()
        self._triggers = []

    def setModel(self, model):
        super().setModel(model)

        current_task = patts.get_active_task()
        if current_task:
            parent_id = current_task[list(current_task.keys())[0]]['typeID']
        else:
            parent_id = '0'

        child_tasks = patts.get_child_types(parent_id)
        self._select_box = QComboBox()

        i = 0
        self._task_map = {}
        for task in child_tasks:
            self._select_box.addItem(child_tasks[task]['displayName'])
            self._task_map[i] = task
            i += 1

        self.setIndexWidget(model.createIndex(0, 0), self._select_box)

        clockInButton = QPushButton(_('TaskTable.clockIn'))
        clockInButton.clicked.connect(self._clock_in)
        self.setIndexWidget(model.createIndex(0, 1), clockInButton)

        if parent_id != '0':
            clockOutButton = QPushButton(_('TaskTable.clockOut'))
            clockOutButton.clicked.connect(self._clock_out)
            self.setIndexWidget(model.createIndex(1, 2), clockOutButton)

        self.resizeColumnsToContents()

    def add_trigger(self, f):
        self._triggers.append(f)

    def _clock_in(self):
        try:
            patts.clockin(self._task_map[self._select_box.currentIndex()])
            for trigger in self._triggers:
                trigger()
        except Exception as e:
            if not (type(e) is KeyError and str(e) == '-1'):
                ExceptionDialog(format_exc()).exec_()

    def _clock_out(self):
        try:
            patts.clockout(list(patts.get_active_task().keys())[0])
            for trigger in self._triggers:
                trigger()
        except:
            ExceptionDialog(format_exc()).exec_()
Exemple #16
0
class SelectFriendDialog(ModalDialog):
    def __init__(self, base):
        ModalDialog.__init__(self, 290, 110)
        self.base = base
        self.setWindowTitle(i18n.get('select_friend_to_send_message'))

        self.accounts_combo = QComboBox()
        accounts = self.base.core.get_registered_accounts()
        for account in accounts:
            protocol = get_protocol_from(account.id_)
            icon = QIcon(base.get_image_path('%s.png' % protocol))
            self.accounts_combo.addItem(icon, get_username_from(account.id_), account.id_)

        completer = QCompleter(self.base.load_friends_list())
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.friend = QLineEdit()
        self.friend.setCompleter(completer)
        select_button = QPushButton(i18n.get('select'))
        select_button.clicked.connect(self.__validate)

        friend_caption = "%s (@)" % i18n.get('friend')
        form = QFormLayout()
        form.addRow(friend_caption, self.friend)
        form.addRow(i18n.get('account'), self.accounts_combo)
        form.setContentsMargins(30, 10, 10, 5)
        form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        button = QPushButton(i18n.get('search'))
        button_box = QHBoxLayout()
        button_box.addStretch(0)
        button_box.addWidget(select_button)
        button_box.setContentsMargins(0, 0, 15, 15)

        layout = QVBoxLayout()
        layout.addLayout(form)
        layout.addLayout(button_box)
        layout.setSpacing(5)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        #load_button = ImageButton(base, 'action-status-menu.png',
        #        i18n.get('load_friends_list'))

        self.exec_()

    def __validate(self):
        if self.get_username() != '':
            self.accept()


    def get_account(self):
        index = self.accounts_combo.currentIndex()
        return str(self.accounts_combo.itemData(index).toPyObject())

    def get_username(self):
        return str(self.friend.text())
Exemple #17
0
class CurrentTaskView(QTableView):
    def __init__(self):
        super().__init__()
        self._triggers = []

    def setModel(self, model):
        super().setModel(model)

        current_task = patts.get_active_task()
        if current_task:
            parent_id = current_task[list(current_task.keys())[0]]['typeID']
        else:
            parent_id = '0'

        child_tasks = patts.get_child_types(parent_id)
        self._select_box = QComboBox()

        i = 0
        self._task_map = {}
        for task in child_tasks:
            self._select_box.addItem(child_tasks[task]['displayName'])
            self._task_map[i] = task
            i += 1

        self.setIndexWidget(model.createIndex(0, 0), self._select_box)

        clockInButton = QPushButton(_('TaskTable.clockIn'))
        clockInButton.clicked.connect(self._clock_in)
        self.setIndexWidget(model.createIndex(0, 1), clockInButton)

        if parent_id != '0':
            clockOutButton = QPushButton(_('TaskTable.clockOut'))
            clockOutButton.clicked.connect(self._clock_out)
            self.setIndexWidget(model.createIndex(1, 2), clockOutButton)

        self.resizeColumnsToContents()

    def add_trigger(self, f):
        self._triggers.append(f)

    def _clock_in(self):
        try:
            patts.clockin(self._task_map[self._select_box.currentIndex()])
            for trigger in self._triggers:
                trigger()
        except Exception as e:
            if not (type(e) is KeyError and str(e) == '-1'):
                ExceptionDialog(format_exc()).exec_()

    def _clock_out(self):
        try:
            patts.clockout(list(patts.get_active_task().keys())[0])
            for trigger in self._triggers:
                trigger()
        except:
            ExceptionDialog(format_exc()).exec_()
Exemple #18
0
class SelectFriendDialog(ModalDialog):
    def __init__(self, base):
        ModalDialog.__init__(self, 290, 110)
        self.base = base
        self.setWindowTitle(i18n.get('select_friend_to_send_message'))

        self.accounts_combo = QComboBox()
        accounts = self.base.core.get_registered_accounts()
        for account in accounts:
            protocol = get_protocol_from(account.id_)
            icon = QIcon(base.get_image_path('%s.png' % protocol))
            self.accounts_combo.addItem(icon, get_username_from(account.id_),
                                        account.id_)

        completer = QCompleter(self.base.load_friends_list())
        completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.friend = QLineEdit()
        self.friend.setCompleter(completer)
        select_button = QPushButton(i18n.get('select'))
        select_button.clicked.connect(self.__validate)

        friend_caption = "%s (@)" % i18n.get('friend')
        form = QFormLayout()
        form.addRow(friend_caption, self.friend)
        form.addRow(i18n.get('account'), self.accounts_combo)
        form.setContentsMargins(30, 10, 10, 5)
        form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        button = QPushButton(i18n.get('search'))
        button_box = QHBoxLayout()
        button_box.addStretch(0)
        button_box.addWidget(select_button)
        button_box.setContentsMargins(0, 0, 15, 15)

        layout = QVBoxLayout()
        layout.addLayout(form)
        layout.addLayout(button_box)
        layout.setSpacing(5)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        #load_button = ImageButton(base, 'action-status-menu.png',
        #        i18n.get('load_friends_list'))

        self.exec_()

    def __validate(self):
        if self.get_username() != '':
            self.accept()

    def get_account(self):
        index = self.accounts_combo.currentIndex()
        return str(self.accounts_combo.itemData(index).toPyObject())

    def get_username(self):
        return str(self.friend.text())
Exemple #19
0
class StaffGroup(_base.Container):
    @staticmethod
    def title(_=_base.translate):
        return _("Staff Group")

    def accepts(self):
        return (StaffGroup, _base.Part)

    def createWidgets(self, layout):
        self.systemStartLabel = QLabel()
        self.systemStart = QComboBox()
        self.systemStartLabel.setBuddy(self.systemStart)
        self.systemStart.setModel(
            listmodel.ListModel(
                (
                    # L10N: Brace like a piano staff
                    (lambda: _("Brace"), 'system_start_brace'),
                    # L10N: Bracket like a choir staff
                    (lambda: _("Bracket"), 'system_start_bracket'),
                    # L10N: Square bracket like a sub-group
                    (lambda: _("Square"), 'system_start_square'),
                ),
                self.systemStart,
                display=listmodel.translate_index(0),
                icon=lambda item: symbols.icon(item[1])))
        self.systemStart.setIconSize(QSize(64, 64))
        self.connectBarLines = QCheckBox(checked=True)

        box = QHBoxLayout()
        box.addWidget(self.systemStartLabel)
        box.addWidget(self.systemStart)
        layout.addLayout(box)
        layout.addWidget(self.connectBarLines)

    def translateWidgets(self):
        self.systemStartLabel.setText(_("Type:"))
        self.connectBarLines.setText(_("Connect Barlines"))
        self.connectBarLines.setToolTip(
            _("If checked, barlines are connected between the staves."))
        self.systemStart.model().update()

    def build(self, data, builder):
        s = self.systemStart.currentIndex()
        b = self.connectBarLines.isChecked()
        if s == 0:
            node = ly.dom.GrandStaff()
            if not b:
                ly.dom.Line("\\remove Span_bar_engraver", node.getWith())
        else:
            node = ly.dom.StaffGroup() if b else ly.dom.ChoirStaff()
            if s == 2:
                node.getWith()['systemStartDelimiter'] = ly.dom.Scheme(
                    "'SystemStartSquare")
        data.nodes.append(node)
        data.music = ly.dom.Simr(node)
Exemple #20
0
class InterfacePage(QWizardPage):
    """
    Allows the user to choose one among networkable interfaces to build a net upon.
    """
    def __init__(self, parent=None):
        QWizardPage.__init__(self, parent)
        self.__make_gui()
        self.__populate()
        self.connect(self.__dropdown, SIGNAL("currentIndexChanged(int)"), self.propagate)

    def __make_gui(self):
        self.setTitle(tr("Network Editor"))
        self.setSubTitle(tr("Select the interface to which you want to add a network"))
        box = QVBoxLayout(self)
        self.__dropdown = QComboBox()
        box.addWidget(self.__dropdown)

    def __candidates(self):
        candidates = list(
            QNetObject.getInstance().netcfg.iterNetworkables()
            )
        candidates.sort()
        return candidates

    def __populate(self):
        candidates = self.__candidates()
        for interface in candidates:
            variant = QVariant(interface)
            self.__dropdown.addItem(interface.fullName(), variant)

    def propagate(self):
        """
        propagate: emits a "changed" SIGNAL with the chosen interface as content
        """
        self.emit(SIGNAL("changed"), self.interface())

    def interface(self):
        """
        returns the currently selected interface
        """
        #QVariant with custom content
        variant = self.__dropdown.itemData(
            self.__dropdown.currentIndex()
            )
        interface = variant.toPyObject()
        return interface

    def setInterface(self, target):
        for index in xrange(self.__dropdown.count()):
            variant = self.__dropdown.itemData(index)
            interface = variant.toPyObject()
            if interface is target:
                break
        self.__dropdown.setCurrentIndex(index)
class NewFileDialog(QDialog):

    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setMinimumWidth(400)
        self.setWindowTitle(self.tr("Nuevo archivo"))
        self._data = {}
        container = QVBoxLayout(self)
        # Filename
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(self.tr("Nombre:")))
        self._line_filename = QLineEdit()
        hbox.addWidget(self._line_filename)
        container.addLayout(hbox)
        # Type
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(self.tr("Tipo:")))
        self._combo_type = QComboBox()
        self._combo_type.addItems([
            self.tr("Archivo Fuente"),
            self.tr("Archivo de Cabecera")
            ])
        hbox.addWidget(self._combo_type, 1)
        container.addLayout(hbox)
        # Buttons
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        btn_ok = QPushButton(self.tr("Aceptar"))
        hbox.addWidget(btn_ok)
        btn_cancel = QPushButton(self.tr("Cancelar"))
        hbox.addWidget(btn_cancel)
        container.addLayout(hbox)

        # Conexiones
        self.connect(btn_ok, SIGNAL("clicked()"), self._save_data)
        self.connect(btn_cancel, SIGNAL("clicked()"), self.close)

        self.exec_()

    def _save_data(self):
        filename = self._line_filename.text()
        file_type = self._combo_type.currentIndex()
        if file_type == 0:
            filename += '.c'
        else:
            filename += '.h'
        self._data = {'filename': filename, 'type': file_type}
        self.close()

    @property
    def data(self):
        return self._data
Exemple #22
0
class SearchDialog(QDialog):
    def __init__(self, base):
        QDialog.__init__(self)
        self.base = base
        self.setWindowTitle(i18n.get('search'))
        self.setFixedSize(270, 110)
        self.setWindowFlags(Qt.Window | Qt.WindowTitleHint
                            | Qt.WindowCloseButtonHint
                            | Qt.CustomizeWindowHint)
        self.setModal(True)

        self.accounts_combo = QComboBox()
        accounts = self.base.core.get_registered_accounts()
        for account in accounts:
            protocol = get_protocol_from(account.id_)
            icon = QIcon(base.get_image_path('%s.png' % protocol))
            self.accounts_combo.addItem(icon, get_username_from(account.id_),
                                        account.id_)

        self.criteria = QLineEdit()
        self.criteria.setToolTip(i18n.get('criteria_tooltip'))

        form = QFormLayout()
        form.addRow(i18n.get('criteria'), self.criteria)
        form.addRow(i18n.get('account'), self.accounts_combo)
        form.setContentsMargins(30, 10, 10, 5)
        form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        button = QPushButton(i18n.get('search'))
        button_box = QHBoxLayout()
        button_box.addStretch(0)
        button_box.addWidget(button)
        button_box.setContentsMargins(0, 0, 15, 15)

        button.clicked.connect(self.accept)

        layout = QVBoxLayout()
        layout.addLayout(form)
        layout.addLayout(button_box)
        layout.setSpacing(5)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        self.criteria.setFocus()

        self.exec_()

    def get_criteria(self):
        return self.criteria.text()

    def get_account(self):
        index = self.accounts_combo.currentIndex()
        return self.accounts_combo.itemData(index)
Exemple #23
0
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        principalLabel = QLabel("Principal:")
        self.principalSpinBox = QDoubleSpinBox()
        self.principalSpinBox.setRange(1, 1000000000)
        self.principalSpinBox.setValue(1000)
        self.principalSpinBox.setPrefix("$ ")
        rateLabel = QLabel("Rate:")
        self.rateSpinBox = QDoubleSpinBox()
        self.rateSpinBox.setRange(1, 100)
        self.rateSpinBox.setValue(5)
        self.rateSpinBox.setSuffix(" %")
        yearsLabel = QLabel("Years:")
        self.yearsComboBox = QComboBox()
        self.yearsComboBox.addItem("1 year")
        self.yearsComboBox.addItems(
            ["{0} years".format(x) for x in range(2, 26)])
        amountLabel = QLabel("Amount")
        self.amountLabel = QLabel()

        grid = QGridLayout()
        grid.addWidget(principalLabel, 0, 0)
        grid.addWidget(self.principalSpinBox, 0, 1)
        grid.addWidget(rateLabel, 1, 0)
        grid.addWidget(self.rateSpinBox, 1, 1)
        grid.addWidget(yearsLabel, 2, 0)
        grid.addWidget(self.yearsComboBox, 2, 1)
        grid.addWidget(amountLabel, 3, 0)
        grid.addWidget(self.amountLabel, 3, 1)
        self.setLayout(grid)

        self.connect(self.principalSpinBox, SIGNAL("valueChanged(double)"),
                     self.updateUi)
        self.connect(self.rateSpinBox, SIGNAL("valueChanged(double)"),
                     self.updateUi)
        self.connect(self.yearsComboBox, SIGNAL("currentIndexChanged(int)"),
                     self.updateUi)

        self.setWindowTitle("Interest")
        self.updateUi()

    def updateUi(self):
        """Calculates compound interest"""
        principal = self.principalSpinBox.value()
        rate = self.rateSpinBox.value()
        years = self.yearsComboBox.currentIndex() + 1
        amount = principal * ((1 + (rate / 100.0))**years)
        self.amountLabel.setText("$ {0:.2f}".format(amount))
    def addAutoFieldToAutoFieldsTable( self, autoField, candidateLayer ):
        """ Add a whole row to the AutoFields table """
        row = self.tblAutoFields.rowCount()
        self.tblAutoFields.insertRow( row )
        layerName = self.ogrLayerName( autoField['layer'] )
        item = QTableWidgetItem( layerName if layerName else autoField['layer'] )
        item.setData( Qt.UserRole, autoField['layer'] )
        item.setData( Qt.ToolTipRole, autoField['layer'] )
        self.tblAutoFields.setItem( row, 0, item )
        item = QTableWidgetItem( autoField['field'] )
        self.tblAutoFields.setItem( row, 1, item )
        item = QTableWidgetItem( autoField['expression'] )
        self.tblAutoFields.setItem( row, 2, item )

        layerCombo = QComboBox()
        layerCombo.addItem( '[Select a layer]', None )
        for layer in self.layers:
           layerCombo.addItem( layer.name(), layer.id() )
        if candidateLayer:
            layerCombo.setCurrentIndex( layerCombo.findData( candidateLayer.id() ) )
        layerCombo.currentIndexChanged.connect( partial( self.layerOrFieldCombosChanged, row ) )
        self.tblAutoFields.setCellWidget( row, 4, layerCombo )

        fieldCombo = QComboBox()
        fieldCombo.addItem( '[Select a field]', None )
        if layerCombo.currentIndex() != 0:
            for field in candidateLayer.fields():
                fieldCombo.addItem( field.name() )
            fieldIndex = fieldCombo.findText( autoField['field'] )
            fieldCombo.setCurrentIndex( fieldIndex if fieldIndex != -1 else 0 )
        fieldCombo.currentIndexChanged.connect( partial( self.layerOrFieldCombosChanged, None ) )
        self.tblAutoFields.setCellWidget( row, 5, fieldCombo )

        label = self.getLabelWithArrow( layerCombo.currentIndex(), fieldCombo.currentIndex(), candidateLayer, autoField['field'] )
        self.tblAutoFields.setCellWidget( row, 3, label )

        self.layerOrFieldCombosChanged( None, None ) # Validate initial load of AutoFields/Layers
Exemple #25
0
class StaffGroup(_base.Container):
    @staticmethod
    def title(_=_base.translate):
        return _("Staff Group")

    def accepts(self):
        return (StaffGroup, _base.Part)

    def createWidgets(self, layout):
        self.systemStartLabel = QLabel()
        self.systemStart = QComboBox()
        self.systemStartLabel.setBuddy(self.systemStart)
        self.systemStart.setModel(listmodel.ListModel((
            # L10N: Brace like a piano staff
            (lambda: _("Brace"), 'system_start_brace'),
            # L10N: Bracket like a choir staff
            (lambda: _("Bracket"), 'system_start_bracket'),
            # L10N: Square bracket like a sub-group
            (lambda: _("Square"), 'system_start_square'),
            ), self.systemStart, display=listmodel.translate_index(0),
            icon=lambda item: symbols.icon(item[1])))
        self.systemStart.setIconSize(QSize(64, 64))
        self.connectBarLines = QCheckBox(checked=True)
        
        box = QHBoxLayout()
        box.addWidget(self.systemStartLabel)
        box.addWidget(self.systemStart)
        layout.addLayout(box)
        layout.addWidget(self.connectBarLines)
    
    def translateWidgets(self):
        self.systemStartLabel.setText(_("Type:"))
        self.connectBarLines.setText(_("Connect Barlines"))
        self.connectBarLines.setToolTip(_("If checked, barlines are connected between the staves."))
        self.systemStart.model().update()
    
    def build(self, data, builder):
        s = self.systemStart.currentIndex()
        b = self.connectBarLines.isChecked()
        if s == 0:
            node = ly.dom.GrandStaff()
            if not b:
                ly.dom.Line("\\remove Span_bar_engraver", node.getWith())
        else:
            node = ly.dom.StaffGroup() if b else ly.dom.ChoirStaff()
            if s == 2:
                node.getWith()['systemStartDelimiter'] = ly.dom.Scheme("'SystemStartSquare")
        data.nodes.append(node)
        data.music = ly.dom.Simr(node)
class AppLocaleSetupDialog(QDialog):
    def __init__(self, parent):

        QDialog.__init__(self, parent)

        self.prop = MaeMoneyProperties.instance()
        self.locales = {}
        self.locales[self.prop.LANGUAGE_ZH_CN] = self.prop.LOCALE_ZH_CN
        self.locales[self.prop.LANGUAGE_ZH_HK] = self.prop.LOCALE_ZH_HK
        self.locales[self.prop.LANGUAGE_EN_US] = self.prop.LOCALE_EN_US

        self.setupUi()

    def setupUi(self):
        self.setWindowModality(Qt.WindowModal)
        self.buttonBox = QDialogButtonBox(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok)

        self.gridLayout = QGridLayout()
        self.setLayout(self.gridLayout)

        self.labelAppLocale = QLabel(u"語言 Language")
        self.gridLayout.addWidget(self.labelAppLocale, 0, 1, 1, 1)
        self.comboBoxAppLocale = QComboBox()
        for [lang, appLocale] in sorted(self.locales.iteritems()):
            self.comboBoxAppLocale.addItem(lang, appLocale)

        language = self.prop.getAppLanguage()
        index = self.comboBoxAppLocale.findText(language)
        self.comboBoxAppLocale.setCurrentIndex(index)
        self.gridLayout.addWidget(self.comboBoxAppLocale, 0, 2, 1, 1)

        self.gridLayout.addWidget(QLabel(self.tr("Current setting")), 1, 1, 1, 1)
        self.gridLayout.addWidget(QLabel(self.prop.getAppLanguage()), 1, 2, 1, 1)

        self.setLanguageButton = QPushButton(self.tr("Set language"))
        self.gridLayout.addWidget(self.setLanguageButton, 2, 1, 1, 2)

        self.setWindowTitle(self.tr("Language setup"))

        self.connect(self.buttonBox, SIGNAL("accepted()"), self.accept)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.connect(self.setLanguageButton, SIGNAL("clicked()"), self.setLanguage)

    def setLanguage(self):
        indexSelected = self.comboBoxAppLocale.currentIndex()
        locale = self.comboBoxAppLocale.itemData(indexSelected)
        self.prop.setAppLocale(locale)
        self.accept()
Exemple #27
0
class SearchDialog(QDialog):
    def __init__(self, base):
        QDialog.__init__(self)
        self.base = base
        self.setWindowTitle(i18n.get('search'))
        self.setFixedSize(270, 110)
        self.setWindowFlags(Qt.Window | Qt.WindowTitleHint | Qt.WindowCloseButtonHint | Qt.CustomizeWindowHint)
        self.setModal(True)

        self.accounts_combo = QComboBox()
        accounts = self.base.core.get_registered_accounts()
        for account in accounts:
            protocol = get_protocol_from(account.id_)
            icon = QIcon(base.get_image_path('%s.png' % protocol))
            self.accounts_combo.addItem(icon, get_username_from(account.id_), account.id_)

        self.criteria = QLineEdit()
        self.criteria.setToolTip(i18n.get('criteria_tooltip'))

        form = QFormLayout()
        form.addRow(i18n.get('criteria'), self.criteria)
        form.addRow(i18n.get('account'), self.accounts_combo)
        form.setContentsMargins(30, 10, 10, 5)
        form.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)

        button = QPushButton(i18n.get('search'))
        button_box = QHBoxLayout()
        button_box.addStretch(0)
        button_box.addWidget(button)
        button_box.setContentsMargins(0, 0, 15, 15)

        button.clicked.connect(self.accept)

        layout = QVBoxLayout()
        layout.addLayout(form)
        layout.addLayout(button_box)
        layout.setSpacing(5)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)
        self.criteria.setFocus()

        self.exec_()

    def get_criteria(self):
        return self.criteria.text()

    def get_account(self):
        index = self.accounts_combo.currentIndex()
        return self.accounts_combo.itemData(index)
Exemple #28
0
class SizeRequest(Request):
    def __init__(self, parent):
        Request.__init__(self, parent)
        self.setOperators()
        self.setContent()
        self.setSizeType()

    def setOperators(self):
        self.operatorCombo = OperatorCombo(self)
        self.hlayout.addWidget(self.operatorCombo)
        self.connect(self.operatorCombo, SIGNAL("currentIndexChanged ( int )"),
                     self.updateQuery)
        self.connect(self.operatorCombo,
                     SIGNAL("currentIndexChanged ( const QString &)"),
                     self.updateQuery)

    def updateQuery(self, data):
        self.emit(SIGNAL("queryUpdated"))

    def setContent(self):
        self.content = QLineEdit(self)
        self.validator = QIntValidator(0, 2147483647, self)
        self.content.setValidator(self.validator)
        self.hlayout.addWidget(self.content)
        self.connect(self.content, SIGNAL("textChanged(const QString &)"),
                     self.updateQuery)
        self.connect(self.content, SIGNAL("textEdited(const QString &)"),
                     self.updateQuery)

    def setSizeType(self):
        self.stype = QComboBox(self)
        self.stype.addItem(QString("KB"))
        self.stype.addItem(QString("MB"))
        self.stype.addItem(QString("GB"))
        self.hlayout.addWidget(self.stype)
        self.connect(self.stype, SIGNAL("currentIndexChanged ( int )"),
                     self.updateQuery)
        self.connect(self.stype,
                     SIGNAL("currentIndexChanged ( const QString &)"),
                     self.updateQuery)

    def request(self):
        operator = str(self.operatorCombo.currentText())
        factor = SIZE_T[self.stype.currentIndex()]
        size = self.content.text().toULongLong()[0]
        size = size * factor
        res = "(size " + operator + " " + str(size) + ")"
        return res
Exemple #29
0
class NewFileDialog(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.setMinimumWidth(400)
        self.setWindowTitle(self.tr("Nuevo archivo"))
        self._data = {}
        container = QVBoxLayout(self)
        # Filename
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(self.tr("Nombre:")))
        self._line_filename = QLineEdit()
        hbox.addWidget(self._line_filename)
        container.addLayout(hbox)
        # Type
        hbox = QHBoxLayout()
        hbox.addWidget(QLabel(self.tr("Tipo:")))
        self._combo_type = QComboBox()
        self._combo_type.addItems([self.tr("Archivo Fuente"), self.tr("Archivo de Cabecera")])
        hbox.addWidget(self._combo_type, 1)
        container.addLayout(hbox)
        # Buttons
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        btn_ok = QPushButton(self.tr("Aceptar"))
        hbox.addWidget(btn_ok)
        btn_cancel = QPushButton(self.tr("Cancelar"))
        hbox.addWidget(btn_cancel)
        container.addLayout(hbox)

        # Conexiones
        self.connect(btn_ok, SIGNAL("clicked()"), self._save_data)
        self.connect(btn_cancel, SIGNAL("clicked()"), self.close)

        self.exec_()

    def _save_data(self):
        filename = self._line_filename.text()
        file_type = self._combo_type.currentIndex()
        if file_type == 0:
            filename += ".c"
        else:
            filename += ".h"
        self._data = {"filename": filename, "type": file_type}
        self.close()

    @property
    def data(self):
        return self._data
Exemple #30
0
class CreateColumnDialog(utils.Dialog):
    def __init__(self, parent, hex_widget):
        utils.Dialog.__init__(self, parent, name='create_column_dialog')
        self.hexWidget = hex_widget
        self.configWidget = None

        self.setWindowTitle(utils.tr('Add column'))
        self.setLayout(QVBoxLayout())

        self.cmbColumnProvider = QComboBox(self)
        self.cmbColumnProvider.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
        self.layout().addWidget(self.cmbColumnProvider)
        for provider in availableProviders():
            if provider.creatable:
                self.cmbColumnProvider.addItem(provider.name, provider)

        self.txtColumnName = QLineEdit(self)
        forml = QFormLayout()
        forml.addRow(utils.tr('Name:'), self.txtColumnName)
        self.layout().addLayout(forml)

        self.cmbColumnProvider.currentIndexChanged[int].connect(self._onCurrentProviderChanged)

        self.layout().addStretch()

        self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok|QDialogButtonBox.Cancel, Qt.Horizontal, self)
        self.layout().addWidget(self.buttonBox)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self._onCurrentProviderChanged(self.cmbColumnProvider.currentIndex())

    def _onCurrentProviderChanged(self, index):
        provider = self.cmbColumnProvider.itemData(index)
        if self.configWidget is not None:
            self.configWidget.deleteLater()
            self.configWidget = None

        if provider is not None:
            self.configWidget = provider.createConfigurationWidget(self, self.hexWidget)
            self.layout().insertWidget(2, self.configWidget)

    def createColumnModel(self):
        model = self.configWidget.createColumnModel(self.hexWidget)
        model.name = self.txtColumnName.text()
        return model
Exemple #31
0
class DropDownIdListFilter(QWidget, Control):

    """Container for multiple id list filters
    """

    def __init__(self, tree, dataset, master, parent=None):
        QWidget.__init__(self, parent)
        Control.__init__(self, tree, dataset, master)

        self.setLayout(QVBoxLayout())
        self.setContentsMargins(0, 0, 0, 0)
        self.cb = QComboBox()
        self.idsEdit = QPlainTextEdit()

        self.layout().addWidget(self.cb)
        self.layout().addWidget(self.idsEdit)

        self.options = []
        self.setOptions(tree.subelements_top("Option"))

    def setOptions(self, options):
        self.cb.clear()
        self.options = []
        for option in options:
            self.cb.addItem(option.displayName)
            self.options.append(option)

    def value(self):
        return str(self.idsEdit.toPlainText()).split()

    def query(self):
        filter = self.options[self.cb.currentIndex()]
        filter = biomart.FilterDescription(
            self.tree.registry, "FilterDescription",
            filter.attributes, filter.children)
        return [("Filter", filter, self.value())]

    def setControlValue(self, name, value):
        if isinstance(value, list):
            value = "\n".join(value)

        for i, op in enumerate(self.options):
            if name == op.internalName:
                self.cb.setCurrentIndex(i)
                self.idsEdit.setPlainText(value)
class LoadResultsPanel(QWidget):

    def __init__(self):
        QWidget.__init__(self)

        self.setMinimumWidth(500)
        self.setMinimumHeight(200)
        self.__dynamic = False

        self.setWindowTitle("Load results manually")
        self.activateWindow()

        layout = QFormLayout()
        current_case = CaseSelectorModel().getCurrentChoice()

        self.__case_model = AllCasesModel()
        self.__case_combo = QComboBox()
        self.__case_combo.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLength)
        self.__case_combo.setMinimumContentsLength(20)
        self.__case_combo.setModel(self.__case_model)
        self.__case_combo.setCurrentIndex(self.__case_model.indexOf(current_case))
        layout.addRow("Select case:",self.__case_combo)


        self.__active_realizations_model = LoadResultsRealizationsModel(EnsembleSizeModel().getValue())
        self.__active_realizations_field = StringBox(self.__active_realizations_model, "Realizations to load", "load_results_manually/Realizations")
        self.__active_realizations_field.setValidator(RangeStringArgument())
        layout.addRow(self.__active_realizations_field.getLabel(), self.__active_realizations_field)

        self.__iterations_count = LoadResultsModel().getIterationCount()

        self._iterations_model = LoadResultsIterationsModel(self.__iterations_count)
        self._iterations_field = StringBox(self._iterations_model, "Iteration to load", "load_results_manually/iterations")
        self._iterations_field.setValidator(RangeStringArgument())
        layout.addRow(self._iterations_field.getLabel(), self._iterations_field)

        self.setLayout(layout)

    def load(self):
        all_cases = self.__case_model.getAllItems()
        selected_case  = all_cases[self.__case_combo.currentIndex()]
        realizations = self.__active_realizations_model.getActiveRealizationsMask()
        iterations = self._iterations_model.getActiveRealizationsMask()

        LoadResultsModel().loadResults(selected_case, realizations, iterations)
Exemple #33
0
class EkdCodecPropertie(EkdPropertie):
    """
    Définition de la propriété correspondant à un Codec
    """
    def __init__(self, prop, name, value, choices=[], section=None ):
        super(EkdCodecPropertie, self).__init__(prop, name, value, EkdPropertie.CODEC, section)
        self.label = QLabel(name)
        self.widget = QComboBox()
        self.widget.addItems(choices)
        self.value = value
        self.widget.setCurrentIndex(int(value))

        # Quand on change de codec, on met à jour EkdConfig
        self.connect(self.widget, SIGNAL("currentIndexChanged(int)"), self.updateCodec)

    def updateCodec(self):
        self.value = self.widget.currentIndex()
        EkdConfig.set(self.section, self.id, self.value)
Exemple #34
0
class ComboBox(QWidget):
    def __init__(self, id, text, **kwargs):
        QWidget.__init__(self)
        self.id = id
        self.widget = QComboBox(**kwargs)
        label = QLabel(text)
        hbox = HBoxLayout()
        hbox.addWidget(label)
        hbox.addWidget(self.widget, alignment=Qt.AlignRight)
        self.setLayout(hbox)

    def parameterValues(self):
        index = self.widget.currentIndex()
        data = self.widget.itemData(index).toString()
        if not data.isEmpty():
            text = data
        else:
            text = self.widget.currentText()
        return {self.id:text}
Exemple #35
0
class ChordNames(object):
    def createWidgets(self, layout):
        self.chordStyleLabel = QLabel()
        self.chordStyle = QComboBox()
        self.chordStyleLabel.setBuddy(self.chordStyle)
        self.chordStyle.setModel(listmodel.ListModel(chordNameStyles, self.chordStyle,
            display=listmodel.translate))
        self.guitarFrets = QCheckBox()
        
        box = QHBoxLayout()
        box.addWidget(self.chordStyleLabel)
        box.addWidget(self.chordStyle)
        layout.addLayout(box)
        layout.addWidget(self.guitarFrets)
        
    def translateWidgets(self):
        self.chordStyleLabel.setText(_("Chord style:"))
        self.guitarFrets.setText(_("Guitar fret diagrams"))
        self.guitarFrets.setToolTip(_(
            "Show predefined guitar fret diagrams below the chord names "
            "(LilyPond 2.12 and above)."))
        self.chordStyle.model().update()

    def build(self, data, builder):
        p = ly.dom.ChordNames()
        a = data.assign('chordNames')
        ly.dom.Identifier(a.name, p)
        s = ly.dom.ChordMode(a)
        ly.dom.Identifier(data.globalName, s).after = 1
        i = self.chordStyle.currentIndex()
        if i > 0:
            ly.dom.Line('\\{0}Chords'.format(
                ('german', 'semiGerman', 'italian', 'french')[i-1]), s)
        ly.dom.LineComment(_("Chords follow here."), s)
        ly.dom.BlankLine(s)
        data.nodes.append(p)
        if self.guitarFrets.isChecked():
            f = ly.dom.FretBoards()
            ly.dom.Identifier(a.name, f)
            data.nodes.append(f)
            data.includes.append("predefined-guitar-fretboards.ly")
Exemple #36
0
class ComboBox(QWidget):
    def __init__(self,
                 caption,
                 values,
                 default_value,
                 caption_size=None,
                 expand_combo=False):
        QWidget.__init__(self)

        self.values = values

        description = QLabel(caption)
        description.setWordWrap(True)
        if caption_size:
            description.setMaximumWidth(caption_size)

        self.combo = QComboBox()
        for item in values:
            self.combo.addItem(item, item)

        for i in range(0, len(values)):
            if values[i] == default_value:
                self.combo.setCurrentIndex(i)
                break

        hbox = QHBoxLayout()
        hbox.addWidget(description)
        hbox.addSpacing(10)
        if expand_combo:
            hbox.addWidget(self.combo, 1)
        else:
            hbox.addWidget(self.combo)
        hbox.setMargin(0)
        self.setLayout(hbox)
        self.setContentsMargins(0, 0, 0, 0)

    def get_value(self):
        return str(self.values[self.combo.currentIndex()])
Exemple #37
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.d_plot = TVPlot(self)        
        self.setCentralWidget( self.d_plot )
        self.toolBar = QToolBar( self )
        self.typeBox = QComboBox( self.toolBar )
        self.typeBox.addItem( "Outline" )
        self.typeBox.addItem( "Columns" )
        self.typeBox.addItem( "Lines" )
        self.typeBox.addItem( "Column Symbol" )
        self.typeBox.setCurrentIndex( self.typeBox.count() - 1 )
        self.typeBox.setSizePolicy( QSizePolicy.Fixed, QSizePolicy.Fixed )
        self.btnExport = QToolButton( self.toolBar )
        self.btnExport.setText( "Export" )
        self.btnExport.setToolButtonStyle( Qt.ToolButtonTextUnderIcon )
        #connect( btnExport, SIGNAL( clicked() ), d_plot, SLOT( exportPlot() ) )
        self.btnExport.clicked.connect(self.d_plot.exportPlot)
        self.toolBar.addWidget( self.typeBox )
        self.toolBar.addWidget( self.btnExport )
        self.addToolBar( self.toolBar )
        self.d_plot.setMode( self.typeBox.currentIndex() )
        self.typeBox.currentIndexChanged['int'].connect(self.d_plot.setMode)
Exemple #38
0
class IntervalWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        layout = QHBoxLayout(self)
        layout.setContentsMargins(0,0,0,0)

        self.spinbox = QSpinBox(self)
        self.combo = QComboBox(self)

        sp = self.spinbox.sizePolicy()
        sp.setHorizontalStretch(1)
        self.spinbox.setSizePolicy(sp)

        self.spinbox.setRange(0, (1 << 31) - 1)
        self.spinbox.setSingleStep(1)

        self.combo.addItem('Seconds')
        self.combo.addItem('Milliseconds')

        layout.addWidget(self.spinbox)
        layout.addWidget(self.combo)

    def set_interval(self, interval):
        if ('%.03f' % interval).endswith('.000'):
            self.spinbox.setValue(int(interval))
            self.combo.setCurrentIndex(0)
        else:
            self.spinbox.setValue(round(interval * 1000.0))
            self.combo.setCurrentIndex(1)

    def get_interval(self):
        if self.combo.currentIndex() == 0:
            return self.spinbox.value()
        else:
            return self.spinbox.value() / 1000.0
Exemple #39
0
class Browser(QWidget):
    """LilyPond documentation browser widget."""
    def __init__(self, dockwidget):
        super(Browser, self).__init__(dockwidget)

        layout = QVBoxLayout(spacing=0)
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

        self.toolbar = tb = QToolBar()
        self.webview = QWebView(contextMenuPolicy=Qt.CustomContextMenu)
        self.chooser = QComboBox(sizeAdjustPolicy=QComboBox.AdjustToContents)
        self.search = SearchEntry(maximumWidth=200)

        layout.addWidget(self.toolbar)
        layout.addWidget(self.webview)

        ac = dockwidget.actionCollection
        ac.help_back.triggered.connect(self.webview.back)
        ac.help_forward.triggered.connect(self.webview.forward)
        ac.help_home.triggered.connect(self.showHomePage)
        ac.help_print.triggered.connect(self.slotPrint)

        self.webview.page().setNetworkAccessManager(
            lilydoc.network.accessmanager())
        self.webview.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.webview.page().linkClicked.connect(self.openUrl)
        self.webview.page().setForwardUnsupportedContent(True)
        self.webview.page().unsupportedContent.connect(self.slotUnsupported)
        self.webview.urlChanged.connect(self.slotUrlChanged)
        self.webview.customContextMenuRequested.connect(
            self.slotShowContextMenu)

        tb.addAction(ac.help_back)
        tb.addAction(ac.help_forward)
        tb.addSeparator()
        tb.addAction(ac.help_home)
        tb.addAction(ac.help_print)
        tb.addSeparator()
        tb.addWidget(self.chooser)
        tb.addWidget(self.search)

        self.chooser.activated[int].connect(self.showHomePage)
        self.search.textEdited.connect(self.slotSearchChanged)
        self.search.returnPressed.connect(self.slotSearchReturnPressed)
        dockwidget.mainwindow().iconSizeChanged.connect(
            self.updateToolBarSettings)
        dockwidget.mainwindow().toolButtonStyleChanged.connect(
            self.updateToolBarSettings)

        app.settingsChanged.connect(self.readSettings)
        self.readSettings()
        self.loadDocumentation()
        self.showInitialPage()
        app.settingsChanged.connect(self.loadDocumentation)
        app.translateUI(self)

    def readSettings(self):
        s = QSettings()
        s.beginGroup("documentation")
        ws = self.webview.page().settings()
        family = s.value("fontfamily", self.font().family(), type(""))
        size = s.value("fontsize", 16, int)
        ws.setFontFamily(QWebSettings.StandardFont, family)
        ws.setFontSize(QWebSettings.DefaultFontSize, size)
        fixed = textformats.formatData('editor').font
        ws.setFontFamily(QWebSettings.FixedFont, fixed.family())
        ws.setFontSize(QWebSettings.DefaultFixedFontSize,
                       fixed.pointSizeF() * 96 / 72)

    def keyPressEvent(self, ev):
        if ev.text() == "/":
            self.search.setFocus()
        else:
            super(Browser, self).keyPressEvent(ev)

    def translateUI(self):
        try:
            self.search.setPlaceholderText(_("Search..."))
        except AttributeError:
            pass  # not in Qt 4.6

    def showInitialPage(self):
        """Shows the preferred start page.
        
        If a local documentation instance already has a suitable version,
        just loads it. Otherwise connects to the allLoaded signal, that is
        emitted when all the documentation instances have loaded their version
        information and then shows the start page (if another page wasn't yet
        loaded).
        
        """
        if self.webview.url().isEmpty():
            docs = lilydoc.manager.docs()
            version = lilypondinfo.preferred().version()
            index = -1
            if version:
                for num, doc in enumerate(docs):
                    if doc.version() is not None and doc.version() >= version:
                        index = num  # a suitable documentation is found
                        break
            if index == -1:
                # nothing found (or LilyPond version not available),
                # wait for loading or show the most recent version
                if not lilydoc.manager.loaded():
                    lilydoc.manager.allLoaded.connect(self.showInitialPage)
                    return
                index = len(docs) - 1
            self.chooser.setCurrentIndex(index)
            self.showHomePage()

    def loadDocumentation(self):
        """Puts the available documentation instances in the combobox."""
        i = self.chooser.currentIndex()
        self.chooser.clear()
        for doc in lilydoc.manager.docs():
            v = doc.versionString()
            if doc.isLocal():
                t = _("(local)")
            else:
                t = _("({hostname})").format(hostname=doc.url().host())
            self.chooser.addItem("{0} {1}".format(v or _("<unknown>"), t))
        self.chooser.setCurrentIndex(i)
        if not lilydoc.manager.loaded():
            lilydoc.manager.allLoaded.connect(self.loadDocumentation, -1)
            return

    def updateToolBarSettings(self):
        mainwin = self.parentWidget().mainwindow()
        self.toolbar.setIconSize(mainwin.iconSize())
        self.toolbar.setToolButtonStyle(mainwin.toolButtonStyle())

    def showManual(self):
        """Invoked when the user presses F1."""
        self.slotHomeFrescobaldi()  # TEMP

    def slotUrlChanged(self):
        ac = self.parentWidget().actionCollection
        ac.help_back.setEnabled(self.webview.history().canGoBack())
        ac.help_forward.setEnabled(self.webview.history().canGoForward())

    def openUrl(self, url):
        if url.path().endswith(('.ily', '.lyi', '.ly')):
            self.sourceViewer().showReply(lilydoc.network.get(url))
        else:
            self.webview.load(url)

    def slotUnsupported(self, reply):
        helpers.openUrl(reply.url())

    def slotSearchChanged(self):
        text = self.search.text()
        if not text.startswith(':'):
            self.webview.page().findText(text,
                                         QWebPage.FindWrapsAroundDocument)

    def slotSearchReturnPressed(self):
        text = self.search.text()
        if not text.startswith(':'):
            self.slotSearchChanged()
        else:
            pass  # TODO: implement full doc search

    def sourceViewer(self):
        try:
            return self._sourceviewer
        except AttributeError:
            from . import sourceviewer
            self._sourceviewer = sourceviewer.SourceViewer(self)
            return self._sourceviewer

    def showHomePage(self):
        """Shows the homepage of the LilyPond documentation."""
        i = self.chooser.currentIndex()
        if i < 0:
            i = 0
        doc = lilydoc.manager.docs()[i]

        url = doc.home()
        if doc.isLocal():
            path = url.toLocalFile()
            langs = lilydoc.network.langs()
            if langs:
                for lang in langs:
                    if os.path.exists(path + '.' + lang + '.html'):
                        path += '.' + lang
                        break
            url = QUrl.fromLocalFile(path + '.html')
        self.webview.load(url)

    def slotPrint(self):
        printer = QPrinter()
        dlg = QPrintDialog(printer, self)
        dlg.setWindowTitle(app.caption(_("Print")))
        if dlg.exec_():
            self.webview.print_(printer)

    def slotShowContextMenu(self, pos):
        hit = self.webview.page().currentFrame().hitTestContent(pos)
        menu = QMenu()
        if hit.linkUrl().isValid():
            a = self.webview.pageAction(QWebPage.CopyLinkToClipboard)
            a.setIcon(icons.get("edit-copy"))
            a.setText(_("Copy &Link"))
            menu.addAction(a)
            menu.addSeparator()
            a = menu.addAction(icons.get("window-new"),
                               _("Open Link in &New Window"))
            a.triggered.connect(
                (lambda url: lambda: self.slotNewWindow(url))(hit.linkUrl()))
        else:
            if hit.isContentSelected():
                a = self.webview.pageAction(QWebPage.Copy)
                a.setIcon(icons.get("edit-copy"))
                a.setText(_("&Copy"))
                menu.addAction(a)
                menu.addSeparator()
            a = menu.addAction(icons.get("window-new"),
                               _("Open Document in &New Window"))
            a.triggered.connect((lambda url: lambda: self.slotNewWindow(url))(
                self.webview.url()))
        if menu.actions():
            menu.exec_(self.webview.mapToGlobal(pos))

    def slotNewWindow(self, url):
        helpers.openUrl(url)
Exemple #40
0
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setWindowTitle('Address Book')
        self.resize(704, 459)
        self.db_file = self.database_file()
        self.db = database.Database(self.db_file)

        dialog = dialogs.UserPanelDlg(self)
        if dialog.exec_():
            self.user = dialog.user
        else:
            self.close()

        self.categComboBox = QComboBox()
        self.cont_numLabel = QLabel()
        self.contactsListWidget = QListWidget()
        self.searchLineEdit = QLineEdit()

        widgets = ((QLabel('Category:'), self.categComboBox),
                   (self.cont_numLabel, None),
                   (self.contactsListWidget,),
                   (QLabel('Search:'), self.searchLineEdit))
        vlayout1 = QVBoxLayout()

        for i in widgets:
            hlayout = pyqttools.add_to_layout(QHBoxLayout(), i)
            vlayout1.addLayout(hlayout)

        addToolButton = QToolButton()
        addToolButton.setIcon(QIcon(':addcontact.jpeg'))
        addToolButton.setIconSize(QSize(45, 45))
        self.showLabel = QLabel()
        self.showLabel.setFrameShape(QFrame.StyledPanel)
        self.showLabel.setAlignment(Qt.AlignLeading|Qt.AlignLeft|Qt.AlignTop)
        self.editButton = QPushButton('Edit')
        self.delButton = QPushButton('Delete')

        widgets = ((None, addToolButton, None),
                   (self.showLabel,),
                   (None, self.editButton, self.delButton))
        vlayout2 = QVBoxLayout()

        for i in widgets:
            hlayout = pyqttools.add_to_layout(QHBoxLayout(), i)
            vlayout2.addLayout(hlayout)

        f_layout = pyqttools.add_to_layout(QHBoxLayout(), (vlayout1, vlayout2))

        Widget = QWidget()
        Widget.setLayout(f_layout)
        self.setCentralWidget(Widget)

        self.statusBar = self.statusBar()
        self.userLabel = QLabel()
        self.statusBar.addPermanentWidget(self.userLabel)

        c_action = pyqttools.create_action
        panelAction = c_action(self, 'User panel', triggered=self.user_panel)
        quitAction = c_action(self, 'Quit', 'Ctrl+Q',triggered=self.close)
        add_contactAction = c_action(self, 'Add contact', 'Ctrl+N',
                                                    triggered=self.add_contact)
        delete_allAction = c_action(self, 'Delete all contacts',
                                                     triggered=self.delete_all)
        delete_categAction = c_action(self, 'Delete categories',
                                              triggered=self.delete_categories)
        backupAction = c_action(self, 'Backup', triggered=self.backup)
        restoreAction = c_action(self, 'Restore', triggered=self.restore)
        aboutAction = c_action(self, 'About', 'Ctrl+?', triggered=self.about)

        fileMenu = self.menuBar().addMenu('File')
        contactsMenu = self.menuBar().addMenu('Contacts')
        deleteMenu = self.menuBar().addMenu(self.tr('Delete'))
        backupMenu = self.menuBar().addMenu(self.tr('Backup'))
        helpMenu = self.menuBar().addMenu('Help')

        pyqttools.add_actions(fileMenu, [panelAction, None, quitAction])
        pyqttools.add_actions(contactsMenu, [add_contactAction])
        pyqttools.add_actions(deleteMenu,[delete_allAction,delete_categAction])
        pyqttools.add_actions(backupMenu, [backupAction, restoreAction])
        pyqttools.add_actions(helpMenu, [aboutAction])

        addToolButton.clicked.connect(self.add_contact)
        self.editButton.clicked.connect(self.edit_contact)
        self.delButton.clicked.connect(self.delete_contact)
        self.categComboBox.currentIndexChanged.connect(self.fill_ListWidget)
        self.contactsListWidget.currentRowChanged.connect(self.show_contact)
        self.searchLineEdit.textEdited.connect(self.search)

        self.fill_categComboBox()
        self.refresh_userLabel()

    def fill_categComboBox(self):
        categories = ['All']
        categories.extend([i[1] for i in self.db.get_categories(self.user)])
        self.categComboBox.currentIndexChanged.disconnect(self.fill_ListWidget)
        self.categComboBox.clear()
        self.categComboBox.addItems(categories)
        self.categComboBox.currentIndexChanged.connect(self.fill_ListWidget)
        self.fill_ListWidget()

    def fill_ListWidget(self):
        self.showLabel.clear()
        self.contactsListWidget.clear()
        if self.categComboBox.currentIndex() != 0: self.searchLineEdit.clear()

        category = self.categComboBox.currentText()
        if category == 'All':
            contacts = self.db.get_all_contacts(self.user)
        else:
            categ_id = self.db.get_category_id(category, self.user)
            if categ_id is None: return
            contacts = self.db.get_contacts(categ_id)
        for i in contacts:
            self.contactsListWidget.addItem(MyListItem(i[1]+' '+i[2], i[0]))

        self.contactsListWidget.setCurrentRow(0)
        self.refresh_contacts_number()
        self.set_buttons_enabled()

    def refresh_userLabel(self):
        self.userLabel.setText('User:  '******'Contacts Numer:  {0}'.format(self.contactsListWidget.count())
        self.cont_numLabel.setText(text)

    def set_buttons_enabled(self):
        enable = bool(self.contactsListWidget)
        self.editButton.setEnabled(enable)
        self.delButton.setEnabled(enable)

    def user_panel(self):
        dialog = dialogs.UserPanelDlg(self)
        if dialog.exec_():
            self.user = dialog.user
            self.fill_categComboBox()
            self.refresh_userLabel()

    def show_contact(self):
        try:
            _id = self.contactsListWidget.currentItem()._id
        except AttributeError:
            return
        _id, name, surname, mail, address, tel, categ_id = \
                                           self.db.get_contact_from_id(_id)[0]
        category = self.db.get_category_from_id(categ_id)
        text = ''
        data = (name, surname, mail, address, tel, category)
        labs = ('Name', 'Surname', 'e-mail', 'Address', 'Telephone', 'Category')
        for i, y in zip(labs, data):
            text += '''<p style=\' margin-top:0px; margin-bottom:0px; \'>
                  <span style=\' font-weight:600;\'>{0}:</span> {1} </p>\n'''\
                                                                  .format(i, y)
        self.showLabel.setText(text)

    def add_contact(self):
        categories = [i[1] for i in self.db.get_categories(self.user)]
        dialog = dialogs.AddorEditContactDlg(categories)
        if dialog.exec_():
            data = dialog.values
            if data[-1] not in categories:
                self.db.addto_categories(data[-1], self.user)
            categ_id = self.db.get_category_id(data[-1], self.user)
            data[-1] = categ_id
            self.db.addto_contacts(data)
            self.fill_categComboBox()

    def edit_contact(self):
        _id = self.contactsListWidget.currentItem()._id
        data = list(self.db.get_contact_from_id(_id)[0])
        categ = self.db.get_category_from_id(data[-1])
        data[-1] = categ
        categories = [i[1] for i in self.db.get_categories(self.user)]
        dialog = dialogs.AddorEditContactDlg(categories, True, data)
        if dialog.exec_():
            new_data = dialog.values
            if new_data[-1] not in categories:
                self.db.addto_categories(new_data[-1], self.user)
            categ_id = self.db.get_category_id(new_data[-1], self.user)
            new_data[-1] = categ_id
            self.db.edit_contact(new_data, _id)
            self.fill_categComboBox()

    def delete_contact(self):
        reply = QMessageBox.question(self, 'Address Book - Delete Contact',
        'Are you sure that you want to delete this contact?',
        QMessageBox.Yes|QMessageBox.Cancel)
        if reply == QMessageBox.Yes:
            _id = self.contactsListWidget.currentItem()._id
            self.db.delete_contact(_id)
            self.fill_ListWidget()

    def delete_all(self):
        reply = QMessageBox.question(self, 'Address Book - Delete Contact',
        'Are you sure that you want to delete all contacts?',
        QMessageBox.Yes|QMessageBox.Cancel)
        if reply == QMessageBox.Yes:
            self.db.delete_all_contacts()
            self.fill_ListWidget()

    def delete_categories(self):
        categories = [i[1] for i in self.db.get_categories(self.user)]
        dialogs.DelCategoriesDlg(categories, self).exec_()
        self.fill_categComboBox()

    def search(self):
        self.categComboBox.setCurrentIndex(0)
        self.showLabel.clear()
        self.contactsListWidget.clear()

        txt = self.searchLineEdit.text()

        if all(i == ' ' for i in txt):
            self.fill_ListWidget()
            return

        must_appear = []
        contacts = self.db.get_all_contacts(self.user)

        if not ' ' in txt:
            for i in contacts:
                if txt.lower() in i[1].lower() or txt.lower() in i[2].lower():
                    must_appear.append(i)
        else:
            try:
                first, last = txt.split()
            except ValueError:
                return
            for i in contacts:
                _bool = bool(first.lower() in i[1].lower() or first.lower() in
                             i[2].lower() or last.lower() in i[1].lower() or
                             last.lower() in i[2].lower())
                if _bool: must_appear.append(i)

        for i in must_appear:
            item = MyListItem(i[1] + ' ' + i[2], i[0])
            self.contactsListWidget.addItem(item)

        self.contactsListWidget.setCurrentRow(0)
        self.refresh_contacts_number()
        self.set_buttons_enabled()

    def backup(self):
        fname = QFileDialog.getSaveFileName(self,'Address Book - Backup','.db')
        if fname:
            try:
                shutil.copy(self.db_file, fname)
            except IOError:
                pass

    def restore(self):
        reply = QMessageBox.question(self, 'Address Book - Restore',
            'All current contacts will be deleted.\nAre you sure that you want'
            ' to continue?', QMessageBox.Yes|QMessageBox.Cancel)
        if reply == QMessageBox.Yes:
            fname = QFileDialog.getOpenFileName(self, 'Address Book - Restore')
            if fname:
                msg = 'Succesful restore!'
                try:
                    os.remove(self.db_file)
                    shutil.copy(fname, self.db_file)
                except (OSError, IOError):
                    msg = 'Restore failed!'
                QMessageBox.information(self, 'Addess Book - Restore', msg)
                self.db = database.Database(self.db_file)
                self.fill_categComboBox()

    def database_file(self):
        _file = 'addressbook.db'
        if not platform.platform().startswith('Windows'):
            folder = os.getenv('HOME') + os.sep + '.addressbook'
            if not os.path.exists(folder): os.mkdir(folder)
            _file = folder + os.sep + _file
        return _file

    def about(self):
        link = 'http://wiki.ubuntu-gr.org/Address%20Book'
        QMessageBox.about(self, self.tr('About') + ' FF Multi Converter',
            '''<b> Address Book {0} </b>
            <p>Gui application to organize your contacts!
            <p>Copyright &copy; 2012 Ilias Stamatis
            <br>License: GNU GPL3
            <p><a href='{1}'>http://wiki.ubuntu-gr.org/Address Book</a>
            <p>Python {2} - Qt {3} - PyQt {4} on {5}'''
            .format(__version__, link, platform.python_version()[:5],
            QT_VERSION_STR, PYQT_VERSION_STR, platform.system()))

    def close(self):
        self.db.close()
        sys.exit()
class EditDialog(QDialog):
    pagetitle = "Edit Term's Assessment"
    holdc = {}

    def __init__(self, sid, mid, parent=None):
        super(EditDialog, self).__init__(parent)
        self.sid = sid
        self.mid = mid

        displayInfo = self.pullSubjects()

        dis = self.pullOne(self.mid)

        self.l1 = QLabel("Assessment Types")
        self.le = QComboBox()
        for dd in displayInfo:
            self.le.addItem(str(dd['name']).upper(), dd['id'])

        self.le.setObjectName("name")
        #self.le.setCurrentIndex(2)

        self.l2 = QLabel("Max Score")
        self.le2 = QLineEdit()
        self.le2.setObjectName("maxscore")
        if dis:
            self.le2.setText(dis['abbrv'])
        else:
            pass

        self.pb = QPushButton()
        self.pb.setObjectName("Submit")
        self.pb.setText("Submit")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        layout = QFormLayout()
        layout.addRow(self.l1, self.le)
        layout.addRow(self.l2, self.le2)
        layout.addRow(self.pb1, self.pb)

        groupBox = QGroupBox('Add Assessment')
        groupBox.setLayout(layout)

        grid = QGridLayout()
        grid.addWidget(groupBox, 0, 0)
        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"),
                     lambda: self.button_click(self))
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close(self))

        self.setWindowTitle(self.pagetitle)

    def pullSubjects(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {'pubID': 7})
        return arr

    def pullOne(self, b):
        cn = Db()
        arr = cn.selectn('datas', '', 1, {'id': b})
        return arr

    def button_close(self, a):
        a.close()
        self.lunchForm()

    def lunchForm(self):
        sid = self.sid
        form = TermCaDialog(sid)
        form.show()

    def button_click(self, b):
        # shost is a QString object
        b.close()
        sid = self.sid
        mid = self.mid
        s2 = self.le2.text()
        s1 = self.le.itemData(self.le.currentIndex())
        g = Db()
        try:
            if (int(s2) > 0):
                y = {'name': s1, 'abbrv': s2}
                z = {'id': mid}
                g.update('datas', y, z)

            else:
                pass
        except:
            pass

        try:
            self.lunchForm()
        except:
            pass
        try:
            self.close()
        except:
            pass
class TermFeeDialog(QDialog):

    holdc = {}

    def __init__(self, term, parent=None):
        super(TermFeeDialog, self).__init__(parent)
        self.term = term
        terms = self.pullOnes('terms', self.term)
        session = self.pullOnes('session', terms['sessionID'])
        self.termname = str(
            session['name']) + ' ' + terms['name'] + ' Term Report'
        self.pagetitle = self.termname

        #pull all CA
        ko = 0
        feesText = QLabel('Select Fee')
        feesAmountText = QLabel('Amount')
        self.feesPop = QLabel('Total:')
        self.feesAmount = QLineEdit()
        self.feesAmount.setObjectName("schno")
        self.feesAmount.setPlaceholderText("000.00")
        self.feesCombo = QComboBox()
        self.arr = self.pullFees()
        self.hol = {}
        ko = 0
        if self.arr and len(self.arr) > 0:
            for val in self.arr:
                self.feesCombo.addItem(val['name'].upper())
                self.hol[ko] = val['id']
                ko += 1

        self.tree1 = QTreeWidget()
        self.tree1.setHeaderLabel("Choose Class")
        self.cla_arr = {}
        parent1 = QTreeWidgetItem(self.tree1)
        parent1.setText(0, "Select Class")
        parent1.setFlags(parent1.flags() | Qt.ItemIsTristate
                         | Qt.ItemIsUserCheckable)
        arr1 = self.pullClass()
        if arr1 and len(arr1) > 0:
            for val in arr1:
                child = QTreeWidgetItem(parent1)
                child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                child.setText(0, str(val['name']).upper())

                self.cla_arr[val['id']] = child
                if (val['active'] == 0):
                    child.setCheckState(0, Qt.Unchecked)
                else:
                    child.setCheckState(0, Qt.Unchecked)
                ko += 1

        self.tree1.itemClicked.connect(lambda x=7: self.getClass(x))

        self.hw = QFormLayout()
        self.hw.addRow(feesText, self.feesCombo)

        self.hw1 = QFormLayout()
        self.hw1.addRow(feesAmountText, self.feesAmount)

        layout1 = QGridLayout()
        layout1.addLayout(self.hw, 0, 0)
        layout1.addWidget(self.tree1, 1, 0)
        layout1.addLayout(self.hw1, 2, 0)

        layout2 = QGridLayout()
        layout2.addWidget(self.feesPop, 0, 0)

        groupBox1 = QGroupBox('Fees Settings')
        groupBox1.setLayout(layout1)

        self.pb = QPushButton()
        self.pb.setObjectName("Add")
        self.pb.setText("Add Fees")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Cancel")
        self.pb1.setText("Cancel")

        hbo = QHBoxLayout()
        hbo.addWidget(self.pb1)
        hbo.addStretch()
        hbo.addWidget(self.pb)
        groupBox2 = QGroupBox('')
        groupBox2.setLayout(hbo)

        groupBox3 = QGroupBox('')
        groupBox3.setLayout(layout2)

        grid = QGridLayout()
        grid.addWidget(groupBox1, 0, 0)
        grid.addWidget(groupBox3, 1, 0)
        grid.addWidget(groupBox2, 2, 0)

        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click())
        self.connect(self.pb1, SIGNAL("clicked()"),
                     lambda: self.button_close(self))

        self.setWindowTitle(self.pagetitle)

    def getClass(self, x):
        # shost is a QString object
        class_arr = []
        for i in self.cla_arr:
            if self.cla_arr[i].checkState(0) == Qt.Checked:
                class_arr.append(i)

        c = self.getClassStudent(class_arr)
        self.feesPop.setText('Total: ' + str(c[0]))
        self.cla = class_arr
        self.students = c[1]

    def getClassStudent(self, x=[]):
        post = StudentTable(self.term, [None], x, [None])
        d = post.classStudentMul()
        return d

    def pullSubjects(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {'pubID': 7})
        return arr

    def pullOne(self, b):
        cn = Db()
        arr = cn.selectn('datas', '', 1, {'id': b})
        return arr

    def pullOnes(self, a, b):
        cn = Db()
        arr = cn.selectn(a, '', 1, {'id': b})
        return arr

    def pullFees(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 17, "active": 0})
        return arr

    def pullClass(self):
        cn = Db()
        arr = cn.selectn('datas', '', '', {"pubID": 1, "active": 0})
        return arr

    def pullRep(self):
        cn = Db()
        ca = "rep"
        arr = cn.selectn('datas', '', '', {"subID": self.sid, "pubID": ca})
        return arr

    def button_close(self, b):
        b.close()

    def button_report(self, b):
        b.close()
        self.post = ReportDialog(self.sid)
        self.post.show()

    def button_click(self):
        tex = ' Please wait processing, do not cancel or close..'
        self.feesPop.setText(tex)
        _term = self.term
        _class = self.cla
        _students = self.students
        _amount = self.feesAmount.text()
        _fee = self.hol[self.feesCombo.currentIndex()]
        feeStudent = 0
        feeStudentUp = 0
        ins = []
        ups = []
        for j in _class:
            st = self.getClassStudent([j])
            post = StudentTable(self.term, [None], [None], [None])
            _students = post.getIDs(st[1])
            data = {}
            data['pubID'] = 'fee'
            data['subID'] = _term
            data['abbrv'] = _fee
            data['name'] = j

            cn = Db()
            check = cn.selectn('datas', '', 1, data)
            if (check and check['id'] > 0):
                if float(check['description']) == float(_amount):
                    pass
                else:
                    #update
                    sid = cn.update('datas', {'description': _amount},
                                    {'id': check['id']})
                    re = self.feeStudentsUpdate(_term, _students, _fee,
                                                _amount, check['id'])
                    feeStudent = re[0]
                    feeStudentUp = re[1]
            else:
                data['description'] = _amount
                sid = cn.insert('datas', data)
                if int(sid) > 0:
                    feeStudent = self.feeStudents(_term, _students, _fee,
                                                  _amount, sid)

            ins.append(int(feeStudent))
            ups.append(int(feeStudentUp))
        tex = ' TOTAL of ' + str(sum(ins)) + ' inserted ' + str(
            sum(ups)) + ' updated.'
        self.feesPop.setText(tex)

    def feeStudents(self, session, students, fee, amount, sid):
        db = 'student_fee' + str(session)
        cn = Db()
        ed = []

        for s in students:
            data = {}
            data['studentID'] = s
            data['feeID'] = fee
            data['amount'] = amount
            data['active'] = sid

            chk = cn.selectn(db, '', 1, data)
            if (chk and int(chk['id']) > 0):
                #confirm if money available
                pass
            else:
                #if money not set , set
                e = cn.insert(db, data)
                ed.append(e)

        return len(ed)

    def feeStudentsUpdate(self, session, students, fee, amount, sid):
        db = 'student_fee' + str(session)
        cn = Db()
        ed = []
        ed1 = []

        for s in students:
            datas = {}
            datas['studentID'] = s
            datas['feeID'] = fee
            #datas['active'] = sid

            data = {}
            data['studentID'] = s
            data['feeID'] = fee
            data['amount'] = amount
            data['active'] = sid
            e = cn.update(db, data, datas)
            if e == 1:
                ed1.append(e)
            else:
                e = cn.insert(db, data)
                ed.append(e)

        return [len(ed), len(ed1)]

    def lunchEditForm(self, row):
        term = self.term
        self.close()
        self.post = EditReportDialog(term, row)
        self.post.show()

    def lunchDeleteForm(self, row):
        cn = Db()
        arr = cn.update('datas', {"active": 1})
        self.close()
        self.__init__(self.term, self.termname)
Exemple #43
0
class TradingWidget(QFrame):
    """简单交易组件"""
    signal = QtCore.pyqtSignal(type(Event()))
    
    directionList = [DIRECTION_LONG,
                     DIRECTION_SHORT]
    
    offsetList = [OFFSET_OPEN,
                  OFFSET_CLOSE,
                  OFFSET_CLOSEYESTERDAY,
                  OFFSET_CLOSETODAY]
    
    priceTypeList = [PRICETYPE_LIMITPRICE,
                     PRICETYPE_VWAP,
                     PRICETYPE_TWAP]
    
    exchangeList = [EXCHANGE_NONE,
                    EXCHANGE_CFFEX,
                    EXCHANGE_SHFE,
                    EXCHANGE_DCE,
                    EXCHANGE_CZCE,
                    EXCHANGE_SSE,
                    EXCHANGE_SZSE,
                    EXCHANGE_SGE,
                    EXCHANGE_HKEX,
                    
                    EXCHANGE_CSI, 
                    EXCHANGE_HKH, 
                    EXCHANGE_HKS, 
                    EXCHANGE_JZ,  
                    EXCHANGE_SPOT,
                    EXCHANGE_IB,  
                    EXCHANGE_FX,  
                    EXCHANGE_INE, 
                    
                    EXCHANGE_SMART,
                    EXCHANGE_ICE,
                    EXCHANGE_CME,
                    EXCHANGE_NYMEX,
                    EXCHANGE_GLOBEX,
                    EXCHANGE_IDEALPRO]
    
    currencyList = [CURRENCY_NONE,
                    CURRENCY_CNY,
                    CURRENCY_USD]
    
    productClassList = [PRODUCT_NONE,
                        PRODUCT_EQUITY,
                        PRODUCT_FUTURES,
                        PRODUCT_OPTION,
                        PRODUCT_BOND,
                        PRODUCT_FOREX]
    
    # ----------------------------------------------------------------------
    def __init__(self, mainEngine, eventEngine, parent=None):
        """Constructor"""
        super(TradingWidget, self).__init__(parent)
        self.mainEngine = mainEngine
        self.eventEngine = eventEngine
        
        self.symbol = ''
        self.signalemit = None
        
        self.initUi()
        self.connectSignal()
    
    # ----------------------------------------------------------------------
    def initUi(self):
        """初始化界面"""
        self.setWindowTitle(u'交易')
        self.setMaximumWidth(500)
        self.setFrameShape(self.Box)  # 设置边框
        self.setLineWidth(1)
        
        # 左边部分
        labelSymbol = QLabel(u'代码')
        labelName = QLabel(u'名称')
        labelDirection = QLabel(u'方向类型')
        labelOffset = QLabel(u'开平')
        labelPrice = QLabel(u'价格')
        labelVolume = QLabel(u'数量')
        labelPriceType = QLabel(u'价格类型')
        labelExchange = QLabel(u'交易所')
        labelCurrency = QLabel(u'货币')
        labelProductClass = QLabel(u'产品类型')
        labelUrgency = QLabel(u'紧急度')
        
        self.lineSymbol = QLineEdit()
        self.lineName = QLineEdit()
        
        self.comboDirection = QComboBox()
        self.comboDirection.addItems(self.directionList)
        
        self.comboOffset = QComboBox()
        self.comboOffset.addItem('')
        self.comboOffset.addItems(self.offsetList)
        self.comboOffset.setEnabled(False)
        
        self.tickOffset = QCheckBox(u'指定')
        
        self.spinPrice = QDoubleSpinBox()
        self.spinPrice.setDecimals(4)
        self.spinPrice.setMinimum(0)
        self.spinPrice.setMaximum(100000)
        
        self.spinVolume = QSpinBox()
        self.spinVolume.setMinimum(0)
        self.spinVolume.setMaximum(1000000)
        
        self.comboPriceType = QComboBox()
        self.comboPriceType.addItems(self.priceTypeList)
        
        self.comboExchange = QComboBox()
        self.comboExchange.addItems(self.exchangeList)
        self.comboExchange.setEnabled(False)
        
        self.comboCurrency = QComboBox()
        self.comboCurrency.addItems(self.currencyList)
        self.comboCurrency.setEnabled(False)
        
        self.comboProductClass = QComboBox()
        self.comboProductClass.addItems(self.productClassList)
        self.comboProductClass.setEnabled(False)
        
        self.spinUrgency = QSpinBox()
        self.spinUrgency.setMinimum(1)
        self.spinUrgency.setMaximum(9)
        self.spinUrgency.setSingleStep(1)
        self.spinUrgency.setValue(5)
        
        gridleft = QGridLayout()
        gridleft.addWidget(labelSymbol, 0, 0)
        gridleft.addWidget(labelName, 1, 0)
        gridleft.addWidget(labelDirection, 2, 0)
        gridleft.addWidget(labelOffset, 3, 0)
        gridleft.addWidget(labelPrice, 4, 0)
        gridleft.addWidget(labelVolume, 5, 0)
        gridleft.addWidget(labelPriceType, 6, 0)
        gridleft.addWidget(labelUrgency, 7, 0)
        gridleft.addWidget(labelExchange, 8, 0)
        gridleft.addWidget(labelProductClass, 9, 0)
        gridleft.addWidget(labelCurrency, 10, 0)
        
        gridleft.addWidget(self.lineSymbol, 0, 1)
        gridleft.addWidget(self.lineName, 1, 1)
        gridleft.addWidget(self.comboDirection, 2, 1)
        
        hbox1 = QHBoxLayout()
        hbox1.addWidget(self.comboOffset)
        lable1 = QLabel()
        hbox1.addWidget(lable1)
        hbox1.addWidget(self.tickOffset)
        hbox1.setStretchFactor(self.comboOffset, 4)
        hbox1.setStretchFactor(lable1, 1)
        hbox1.setStretchFactor(self.tickOffset, 3)
        gridleft.addItem(hbox1, 3, 1)
        
        gridleft.addWidget(self.spinPrice, 4, 1)
        gridleft.addWidget(self.spinVolume, 5, 1)
        gridleft.addWidget(self.comboPriceType, 6, 1)
        gridleft.addWidget(self.spinUrgency, 7, 1)
        gridleft.addWidget(self.comboExchange, 8, 1)
        gridleft.addWidget(self.comboProductClass, 9, 1)
        gridleft.addWidget(self.comboCurrency, 10, 1)
        
        # 右边部分
        labelBid1 = QLabel(u'买一')
        labelBid2 = QLabel(u'买二')
        labelBid3 = QLabel(u'买三')
        labelBid4 = QLabel(u'买四')
        labelBid5 = QLabel(u'买五')
        
        labelAsk1 = QLabel(u'卖一')
        labelAsk2 = QLabel(u'卖二')
        labelAsk3 = QLabel(u'卖三')
        labelAsk4 = QLabel(u'卖四')
        labelAsk5 = QLabel(u'卖五')
        
        self.labelBidPrice1 = QLabel()
        self.labelBidPrice2 = QLabel()
        self.labelBidPrice3 = QLabel()
        self.labelBidPrice4 = QLabel()
        self.labelBidPrice5 = QLabel()
        self.labelBidVolume1 = QLabel()
        self.labelBidVolume2 = QLabel()
        self.labelBidVolume3 = QLabel()
        self.labelBidVolume4 = QLabel()
        self.labelBidVolume5 = QLabel()
        
        self.labelAskPrice1 = QLabel()
        self.labelAskPrice2 = QLabel()
        self.labelAskPrice3 = QLabel()
        self.labelAskPrice4 = QLabel()
        self.labelAskPrice5 = QLabel()
        self.labelAskVolume1 = QLabel()
        self.labelAskVolume2 = QLabel()
        self.labelAskVolume3 = QLabel()
        self.labelAskVolume4 = QLabel()
        self.labelAskVolume5 = QLabel()
        
        labelLast = QLabel(u'最新')
        self.labelLastPrice = QLabel()
        self.labelReturn = QLabel()
        
        self.labelLastPrice.setMinimumWidth(60)
        self.labelReturn.setMinimumWidth(60)
        
        gridRight = QGridLayout()
        gridRight.addWidget(labelAsk5, 0, 0)
        gridRight.addWidget(labelAsk4, 1, 0)
        gridRight.addWidget(labelAsk3, 2, 0)
        gridRight.addWidget(labelAsk2, 3, 0)
        gridRight.addWidget(labelAsk1, 4, 0)
        gridRight.addWidget(labelLast, 5, 0)
        gridRight.addWidget(labelBid1, 6, 0)
        gridRight.addWidget(labelBid2, 7, 0)
        gridRight.addWidget(labelBid3, 8, 0)
        gridRight.addWidget(labelBid4, 9, 0)
        gridRight.addWidget(labelBid5, 10, 0)
        
        gridRight.addWidget(self.labelAskPrice5, 0, 1)
        gridRight.addWidget(self.labelAskPrice4, 1, 1)
        gridRight.addWidget(self.labelAskPrice3, 2, 1)
        gridRight.addWidget(self.labelAskPrice2, 3, 1)
        gridRight.addWidget(self.labelAskPrice1, 4, 1)
        gridRight.addWidget(self.labelLastPrice, 5, 1)
        gridRight.addWidget(self.labelBidPrice1, 6, 1)
        gridRight.addWidget(self.labelBidPrice2, 7, 1)
        gridRight.addWidget(self.labelBidPrice3, 8, 1)
        gridRight.addWidget(self.labelBidPrice4, 9, 1)
        gridRight.addWidget(self.labelBidPrice5, 10, 1)
        
        gridRight.addWidget(self.labelAskVolume5, 0, 2)
        gridRight.addWidget(self.labelAskVolume4, 1, 2)
        gridRight.addWidget(self.labelAskVolume3, 2, 2)
        gridRight.addWidget(self.labelAskVolume2, 3, 2)
        gridRight.addWidget(self.labelAskVolume1, 4, 2)
        gridRight.addWidget(self.labelReturn, 5, 2)
        gridRight.addWidget(self.labelBidVolume1, 6, 2)
        gridRight.addWidget(self.labelBidVolume2, 7, 2)
        gridRight.addWidget(self.labelBidVolume3, 8, 2)
        gridRight.addWidget(self.labelBidVolume4, 9, 2)
        gridRight.addWidget(self.labelBidVolume5, 10, 2)
        
        # 发单按钮
        buttonSendOrder = QPushButton(u'发单')
        buttonCancelAll = QPushButton(u'全撤')
        
        size = buttonSendOrder.sizeHint()
        buttonSendOrder.setMinimumHeight(size.height() * 2)  # 把按钮高度设为默认两倍
        buttonCancelAll.setMinimumHeight(size.height() * 2)
        
        # 整合布局
        hbox = QHBoxLayout()
        hbox.addLayout(gridleft)
        hbox.addLayout(gridRight)
        
        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.addWidget(buttonSendOrder)
        vbox.addWidget(buttonCancelAll)
        vbox.addStretch()
        
        self.setLayout(vbox)
        
        # 关联更新
        buttonSendOrder.clicked.connect(self.sendOrder)
        buttonCancelAll.clicked.connect(self.cancelAll)
        self.lineSymbol.returnPressed.connect(self.updateSymbol)
        self.comboDirection.currentIndexChanged.connect(self.updateOffset)
        self.tickOffset.stateChanged.connect(self.updateOffset)
        
        self.labelAskPrice1.mouseDoubleClickEvent = self.ask1clicked
        self.labelAskPrice2.mouseDoubleClickEvent = self.ask2clicked
        self.labelAskPrice3.mouseDoubleClickEvent = self.ask3clicked
        self.labelAskPrice4.mouseDoubleClickEvent = self.ask4clicked
        self.labelAskPrice5.mouseDoubleClickEvent = self.ask5clicked
        
        self.labelBidPrice1.mouseDoubleClickEvent = self.bid1clicked
        self.labelBidPrice2.mouseDoubleClickEvent = self.bid2clicked
        self.labelBidPrice3.mouseDoubleClickEvent = self.bid3clicked
        self.labelBidPrice4.mouseDoubleClickEvent = self.bid4clicked
        self.labelBidPrice5.mouseDoubleClickEvent = self.bid5clicked
        
        self.labelLastPrice.mouseDoubleClickEvent = self.lastclicked
    
    def ask1clicked(self, a):
        self.askclicked(self.labelAskPrice1.text())
    
    def ask2clicked(self, a):
        self.askclicked(self.labelAskPrice2.text())
    
    def ask3clicked(self, a):
        self.askclicked(self.labelAskPrice3.text())
    
    def ask4clicked(self, a):
        self.askclicked(self.labelAskPrice4.text())
    
    def ask5clicked(self, a):
        self.askclicked(self.labelAskPrice5.text())
    
    def bid1clicked(self, a):
        self.bidclicked(self.labelBidPrice1.text())
    
    def bid2clicked(self, a):
        self.bidclicked(self.labelBidPrice2.text())
    
    def bid3clicked(self, a):
        self.bidclicked(self.labelBidPrice3.text())
    
    def bid4clicked(self, a):
        self.bidclicked(self.labelBidPrice4.text())
    
    def bid5clicked(self, a):
        self.bidclicked(self.labelBidPrice5.text())
    
    def lastclicked(self, a):
        self.setPrice(self.labelLastPrice.text())
    
    def setPrice(self, text):
        result = False
        if text is not None and len(text) > 0:
            price = float(str(text))
            if price > 0:
                self.spinPrice.setValue(price)
                result = True
        return result
    
    def askclicked(self, text):
        if self.setPrice(text):
            self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG))
            self.updateOffset()
    
    def bidclicked(self, text):
        if self.setPrice(text):
            self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT))
            self.updateOffset()
    
    def updateOffset(self):
        if self.tickOffset.checkState():
            self.comboOffset.setEnabled(True)
            if self.comboProductClass.currentText() in (PRODUCT_EQUITY, PRODUCT_BOND):
                dir = self.comboDirection.currentText()
                if dir == DIRECTION_LONG:
                    self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_OPEN) + 1)
                elif dir == DIRECTION_SHORT:
                    self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1)
            elif self.comboOffset.currentIndex() == 0:
                self.comboOffset.setCurrentIndex(1)
        else:
            self.comboOffset.setEnabled(False)
            self.comboOffset.setCurrentIndex(0)
    
    # ----------------------------------------------------------------------
    def updateSymbol(self):
        """合约变化"""
        # 读取组件数据
        symbol = str(self.lineSymbol.text())
        self.comboCurrency.setCurrentIndex(1)
        
        currency = safeUnicode(self.comboCurrency.currentText())
        gatewayName = safeUnicode('quantos')
        
        # 查询合约
        contract = self.mainEngine.getContract(symbol)
        
        # 清空价格数量
        self.spinPrice.setValue(0)
        self.spinVolume.setValue(0)
        
        if contract:
            gatewayName = contract.gatewayName
            self.lineName.setText(contract.name)
            p = self.lineName.palette()
            p.setColor(self.lineName.foregroundRole(), QtGui.QColor('black'))
            self.lineName.setPalette(p)
            exchange = contract.exchange
            productClass = contract.productClass
            self.comboExchange.setCurrentIndex(self.exchangeList.index(exchange))
            self.comboProductClass.setCurrentIndex(self.productClassList.index(productClass))
            self.spinPrice.setSingleStep(contract.priceTick)
            self.spinVolume.setSingleStep(contract.lotsize)
            
            self.updateOffset()
        
        else:
            self.comboExchange.setCurrentIndex(0)
            self.comboProductClass.setCurrentIndex(0)
            productClass = safeUnicode(self.comboProductClass.currentText())
            exchange = safeUnicode(self.comboExchange.currentText())
            self.lineName.setText(u'不存在')
            p = self.lineName.palette()
            p.setColor(self.lineName.foregroundRole(), QtGui.QColor('red'))
            self.lineName.setPalette(p)
        
        # 清空行情显示
        self.labelBidPrice1.setText('')
        self.labelBidPrice2.setText('')
        self.labelBidPrice3.setText('')
        self.labelBidPrice4.setText('')
        self.labelBidPrice5.setText('')
        self.labelBidVolume1.setText('')
        self.labelBidVolume2.setText('')
        self.labelBidVolume3.setText('')
        self.labelBidVolume4.setText('')
        self.labelBidVolume5.setText('')
        self.labelAskPrice1.setText('')
        self.labelAskPrice2.setText('')
        self.labelAskPrice3.setText('')
        self.labelAskPrice4.setText('')
        self.labelAskPrice5.setText('')
        self.labelAskVolume1.setText('')
        self.labelAskVolume2.setText('')
        self.labelAskVolume3.setText('')
        self.labelAskVolume4.setText('')
        self.labelAskVolume5.setText('')
        self.labelLastPrice.setText('')
        self.labelReturn.setText('')
        
        if contract:
            # 重新注册事件监听
            if self.signalemit != None:
                self.eventEngine.unregister(EVENT_TICK + self.symbol, self.signalemit)
            
            self.signalemit = self.signal.emit
            self.eventEngine.register(EVENT_TICK + symbol, self.signalemit)
            
            # 订阅合约
            self.mainEngine.subscribe(contract.symbol, gatewayName)
            
            # 更新组件当前交易的合约
            self.symbol = symbol

    # ----------------------------------------------------------------------
    def format_price(self, price):
        return int(price * 1000) / 1000

    # ----------------------------------------------------------------------
    def updateTick(self, event):
        """更新行情"""
        tick = event.dict_['data']

        if tick.symbol == self.symbol:
            contract = self.mainEngine.getContract(tick.symbol)
            price_tick = contract.priceTick

            self.labelBidPrice1.setText(str(self.format_price(tick.bidPrice1)))
            self.labelAskPrice1.setText(str(self.format_price(tick.askPrice1)))
            self.labelBidVolume1.setText(str(tick.bidVolume1))
            self.labelAskVolume1.setText(str(tick.askVolume1))
            
            if tick.bidPrice2:
                self.labelBidPrice2.setText(str(self.format_price(tick.bidPrice2)))
                self.labelBidPrice3.setText(str(self.format_price(tick.bidPrice3)))
                self.labelBidPrice4.setText(str(self.format_price(tick.bidPrice4)))
                self.labelBidPrice5.setText(str(self.format_price(tick.bidPrice5)))
                
                self.labelAskPrice2.setText(str(self.format_price(tick.askPrice2)))
                self.labelAskPrice3.setText(str(self.format_price(tick.askPrice3)))
                self.labelAskPrice4.setText(str(self.format_price(tick.askPrice4)))
                self.labelAskPrice5.setText(str(self.format_price(tick.askPrice5)))
                
                self.labelBidVolume2.setText(str(tick.bidVolume2))
                self.labelBidVolume3.setText(str(tick.bidVolume3))
                self.labelBidVolume4.setText(str(tick.bidVolume4))
                self.labelBidVolume5.setText(str(tick.bidVolume5))
                
                self.labelAskVolume2.setText(str(tick.askVolume2))
                self.labelAskVolume3.setText(str(tick.askVolume3))
                self.labelAskVolume4.setText(str(tick.askVolume4))
                self.labelAskVolume5.setText(str(tick.askVolume5))
            
            self.labelLastPrice.setText(str(self.format_price(tick.lastPrice)))
            if self.spinPrice.value() < 0.000001 and tick.lastPrice > 0.000001:
                self.spinPrice.setValue(tick.lastPrice)
            
            if tick.preClosePrice:
                rt = (old_div(tick.lastPrice, tick.preClosePrice)) - 1
                self.labelReturn.setText(('%.2f' % (rt * 100)) + '%')
            else:
                self.labelReturn.setText('')
    
    # ----------------------------------------------------------------------
    def connectSignal(self):
        """连接Signal"""
        self.signal.connect(self.updateTick)
    
    # ----------------------------------------------------------------------
    def sendOrder(self):
        """发单"""
        symbol = str(self.lineSymbol.text()).strip()
        exchange = safeUnicode(self.comboExchange.currentText())
        price = self.spinPrice.value()
        volume = self.spinVolume.value()
        gatewayName = safeUnicode('quantos')
        
        if len(symbol) <= 0 or len(exchange) <= 0 or price <= 0 or volume <= 0:
            return
        
        # 查询合约
        contract = self.mainEngine.getContract(symbol)

        if contract:
            gatewayName = contract.gatewayName
            exchange = contract.exchange  # 保证有交易所代码
        
        req = VtOrderReq()
        idx = symbol.find(".")
        if idx != -1:
            req.symbol = symbol[0:idx]
        else:
            req.symbol = symbol
        req.exchange = exchange
        req.price = price
        req.volume = volume
        req.direction = safeUnicode(self.comboDirection.currentText())
        req.priceType = safeUnicode(self.comboPriceType.currentText())
        req.offset = safeUnicode(self.comboOffset.currentText())
        req.urgency = self.spinUrgency.value()
        req.productClass = safeUnicode(self.comboProductClass.currentText())
        
        self.mainEngine.sendOrder(req, gatewayName)
    
    # ----------------------------------------------------------------------
    def cancelAll(self):
        """一键撤销所有委托"""
        l = self.mainEngine.getAllWorkingOrders()
        for order in l:
            req = VtCancelOrderReq()
            req.symbol = order.symbol
            req.exchange = order.exchange
            req.frontID = order.frontID
            req.sessionID = order.sessionID
            req.orderID = order.taskID
            self.mainEngine.cancelOrder(req, order.gatewayName)
    
    # ----------------------------------------------------------------------
    def closePosition(self, cell):
        """根据持仓信息自动填写交易组件"""
        # 读取持仓数据,cell是一个表格中的单元格对象
        pos = cell.data
        symbol = pos.symbol
        
        # 更新交易组件的显示合约
        self.lineSymbol.setText(symbol)
        self.updateSymbol()
        
        # 自动填写信息
        self.comboPriceType.setCurrentIndex(self.priceTypeList.index(PRICETYPE_LIMITPRICE))
        self.spinVolume.setValue(pos.enable)
        if pos.direction == DIRECTION_LONG or pos.direction == DIRECTION_NET:
            self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_SHORT))
        else:
            self.comboDirection.setCurrentIndex(self.directionList.index(DIRECTION_LONG))
        
        if self.comboProductClass.currentText() not in (PRODUCT_EQUITY, PRODUCT_BOND):
            self.tickOffset.setChecked(True)
            self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1)
        elif self.tickOffset.checkState():
            self.comboOffset.setCurrentIndex(self.offsetList.index(OFFSET_CLOSE) + 1)
            
            # 价格留待更新后由用户输入,防止有误操作
    
    def fillSymbol(self, cell):
        
        tick = cell.data
        self.lineSymbol.setText(tick.symbol)
        
        self.updateSymbol()
        
        if type(cell) in (BidCell, AskCell):
            price = str(cell.text())
            if len(price) > 0:
                price = float(price)
                if price > 0:
                    self.spinPrice.setValue(price)
                    direction = DIRECTION_LONG if type(cell) is AskCell else DIRECTION_SHORT
                    self.comboDirection.setCurrentIndex(self.directionList.index(direction))
                    self.updateOffset()
Exemple #44
0
class EditOrAddMemberDialog(QDialog, FWidget):
    def __init__(self,
                 table_p,
                 parent,
                 scoop=None,
                 member=None,
                 *args,
                 **kwargs):
        FWidget.__init__(self, parent, *args, **kwargs)

        self.table_p = table_p
        self.member = member
        self.scoop = scoop
        self.parent = parent
        full_name = ""
        self.ddn_field = FormatDate(QDate(QDate.currentDate()))

        addres = ""
        nationality = ""
        phone = ""
        if self.member:
            self.new = False
            full_name = self.member.full_name
            mddn = self.member.ddn
            if mddn:
                day, month, year = mddn.split("/")
                ddn = datetime.strptime(mddn, '%d/%m/%Y')
                self.ddn_field.setDate(QDate(ddn))
            addres = self.member.addres
            nationality = self.member.nationality
            phone = str(self.member.phone or "")

            self.title = u"Modification de {}".format(self.member)
            self.succes_msg = u"{} a été bien mise à jour".format(self.member)
        else:
            self.new = True
            self.succes_msg = u"Client a été bien enregistré"
            self.title = u"Ajout nouveau membre"
            self.member = CooperativeMember()
        self.setWindowTitle(self.title)

        vbox = QVBoxLayout()
        # vbox.addWidget(FPageTitle(u"Utilisateur: %s " % self.member.name))

        self.full_name_field = LineEdit(full_name)
        self.sex_list = CooperativeMember.SEX.items()
        # Combobox widget
        self.sex_box = QComboBox()

        for index, value in enumerate(self.sex_list):
            # form = self.sex_list[index]
            self.sex_box.addItem("{}".format(value[1].upper()), value[0])
            if self.member.sex == value[0]:
                self.sex_box.setCurrentIndex(index)
        # print("DE", ddn)
        # self.ddn_field.setDate(ddn)
        # self.ddn_field = QDateEdit(QDate(ddn))
        self.addres_field = QTextEdit(addres)
        self.nationality_field = LineEdit(nationality)
        self.phone_field = IntLineEdit(phone)
        self.phone_field.setInputMask("## ## ## ##")
        self.poste_list = get_postes()
        self.poste_box = QComboBox()
        for index, value in enumerate(self.poste_list):
            self.poste_box.addItem(
                "{}".format(self.poste_list.get(value).upper()), value)
            if self.member.poste == value:
                print(value)
                self.poste_box.setCurrentIndex(index)

        formbox = QFormLayout()
        formbox.addRow(FormLabel(u"Nom complet : *"), self.full_name_field)
        formbox.addRow(FormLabel(u"Sexe *:"), self.sex_box)
        formbox.addRow(FormLabel(u"Date de naissance *:"), self.ddn_field)
        formbox.addRow(FormLabel(u"Poste occupé *:"), self.poste_box)
        formbox.addRow(FormLabel(u"Nationalité *:"), self.nationality_field)
        formbox.addRow(FormLabel(u"Téléphone :"), self.phone_field)
        formbox.addRow(FormLabel(u"Adresse :"), self.addres_field)

        butt = Button(u"Enregistrer")
        butt.clicked.connect(self.save_edit)
        formbox.addRow("", butt)

        vbox.addLayout(formbox)
        self.setLayout(vbox)

    def is_valide(self):
        if check_is_empty(self.full_name_field):
            return False
        if check_is_empty(self.ddn_field):
            return False
        if check_is_empty(self.nationality_field):
            return False
        if check_is_empty(self.phone_field):
            return False
        return True

    def save_edit(self):
        ''' add operation '''
        if not self.is_valide():
            return
        print("Save")
        self.member.scoop = self.scoop
        self.member.full_name = self.full_name_field.text()
        self.member.sex = self.sex_box.itemData(self.sex_box.currentIndex())
        self.member.ddn = self.ddn_field.text()
        self.member.addres = self.addres_field.toPlainText()
        self.member.nationality = self.nationality_field.text()
        phone = self.phone_field.text()
        self.member.phone = is_int(phone)
        self.member.poste = self.poste_box.itemData(
            self.poste_box.currentIndex())
        try:
            self.member.save_()
            self.close()
            self.table_p.refresh_()
            self.parent.Notify(
                u"Le membre {} ({}) a été mise à jour".format(
                    self.member.full_name, self.member.poste), "success")
        except peewee.IntegrityError:
            field_error(self.full_name_field,
                        "Ce nom existe dans la basse de donnée.")
Exemple #45
0
class CSVOptionsWidget(QWidget):
    _PresetDelimiters = [
        ("Comma", ","),
        ("Tab", "\t"),
        ("Semicolon", ";"),
        ("Space", " "),
    ]

    format_changed = Signal()

    def __init__(self, parent=None, **kwargs):
        self._delimiter_idx = 0
        self._delimiter_custom = "|"
        self._delimiter = ","
        self._quotechar = "'"
        self._escapechar = "\\"
        self._doublequote = True
        self._skipinitialspace = False

        super(QWidget, self).__init__(parent, **kwargs)

        # Dialect options
        form = QFormLayout()
        self.delimiter_cb = QComboBox()
        self.delimiter_cb.addItems(
            [name for name, _ in self._PresetDelimiters])
        self.delimiter_cb.insertSeparator(self.delimiter_cb.count())
        self.delimiter_cb.addItem("Other")

        self.delimiter_cb.setCurrentIndex(self._delimiter_idx)
        self.delimiter_cb.activated.connect(self._on_delimiter_idx_changed)

        validator = QRegExpValidator(QRegExp("."))
        self.delimiteredit = LineEdit(self._delimiter_custom,
                                      enabled=False,
                                      minimumContentsLength=2)
        self.delimiteredit.setValidator(validator)
        self.delimiteredit.editingFinished.connect(self._on_delimiter_changed)

        delimlayout = QHBoxLayout()
        delimlayout.setContentsMargins(0, 0, 0, 0)
        delimlayout.addWidget(self.delimiter_cb)
        delimlayout.addWidget(self.delimiteredit)

        self.quoteedit = LineEdit(self._quotechar, minimumContentsLength=2)
        self.quoteedit.setValidator(validator)
        self.quoteedit.editingFinished.connect(self._on_quotechar_changed)

        self.escapeedit = LineEdit(self._escapechar, minimumContentsLength=2)
        self.escapeedit.setValidator(validator)
        self.escapeedit.editingFinished.connect(self._on_escapechar_changed)

        #         self.skipinitialspace_cb = QCheckBox(
        #             checked=self._skipinitialspace
        #         )

        form.addRow("Cell delimiter", delimlayout)
        form.addRow("Quote character", self.quoteedit)
        form.addRow("Escape character", self.escapeedit)

        form.addRow(QFrame(self, frameShape=QFrame.HLine))

        # File format option
        self.missingedit = QLineEdit()
        self.missingedit.editingFinished.connect(self.format_changed)

        form.addRow("Missing values", self.missingedit)

        self.header_format_cb = QComboBox()
        self.header_format_cb.addItems([
            "No header", "Plain header", "Orange header",
            "Orange simplified header"
        ])
        self.header_format_cb.currentIndexChanged.connect(self.format_changed)
        form.addRow("Header", self.header_format_cb)

        self.setLayout(form)
        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)

    def dialect(self):
        """
        Return the current state as a Dialect instance.
        """
        if self._delimiter_idx >= len(self._PresetDelimiters):
            delimiter = self._delimiter_custom
        else:
            _, delimiter = self._PresetDelimiters[self._delimiter_idx]

        quotechar = str(self.quoteedit.text()) or ""
        escapechar = str(self.escapeedit.text()) or None
        skipinitialspace = True
        return Dialect(delimiter,
                       quotechar,
                       escapechar,
                       doublequote=True,
                       skipinitialspace=skipinitialspace)

    def set_dialect(self, dialect):
        """
        Set the current state to match dialect instance.
        """
        delimiter = dialect.delimiter
        try:
            index = [d for _, d in self._PresetDelimiters].index(delimiter)
        except ValueError:
            index = len(self._PresetDelimiters) + 1
        self._delimiter_idx = index
        self._delimiter_custom = delimiter
        self._quotechar = dialect.quotechar
        self._escapechar = dialect.escapechar
        self._skipinitialspace = dialect.skipinitialspace

        self.delimiter_cb.setCurrentIndex(index)
        self.delimiteredit.setText(delimiter)
        self.quoteedit.setText(dialect.quotechar or '"')
        self.escapeedit.setText(dialect.escapechar or "")


#         self.skipinitialspace_cb.setChecked(dialect.skipinitialspace)

    def set_header_format(self, header_format):
        """Set the current selected header format."""
        self._header_format = header_format
        self.header_format_cb.setCurrentIndex(header_format)

    def header_format(self):
        return self.header_format_cb.currentIndex()

    def set_missing_values(self, missing):
        self.missingedit.setText(missing)

    def missing_values(self):
        return str(self.missingedit.text())

    def _on_delimiter_idx_changed(self, index):
        if index < len(self._PresetDelimiters):
            self.delimiteredit.setText(self._PresetDelimiters[index][1])
        else:
            self.delimiteredit.setText(self._delimiter_custom)

        self.delimiteredit.setEnabled(index >= len(self._PresetDelimiters))
        self._delimiter_idx = index

        self.format_changed.emit()

    def _on_delimiter_changed(self):
        self._delimiter_custom = str(self.delimiteredit.text())
        self.format_changed.emit()

    def _on_quotechar_changed(self):
        self._quotechar = str(self.quoteedit.text())
        self.format_changed.emit()

    def _on_escapechar_changed(self):
        self._escapechar = str(self.escapeedit.text())
        self.format_changed.emit()

    def _on_skipspace_changed(self, skipinitialspace):
        self._skipinitialspace = skipinitialspace
        self.format_changed.emit()
class MCAHPanel(QWidget):
    def __init__(self, parent, altitudeUnit=AltitudeUnits.FT):
        QWidget.__init__(self, parent)
        while not isinstance(parent, QDialog):
            parent = parent.parent()
        self.setObjectName("MCAHPanel" +
                           str(len(parent.findChildren(MCAHPanel))))

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

        self.hLayout = QHBoxLayout(self)
        self.hLayout.setSpacing(0)
        self.hLayout.setMargin(0)
        self.hLayout.setObjectName("hLayout")

        self.basicFrame = Frame(self, "HL")
        self.basicFrame.Spacing = 0
        self.hLayout.addWidget(self.basicFrame)

        self.lblMCAH = QLabel(self.basicFrame)
        self.lblMCAH.setMinimumSize(QSize(250, 0))
        font = QFont()
        font.setWeight(50)
        font.setBold(False)
        self.lblMCAH.setFont(font)
        self.lblMCAH.setObjectName(("lblMCAH"))
        self.basicFrame.Add = self.lblMCAH
        self.cmbMCAH = QComboBox(self.basicFrame)
        font = QFont()
        font.setWeight(50)
        font.setBold(False)
        self.cmbMCAH.setFont(font)
        self.cmbMCAH.setObjectName(self.objectName() + "_cmbMCAH")
        self.basicFrame.Add = self.cmbMCAH
        self.txtMCAH = QLineEdit(self.basicFrame)
        font = QFont()
        font.setWeight(50)
        font.setBold(False)
        self.txtMCAH.setFont(font)
        self.txtMCAH.setObjectName(self.objectName() + "_txtMCAH")
        self.txtMCAH.setMinimumWidth(70)
        self.txtMCAH.setMaximumWidth(70)
        self.basicFrame.Add = self.txtMCAH
        self.setLayout(self.hLayout)

        spacerItem = QSpacerItem(0, 10, QSizePolicy.Minimum,
                                 QSizePolicy.Minimum)
        self.hLayout.addItem(spacerItem)
        self.cmbMCAH.addItems([MCAHType.MCA, MCAHType.MCH])
        #         self.txtMCAH.textChanged.connect(self.txtAltitude_TextChanged)
        self.altitudeUnit = altitudeUnit

    def setValue(self, altitude_0):
        if self.altitudeUnit == AltitudeUnits.FT:
            value1 = altitude_0.Feet
        elif self.altitudeUnit == AltitudeUnits.M:
            value1 = altitude_0.Metres
        self.txtMCAH.setText(str(value1))

    def set_Value(self, altitude_0):
        if self.altitudeUnit == AltitudeUnits.FT:
            value1 = altitude_0.Feet
        elif self.altitudeUnit == AltitudeUnits.M:
            value1 = altitude_0.Metres
        self.txtMCAH.setText(str(value1))

    def get_Value(self):
        try:
            return Altitude(float(self.txtMCAH.text()), self.altitudeUnit)
        except:
            raise UserWarning, self.lblMCAH.text() + " is invalid!"

    Value = property(get_Value, set_Value, None, None)

    def IsEmpty(self):
        if self.txtMCAH.text() == "":
            return True
        else:
            return False

    def method_2(self, altitude_0):
        if (self.cmbMCAH.currentIndex() == 0):
            return self.Value
        return self.Value + (altitude_0)

    def method_3(self, altitude_0):
        if (self.cmbMCAH.currentIndex() != 0):
            return self.Value
        return self.Value - (altitude_0)
Exemple #47
0
class CADOptionsToolbar_Arc(CADOptionsToolbar):
    def __init__(self, layer):
        super(CADOptionsToolbar_Arc, self).__init__()
        self.settings = QSettings()

        self.arc_featurePitch = self.settings.value("/CADDigitize/arc/pitch",
                                                    2, type=float)
        self.arc_featureAngle = self.settings.value("/CADDigitize/arc/angle",
                                                    1, type=int)
        self.arc_method = self.settings.value("/CADDigitize/arc/method",
                                              "pitch", type=str)
        self.arc_angleDirection = self.settings.value(
                                        "/CADDigitize/arc/direction",
                                        "ClockWise", type=str)
        if layer.geometryType() == 2:
            self.arc_polygonCreation = self.settings.value(
                "/CADDigitize/arc/polygon",  "pie")
            self.ArcPolygonCombo = QComboBox(self.optionsToolBar)
            self.ArcPolygonCombo.addItems([
                tr(u"Pie segment"),
                tr(u"Chord")])
            self.ArcPolygonComboAction = self.optionsToolBar.addWidget(
                self.ArcPolygonCombo)
            if self.arc_polygonCreation == "pie":
                self.ArcPolygonCombo.setCurrentIndex(0)
            else:
                self.ArcPolygonCombo.setCurrentIndex(1)

            self.ArcPolygonCombo.currentIndexChanged["int"].connect(
                self.polygonArc)

        self.ArcAngleDirectionCombo = QComboBox(self.optionsToolBar)
        self.ArcAngleDirectionCombo.addItems([
            tr(u"ClockWise"),
            tr(u"CounterClockWise")])
        self.ArcAngleDirectionComboAction = self.optionsToolBar.addWidget(
            self.ArcAngleDirectionCombo)

        self.ArcFeatureCombo = QComboBox(self.optionsToolBar)
        self.ArcFeatureCombo.addItems([
            tr(u"Pitch"),
            tr(u"Angle")])
        self.ArcFeatureComboAction = self.optionsToolBar.addWidget(
            self.ArcFeatureCombo)

        self.ArcPitchSpin = QDoubleSpinBox(self.optionsToolBar)
        self.ArcPitchSpin.setMinimum(1)
        self.ArcPitchSpin.setMaximum(1000)
        self.ArcPitchSpin.setDecimals(1)
        self.ArcPitchSpin.setValue(self.arc_featurePitch)
        self.ArcPitchSpinAction = self.optionsToolBar.addWidget(
            self.ArcPitchSpin)
        self.ArcPitchSpin.setToolTip(tr(u"Pitch"))
        self.ArcPitchSpinAction.setEnabled(True)

        self.ArcAngleSpin = QDoubleSpinBox(self.optionsToolBar)
        self.ArcAngleSpin.setMinimum(1)
        self.ArcAngleSpin.setMaximum(3600)
        self.ArcAngleSpin.setDecimals(0)
        self.ArcAngleSpin.setValue(self.arc_featureAngle)
        self.ArcAngleSpinAction = self.optionsToolBar.addWidget(
            self.ArcAngleSpin)
        self.ArcAngleSpin.setToolTip(tr(u"Angle"))
        self.ArcAngleSpinAction.setEnabled(True)

        if self.arc_method == "pitch":
            self.ArcPitchSpin.setEnabled(True)
            self.ArcAngleSpin.setEnabled(False)
            self.ArcFeatureCombo.setCurrentIndex(0)
        else:
            self.ArcPitchSpin.setEnabled(False)
            self.ArcAngleSpin.setEnabled(True)
            self.ArcFeatureCombo.setCurrentIndex(1)

        if self.arc_angleDirection == "ClockWise":
            self.ArcAngleDirectionCombo.setCurrentIndex(0)
        else:
            self.ArcAngleDirectionCombo.setCurrentIndex(1)

        self.ArcPitchSpin.valueChanged["double"].connect(
            self.pitchSettings)
        self.ArcAngleSpin.valueChanged["double"].connect(
            self.angleSettings)
        self.ArcFeatureCombo.currentIndexChanged["int"].connect(
            self.featureArc)
        self.ArcAngleDirectionCombo.currentIndexChanged["int"].connect(
            self.angleDirectionArc)

    def polygonArc(self):
        if self.ArcPolygonCombo.currentIndex() == 0:
            self.settings.setValue("/CADDigitize/arc/polygon", "pie")
        else:
            self.settings.setValue("/CADDigitize/arc/polygon", "chord")

    def angleDirectionArc(self):
        if self.ArcAngleDirectionCombo.currentIndex() == 0:
            self.settings.setValue("/CADDigitize/arc/direction",
                                   "ClockWise")
        else:
            self.settings.setValue("/CADDigitize/arc/direction",
                                   "CounterClockWise")

    def angleSettings(self):
        self.arc_featureAngle = self.ArcAngleSpin.value()
        self.settings.setValue("/CADDigitize/arc/angle",
                               self.arc_featureAngle)

    def pitchSettings(self):
        self.arc_featurePitch = self.ArcPitchSpin.value()
        self.settings.setValue("/CADDigitize/arc/pitch",
                               self.arc_featurePitch)

    def featureArc(self):
        if self.ArcFeatureCombo.currentIndex() == 0:
            self.ArcPitchSpin.setEnabled(True)
            self.ArcAngleSpin.setEnabled(False)
            self.settings.setValue("/CADDigitize/arc/method",
                                   "pitch")
        else:
            self.ArcPitchSpin.setEnabled(False)
            self.ArcAngleSpin.setEnabled(True)
            self.settings.setValue("/CADDigitize/arc/method",
                                   "angle")
class MotorizedLinearPoti(COMCUPluginBase):
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletMotorizedLinearPoti, *args)

        self.mp = self.device

        self.cbe_position = CallbackEmulator(self.mp.get_position,
                                             self.cb_position,
                                             self.increase_error_count)

        self.current_position = None

        self.slider = QSlider(Qt.Horizontal)
        self.slider.setRange(0, 100)
        self.slider.setMinimumWidth(200)
        self.slider.setEnabled(False)

        plots = [('Potentiometer Position', Qt.red, lambda: self.current_position, str)]
        self.plot_widget = PlotWidget('Position', plots, extra_key_widgets=[self.slider],
                                      curve_motion_granularity=40, update_interval=0.025)

        self.motor_slider = QSlider(Qt.Horizontal)
        self.motor_slider.setRange(0, 100)
        self.motor_slider.valueChanged.connect(self.motor_slider_value_changed)
        self.motor_hold_position = QCheckBox("Hold Position")
        self.motor_drive_mode = QComboBox()
        self.motor_drive_mode.addItem('Fast')
        self.motor_drive_mode.addItem('Smooth')
        
        def get_motor_slider_value():
            return self.motor_slider.value()
        
        self.motor_hold_position.stateChanged.connect(lambda x: self.motor_slider_value_changed(get_motor_slider_value()))
        self.motor_drive_mode.currentIndexChanged.connect(lambda x: self.motor_slider_value_changed(get_motor_slider_value()))

        self.motor_position_label = MotorPositionLabel('Motor Target Position:')

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.motor_position_label)
        hlayout.addWidget(self.motor_slider)
        hlayout.addWidget(self.motor_drive_mode)
        hlayout.addWidget(self.motor_hold_position)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(hlayout)

    def start(self):
        async_call(self.mp.get_position, None, self.cb_position, self.increase_error_count)
        async_call(self.mp.get_motor_position, None, self.cb_motor_position, self.increase_error_count)

        self.cbe_position.set_period(25)
        self.plot_widget.stop = False

    def stop(self):
        self.cbe_position.set_period(0)
        self.plot_widget.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletMotorizedLinearPoti.DEVICE_IDENTIFIER

    def cb_position(self, position):
        self.current_position = position
        self.slider.setValue(position)

    def cb_motor_position(self, motor):
        self.motor_slider.blockSignals(True)
        self.motor_hold_position.blockSignals(True)
        self.motor_drive_mode.blockSignals(True)

        self.motor_hold_position.setChecked(motor.hold_position)
        self.motor_drive_mode.setCurrentIndex(motor.drive_mode)
        self.motor_position_label.setText(str(motor.position))
        self.motor_slider.setValue(motor.position)

        self.motor_slider.blockSignals(False)
        self.motor_hold_position.blockSignals(False)
        self.motor_drive_mode.blockSignals(False)

    
    def motor_slider_value_changed(self, position):
        self.motor_position_label.setText(str(position))
        self.mp.set_motor_position(self.motor_slider.value(), self.motor_drive_mode.currentIndex(), self.motor_hold_position.isChecked())
Exemple #49
0
class ReportDialog(QDialog):
    def __init__(self, parent, params):

        QDialog.__init__(self, parent)

        self.parent = parent
        self.params = params

        self.setMinimumWidth(min_width)
        # self.setMinimumHeight(min_height)

        # Build dialog
        self.setWindowTitle('Options - Report')  # TODO: softcode
        self.setWindowModality(QtCore.Qt.ApplicationModal)

        self.fra_form = QFrame(self)
        fra_form_lay = QFormLayout(self.fra_form)
        fra_form_lay.setContentsMargins(10, 10, 10, 10)

        self.lbl_status = QLabel('Hydraulic status:')  # TODO: softocode
        self.cbo_status = QComboBox()
        fra_form_lay.addRow(self.lbl_status, self.cbo_status)

        self.lbl_summary = QLabel('Summary')  # TODO: softocode
        self.cbo_summary = QComboBox()
        fra_form_lay.addRow(self.lbl_summary, self.cbo_summary)

        self.lbl_energy = QLabel('Energy')  # TODO: softocode
        self.cbo_energy = QComboBox()
        fra_form_lay.addRow(self.lbl_energy, self.cbo_energy)

        self.lbl_nodes = QLabel('Nodes')  # TODO: softocode
        self.cbo_nodes = QComboBox()
        fra_form_lay.addRow(self.lbl_nodes, self.cbo_nodes)

        self.lbl_links = QLabel('Links')  # TODO: softocode
        self.cbo_links = QComboBox()
        fra_form_lay.addRow(self.lbl_links, self.cbo_links)

        # Buttons
        self.fra_buttons = QFrame(self)
        fra_buttons_lay = QHBoxLayout(self.fra_buttons)
        self.btn_Ok = QPushButton('OK')
        self.btn_Cancel = QPushButton('Cancel')
        fra_buttons_lay.addWidget(self.btn_Ok)
        fra_buttons_lay.addWidget(self.btn_Cancel)

        # Add to main
        fra_main_lay = QVBoxLayout(self)
        fra_main_lay.setContentsMargins(0, 0, 0, 0)
        fra_main_lay.addWidget(self.fra_form)
        fra_main_lay.addWidget(self.fra_buttons)

        self.setup()

    def setup(self):

        # Combos
        for key, value in Report.status_names.iteritems():
            self.cbo_status.addItem(value, key)

        for key, value in Report.summary_names.iteritems():
            self.cbo_summary.addItem(value, key)

        for key, value in Report.energy_names.iteritems():
            self.cbo_energy.addItem(value, key)

        for key, value in Report.nodes_names.iteritems():
            self.cbo_nodes.addItem(value, key)

        for key, value in Report.links_names.iteritems():
            self.cbo_links.addItem(value, key)

        # Buttons
        self.btn_Cancel.clicked.connect(self.btn_cancel_clicked)
        self.btn_Ok.clicked.connect(self.btn_ok_clicked)

    def show(self):
        super(ReportDialog, self).show()
        self.cbo_status.setCurrentIndex(
            self.cbo_status.findData(self.params.report.status))
        self.cbo_summary.setCurrentIndex(
            self.cbo_summary.findData(self.params.report.summary))
        self.cbo_energy.setCurrentIndex(
            self.cbo_energy.findData(self.params.report.energy))
        self.cbo_nodes.setCurrentIndex(
            self.cbo_nodes.findData(self.params.report.nodes))
        self.cbo_links.setCurrentIndex(
            self.cbo_links.findData(self.params.report.links))

    def btn_cancel_clicked(self):
        self.setVisible(False)

    def btn_ok_clicked(self):

        self.params.report.status = self.cbo_status.itemData(
            self.cbo_status.currentIndex())
        self.params.report.summary = self.cbo_summary.itemData(
            self.cbo_summary.currentIndex())
        self.params.report.energy = self.cbo_energy.itemData(
            self.cbo_energy.currentIndex())
        self.params.report.nodes = self.cbo_nodes.itemData(
            self.cbo_nodes.currentIndex())
        self.params.report.links = self.cbo_links.itemData(
            self.cbo_links.currentIndex())

        self.setVisible(False)
Exemple #50
0
class TimesDialog(QDialog):
    def __init__(self, parent, params):

        QDialog.__init__(self, parent)

        self.parent = parent
        self.params = params

        self.setMinimumWidth(min_width)

        # Build dialog
        self.setWindowTitle('Options - Times')  # TODO: softcode
        self.setWindowModality(QtCore.Qt.ApplicationModal)

        self.fra_form = QFrame(self)
        fra_form_lay = QFormLayout(self.fra_form)
        fra_form_lay.setContentsMargins(10, 10, 10, 10)

        self.lbl_units = QLabel('Units:')  # TODO: softocode
        self.cbo_units = QComboBox()
        fra_form_lay.addRow(self.lbl_units, self.cbo_units)

        self.lbl_duration = QLabel('Duration:')  # TODO: softocode
        self.txt_duration = QLineEdit()
        fra_form_lay.addRow(self.lbl_duration, self.txt_duration)

        self.lbl_hydraulic_timestep = QLabel(
            'Hydraulic timestep:')  # TODO: softocode
        self.txt_hydraulic_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_hydraulic_timestep,
                            self.txt_hydraulic_timestep)

        self.lbl_quality_timestep = QLabel(
            'Quality timestep:')  # TODO: softocode
        self.txt_quality_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_quality_timestep,
                            self.txt_quality_timestep)

        self.lbl_rule_timestep = QLabel('Rule timestep:')  # TODO: softocode
        self.txt_rule_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_rule_timestep, self.txt_rule_timestep)

        self.lbl_pattern_timestep = QLabel(
            'Pattern timestep:')  # TODO: softocode
        self.txt_pattern_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_pattern_timestep,
                            self.txt_pattern_timestep)

        self.lbl_pattern_start = QLabel('Pattern start:')  # TODO: softocode
        self.txt_pattern_start = QLineEdit()
        fra_form_lay.addRow(self.lbl_pattern_start, self.txt_pattern_start)

        self.lbl_report_timestep = QLabel(
            'Report timestep:')  # TODO: softocode
        self.txt_report_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_report_timestep, self.txt_report_timestep)

        self.lbl_report_start = QLabel('Report start:')  # TODO: softocode
        self.txt_report_start = QLineEdit()
        fra_form_lay.addRow(self.lbl_report_start, self.txt_report_start)

        self.lbl_clock_time_start = QLabel(
            'Clock start time:')  # TODO: softocode
        self.txt_clock_time_start = QLineEdit()
        fra_form_lay.addRow(self.lbl_clock_time_start,
                            self.txt_clock_time_start)

        self.lbl_statistic = QLabel('Statistic:')  # TODO: softocode
        self.cbo_statistic = QComboBox()
        fra_form_lay.addRow(self.lbl_statistic, self.cbo_statistic)

        # Buttons
        self.fra_buttons = QFrame(self)
        fra_buttons_lay = QHBoxLayout(self.fra_buttons)
        self.btn_Ok = QPushButton('OK')
        self.btn_Cancel = QPushButton('Cancel')
        fra_buttons_lay.addWidget(self.btn_Ok)
        fra_buttons_lay.addWidget(self.btn_Cancel)

        # Add to main
        fra_main_lay = QVBoxLayout(self)
        fra_main_lay.setContentsMargins(0, 0, 0, 0)
        fra_main_lay.addWidget(self.fra_form)
        fra_main_lay.addWidget(self.fra_buttons)

        self.setup()

    def setup(self):

        for key, text in self.params.times.unit_text.iteritems():
            self.cbo_units.addItem(text, key)

        # Buttons
        self.btn_Cancel.clicked.connect(self.btn_cancel_clicked)
        self.btn_Ok.clicked.connect(self.btn_ok_clicked)

        # Validators
        self.txt_duration.setValidator(RegExValidators.get_pos_int())

        self.txt_duration.setInputMask('0009:99')
        self.txt_duration.setValidator(RegExValidators.get_time_hs_mm())

        self.txt_hydraulic_timestep.setInputMask('009:99')
        self.txt_hydraulic_timestep.setValidator(
            RegExValidators.get_time_hs_mm())

        self.txt_quality_timestep.setInputMask('009:99')
        self.txt_quality_timestep.setValidator(
            RegExValidators.get_time_hs_mm())

        self.txt_rule_timestep.setInputMask('009:99')
        self.txt_rule_timestep.setValidator(RegExValidators.get_time_hs_mm())

        self.txt_pattern_timestep.setInputMask('009:99')
        self.txt_pattern_timestep.setValidator(
            RegExValidators.get_time_hs_mm())

        self.txt_pattern_start.setInputMask('09:99')
        self.txt_pattern_start.setValidator(RegExValidators.get_time_hh_mm())

        self.txt_report_timestep.setInputMask('009:99')
        self.txt_report_timestep.setValidator(RegExValidators.get_time_hs_mm())

        self.txt_report_start.setInputMask('09:99')
        self.txt_report_start.setValidator(RegExValidators.get_time_hh_mm())

        self.txt_clock_time_start.setInputMask('09:99')
        self.txt_clock_time_start.setValidator(
            RegExValidators.get_time_hh_mm())

        for key, text in self.params.times.stats_text.iteritems():
            self.cbo_statistic.addItem(text, key)

    def show(self):
        super(TimesDialog, self).show()

        self.cbo_units.setCurrentIndex(
            self.cbo_units.findData(self.params.times.units))
        self.txt_duration.setText(self.params.times.duration.get_as_text(4))
        self.txt_hydraulic_timestep.setText(
            self.params.times.hydraulic_timestep.get_as_text(3))
        self.txt_quality_timestep.setText(
            self.params.times.quality_timestep.get_as_text(3))
        self.txt_rule_timestep.setText(
            self.params.times.rule_timestep.get_as_text(3))
        self.txt_pattern_timestep.setText(
            self.params.times.pattern_timestep.get_as_text(3))
        self.txt_pattern_start.setText(
            self.params.times.pattern_start.get_as_text())
        self.txt_report_timestep.setText(
            self.params.times.report_timestep.get_as_text(3))
        self.txt_report_start.setText(
            self.params.times.report_start.get_as_text())
        self.txt_clock_time_start.setText(
            self.params.times.clocktime_start.get_as_text())
        self.cbo_statistic.setCurrentIndex(
            self.cbo_statistic.findData(self.params.times.statistic))

    def btn_cancel_clicked(self):
        self.setVisible(False)

    def btn_ok_clicked(self):

        # Update parameters and options
        self.params.times.units = self.cbo_units.itemData(
            self.cbo_units.currentIndex())
        self.params.times.duration = Hour.from_string(self.txt_duration.text())
        self.params.times.hydraulic_timestep = Hour.from_string(
            self.txt_hydraulic_timestep.text())
        self.params.times.quality_timestep = Hour.from_string(
            self.txt_quality_timestep.text())
        self.params.times.rule_timestep = Hour.from_string(
            self.txt_rule_timestep.text())
        self.params.times.pattern_timestep = Hour.from_string(
            self.txt_pattern_timestep.text())
        self.params.times.pattern_start = Hour.from_string(
            self.txt_pattern_start.text())
        self.params.times.report_timestep = Hour.from_string(
            self.txt_report_timestep.text())
        self.params.times.report_start = Hour.from_string(
            self.txt_report_start.text())
        self.params.times.clocktime_start = Hour.from_string(
            self.txt_clock_time_start.text())
        self.params.times.statistic = self.cbo_statistic.currentIndex()

        self.setVisible(False)
Exemple #51
0
class Pressure(PluginBase):
    def __init__(self, *args):
        PluginBase.__init__(self, BrickletPressure, *args)

        self.p = self.device

        self.cbe_pressure = CallbackEmulator(self.p.get_pressure,
                                             self.cb_pressure,
                                             self.increase_error_count)

        self.current_pressure = None  # float, kPa

        plots = [('Pressure', Qt.red, lambda: self.current_pressure,
                  '{:.3f} kPa'.format)]
        self.plot_widget = PlotWidget('Pressure [kPa]', plots)

        self.combo_sensor = QComboBox()
        self.combo_sensor.addItem('MPX5500')
        self.combo_sensor.addItem('MPXV5004')
        self.combo_sensor.addItem('MPX4115A')
        self.combo_sensor.currentIndexChanged.connect(
            self.combo_sensor_changed)

        self.spin_average = QSpinBox()
        self.spin_average.setMinimum(1)
        self.spin_average.setMaximum(50)
        self.spin_average.setSingleStep(1)
        self.spin_average.setValue(50)
        self.spin_average.editingFinished.connect(self.spin_average_finished)

        hlayout = QHBoxLayout()
        hlayout.addWidget(QLabel('Sensor Type:'))
        hlayout.addWidget(self.combo_sensor)
        hlayout.addStretch()
        hlayout.addWidget(QLabel('Moving Average Length:'))
        hlayout.addWidget(self.spin_average)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(hlayout)

    def get_sensor_type_async(self, sensor):
        self.combo_sensor.setCurrentIndex(sensor)

    def get_moving_average_async(self, average):
        self.spin_average.setValue(average)

    def start(self):
        async_call(self.p.get_sensor_type, None, self.get_sensor_type_async,
                   self.increase_error_count)
        async_call(self.p.get_moving_average, None,
                   self.get_moving_average_async, self.increase_error_count)
        async_call(self.p.get_pressure, None, self.cb_pressure,
                   self.increase_error_count)
        self.cbe_pressure.set_period(100)

        self.plot_widget.stop = False

    def stop(self):
        self.cbe_pressure.set_period(0)

        self.plot_widget.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletPressure.DEVICE_IDENTIFIER

    def cb_pressure(self, pressure):
        self.current_pressure = pressure / 1000.0

    def combo_sensor_changed(self):
        self.p.set_sensor_type(self.combo_sensor.currentIndex())

    def spin_average_finished(self):
        self.p.set_moving_average(self.spin_average.value())
Exemple #52
0
class ShowSettingsDialog(QDialog):
    """
    Dialog class for plugin settings
    """
    def __init__(self, iface, memoryPointsLayer, memoryLinesLayer,
                 importConfigTable, importUriDb, importSchemaDb,
                 controlConfigTable, controlUriDb, controlSchemaDb, mntUrl,
                 refLayers, adjLayers, levelAtt, levelVal, drawdowmLayer,
                 pipeDiam, moreTools):
        """
        Constructor
        :param iface: interface
        :param memoryPointsLayer: working memory points layer
        :param memoryLinesLayer: working memory lines layer
        :param importConfigTable: config table selected for import
        :param importUriDb: database for import
        :param importSchemaDb: db schema for import
        :param controlConfigTable: config table selected for control
        :param controlUriDb: database for control
        :param controlSchemaDb: db schema for control
        :param mntUrl: url to get mnt
        :param refLayers: reference layers for drawdown
        :param adjLayers: adjustement layers for drawdown
        :param levelAtt: level attribute for drawdown
        :param levelVal: level value for drawdown
        :param drawdowmLayer: line layer for drawdown
        :param pipeDiam: pipe diameter for drawdown
        :param moreTools: if more tools or not
        """
        QDialog.__init__(self)
        self.__iface = iface
        self.__memoryPointsLayer = memoryPointsLayer
        self.__memoryLinesLayer = memoryLinesLayer
        self.__importConfigTable = importConfigTable
        self.__importUriDb = importUriDb
        self.__importSchemaDb = importSchemaDb
        self.__controlConfigTable = controlConfigTable
        self.__controlUriDb = controlUriDb
        self.__controlSchemaDb = controlSchemaDb
        self.__mntUrl = mntUrl
        self.__refLayers = refLayers
        self.__adjLayers = adjLayers
        self.__levelAtt = levelAtt
        self.__levelVal = levelVal
        self.__drawdowmLayer = drawdowmLayer
        self.__pipeDiam = pipeDiam
        self.setWindowTitle(QCoreApplication.translate("VDLTools", "Settings"))
        self.__pointsLayers = []
        self.__linesLayers = []
        self.__refAvailableLayers = []
        self.__drawdownLayers = []
        self.__tables = []
        self.__schemas = []
        self.__pipeDiamFields = []
        self.__levelAttFields = []
        self.__dbs = DBConnector.getUsedDatabases()

        self.__refLabels = []
        self.__refChecks = []
        self.__adjChecks = []

        for layer in list(QgsMapLayerRegistry.instance().mapLayers().values()):
            if layer is not None and layer.type() == QgsMapLayer.VectorLayer:
                if layer.providerType() == "memory":
                    if layer.geometryType() == QGis.Point:
                        self.__pointsLayers.append(layer)
                    if layer.geometryType() == QGis.Line:
                        self.__linesLayers.append(layer)
                if QGis.fromOldWkbType(
                        layer.wkbType()) == QgsWKBTypes.LineStringZ:
                    self.__drawdownLayers.append(layer)
                if QGis.fromOldWkbType(layer.wkbType()) == QgsWKBTypes.PointZ:
                    self.__refAvailableLayers.append(layer)

        self.resize(600, 500)
        self.__layout = QGridLayout()
        self.__scrollLayout = QGridLayout()
        line = 0

        intersectLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Intersect "))
        self.__scrollLayout.addWidget(intersectLabel, line, 0)

        line += 1

        pointLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Working points layer : "))
        self.__scrollLayout.addWidget(pointLabel, line, 1)

        self.__pointCombo = QComboBox()
        self.__pointCombo.setMinimumHeight(20)
        self.__pointCombo.setMinimumWidth(50)
        self.__pointCombo.addItem("")
        for layer in self.__pointsLayers:
            self.__pointCombo.addItem(layer.name())
        self.__scrollLayout.addWidget(self.__pointCombo, line, 2)
        self.__pointCombo.currentIndexChanged.connect(self.__pointComboChanged)
        if self.__memoryPointsLayer is not None:
            if self.__memoryPointsLayer in self.__pointsLayers:
                self.__pointCombo.setCurrentIndex(
                    self.__pointsLayers.index(self.__memoryPointsLayer) + 1)

        line += 1

        lineLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Working lines layer : "))
        self.__scrollLayout.addWidget(lineLabel, line, 1)

        self.__lineCombo = QComboBox()
        self.__lineCombo.setMinimumHeight(20)
        self.__lineCombo.setMinimumWidth(50)
        self.__lineCombo.addItem("")
        for layer in self.__linesLayers:
            self.__lineCombo.addItem(layer.name())
        self.__scrollLayout.addWidget(self.__lineCombo, line, 2)
        self.__lineCombo.currentIndexChanged.connect(self.__lineComboChanged)
        if self.__memoryLinesLayer is not None:
            if self.__memoryLinesLayer in self.__linesLayers:
                self.__lineCombo.setCurrentIndex(
                    self.__linesLayers.index(self.__memoryLinesLayer) + 1)

        line += 1

        profilesLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Profiles "))
        self.__scrollLayout.addWidget(profilesLabel, line, 0)

        line += 1

        mntLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Url for MNT : "))
        self.__scrollLayout.addWidget(mntLabel, line, 1)

        self.__mntText = QLineEdit()
        if self.__mntUrl is None or self.__mntUrl == "None":
            self.__mntText.insert(
                'https://map.lausanne.ch/prod/wsgi/profile.json')
        else:
            self.__mntText.insert(self.__mntUrl)
        self.__mntText.setMinimumHeight(20)
        self.__mntText.setMinimumWidth(100)
        self.__scrollLayout.addWidget(self.__mntText, line, 2)

        line += 1

        ddLabel = QLabel(QCoreApplication.translate("VDLTools", "Drawdown "))
        self.__scrollLayout.addWidget(ddLabel, line, 0)

        line += 1

        self.__scrollLayout.addWidget(
            QLabel(QCoreApplication.translate("VDLTools", "Layer")), line, 1)

        namesLayout = QHBoxLayout()
        namesWidget = QWidget()
        namesLayout.addWidget(
            QLabel(QCoreApplication.translate("VDLTools", "Reference")))
        namesLayout.addWidget(
            QLabel(QCoreApplication.translate("VDLTools", "Adjustable")))
        namesLayout.setContentsMargins(0, 0, 0, 0)
        namesWidget.setLayout(namesLayout)
        self.__scrollLayout.addWidget(namesWidget, line, 2)

        line += 1

        for layer in self.__refAvailableLayers:
            refLabel = QLabel("  - " + layer.name())
            self.__refLabels.append(refLabel)
            self.__scrollLayout.addWidget(refLabel, line, 1)

            checksLayout = QHBoxLayout()
            checksLayout.setContentsMargins(0, 0, 0, 0)
            checksWidget = QWidget()

            refCheck = QCheckBox()
            self.__refChecks.append(refCheck)
            refCheck.stateChanged.connect(self.__refBoxesChanged)
            checksLayout.addWidget(refCheck)

            adjCheck = QCheckBox()
            self.__adjChecks.append(adjCheck)
            checksLayout.addWidget(adjCheck)

            checksWidget.setLayout(checksLayout)
            self.__scrollLayout.addWidget(checksWidget, line, 2)

            line += 1

        levelAttLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Code(s) on pipe : "))
        self.__scrollLayout.addWidget(levelAttLabel, line, 1)

        self.__levelAttCombo = QComboBox()
        self.__levelAttCombo.setMinimumHeight(20)
        self.__levelAttCombo.setMinimumWidth(50)
        self.__levelAttCombo.addItem("")
        self.__scrollLayout.addWidget(self.__levelAttCombo, line, 2)

        self.__levelAttCombo.currentIndexChanged.connect(
            self.__levelAttComboChanged)

        i = 0
        for layer in self.__refAvailableLayers:
            if layer in self.__refLayers:
                self.__refChecks[i].setChecked(True)
            if layer in self.__adjLayers:
                self.__adjChecks[i].setChecked(True)
            i += 1

        line += 1

        levelValLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Point code attribute : "))
        self.__scrollLayout.addWidget(levelValLabel, line, 1)

        self.__levelValText = QLineEdit()
        if self.__levelVal is not None and self.__levelVal != "None":
            self.__levelValText.insert(self.__levelVal)
        self.__levelValText.setMinimumHeight(20)
        self.__levelValText.setMinimumWidth(100)
        self.__scrollLayout.addWidget(self.__levelValText, line, 2)

        line += 1

        drawdownLabel = QLabel(
            QCoreApplication.translate("VDLTools", "drawdown layer : "))
        self.__scrollLayout.addWidget(drawdownLabel, line, 1)

        self.__drawdownCombo = QComboBox()
        self.__drawdownCombo.setMinimumHeight(20)
        self.__drawdownCombo.setMinimumWidth(50)
        self.__drawdownCombo.addItem("")
        for layer in self.__drawdownLayers:
            self.__drawdownCombo.addItem(layer.name())
        self.__scrollLayout.addWidget(self.__drawdownCombo, line, 2)

        line += 1

        pipeDiamLabel = QLabel(
            QCoreApplication.translate("VDLTools",
                                       "Pipe diameter attribute [cm] : "))
        self.__scrollLayout.addWidget(pipeDiamLabel, line, 1)

        self.__pipeDiamCombo = QComboBox()
        self.__pipeDiamCombo.setMinimumHeight(20)
        self.__pipeDiamCombo.setMinimumWidth(50)
        self.__pipeDiamCombo.addItem("")
        self.__scrollLayout.addWidget(self.__pipeDiamCombo, line, 2)

        self.__drawdownCombo.currentIndexChanged.connect(
            self.__drawdownComboChanged)
        self.__pipeDiamCombo.currentIndexChanged.connect(
            self.__pipeDiamComboChanged)

        if self.__drawdowmLayer is not None:
            if self.__drawdowmLayer in self.__drawdownLayers:
                self.__drawdownCombo.setCurrentIndex(
                    self.__drawdownLayers.index(self.__drawdowmLayer) + 1)

        line += 1

        controlLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Control "))
        self.__scrollLayout.addWidget(controlLabel, line, 0)

        line += 1

        controlDbLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Control database : "))
        self.__scrollLayout.addWidget(controlDbLabel, line, 1)

        self.__controlDbCombo = QComboBox()
        self.__controlDbCombo.setMinimumHeight(20)
        self.__controlDbCombo.setMinimumWidth(50)
        self.__controlDbCombo.addItem("")
        for db in list(self.__dbs.keys()):
            self.__controlDbCombo.addItem(db)
        self.__scrollLayout.addWidget(self.__controlDbCombo, line, 2)

        line += 1

        controlSchemaLabel = QLabel(
            QCoreApplication.translate("VDLTools",
                                       "Control database schema : "))
        self.__scrollLayout.addWidget(controlSchemaLabel, line, 1)

        self.__controlSchemaCombo = QComboBox()
        self.__controlSchemaCombo.setMinimumHeight(20)
        self.__controlSchemaCombo.setMinimumWidth(50)
        self.__controlSchemaCombo.addItem("")
        self.__scrollLayout.addWidget(self.__controlSchemaCombo, line, 2)

        line += 1

        controlTableLabel = QLabel(
            QCoreApplication.translate("VDLTools", "Control config table : "))
        self.__scrollLayout.addWidget(controlTableLabel, line, 1)

        self.__controlTableCombo = QComboBox()
        self.__controlTableCombo.setMinimumHeight(20)
        self.__controlTableCombo.setMinimumWidth(50)
        self.__controlTableCombo.addItem("")
        self.__scrollLayout.addWidget(self.__controlTableCombo, line, 2)

        self.__controlDbCombo.currentIndexChanged.connect(
            self.__controlDbComboChanged)
        self.__controlSchemaCombo.currentIndexChanged.connect(
            self.__controlSchemaComboChanged)
        self.__controlTableCombo.currentIndexChanged.connect(
            self.__controlTableComboChanged)

        if self.__controlUriDb is not None:
            if self.__controlUriDb.database() in list(self.__dbs.keys()):
                self.__controlDbCombo.setCurrentIndex(
                    list(self.__dbs.keys()).index(
                        self.__controlUriDb.database()) + 1)

        if moreTools:
            line += 1

            importLabel = QLabel(
                QCoreApplication.translate("VDLTools", "Import "))
            self.__scrollLayout.addWidget(importLabel, line, 0)

            line += 1

            importDbLabel = QLabel(
                QCoreApplication.translate("VDLTools", "Import database : "))
            self.__scrollLayout.addWidget(importDbLabel, line, 1)

            self.__importDbCombo = QComboBox()
            self.__importDbCombo.setMinimumHeight(20)
            self.__importDbCombo.setMinimumWidth(50)
            self.__importDbCombo.addItem("")
            for db in list(self.__dbs.keys()):
                self.__importDbCombo.addItem(db)
            self.__scrollLayout.addWidget(self.__importDbCombo, line, 2)

            line += 1

            importSchemaLabel = QLabel(
                QCoreApplication.translate("VDLTools",
                                           "Import database schema : "))
            self.__scrollLayout.addWidget(importSchemaLabel, line, 1)

            self.__importSchemaCombo = QComboBox()
            self.__importSchemaCombo.setMinimumHeight(20)
            self.__importSchemaCombo.setMinimumWidth(50)
            self.__importSchemaCombo.addItem("")
            self.__scrollLayout.addWidget(self.__importSchemaCombo, line, 2)

            line += 1

            importTableLabel = QLabel(
                QCoreApplication.translate("VDLTools",
                                           "Import config table : "))
            self.__scrollLayout.addWidget(importTableLabel, line, 1)

            self.__importTableCombo = QComboBox()
            self.__importTableCombo.setMinimumHeight(20)
            self.__importTableCombo.setMinimumWidth(50)
            self.__importTableCombo.addItem("")
            self.__scrollLayout.addWidget(self.__importTableCombo, line, 2)

            self.__importDbCombo.currentIndexChanged.connect(
                self.__importDbComboChanged)
            self.__importSchemaCombo.currentIndexChanged.connect(
                self.__importSchemaComboChanged)
            self.__importTableCombo.currentIndexChanged.connect(
                self.__importTableComboChanged)

            if self.__importUriDb is not None:
                if self.__importUriDb.database() in list(self.__dbs.keys()):
                    self.__importDbCombo.setCurrentIndex(
                        list(self.__dbs.keys()).index(
                            self.__importUriDb.database()) + 1)

        else:
            self.__importDbCombo = None
            self.__importSchemaCombo = None
            self.__importTableCombo = None

        widget = QWidget()
        widget.setLayout(self.__scrollLayout)

        scroll = QScrollArea()
        scroll.setWidgetResizable(True)
        scroll.setWidget(widget)

        self.__layout.addWidget(scroll, 1, 0, 1, 2)

        self.__okButton = QPushButton(
            QCoreApplication.translate("VDLTools", "OK"))
        self.__okButton.setMinimumHeight(20)
        self.__okButton.setMinimumWidth(100)

        self.__cancelButton = QPushButton(
            QCoreApplication.translate("VDLTools", "Cancel"))
        self.__cancelButton.setMinimumHeight(20)
        self.__cancelButton.setMinimumWidth(100)

        self.__layout.addWidget(self.__okButton, 100, 0)
        self.__layout.addWidget(self.__cancelButton, 100, 1)
        self.setLayout(self.__layout)

    @staticmethod
    def __resetCombo(combo):
        """
        To reset a combo list
        :param combo: concerned combo
        """
        while combo.count() > 0:
            combo.removeItem(combo.count() - 1)

    def __setSchemaCombo(self, uriDb, schemaCombo, schemaComboChanged,
                         schemaDb):
        """
        To fill the schema combo list
        :param uriDb: selected database uri
        :param schemaCombo: concerned schema combo
        :param schemaComboChanged: concerned schema combo change event
        :param schemaDb: selected schema db
        """
        connector = DBConnector(uriDb, self.__iface)
        db = connector.setConnection()
        if db:
            Signal.safelyDisconnect(schemaCombo.currentIndexChanged,
                                    schemaComboChanged)
            self.__resetCombo(schemaCombo)
            schemaCombo.addItem("")
            self.__schemas = []
            query = db.exec_(
                """SELECT DISTINCT table_schema FROM information_schema.tables WHERE table_schema NOT IN
                ('pg_catalog', 'information_schema', 'topology') AND table_type = 'BASE TABLE' AND table_name NOT IN
                (SELECT f_table_name FROM geometry_columns)""")
            if query.lastError().isValid():
                self.__iface.messageBar().pushMessage(
                    query.lastError().text(),
                    level=QgsMessageBar.CRITICAL,
                    duration=0)
            else:
                while next(query):
                    self.__schemas.append(query.value(0))
                db.close()
                for schema in self.__schemas:
                    schemaCombo.addItem(schema)
                schemaCombo.currentIndexChanged.connect(schemaComboChanged)
                if schemaDb is not None:
                    if schemaDb in self.__schemas:
                        schemaCombo.setCurrentIndex(
                            self.__schemas.index(schemaDb) + 1)

    def __setTableCombo(self, uriDb, schema, tableCombo, tableComboChanged,
                        configTable):
        """
        To fill the table combo list
        :param uriDb: selected database uri
        :param schema: selected database schema
        :param tableCombo: concerned table combo
        :param tableComboChanged: concerned table combo change event
        :param configTable: selected config table
        """
        connector = DBConnector(uriDb, self.__iface)
        db = connector.setConnection()
        if db:
            Signal.safelyDisconnect(tableCombo.currentIndexChanged,
                                    tableComboChanged)
            self.__resetCombo(tableCombo)
            tableCombo.addItem("")
            self.__tables = []
            query = db.exec_(
                """SELECT table_name FROM information_schema.tables WHERE table_schema = '"""
                + schema + """' ORDER BY table_name""")
            if query.lastError().isValid():
                self.__iface.messageBar().pushMessage(
                    query.lastError().text(),
                    level=QgsMessageBar.CRITICAL,
                    duration=0)
            else:
                while next(query):
                    self.__tables.append(query.value(0))
                db.close()
                for table in self.__tables:
                    if tableCombo.findText(table) == -1:
                        tableCombo.addItem(table)
                tableCombo.currentIndexChanged.connect(tableComboChanged)
                if configTable is not None:
                    if configTable in self.__tables:
                        tableCombo.setCurrentIndex(
                            self.__tables.index(configTable) + 1)

    def __setPipeDiamCombo(self, drawdownLayer):
        """
        To fill the pipe diameter combo list
        :param drawdownLayer: choosen drawdown layer
        """
        Signal.safelyDisconnect(self.__pipeDiamCombo.currentIndexChanged,
                                self.__pipeDiamComboChanged)
        self.__resetCombo(self.__pipeDiamCombo)
        self.__pipeDiamCombo.addItem("")
        fields = drawdownLayer.fields()
        self.__pipeDiamFields = []
        for field in fields:
            self.__pipeDiamFields.append(field.name())
            self.__pipeDiamCombo.addItem(field.name())
        self.__pipeDiamCombo.currentIndexChanged.connect(
            self.__pipeDiamComboChanged)
        if self.__pipeDiam is not None:
            if self.__pipeDiam in self.__pipeDiamFields:
                self.__pipeDiamCombo.setCurrentIndex(
                    self.__pipeDiamFields.index(self.__pipeDiam) + 1)

    def __setLevelAttCombo(self, refLayers):
        """
        To fill the level attribute combo list
        :param refLayers: choosen reference layers
        """
        Signal.safelyDisconnect(self.__levelAttCombo.currentIndexChanged,
                                self.__levelAttComboChanged)
        self.__resetCombo(self.__levelAttCombo)
        self.__levelAttCombo.addItem("")
        self.__levelAttFields = []
        num = 0
        for layer in refLayers:
            fields = layer.fields()
            if num == 0:
                for field in fields:
                    self.__levelAttFields.append(field.name())
                num = 1
            else:
                names = []
                for field in fields:
                    names.append(field.name())
                news = []
                for name in self.__levelAttFields:
                    if name in names:
                        news.append(name)
                self.__levelAttFields = news

        for name in self.__levelAttFields:
            self.__levelAttCombo.addItem(name)
        self.__levelAttCombo.currentIndexChanged.connect(
            self.__levelAttComboChanged)
        if self.__levelAtt is not None:
            if self.__levelAtt in self.__levelAttFields:
                self.__levelAttCombo.setCurrentIndex(
                    self.__levelAttFields.index(self.__levelAtt) + 1)

    def __lineComboChanged(self):
        """
        To remove blank item when another one is selected
        """
        if self.__lineCombo.itemText(0) == "":
            self.__lineCombo.removeItem(0)

    def __pointComboChanged(self):
        """
        To remove blank item when another one is selected
        """
        if self.__pointCombo.itemText(0) == "":
            self.__pointCombo.removeItem(0)

    def __refBoxesChanged(self):
        """
        To update level attribute combo when reference layers have changed
        """
        if self.refLayers() is not None:
            self.__setLevelAttCombo(self.refLayers())

    def __drawdownComboChanged(self):
        """
        To remove blank item when another one is selected
        and update pipe diamete combo when drawdown layer has changed
        """
        if self.__drawdownCombo.itemText(0) == "":
            self.__drawdownCombo.removeItem(0)
        if self.drawdownLayer() is not None:
            self.__setPipeDiamCombo(self.drawdownLayer())

    def __controlTableComboChanged(self):
        """
        To remove blank item when another one is selected
        """
        if self.__controlTableCombo.itemText(0) == "":
            self.__controlTableCombo.removeItem(0)

    def __importTableComboChanged(self):
        """
        To remove blank item when another one is selected
        """
        if self.__importTableCombo.itemText(0) == "":
            self.__importTableCombo.removeItem(0)

    def __controlDbComboChanged(self):
        """
        When the selection in db combo has changed
        """
        if self.__controlDbCombo.itemText(0) == "":
            self.__controlDbCombo.removeItem(0)
        if self.controlUriDb() is not None:
            self.__setSchemaCombo(self.controlUriDb(),
                                  self.__controlSchemaCombo,
                                  self.__controlSchemaComboChanged,
                                  self.__controlSchemaDb)

    def __importDbComboChanged(self):
        """
        When the selection in db combo has changed
        """
        if self.__importDbCombo.itemText(0) == "":
            self.__importDbCombo.removeItem(0)
        if self.importUriDb() is not None:
            self.__setSchemaCombo(self.importUriDb(), self.__importSchemaCombo,
                                  self.__importSchemaComboChanged,
                                  self.__importSchemaDb)

    def __controlSchemaComboChanged(self):
        """
        When the selection in schema combo has changed
        """
        if self.__controlSchemaCombo.itemText(0) == "":
            self.__controlSchemaCombo.removeItem(0)
        if self.controlSchemaDb() is not None:
            self.__setTableCombo(self.controlUriDb(), self.controlSchemaDb(),
                                 self.__controlTableCombo,
                                 self.__controlTableComboChanged,
                                 self.__controlConfigTable)

    def __importSchemaComboChanged(self):
        """
        When the selection in schema combo has changed
        """
        if self.__importSchemaaCombo.itemText(0) == "":
            self.__importSchemaCombo.removeItem(0)
        if self.importSchemaDb() is not None:
            self.__setTableCombo(self.importUriDb(), self.importSchemaDb(),
                                 self.__importTableCombo,
                                 self.__importTableComboChanged,
                                 self.__importConfigTable)

    def __pipeDiamComboChanged(self):
        """
        When the selection in schema combo has changed
        """
        if self.__pipeDiamCombo.itemText(0) == "":
            self.__pipeDiamCombo.removeItem(0)

    def __levelAttComboChanged(self):
        """
        When the selection in schema combo has changed
        """
        if self.__levelAttCombo.itemText(0) == "":
            self.__levelAttCombo.removeItem(0)

    def okButton(self):
        """
        To get the ok button instance
        :return: ok button instance
        """
        return self.__okButton

    def cancelButton(self):
        """
        To get the cancel button instance
        :return: cancel button instance
        """
        return self.__cancelButton

    def pointsLayer(self):
        """
        To get the selected memory points layer
        :return: selected memory points layer, or none
        """
        index = self.__pointCombo.currentIndex()
        if self.__pointCombo.itemText(index) == "":
            return None
        else:
            return self.__pointsLayers[index]

    def linesLayer(self):
        """
        To get the selected memory lines layer
        :return: selected memory lines layer, or none
        """
        index = self.__lineCombo.currentIndex()
        if self.__lineCombo.itemText(index) == "":
            return None
        else:
            return self.__linesLayers[index]

    def refLayers(self):
        """
        To get the selected reference layers
        :return: selected reference layers, or none
        """
        layers = []
        i = 0
        for check in self.__refChecks:
            if check.isChecked():
                layers.append(self.__refAvailableLayers[i])
            i += 1
        return layers

    def adjLayers(self):
        """
        To get the selected ajustable layers
        :return: selected adjustable layers, or none
        """
        layers = []
        i = 0
        for check in self.__adjChecks:
            if check.isChecked():
                layers.append(self.__refAvailableLayers[i])
            i += 1
        return layers

    def levelAtt(self):
        """
        To get the selected level attribute
        :return:  selected level attribute, or none
        """
        if self.__levelAttCombo is None:
            return None
        index = self.__levelAttCombo.currentIndex()
        if self.__levelAttCombo.itemText(index) == "":
            return None
        else:
            return self.__levelAttFields[index]

    def levelVal(self):
        """
        To get the filled level value
        :return: filled level value
        """
        return self.__levelValText.text()

    def drawdownLayer(self):
        """
        To get the selected drawdown layer
        :return: selected drawdown layer, or none
        """
        index = self.__drawdownCombo.currentIndex()
        if self.__drawdownCombo.itemText(index) == "":
            return None
        else:
            return self.__drawdownLayers[index]

    def pipeDiam(self):
        """
        To get the selected pipe diameter
        :return: selected pipe diameter, or none
        """
        if self.__pipeDiamCombo is None:
            return None
        index = self.__pipeDiamCombo.currentIndex()
        if self.__pipeDiamCombo.itemText(index) == "":
            return None
        else:
            return self.__pipeDiamFields[index]

    def controlConfigTable(self):
        """
        To get the selected config table
        :return: selected config table, or none
        """
        if self.__controlTableCombo is None:
            return None
        index = self.__controlTableCombo.currentIndex()
        if self.__controlTableCombo.itemText(index) == "":
            return None
        else:
            return self.__tables[index]

    def importConfigTable(self):
        """
        To get the selected config table
        :return: selected config table, or none
        """
        if self.__importTableCombo is None:
            return None
        index = self.__importTableCombo.currentIndex()
        if self.__importTableCombo.itemText(index) == "":
            return None
        else:
            return self.__tables[index]

    def controlUriDb(self):
        """
        To get selected import database uri
        :return: import database uri
        """
        if self.__controlDbCombo is None:
            return None
        index = self.__controlDbCombo.currentIndex()
        if self.__controlDbCombo.itemText(index) == "":
            return None
        else:
            return self.__dbs[list(self.__dbs.keys())[index]]

    def importUriDb(self):
        """
        To get selected import database uri
        :return: import database uri
        """
        if self.__importDbCombo is None:
            return None
        index = self.__importDbCombo.currentIndex()
        if self.__importDbCombo.itemText(index) == "":
            return None
        else:
            return self.__dbs[list(self.__dbs.keys())[index]]

    def controlSchemaDb(self):
        """
        To get selected import database schema
        :return: import database schema
        """
        if self.__controlSchemaCombo is None:
            return None
        index = self.__controlSchemaCombo.currentIndex()
        if self.__controlSchemaCombo.itemText(index) == "":
            return None
        else:
            return self.__schemas[index]

    def importSchemaDb(self):
        """
        To get selected import database schema
        :return: import database schema
        """
        if self.__importSchemaCombo is None:
            return None
        index = self.__importSchemaCombo.currentIndex()
        if self.__importSchemaCombo.itemText(index) == "":
            return None
        else:
            return self.__schemas[index]

    def mntUrl(self):
        """
        To get selected MN url
        :return: MN url
        """
        return self.__mntText.text()
Exemple #53
0
class OWImpute(OWWidget):
    name = "Impute"
    description = "Imputes missing values in the data table."
    icon = "icons/Impute.svg"
    priority = 2130

    inputs = [("Data", Orange.data.Table, "set_data"),
              ("Learner", Orange.classification.Learner, "set_learner")]
    outputs = [("Data", Orange.data.Table)]

    METHODS = METHODS

    settingsHandler = settings.DomainContextHandler()

    default_method = settings.Setting(1)
    variable_methods = settings.ContextSetting({})
    autocommit = settings.Setting(True)

    want_main_area = False

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

        box = group_box(self.tr("Default method"),
                        layout=layout(Qt.Vertical))
        self.controlArea.layout().addWidget(box)

        bgroup = QButtonGroup()

        for i, m in enumerate(self.METHODS[1:-1], 1):
            b = radio_button(m.name, checked=i == self.default_method,
                             group=bgroup, group_id=i)
            box.layout().addWidget(b)

        self.defbggroup = bgroup

        bgroup.buttonClicked[int].connect(self.set_default_method)
        box = group_box(self.tr("Individual attribute settings"),
                        layout=layout(Qt.Horizontal))
        self.controlArea.layout().addWidget(box)

        self.varview = QtGui.QListView(
            selectionMode=QtGui.QListView.ExtendedSelection
        )
        self.varview.setItemDelegate(DisplayFormatDelegate())
        self.varmodel = itemmodels.VariableListModel()
        self.varview.setModel(self.varmodel)
        self.varview.selectionModel().selectionChanged.connect(
            self._on_var_selection_changed
        )
        self.selection = self.varview.selectionModel()

        box.layout().addWidget(self.varview)

        method_layout = layout(Qt.Vertical, margins=0)
        box.layout().addLayout(method_layout)

        methodbox = group_box(layout=layout(Qt.Vertical))

        bgroup = QButtonGroup()
        for i, m in enumerate(self.METHODS):
            b = radio_button(m.name, group=bgroup, group_id=i)
            methodbox.layout().addWidget(b)

        assert self.METHODS[-1].short == "value"

        self.value_stack = value_stack = QStackedLayout()
        self.value_combo = QComboBox(activated=self._on_value_changed)
        self.value_line = QLineEdit(editingFinished=self._on_value_changed)
        self.value_line.setValidator(QDoubleValidator())
        value_stack.addWidget(self.value_combo)
        value_stack.addWidget(self.value_line)
        methodbox.layout().addLayout(value_stack)

        bgroup.buttonClicked[int].connect(
            self.set_method_for_current_selection
        )
        reset_button = push_button("Restore all to default",
                                   clicked=self.reset_var_methods,
                                   default=False, autoDefault=False)

        method_layout.addWidget(methodbox)
        method_layout.addStretch(2)
        method_layout.addWidget(reset_button)
        self.varmethodbox = methodbox
        self.varbgroup = bgroup

        commitbox = group_box("Commit", layout=layout(margins=0))

        cwidget = commit_widget(
            button_text="Commit",
            button_default=True,
            check_text="Commit on any change",
            checked=self.autocommit,
            clicked=self.commit
        )

        def toggle_auto_commit(b):
            self.autocommit = b
            if self.modified:
                self.commit()

        cwidget.auto_commit_check.toggled[bool].connect(toggle_auto_commit)
        commitbox.layout().addWidget(cwidget)

        self.addAction(cwidget.commit_action)
        self.controlArea.layout().addWidget(commitbox)

        self.data = None
        self.learner = None

    def set_default_method(self, index):
        """
        Set the current selected default imputation method.
        """
        if self.default_method != index:
            self.default_method = index
            self.defbggroup.button(index).setChecked(True)
            self._invalidate()

    def set_data(self, data):
        self.closeContext()
        self.clear()
        self.data = data
        if data is not None:
            self.varmodel[:] = data.domain.variables
            self.openContext(data.domain)
            self.restore_state(self.variable_methods)
            itemmodels.select_row(self.varview, 0)

        self.commit()

    def set_learner(self, learner):
        self.learner = learner

        if self.data is not None and \
                any(state.model.short == "model" for state in
                    map(self.state_for_column, range(len(self.data.domain)))):
            self.commit()

    def restore_state(self, state):
        for i, var in enumerate(self.varmodel):
            key = variable_key(var)
            if key in state:
                index = self.varmodel.index(i)
                self.varmodel.setData(index, state[key], Qt.UserRole)

    def clear(self):
        self.varmodel[:] = []
        self.variable_methods = {}
        self.data = None
        self.modified = False

    def state_for_column(self, column):
        """
        #:: int -> State
        Return the effective imputation state for `column`.

        :param int column:
        :rtype State:

        """
        var = self.varmodel[column]

        state = self.variable_methods.get(variable_key(var), None)
        if state is None or state.method == METHODS[0]:
            state = State(METHODS[self.default_method], ())
        return state

    def imputer_for_column(self, column):
        state = self.state_for_column(column)
        data = self.data
        var = data.domain[column]
        method, params = state
        if method.short == "leave":
            return None
        elif method.short == "avg":
            return column_imputer_average(var, data)
        elif method.short == "model":
            learner = self.learner if self.learner is not None else MeanLearner()
            return column_imputer_by_model(var, data, learner=learner)
        elif method.short == "random":
            return column_imputer_random(var, data)
        elif method.short == "value":
            return column_imputer_defaults(var, data, float(params[0]))
        elif method.short == "as_value":
            return column_imputer_as_value(var, data)
        else:
            assert False

    def commit(self):
        if self.data is not None:
            states = [self.state_for_column(i)
                      for i in range(len(self.varmodel))]

            # Columns to filter unknowns by dropping rows.
            filter_columns = [i for i, state in enumerate(states)
                              if state.method.short == "drop"]

            impute_columns = [i for i, state in enumerate(states)
                              if state.method.short not in ["drop", "leave"]]

            imputers = [(self.varmodel[i], self.imputer_for_column(i))
                        for i in impute_columns]

            data = self.data

            if imputers:
                table_imputer = ImputerModel(data.domain, dict(imputers))
                data = table_imputer(data)

            if filter_columns:
                filter_ = data_filter.IsDefined(filter_columns)
                data = filter_(data)
        else:
            data = None

        self.send("Data", data)
        self.modified = False

    def _invalidate(self):
        self.modified = True
        if self.autocommit:
            self.commit()

    def _on_var_selection_changed(self):
        indexes = self.selection.selectedIndexes()

        vars = [self.varmodel[index.row()] for index in indexes]
        defstate = State(METHODS[0], ())
        states = [self.variable_methods.get(variable_key(var), defstate)
                  for var in vars]
        all_cont = all(isinstance(var, Orange.data.ContinuousVariable)
                       for var in vars)
        states = list(unique(states))
        method = None
        params = ()
        state = None
        if len(states) == 1:
            state = states[0]
            method, params = state
            mindex = METHODS.index(method)
            self.varbgroup.button(mindex).setChecked(True)
        elif self.varbgroup.checkedButton() is not None:
            self.varbgroup.setExclusive(False)
            self.varbgroup.checkedButton().setChecked(False)
            self.varbgroup.setExclusive(True)

        values, enabled, stack_index = [], False, 0
        value, value_index = "0.0", 0
        if all_cont:
            enabled, stack_index = True, 1
            if method is not None and method.short == "value":
                value = params[0]

        elif len(vars) == 1 and \
                isinstance(vars[0], Orange.data.DiscreteVariable):
            values, enabled, stack_index = vars[0].values, True, 0
            if method is not None and method.short == "value":
                try:
                    value_index = values.index(params[0])
                except IndexError:
                    pass

        self.value_stack.setCurrentIndex(stack_index)
        self.value_stack.setEnabled(enabled)

        if stack_index == 0:
            self.value_combo.clear()
            self.value_combo.addItems(values)
            self.value_combo.setCurrentIndex(value_index)
        else:
            self.value_line.setText(value)

    def _on_value_changed(self):
        # The "fixed" value in the widget has been changed by the user.
        index = self.varbgroup.checkedId()
        self.set_method_for_current_selection(index)

    def set_method_for_current_selection(self, methodindex):
        indexes = self.selection.selectedIndexes()
        self.set_method_for_indexes(indexes, methodindex)

    def set_method_for_indexes(self, indexes, methodindex):
        method = METHODS[methodindex]
        params = (None,)
        if method.short == "value":
            if self.value_stack.currentIndex() == 0:
                value = self.value_combo.currentIndex()
            else:
                value = self.value_line.text()
            params = (value, )
        elif method.short == "model":
            params = ("model", )
        state = State(method, params)

        for index in indexes:
            self.varmodel.setData(index, state, Qt.UserRole)
            var = self.varmodel[index.row()]
            self.variable_methods[variable_key(var)] = state

        self._invalidate()

    def reset_var_methods(self):
        indexes = map(self.varmodel.index, range(len(self.varmodel)))
        self.set_method_for_indexes(indexes, 0)
class ProxyConfigPage(QWizardPage):
    def __init__(self, parent=None,key=None):
        super(ProxyConfigPage, self).__init__(parent)
        
        self.parent = parent 
        self.key = key
        
        try:
            (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = self.parent.mfr.readProxyConfig()
        except:
            (pxytype,pxyhost,pxyport,pxyauth,pxyusr,pxypwd) = (None,)*6
            
        #if we use enums for pxy types
        #pxytype = [a[0] for a in WFSDataStore.PROXY_TYPE.reverse.items() if a[1]==pxytype][0]

            
        self.setTitle(self.parent.plist.get(self.key)[1]+' Configuration Options')
        self.setSubTitle('Enter the hostname/ip-address, port number and authentication details of your HTTP proxy')

        QToolTip.setFont(QFont('SansSerif', 10))
        
        #labels
        directlabel = QLabel('Direct Connection')
        systemlabel = QLabel('Use System Proxy settings')
        proxylabel = QLabel('Configure Proxy')
        
        hostLabel = QLabel('Proxy Host')
        portLabel = QLabel('Proxy Port')
        authLabel = QLabel('Authentication')
        usrLabel = QLabel('Username')
        pwdLabel = QLabel('Password')
        
        
        #radio buttons
        self.directradio = QRadioButton()
        self.systemradio = QRadioButton()
        self.usrdefradio = QRadioButton()
        
        
        #edit boxes
        self.hostEdit = QLineEdit(pxyhost)
        self.hostEdit.setToolTip('Enter Proxy host (IP Address or hostname)')
        self.portEdit = QLineEdit(pxyport)
        self.portEdit.setToolTip('Enter Proxy port')
        
        #dropdown
        self.authSelect = QComboBox()
        self.authSelect.addItem('')
        self.authSelect.setToolTip('Select appropriate proxy authentication mechanism')
        self.authSelect.addItems(WFSDataStore.PROXY_AUTH)
        self.authSelect.setCurrentIndex(0 if LU.assessNone(pxyauth) is None else WFSDataStore.PROXY_AUTH.index(pxyauth))
        
        self.usrEdit = QLineEdit(pxyusr)
        self.usrEdit.setToolTip('Enter your proxy username (if required)')
        self.pwdEdit = QLineEdit('')#pxypwd
        self.usrEdit.setToolTip('Enter your proxy password (if required)')
        self.pwdEdit.setEchoMode(QLineEdit.Password)
        
        self.portEdit.setValidator(QRegExpValidator(QRegExp("\d{1,5}"), self))
        
        self.registerField(self.key+"host",self.hostEdit)
        self.registerField(self.key+"port",self.portEdit)
        self.registerField(self.key+"auth",self.authSelect,"currentIndex")
        self.registerField(self.key+"usr",self.usrEdit)
        self.registerField(self.key+"pwd",self.pwdEdit)
        
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[0],self.directradio)
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[1],self.systemradio)
        self.registerField(self.key+WFSDataStore.PROXY_TYPE[2],self.usrdefradio)

        #grid
        grid1 = QGridLayout()
        grid1.setSpacing(10)
        
        grid2 = QGridLayout()
        grid2.setSpacing(10)
        
        #layout
        hbox = QHBoxLayout()
        grid1.addWidget(self.directradio,1,0)
        grid1.addWidget(directlabel,1,1)
        grid1.addWidget(self.systemradio,2,0)
        grid1.addWidget(systemlabel,2,1)
        grid1.addWidget(self.usrdefradio,3,0)
        grid1.addWidget(proxylabel,3,1)
        hbox.addLayout(grid1)
        hbox.addStretch(1)
        
        
        self.gbox = QGroupBox('Proxy Configuration')

        #dsu
        subs = False
        if pxytype == WFSDataStore.PROXY_TYPE[1]:
            #system
            self.systemradio.setChecked(True)
        elif pxytype == WFSDataStore.PROXY_TYPE[2]:
            #user_defined
            self.usrdefradio.setChecked(True)
            subs = True
        else:
            #direct (default)
            self.directradio.setChecked(True)
            
        self.setUserDefined(subs)
        
        self.directradio.clicked.connect(self.disableUserDefined)
        self.systemradio.clicked.connect(self.disableUserDefined)
        self.usrdefradio.clicked.connect(self.enableUserDefined)
        
        grid2.addWidget(hostLabel, 1, 0)
        grid2.addWidget(self.hostEdit, 1, 2)
        
        grid2.addWidget(portLabel, 2, 0)
        grid2.addWidget(self.portEdit, 2, 2)
        
        grid2.addWidget(authLabel, 3, 0)
        grid2.addWidget(self.authSelect, 3, 2)
        
        grid2.addWidget(usrLabel, 4, 0)
        grid2.addWidget(self.usrEdit, 4, 2)
        
        grid2.addWidget(pwdLabel, 5, 0)
        grid2.addWidget(self.pwdEdit, 5, 2)
             
        self.gbox.setLayout(grid2)
        
        #layout    
        vbox = QVBoxLayout()
        vbox.addLayout(hbox)
        vbox.insertWidget(1,self.gbox)
        self.setLayout(vbox)  
        
    def selectConfFile(self):
        self.fileEdit.setText(QFileDialog.getOpenFileName())

    def nextId(self):
        #now go to selected dest configger
        #return int(self.field("ldsdest").toString())
    
        if self.testConnection():
            return self.field("ldsdest")
        return self.parent.plist.get('proxy')[0]
    
    def disableUserDefined(self):
        self.setUserDefined(False)
        
    def enableUserDefined(self):
        self.setUserDefined(True)
        
    def setUserDefined(self,udval):
        self.gbox.setEnabled(udval)
        self.hostEdit.setEnabled(udval)
        self.portEdit.setEnabled(udval)
        self.authSelect.setEnabled(udval)
        self.usrEdit.setEnabled(udval)
        self.pwdEdit.setEnabled(udval)
        
    def testConnection(self):
        if not self.usrdefradio.isChecked(): 
            return True
        if not any(f for f in (self.hostEdit.isModified(),self.portEdit.isModified(),
                               self.usrEdit.isModified(),self.pwdEdit.isModified())):
            return False
        proxydata = {'type':'USER','host':str(self.hostEdit.text()),'port':str(self.portEdit.text()),
                     'auth':str(WFSDataStore.PROXY_AUTH[self.authSelect.currentIndex()-1]),
                     'user':str(self.usrEdit.text()),'pass':str(self.pwdEdit.text())}
        wfsdata = {'key':'00112233445566778899aabbccddeeff'}#key not necessary but config tester checks format
        lds = LDSDataStore(None,{'Proxy':proxydata,'WFS':wfsdata}) 
        lds.applyConfigOptions()
        
        try:
            #use website likely to be up (that isn't LDS so error is distinct)
            lds.initDS('http://www.google.com/',False)
        except DatasourceConnectException as dce:
            QMessageBox.warning(self, 'Connection Error', 'Cannot connect to network using proxy parameters provided {}'.format(dce), 'OK')
            return False
        except DatasourceOpenException as dse:
            QMessageBox.info(self, 'Connection Warning', 'Connection parameters confirmed, Datasource initialisation untested. Continuing.\n{}'.format(dse), 'OK')
            return True
        except RuntimeError as rte:
            QMessageBox.warning(self, 'RuntimeError', 'Error connecting to network: '+str(rte), 'OK')
            return False
        return True
Exemple #55
0
class ActionBar(QFrame):
    """
    SIGNALS:
    @changeCurrent(PyQt_PyObject)
    @runFile(QString)
    @reopenTab(QString)
    @recentTabsModified()
    """

    def __init__(self, main_combo=False):
        super(ActionBar, self).__init__()
        self.setObjectName("actionbar")
        hbox = QHBoxLayout(self)
        hbox.setContentsMargins(1, 1, 1, 1)
        hbox.setSpacing(1)

        self.lbl_checks = QLabel('')
        self.lbl_checks.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.lbl_checks.setFixedWidth(48)
        self.lbl_checks.setVisible(False)
        hbox.addWidget(self.lbl_checks)

        self.combo = QComboBox()
        self.combo.setIconSize(QSize(16, 16))
        #model = QStandardItemModel()
        #self.combo.setModel(model)
        #self.combo.view().setDragDropMode(QAbstractItemView.InternalMove)
        self.combo.setMaximumWidth(300)
        self.combo.setObjectName("combotab")
        self.connect(self.combo, SIGNAL("currentIndexChanged(int)"),
            self.current_changed)
        self.combo.setToolTip(translations.TR_COMBO_FILE_TOOLTIP)
        self.combo.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(self.combo, SIGNAL(
            "customContextMenuRequested(const QPoint &)"),
            self._context_menu_requested)
        hbox.addWidget(self.combo)

        self.symbols_combo = QComboBox()
        self.symbols_combo.setIconSize(QSize(16, 16))
        self.symbols_combo.setObjectName("combo_symbols")
        self.connect(self.symbols_combo, SIGNAL("activated(int)"),
            self.current_symbol_changed)
        hbox.addWidget(self.symbols_combo)

        self.code_navigator = CodeNavigator()
        hbox.addWidget(self.code_navigator)

        self._pos_text = "Line: %d, Col: %d"
        self.lbl_position = QLabel(self._pos_text % (0, 0))
        self.lbl_position.setObjectName("position")
        self.lbl_position.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.lbl_position)

        self.btn_close = QPushButton(
            self.style().standardIcon(QStyle.SP_DialogCloseButton), '')
        self.btn_close.setIconSize(QSize(16, 16))
        if main_combo:
            self.btn_close.setObjectName('navigation_button')
            self.btn_close.setToolTip(translations.TR_CLOSE_FILE)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                self.about_to_close_file)
        else:
            self.btn_close.setObjectName('close_split')
            self.btn_close.setToolTip(translations.TR_CLOSE_SPLIT)
            self.connect(self.btn_close, SIGNAL("clicked()"),
                self.close_split)
        self.btn_close.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        hbox.addWidget(self.btn_close)

    def resizeEvent(self, event):
        super(ActionBar, self).resizeEvent(event)
        if event.size().width() < 350:
            self.symbols_combo.hide()
            self.code_navigator.hide()
            self.lbl_position.hide()
        else:
            self.symbols_combo.show()
            self.code_navigator.show()
            self.lbl_position.show()

    def add_item(self, text, neditable):
        """Add a new item to the combo and add the neditable data."""
        self.combo.addItem(text, neditable)
        self.combo.setCurrentIndex(self.combo.count() - 1)

    def get_editables(self):
        editables = []
        for index in range(self.combo.count()):
            neditable = self.combo.itemData(index)
            editables.append(neditable)
        return editables

    def add_symbols(self, symbols):
        """Add the symbols to the symbols's combo."""
        self.symbols_combo.clear()
        for symbol in symbols:
            data = symbol[1]
            if data[1] == 'f':
                icon = QIcon(":img/function")
            else:
                icon = QIcon(":img/class")
            self.symbols_combo.addItem(icon, data[0])

    def set_current_symbol(self, index):
        self.symbols_combo.setCurrentIndex(index)

    def update_item_icon(self, neditable, icon):
        index = self.combo.findData(neditable)
        self.combo.setItemIcon(index, icon)

    def update_item_text(self, neditable, text):
        index = self.combo.findData(neditable)
        self.combo.setItemText(index, text)

    def current_changed(self, index):
        """Change the current item in the combo."""
        neditable = self.combo.itemData(index)
        self.emit(SIGNAL("changeCurrent(PyQt_PyObject, int)"), neditable, index)

    def current_symbol_changed(self, index):
        """Change the current symbol in the combo."""
        self.emit(SIGNAL("goToSymbol(int)"), index)

    def update_line_col(self, line, col):
        """Update the line and column position."""
        self.lbl_position.setText(self._pos_text % (line, col))

    def _context_menu_requested(self, point):
        """Display context menu for the combo file."""
        if self.combo.count() == 0:
            # If there is not an Editor opened, don't show the menu
            return
        menu = QMenu()
        actionAdd = menu.addAction(translations.TR_ADD_TO_PROJECT)
        actionRun = menu.addAction(translations.TR_RUN_FILE)
        menuSyntax = menu.addMenu(translations.TR_CHANGE_SYNTAX)
        self._create_menu_syntax(menuSyntax)
        menu.addSeparator()
        actionClose = menu.addAction(translations.TR_CLOSE_FILE)
        actionCloseAll = menu.addAction(translations.TR_CLOSE_ALL_FILES)
        actionCloseAllNotThis = menu.addAction(
            translations.TR_CLOSE_OTHER_FILES)
        menu.addSeparator()
        actionSplitH = menu.addAction(translations.TR_SPLIT_VERTICALLY)
        actionSplitV = menu.addAction(translations.TR_SPLIT_HORIZONTALLY)
        menu.addSeparator()
        actionCopyPath = menu.addAction(
            translations.TR_COPY_FILE_PATH_TO_CLIPBOARD)
        actionReopen = menu.addAction(translations.TR_REOPEN_FILE)
        actionUndock = menu.addAction(translations.TR_UNDOCK_EDITOR)
        if len(settings.LAST_OPENED_FILES) == 0:
            actionReopen.setEnabled(False)
        #Connect actions
        self.connect(actionSplitH, SIGNAL("triggered()"),
            lambda: self._split(False))
        self.connect(actionSplitV, SIGNAL("triggered()"),
            lambda: self._split(True))
        self.connect(actionRun, SIGNAL("triggered()"),
            self._run_this_file)
        self.connect(actionAdd, SIGNAL("triggered()"),
            self._add_to_project)
        self.connect(actionClose, SIGNAL("triggered()"),
            self.about_to_close_file)
        self.connect(actionCloseAllNotThis, SIGNAL("triggered()"),
            self._close_all_files_except_this)
        self.connect(actionCloseAll, SIGNAL("triggered()"),
            self._close_all_files)
        self.connect(actionCopyPath, SIGNAL("triggered()"),
            self._copy_file_location)
        self.connect(actionReopen, SIGNAL("triggered()"),
            self._reopen_last_tab)
        self.connect(actionUndock, SIGNAL("triggered()"),
            self._undock_editor)

        menu.exec_(QCursor.pos())

    def _create_menu_syntax(self, menuSyntax):
        """Create Menu with the list of syntax supported."""
        syntax = list(settings.SYNTAX.keys())
        syntax.sort()
        for syn in syntax:
            menuSyntax.addAction(syn)
            self.connect(menuSyntax, SIGNAL("triggered(QAction*)"),
                self._reapply_syntax)

    def _reapply_syntax(self, syntaxAction):
        #TODO
        if [self.currentIndex(), syntaxAction] != self._resyntax:
            self._resyntax = [self.currentIndex(), syntaxAction]
            self.emit(SIGNAL("syntaxChanged(QWidget, QString)"),
                self.currentWidget(), syntaxAction.text())

    def set_current_file(self, neditable):
        index = self.combo.findData(neditable)
        self.combo.setCurrentIndex(index)

    def set_current_by_index(self, index):
        self.combo.setCurrentIndex(index)

    def about_to_close_file(self, index=None):
        """Close the NFile object."""
        if index is None:
            index = self.combo.currentIndex()
        neditable = self.combo.itemData(index)
        if neditable:
            neditable.nfile.close()

    def close_split(self):
        self.emit(SIGNAL("closeSplit()"))

    def close_file(self, neditable):
        """Receive the confirmation to close the file."""
        index = self.combo.findData(neditable)
        self.combo.removeItem(index)
        return index

    def _run_this_file(self):
        """Execute the current file."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("runFile(QString)"), neditable.file_path)

    def _add_to_project(self):
        """Emit a signal to let someone handle the inclusion of the file
        inside a project."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        self.emit(SIGNAL("addToProject(QString)"), neditable.file_path)

    def _reopen_last_tab(self):
        self.emit(SIGNAL("reopenTab(QString)"),
            settings.LAST_OPENED_FILES.pop())
        self.emit(SIGNAL("recentTabsModified()"))

    def _undock_editor(self):
        self.emit(SIGNAL("undockEditor()"))

    def _split(self, orientation):
        self.emit(SIGNAL("splitEditor(bool)"), orientation)

    def _copy_file_location(self):
        """Copy the path of the current opened file to the clipboard."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        QApplication.clipboard().setText(neditable.file_path,
            QClipboard.Clipboard)

    def _close_all_files(self):
        """Close all the files opened."""
        for i in range(self.combo.count()):
            self.about_to_close_file(0)

    def _close_all_files_except_this(self):
        """Close all the files except the current one."""
        neditable = self.combo.itemData(self.combo.currentIndex())
        for i in reversed(list(range(self.combo.count()))):
            ne = self.combo.itemData(i)
            if ne is not neditable:
                self.about_to_close_file(i)
Exemple #56
0
class SimulationPanel(QWidget):
    def __init__(self):
        QWidget.__init__(self)

        layout = QVBoxLayout()

        self._simulation_mode_combo = QComboBox()
        addHelpToWidget(self._simulation_mode_combo, "run/simulation_mode")

        self._simulation_mode_combo.currentIndexChanged.connect(
            self.toggleSimulationMode)

        simulation_mode_layout = QHBoxLayout()
        simulation_mode_layout.addSpacing(10)
        simulation_mode_layout.addWidget(QLabel("Simulation mode:"), 0,
                                         Qt.AlignVCenter)
        simulation_mode_layout.addWidget(self._simulation_mode_combo, 0,
                                         Qt.AlignVCenter)

        simulation_mode_layout.addSpacing(20)

        self.run_button = QToolButton()
        self.run_button.setIconSize(QSize(32, 32))
        self.run_button.setText("Start Simulation")
        self.run_button.setIcon(resourceIcon("ide/gear_in_play"))
        self.run_button.clicked.connect(self.runSimulation)
        self.run_button.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        addHelpToWidget(self.run_button, "run/start_simulation")

        simulation_mode_layout.addWidget(self.run_button)
        simulation_mode_layout.addStretch(1)

        layout.addSpacing(5)
        layout.addLayout(simulation_mode_layout)
        layout.addSpacing(10)

        self._simulation_stack = QStackedWidget()
        self._simulation_stack.setLineWidth(1)
        self._simulation_stack.setFrameStyle(QFrame.StyledPanel)

        layout.addWidget(self._simulation_stack)

        self._simulation_widgets = {}
        """ :type: dict[BaseRunModel,SimulationConfigPanel]"""

        self.addSimulationConfigPanel(EnsembleExperimentPanel())
        self.addSimulationConfigPanel(EnsembleSmootherPanel())
        self.addSimulationConfigPanel(IteratedEnsembleSmootherPanel())
        self.addSimulationConfigPanel(MultipleDataAssimilationPanel())

        self.setLayout(layout)

    def addSimulationConfigPanel(self, panel):
        assert isinstance(panel, SimulationConfigPanel)

        panel.toggleAdvancedOptions(False)
        self._simulation_stack.addWidget(panel)

        simulation_model = panel.getSimulationModel()

        self._simulation_widgets[simulation_model] = panel
        self._simulation_mode_combo.addItem(str(simulation_model),
                                            simulation_model)
        panel.simulationConfigurationChanged.connect(
            self.validationStatusChanged)

    def getActions(self):
        return []

    def toggleAdvancedMode(self, show_advanced):
        for panel in self._simulation_widgets.values():
            panel.toggleAdvancedOptions(show_advanced)

    def getCurrentSimulationModel(self):
        data = self._simulation_mode_combo.itemData(
            self._simulation_mode_combo.currentIndex(), Qt.UserRole)
        return data.toPyObject()

    def getSimulationArguments(self):
        """ @rtype: dict[str,object]"""
        simulation_widget = self._simulation_widgets[
            self.getCurrentSimulationModel()]
        return simulation_widget.getSimulationArguments()

    def runSimulation(self):
        case_name = getCurrentCaseName()
        message = "Are you sure you want to use case '%s' for initialization of the initial ensemble when running the simulations?" % case_name
        start_simulations = QMessageBox.question(
            self, "Start simulations?", message,
            QMessageBox.Yes | QMessageBox.No)

        if start_simulations == QMessageBox.Yes:
            run_model = self.getCurrentSimulationModel()
            arguments = self.getSimulationArguments()
            dialog = RunDialog(run_model, arguments, self)
            dialog.startSimulation()
            dialog.exec_()

            ERT.emitErtChange()  # simulations may have added new cases.

    def toggleSimulationMode(self):
        widget = self._simulation_widgets[self.getCurrentSimulationModel()]
        self._simulation_stack.setCurrentWidget(widget)
        self.validationStatusChanged()

    def validationStatusChanged(self):
        widget = self._simulation_widgets[self.getCurrentSimulationModel()]
        self.run_button.setEnabled(widget.isConfigurationValid())