Exemple #1
0
 def addWidgets(self):
     layout = QVBoxLayout()
     self.setLayout(layout)
     layout.addSpacing(10)
     preamble = QLabel('This vault is locked.', self)
     layout.addWidget(preamble)
     passwdedt = QLineEdit(self)
     passwdedt.setPlaceholderText('Type password to unlock')
     passwdedt.setEchoMode(QLineEdit.Password)
     passwdedt.textChanged.connect(self.passwordChanged)
     passwdedt.returnPressed.connect(self.unlockVault)
     layout.addSpacing(10)
     layout.addWidget(passwdedt)
     self.passwdedt = passwdedt
     unlockcb = QCheckBox('Try unlock other vaults too', self)
     unlockcb.stateChanged.connect(self.saveConfig)
     unlockcb.setVisible(False)
     layout.addWidget(unlockcb)
     self.unlockcb = unlockcb
     status = QLabel('', self)
     status.setVisible(False)
     status.setContentsMargins(0, 10, 0, 0)
     layout.addWidget(status)
     self.status = status
     hbox = QHBoxLayout()
     unlockbtn = QPushButton('Unlock', self)
     unlockbtn.setFixedSize(unlockbtn.sizeHint())
     unlockbtn.clicked.connect(self.unlockVault)
     unlockbtn.setEnabled(False)
     hbox.addWidget(unlockbtn)
     self.unlockbtn = unlockbtn
     hbox.addStretch(100)
     layout.addSpacing(10)
     layout.addLayout(hbox)
     layout.addStretch(100)
class AddressAndMaskInput(QWidget):
    def __init__(self, ip_version=4, parent=None):
        QWidget.__init__(self, parent)

        self.address = QLineEdit()
        self.prefix = QSpinBox()
        self.prefix.setMinimum(0)

        self.setVersion(ip_version)
        layout = QHBoxLayout(self)

        layout.addWidget(self.address)
        layout.addWidget(QLabel("<h2>/</h2>"))
        layout.addWidget(self.prefix)

    def setVersion(self, ip_version):
        if ip_version == 4:
            self.ip_regex = IPV4_REGEXP
            mask_size = 31
        else:
            self.ip_regex = IPV6_REGEXP
            mask_size = 127

        validator = QRegExpValidator(self.ip_regex, self.address)
        self.address.setValidator(validator)
        self.prefix.setMaximum(mask_size)

    def showValid(self, valid):
        if valid:
            style = u''
        else:
            style = u'background: #b52323;'

        for widget in (self.prefix, self.address):
            widget.setStyleSheet(style)
Exemple #3
0
class AddServerDialog(QDialog):
    def __init__(self,parent=None,name="",address="",port=6600):
        super(AddServerDialog,self).__init__(parent)
        self.setWindowTitle("Add Server")
        layout = QHBoxLayout()
        srvlayout = QGridLayout()
        srvlayout.addWidget(QLabel("Name"), 0, 0)
        self.name = QLineEdit(name)
        srvlayout.addWidget(self.name, 0, 1)
        srvlayout.addWidget(QLabel("Address"), 1, 0)
        self.address = QLineEdit(address)
        srvlayout.addWidget(self.address, 1, 1)
        srvlayout.addWidget(QLabel("Port"))
        self.port = QLineEdit(str(port))
        srvlayout.addWidget(self.port)
        layout.addLayout( srvlayout)
        btnbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel,
                                  Qt.Vertical)
        btnbox.accepted.connect( self.accept)
        btnbox.rejected.connect( self.reject)
        layout.addWidget(btnbox)
        self.setLayout(layout)
    
    def exec_(self):
        ret = [super(AddServerDialog,self).exec_()]
        if ret[0] == QDialog.Accepted:
            ret += [
                str(self.name.text()),
                str(self.address.text()),
                int(self.port.text()) ]
        return ret
Exemple #4
0
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space:
            currentText = unicode(self.frame.listWidget.currentItem().text())
            self.setText(currentText)
            return

        QLineEdit.keyPressEvent(self, event)
        if event.key() == Qt.Key_Down:
            if self.frame.listWidget.currentRow() != \
              self.frame.listWidget.count() - 1:
                self.frame.listWidget.setCurrentRow(
                    self.frame.listWidget.currentRow() + 1)
        elif event.key() == Qt.Key_Up:
            if self.frame.listWidget.currentRow() > 0:
                self.frame.listWidget.setCurrentRow(
                    self.frame.listWidget.currentRow() - 1)
        elif event.key() in (Qt.Key_Tab, Qt.Key_Return, Qt.Key_Enter):
            item = self.frame.listWidget.currentItem()
            self.emit(SIGNAL("itemFound(QString)"), item.path)
            self.setText('')
            self.frame.hide()
            self._parent._parentTree.setFocus()
        elif event.key() == Qt.Key_Escape:
            self.frame.hide()
            self._parent._parentTree.setFocus()
Exemple #5
0
 def __init__(self, page):
     super(TypographicalQuotes, self).__init__(page)
     
     layout = QGridLayout(spacing=1)
     self.setLayout(layout)
     l = self.languageLabel = QLabel()
     c = self.languageCombo = QComboBox(currentIndexChanged=self.languageChanged)
     l.setBuddy(c)
     
     self.primaryLabel = QLabel()
     self.secondaryLabel = QLabel()
     self.primaryLeft = QLineEdit(textEdited=self.changed)
     self.primaryRight = QLineEdit(textEdited=self.changed)
     self.secondaryLeft = QLineEdit(textEdited=self.changed)
     self.secondaryRight = QLineEdit(textEdited=self.changed)
     
     self._langs = ["current", "custom"]
     self._langs.extend(lang for lang in lasptyqu.available() if lang != "C")
     c.addItems(['' for i in self._langs])
     
     layout.addWidget(self.languageLabel, 0, 0)
     layout.addWidget(self.primaryLabel, 1, 0)
     layout.addWidget(self.secondaryLabel, 2, 0)
     layout.addWidget(self.languageCombo, 0, 1, 1, 2)
     layout.addWidget(self.primaryLeft, 1, 1)
     layout.addWidget(self.primaryRight, 1, 2)
     layout.addWidget(self.secondaryLeft, 2, 1)
     layout.addWidget(self.secondaryRight, 2, 2)
     
     app.translateUI(self)
Exemple #6
0
 def __init__(self, parent, attribut, editable=False):
     QLineEdit.__init__(self, parent)
     self.setMinimumWidth(300)
     self.parent = parent
     self.attribut = attribut
     self.setReadOnly(not editable)
     self.actualiser()
Exemple #7
0
 def __init__(self, value):
     QLineEdit.__init__(self)
     self._value = value
     if value.default:
         self.setText(unicode(value.default))
     if value.masked:
         self.setEchoMode(self.Password)
Exemple #8
0
 def _getPersonWidget(self):
     widget = QWidget()
     
     grid = QGridLayout()
     grid.setSpacing(10)
     
     self.forenameLabel = QLabel('Forename')
     self.surnameLabel = QLabel('Surname')
     
     self.forenameLineEdit = QLineEdit()
     self.surnameLineEdit = QLineEdit()
     
     if self.contact.forename:
         self.forenameLineEdit.setText(self.contact.forename)
     
     if self.contact.surname:
         self.surnameLineEdit.setText(self.contact.surname)
     
     grid.addWidget(self.forenameLabel, 0, 0)
     grid.addWidget(self.surnameLabel, 1, 0)
     
     grid.addWidget(self.forenameLineEdit, 0, 1)
     grid.addWidget(self.surnameLineEdit, 1, 1)
     
     widget.setLayout(grid)
     
     return widget
class ColorLayout(QHBoxLayout):
    """Color-specialized QLineEdit layout"""
    def __init__(self, color, parent=None):
        QHBoxLayout.__init__(self)
        assert isinstance(color, QColor)
        self.lineedit = QLineEdit(color.name(), parent)
        self.connect(self.lineedit, SIGNAL("textChanged(QString)"),
                     self.update_color)
        self.addWidget(self.lineedit)
        self.colorbtn = ColorButton(parent)
        self.colorbtn.color = color
        self.connect(self.colorbtn, SIGNAL("colorChanged(QColor)"),
                     self.update_text)
        self.addWidget(self.colorbtn)

    def update_color(self, text):
        color = text_to_qcolor(text)
        if color.isValid():
            self.colorbtn.color = color

    def update_text(self, color):
        self.lineedit.setText(color.name())
        
    def text(self):
        return self.lineedit.text()
Exemple #10
0
class EkdPathPropertie(EkdPropertie):
    """
    Définition de la propriété correspondant à un chemin
    """
    def __init__(self, prop, name, value, section=None ):
        super(EkdPathPropertie, self).__init__(prop, name, value, EkdPropertie.PATH, section)
        self.label = QLabel(name)
        self.widget = QFrame()
        self.layout = QHBoxLayout(self.widget)
        self.line = QLineEdit(value)
        self.line.setReadOnly(True)
        self.layout.addWidget(self.line)
        self.boutton = QPushButton(u"...")
        self.boutton.setFixedSize(25,25)
        self.layout.addWidget(self.boutton)

        # Quand on clique sur le boutton on défini le path
        self.connect(self.boutton, SIGNAL("clicked()"), self.updatePath)

    def updatePath(self):
        newpath = QFileDialog.getExistingDirectory(None, _(u"Choisissez un chemin"), self.value )
        if newpath:
            self.value = newpath
            self.line.setText(self.value)
            EkdConfig.set(self.section, self.id, self.value)
Exemple #11
0
class EkdColorPropertie(EkdPropertie):
    """
    Définition de la propriété correspondant à une Couleur
    """
    def __init__(self, prop, name, value, section=None ):
        super(EkdColorPropertie, self).__init__(prop, name, value, EkdPropertie.COLOR, section)
        self.label = QLabel(name)
        self.widget = QFrame()
        self.layout = QHBoxLayout(self.widget)
        self.line = QLineEdit(value)
        self.value = value
        self.line.setReadOnly(True)
        self.layout.addWidget(self.line)
        self.color = QPixmap(15, 15)
        self.color.fill(QColor.fromRgb(int("%d" % int(self.value, 16))))
        self.boutton = QPushButton(QIcon(self.color), u"")
        self.boutton.setFixedSize(25,25)
        self.layout.addWidget(self.boutton)

        # Quand on clique sur le boutton on défini la couleur
        self.connect(self.boutton, SIGNAL("clicked()"), self.updateColor)

    def updateColor(self):
        newcolor = QColorDialog.getColor(QColor.fromRgb(int("%d" % int(self.value, 16))), None )# Non supporté sous Jaunty ??
        if newcolor.isValid():
            self.value = str("%x" % newcolor.rgb())[2:]
            self.color.fill(QColor.fromRgb(int("%d" % int(self.value, 16))))
            self.boutton.setIcon(QIcon(self.color))
            self.line.setText(self.value)
            EkdConfig.set(self.section, self.id, self.value)
    def __init__(self, editorWidget, parent=None):
        QDialog.__init__(self, parent, Qt.Dialog)
        self.setWindowTitle('from ... import ...')
        self._editorWidget = editorWidget

        source = self._editorWidget.get_text()
        source = source.encode(self._editorWidget.encoding)
        self._imports = introspection.obtain_imports(source)

        self._imports_names = list(self._imports["imports"].keys())
        self._imports_names += [imp for imp in self._imports['fromImports']]
        self._froms = [self._imports['fromImports'][imp]['module']
                            for imp in self._imports['fromImports']]
        self._froms += builtin_module_names
        self._froms += [module_name[1] for module_name in iter_modules()]
        self._froms = tuple(sorted(set(self._froms)))

        hbox = QHBoxLayout(self)
        hbox.addWidget(QLabel('from'))
        self._lineFrom = QLineEdit()
        self._completer = QCompleter(self._froms)
        self._lineFrom.setCompleter(self._completer)
        hbox.addWidget(self._lineFrom)
        hbox.addWidget(QLabel('import'))
        self._lineImport = QLineEdit()
        self._completerImport = QCompleter(self._imports_names)
        self._lineImport.setCompleter(self._completerImport)
        hbox.addWidget(self._lineImport)
        self._btnAdd = QPushButton(self.tr('Add'))
        hbox.addWidget(self._btnAdd)

        self.connect(self._lineImport, SIGNAL("returnPressed()"),
            self._add_import)
        self.connect(self._btnAdd, SIGNAL("clicked()"),
            self._add_import)
Exemple #13
0
class ArgumentWidget(QWidget):
    def __init__(self, argument, parent=None):
        super(ArgumentWidget, self).__init__(parent)
        self.layout = QHBoxLayout()
        self.layout.setContentsMargins(1, 0, 1, 1)
        self.setLayout(self.layout)
        label = QLabel(argument)
        self.component_id = None
        self.layout.addWidget(label)
        self.editor = QLineEdit()
        self.editor.setReadOnly(True)
        self.layout.addWidget(self.editor)
        self.setAcceptDrops(True)

    def dragEnterEvent(self, event):
        if event.mimeData().hasFormat('application/py_instance'):
            event.accept()
        else:
            event.ignore()

    def dropEvent(self, event):
        obj = event.mimeData().data('application/py_instance')
        if not isinstance(obj, core.data.ComponentID):
            return
        self.component_id = obj
        self.editor.setText(str(obj))
Exemple #14
0
class NewWordEditor(QDialog):
    def __init__(self, word_content, title, parent):
        QDialog.__init__(self, parent)
        self.setWindowTitle(title)

        self.word_content = word_content
        layout = QFormLayout(self)
        layout.addRow('&Word', self._create_word())
        layout.addRow('&Content', self._create_content())
        layout.addRow(self._create_buttons())

    def _create_buttons(self):
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal ,self)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)
        return buttons

    def _create_word(self):
        self.word_edit = QLineEdit(self.word_content.lower(), self)
        return self.word_edit

    def _create_content(self):
        self.content_edit = QLineEdit(self.word_content, self)
        return self.content_edit

    def get_new_word(self):
        s = get_session()
        w = unicode(self.word_edit.text()).strip()
        word = Word.find(s, w)
        if word is not None:
            word = word.id
        else:
            word = Word(w)
        return ArticleNewWord(None, word, unicode(self.content_edit.text()).strip())
Exemple #15
0
	def __init__(self, parent = None, _id = 0):
		super(TplRow, self).__init__(parent)
		self.id = _id
		self.setLayout(QHBoxLayout())
		self.idLabel = QLabel(self)
		self.beginEdit = QDateTimeEdit(self)
		self.beginEdit.setCalendarPopup(True) 
		self.endEdit = QDateTimeEdit(self)
		self.endEdit.setCalendarPopup(True)
		self.timeDiff = ClickLabel(self)
		self.descriptionEdit = QLineEdit(self)
		self.noteEdit = QLineEdit(self)
		self.delButton = QPushButton(self)
		self.delButton.setText('X')
		
		self.layout().addWidget(self.idLabel)
		self.layout().addWidget(self.beginEdit)
		self.layout().addWidget(self.endEdit)
		self.layout().addWidget(self.timeDiff)
		self.layout().addWidget(self.descriptionEdit)
		self.layout().addWidget(self.noteEdit)
		self.layout().addWidget(self.delButton)

		self.layout().setContentsMargins(2,2,2,2)
		
		self.connect(self.descriptionEdit, SIGNAL('editingFinished ()'), self.notify)
		self.connect(self.noteEdit, SIGNAL('editingFinished ()'), self.notify)
		self.connect(self.beginEdit, SIGNAL('editingFinished ()'), self.notify)
		self.connect(self.endEdit, SIGNAL('editingFinished ()'), self.notify)
		self.connect(self.delButton, SIGNAL('clicked()'), self.delete)
		self.connect(self.timeDiff, SIGNAL('clicked()'), self.onTimeDiff)
  def __init__(self, type_txt, id_txt, parent=None):
    super(FixItemNameDialog, self).__init__(parent)
    self.type = type_txt
    self.id = id_txt

    self.setWindowTitle('Add/Correct Item Name')

    self.layout = QGridLayout(self)

    self.layout.addWidget(QLabel('Type:'), 0, 0)
    self.txt_type = QLineEdit(type_txt, self)
    self.txt_type.setDisabled(True)
    self.layout.addWidget(self.txt_type, 0, 1)

    self.layout.addWidget(QLabel('ID:'), 1, 0)
    self.txt_id = QLineEdit(id_txt, self)
    self.txt_id.setDisabled(True)
    self.layout.addWidget(self.txt_id, 1, 1)

    self.layout.addWidget(QLabel('Item Name:'), 2, 0)
    self.txt_name = QLineEdit(self)
    self.layout.addWidget(self.txt_name, 2, 1)

    self.layout.addWidget(QLabel('Contributor:'), 3, 0)
    self.txt_contributor = QLineEdit(self)
    self.txt_contributor.setPlaceholderText('anonymous')
    self.layout.addWidget(self.txt_contributor, 3, 1)

    self.btn_submit = QPushButton('Submit', self)
    self.btn_submit.clicked.connect(self.onSubmit)
    self.layout.addWidget(self.btn_submit, 4, 0)
    self.btn_cancel = QPushButton('Cancel', self)
    self.btn_cancel.clicked.connect(self.reject)
    self.layout.addWidget(self.btn_cancel, 4, 1)
Exemple #17
0
    def __init__(self, model, help_link="", default_string="", continuous_update=False):
        """
        :type model: ValueModel
        :type help_link: str
        :type default_string: str
        :type continuous_update: bool
        """
        QLineEdit.__init__(self)
        addHelpToWidget(self, help_link)
        self.setMinimumWidth(250)
        self._validation = ValidationSupport(self)
        self._validator = None
        self._model = model

        self.editingFinished.connect(self.stringBoxChanged)
        self.editingFinished.connect(self.validateString)

        if continuous_update:
            self.textChanged.connect(self.stringBoxChanged)

        self.textChanged.connect(self.validateString)

        self._valid_color = self.palette().color(self.backgroundRole())
        self.setText(default_string)

        self._model.valueChanged.connect(self.modelChanged)
        self.modelChanged()
    def __init__(self, username='', parent=None):
        self.password = "******"
        self.username = username
        super(GetPassword, self).__init__(parent)

        self.username_le = QLineEdit()
        self.username_le.setText(self.username)
        self.username_le.setObjectName("username_le")
        self.username_lbl = QLabel('USERNAME:'******'PASSWORD:', self)

        self.ok = QPushButton()
        self.ok.setObjectName("OK")
        self.ok.setText("OK")

        layout = QFormLayout()
        layout.addRow(self.username_lbl, self.username_le)
        layout.addRow(self.password_lbl, self.password_le)
        layout.addWidget(self.ok)

        self.setLayout(layout)
        self.connect(self.ok, SIGNAL("clicked()"), self.ok_click)
        self.setWindowTitle("Please enter your username and password")
Exemple #19
0
    def __init__(self, parent):
        super(ManualInstallWidget, self).__init__()
        self._parent = parent
        vbox = QVBoxLayout(self)
        form = QFormLayout()
        self._txtName = QLineEdit()
        self._txtVersion = QLineEdit()
        form.addRow(self.tr("Plugin Name:"), self._txtName)
        form.addRow(self.tr("Plugin Version:"), self._txtVersion)
        vbox.addLayout(form)
        hPath = QHBoxLayout()
        self._txtFilePath = QLineEdit()
        self._btnFilePath = QPushButton(QIcon(":img/open"), '')
        hPath.addWidget(QLabel(self.tr("Plugin File:")))
        hPath.addWidget(self._txtFilePath)
        hPath.addWidget(self._btnFilePath)
        vbox.addLayout(hPath)
        vbox.addSpacerItem(QSpacerItem(0, 1, QSizePolicy.Expanding,
            QSizePolicy.Expanding))

        hbox = QHBoxLayout()
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        self._btnInstall = QPushButton(self.tr("Install"))
        hbox.addWidget(self._btnInstall)
        vbox.addLayout(hbox)

        #Signals
        self.connect(self._btnFilePath,
            SIGNAL("clicked()"), self._load_plugin_path)
        self.connect(self._btnInstall, SIGNAL("clicked()"),
            self.install_plugin)
    def __init__(
        self, parent=None, uiSearchImage=None, uiSearchClickedImage=None, uiClearImage=None, uiClearClickedImage=None
    ):
        """
		Initializes the class.

		:param parent: Widget parent.
		:type parent: QObject
		:param uiSearchImage: Search button image path.
		:type uiSearchImage: str
		:param uiSearchClickedImage: Search button clicked image path.
		:type uiSearchClickedImage: str
		:param uiClearImage: Clear button image path.
		:type uiClearImage: str
		:param uiClearClickedImage: Clear button clicked image path.
		:type uiClearClickedImage: str
		"""

        LOGGER.debug("> Initializing '{0}()' class.".format(self.__class__.__name__))

        QLineEdit.__init__(self, parent)

        # --- Setting class attributes. ---
        self.__uiSearchImage = None
        self.uiSearchImage = uiSearchImage or umbra.ui.common.getResourcePath("images/Search_Glass.png")
        self.__uiSearchClickedImage = None
        self.uiSearchClickedImage = uiSearchClickedImage or umbra.ui.common.getResourcePath(
            "images/Search_Glass_Clicked.png"
        )
        self.__uiClearImage = None
        self.uiClearImage = uiClearImage or umbra.ui.common.getResourcePath("images/Search_Clear.png")
        self.__uiClearClickedImage = None
        self.uiClearClickedImage = uiClearClickedImage or umbra.ui.common.getResourcePath(
            "images/Search_Clear_Clicked.png"
        )

        self.__searchActiveLabel = Active_QLabel(
            self, QPixmap(self.__uiSearchImage), QPixmap(self.__uiSearchImage), QPixmap(self.__uiSearchClickedImage)
        )
        self.__searchActiveLabel.setObjectName("Search_Field_activeLabel")
        self.__searchActiveLabel.showEvent = lambda event: reduce(
            lambda *args: None, (self.__setStyleSheet(), Active_QLabel.showEvent(self.__searchActiveLabel, event))
        )
        self.__searchActiveLabel.hideEvent = lambda event: reduce(
            lambda *args: None, (self.__setStyleSheet(), Active_QLabel.hideEvent(self.__searchActiveLabel, event))
        )

        self.__clearButton = QToolButton(self)
        self.__clearButton.setObjectName("Clear_Field_button")

        self.__completer = QCompleter()
        self.setCompleter(self.__completer)
        self.__completerVisibleItemsCount = 16

        Search_QLineEdit.__initializeUi(self)
        self.__setClearButtonVisibility(self.text())

        # Signals / Slots.
        self.__clearButton.clicked.connect(self.clear)
        self.textChanged.connect(self.__setClearButtonVisibility)
Exemple #21
0
    def createValues(self):
        self.wvalues = QWidget()
        self.valuesgrid = QGridLayout()

        ltype = QLabel("Type:")
        self.type = QComboBox()
        self.type.addItem("Hexadecimal")
        self.type.addItem("Character(s)")
        self.type.addItem("Unicode")

        lneedle = QLabel("Pattern:")
        self.needle = QLineEdit()

        lwild = QLabel("Wildcard:")
        self.wildcard = QLineEdit()

        lstart = QLabel("Start: ")
        self.start = QFFSpinBox(self)
        self.start.setMaximum(self.heditor.filesize)
        self.start.setValue(0)

        self.valuesgrid.addWidget(ltype, 0, 0)
        self.valuesgrid.addWidget(self.type, 0, 1)

        self.valuesgrid.addWidget(lneedle, 1, 0)        
        self.valuesgrid.addWidget(self.needle, 1, 1)

        self.valuesgrid.addWidget(lwild, 2, 0)        
        self.valuesgrid.addWidget(self.wildcard, 2, 1)

        self.valuesgrid.addWidget(lstart, 3, 0)        
        self.valuesgrid.addWidget(self.start, 3, 1)
        
        self.wvalues.setLayout(self.valuesgrid)
        self.vbox.addWidget(self.wvalues)
Exemple #22
0
    def __init__(self, parent=None):
        super(NewNotebookDlg, self).__init__(parent)
        self.setWindowTitle('Add Notebook - mikidown')
        tipLabel = QLabel('Choose a name and folder for your notebook.' +
                          '\nThe folder can be an existing notebook folder.')
        self.nameEditor = QLineEdit()
        self.nameEditor.setText('Notes')
        nameLabel = QLabel('Name:')
        nameLabel.setBuddy(self.nameEditor)
        self.pathEditor = QLineEdit()
        # self.pathEditor.setText('~/mikidown')
        self.pathEditor.setText(os.environ['HOME']+'/mikinotes')
        pathLabel = QLabel('Path:')
        pathLabel.setBuddy(self.pathEditor)
        browse = QPushButton('Browse')
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok |
                                     QDialogButtonBox.Cancel)

        grid = QGridLayout()
        grid.setRowMinimumHeight(1, 10)
        grid.setRowMinimumHeight(4, 10)
        grid.addWidget(tipLabel, 0, 0, 1, 4)
        grid.addWidget(nameLabel, 2, 0)
        grid.addWidget(self.nameEditor, 2, 1, 1, 4)
        grid.addWidget(pathLabel, 3, 0)
        grid.addWidget(self.pathEditor, 3, 1, 1, 4)
        grid.addWidget(browse, 3, 5)
        grid.addWidget(buttonBox, 5, 4, 1, 2)
        self.setLayout(grid)

        browse.clicked.connect(self.browse)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
Exemple #23
0
 def setupUi(self):
     f =QFormLayout(self)
     self.username =QLineEdit(self)
     self.password = QLineEdit(self)
     self.password.setEchoMode(QLineEdit.Password)
     self.host = QLineEdit(self)
     self.dirName = QLineEdit(self)
     self.checkDir = QPushButton("set directory to upload", self)
     self.mail = QLineEdit()
     self.mail.setToolTip("if you enter your email now, metms will be able to get the result on the cluster, if empty you will have to do by yourself")
     self.queue = QComboBox(self)
     self.queue.setToolTip("Each queues correspond to a series of nodes of the same power workq<longq<bigmemq")
     self.queue.addItems(self.queueItems)
     self.interactiveSession=QCheckBox("start an interactive session")
     f.addRow("username:"******"password:"******"hostname:", self.host)
     f.addRow("email:", self.mail)
     f.addRow(self.checkDir, self.dirName)
     f.addRow("select a queue:", self.queue)
     f.addRow("", self.interactiveSession)
     
     self.buttonBox = QDialogButtonBox(self)
     self.buttonBox.setStandardButtons(QDialogButtonBox.Ok|QDialogButtonBox.Cancel)
     f.addRow("", self.buttonBox)
Exemple #24
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 #25
0
    def __init__(self, recipe = None, parent = None):
        super(RecipeEditionDialog, self).__init__(parent)

        self.setWindowTitle('Recipe edition')

        self.name = QLineEdit()
        self.description = QPlainTextEdit()
        self.tags = QLineEdit()
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)

        l = QFormLayout(self)
        l.addRow('Name', self.name)
        l.addRow('Description', self.description)
        l.addRow('Tags', self.tags)
        l.addWidget(buttons)


        if recipe:
            self.recipe = recipe
            self.name.setText(recipe.name)
            self.description.setPlainText(recipe.description)
            self.tags.setText(';'.join(t.name for t in recipe.tags))
        else:
            self.recipe = Recipe('')

        self.accepted.connect(self.save_recipe)
Exemple #26
0
class LocalityWidGet(QWidget):
    """Modal para alterer a localidade da previção do tempo"""
    
    def __init__(self):
        super(LocalityWidGet, self).__init__()
        
        self.setWindowTitle = 'Settings'
        self.setGeometry(450, 300, 400, 200)

        self.locality_label = QLabel('Localidade: ',self)
        self.locality_label.move(20, 35)

        self.locality_label_example = QLabel('Exemplo: Porto Alegre, RS', self)
        self.locality_label_example.move(100, 60)

        self.locality_input_text = QLineEdit(self)
        self.locality_input_text.move(100, 30)

        wc = WeatherClient()
        current_locality = wc.get_place()
        self.locality_input_text.setText(current_locality.replace('+', ', ').decode('utf-8'))

        self.btnOk = QPushButton('OK', self)
        self.btnOk.move(250, 150)
        self.btnOk.clicked.connect(lambda: Eventer.save_new_locality(self))


        self.show()
class H5FileWidget(FileWidget):
    def __init__(self, path="", parent=None):
        super(H5FileWidget, self).__init__(path)
        dataset_button = QPushButton("Dataset")
        self.dataset_edit = QLineEdit()
        self.layout().addRow(dataset_button, self.dataset_edit)
        dataset_button.clicked.connect(self.set_dataset)

    def set_dataset(self):
        dialog = QDialog()
        layout = QVBoxLayout(dialog)
        model = H5File(h5py.File(self.get_path()))
        tree_view = H5View()
        tree_view.setModel(model)
        tree_view.setSelectionMode(QAbstractItemView.SingleSelection)
        button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        button_box.accepted.connect(dialog.accept)
        button_box.rejected.connect(dialog.reject)
        layout.addWidget(tree_view)
        layout.addWidget(button_box)
        if dialog.exec_():
            self.dataset_edit.setText(tree_view.selected_path()[1:])

    def get_file(self):
        f = h5py.File(self.get_path())
        return dataserver_helpers.resolve_path(f, str(self.dataset_edit.text()))
Exemple #28
0
 def setupUi(self, edit_projector_dialog):
     """
     Create the interface layout.
     """
     edit_projector_dialog.setObjectName('edit_projector_dialog')
     edit_projector_dialog.setWindowIcon(build_icon(u':/icon/openlp-logo-32x32.png'))
     edit_projector_dialog.setMinimumWidth(400)
     edit_projector_dialog.setModal(True)
     # Define the basic layout
     self.dialog_layout = QGridLayout(edit_projector_dialog)
     self.dialog_layout.setObjectName('dialog_layout')
     self.dialog_layout.setSpacing(8)
     self.dialog_layout.setContentsMargins(8, 8, 8, 8)
     # IP Address
     self.ip_label = QLabel(edit_projector_dialog)
     self.ip_label.setObjectName('projector_edit_ip_label')
     self.ip_text = QLineEdit(edit_projector_dialog)
     self.ip_text.setObjectName('projector_edit_ip_text')
     self.dialog_layout.addWidget(self.ip_label, 0, 0)
     self.dialog_layout.addWidget(self.ip_text, 0, 1)
     # Port number
     self.port_label = QLabel(edit_projector_dialog)
     self.port_label.setObjectName('projector_edit_ip_label')
     self.port_text = QLineEdit(edit_projector_dialog)
     self.port_text.setObjectName('projector_edit_port_text')
     self.dialog_layout.addWidget(self.port_label, 1, 0)
     self.dialog_layout.addWidget(self.port_text, 1, 1)
     # PIN
     self.pin_label = QLabel(edit_projector_dialog)
     self.pin_label.setObjectName('projector_edit_pin_label')
     self.pin_text = QLineEdit(edit_projector_dialog)
     self.pin_label.setObjectName('projector_edit_pin_text')
     self.dialog_layout.addWidget(self.pin_label, 2, 0)
     self.dialog_layout.addWidget(self.pin_text, 2, 1)
     # Name
     self.name_label = QLabel(edit_projector_dialog)
     self.name_label.setObjectName('projector_edit_name_label')
     self.name_text = QLineEdit(edit_projector_dialog)
     self.name_text.setObjectName('projector_edit_name_text')
     self.dialog_layout.addWidget(self.name_label, 3, 0)
     self.dialog_layout.addWidget(self.name_text, 3, 1)
     # Location
     self.location_label = QLabel(edit_projector_dialog)
     self.location_label.setObjectName('projector_edit_location_label')
     self.location_text = QLineEdit(edit_projector_dialog)
     self.location_text.setObjectName('projector_edit_location_text')
     self.dialog_layout.addWidget(self.location_label, 4, 0)
     self.dialog_layout.addWidget(self.location_text, 4, 1)
     # Notes
     self.notes_label = QLabel(edit_projector_dialog)
     self.notes_label.setObjectName('projector_edit_notes_label')
     self.notes_text = QPlainTextEdit(edit_projector_dialog)
     self.notes_text.setObjectName('projector_edit_notes_text')
     self.dialog_layout.addWidget(self.notes_label, 5, 0, alignment=QtCore.Qt.AlignTop)
     self.dialog_layout.addWidget(self.notes_text, 5, 1)
     # Time for the buttons
     self.button_box = QDialogButtonBox(QDialogButtonBox.Help |
                                        QDialogButtonBox.Save |
                                        QDialogButtonBox.Cancel)
     self.dialog_layout.addWidget(self.button_box, 8, 0, 1, 2)
Exemple #29
0
 def createtokenwidgets(self, tokens, layout):
     for token in tokens:
         label = QLabel(token)
         lineedit = QLineEdit()
         lineedit.setObjectName(token)
         self.tokenwidgets.append(lineedit)
         layout.addRow(label, lineedit)
Exemple #30
0
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Space:
            item = self.frame.listWidget.currentItem()
            self.setText(unicode(item._data[1]))
            return

        QLineEdit.keyPressEvent(self, event)
        currentRow = self.frame.listWidget.currentRow()
        if event.key() == Qt.Key_Down:
            count = self.frame.listWidget.count()
            #If the current position is greater than the amount of items in
            #the list - 6, then try to fetch more items in the list.
            if currentRow >= (count - 6):
                locations = self._create_list_widget_items(self.tempLocations)
                self.frame.fetch_more(locations)
            #While the current position is lower that the list size go to next
            if currentRow != count - 1:
                self.frame.listWidget.setCurrentRow(
                    self.frame.listWidget.currentRow() + 1)
        elif event.key() == Qt.Key_Up:
            #while the current position is greater than 0, go to previous
            if currentRow > 0:
                self.frame.listWidget.setCurrentRow(
                    self.frame.listWidget.currentRow() - 1)
        elif event.key() in (Qt.Key_Return, Qt.Key_Enter):
            #If the user press enter, go to the item selected
            item = self.frame.listWidget.currentItem()
            if type(item) is LocateItem:
                self._open_item(item._data)
            self._parent.statusBar.hide_status()
Exemple #31
0
    def __init__(self, parent):
        super(InfoDialog, self).__init__(parent)
        self.setWindowModality(Qt.WindowModal)

        layout = QVBoxLayout()
        layout.setSpacing(10)
        self.setLayout(layout)

        self.tab = QTabWidget()
        tab_general = QWidget()
        tab_toolcommands = QWidget()
        self.tab.addTab(tab_general, "")
        self.tab.addTab(tab_toolcommands, "")

        # general tab
        vbox = QVBoxLayout()
        vbox.setSpacing(4)
        tab_general.setLayout(vbox)

        hbox = QHBoxLayout()
        self.lilyname = QLineEdit()
        self.lilynameLabel = l = QLabel()
        l.setBuddy(self.lilyname)
        hbox.addWidget(l)
        hbox.addWidget(self.lilyname)
        vbox.addLayout(hbox)

        self.lilypond = widgets.urlrequester.UrlRequester()
        self.lilypond.setFileMode(QFileDialog.ExistingFile)
        self.lilypondLabel = l = QLabel()
        l.setBuddy(self.lilypond)
        vbox.addWidget(l)
        vbox.addWidget(self.lilypond)

        self.auto = QCheckBox()
        vbox.addWidget(self.auto)
        vbox.addStretch(1)

        # toolcommands tab
        grid = QGridLayout()
        grid.setSpacing(4)
        tab_toolcommands.setLayout(grid)

        self.ly_tool_widgets = {}
        row = 0
        for name, gui in self.toolnames():
            w = QLineEdit()
            l = QLabel()
            l.setBuddy(w)
            grid.addWidget(l, row, 0)
            grid.addWidget(w, row, 1)
            row += 1
            self.ly_tool_widgets[name] = (l, w)

        layout.addWidget(self.tab)
        layout.addWidget(widgets.Separator())
        b = self.buttons = QDialogButtonBox(self)
        layout.addWidget(b)

        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        userguide.addButton(b, "prefs_lilypond")
        app.translateUI(self)
        qutil.saveDialogSize(self,
                             "/preferences/lilypond/lilypondinfo/dialog/size")
Exemple #32
0
class SettingsPage(QWidget):
    """
    """
    ReloadSettings = pyqtSignal()

    def __init__(self, parent):
        """
        """
        super(SettingsPage, self).__init__()
        self.__core = parent
        self.config = None

        self.createWidgets()
        self.createConnections()

        self.loadCfg()

    def core(self):
        """
        """
        return self.__core

    def createConnections(self):
        """
        """
        self.saveButton.clicked.connect(self.saveCfg)

    def createWidgets(self):
        """
        """
        jenkinsSvrGroup = QGroupBox(self.tr("Jenkins server informations"))
        self.jenkinsSvrURL = QLineEdit()

        jenkinsSvrLayout = QGridLayout()
        jenkinsSvrLayout.addWidget(QLabel("URL"), 0, 0)
        jenkinsSvrLayout.addWidget(self.jenkinsSvrURL, 0, 1)
        jenkinsSvrGroup.setLayout(jenkinsSvrLayout)

        layoutCtrls = QHBoxLayout()
        self.saveButton = QPushButton(self.tr("Save Settings"), self)
        layoutCtrls.addWidget(self.saveButton)

        mainLayout = QVBoxLayout()
        mainLayout.addWidget(jenkinsSvrGroup)
        mainLayout.addLayout(layoutCtrls)
        mainLayout.addStretch(1)
        self.setLayout(mainLayout)

    def loadCfg(self):
        """
        """
        with open("%s/config.json" % (QtHelper.dirExec())) as f:
            CONFIG_RAW = f.read()
        self.config = json.loads(CONFIG_RAW)

        self.jenkinsSvrURL.setText(self.config["jenkins-server"]["url"])

    def saveCfg(self):
        """
        """
        if not len(self.jenkinsSvrURL.text()):
            QMessageBox.warning(self, self.tr("Save Settings"),
                                self.tr("Please to set the server url"))
            return

        self.config["jenkins-server"]["url"] = self.jenkinsSvrURL.text()

        with open("%s/config.json" % (QtHelper.dirExec()), "w") as f:
            f.write(json.dumps(self.config))

        self.ReloadSettings.emit()

        QMessageBox.information(self, self.tr("Save Settings"),
                                self.tr("Settings saved."))

    def cfg(self):
        """
        """
        return self.config
Exemple #33
0
    def createWidgets(self):
        """
        QtWidgets creation

        QTreeWidget (Name, Running on address, Type, Sched at, Version, Description)
         _______________
        |               |
        |---------------|
        |               |
        |               |
        |_______________|
        """
        layout = QHBoxLayout()

        self.deployBox = QGroupBox("Default probes")
        self.probesAvailable = QTreeWidget(self)
        self.probesAvailable.setIndentation(10)
        self.labelsAvail = [self.tr("Installed")]
        self.probesAvailable.setHeaderLabels(self.labelsAvail)

        self.runningBox = QGroupBox("Running")
        self.probesRegistered = QTreeWidget(self)
        self.probesRegistered.setIndentation(10)
        self.runningDockToolbar = QToolBar(self)
        self.runningDockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.availDockToolbar = QToolBar(self)
        self.availDockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.labels = [
            self.tr("Name"),
            self.tr("Running on address"),
            self.tr("Started at"),
            self.tr("Type"),
            self.tr("Auto Startup"),
            self.tr("Description")
        ]
        self.probesRegistered.setHeaderLabels(self.labels)
        self.probesRegistered.setColumnWidth(0, 180)
        self.probesRegistered.setColumnWidth(1, 120)
        self.probesRegistered.setColumnWidth(2, 150)
        self.probesRegistered.setColumnWidth(3, 70)
        self.probesRegistered.setContextMenuPolicy(Qt.CustomContextMenu)

        self.probesDefault = QTreeWidget(self)
        self.probesDefault.setIndentation(10)
        self.labelsDefault = [
            self.tr("Enabled"),
            self.tr("Name"),
            self.tr("Type"),
            self.tr("Description")
        ]
        self.probesDefault.setHeaderLabels(self.labelsDefault)
        self.probesDefault.setContextMenuPolicy(Qt.CustomContextMenu)
        self.probesDefault.setColumnWidth(1, 180)

        layoutRunning = QVBoxLayout()
        layoutRunning.addWidget(self.runningDockToolbar)
        layoutRunning.addWidget(self.probesRegistered)
        self.runningBox.setLayout(layoutRunning)

        self.probeNameEdit = QLineEdit('')
        self.probeNameEdit.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)

        self.probeDescEdit = QLineEdit('')
        self.probeDescEdit.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)

        self.probeTypeEdit = QLineEdit('')
        self.probeTypeEdit.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
        self.probeTypeEdit.setEnabled(False)

        self.probeDescrInstalledEdit = QTextEdit('')
        self.probeDescrInstalledEdit.setEnabled(False)

        self.checkAutoStartOption = QCheckBox()
        self.checkStartNowOption = QCheckBox()

        paramLayout = QGridLayout()
        paramLayout.addWidget(QLabel("Type:"), 0, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeTypeEdit, 0, 1)
        paramLayout.addWidget(QLabel("Name:"), 1, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeNameEdit, 1, 1)
        paramLayout.addWidget(QLabel("Description:"), 2, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeDescEdit, 2, 1)
        paramLayout.addWidget(QLabel("Startup on boot:"), 3, 0, Qt.AlignRight)
        paramLayout.addWidget(self.checkAutoStartOption, 3, 1)
        paramLayout.addWidget(QLabel("Start now:"), 4, 0, Qt.AlignRight)
        paramLayout.addWidget(self.checkStartNowOption, 4, 1)

        layoutLeft = QVBoxLayout()

        layoutAvail = QHBoxLayout()
        layoutAvail.addWidget(self.probesAvailable)
        layoutAvail.addWidget(self.probeDescrInstalledEdit)

        layoutLeft.addLayout(layoutAvail)
        layoutLeft.addWidget(self.runningBox)

        layoutDeploy = QVBoxLayout()
        layoutDeploy.addWidget(self.availDockToolbar)
        layoutDeploy.addLayout(paramLayout)
        layoutDeploy.addWidget(self.probesDefault)
        self.deployBox.setLayout(layoutDeploy)

        layoutRight = QVBoxLayout()
        layoutRight.addWidget(self.deployBox)

        layout.addLayout(layoutLeft)
        layout.addLayout(layoutRight)
        self.setLayout(layout)
Exemple #34
0
class WProbes(QWidget, Logger.ClassLogger):
    """
    Widget for probes
    """
    def __init__(self, parent):
        """
        Constructs WProbes widget

        @param parent: 
        @type parent:
        """
        QWidget.__init__(self, parent)
        self.parent = parent
        self.name = self.tr("Probes")
        self.itemCurrentRunning = None
        self.itemCurrentInstalled = None
        self.itemCurrentDefault = None
        self.probes = {}

        self.nbPrbs = 0
        # self.prbsInstalled = None

        self.createWidgets()
        self.createConnections()
        self.createActions()
        self.createToolbar()
        self.deactivate()

    def createWidgets(self):
        """
        QtWidgets creation

        QTreeWidget (Name, Running on address, Type, Sched at, Version, Description)
         _______________
        |               |
        |---------------|
        |               |
        |               |
        |_______________|
        """
        layout = QHBoxLayout()

        self.deployBox = QGroupBox("Default probes")
        self.probesAvailable = QTreeWidget(self)
        self.probesAvailable.setIndentation(10)
        self.labelsAvail = [self.tr("Installed")]
        self.probesAvailable.setHeaderLabels(self.labelsAvail)

        self.runningBox = QGroupBox("Running")
        self.probesRegistered = QTreeWidget(self)
        self.probesRegistered.setIndentation(10)
        self.runningDockToolbar = QToolBar(self)
        self.runningDockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)
        self.availDockToolbar = QToolBar(self)
        self.availDockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.labels = [
            self.tr("Name"),
            self.tr("Running on address"),
            self.tr("Started at"),
            self.tr("Type"),
            self.tr("Auto Startup"),
            self.tr("Description")
        ]
        self.probesRegistered.setHeaderLabels(self.labels)
        self.probesRegistered.setColumnWidth(0, 180)
        self.probesRegistered.setColumnWidth(1, 120)
        self.probesRegistered.setColumnWidth(2, 150)
        self.probesRegistered.setColumnWidth(3, 70)
        self.probesRegistered.setContextMenuPolicy(Qt.CustomContextMenu)

        self.probesDefault = QTreeWidget(self)
        self.probesDefault.setIndentation(10)
        self.labelsDefault = [
            self.tr("Enabled"),
            self.tr("Name"),
            self.tr("Type"),
            self.tr("Description")
        ]
        self.probesDefault.setHeaderLabels(self.labelsDefault)
        self.probesDefault.setContextMenuPolicy(Qt.CustomContextMenu)
        self.probesDefault.setColumnWidth(1, 180)

        layoutRunning = QVBoxLayout()
        layoutRunning.addWidget(self.runningDockToolbar)
        layoutRunning.addWidget(self.probesRegistered)
        self.runningBox.setLayout(layoutRunning)

        self.probeNameEdit = QLineEdit('')
        self.probeNameEdit.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)

        self.probeDescEdit = QLineEdit('')
        self.probeDescEdit.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)

        self.probeTypeEdit = QLineEdit('')
        self.probeTypeEdit.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
        self.probeTypeEdit.setEnabled(False)

        self.probeDescrInstalledEdit = QTextEdit('')
        self.probeDescrInstalledEdit.setEnabled(False)

        self.checkAutoStartOption = QCheckBox()
        self.checkStartNowOption = QCheckBox()

        paramLayout = QGridLayout()
        paramLayout.addWidget(QLabel("Type:"), 0, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeTypeEdit, 0, 1)
        paramLayout.addWidget(QLabel("Name:"), 1, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeNameEdit, 1, 1)
        paramLayout.addWidget(QLabel("Description:"), 2, 0, Qt.AlignRight)
        paramLayout.addWidget(self.probeDescEdit, 2, 1)
        paramLayout.addWidget(QLabel("Startup on boot:"), 3, 0, Qt.AlignRight)
        paramLayout.addWidget(self.checkAutoStartOption, 3, 1)
        paramLayout.addWidget(QLabel("Start now:"), 4, 0, Qt.AlignRight)
        paramLayout.addWidget(self.checkStartNowOption, 4, 1)

        layoutLeft = QVBoxLayout()

        layoutAvail = QHBoxLayout()
        layoutAvail.addWidget(self.probesAvailable)
        layoutAvail.addWidget(self.probeDescrInstalledEdit)

        layoutLeft.addLayout(layoutAvail)
        layoutLeft.addWidget(self.runningBox)

        layoutDeploy = QVBoxLayout()
        layoutDeploy.addWidget(self.availDockToolbar)
        layoutDeploy.addLayout(paramLayout)
        layoutDeploy.addWidget(self.probesDefault)
        self.deployBox.setLayout(layoutDeploy)

        layoutRight = QVBoxLayout()
        layoutRight.addWidget(self.deployBox)

        layout.addLayout(layoutLeft)
        layout.addLayout(layoutRight)
        self.setLayout(layout)

    def createConnections(self):
        """
        Create Qt Connections
        """
        self.probesRegistered.customContextMenuRequested.connect(
            self.onPopupMenu)
        self.probesRegistered.currentItemChanged.connect(
            self.currentItemChanged)
        self.probesRegistered.itemClicked.connect(self.itemClicked)

        self.probesAvailable.currentItemChanged.connect(
            self.currentItemChanged)

        self.probesDefault.currentItemChanged.connect(self.currentItemChanged)
        self.probesDefault.customContextMenuRequested.connect(
            self.onPopupMenuDefault)

    def createActions(self):
        """
        Actions defined:
         * stop probe
         * start probe
         * delete one probe
         * clear fields
         * refresh running probes
         * refresh default probes
        """
        self.stopAction = QtHelper.createAction(self,
                                                "&Stop",
                                                self.stopProbe,
                                                tip='Stop probe',
                                                icon=QIcon(":/act-stop.png"))
        self.startAction = QtHelper.createAction(self,
                                                 "&Add / Start",
                                                 self.startProbe,
                                                 tip='Add default probe',
                                                 icon=QIcon(":/probe-add.png"))
        self.delProbeAction = QtHelper.createAction(
            self,
            "&Delete",
            self.delProbe,
            tip='Delete default probe',
            icon=QIcon(":/probe-del.png"))
        self.cancelAction = QtHelper.createAction(self,
                                                  "&Clear",
                                                  self.resetProbe,
                                                  tip='Clear fields',
                                                  icon=QIcon(":/clear.png"))
        self.refreshRunningAction = QtHelper.createAction(
            self,
            "&Refresh",
            self.refreshRunningProbe,
            tip='Refresh running probes',
            icon=QIcon(":/act-refresh.png"))
        self.refreshDefaultAction = QtHelper.createAction(
            self,
            "&Refresh",
            self.refreshDefaultProbe,
            tip='Refresh default probes',
            icon=QIcon(":/act-refresh.png"))

    def createToolbar(self):
        """
        Toolbar creation
            
        ||-------||
        || Empty ||
        ||-------||
        """
        self.runningDockToolbar.setObjectName("Registered Probe toolbar")
        self.runningDockToolbar.addAction(self.refreshRunningAction)
        self.runningDockToolbar.addSeparator()
        self.runningDockToolbar.addAction(self.stopAction)
        self.runningDockToolbar.addSeparator()
        self.runningDockToolbar.setIconSize(QSize(16, 16))

        self.availDockToolbar.setObjectName("Installed Probe toolbar")
        self.availDockToolbar.addAction(self.refreshDefaultAction)
        self.availDockToolbar.addSeparator()
        self.availDockToolbar.addAction(self.startAction)
        self.availDockToolbar.addAction(self.delProbeAction)
        self.availDockToolbar.addSeparator()
        self.availDockToolbar.addAction(self.cancelAction)
        self.availDockToolbar.addSeparator()
        self.availDockToolbar.setIconSize(QSize(16, 16))

    def itemClicked(self, currentItem):
        """
        On item clicked

        @param currentItem: 
        @type currentItem:  
        """
        if currentItem is not None:
            if isinstance(currentItem, ProbeItem):
                self.itemCurrentRunning = currentItem
                self.stopAction.setEnabled(True)

    def currentItemChanged(self, currentItem, previousItem):
        """
        On current item changed

        @param currentItem: 
        @type currentItem:  

        @param previousItem: 
        @type previousItem: 
        """
        if currentItem is not None:
            if isinstance(currentItem, ProbeInstalledItem):
                self.itemCurrentInstalled = currentItem
                if 'description' in currentItem.dataProbe:
                    self.probeDescrInstalledEdit.setText(
                        currentItem.dataProbe['description'])
                    self.probeTypeEdit.setText(currentItem.dataProbe['type'])
                else:
                    self.probeDescrInstalledEdit.setText('')
            elif isinstance(currentItem, ProbeItem):
                self.itemCurrentRunning = currentItem
                self.stopAction.setEnabled(True)
            elif isinstance(currentItem, ProbeDefaultItem):
                self.itemCurrentDefault = currentItem
                self.delProbeAction.setEnabled(True)
            else:
                self.stopAction.setEnabled(False)
                self.delProbeAction.setEnabled(False)
                self.probeDescrInstalledEdit.setText('')

    def onPopupMenu(self, pos):
        """
        Display menu on right click

        @param pos: 
        @type pos:
        """
        self.menu = QMenu()
        item = self.probesRegistered.itemAt(pos)
        if item:
            self.itemCurrentRunning = item
            self.menu.addAction("Stop...", self.stopProbe)
            self.menu.popup(self.probesRegistered.mapToGlobal(pos))

    def onPopupMenuDefault(self, pos):
        """
        Display menu on right click

        @param pos: 
        @type pos:
        """
        self.menu = QMenu()
        item = self.probesDefault.itemAt(pos)
        if item:
            self.itemCurrentDefault = item
            self.menu.addAction("Delete...", self.delProbe)
            self.menu.popup(self.probesDefault.mapToGlobal(pos))

    def refreshDefaultProbe(self):
        """
        Refresh the default list of probes
        """
        RCI.instance().defaultProbes()

    def refreshRunningProbe(self):
        """
        Refresh the running list of probes
        """
        RCI.instance().runningProbes()

    def delProbe(self):
        """
        Delete probe
        """
        if self.itemCurrentDefault is not None:
            reply = QMessageBox.question(self, "Stop probe", "Are you sure ?",
                                         QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                probeName = self.itemCurrentDefault.dataProbe['name']
                self.delProbeAction.setEnabled(False)

                # rest call
                RCI.instance().removeProbe(probeName=probeName)

    def stopProbe(self):
        """
        Stop the selected probe
        """
        if self.itemCurrentRunning is not None:
            reply = QMessageBox.question(self, "Stop probe", "Are you sure ?",
                                         QMessageBox.Yes | QMessageBox.No)
            if reply == QMessageBox.Yes:
                probeName = self.itemCurrentRunning.dataProbe['id']
                self.itemCurrentRunning = None
                self.stopAction.setEnabled(False)

                # rest call
                RCI.instance().disconnectProbe(probeName=probeName)

    def startProbe(self):
        """
        Start a new probe
        """
        # some checks before
        if self.probeTypeEdit.text() == '':
            QMessageBox.information(self, "Add Default Probe",
                                    "Please select the probe type.")
            return
        if self.probeNameEdit.text() == '':
            QMessageBox.information(self, "Add Default Probe",
                                    "Probe name is mandatory.")
            return
        if not self.checkAutoStartOption.isChecked(
        ) and not self.checkStartNowOption.isChecked():
            QMessageBox.information(self, "Add Default Probe",
                                    "Select startup option.")
            return

        # call web services
        probeType = str(self.probeTypeEdit.text())
        probeName = str(self.probeNameEdit.text())
        probeDescription = str(self.probeDescEdit.text())
        probeAutoStart = self.checkAutoStartOption.isChecked()

        if not self.checkStartNowOption.isChecked():
            RCI.instance().addProbe(probeName=probeName,
                                    probeType=probeType,
                                    probeDescription=probeDescription)
        else:
            RCI.instance().connectProbe(probeName=probeName,
                                        probeType=probeType,
                                        probeDescription=probeDescription,
                                        probeBoot=probeAutoStart)

    def resetProbe(self):
        """
        Clear probe field
        """
        self.probeDescrInstalledEdit.setText('')
        self.probeDescEdit.setText('')
        self.probeNameEdit.setText('')
        self.probeTypeEdit.setText('')

        # clear selection
        itms = self.probesAvailable.selectedItems()
        for i in itms:
            if i.isSelected():
                i.setSelected(False)
        self.itemCurrentInstalled = None

    def active(self):
        """
        Enables QTreeWidget
        """
        self.probesRegistered.setEnabled(True)
        self.probesAvailable.setEnabled(True)
        self.deployBox.setEnabled(True)
        self.runningBox.setEnabled(True)

        self.refreshRunningAction.setEnabled(True)

    def deactivate(self):
        """
        Clears QTreeWidget and disables it
        """
        self.checkAutoStartOption.setCheckState(Qt.Unchecked)
        self.checkStartNowOption.setCheckState(Qt.Unchecked)

        self.probesAvailable.clear()
        self.probeDescrInstalledEdit.setText('')

        self.probesRegistered.clear()
        self.probesDefault.clear()
        self.probes = {}

        self.probesRegistered.setEnabled(False)
        self.probesAvailable.setEnabled(False)
        self.deployBox.setEnabled(False)
        self.runningBox.setEnabled(False)

        # actions
        self.stopAction.setEnabled(False)
        self.delProbeAction.setEnabled(False)

        self.itemCurrentRunning = None
        self.itemCurrentInstalled = None

        self.probeDescEdit.setText('')
        self.probeTypeEdit.setText('')
        self.probeNameEdit.setText('')

        self.resetNbProbes()

        self.refreshRunningAction.setEnabled(False)

    def getRunningProbes(self):
        """
        Get running probes 
        """
        if sys.version_info > (3, ):  # python3 support
            return list(self.probes.keys())
        else:
            return self.probes.keys()

    def getProbeTypeByName(self, name):
        """
        Get probe type by name

        @param name: 
        @type name:
        """
        if name in self.probes:
            return self.probes[name].getProbeType()
        else:
            return ''

    def loadDefault(self, data):
        """
        Loads default probes

        @param data: 
        @type data: dict
        """
        self.probesDefault.clear()

        for defProbe in data:
            defProbeItem = ProbeDefaultItem(probe=defProbe,
                                            parent=self.probesDefault)

    def loadData(self, data, dataInstalled=None):
        """
        Loads probes

        @param data: 
        @type data: dict

        @param dataInstalled: 
        @type dataInstalled:
        """
        if isinstance(data, dict):
            data = [data]

        self.probesRegistered.clear()

        for probe in data:
            probeItem = ProbeItem(probe=probe, parent=self.probesRegistered)
            self.probes[probe['id']] = probeItem

        # load tests stats
        if dataInstalled is not None:
            if len(dataInstalled) == 0:
                self.deployBox.setEnabled(False)
                self.probesAvailable.setEnabled(False)

    def resetNbProbes(self, data=None):
        """
        Reset the number of probes
        """
        pass

    def refreshData(self, data, action):
        """
        Refresh probes

        @param data: 
        @type data: dict

        @param action: expected values in 'del' and 'add'
        @type action: string
        """
        if action == 'del':
            self.probesRegistered.clear()
            self.probes = {}
            self.resetNbProbes(data=data)
            self.loadData(data=data)
        elif action == 'add':
            self.resetNbProbes(data=data)
            self.loadData(data=data)
        else:
            self.error('action unknown: %s' % str(action))

    def refreshDataDefault(self, data, action):
        """
        Refresh probes

        @param data: 
        @type data: dict

        @param action: expected values in 'del' and 'add'
        @type action: string
        """
        if action == 'del':
            self.probesDefault.clear()
            self.loadDefault(data=data)
        elif action == 'add':
            self.probesDefault.clear()
            self.loadDefault(data=data)
        else:
            self.error('action unknown: %s' % str(action))
Exemple #35
0
    def runConfigWizard(self):
        try:
            api = InstagramAPI(
                client_id=self.options_string['hidden_client_id'],
                client_secret=self.options_string['hidden_client_secret'],
                redirect_uri=self.options_string['redirect_uri'])
            url = api.get_authorize_login_url()

            self.wizard.setWindowTitle('Instagram plugin configuration wizard')
            page1 = QWizardPage()
            layout1 = QVBoxLayout()
            txtArea = QLabel()
            txtArea.setText(
                'Please copy the following link to your browser window. \n ' +
                'Once you authenticate with Instagram you will be redirected to '
                +
                'www.geocreepy.com and get your token. Copy the token to the input field below:'
            )
            urlArea = QLineEdit()
            urlArea.setObjectName('urlArea')
            urlArea.setText(url)
            inputLink = QLineEdit()
            inputLink.setObjectName('inputLink')
            labelLink = QLabel('Your token value:')
            openInBrowserButton = QPushButton('Open in browser')
            openInBrowserButton.clicked.connect(
                functools.partial(self.openLinkInBrowser, url))
            layout1.addWidget(txtArea)
            layout1.addWidget(urlArea)
            layout1.addWidget(openInBrowserButton)
            layout1.addWidget(labelLink)
            layout1.addWidget(inputLink)
            page1.setLayout(layout1)
            self.wizard.addPage(page1)
            self.wizard.resize(600, 400)
            if self.wizard.exec_():
                c = str(inputLink.text())
                if c:
                    try:
                        access_token = api.exchange_code_for_access_token(
                            code=c)
                        self.options_string[
                            'hidden_access_token'] = access_token[0]
                        self.saveConfiguration(self.config)
                    except Exception, err:
                        logger.error(err)
                        self.showWarning(
                            'Error Getting Access Token',
                            'Please verify that the link you pasted was correct. '
                            'Try running the wizard again.')
                else:
                    self.showWarning(
                        'Error Getting Access Token',
                        'Please verify that the link you pasted was correct. Try running the wizard again.'
                    )

        except Exception, err:
            logger.error(err)
            self.showWarning('Error', 'Error was {0}'.format(err))
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.fnames = []  # list of file names to be converted
        self.office_listener_started = False

        self.parse_cla()

        addQPB = QPushButton(self.tr('Add'))
        delQPB = QPushButton(self.tr('Delete'))
        clearQPB = QPushButton(self.tr('Clear'))
        vlayout1 = utils.add_to_layout('v', addQPB, delQPB, clearQPB, None)

        self.filesList = utils.FilesList()
        self.filesList.setSelectionMode(QAbstractItemView.ExtendedSelection)
        hlayout1 = utils.add_to_layout('h', self.filesList, vlayout1)

        outputQL = QLabel(self.tr('Output folder:'))
        self.toQLE = QLineEdit()
        self.toQLE.setReadOnly(True)
        self.toQTB = QToolButton()
        self.toQTB.setText('...')
        hlayout2 = utils.add_to_layout('h', outputQL, self.toQLE, self.toQTB)

        self.audiovideo_tab = AudioVideoTab(self)
        self.image_tab = ImageTab(self)
        self.document_tab = DocumentTab(self)

        self.tabs = [self.audiovideo_tab, self.image_tab, self.document_tab]
        tab_names = [
            self.tr('Audio/Video'),
            self.tr('Images'),
            self.tr('Documents')
        ]

        self.tabWidget = QTabWidget()
        for num, tab in enumerate(tab_names):
            self.tabWidget.addTab(self.tabs[num], tab)
        self.tabWidget.setCurrentIndex(0)

        self.origQCB = QCheckBox(
            self.tr('Save each file in the same\nfolder as input file'))
        self.deleteQCB = QCheckBox(self.tr('Delete original'))
        convertQPB = QPushButton(self.tr('&Convert'))

        hlayout3 = utils.add_to_layout('h', self.origQCB, self.deleteQCB, None)
        hlayout4 = utils.add_to_layout('h', None, convertQPB)
        final_layout = utils.add_to_layout('v', hlayout1, self.tabWidget,
                                           hlayout2, hlayout3, hlayout4)

        self.dependenciesQL = QLabel()
        self.statusBar().addPermanentWidget(self.dependenciesQL, stretch=1)

        widget = QWidget()
        widget.setLayout(final_layout)
        self.setCentralWidget(widget)

        openAction = utils.create_action(self, self.tr('Open'),
                                         QKeySequence.Open, None,
                                         self.tr('Open a file'),
                                         self.add_files)
        convertAction = utils.create_action(self, self.tr('Convert'), 'Ctrl+C',
                                            None, self.tr('Convert files'),
                                            self.start_conversion)
        quitAction = utils.create_action(self, self.tr('Quit'), 'Ctrl+Q', None,
                                         self.tr('Quit'), self.close)
        edit_presetsAction = utils.create_action(self, self.tr('Edit Presets'),
                                                 'Ctrl+P', None,
                                                 self.tr('Edit Presets'),
                                                 self.open_dialog_presets)
        importAction = utils.create_action(self, self.tr('Import'), None, None,
                                           self.tr('Import presets'),
                                           self.import_presets)
        exportAction = utils.create_action(self, self.tr('Export'), None, None,
                                           self.tr('Export presets'),
                                           self.export_presets)
        resetAction = utils.create_action(self, self.tr('Reset'), None, None,
                                          self.tr('Reset presets'),
                                          self.reset_presets)
        syncAction = utils.create_action(self, self.tr('Synchronize'), None,
                                         None, self.tr('Synchronize presets'),
                                         self.sync_presets)
        removeoldAction = utils.create_action(self, self.tr('Remove old'),
                                              None, None,
                                              self.tr('Remove old presets'),
                                              self.removeold_presets)
        clearallAction = utils.create_action(self, self.tr('Clear All'), None,
                                             None, self.tr('Clear form'),
                                             self.clear_all)
        preferencesAction = utils.create_action(self, self.tr('Preferences'),
                                                'Alt+Ctrl+P', None,
                                                self.tr('Preferences'),
                                                self.open_dialog_preferences)
        trackerAction = utils.create_action(
            self, 'Issue tracker', None, None, None, lambda: webbrowser.open(
                "https://github.com/Ilias95/FF-Multi-Converter/issues"))
        wikiAction = utils.create_action(
            self, 'Wiki', None, None, None, lambda: webbrowser.open(
                "https://github.com/Ilias95/FF-Multi-Converter/wiki"))
        ffmpegdocAction = utils.create_action(
            self, 'FFmpeg ' + self.tr('documentation'), None, None, None,
            lambda: webbrowser.open("https://www.ffmpeg.org/documentation.html"
                                    ))
        imagemagickdocAction = utils.create_action(
            self, 'ImageMagick ' + self.tr('documentation'), None, None, None,
            lambda: webbrowser.open(
                "http://www.imagemagick.org/script/convert.php"))
        aboutAction = utils.create_action(self, self.tr('About'), 'Ctrl+?',
                                          None, self.tr('About'),
                                          self.open_dialog_about)

        fileMenu = self.menuBar().addMenu(self.tr('File'))
        editMenu = self.menuBar().addMenu(self.tr('Edit'))
        presetsMenu = self.menuBar().addMenu(self.tr('Presets'))
        helpMenu = self.menuBar().addMenu(self.tr('Help'))

        utils.add_actions(fileMenu,
                          [openAction, convertAction, None, quitAction])
        utils.add_actions(presetsMenu, [
            edit_presetsAction, importAction, exportAction, resetAction, None,
            syncAction, removeoldAction
        ])
        utils.add_actions(editMenu, [clearallAction, None, preferencesAction])
        utils.add_actions(helpMenu, [
            trackerAction, wikiAction, None, ffmpegdocAction,
            imagemagickdocAction, None, aboutAction
        ])

        self.filesList.dropped.connect(self.add_files_dropped)
        addQPB.clicked.connect(self.add_files)
        delQPB.clicked.connect(self.delete_files)
        clearQPB.clicked.connect(self.clear_fileslist)
        self.tabWidget.currentChanged.connect(
            lambda: self.tabs[0].moreQPB.setChecked(False))
        self.origQCB.toggled.connect(
            lambda: self.toQLE.setEnabled(not self.origQCB.isChecked()))
        self.toQTB.clicked.connect(self.open_dir)
        convertQPB.clicked.connect(convertAction.triggered)

        del_shortcut = QShortcut(self)
        del_shortcut.setKey(Qt.Key_Delete)
        del_shortcut.activated.connect(self.delete_files)

        self.setWindowTitle('FF Multi Converter')

        QTimer.singleShot(0, self.check_for_dependencies)
        QTimer.singleShot(0, self.load_settings)
        QTimer.singleShot(0, self.audiovideo_tab.set_default_command)
        QTimer.singleShot(0, self.image_tab.set_default_command)
        QTimer.singleShot(0, self.update_filesList)
class MainWindow(QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)

        self.fnames = []  # list of file names to be converted
        self.office_listener_started = False

        self.parse_cla()

        addQPB = QPushButton(self.tr('Add'))
        delQPB = QPushButton(self.tr('Delete'))
        clearQPB = QPushButton(self.tr('Clear'))
        vlayout1 = utils.add_to_layout('v', addQPB, delQPB, clearQPB, None)

        self.filesList = utils.FilesList()
        self.filesList.setSelectionMode(QAbstractItemView.ExtendedSelection)
        hlayout1 = utils.add_to_layout('h', self.filesList, vlayout1)

        outputQL = QLabel(self.tr('Output folder:'))
        self.toQLE = QLineEdit()
        self.toQLE.setReadOnly(True)
        self.toQTB = QToolButton()
        self.toQTB.setText('...')
        hlayout2 = utils.add_to_layout('h', outputQL, self.toQLE, self.toQTB)

        self.audiovideo_tab = AudioVideoTab(self)
        self.image_tab = ImageTab(self)
        self.document_tab = DocumentTab(self)

        self.tabs = [self.audiovideo_tab, self.image_tab, self.document_tab]
        tab_names = [
            self.tr('Audio/Video'),
            self.tr('Images'),
            self.tr('Documents')
        ]

        self.tabWidget = QTabWidget()
        for num, tab in enumerate(tab_names):
            self.tabWidget.addTab(self.tabs[num], tab)
        self.tabWidget.setCurrentIndex(0)

        self.origQCB = QCheckBox(
            self.tr('Save each file in the same\nfolder as input file'))
        self.deleteQCB = QCheckBox(self.tr('Delete original'))
        convertQPB = QPushButton(self.tr('&Convert'))

        hlayout3 = utils.add_to_layout('h', self.origQCB, self.deleteQCB, None)
        hlayout4 = utils.add_to_layout('h', None, convertQPB)
        final_layout = utils.add_to_layout('v', hlayout1, self.tabWidget,
                                           hlayout2, hlayout3, hlayout4)

        self.dependenciesQL = QLabel()
        self.statusBar().addPermanentWidget(self.dependenciesQL, stretch=1)

        widget = QWidget()
        widget.setLayout(final_layout)
        self.setCentralWidget(widget)

        openAction = utils.create_action(self, self.tr('Open'),
                                         QKeySequence.Open, None,
                                         self.tr('Open a file'),
                                         self.add_files)
        convertAction = utils.create_action(self, self.tr('Convert'), 'Ctrl+C',
                                            None, self.tr('Convert files'),
                                            self.start_conversion)
        quitAction = utils.create_action(self, self.tr('Quit'), 'Ctrl+Q', None,
                                         self.tr('Quit'), self.close)
        edit_presetsAction = utils.create_action(self, self.tr('Edit Presets'),
                                                 'Ctrl+P', None,
                                                 self.tr('Edit Presets'),
                                                 self.open_dialog_presets)
        importAction = utils.create_action(self, self.tr('Import'), None, None,
                                           self.tr('Import presets'),
                                           self.import_presets)
        exportAction = utils.create_action(self, self.tr('Export'), None, None,
                                           self.tr('Export presets'),
                                           self.export_presets)
        resetAction = utils.create_action(self, self.tr('Reset'), None, None,
                                          self.tr('Reset presets'),
                                          self.reset_presets)
        syncAction = utils.create_action(self, self.tr('Synchronize'), None,
                                         None, self.tr('Synchronize presets'),
                                         self.sync_presets)
        removeoldAction = utils.create_action(self, self.tr('Remove old'),
                                              None, None,
                                              self.tr('Remove old presets'),
                                              self.removeold_presets)
        clearallAction = utils.create_action(self, self.tr('Clear All'), None,
                                             None, self.tr('Clear form'),
                                             self.clear_all)
        preferencesAction = utils.create_action(self, self.tr('Preferences'),
                                                'Alt+Ctrl+P', None,
                                                self.tr('Preferences'),
                                                self.open_dialog_preferences)
        trackerAction = utils.create_action(
            self, 'Issue tracker', None, None, None, lambda: webbrowser.open(
                "https://github.com/Ilias95/FF-Multi-Converter/issues"))
        wikiAction = utils.create_action(
            self, 'Wiki', None, None, None, lambda: webbrowser.open(
                "https://github.com/Ilias95/FF-Multi-Converter/wiki"))
        ffmpegdocAction = utils.create_action(
            self, 'FFmpeg ' + self.tr('documentation'), None, None, None,
            lambda: webbrowser.open("https://www.ffmpeg.org/documentation.html"
                                    ))
        imagemagickdocAction = utils.create_action(
            self, 'ImageMagick ' + self.tr('documentation'), None, None, None,
            lambda: webbrowser.open(
                "http://www.imagemagick.org/script/convert.php"))
        aboutAction = utils.create_action(self, self.tr('About'), 'Ctrl+?',
                                          None, self.tr('About'),
                                          self.open_dialog_about)

        fileMenu = self.menuBar().addMenu(self.tr('File'))
        editMenu = self.menuBar().addMenu(self.tr('Edit'))
        presetsMenu = self.menuBar().addMenu(self.tr('Presets'))
        helpMenu = self.menuBar().addMenu(self.tr('Help'))

        utils.add_actions(fileMenu,
                          [openAction, convertAction, None, quitAction])
        utils.add_actions(presetsMenu, [
            edit_presetsAction, importAction, exportAction, resetAction, None,
            syncAction, removeoldAction
        ])
        utils.add_actions(editMenu, [clearallAction, None, preferencesAction])
        utils.add_actions(helpMenu, [
            trackerAction, wikiAction, None, ffmpegdocAction,
            imagemagickdocAction, None, aboutAction
        ])

        self.filesList.dropped.connect(self.add_files_dropped)
        addQPB.clicked.connect(self.add_files)
        delQPB.clicked.connect(self.delete_files)
        clearQPB.clicked.connect(self.clear_fileslist)
        self.tabWidget.currentChanged.connect(
            lambda: self.tabs[0].moreQPB.setChecked(False))
        self.origQCB.toggled.connect(
            lambda: self.toQLE.setEnabled(not self.origQCB.isChecked()))
        self.toQTB.clicked.connect(self.open_dir)
        convertQPB.clicked.connect(convertAction.triggered)

        del_shortcut = QShortcut(self)
        del_shortcut.setKey(Qt.Key_Delete)
        del_shortcut.activated.connect(self.delete_files)

        self.setWindowTitle('FF Multi Converter')

        QTimer.singleShot(0, self.check_for_dependencies)
        QTimer.singleShot(0, self.load_settings)
        QTimer.singleShot(0, self.audiovideo_tab.set_default_command)
        QTimer.singleShot(0, self.image_tab.set_default_command)
        QTimer.singleShot(0, self.update_filesList)

    def parse_cla(self):
        """Parse command line arguments."""
        for i in QCoreApplication.argv()[1:]:
            i = os.path.abspath(i)
            if os.path.isfile(i):
                self.fnames.append(i)
            else:
                print("ffmulticonverter: {0}: Not a file".format(i))

    def check_for_dependencies(self):
        """
        Check if each one of the program dependencies are installed and
        update self.dependenciesQL with the appropriate message.
        """
        self.vidconverter = None
        if utils.is_installed('ffmpeg'):
            self.vidconverter = 'ffmpeg'
        elif utils.is_installed('avconv'):
            self.vidconverter = 'avconv'
        self.unoconv = utils.is_installed('unoconv')
        self.imagemagick = utils.is_installed('convert')

        missing = []
        if self.vidconverter is None:
            missing.append('ffmpeg/avconv')
        if not self.unoconv:
            missing.append('unoconv')
        if not self.imagemagick:
            missing.append('imagemagick')

        if missing:
            missing = ', '.join(missing)
            status = self.tr('Missing dependencies:') + ' ' + missing
            self.dependenciesQL.setText(status)

    def load_settings(self, onstart=True):
        """
        Load settings values.

        onstart -- True means that this is the first time the method called,
                   usually when program beggins
        """
        def get_str_value(settings, name):
            value = settings.value(name)
            if value is not None:
                return value
            return ''

        settings = QSettings()
        self.overwrite_existing = utils.str_to_bool(
            get_str_value(settings, 'overwrite_existing'))
        self.default_output = get_str_value(settings, 'default_output')
        self.prefix = get_str_value(settings, 'prefix')
        self.suffix = get_str_value(settings, 'suffix')
        defcmd = get_str_value(settings, 'default_command')
        extraformats_video = get_str_value(settings, 'extraformats')
        videocodecs = settings.value('videocodecs')
        audiocodecs = settings.value('audiocodecs')
        defcmd_image = get_str_value(settings, 'default_command_image')
        extraformats_image = get_str_value(settings, 'extraformats_image')

        if videocodecs is None:
            videocodecs = "\n".join(config.video_codecs)
            settings.setValue('videocodecs', videocodecs)
        if audiocodecs is None:
            audiocodecs = "\n".join(config.audio_codecs)
            settings.setValue('audiocodecs', audiocodecs)

        if defcmd:
            self.default_command = defcmd
        else:
            self.default_command = config.default_ffmpeg_cmd
        if defcmd_image:
            self.default_command_image = defcmd_image
        else:
            self.default_command_image = config.default_imagemagick_cmd

        self.audiovideo_tab.fill_video_comboboxes(videocodecs, audiocodecs,
                                                  extraformats_video)
        self.image_tab.fill_extension_combobox(extraformats_image)

        if onstart:
            self.toQLE.setText(self.default_output)

    def current_tab(self):
        """Return the corresponding object of the selected tab."""
        for i in self.tabs:
            if self.tabs.index(i) == self.tabWidget.currentIndex():
                return i

    def update_filesList(self):
        """Clear self.filesList and add to it all items of self.fname."""
        self.filesList.clear()
        for i in self.fnames:
            self.filesList.addItem(i)

    def add_files(self):
        """
        Get file names using a standard Qt dialog.
        Append to self.fnames each file name that not already exists
        and update self.filesList.
        """
        # Create lists holding file formats extension.
        # To be passed in QFileDialog.getOpenFileNames().
        all_files = '*'
        audiovideo_files = ' '.join(
            ['*.' + i for i in self.audiovideo_tab.formats])
        img_formats = self.image_tab.formats[:]
        img_formats.extend(self.image_tab.extra_img)
        image_files = ' '.join(['*.' + i for i in img_formats])
        document_files = ' '.join(
            ['*.' + i for i in self.document_tab.formats])
        formats = [all_files, audiovideo_files, image_files, document_files]
        strings = [
            self.tr('All Files'),
            self.tr('Audio/Video Files'),
            self.tr('Image Files'),
            self.tr('Document Files')
        ]

        filters = ''
        for string, extensions in zip(strings, formats):
            filters += string + ' ({0});;'.format(extensions)
        filters = filters[:-2]  # remove last ';;'

        fnames = QFileDialog.getOpenFileNames(
            self, 'FF Multi Converter - ' + self.tr('Choose File'),
            config.home, filters)

        if fnames:
            for i in fnames:
                if not i in self.fnames:
                    self.fnames.append(i)
            self.update_filesList()

    def add_files_dropped(self, links):
        """
        Append to self.fnames each file name that not already exists
        and update self.filesList.
        """
        for path in links:
            if os.path.isfile(path) and not path in self.fnames:
                self.fnames.append(path)
        self.update_filesList()

    def delete_files(self):
        """
        Get selectedItems of self.filesList, remove them from self.fnames and
        update the filesList.
        """
        items = self.filesList.selectedItems()
        if items:
            for i in items:
                self.fnames.remove(i.text())
            self.update_filesList()

    def clear_fileslist(self):
        """Make self.fnames empty and update self.filesList."""
        self.fnames = []
        self.update_filesList()

    def clear_all(self):
        """Clear all values of graphical widgets."""
        self.toQLE.clear()
        self.origQCB.setChecked(False)
        self.deleteQCB.setChecked(False)
        self.clear_fileslist()

        self.audiovideo_tab.clear()
        self.image_tab.clear()

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

    def import_presets(self):
        presets_dlgs.ShowPresets().import_presets()

    def export_presets(self):
        presets_dlgs.ShowPresets().export_presets()

    def reset_presets(self):
        presets_dlgs.ShowPresets().reset()

    def sync_presets(self):
        presets_dlgs.ShowPresets().synchronize()

    def removeold_presets(self):
        presets_dlgs.ShowPresets().remove_old()

    def ok_to_continue(self):
        """
        Check if everything is ok to continue with conversion.

        Check if:
        - At least one file has given for conversion.
        - An output folder has given.
        - Output folder exists.

        Return False if an error arises, else True.
        """
        try:
            if not self.fnames:
                raise ValidationError(
                    self.tr('You must add at least one file to convert!'))
            elif not self.origQCB.isChecked() and not self.toQLE.text():
                raise ValidationError(
                    self.tr('You must choose an output folder!'))
            elif (not self.origQCB.isChecked()
                  and not os.path.exists(self.toQLE.text())):
                raise ValidationError(
                    self.tr('Output folder does not exists!'))
            if not self.current_tab().ok_to_continue():
                return False
            return True

        except ValidationError as e:
            QMessageBox.warning(self,
                                'FF Multi Converter - ' + self.tr('Error!'),
                                str(e))
            return False

    def get_output_extension(self):
        """Extract the desired output file extension from GUI and return it."""
        tab = self.current_tab()
        if tab.name == 'AudioVideo':
            ext_to = self.audiovideo_tab.extQCB.currentText()
        elif tab.name == 'Images':
            ext_to = tab.extQCB.currentText()
        else:
            ext_to = tab.convertQCB.currentText().split()[-1]

        return '.' + ext_to

    def start_conversion(self):
        """
        Extract the appropriate information from GUI and call the
        Progress dialog with the suitable argumens.
        """
        if not self.ok_to_continue():
            return

        tab = self.current_tab()
        if tab.name == 'Documents' and not self.office_listener_started:
            utils.start_office_listener()
            self.office_listener_started = True

        ext_to = self.get_output_extension()
        _list = utils.create_paths_list(self.fnames, ext_to, self.prefix,
                                        self.suffix, self.toQLE.text(),
                                        self.origQCB.isChecked(),
                                        self.overwrite_existing)

        dialog = progress.Progress(_list, tab, self.deleteQCB.isChecked(),
                                   self)
        dialog.show()

    def open_dialog_preferences(self):
        """Open the preferences dialog."""
        dialog = preferences_dlg.Preferences(self)
        if dialog.exec_():
            self.load_settings(onstart=False)

    def open_dialog_presets(self):
        """Open the presets dialog."""
        dialog = presets_dlgs.ShowPresets(self)
        dialog.exec_()

    def open_dialog_about(self):
        """Call the about dialog with the appropriate values."""
        msg = self.tr('Convert among several file types to other formats')
        msg = textwrap.fill(msg, 54).replace('\n', '<br>')
        text = '''<b> FF Multi Converter {0} </b>
                 <p>{1}
                 <p><a href="{2}">FF Multi Converter - Home Page</a>
                 <p>Copyright &copy; 2011-2015 {3}
                 <br>License: {4}
                 <p>Python {5} - Qt {6} - PyQt {7} on {8}'''\
                 .format(ffmc.__version__, msg, ffmc.__url__, ffmc.__author__,
                         ffmc.__license__, platform.python_version()[:5],
                         QT_VERSION_STR, PYQT_VERSION_STR, platform.system())
        image = ':/ffmulticonverter.png'
        authors = '{0} <{1}>\n\n'.format(ffmc.__author__,
                                         ffmc.__author_email__)
        authors += 'Contributors:\nPanagiotis Mavrogiorgos'
        translators = []
        for i in config.translators:
            translators.append('{0}\n     {1}'.format(i[0], i[1]))
        translators = '\n\n'.join(translators)

        dialog = about_dlg.AboutDialog(text, image, authors, translators, self)
        dialog.exec_()
Exemple #38
0
    def __init__(self, reaction):
        super(ConditionsDialog, self).__init__()
        self.setGeometry (300 , 300 , 700 , 350)
        self.setWindowTitle ('Edit Conditions')
        if reaction is None:
            self._reaction = Reaction()
        else:
            self._reaction = reaction
        self._CanReturnReaction = False

        # Sets up GUI widgets. Formula boxes will need to support super and subscript somehow
        # Will also need validation later

        # Reactants section
        self._reactantbox = QGroupBox("Reactants", self)
        self._reactantform = QFormLayout()
        self._reactantinfoboxes = []
        self._productinfoboxes = []
        self._catalystinfoboxes = []
        for x in range(Reaction.REACTING_SPECIES_LIMIT):
            self._reactantinfoboxes.append(QLineEdit())
            self._reactantinfoboxes[x*2].setText(self._reaction.GetReactants()[x].GetFormula())
            self._reactantinfoboxes.append(QLineEdit())
            self._reactantinfoboxes[x*2+1].setText(str(self._reaction.GetReactants()[x].GetInitialMoles()))
            self._reactantform.addRow(QLabel(str(x + 1)+".\tFormula:"), self._reactantinfoboxes[x*2])
            self._reactantform.addRow(QLabel("\tInitial Moles:"), self._reactantinfoboxes[x*2+1])
        self._reactantbox.setLayout(self._reactantform)
        # Products section
        self._productbox = QGroupBox("Products", self)
        self._productform = QFormLayout()
        for x in range(Reaction.REACTING_SPECIES_LIMIT):
            self._productinfoboxes.append(QLineEdit())
            self._productinfoboxes[x*2].setText(self._reaction.GetProducts()[x].GetFormula())
            self._productinfoboxes.append(QLineEdit())
            self._productinfoboxes[x*2+1].setText(str(self._reaction.GetProducts()[x].GetInitialMoles()))
            self._productform.addRow(QLabel(str(x + 1)+".\tFormula:"), self._productinfoboxes[x*2])
            self._productform.addRow(QLabel("\tInitial Moles:"), self._productinfoboxes[x*2+1])
        self._productbox.setLayout(self._productform)
        # Catalyst section
        self._catalystbox = QGroupBox("Catalyst", self)
        self._catalystform = QFormLayout()
        self._catalystinfoboxes.append(QLineEdit())
        self._catalystinfoboxes.append(QLineEdit())
        self._catalystinfoboxes.append(QLineEdit())
        self._catalystinfoboxes[0].setText(self._reaction.GetCatalyst().GetFormula())
        self._catalystinfoboxes[1].setText(str(self._reaction.GetCatalyst().GetInitialMoles()))
        self._catalystinfoboxes[2].setText(str(self._reaction.GetCatalyst().GetEaChangePerMole()))
        self._catalystform.addRow(QLabel("Formula:"), self._catalystinfoboxes[0])
        self._catalystform.addRow(QLabel("Moles:"), self._catalystinfoboxes[1])
        self._catalystform.addRow(QLabel("Ea change (per mole):"), self._catalystinfoboxes[2])
        self._catalystbox.setLayout(self._catalystform)
        # Forward heat transfer
        self._heatbox = QGroupBox("Forward heat transfer", self)
        self._heatform = QFormLayout()
        self._endo = QRadioButton("Endothermic")
        self._exo = QRadioButton("Exothermic")
        if self._reaction.GetEndothermic():
            self._endo.setChecked(True)
        else:
            self._exo.setChecked(True)
        self._heatform.addRow(self._endo)
        self._heatform.addRow(self._exo)
        self._heatbox.setLayout(self._heatform)
        # Other conditions section. Includes Vessel volume; Temperature.
        self._otherbox = QGroupBox("Other conditions")
        self._otherform = QFormLayout()
        self._tempbox = QLineEdit()
        self._volbox = QLineEdit()
        self._tempbox.setText(str(self._reaction.GetTemperature()))
        self._volbox.setText(str(self._reaction.GetVolume()))
        self._otherform.addRow(QLabel("Vessel volume:"), self._volbox)
        self._otherform.addRow(QLabel("Temperature:"), self._tempbox)
        self._otherbox.setLayout(self._otherform)
        # OK and Cancel buttons
        self._okbtn = QPushButton("OK")
        self._okbtn.clicked.connect(self.ApplyChanges)
        self._cancelbtn = QPushButton("Cancel")

        self._rightbox = QGroupBox()
        self._rightbox.setFlat(False)
        self._rightform = QVBoxLayout()
        self._rightform.addWidget(self._catalystbox)
        self._rightform.addWidget(self._heatbox)
        self._rightform.addWidget(self._otherbox)
        self._rightbox.setLayout(self._rightform)

        # Layout of all those group boxes
        self._grid = QGridLayout()
        self._grid.addWidget(self._reactantbox, 0, 0)
        self._grid.addWidget(self._productbox, 0, 1)
        self._grid.addWidget(self._rightbox, 0, 2)
        self._grid.addWidget(self._okbtn, 1, 1)
        self._grid.addWidget(self._cancelbtn, 1, 2)
        self.setLayout(self._grid)

        if reaction is None:
            self._reaction = Reaction()
        else:
            self._reaction = reaction

        self._okbtn.clicked.connect(self.close)
        self._cancelbtn.clicked.connect(self.close)
        self.exec_()
Exemple #39
0
class GeneralSection(QWidget):
    def __init__(self):
        super(GeneralSection, self).__init__()
        container = QVBoxLayout(self)

        # Inicio
        group_on_start = QGroupBox(self.tr("Al Iniciar:"))
        box = QVBoxLayout(group_on_start)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_splash = QCheckBox(self.tr("Mostrar Splash"))
        self.check_splash.setChecked(
            settings.get_setting('general/show-splash'))
        box.addWidget(self.check_splash)
        self.check_on_start = QCheckBox(self.tr("Mostrar Página de Inicio"))
        show_start_page = settings.get_setting('general/show-start-page')
        self.check_on_start.setChecked(show_start_page)
        box.addWidget(self.check_on_start)
        self.check_load_files = QCheckBox(
            self.tr("Cargar archivos desde la "
                    "última sesión"))
        load_files = settings.get_setting('general/load-files')
        self.check_load_files.setChecked(load_files)
        box.addWidget(self.check_load_files)
        container.addWidget(group_on_start)

        # Al salir
        group_on_exit = QGroupBox(self.tr("Al Salir:"))
        box = QVBoxLayout(group_on_exit)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_on_exit = QCheckBox(self.tr("Confirmar Salida"))
        self.check_on_exit.setChecked(
            settings.get_setting('general/confirm-exit'))
        box.addWidget(self.check_on_exit)
        self.check_geometry = QCheckBox(
            self.tr("Guardar posición y tamaño de la ventana"))
        self.check_geometry.setChecked(
            settings.get_setting('window/store-size'))
        box.addWidget(self.check_geometry)
        container.addWidget(group_on_exit)

        # Notificaciones
        group_notifications = QGroupBox(self.tr("Notificaciones:"))
        box = QVBoxLayout(group_notifications)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_updates = QCheckBox(self.tr("Buscar Actualizaciones"))
        self.check_updates.setChecked(
            settings.get_setting('general/check-updates'))
        box.addWidget(self.check_updates)
        container.addWidget(group_notifications)

        # Sistema
        if settings.IS_LINUX:
            group_terminal = QGroupBox(self.tr("Sistema:"))
            box = QHBoxLayout(group_terminal)
            box.addWidget(QLabel(self.tr("Ejecutar programa con:")))
            self.line_terminal = QLineEdit()
            self.line_terminal.setAlignment(Qt.AlignLeft)
            self.line_terminal.setFixedWidth(300)
            self.line_terminal.setText(settings.get_setting('terminal'))
            box.addWidget(self.line_terminal, 1, Qt.AlignLeft)
            container.addWidget(group_terminal)

        # User Interface
        group_ui = QGroupBox(self.tr("Interfáz de Usuario:"))
        box = QGridLayout(group_ui)
        box.setContentsMargins(20, 5, 20, 5)
        box.addWidget(QLabel(self.tr("Tema:")), 0, 0)
        self.combo_theme = QComboBox()
        self.combo_theme.setFixedWidth(200)
        self._update_combo()
        index = self.combo_theme.findText(
            settings.get_setting('window/style-sheet'))
        self.combo_theme.setCurrentIndex(index)
        box.addWidget(self.combo_theme, 0, 1)

        self.combo_lang = QComboBox()
        self.combo_lang.setFixedWidth(200)
        box.addWidget(QLabel(self.tr("Idioma:")), 1, 0)
        box.addWidget(self.combo_lang, 1, 1)
        langs = os.listdir(os.path.join(paths.PATH, "extras", "i18n"))
        self.combo_lang.addItems(["Spanish"] + [lang[:-3] for lang in langs])
        lang = settings.get_setting('general/language')
        index = 0 if not lang else self.combo_lang.findText(lang)
        self.combo_lang.setCurrentIndex(index)
        container.addWidget(group_ui)
        box.setAlignment(Qt.AlignLeft)

        # Reestablecer
        group_restart = QGroupBox(self.tr("Reestablecer:"))
        box = QHBoxLayout(group_restart)
        box.setContentsMargins(20, 5, 20, 5)
        btn_restart = QPushButton(self.tr("Reiniciar configuraciones"))
        btn_restart.setObjectName("custom")
        box.addWidget(btn_restart)
        box.addStretch(1)
        container.addWidget(group_restart)

        container.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding))

        # Conexiones
        btn_restart.clicked.connect(self._restart_configurations)
        self.combo_theme.currentIndexChanged[int].connect(
            self._change_style_sheet)

        # Install
        EnvironmentConfiguration.install_widget(self.tr("General"), self)

    def _update_combo(self):
        self.combo_theme.addItems(['Default', 'Edark'])
        list_dir = os.listdir(paths.EDIS)
        list_styles = [
            i.split('.')[0] for i in list_dir
            if os.path.splitext(i)[-1] == '.qss'
        ]
        self.combo_theme.insertItems(2, list_styles)

    def _change_style_sheet(self, index):
        style_sheet = None
        path = None
        if index == 1:
            path = os.path.join(paths.PATH, "extras", "theme", "edark.qss")
        elif index != 0:
            style = self.combo_styles.currentText() + '.qss'
            path = os.path.join(paths.EDIS, style)
        if path is not None:
            with open(path, mode='r') as f:
                style_sheet = f.read()
        QApplication.instance().setStyleSheet(style_sheet)

    def _restart_configurations(self):
        flags = QMessageBox.Cancel
        flags |= QMessageBox.Yes

        result = QMessageBox.question(
            self, self.tr("Advertencia!"),
            self.tr("Está seguro que quiere "
                    "reestablecer las "
                    "configuraciones?"), flags)
        if result == QMessageBox.Cancel:
            return
        elif result == QMessageBox.Yes:
            QSettings(paths.CONFIGURACION, QSettings.IniFormat).clear()
            dialog_preferences = Edis.get_component("preferences")
            dialog_preferences.close()

    def save(self):

        settings.set_setting('general/show-splash',
                             self.check_splash.isChecked())
        show_start_page = self.check_on_start.isChecked()
        settings.set_setting('general/show-start-page', show_start_page)
        settings.set_setting('ventana/store-size',
                             self.check_geometry.isChecked())
        settings.set_setting('general/confirm-exit',
                             self.check_on_exit.isChecked())
        settings.set_setting('general/check-updates',
                             self.check_updates.isChecked())
        load_files = self.check_load_files.isChecked()
        settings.set_setting('general/load-files', load_files)
        lang = self.combo_lang.currentText()
        settings.set_setting('general/language', lang)
        if settings.IS_LINUX:
            settings.set_setting('terminal', self.line_terminal.text())
Exemple #40
0
class InfoDialog(QDialog):
    def __init__(self, parent):
        super(InfoDialog, self).__init__(parent)
        self.setWindowModality(Qt.WindowModal)

        layout = QVBoxLayout()
        layout.setSpacing(10)
        self.setLayout(layout)

        self.tab = QTabWidget()
        tab_general = QWidget()
        tab_toolcommands = QWidget()
        self.tab.addTab(tab_general, "")
        self.tab.addTab(tab_toolcommands, "")

        # general tab
        vbox = QVBoxLayout()
        vbox.setSpacing(4)
        tab_general.setLayout(vbox)

        hbox = QHBoxLayout()
        self.lilyname = QLineEdit()
        self.lilynameLabel = l = QLabel()
        l.setBuddy(self.lilyname)
        hbox.addWidget(l)
        hbox.addWidget(self.lilyname)
        vbox.addLayout(hbox)

        self.lilypond = widgets.urlrequester.UrlRequester()
        self.lilypond.setFileMode(QFileDialog.ExistingFile)
        self.lilypondLabel = l = QLabel()
        l.setBuddy(self.lilypond)
        vbox.addWidget(l)
        vbox.addWidget(self.lilypond)

        self.auto = QCheckBox()
        vbox.addWidget(self.auto)
        vbox.addStretch(1)

        # toolcommands tab
        grid = QGridLayout()
        grid.setSpacing(4)
        tab_toolcommands.setLayout(grid)

        self.ly_tool_widgets = {}
        row = 0
        for name, gui in self.toolnames():
            w = QLineEdit()
            l = QLabel()
            l.setBuddy(w)
            grid.addWidget(l, row, 0)
            grid.addWidget(w, row, 1)
            row += 1
            self.ly_tool_widgets[name] = (l, w)

        layout.addWidget(self.tab)
        layout.addWidget(widgets.Separator())
        b = self.buttons = QDialogButtonBox(self)
        layout.addWidget(b)

        b.setStandardButtons(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        b.accepted.connect(self.accept)
        b.rejected.connect(self.reject)
        userguide.addButton(b, "prefs_lilypond")
        app.translateUI(self)
        qutil.saveDialogSize(self,
                             "/preferences/lilypond/lilypondinfo/dialog/size")

    def toolnames(self):
        """Yield tuples (name, GUI name) for the sub tools we allow to be configured."""
        yield 'convert-ly', _("Convert-ly:")
        yield 'lilypond-book', _("LilyPond-book:")
        yield 'midi2ly', _("Midi2ly:")
        yield 'musicxml2ly', _("MusicXML2ly:")
        yield 'abc2ly', _("ABC2ly:")

    def translateUI(self):
        self.setWindowTitle(app.caption(_("LilyPond")))
        self.lilynameLabel.setText(_("Label:"))
        self.lilynameLabel.setToolTip(
            _("How this version of LilyPond will be displayed."))
        self.lilypondLabel.setText(_("LilyPond Command:"))
        self.lilypond.lineEdit.setToolTip(
            _("Name or full path of the LilyPond program."))
        self.auto.setText(_("Include in automatic version selection"))
        self.tab.setTabText(0, _("General"))
        self.tab.setTabText(1, _("Tool Commands"))
        for name, gui in self.toolnames():
            self.ly_tool_widgets[name][0].setText(gui)

    def loadInfo(self, info):
        """Takes over settings for the dialog from the LilyPondInfo object."""
        self.lilyname.setText(info.name)
        self.lilypond.setPath(info.command)
        self.auto.setChecked(info.auto)
        for name, gui in self.toolnames():
            self.ly_tool_widgets[name][1].setText(info.ly_tool(name))

    def newInfo(self):
        """Returns a new LilyPondInfo instance for our settings."""
        if sys.platform.startswith('darwin') and self.lilypond.path().endswith(
                '.app'):
            info = lilypondinfo.LilyPondInfo(
                self.lilypond.path() + '/Contents/Resources/bin/lilypond')
        else:
            info = lilypondinfo.LilyPondInfo(self.lilypond.path())
        if self.lilyname.text() and not self.lilyname.text().isspace():
            info.name = self.lilyname.text()
        info.auto = self.auto.isChecked()
        for name, gui in self.toolnames():
            info.set_ly_tool(name, self.ly_tool_widgets[name][1].text())
        return info
class DlgUserInputPanel(QDialog):
    def __init__(self, parent=None):
        QDialog.__init__(self, parent)
        self.resize(100, 70)
        self.setWindowTitle("User Input Panel")
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())
        self.setSizePolicy(sizePolicy)
        verticalLayoutDlg = QVBoxLayout(self)
        verticalLayoutDlg.setObjectName(("verticalLayoutDlg"))

        self.groupBox1 = GroupBox(self)
        self.groupBox1.Caption = ""
        verticalLayoutDlg.addWidget(self.groupBox1)

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

        self.spinBox = QLineEdit(self.frameBoxPanel)
        # self.spinBox.setMaximum(1000000000)
        # self.spinBox.setMinimum(-1000000000)
        self.spinBox.setText("0")
        self.spinBox.setMinimumSize(QSize(150, 0))

        self.hLayoutframeBoxPanel.addWidget(self.spinBox)

        self.groupBox1.Add = self.frameBoxPanel

    def getValue(self):
        return float(self.spinBox.text())

    def setValue(self, val):
        if isinstance(val, int) or isinstance(val, float):
            self.spinBox.setText(str(round(val, 4)))

    Value = property(getValue, setValue, None, None)
Exemple #42
0
    def __init__(self):
        super(GeneralSection, self).__init__()
        container = QVBoxLayout(self)

        # Inicio
        group_on_start = QGroupBox(self.tr("Al Iniciar:"))
        box = QVBoxLayout(group_on_start)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_splash = QCheckBox(self.tr("Mostrar Splash"))
        self.check_splash.setChecked(
            settings.get_setting('general/show-splash'))
        box.addWidget(self.check_splash)
        self.check_on_start = QCheckBox(self.tr("Mostrar Página de Inicio"))
        show_start_page = settings.get_setting('general/show-start-page')
        self.check_on_start.setChecked(show_start_page)
        box.addWidget(self.check_on_start)
        self.check_load_files = QCheckBox(
            self.tr("Cargar archivos desde la "
                    "última sesión"))
        load_files = settings.get_setting('general/load-files')
        self.check_load_files.setChecked(load_files)
        box.addWidget(self.check_load_files)
        container.addWidget(group_on_start)

        # Al salir
        group_on_exit = QGroupBox(self.tr("Al Salir:"))
        box = QVBoxLayout(group_on_exit)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_on_exit = QCheckBox(self.tr("Confirmar Salida"))
        self.check_on_exit.setChecked(
            settings.get_setting('general/confirm-exit'))
        box.addWidget(self.check_on_exit)
        self.check_geometry = QCheckBox(
            self.tr("Guardar posición y tamaño de la ventana"))
        self.check_geometry.setChecked(
            settings.get_setting('window/store-size'))
        box.addWidget(self.check_geometry)
        container.addWidget(group_on_exit)

        # Notificaciones
        group_notifications = QGroupBox(self.tr("Notificaciones:"))
        box = QVBoxLayout(group_notifications)
        box.setContentsMargins(20, 5, 20, 5)
        self.check_updates = QCheckBox(self.tr("Buscar Actualizaciones"))
        self.check_updates.setChecked(
            settings.get_setting('general/check-updates'))
        box.addWidget(self.check_updates)
        container.addWidget(group_notifications)

        # Sistema
        if settings.IS_LINUX:
            group_terminal = QGroupBox(self.tr("Sistema:"))
            box = QHBoxLayout(group_terminal)
            box.addWidget(QLabel(self.tr("Ejecutar programa con:")))
            self.line_terminal = QLineEdit()
            self.line_terminal.setAlignment(Qt.AlignLeft)
            self.line_terminal.setFixedWidth(300)
            self.line_terminal.setText(settings.get_setting('terminal'))
            box.addWidget(self.line_terminal, 1, Qt.AlignLeft)
            container.addWidget(group_terminal)

        # User Interface
        group_ui = QGroupBox(self.tr("Interfáz de Usuario:"))
        box = QGridLayout(group_ui)
        box.setContentsMargins(20, 5, 20, 5)
        box.addWidget(QLabel(self.tr("Tema:")), 0, 0)
        self.combo_theme = QComboBox()
        self.combo_theme.setFixedWidth(200)
        self._update_combo()
        index = self.combo_theme.findText(
            settings.get_setting('window/style-sheet'))
        self.combo_theme.setCurrentIndex(index)
        box.addWidget(self.combo_theme, 0, 1)

        self.combo_lang = QComboBox()
        self.combo_lang.setFixedWidth(200)
        box.addWidget(QLabel(self.tr("Idioma:")), 1, 0)
        box.addWidget(self.combo_lang, 1, 1)
        langs = os.listdir(os.path.join(paths.PATH, "extras", "i18n"))
        self.combo_lang.addItems(["Spanish"] + [lang[:-3] for lang in langs])
        lang = settings.get_setting('general/language')
        index = 0 if not lang else self.combo_lang.findText(lang)
        self.combo_lang.setCurrentIndex(index)
        container.addWidget(group_ui)
        box.setAlignment(Qt.AlignLeft)

        # Reestablecer
        group_restart = QGroupBox(self.tr("Reestablecer:"))
        box = QHBoxLayout(group_restart)
        box.setContentsMargins(20, 5, 20, 5)
        btn_restart = QPushButton(self.tr("Reiniciar configuraciones"))
        btn_restart.setObjectName("custom")
        box.addWidget(btn_restart)
        box.addStretch(1)
        container.addWidget(group_restart)

        container.addItem(
            QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Expanding))

        # Conexiones
        btn_restart.clicked.connect(self._restart_configurations)
        self.combo_theme.currentIndexChanged[int].connect(
            self._change_style_sheet)

        # Install
        EnvironmentConfiguration.install_widget(self.tr("General"), self)
Exemple #43
0
    def create_main_frame(self):
        self.main_frame = QWidget()
        # Looking at the main frame as two columns. On the left there is the
        # chart and the IF control. In the right column we'll have range
        # settings, mixer settings, and maybe other stuff that comes up?

        self.IFtextbox = QLineEdit()
        self.IFtextbox.setMinimumWidth(6)
        self.IFtextbox.setText(str(self.spurset.mixer.IF))
        # TODO link up the textbox so that it can also be input

        self.IFslider = QSlider(Qt.Horizontal)
        # TODO I'd really like some form of slider that doesn't actually limit
        # the user. Also, if IFtextbox could modify the IF, that'd be nice.
        self.IFslider.setRange(int(self.mx.IF * 0.1), (self.mx.IF * 5))
        self.IFslider.setValue(self.mx.IF)
        self.IFslider.setTracking(True)
        self.IFslider.setTickPosition(QSlider.TicksAbove)
        step = max(1, int(0.01 * self.mx.IF))
        self.IFslider.setSingleStep(step)
        self.IFslider.setPageStep(step * 10)
        self.IFcid = self.connect(self.IFslider, SIGNAL('valueChanged(int)'),
                                  self.IF_slide)

        IFbar = QHBoxLayout()
        IFbar.addWidget(QLabel('IF'))
        IFbar.addWidget(self.IFtextbox)
        IFbar.addWidget(self.IFslider)
        IFbar.addStretch()

        leftcol = QVBoxLayout()
        leftcol.addWidget(self.chart.plot)
        leftcol.addLayout(IFbar)

        # left column done. Now the right-hand side
        rangebox = QVBoxLayout()
        for (prop, name, f) in [(spurset.RFmin, 'RFmin', self.spurset.RFmin),
                                (spurset.RFmax, 'RFmax', self.spurset.RFmax),
                                (spurset.dspan, 'dspan', self.spurset.dspan)]:
            rangebox.addLayout(Fbar(self.spurset, prop, name, f, 0, 10000))
        autocb = QCheckBox('Auto')
        # Disable it, won't be implemented for release
        # but leave it there, to nag me into doing it.
        autocb.setDisabled(True)
        rangebox.addWidget(autocb)

        # a line to report the front-end filter's limits
        fefstat = QHBoxLayout()
        fefstat.addWidget(QLabel('Filter Range: '))
        fefrange = QLabel('%d - %d' % (self.fef.start, self.fef.stop))
        # TODO not sure about the lambda here. Feels like if I give it time,
        # I'll sort out a sensible overall connection scheme.
        self.fef.register(lambda o: fefrange.setText('%d - %d' % (
            self.fef.start, self.fef.stop)))
        fefstat.addWidget(fefrange)

        # mixer high/low-side injection picker
        mxbar = QHBoxLayout()
        mxbar.addWidget(QLabel('IF = '))
        mxtype = QComboBox()
        mxtype.addItem('LO - RF')
        mxtype.addItem('RF - LO')
        mxtype.addItem('RF + LO')
        # TODO this is ugly
        mxtype.setCurrentIndex([(-1, 1), (1, -1), (1, 1)].index(
            (self.mx.m, self.mx.n)))
        self.mxtypecid = self.connect(mxtype,
                                      SIGNAL('currentIndexChanged(int)'),
                                      self.mxtypecb)
        mxbar.addWidget(mxtype)

        # alright, the actual column proper in the layout
        vbar = QVBoxLayout()
        vbar.addLayout(rangebox)
        vbar.addLayout(fefstat)
        vbar.addLayout(mxbar)
        legend = self.chart.legend()
        vbar.addWidget(legend)
        # need to let the legend stretch so that everything fits in it
        vbar.setStretchFactor(legend, 1)
        vbar.addStretch()

        hbox = QHBoxLayout()
        hbox.addLayout(leftcol)
        hbox.addLayout(vbar)
        # make sure the legend doesn't stretch so far horizontally that the
        # chart suffers considerable loss of space.
        hbox.setStretchFactor(leftcol, 5)
        hbox.setStretchFactor(vbar, 1)

        self.main_frame.setLayout(hbox)
        self.setCentralWidget(self.main_frame)
Exemple #44
0
class goto(QWidget):
    def __init__(self, parent):
        QWidget.__init__(self)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.bdiff = parent
        
    def initShape(self):
        self.vbox = QVBoxLayout()
        self.createGoto()
        self.createOptions()

        fill = QWidget()
        self.vbox.addWidget(fill)
        #Go button
        self.gobutton = QPushButton("Go")
        self.connect(self.gobutton, SIGNAL('clicked()'), self.go)
        self.vbox.addWidget(self.gobutton)
    
        self.setLayout(self.vbox)

    def createGoto(self):
        self.offbox = QGroupBox("Go to location")
        self.offgrid = QGridLayout()

        #Format
        formatlabel = QLabel("Format :")
        self.format = QComboBox()
        self.format.addItem("Hexadecimal")
        self.format.addItem("Decimal")
        #Type: Offset, Page, Block
        typelabel = QLabel("Type :")
        self.type = QComboBox()
        self.type.addItem("Offset")
        self.type.addItem("Page")
        self.type.addItem("Block")
        #Place
        offsetlabel = QLabel("Place :")
        self.offset = QLineEdit()

        self.offgrid.addWidget(formatlabel, 0, 0)
        self.offgrid.addWidget(self.format, 0, 1)

        self.offgrid.addWidget(typelabel, 1, 0)
        self.offgrid.addWidget(self.type, 1, 1)

        self.offgrid.addWidget(offsetlabel, 2, 0)
        self.offgrid.addWidget(self.offset, 2, 1)

        self.offbox.setLayout(self.offgrid)
        self.vbox.addWidget(self.offbox)

    def createOptions(self):
        self.optbox = QGroupBox("Options")
        self.optgrid = QGridLayout()

        self.fromcursor = QCheckBox("From cursor")
        self.backwards = QCheckBox("Backwards")

        self.optgrid.addWidget(self.fromcursor, 0, 0)
        self.optgrid.addWidget(self.backwards, 1, 0)

        self.optbox.setLayout(self.optgrid)
        self.vbox.addWidget(self.optbox)

    def checkLocation(self, str, base, type):
        offset = QString(str)
        off = offset.toULongLong(base)
        if off[1]:
            if type == "Offset":
                if off[0] < self.bdiff.masterFileSize:
                    return off[0]
                else:
                    msg = MessageBoxError(self.bdiff, "Offset value too high")
                    msg.exec_()
                    return -1
            elif type == "Page":
                if off[0] < self.bdiff.pages:
                    return off[0]
                else:
                    msg = MessageBoxError(self.bdiff, "Page value too high")
                    msg.exec_()
                    return -1
            elif type == "Block":
                if off[0] < self.bdiff.blocks:
                    return off[0]
                else:
                    msg = MessageBoxError(self.bdiff, "Block value too high")
                    msg.exec_()
                    return -1
            else:
                return -1
        else:
            msg = MessageBoxError(self.bdiff, "Base conversion Error")
            msg.exec_()
            return -1
        return -1

    def getOffset(self, offset, fromcursor, back, type):
        #Init position
        if type == "Offset":
            if fromcursor:
                off = self.bdiff.currentOffset
                if back:
                    off -= offset
                else:
                    off += offset
            else:
                if back:
                    off = self.bdiff.masterFileSize - offset
                else:
                    off = offset
            return off
        elif type == "Page":
            if fromcursor:
                off = self.bdiff.currentPage
                if back:
                    off -= offset
                else:
                    off += offset
            else:
                if back:
                    off = self.bdiff.pages - offset
                else:
                    off = offset
            return (off * self.bdiff.pageSize)
        elif type == "Block":
            if fromcursor:
                off = self.bdiff.currentBlock
                if back:
                    off -= offset
                else:
                    off += offset
            else:
                if back:
                    off = self.bdiff.blocks - offset
                else:
                    off = offset
            return (off * (self.bdiff.pageSize * self.bdiff.pagesPerBlock))
        else:
            return -1
        return -1

    def go(self):
        format = self.format.currentText()
        off = self.offset.text()
        type = self.type.currentText()

        opt_fromcursor = self.fromcursor.isChecked()
        opt_backwards = self.backwards.isChecked()

        if format == "Hexadecimal":
            offset = self.checkLocation(str(off), 16, type)
        else:
            offset = self.checkLocation(str(off), 10, type)

        print offset

        if offset != -1:
            off = self.getOffset(offset, opt_fromcursor, opt_backwards, type)
            print off
            if off != -1:
                self.bdiff.readOffset(off)
            else:
                msg = MessageBoxError(self.bdiff, "Problem in offset conversion")
                msg.exec_()


    def keyPressEvent(self, kEvent):
        key = kEvent.key()
        if key == Qt.Key_Return or key == Qt.Key_Enter:
            self.go()
class ShortcutDialog(QDialog):
    """
    Dialog to set a shortcut for an action
    this class emit the follow signals:
        shortcutChanged(QKeySequence)
    """

    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.keys = 0
        #Keyword modifiers!
        self.keyword_modifiers = (Qt.Key_Control, Qt.Key_Meta, Qt.Key_Shift,
            Qt.Key_Alt, Qt.Key_Menu)
        #main layout
        main_vbox = QVBoxLayout(self)
        self.line_edit = QLineEdit()
        self.line_edit.setReadOnly(True)
        #layout for buttons
        buttons_layout = QHBoxLayout()
        ok_button = QPushButton(self.tr("Accept"))
        cancel_button = QPushButton(self.tr("Cancel"))
        #add widgets
        main_vbox.addWidget(self.line_edit)
        buttons_layout.addWidget(ok_button)
        buttons_layout.addWidget(cancel_button)
        main_vbox.addLayout(buttons_layout)
        self.line_edit.installEventFilter(self)
        #buttons signals
        self.connect(ok_button, SIGNAL("clicked()"), self.save_shortcut)
        self.connect(cancel_button, SIGNAL("clicked()"), self.close)

    def save_shortcut(self):
        self.hide()
        shortcut = QKeySequence(self.line_edit.text())
        self.emit(SIGNAL('shortcutChanged'), shortcut)

    def set_shortcut(self, txt):
        self.line_edit.setText(txt)

    def eventFilter(self, watched, event):
        if event.type() == QEvent.KeyPress:
            self.keyPressEvent(event)
            return True

        return False

    def keyPressEvent(self, evt):
        #modifier can not be used as shortcut
        if evt.key() in self.keyword_modifiers:
            return

        #save the key
        if evt.key() == Qt.Key_Backtab and evt.modifiers() & Qt.ShiftModifier:
            self.keys = Qt.Key_Tab
        else:
            self.keys = evt.key()

        if evt.modifiers() & Qt.ShiftModifier:
            self.keys += Qt.SHIFT
        if evt.modifiers() & Qt.ControlModifier:
            self.keys += Qt.CTRL
        if evt.modifiers() & Qt.AltModifier:
            self.keys += Qt.ALT
        if evt.modifiers() & Qt.MetaModifier:
            self.keys += Qt.META
        #set the keys
        self.set_shortcut(QKeySequence(self.keys).toString())
Exemple #46
0
 def createEditor(self, parent, option, index):
     lineedit = QLineEdit(parent)
     return lineedit
Exemple #47
0
class ManualInstallWidget(QWidget):

    def __init__(self, parent):
        super(ManualInstallWidget, self).__init__()
        self._parent = parent
        vbox = QVBoxLayout(self)
        form = QFormLayout()
        self._txtName = QLineEdit()
        self._txtName.setPlaceholderText('my_plugin')
        self._txtVersion = QLineEdit()
        self._txtVersion.setPlaceholderText('0.1')
        form.addRow(self.tr("Plugin Name:"), self._txtName)
        form.addRow(self.tr("Plugin Version:"), self._txtVersion)
        vbox.addLayout(form)
        hPath = QHBoxLayout()
        self._txtFilePath = QLineEdit()
        self._txtFilePath.setPlaceholderText(os.path.join(
            os.path.expanduser('~'), 'full', 'path', 'to', 'plugin.zip'))
        self._btnFilePath = QPushButton(QIcon(":img/open"), '')
        self.completer, self.dirs = QCompleter(self), QDirModel(self)
        self.dirs.setFilter(QDir.AllEntries | QDir.NoDotAndDotDot)
        self.completer.setModel(self.dirs)
        self._txtFilePath.setCompleter(self.completer)
        hPath.addWidget(QLabel(self.tr("Plugin File:")))
        hPath.addWidget(self._txtFilePath)
        hPath.addWidget(self._btnFilePath)
        vbox.addLayout(hPath)
        vbox.addSpacerItem(QSpacerItem(0, 1, QSizePolicy.Expanding,
            QSizePolicy.Expanding))

        hbox = QHBoxLayout()
        hbox.addSpacerItem(QSpacerItem(1, 0, QSizePolicy.Expanding))
        self._btnInstall = QPushButton(self.tr("Install"))
        hbox.addWidget(self._btnInstall)
        vbox.addLayout(hbox)

        #Signals
        self.connect(self._btnFilePath,
            SIGNAL("clicked()"), self._load_plugin_path)
        self.connect(self._btnInstall, SIGNAL("clicked()"),
            self.install_plugin)

    def _load_plugin_path(self):
        path = QFileDialog.getOpenFileName(self, self.tr("Select Plugin Path"))
        if path:
            self._txtFilePath.setText(path)

    def install_plugin(self):
        if self._txtFilePath.text() and self._txtName.text():
            plug = []
            plug.append(self._txtName.text())
            plug.append(self._txtVersion.text())
            plug.append('')
            plug.append('')
            plug.append('')
            plug.append(self._txtFilePath.text())
            self._parent.install_plugins_manually([plug])
Exemple #48
0
class MainWin(QMainWindow):
    def __init__(self, mx, spurs, fef, parent=None, plot_lib='mpl'):
        QMainWindow.__init__(self, parent)

        self.mx = mx
        self.spurset = spurs
        self.fef = fef

        if plot_lib == 'qwt':
            from chart.qwtchart import qwtchart as chart
        elif plot_lib == 'mpl':
            from chart.mplchart import mplchart as chart
        elif plot_lib == 'pg':
            from chart.pyqtgraphchart import pyqtgraphchart as chart
        else:
            raise NotImplementedError

        self.chart = chart(self.spurset, self.fef, self)
        self.create_menu_bar()
        self.create_main_frame()
        self.hookup()

    def hookup(self):
        # connect all the objects that are supposed to be watching each other
        # for changes and updates.
        self.mx.register(self.chart.draw_spurs)
        self.spurset.register(self.chart.draw_spurs)
        self.chart.picker_watch(self.fef)
        self.fef.register(self.chart.draw_fef)
        self.chart.draw_spurs(self.spurset)
        self.chart.draw_fef(self.fef)

    def IF_slide(self, i):
        """ callback method for the IF selection slider"""
        self.IFtextbox.setText(str(i))
        self.mx.IF = i

    def about(self):
        msg = '''
        A frequency-planing tool based on the method of spur distances.
        (A reference to the article will go here)
        For more info, view the README included with this program.

        Patrick Yeon, 2012'''
        QMessageBox.about(self, 'Spur Distance Chart', msg.strip())

    def mxtypecb(self, i):
        """ callback method for mixer configuration selection combobox"""
        self.mx.m, self.mx.n = [(-1, 1), (1, -1), (1, 1)][i]
        # trigger anything watching the mixer
        self.mx.update_watchers()

    def create_main_frame(self):
        self.main_frame = QWidget()
        # Looking at the main frame as two columns. On the left there is the
        # chart and the IF control. In the right column we'll have range
        # settings, mixer settings, and maybe other stuff that comes up?

        self.IFtextbox = QLineEdit()
        self.IFtextbox.setMinimumWidth(6)
        self.IFtextbox.setText(str(self.spurset.mixer.IF))
        # TODO link up the textbox so that it can also be input

        self.IFslider = QSlider(Qt.Horizontal)
        # TODO I'd really like some form of slider that doesn't actually limit
        # the user. Also, if IFtextbox could modify the IF, that'd be nice.
        self.IFslider.setRange(int(self.mx.IF * 0.1), (self.mx.IF * 5))
        self.IFslider.setValue(self.mx.IF)
        self.IFslider.setTracking(True)
        self.IFslider.setTickPosition(QSlider.TicksAbove)
        step = max(1, int(0.01 * self.mx.IF))
        self.IFslider.setSingleStep(step)
        self.IFslider.setPageStep(step * 10)
        self.IFcid = self.connect(self.IFslider, SIGNAL('valueChanged(int)'),
                                  self.IF_slide)

        IFbar = QHBoxLayout()
        IFbar.addWidget(QLabel('IF'))
        IFbar.addWidget(self.IFtextbox)
        IFbar.addWidget(self.IFslider)
        IFbar.addStretch()

        leftcol = QVBoxLayout()
        leftcol.addWidget(self.chart.plot)
        leftcol.addLayout(IFbar)

        # left column done. Now the right-hand side
        rangebox = QVBoxLayout()
        for (prop, name, f) in [(spurset.RFmin, 'RFmin', self.spurset.RFmin),
                                (spurset.RFmax, 'RFmax', self.spurset.RFmax),
                                (spurset.dspan, 'dspan', self.spurset.dspan)]:
            rangebox.addLayout(Fbar(self.spurset, prop, name, f, 0, 10000))
        autocb = QCheckBox('Auto')
        # Disable it, won't be implemented for release
        # but leave it there, to nag me into doing it.
        autocb.setDisabled(True)
        rangebox.addWidget(autocb)

        # a line to report the front-end filter's limits
        fefstat = QHBoxLayout()
        fefstat.addWidget(QLabel('Filter Range: '))
        fefrange = QLabel('%d - %d' % (self.fef.start, self.fef.stop))
        # TODO not sure about the lambda here. Feels like if I give it time,
        # I'll sort out a sensible overall connection scheme.
        self.fef.register(lambda o: fefrange.setText('%d - %d' % (
            self.fef.start, self.fef.stop)))
        fefstat.addWidget(fefrange)

        # mixer high/low-side injection picker
        mxbar = QHBoxLayout()
        mxbar.addWidget(QLabel('IF = '))
        mxtype = QComboBox()
        mxtype.addItem('LO - RF')
        mxtype.addItem('RF - LO')
        mxtype.addItem('RF + LO')
        # TODO this is ugly
        mxtype.setCurrentIndex([(-1, 1), (1, -1), (1, 1)].index(
            (self.mx.m, self.mx.n)))
        self.mxtypecid = self.connect(mxtype,
                                      SIGNAL('currentIndexChanged(int)'),
                                      self.mxtypecb)
        mxbar.addWidget(mxtype)

        # alright, the actual column proper in the layout
        vbar = QVBoxLayout()
        vbar.addLayout(rangebox)
        vbar.addLayout(fefstat)
        vbar.addLayout(mxbar)
        legend = self.chart.legend()
        vbar.addWidget(legend)
        # need to let the legend stretch so that everything fits in it
        vbar.setStretchFactor(legend, 1)
        vbar.addStretch()

        hbox = QHBoxLayout()
        hbox.addLayout(leftcol)
        hbox.addLayout(vbar)
        # make sure the legend doesn't stretch so far horizontally that the
        # chart suffers considerable loss of space.
        hbox.setStretchFactor(leftcol, 5)
        hbox.setStretchFactor(vbar, 1)

        self.main_frame.setLayout(hbox)
        self.setCentralWidget(self.main_frame)

    def create_menu_bar(self):
        filemenu = self.menuBar().addMenu('&File')
        close = QAction('&Quit', self)
        close.setShortcut('Ctrl+W')
        self.connect(close, SIGNAL('triggered()'), self.close)
        filemenu.addAction(close)

        helpmenu = self.menuBar().addMenu('&Help')
        about = QAction('&About', self)
        about.setShortcut('F1')
        self.connect(about, SIGNAL('triggered()'), self.about)
        helpmenu.addAction(about)
Exemple #49
0
class CANFilterBox(QWidget):
    def __init__(self, withChanged, parent):
        QWidget.__init__(self, parent)
        self.canMonitor=parent
        self.filter=False
        self.filterValue=""
        self.filterRingIds=False
        self.withChanged=withChanged
        self.filterChanged=False
        
    def addFilterBox(self, layout):
        hbox = QHBoxLayout()
        layout.addLayout(hbox)
#        hbox.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
                
        self.filterButton=QCheckBox("Filter", self.canMonitor)
        self.filterButton.setToolTip('Enable filter')
        self.filterButton.resize(self.filterButton.sizeHint())
        self.filterButton.clicked.connect(self._enableFilter)
        hbox.addWidget(self.filterButton)
        
        self.filterEdit=QLineEdit(self.canMonitor)
        self.filterEdit.setToolTip('Id Filter')
        self.filterEdit.setDisabled(self.filter==False)
        self.filterEdit.returnPressed.connect(self._applyFilter)
        hbox.addWidget(self.filterEdit)
        
        self.applyFilterButton = QPushButton('Apply', self.canMonitor)
        self.applyFilterButton.setToolTip('Use Id filter')
        self.applyFilterButton.resize(self.applyFilterButton.sizeHint())
        self.applyFilterButton.clicked.connect(self._applyFilter)
        self.applyFilterButton.setDisabled(self.filter==False)
        hbox.addWidget(self.applyFilterButton)
        
        self.filterKnown=QRadioButton("Known", self.canMonitor)
        self.filterKnown.clicked.connect(self._applyFilter)
        self.filterKnown.setDisabled(self.filter==False)
        hbox.addWidget(self.filterKnown)
        
        self.filterUnknown=QRadioButton("Unknown", self.canMonitor)
        self.filterUnknown.clicked.connect(self._applyFilter)
        self.filterUnknown.setDisabled(self.filter==False)
        hbox.addWidget(self.filterUnknown)
        
        self.filterAll=QRadioButton("All", self.canMonitor)
        self.filterAll.clicked.connect(self._applyFilter)
        self.filterAll.setDisabled(self.filter==False)
        self.filterAll.setChecked(True)
        hbox.addWidget(self.filterAll)

        self.filterRingIdsButton=QCheckBox("Ring Ids", self.canMonitor)
        self.filterRingIdsButton.resize(self.filterRingIdsButton.sizeHint())
        self.filterRingIdsButton.clicked.connect(self._enableFilterRingIds)
        self.filterRingIdsButton.setDisabled(self.filter==False)
        self.filterRingIdsButton.setChecked(self.filterRingIds)
        hbox.addWidget(self.filterRingIdsButton)
        
        if self.withChanged==True:
            self.filterChangedButton=QCheckBox("Changed", self.canMonitor)
            self.filterChangedButton.resize(self.filterChangedButton.sizeHint())
            self.filterChangedButton.clicked.connect(self._enableFilterChanged)
            self.filterChangedButton.setDisabled(self.filter==False)
            self.filterChangedButton.setChecked(self.filterChanged)
            hbox.addWidget(self.filterChangedButton)
        
    def matchFilter(self, canId, line, lineInit):
        if self.filter==True:
            idMatch=self.matchIdFilter(canId)
            if idMatch==False:
                return False
            
            changedMatched=self.matchChangedFilter(line, lineInit)
            if changedMatched==False:
                return False
            
            if self.filterAll.isChecked():
                return idMatch
            
            isKnownId=self.canMonitor.canIdIsInKnownList(canId)
            if self.filterKnown.isChecked():
                return isKnownId==False
            if self.filterUnknown.isChecked():
                return isKnownId==True
        return True
    
    def matchIdFilter(self, canId):     
        if self.filter==True:
            # filter ring ids
            if self.filterRingIds==True:
                if canId>=0x400 and canId <=0x43F:
                    return False
              
            if len(self.filterValue)!=0:
                if not fnmatch.fnmatch(hex(canId), self.filterValue):
                    return False
        
        return True
    
    def matchChangedFilter(self, line, lineInit):
        if self.filter==True:
            if self.filterChanged==True:
                if line!=lineInit:
                    return True
                return False
        return True
    
    @pyqtSlot()
    def _applyFilter(self):
        if self.filter==True:
            self.filterValue=self.filterEdit.text()
        else:
            self.filterValue=""
          
                  
    @pyqtSlot()
    def _enableFilter(self):
        self.filter=self.filterButton.isChecked()
        self.filterEdit.setDisabled(self.filter==False)
        self.applyFilterButton.setDisabled(self.filter==False)
        self.filterAll.setDisabled(self.filter==False)
        self.filterKnown.setDisabled(self.filter==False)
        self.filterUnknown.setDisabled(self.filter==False)
        self.filterRingIdsButton.setDisabled(self.filter==False)
        if self.withChanged==True:
            self.filterChangedButton.setDisabled(self.filter==False)
    
    @pyqtSlot()
    def _enableFilterRingIds(self):
        self.filterRingIds=self.filterRingIdsButton.isChecked()

    @pyqtSlot()
    def _enableFilterChanged(self):
        self.filterChanged=self.filterChangedButton.isChecked()
Exemple #50
0
 def __init__(self, parent):
     QLineEdit.__init__(self, parent)
     self._parent = parent
     self.counter = ui_tools.LineEditCount(self)
Exemple #51
0
class DHttpReplay(QtHelper.EnhancedQDialog, Logger.ClassLogger):
    """
    Http replay dialog
    """
    def __init__(self, parent=None, offlineMode=False):
        """
        Constructor

        @param parent: 
        @type parent:
        """
        super(DHttpReplay, self).__init__(parent)
        self.offlineMode = offlineMode
        self.defaultIp = "127.0.0.1"
        self.defaultPort = "80"
        self.newTest = ''
        self.newTestExec = ''
        self.newInputs = []
        self.requests = []
        self.responses = []
        self.defaultTemplates = DefaultTemplates.Templates()
        self.testType = None

        self.createDialog()
        self.createConnections()
        self.createActions()
        self.createToolbar()

    def createActions(self):
        """
        Create qt actions
        """
        self.openAction = QtHelper.createAction(self,
                                                "&Open",
                                                self.importTrace,
                                                icon=QIcon(":/folder_add.png"),
                                                tip='Open network trace.')
        self.exportTUAction = QtHelper.createAction(
            self,
            "&Test Unit",
            self.exportToTU,
            icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE),
            tip='Export to Test Unit')
        self.exportTSAction = QtHelper.createAction(
            self,
            "&Test Suite",
            self.exportToTS,
            icon=QIcon(":/%s.png" % WWorkspace.TestSuite.TYPE),
            tip='Export to Test Suite')
        self.cancelAction = QtHelper.createAction(self,
                                                  "&Cancel",
                                                  self.reject,
                                                  tip='Cancel')

        menu = QMenu(self)
        menu.addAction(self.exportTUAction)
        menu.addAction(self.exportTSAction)

        self.exportToAction = QtHelper.createAction(
            self,
            "&Export to",
            self.exportToTU,
            icon=QIcon(":/%s.png" % WWorkspace.TestUnit.TYPE),
            tip='Export to tests')
        self.exportToAction.setMenu(menu)
        self.exportToAction.setEnabled(False)

    def createDialog(self):
        """
        Create dialog
        """

        self.dockToolbar = QToolBar(self)
        self.dockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.setWindowTitle(WINDOW_TITLE)
        self.resize(500, 400)

        self.ipEdit = QLineEdit(self.defaultIp)
        ipRegExpVal = QRegExpValidator(self)
        ipRegExp = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
        ipRegExpVal.setRegExp(ipRegExp)
        self.ipEdit.setValidator(ipRegExpVal)

        self.portEdit = QLineEdit(self.defaultPort)
        self.portEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        validatorPort = QIntValidator(self)
        self.portEdit.setValidator(validatorPort)

        self.progressBar = QProgressBar(self)
        self.progressBar.setMaximum(100)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setAlignment(Qt.AlignCenter)
        self.progressBar.setObjectName("progressBar")

        self.guiSikuliGroupBox = QGroupBox("")
        self.guiSikuliGroupBox.setFlat(True)
        self.automaticAdp = QRadioButton("Automatic")
        self.automaticAdp.setChecked(True)
        self.defaultAdp = QRadioButton("Default")
        self.genericAdp = QRadioButton("Generic")
        vbox = QHBoxLayout()
        vbox.addWidget(self.automaticAdp)
        vbox.addWidget(self.defaultAdp)
        vbox.addWidget(self.genericAdp)
        vbox.addStretch(1)
        self.guiSikuliGroupBox.setLayout(vbox)

        layout = QVBoxLayout()
        layout.addWidget(self.dockToolbar)
        layout.addSpacing(12)
        paramLayout = QGridLayout()
        paramLayout.addWidget(QLabel("Destination IP:"), 0, 0, Qt.AlignRight)
        paramLayout.addWidget(self.ipEdit, 0, 1)
        paramLayout.addWidget(QLabel("Destination Port:"), 1, 0, Qt.AlignRight)
        paramLayout.addWidget(self.portEdit, 1, 1)
        paramLayout.addWidget(QLabel(self.tr("Gui adapter selector:")), 2, 0,
                              Qt.AlignRight)
        paramLayout.addWidget(self.guiSikuliGroupBox, 2, 1)
        layout.addLayout(paramLayout)

        self.logsEdit = QTextEdit()
        self.logsEdit.setReadOnly(True)
        self.logsEdit.setTextInteractionFlags(Qt.NoTextInteraction)

        layout.addSpacing(12)
        layout.addWidget(self.logsEdit)
        layout.addSpacing(12)
        layout.addWidget(self.progressBar)

        self.setLayout(layout)

    def createToolbar(self):
        """
        Create toolbar
        """
        self.dockToolbar.setObjectName("File toolbar")
        self.dockToolbar.addAction(self.openAction)
        self.dockToolbar.addSeparator()
        self.dockToolbar.addAction(self.exportToAction)
        self.dockToolbar.addSeparator()
        self.dockToolbar.setIconSize(QSize(16, 16))

    def createConnections(self):
        """
        Create qt connections
        """
        pass

    def autoScrollOnTextEdit(self):
        """
        Automatic scroll on text edit
        """
        cursor = self.logsEdit.textCursor()
        cursor.movePosition(QTextCursor.End)
        self.logsEdit.setTextCursor(cursor)

    def strip_html(self, txt):
        """
        Strip html
        """
        if "<" in txt:
            txt = txt.replace('<', '&lt;')
        if ">" in txt:
            txt = txt.replace('>', '&gt;')
        return txt

    def addLogSuccess(self, txt):
        """
        Add log success in the text edit
        """
        self.logsEdit.insertHtml(
            "<span style='color:darkgreen'>%s</span><br />" %
            unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLogWarning(self, txt):
        """
        Add log warning in the text edit
        """
        self.logsEdit.insertHtml(
            "<span style='color:darkorange'>%s</span><br />" %
            unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLogError(self, txt):
        """
        Add log error in the text edit
        """
        self.logsEdit.insertHtml("<span style='color:red'>%s</span><br />" %
                                 unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def addLog(self, txt):
        """
        Append log to the logsEdit widget
        """
        self.logsEdit.insertHtml("%s<br />" % unicode(self.strip_html(txt)))
        self.autoScrollOnTextEdit()

    def importTrace(self):
        """
        Import network trace
        """
        self.logsEdit.clear()
        self.testType = None

        if not self.offlineMode:
            if not RCI.instance().isAuthenticated():
                self.addLogWarning(
                    txt="<< Connect to the test center in first!")
                QMessageBox.warning(self, "Import",
                                    "Connect to the test center in first!")
                return

        self.exportToAction.setEnabled(False)
        self.newTest = ''
        self.progressBar.setMaximum(100)
        self.progressBar.setValue(0)

        if sys.version_info > (3, ):
            fileName = QFileDialog.getOpenFileName(
                self, self.tr("Open File"), "",
                "Network dump (*.cap;*.pcap;*.pcapng)")
        else:
            fileName = QFileDialog.getOpenFileName(self, self.tr("Open File"),
                                                   "", "Network dump (*.cap)")
        # new in v18 to support qt5
        if QtHelper.IS_QT5:
            _fileName, _type = fileName
        else:
            _fileName = fileName
        # end of new

        if not _fileName:
            return

        if sys.version_info < (3, ):
            extension = str(_fileName).rsplit(".", 1)[1]
            if not (extension == "cap"):
                self.addLogError(txt="<< File not supported %s" % _fileName)
                QMessageBox.critical(self, "Open", "File not supported")
                return

        _fileName = str(_fileName)
        capName = _fileName.rsplit("/", 1)[1]

        self.addLogSuccess(txt=">> Reading the file %s" % _fileName)
        if sys.version_info > (3, ):
            self.readFileV2(fileName=_fileName)
        else:
            self.readFile(fileName=_fileName)

    def exportToTS(self):
        """
        Export to test suite
        """
        self.testType = TS
        self.exportToTest(TS=True, TU=False)

    def exportToTU(self):
        """
        Export to test unit
        """
        self.testType = TU
        self.exportToTest(TS=False, TU=True)

    def searchHTTP(self):
        """
        Search HTTP module in assistant
        """
        # modules accessor
        ret = "SutAdapters"
        if self.automaticAdp.isChecked():
            isGeneric = WWorkspace.Helper.instance().isGuiGeneric(name="GUI")
            if isGeneric:
                ret = "SutAdapters.Generic"
        elif self.defaultAdp.isChecked():
            return ret
        elif self.genericAdp.isChecked():
            ret = "SutAdapters.Generic"
        else:
            pass
        return ret

    def exportToTest(self, TS=True, TU=False):
        """
        Export to test
        """
        if not RCI.instance().isAuthenticated():
            self.addLogWarning(txt="<< Connect to the test center in first!")
            QMessageBox.warning(self, "Import",
                                "Connect to the test center in first!")
            return

        if TS:
            self.newTest = self.defaultTemplates.getTestDefinitionAuto()
            self.newTestExec = self.defaultTemplates.getTestExecutionAuto()
        if TU:
            self.newTest = self.defaultTemplates.getTestUnitDefinitionAuto()

        destIp = str(self.ipEdit.text())
        destPort = str(self.portEdit.text())

        self.newInputs = []
        self.newInputs.append({
            'type': 'self-ip',
            'name': 'BIND_IP',
            'description': '',
            'value': '0.0.0.0',
            'color': ''
        })
        self.newInputs.append({
            'type': 'int',
            'name': 'BIND_PORT',
            'description': '',
            'value': '0',
            'color': ''
        })
        self.newInputs.append({
            'type': 'str',
            'name': 'DEST_IP',
            'description': '',
            'value': '%s' % destIp,
            'color': ''
        })
        self.newInputs.append({
            'type': 'int',
            'name': 'DEST_PORT',
            'description': '',
            'value': '%s' % destPort,
            'color': ''
        })
        self.newInputs.append({
            'type': 'bool',
            'name': 'DEBUG',
            'description': '',
            'value': 'False',
            'color': ''
        })
        self.newInputs.append({
            'type': 'float',
            'name': 'TIMEOUT',
            'description': '',
            'value': '5.0',
            'color': ''
        })

        adps = """self.ADP_HTTP = %s.HTTP.Client(parent=self, bindIp=input('BIND_IP'), bindPort=input('BIND_PORT'), destinationIp=input('DEST_IP'), destinationPort=input('DEST_PORT'), debug=input('DEBUG'))""" % self.searchHTTP(
        )

        # prepare steps
        steps = []
        j = 0
        for i in xrange(len(self.requests)):
            j = i + 1
            if sys.version_info > (3, ):  # python3 support
                (source, dest, source_port, dest_port, buf_req,
                 reqDecoded) = self.requests[i]
                http_method = str(reqDecoded['method'], 'utf8')
                http_status = 'no'
                http_reason = ''
            else:
                http_method = self.requests[i]['tcp-object'].method
                http_status = 'no'
                http_reason = ''
            try:
                if sys.version_info > (3, ):  # python3 support
                    (sourceRsp, destRsp, sourcePortRsp, destPortRsp, bufReqRsp,
                     reqDecodedRsp) = self.responses[i]
                    http_status = str(reqDecodedRsp['code'])
                    http_reason = str(reqDecodedRsp['phrase'], 'utf8')
                else:
                    http_status = self.responses[i]['tcp-object'].status
                    http_reason = self.responses[i]['tcp-object'].reason
            except Exception as e:
                print(e)
            steps.append(
                'self.step%s = self.addStep(expected="%s %s response", description="send %s request", summary="send %s request")'
                % (j, http_status, http_reason, http_method, http_method))

        tests = []
        for i in xrange(len(self.requests)):
            j = i + 1
            if sys.version_info > (3, ):  # python3 support
                (source, dest, source_port, dest_port, buf_req,
                 reqDecoded) = self.requests[i]
            tests.append("# request %s" % j)
            tests.append('self.step%s.start()' % j)

            if sys.version_info > (3, ):  # python3 support
                lines_req = buf_req.splitlines()
            else:
                lines_req = self.requests[i]['tcp-data'].splitlines()

            if sys.version_info > (3, ):  # python3 support
                tests.append('rawHttp = [%s]' %
                             lines_req[0].replace(b'"', b'\\"'))
            else:
                tests.append('rawHttp = ["%s"]' %
                             lines_req[0].replace(b'"', b'\\"'))
            for lreq in lines_req[1:]:
                if sys.version_info > (3, ):  # python3 support
                    tests.append('rawHttp.append(%s)' %
                                 lreq.replace(b'"', b'\\"'))
                else:
                    tests.append('rawHttp.append("%s")' %
                                 lreq.replace(b'"', b'\\"'))

            tests.append('')
            tests.append(
                'req_tpl = self.ADP_HTTP.constructTemplateRequest(rawHttp=rawHttp)'
            )
            tests.append('req = self.ADP_HTTP.sendRequest(tpl=req_tpl)')

            try:
                tests.append('')
                if sys.version_info > (3, ):  # python3 support
                    (sourceRsp, destRsp, sourcePortRsp, destPortRsp, bufReqRsp,
                     reqDecodedRsp) = self.responses[i]
                    lines_res = bufReqRsp.splitlines()
                else:
                    lines_res = self.responses[i]['tcp-data'].splitlines()
                if sys.version_info > (3, ):  # python3 support
                    tests.append('rawHttpRsp = [%s]' %
                                 lines_res[0].replace(b"'", b"\\'"))
                else:
                    tests.append('rawHttpRsp = ["%s"]' %
                                 lines_res[0].replace(b'"', b'\\"'))
                for lres in lines_res[1:]:
                    if sys.version_info > (3, ):  # python3 support
                        tests.append('rawHttpRsp.append(%s)' %
                                     lres.replace(b"'", b"\\'"))
                    else:
                        tests.append('rawHttpRsp.append("%s")' %
                                     lres.replace(b'"', b'\\"'))
            except Exception as e:
                self.error("unable to append response: %s" % e)
            tests.append(
                'rsp_tpl = self.ADP_HTTP.constructTemplateResponse(rawHttp=rawHttpRsp)'
            )
            tests.append(
                "rsp = self.ADP_HTTP.hasReceivedResponse(expected=rsp_tpl, timeout=input('TIMEOUT'))"
            )
            tests.append('if rsp is None:')
            tests.append(
                '\tself.step%s.setFailed(actual="incorrect response")' % j)
            tests.append('else:')
            tests.append('\tself.step%s.setPassed(actual="ok")' % j)
            tests.append('')
        if TS:
            init = """self.ADP_HTTP.connect()
		connected = self.ADP_HTTP.isConnected( timeout=input('TIMEOUT') )
		if not connected:
			self.abort( 'unable to connect to the tcp port %s'  )
""" % str(self.portEdit.text())

        if TU:
            init = """self.ADP_HTTP.connect()
	connected = self.ADP_HTTP.isConnected( timeout=input('TIMEOUT') )
	if not connected:
		self.abort( 'unable to connect to the tcp port %s'  )
""" % str(self.portEdit.text())

        if TS:
            cleanup = """self.ADP_HTTP.disconnect()
		disconnected = self.ADP_HTTP.isDisconnected( timeout=input('TIMEOUT') )
		if not disconnected:
			self.error( 'unable to disconnect from the tcp port %s' )
""" % str(self.portEdit.text())

        if TU:
            cleanup = """self.ADP_HTTP.disconnect()
	disconnected = self.ADP_HTTP.isDisconnected( timeout=input('TIMEOUT') )
	if not disconnected:
		self.error( 'unable to disconnect from the tcp port %s' )
""" % str(self.portEdit.text())

        self.newTest = self.newTest.replace(
            "<<PURPOSE>>", 'self.setPurpose(purpose="Replay HTTP")')
        self.newTest = self.newTest.replace("<<ADPS>>", adps)
        if TS:
            self.newTest = self.newTest.replace("<<STEPS>>",
                                                '\n\t\t'.join(steps))
        if TU:
            self.newTest = self.newTest.replace("<<STEPS>>",
                                                '\n\t'.join(steps))
        self.newTest = self.newTest.replace("<<INIT>>", init)
        self.newTest = self.newTest.replace("<<CLEANUP>>", cleanup)
        if TS:
            self.newTest = self.newTest.replace("<<TESTS>>",
                                                '\n\t\t'.join(tests))
        if TU:
            self.newTest = self.newTest.replace("<<TESTS>>",
                                                '\n\t'.join(tests))

        self.accept()

    def decodeHttpRequest(self, data):
        """
        Decode http request
        Content chunked not yet implemented
        """
        http = {"type": "request"}
        lines = data.splitlines()
        try:
            request_line = lines[0]
        except Exception:
            self.error("unable to decode http request: %s" % lines)
            return None

        try:
            http["method"] = request_line.split(b" ", 2)[0]
            http["uri"] = request_line.split(b" ", 2)[1]
            http["version"] = request_line.split(b" ", )[2]
        except Exception:
            self.error(
                "unable to decode status code in the http response: %s" %
                request_line)
            return None

        http["body"] = data.split(b"\r\n\r\n")[1]

        headers = []
        contentLenght = 0
        contentChunked = False
        for hdr in data.split(b"\r\n\r\n")[0].splitlines()[1:]:
            if len(hdr):
                k, v = hdr.split(b":", 1)
                if k.lower() == b"content-length":
                    contentLenght = int(v)
                if k.lower() == b"transfer-encoding":
                    if v.lowert() == b"chunked":
                        contentChunked = True

                headers.append(hdr)

        http["headers"] = headers

        if len(http["body"]) != contentLenght:
            return None  # need more data
        return http

    def decodeHttpResponse(self, data):
        """
        Decode http response without body
        """
        http = {"type": "response"}
        lines = data.splitlines()
        try:
            status_line = lines[0]
        except Exception:
            self.error("unable to decode http response: %s" % lines)
            return None

        try:
            http["code"] = int(status_line.split(b" ")[1])
            http["phrase"] = status_line.split(b" ", 2)[2]
        except Exception:
            self.error(
                "unable to decode status code in the http response: %s" %
                status_line)
            return None

        http["headers"] = lines[1:]
        return http

    def readFileV2(self, fileName):
        """
        Read pcap file 
        Support pcap-ng too
        """
        fd = open(fileName, 'rb')
        fileFormat, fileHead = PcapParse.extractFormat(fd)
        if fileFormat == PcapParse.FileFormat.PCAP:
            self.trace("pcap file detected")
            pcapFile = PcapReader.PcapFile(fd, fileHead).read_packet
            self.readFilePacket(pcapFile=pcapFile)
        elif fileFormat == PcapParse.FileFormat.PCAP_NG:
            self.trace("pcap-png file detected")
            pcapFile = PcapngReader.PcapngFile(fd, fileHead).read_packet
            self.readFilePacket(pcapFile=pcapFile)
        else:
            self.addLogError(txt="<< Error to open the network trace")
            self.error('unable to open the network trace: file format = %s' %
                       fileFormat)
            QMessageBox.critical(self, "Import", "File not supported")

    def __readRequest(self, buffer, data, request, output):
        """
        Read request
        """
        buffer += data
        if b'\r\n\r\n' in data:
            reqDecoded = self.decodeHttpRequest(data=buffer)
            if reqDecoded is not None:
                output.append(request + (reqDecoded, ))
                buffer = b''
            else:
                print("need more data: decode request failed")
        else:
            print("need more data, no body separator detected on request")

    def readFilePacket(self, pcapFile):
        """
        Read file packet by packet
        """
        ip_expected = str(self.ipEdit.text())
        port_expected = int(self.portEdit.text())

        # read packet)
        packets = pcapFile()
        ethernetPackets = list(packets)
        self.addLogSuccess(txt="<< Number of packets detected: %s " %
                           len(ethernetPackets))

        # extract tcp packet according to the expected ip and port
        tcpPacketsSent = []
        tcpPacketsRecv = []
        i = 1
        self.progressBar.setMaximum(len(ethernetPackets))
        self.progressBar.setValue(0)
        for pkt in ethernetPackets:
            self.progressBar.setValue(i)
            i += 1
            pktDecoded = PcapParse.decodePacket(pkt, getTcp=True, getUdp=False)
            if pktDecoded is not None:
                (source, dest, source_port, dest_port, data) = pktDecoded
                # skip when no data exists
                if dest == ip_expected and int(dest_port) == int(
                        port_expected) and len(data) > 0:
                    tcpPacketsSent.append(pktDecoded)
                if source == ip_expected and int(source_port) == int(
                        port_expected) and len(data) > 0:
                    tcpPacketsRecv.append(pktDecoded)
        self.addLogSuccess(txt="<< Number of TCP packets sent: %s " %
                           len(tcpPacketsSent))
        self.addLogSuccess(txt="<< Number of TCP packets received: %s " %
                           len(tcpPacketsRecv))

        # decode https requests
        self.requests = []
        buf_req = b''
        i = 1
        self.progressBar.setMaximum(len(tcpPacketsSent))
        self.progressBar.setValue(0)
        # decode the complete packet
        for req in tcpPacketsSent:
            self.progressBar.setValue(i)
            i += 1
            (source, dest, source_port, dest_port, data) = req
            if buf_req:
                buf_req += data
                if b'\r\n\r\n' in data:
                    reqDecoded = self.decodeHttpRequest(data=buf_req)
                    if reqDecoded is not None:
                        self.requests.append((source, dest, source_port,
                                              dest_port, buf_req, reqDecoded))
                        buf_req = b''
            else:
                if isRequest(data):
                    buf_req += data
                    if b'\r\n\r\n' in data:
                        reqDecoded = self.decodeHttpRequest(data=buf_req)
                        if reqDecoded is not None:
                            self.requests.append(
                                (source, dest, source_port, dest_port, buf_req,
                                 reqDecoded))
                            buf_req = b''

        self.addLogSuccess(txt="<< Number of HTTP requests extracted: %s " %
                           len(self.requests))

        # decode https response
        self.responses = []
        buf_rsp = b''
        i = 1
        self.progressBar.setMaximum(len(tcpPacketsRecv))
        self.progressBar.setValue(0)
        # decode just headers for response
        for req in tcpPacketsRecv:
            self.progressBar.setValue(i)
            i += 1
            (source, dest, source_port, dest_port, data) = req
            if buf_rsp:
                buf_rsp += data
                # try to decode response without body
                if b'\r\n\r\n' in data:
                    rspDecoded = self.decodeHttpResponse(data=buf_rsp)
                    if rspDecoded is not None:
                        self.responses.append((source, dest, source_port,
                                               dest_port, buf_rsp, rspDecoded))
                        buf_rsp = b''
            else:
                # is http response ?
                if data.startswith(b'HTTP/'):
                    buf_rsp += data
                    if b'\r\n\r\n' in data:
                        rspDecoded = self.decodeHttpResponse(data=buf_rsp)
                        if rspDecoded is not None:
                            self.responses.append(
                                (source, dest, source_port, dest_port, buf_rsp,
                                 rspDecoded))
                            buf_rsp = b''
        self.addLogSuccess(txt="<< Number of HTTP responses extracted: %s " %
                           len(self.responses))

        if self.requests:
            self.addLogSuccess("<< Read the file finished with success!")
            self.addLogWarning(
                "<< Click on the export button to generate the test!")
            self.exportToAction.setEnabled(True)
        else:
            self.addLogWarning("<< No http extracted!")

    def readFile(self, fileName):
        """
        Read the file passed as argument
        Old function with dtpkt and python2.7
        """
        self.requests = []
        self.responses = []

        ip_expected = socket.inet_aton(str(self.ipEdit.text()))
        port_expected = str(self.portEdit.text())

        try:
            f = open(fileName, 'rb')
            pcap = dpkt.pcap.Reader(f)
            tot_pkts = len(list(pcap))
        except Exception as e:
            self.addLogError(txt="<< Error to open the network trace")
            self.error('unable to open the network trace: %s' % str(e))
            QMessageBox.critical(self, "Import", "File not supported")
            return
        else:
            self.addLogSuccess(txt="<< Total packets detected: %s " % tot_pkts)
            self.progressBar.setMaximum(tot_pkts)

            # decode http request
            i = 1
            buf_req = ''
            for ts, buf in pcap:
                self.progressBar.setValue(i)
                i += 1

                # read ethernet layer
                eth = dpkt.ethernet.Ethernet(buf)
                if eth.type == dpkt.ethernet.ETH_TYPE_IP:
                    # continue with ip decoding layer
                    ip = eth.data
                    if ip.dst == ip_expected:
                        ip_layer = (ip.src, ip.dst)
                        if ip.p == dpkt.ip.IP_PROTO_TCP:
                            tcp = ip.data
                            if tcp.dport == int(port_expected) and len(
                                    tcp.data) > 0:
                                tcp_layer = (tcp.sport, tcp.dport)
                                buf_req += tcp.data
                                try:
                                    http_req = dpkt.http.Request(buf_req)
                                except dpkt.dpkt.NeedData as e:
                                    pass
                                except dpkt.UnpackError as e:
                                    pass
                                else:
                                    self.requests.append({
                                        'ip-src': ip.src,
                                        'ip-dst': ip.dst,
                                        'port-src': tcp.sport,
                                        'port-dst': tcp.dport,
                                        'tcp-data': buf_req,
                                        'tcp-object': http_req
                                    })
                                    self.addLogWarning(
                                        txt="<< %s http request(s) extracted" %
                                        len(self.requests))
                                    buf_req = ''

            # decode http responses
            i = 1
            self.progressBar.setValue(0)
            for ts, buf in pcap:
                self.progressBar.setValue(i)
                i += 1

                # read ethernet layer
                eth = dpkt.ethernet.Ethernet(buf)
                if eth.type == dpkt.ethernet.ETH_TYPE_IP:
                    # continue with ip decoding layer
                    ip = eth.data
                    if ip.src == ip_expected:
                        ip_layer = (ip.src, ip.dst)
                        if ip.p == dpkt.ip.IP_PROTO_TCP:
                            tcp = ip.data
                            if tcp.sport == int(port_expected) and len(
                                    tcp.data) > 0:
                                tcp_layer = (tcp.sport, tcp.dport)
                                if (tcp.data).startswith('HTTP/'):
                                    try:
                                        new_res = "%s\r\n\r\n" % (
                                            tcp.data).splitlines()[0]
                                        http_res = dpkt.http.Response(new_res)
                                    except dpkt.dpkt.NeedData as e:
                                        pass
                                    except dpkt.UnpackError as e:
                                        pass
                                    else:
                                        self.responses.append({
                                            'ip-src':
                                            ip.src,
                                            'ip-dst':
                                            ip.dst,
                                            'port-src':
                                            tcp.sport,
                                            'port-dst':
                                            tcp.dport,
                                            'tcp-data':
                                            new_res,
                                            'tcp-object':
                                            http_res
                                        })
                                        self.addLogWarning(
                                            txt=
                                            "<< %s http response(s) extracted"
                                            % len(self.responses))
            if self.requests:
                self.addLogSuccess("<< File decoded with success!")
                self.addLogWarning(
                    "<< Click on the export button to generate the test!")
                self.exportToAction.setEnabled(True)
            else:
                self.addLogWarning("<< No http extracted!")
class Form(QDialog):
    def __init__(self, parent=None):
        super(Form, self).__init__(parent)

        self.ql = QLabel("Enter Specification for Doctor:")
        self.le = QLineEdit()
        self.le.setObjectName("Specification")

        self.ql1 = QLabel("Enter city:")
        self.le1 = QLineEdit()
        self.le1.setObjectName("City")

        self.pb = QPushButton()
        self.pb.setObjectName("Create")
        self.pb.setText("CREATE")

        self.pb1 = QPushButton()
        self.pb1.setObjectName("Show")
        self.pb1.setText("SHOW")

        layout = QFormLayout()

        layout.addWidget(self.ql)
        layout.addWidget(self.le)

        layout.addWidget(self.ql1)
        layout.addWidget(self.le1)

        layout.addWidget(self.pb)
        layout.addWidget(self.pb1)

        self.setLayout(layout)
        self.connect(self.pb, SIGNAL("clicked()"), self.create_click)
        self.connect(self.pb1, SIGNAL("clicked()"), self.show_click)

        self.setWindowTitle("HOSPITAL MANAGEMENT SYSTEM")

    def create_click(self):
        spec = self.le.text()
        city = self.le1.text()
        cur.execute(
            str("SELECT doc_ID FROM DoctorDetails WHERE spec=\"" + spec +
                "\";"))
        did = cur.fetchall()
        cur.execute(
            str("SELECT Hospital_ID FROM Hospital WHERE Hospital_address LIKE \"%"
                + city + "%\";"))
        hid = cur.fetchall()
        token_file = open("token.txt")
        token = int(token_file.read())
        command = "INSERT INTO Appointment VALUES (" + "\"" + pid + "\"," + "\"" + str(
            did[0][0]) + "\"," + "\"" + str(hid[0][0]) + "\"," + "\"" + str(
                app_date) + "\"," + "\"" + str(token) + "\");"
        token_file.close()
        token += 1
        token_file = open('token.txt', 'w+')
        token_file.seek(0)
        token_file.write(str(token))
        token_file.close()
        cur.execute(command)
        conn.commit()

    def show_click(self):
        os.system("python3 patient-app-show.py")
Exemple #53
0
class AddForm(QDialog):    
    def __init__(self, sid,  parent=None):
        super(AddForm, self).__init__(parent)
        self.sid = sid
        try: 
            details = self.pullDetails(self.sid)
            pagetitle = str(details[1]) +' Session' 
        except:
            details = []
            pagetitle = 'None'
        
        self.l1 = QLabel("Name")
        self.le = QLineEdit()
        self.le.setObjectName("name")
        self.le.setText("")
        
        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.pb1, self.pb)
        
        
        groupBox = QGroupBox('Add New Term')
        groupBox.setLayout(layout)
        
        
        grid = QGridLayout()
        grid.addWidget(groupBox, 0, 0)
        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click(self.sid, self))
        self.connect(self.pb1, SIGNAL("clicked()"), lambda: self.button_close(self.sid, self))
        self.setWindowTitle(pagetitle)
        
    def button_click(self, a, b):
        # shost is a QString object
        b.close()
        self.a = a
        s1 = self.le.text()
        g = Db()
        try:
            if(len(s1) > 0):
                y = { 'name':s1, 'sessionID':self.a,  'start_date':s2, 'end_date':s3, 'active':0}
                z = g.insert('terms', y)
                
                if z and z > 0:
                    g.createClass(z)
                    g.createFee(z)
                    g.createResult(z)   
            else:
                pass
        except:
            pass
        
        try:
            self.lunchForm(self.a)
        except:
            pass
        try:
            self.close()
        except:
            pass
        
    def pullDetails(self, a):
        self.a = a
        cn = Db()
        datas = cn.select('session', '' , 1, {'id':self.a})
        return datas    
        
    def lunchForm(self, a):
        self.a = a
        self.form = TermForm(self.a)
        self.form.show()
    
    def button_close(self, a, b):
        b.close()
        self.a = a
        self.lunchForm(self.a)
Exemple #54
0
    def createDialog(self):
        """
        Create dialog
        """

        self.dockToolbar = QToolBar(self)
        self.dockToolbar.setToolButtonStyle(Qt.ToolButtonTextBesideIcon)

        self.setWindowTitle(WINDOW_TITLE)
        self.resize(500, 400)

        self.ipEdit = QLineEdit(self.defaultIp)
        ipRegExpVal = QRegExpValidator(self)
        ipRegExp = QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
        ipRegExpVal.setRegExp(ipRegExp)
        self.ipEdit.setValidator(ipRegExpVal)

        self.portEdit = QLineEdit(self.defaultPort)
        self.portEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        validatorPort = QIntValidator(self)
        self.portEdit.setValidator(validatorPort)

        self.progressBar = QProgressBar(self)
        self.progressBar.setMaximum(100)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setAlignment(Qt.AlignCenter)
        self.progressBar.setObjectName("progressBar")

        self.guiSikuliGroupBox = QGroupBox("")
        self.guiSikuliGroupBox.setFlat(True)
        self.automaticAdp = QRadioButton("Automatic")
        self.automaticAdp.setChecked(True)
        self.defaultAdp = QRadioButton("Default")
        self.genericAdp = QRadioButton("Generic")
        vbox = QHBoxLayout()
        vbox.addWidget(self.automaticAdp)
        vbox.addWidget(self.defaultAdp)
        vbox.addWidget(self.genericAdp)
        vbox.addStretch(1)
        self.guiSikuliGroupBox.setLayout(vbox)

        layout = QVBoxLayout()
        layout.addWidget(self.dockToolbar)
        layout.addSpacing(12)
        paramLayout = QGridLayout()
        paramLayout.addWidget(QLabel("Destination IP:"), 0, 0, Qt.AlignRight)
        paramLayout.addWidget(self.ipEdit, 0, 1)
        paramLayout.addWidget(QLabel("Destination Port:"), 1, 0, Qt.AlignRight)
        paramLayout.addWidget(self.portEdit, 1, 1)
        paramLayout.addWidget(QLabel(self.tr("Gui adapter selector:")), 2, 0,
                              Qt.AlignRight)
        paramLayout.addWidget(self.guiSikuliGroupBox, 2, 1)
        layout.addLayout(paramLayout)

        self.logsEdit = QTextEdit()
        self.logsEdit.setReadOnly(True)
        self.logsEdit.setTextInteractionFlags(Qt.NoTextInteraction)

        layout.addSpacing(12)
        layout.addWidget(self.logsEdit)
        layout.addSpacing(12)
        layout.addWidget(self.progressBar)

        self.setLayout(layout)
Exemple #55
0
class AddUserDialog(MustChooseDialog):
    """add a user account on a server: This dialog asks for the needed attributes"""

    # pylint: disable=R0902
    # pylint we need more than 10 instance attributes

    def __init__(self, url, username, password):
        MustChooseDialog.__init__(self, None)
        self.setWindowTitle(m18n('Create User Account') + ' - Kajongg')
        self.buttonBox = KDialogButtonBox(self)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)
        vbox = QVBoxLayout(self)
        grid = QFormLayout()
        self.lbServer = QLabel()
        self.lbServer.setText(url)
        grid.addRow(m18n('Game server:'), self.lbServer)
        self.lbUser = QLabel()
        grid.addRow(m18n('Username:'******'Password:'******'Repeat password:'), self.edPassword2)
        vbox.addLayout(grid)
        vbox.addWidget(self.buttonBox)
        pol = QSizePolicy()
        pol.setHorizontalPolicy(QSizePolicy.Expanding)
        self.lbUser.setSizePolicy(pol)

        self.edPassword.textChanged.connect(self.passwordChanged)
        self.edPassword2.textChanged.connect(self.passwordChanged)
        StateSaver(self)
        self.username = username
        self.password = password
        self.passwordChanged()
        self.edPassword2.setFocus()

    def passwordChanged(self, dummyText=None):
        """password changed"""
        self.validate()

    def validate(self):
        """does the dialog hold valid data?"""
        equal = self.edPassword.size() and self.edPassword.text(
        ) == self.edPassword2.text()
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(equal)

    @property
    def username(self):
        """abstracts the username of the dialog"""
        return unicode(self.lbUser.text())

    @username.setter
    def username(self, username):
        """abstracts the username of the dialog"""
        self.lbUser.setText(username)

    @property
    def password(self):
        """abstracts the password of the dialog"""
        return unicode(self.edPassword.text())

    @password.setter
    def password(self, password):
        """abstracts the password of the dialog"""
        self.edPassword.setText(password)
Exemple #56
0
class EditForm(QDialog): 
    
    def __init__(self, sid, parent=None):
        super(EditForm, self).__init__(parent)
        self.sid = sid
        data = self.callData(self.sid)
        
        
        try: 
            details = self.pullDetails(data[1])
            pagetitle = str(details[2]) +' Session' 
        except:
            details = []
            pagetitle = 'None'
        
        self.l1 = QLabel("Name")
        self.le = QLineEdit()
        self.le.setObjectName("name")
        self.le.setText(str(data[1]))
        
        self.l2 = QLabel("Start Date")
        self.le2 = QDateEdit()
        self.le2.setObjectName("startdate")
        #self.le2.setDate(data[2])
        
        self.l3 = QLabel("End Date")
        self.le3 = QDateEdit()
        self.le3.setObjectName("enddate")
        #self.le3.setDate(data[3])

        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.l3, self.le3)
        layout.addRow(self.pb1, self.pb)
        
        groupBox = QGroupBox('Edit Session')
        groupBox.setLayout(layout)
        
        grid = QGridLayout()
        grid.addWidget(groupBox, 0, 0)
        self.setLayout(grid)
        self.connect(self.pb, SIGNAL("clicked()"), lambda: self.button_click(data[0], self))
        self.connect(self.pb1, SIGNAL("clicked()"),lambda: self.button_close(self))
        self.setWindowTitle(pagetitle)
        
    def button_click(self, a, b):
        # shost is a QString object
        b.close()
        s1 = self.le.text()
        s2 = self.le2.date().toPyDate()
        s3 = self.le3.date().toPyDate()
        self.a = a
        g = Db()
        if(len(s1) > 0):
            y = { 'name':s1, 'start_date':s2, 'end_date':s3}
            z = {'id':self.a}
            g.update('terms', y, z)
            if self.a and self.a > 0:
                    g.createClass(self.a)
                    g.createFee(self.a)
                    g.createResult(self.a) 
        
        self.form = TermForm(self.a)
        self.form.show()
        self.close()
        #self.lunchForm()
        
    def lunchForm(self, a):
        self.a = a
        self.form = TermForm(self.a)
        self.form.show()
        
    def button_close(self, a, b):
        b.close()
        self.a = a
        self.lunchForm(self.a)
        
    def pullDetails(self, a):
        self.a = a
        cn = Db()
        datas = cn.select('session', '' , 1, {'id':self.a})
        
        return datas 

    def callData(self, a):
        # select a file
        self.a = a
        g = Db()
        return  g.select('terms', '', 1, {'id':self.a})
Exemple #57
0
class RawFind(QWidget):
    """
    Raw find widget
    """
    def __init__(self, parent, editor, buttonNext=True):
        """
        Constructor
        """
        QWidget.__init__(self, parent)
        self.editor = editor
        self.buttonNext = buttonNext
        self.createWidgets()
        self.createConnections()

    def createWidgets(self):
        """
        Create qt widget
        """

        self.edit = QLineEdit()
        self.edit.setPlaceholderText("Search text?")
        if self.buttonNext:
            self.buttonNext = QPushButton("Next")

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.edit)
        if self.buttonNext:
            hlayout.addWidget(self.buttonNext)
        hlayout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(hlayout)

    def resetLine(self):
        """
        Reset line
        """
        self.edit.setText("")
        self.edit.setStyleSheet("")

    def createConnections(self):
        """
        QtSignals connection
        """
        self.edit.textChanged.connect(self.textHasChanged)
        if self.buttonNext:
            self.buttonNext.clicked.connect(self.enterPressed)
        else:
            self.edit.returnPressed.connect(self.enterPressed)

    def enterPressed(self):
        """
        Called on enter pressed
        """
        text = self.edit.text()
        if len(text) > 0:
            found = self.editor.searchNext(text)
            if not found:
                self.edit.setStyleSheet("background-color:rgb(255, 175, 90);")
            else:
                self.edit.setStyleSheet("background-color:rgb(144, 238, 144);")
        else:
            self.edit.setStyleSheet("")

    def textHasChanged(self):
        """
        Text has changed
        """
        text = self.edit.text()
        if len(text) > 0:
            found = self.editor.search(text)
            if not found:
                self.edit.setStyleSheet("background-color:rgb(255, 175, 90);")
            else:
                self.edit.setStyleSheet("background-color:rgb(144, 238, 144);")
        else:
            self.edit.setStyleSheet("")

    def setReadOnly(self, readonly):
        """
        Set editor to read only
        """
        self.edit.setReadOnly(readonly)
Exemple #58
0
class LoginDlg(QDialog):
    """login dialog for server"""
    def __init__(self):
        """self.servers is a list of tuples containing server and last playername"""
        QDialog.__init__(self, None)
        self.setWindowTitle(m18n('Login') + ' - Kajongg')
        self.setupUi()

        localName = m18nc('kajongg name for local game server',
                          Query.localServerName)
        self.servers = Query(
            'select url,lastname from server order by lasttime desc').records
        servers = [
            m18nc('kajongg name for local game server', x[0])
            for x in self.servers
        ]
        # the first server combobox item should be default: either the last used server
        # or localName for autoPlay
        if localName not in servers:
            servers.append(localName)
        if 'kajongg.org' not in servers:
            servers.append('kajongg.org')
            demoHost = Options.host or localName
            if demoHost in servers:
                servers.remove(
                    demoHost
                )  # we want a unique list, it will be re-used for all following games
            servers.insert(
                0, demoHost)  # in this process but they will not be autoPlay
        self.cbServer.addItems(servers)
        self.passwords = Query(
            'select url, p.name, passwords.password from passwords, player p '
            'where passwords.player=p.id').records
        Players.load()
        self.cbServer.editTextChanged.connect(self.serverChanged)
        self.cbUser.editTextChanged.connect(self.userChanged)
        self.serverChanged()
        StateSaver(self)

    def returns(self, dummyButton=None):
        """maybe we should return an class ServerConnection"""
        return (self.useSocket, self.url, self.username,
                self.__defineRuleset())

    def setupUi(self):
        """create all Ui elements but do not fill them"""
        buttonBox = KDialogButtonBox(self)
        buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                     | QDialogButtonBox.Ok)
        # Ubuntu 11.10 unity is a bit strange - without this, it sets focus on
        # the cancel button (which it shows on the left). I found no obvious
        # way to use setDefault and setAutoDefault for fixing this.
        buttonBox.button(QDialogButtonBox.Ok).setFocus(True)
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)
        vbox = QVBoxLayout(self)
        self.grid = QFormLayout()
        self.cbServer = QComboBox()
        self.cbServer.setEditable(True)
        self.grid.addRow(m18n('Game server:'), self.cbServer)
        self.cbUser = QComboBox()
        self.cbUser.setEditable(True)
        self.grid.addRow(m18n('Username:'******'Password:'******'kajongg', 'Ruleset:'), self.cbRuleset)
        vbox.addLayout(self.grid)
        vbox.addWidget(buttonBox)
        pol = QSizePolicy()
        pol.setHorizontalPolicy(QSizePolicy.Expanding)
        self.cbUser.setSizePolicy(pol)

    def serverChanged(self, dummyText=None):
        """the user selected a different server"""
        records = Query(
            'select player.name from player, passwords '
            'where passwords.url=? and passwords.player = player.id',
            list([self.url])).records
        players = list(x[0] for x in records)
        preferPlayer = Options.player
        if preferPlayer:
            if preferPlayer in players:
                players.remove(preferPlayer)
            players.insert(0, preferPlayer)
        self.cbUser.clear()
        self.cbUser.addItems(players)
        if not self.cbUser.count():
            user = KUser() if os.name == 'nt' else KUser(os.geteuid())
            self.cbUser.addItem(user.fullName() or user.loginName())
        if not preferPlayer:
            userNames = [x[1] for x in self.servers if x[0] == self.url]
            if userNames:
                userIdx = self.cbUser.findText(userNames[0])
                if userIdx >= 0:
                    self.cbUser.setCurrentIndex(userIdx)
        showPW = self.url != Query.localServerName
        self.grid.labelForField(self.edPassword).setVisible(showPW)
        self.edPassword.setVisible(showPW)
        self.grid.labelForField(self.cbRuleset).setVisible(
            not showPW and not Options.ruleset)
        self.cbRuleset.setVisible(not showPW and not Options.ruleset)
        if not showPW:
            self.cbRuleset.clear()
            if Options.ruleset:
                self.cbRuleset.items = [Options.ruleset]
            else:
                self.cbRuleset.items = Ruleset.selectableRulesets(self.url)

    def __defineRuleset(self):
        """find out what ruleset to use"""
        if Options.ruleset:
            return Options.ruleset
        elif Internal.autoPlay or bool(Options.host):
            return Ruleset.selectableRulesets()[0]
        else:
            return self.cbRuleset.current

    def userChanged(self, text):
        """the username has been changed, lookup password"""
        if text == '':
            self.edPassword.clear()
            return
        passw = None
        for entry in self.passwords:
            if entry[0] == self.url and entry[1] == unicode(text):
                passw = entry[2]
        if passw:
            self.edPassword.setText(passw)
        else:
            self.edPassword.clear()

    @property
    def url(self):
        """abstracts the url of the dialog"""
        return english(unicode(self.cbServer.currentText()))

    @property
    def host(self):
        """abstracts the host of the dialog"""
        return self.url.partition(':')[0]

    @property
    def useSocket(self):
        """do we use socket for current host?"""
        return self.host == Query.localServerName

    @property
    def port(self):
        """abstracts the port of the dialog"""
        try:
            return int(self.url.partition(':')[2])
        except ValueError:
            return Options.defaultPort()

    @property
    def username(self):
        """abstracts the username of the dialog"""
        return unicode(self.cbUser.currentText())

    @property
    def password(self):
        """abstracts the password of the dialog"""
        return unicode(self.edPassword.text())

    @password.setter
    def password(self, password):
        """abstracts the password of the dialog"""
        self.edPassword.setText(password)

    def updateServerInfoInDatabase(self):
        """we are online. Update table server."""
        lasttime = datetime.datetime.now().replace(microsecond=0).isoformat()
        url = english(self.url)  # use unique name for Local Game
        with Transaction():
            serverKnown = Query(
                'update server set lastname=?,lasttime=? where url=?',
                list([self.username, lasttime, url])).rowcount() == 1
            if not serverKnown:
                Query(
                    'insert into server(url,lastname,lasttime) values(?,?,?)',
                    list([url, self.username, lasttime]))
        # needed if the server knows our name but our local data base does not:
        Players.createIfUnknown(self.username)
        playerId = Players.allIds[self.username]
        with Transaction():
            if Query(
                    'update passwords set password=? where url=? and player=?',
                    list([self.password, url, playerId])).rowcount() == 0:
                Query(
                    'insert into passwords(url,player,password) values(?,?,?)',
                    list([url, playerId, self.password]))
class CameraConfigControl(ConfigControl):
    RES_TEXT_WIDTH = 50
    BUTTON_WIDTH = 100

    def __init__(self, camera_config, to_run_before_test_camera):
        ConfigControl.__init__(self, camera_config)
        self._number_item = camera_config.camera_number
        self._width_item = camera_config.width
        self._height_item = camera_config.height
        self._to_run_before_test_camera = to_run_before_test_camera
        self._init_ui()

    def _init_ui(self):
        # Set Camera Number
        self.txt_number = QLineEdit()
        self.txt_number.setFixedWidth(self.RES_TEXT_WIDTH)
        lbl_camera_number = QLabel("Camera Number")
        lbl_camera_number.setFixedWidth(ConfigControl.LABEL_WIDTH)

        hbox_num = QHBoxLayout()
        hbox_num.addWidget(lbl_camera_number)
        hbox_num.addWidget(self.txt_number)
        hbox_num.addStretch()

        # Set Camera Resolution
        lbl = QLabel("Camera Resolution")
        lbl.setFixedWidth(ConfigControl.LABEL_WIDTH)
        self.txt_width = QLineEdit()
        self.txt_width.setFixedWidth(self.RES_TEXT_WIDTH)
        self.txt_height = QLineEdit()
        self.txt_height.setFixedWidth(self.RES_TEXT_WIDTH)

        hbox_res = QHBoxLayout()
        hbox_res.setContentsMargins(0, 0, 0, 0)
        hbox_res.addWidget(lbl)
        hbox_res.addWidget(self.txt_width)
        hbox_res.addWidget(QLabel("x"))
        hbox_res.addWidget(self.txt_height)
        hbox_res.addStretch()

        # Preview camera
        btn_camera_test = QPushButton("Test Camera")
        btn_camera_test.setFixedWidth(self.BUTTON_WIDTH)
        btn_camera_test.clicked.connect(self._test_camera)

        btn_camera_settings = QPushButton("Camera Settings")
        btn_camera_settings.setFixedWidth(self.BUTTON_WIDTH)
        btn_camera_settings.clicked.connect(self._open_camera_controls)

        hbox_buttons = QHBoxLayout()
        hbox_buttons.addWidget(btn_camera_test)
        hbox_buttons.addWidget(btn_camera_settings)
        hbox_buttons.addStretch(1)

        vbox = QVBoxLayout()
        vbox.setContentsMargins(0, 0, 0, 0)
        vbox.addLayout(hbox_num)
        vbox.addLayout(hbox_res)
        vbox.addLayout(hbox_buttons)

        self.setLayout(vbox)

    def update_from_config(self):
        self.txt_number.setText(str(self._number_item.value()))
        self.txt_width.setText(str(self._width_item.value()))
        self.txt_height.setText(str(self._height_item.value()))

    def save_to_config(self):
        self._number_item.set(self.txt_number.text())
        self._width_item.set(self.txt_width.text())
        self._height_item.set(self.txt_height.text())

    def _test_camera(self):
        # Check that values are integers
        try:
            camera_num = int(self.txt_number.text())
            camera_width = int(self.txt_width.text())
            camera_height = int(self.txt_height.text())
        except ValueError:
            QMessageBox.critical(self, "Camera Error", "Camera number, width, and height must be integers")
            return

        self._to_run_before_test_camera()

        # Check that we can connect to the camera
        try:
            stream = CameraStream(camera_num, camera_width, camera_height, use_default_as_backup=False)
        except IOError:
            QMessageBox.critical(self, "Camera Error", "Cannot find specified camera")
            return

        # Check resolution is acceptable
        set_width = int(stream.get_width())
        set_height = int(stream.get_height())
        if set_width != camera_width or set_height != camera_height:
            QMessageBox.warning(self, "Camera Error",
                                "Could not set the camera to the specified resolution: {}x{}.\nThe camera defaulted "
                                "to {}x{}.".format(camera_width, camera_height, set_width, set_height))
            self.txt_width.setText(str(set_width))
            self.txt_height.setText(str(set_height))
            return

        # Display a preview feed from the camera
        breaking_frame = False
        while True:
            # Capture the next frame from the camera
            frame = stream.get_frame()
            if frame is None:
                breaking_frame = True
                break
            elif cv2.waitKey(1) != -1:
                break

            small = cv2.resize(frame, (0, 0), fx=0.5, fy=0.5)
            cv2.imshow('Camera Preview (Press any key to exit)', small)

        stream.release_resources()
        cv2.destroyAllWindows()

        # Opening the camera controls window stops the camera from working; reopen this window
        if breaking_frame:
            self._test_camera()

    def _open_camera_controls(self):
        camera_num = int(self.txt_number.text())
        self._to_run_before_test_camera()
        CameraStream.open_camera_controls(camera_num)
Exemple #60
0
 def __init__(self, completer, type=QCompleter.PopupCompletion):
     QLineEdit.__init__(self)
     self.completer = completer
     self.setTextMargins(0, 0, 5, 0)
     self.completionType = type
     self.completer.setCompletionMode(self.completionType)