Beispiel #1
0
    def __init__(self):
        # super(CodeEditor, self).__init__()
        QPlainTextEdit.__init__(self)
        self.lineNumberArea = LineNumberArea(self)
        self.setTabStopWidth(20)
        self.blockCountChanged.connect(self.updateLineNumberAreaWidth)
        self.updateRequest.connect(self.updateLineNumberArea)
        self.cursorPositionChanged.connect(self.highlightCurrentLine)
        self.updateLineNumberAreaWidth(0)
        self.highlightCurrentLine()
        self.highlighter = PythonHighlighter(self.document())
        self.dirty = False

        # Determine if the line number area needs to be shown or not
        lineNumbersCheckedState = FreeCAD.ParamGet(
            "User parameter:BaseApp/Preferences/Mod/cadquery-freecad-module"
        ).GetBool("showLineNumbers")
        if lineNumbersCheckedState:
            self.showLineNumberArea()
        else:
            self.hideLineNumberArea()

        # self.overlay = FinderOverlay(self)
        # self.overlay.hide()

        self.initUI()
Beispiel #2
0
    def __init__(self):
        super(STM32FProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.stm32f = STM32FProgrammer()

        self.setWindowTitle("Serial STM32F Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("stm32f-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        layoutsetting = QHBoxLayout()
        mode = QComboBox()
        mode.addItem("fast", False)
        mode.addItem("slow", True)
        mode.currentIndexChanged.connect(self.modechanged)
        layoutsetting.addWidget(QLabel("Speed:"))
        layoutsetting.addWidget(mode)

        blocksize = QComboBox()
        blocksize.addItem("256", False)
        blocksize.addItem("64", True)
        blocksize.currentIndexChanged.connect(self.blocksizechanged)
        layoutsetting.addStretch()
        layoutsetting.addWidget(QLabel("Read Block Size:"))
        layoutsetting.addWidget(blocksize)
        layout.addLayout(layoutsetting)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.stm32f.newTextLog.connect(self.append)
        layout.addWidget(self.statusLine)

        # Set dialog layout
        self.setLayout(layout)
Beispiel #3
0
 def setPlainText(self, txt):
     """ Sets the text edit content and emits newTextSet signal.
     :param txt: New text to display
     """
     self.__originalText = txt
     QPlainTextEdit.setPlainText(self, txt)
     self.newTextSet.emit()
Beispiel #4
0
 def focusInEvent(self, event):
     """
     Emits the focusedIn signal
     :param event:
     :return:
     """
     self.focusedIn.emit(event)
     QPlainTextEdit.focusInEvent(self, event)
Beispiel #5
0
 def mousePressEvent(self, event):
     """
     React on a mouse event - move cursor to position of the event.
     """
     if event.button() == Qt.RightButton:
         event = QMouseEvent(QEvent.MouseButtonPress, event.pos(),
                             Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
     QPlainTextEdit.mousePressEvent(self, event)
Beispiel #6
0
 def mouseMoveEvent(self, event):
     assert isinstance(event, QMouseEvent)
     c = self.cursorForPosition(event.pos())
     for sel in self.__selections:
         if sel.containsCursor(c) and sel.tooltip:
             QToolTip.showText(self.mapToGlobal(event.pos()), sel.tooltip, self)
             break
     QPlainTextEdit.mouseMoveEvent(self, event)
Beispiel #7
0
 def mousePressEvent(self, event):
     """
     React on a mouse event - move cursor to position of the event.
     """
     if event.button() == Qt.RightButton:
         event = QMouseEvent(QEvent.MouseButtonPress, event.pos(),
             Qt.LeftButton, Qt.LeftButton, Qt.NoModifier)
     QPlainTextEdit.mousePressEvent(self, event)
Beispiel #8
0
 def testPropertyValues(self):
     app = QApplication(sys.argv)
     textEdit = QPlainTextEdit()
     textEdit.insertPlainText("PySide INdT")
     selection = QTextEdit.ExtraSelection()
     selection.cursor = textEdit.textCursor()
     selection.cursor.setPosition(2)
     self.assertEqual(selection.cursor.position(), 2)
Beispiel #9
0
        def paintEvent(self, event):
            '''Handle the paint event.'''

            super(QPlainTextEdit, self).paintEvent(event)

            self._highlight_indents(event)

            QPlainTextEdit.paintEvent(self, event)
            return
Beispiel #10
0
        def paintEvent(self, event):
            '''Handle the paint event.'''

            super(QPlainTextEdit, self).paintEvent(event)

            self._highlight_indents(event)

            QPlainTextEdit.paintEvent(self, event)
            return
Beispiel #11
0
    def paintEvent(self, event):
        """
        Emits prePainting and postPainting signals

        :param event: QPaintEvent
        """
        self.prePainting.emit(event)
        QPlainTextEdit.paintEvent(self, event)
        self.postPainting.emit(event)
Beispiel #12
0
    def mouseReleaseEvent(self, event):
        """
        Emits mouseReleased signal.

        :param event: QMouseEvent
        """
        event.stop = False
        self.mouseReleased.emit(event)
        if not event.stop:
            QPlainTextEdit.mouseReleaseEvent(self, event)
Beispiel #13
0
    def wheelEvent(self, event):
        """
        Emits the mouseWheelActivated signal.

        :param event: QMouseEvent
        """
        event.stop = False
        self.mouseWheelActivated.emit(event)
        if not event.stop:
            QPlainTextEdit.wheelEvent(self, event)
 def __init__(self, title):
     """
     Constructeur.
     Paramétrisation de la console.
     """
     QPlainTextEdit.__init__(self)
     self.setWindowTitle(str(title))
     self.setWindowIcon(QIcon(WINDOW_ICO_PATH))
     self.setReadOnly(True)
     self.show_request.connect(self.show_listener)
Beispiel #15
0
    def __init__(self, fixtures_folder, parent=None):
        QWidget.__init__(self, parent)
        self.current_fixture = None
        self.fixtures_folder = fixtures_folder
        self.setWindowTitle("Frangitron DMX program editor")

        self.text = QPlainTextEdit()
        font = QFont("Monospace")
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(16)
        self.text.setFont(font)
        self.text.setStyleSheet(
            "color: white; background-color: rgb(30, 30, 30)")

        self.combo_fixture = QComboBox()

        self.frame_programs = QWidget()
        self.checkboxes_programs = list()
        self.layout_programs = QGridLayout(self.frame_programs)

        self.spinner_offset = QSpinBox()
        self.spinner_offset.setMinimum(1)
        self.spinner_offset.setMaximum(512)
        self.spinner_offset.setValue(1)
        self.spinner_offset.valueChanged.connect(self.address_changed)

        self.doc = QPlainTextEdit()
        self.doc.setReadOnly(True)
        self.doc.setFont(font)

        self.status = QLabel()

        layout = QGridLayout(self)
        layout.addWidget(self.combo_fixture, 0, 1)
        layout.addWidget(self.spinner_offset, 0, 2)
        layout.addWidget(self.frame_programs, 1, 1)
        layout.addWidget(self.text, 0, 0, 3, 1)
        layout.addWidget(self.doc, 2, 1, 1, 2)
        layout.addWidget(self.status, 3, 0, 1, 3)
        layout.setColumnStretch(0, 60)
        layout.setColumnStretch(1, 40)

        self.resize(1280, 800)

        self.streamer = Streamer(self.fixtures_folder)

        self.combo_fixture.addItems(sorted(self.streamer.fixtures))
        self.combo_fixture.currentIndexChanged.connect(self.fixture_changed)

        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.timer.start(500.0 / FRAMERATE)
        self.should_reload = True

        self.fixture_changed()
Beispiel #16
0
    def keyReleaseEvent(self, event):
        """
        Performs indentation if tab key pressed, else emits the keyPressed signal

        :param event: QKeyEvent
        """
        assert isinstance(event, QKeyEvent)
        event.stop = False
        self.keyReleased.emit(event)
        if not event.stop:
            QPlainTextEdit.keyReleaseEvent(self, event)
Beispiel #17
0
        def __init__(self, parent, *args):

            QPlainTextEdit.__init__(self, *args)
            self.parent = parent
            self.config_main = self.parent.config_main
            self.config_theme = self.parent.config_theme
            self.tools = self.parent.tools
            self.lvars = self.parent.lvars

            self._loaded = False

            self.setFrameStyle(QFrame.NoFrame)
            self.setLineWrapMode(QPlainTextEdit.NoWrap)

            self._setup_ui()

            self._casts_marked = False
            self._casts_selections = None

            self.cursorPositionChanged.connect(
                self._on_cursor_position_changed)

            self._bracket_info = hrdev_plugin.include.helper.AttributeDict()
            self._bracket_info.saved_bracket = None
            self._bracket_info.depth = 0
            self._bracket_info.seeking_nl = False
            self._bracket_info.open_brackets = ['[', '{', '(']
            self._bracket_info.closed_brackets = [']', '}', ')']
            self._bracket_info.pairs_closed = {']': '[', '}': '{', ')': '('}
            self._bracket_info.pairs_open = {'[': ']', '{': '}', '(': ')'}
            self._bracket_info.ignore_stack_left = []
            self._bracket_info.ignore_stack_right = []

            self._left_selected_bracket = QTextEdit.ExtraSelection()
            self._right_selected_bracket = QTextEdit.ExtraSelection()

            toolTipWidget = QtGui.QLabel()
            toolTipWidget.setStyleSheet(
                "QLabel { background-color : #ffffcc; color : #222; padding: 5px; }"
            )
            toolTipWidget.setFrameShape(QtGui.QFrame.StyledPanel)
            toolTipWidget.setWindowFlags(QtCore.Qt.ToolTip)
            toolTipWidget.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
            toolTipWidget.hide()
            self._toolTipWidget = toolTipWidget

            self._timer = QtCore.QBasicTimer()
            self._timer.start(2000, self)

            self._min_marker_len = self.config_main.getint(
                'editor', 'min_marker_len')
            return
Beispiel #18
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.setLayout(QVBoxLayout(self))
     self.text_display = QPlainTextEdit(self)
     self.text_display.setReadOnly(True)
     self.layout().addWidget(self.text_display)
     self.text_input = QLineEdit(self)
     self.text_input.returnPressed.connect(self.send_text)
     self.layout().addWidget(self.text_input)
     QWidget.setTabOrder(self.text_input, self.text_display)
     self.setEnabled(False)
     self.message.emit('Not connected')
     self._connection = None
Beispiel #19
0
    def _create_changes(self):
        c = QPlainTextEdit()
        c.setReadOnly(True)
        txt = ''
        for i in range(10):
            for a, d, m in self.changes:
                txt += '<p>{} {}</p><p><b><pre> {}</pre></b></p>'.format(a, d, m)

        c.appendHtml(txt)
        cur = c.textCursor()
        cur.movePosition(QtGui.QTextCursor.Start)
        c.setTextCursor(cur)
        c.ensureCursorVisible()
        return c
Beispiel #20
0
        def __init__(self, parent, *args):

            QPlainTextEdit.__init__(self, *args)
            self.parent = parent
            self.config_main = self.parent.config_main
            self.config_theme = self.parent.config_theme
            self.tools = self.parent.tools
            self.lvars = self.parent.lvars

            self._loaded = False

            self.setFrameStyle(QFrame.NoFrame)
            self.setLineWrapMode(QPlainTextEdit.NoWrap)

            self._setup_ui()

            self._casts_marked = False
            self._casts_selections = None

            self.cursorPositionChanged.connect(
                self._on_cursor_position_changed)

            self._bracket_info = hrdev_plugin.include.helper.AttributeDict()
            self._bracket_info.saved_bracket = None
            self._bracket_info.depth = 0
            self._bracket_info.seeking_nl = False
            self._bracket_info.open_brackets = ['[', '{', '(']
            self._bracket_info.closed_brackets = [']', '}', ')']
            self._bracket_info.pairs_closed = {']': '[', '}': '{', ')': '('}
            self._bracket_info.pairs_open = {'[': ']', '{': '}', '(': ')'}
            self._bracket_info.ignore_stack_left = []
            self._bracket_info.ignore_stack_right = []

            self._left_selected_bracket = QTextEdit.ExtraSelection()
            self._right_selected_bracket = QTextEdit.ExtraSelection()

            toolTipWidget = QtGui.QLabel()
            toolTipWidget.setStyleSheet("QLabel { background-color : #ffffcc; color : #222; padding: 5px; }")
            toolTipWidget.setFrameShape(QtGui.QFrame.StyledPanel)
            toolTipWidget.setWindowFlags(QtCore.Qt.ToolTip)
            toolTipWidget.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents)
            toolTipWidget.hide()
            self._toolTipWidget = toolTipWidget

            self._timer = QtCore.QBasicTimer()
            self._timer.start(2000, self)

            self._min_marker_len = self.config_main.getint('editor',
                                                           'min_marker_len')
            return
Beispiel #21
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        layout = QVBoxLayout(self)
        horiz_layout = QHBoxLayout()
        self.conditional_legend_widget = EdgeWidget(self, True)
        self.conditional_legend_widget.setMinimumHeight(15)
        horiz_layout.addWidget(self.conditional_legend_widget)

        self.conditional_legend_label = QLabel("Conditional transition", self)
        horiz_layout.addWidget(self.conditional_legend_label)

        self.unconditional_legend_widget = EdgeWidget(self, False)
        self.unconditional_legend_widget.setMinimumHeight(15)
        horiz_layout.addWidget(self.unconditional_legend_widget)
        self.unconditional_legend_label = QLabel("Non-conditional transition",
                                                 self)
        horiz_layout.addWidget(self.unconditional_legend_label)

        layout.addLayout(horiz_layout)

        self.splitter = QSplitter(self)

        layout.addWidget(self.splitter)

        self.view = ClassyView(self.splitter)
        # layout.addWidget(self.view)
        self.scene = ClassyScene(self)
        self.view.setScene(self.scene)

        self._menu_bar = QMenuBar(self)
        self._menu = QMenu("&File")
        self._menu_bar.addMenu(self._menu)
        layout.setMenuBar(self._menu_bar)

        self.open_action = QAction("O&pen", self)
        self.exit_action = QAction("E&xit", self)
        self._menu.addAction(self.open_action)
        self._menu.addAction(self.exit_action)

        self.connect(self.open_action, SIGNAL("triggered()"), self.open_file)
        self.connect(self.exit_action, SIGNAL("triggered()"), self.close)

        self.settings = QSettings("CD Projekt RED", "TweakDB")

        self.log_window = QPlainTextEdit(self.splitter)
        self.splitter.setOrientation(Qt.Vertical)

        self.setWindowTitle("Classy nodes")
Beispiel #22
0
    def __init__(self,
                 parent,
                 template=LICENSE_TEXT,
                 templateMap=LICENSE_TEMPLATE_MAP,
                 titleText='License',
                 flagSettingName='acceptedLicense'):
        '''
    '''
        super(OnceDialog, self).__init__(parent)
        self.template = template
        self.templateMap = templateMap
        self.titleText = titleText
        self.flagSettingName = flagSettingName

        self.scrollingText = QPlainTextEdit(self.filledTemplatedText(),
                                            parent=self)

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

        # One scrolling text widget
        layout = QGridLayout()
        layout.addWidget(self.scrollingText)

        layout.addWidget(buttonBox)
        self.setLayout(layout)
        self.setWindowTitle(self.tr(self.titleText))

        # connections
        buttonBox.accepted.connect(self.accept)
        buttonBox.rejected.connect(self.reject)

        self.setGeometry(0, 0, 600, 480)
Beispiel #23
0
    def __init__(self, parent, title, sub_title):
        super(AbstractEntry, self).__init__(parent)

        self.setTitle(title)
        self.setSubTitle(sub_title)

        self.score = QComboBox(self)

        self.score.insertItems(5,
                               ["1 - Poor",
                                "2 - Fair",
                                "3 - Good",
                                "4 - Great",
                                "5 - Outstanding"])

        self.comments = QPlainTextEdit(self)
        self.comments.textChanged.connect(self.comments_changed)

        field = "%s.comments*" % title

        self.registerField(field,
                           self.comments,
                           "plainText",
                           SIGNAL("textChanged()"))

        layout = QGridLayout(self)

        layout.addWidget(QLabel(self.tr("Score:"), self),    0, 0)
        layout.addWidget(self.score,                         0, 1)
        layout.addWidget(QLabel(self.tr("Comments:"), self), 1, 0)
        layout.addWidget(self.comments,                      1, 1)
Beispiel #24
0
    def __init__(self):
        super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.xmega = XMEGAProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("xmega-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.xmega.newTextLog.connect(self.append)
        layout.addWidget(self.statusLine)

        # Set dialog layout
        self.setLayout(layout)
Beispiel #25
0
 def __init__(self, parent=None):
     QWidget.__init__(self, parent)
     self.setLayout(QVBoxLayout(self))
     self.text_display = QPlainTextEdit(self)
     self.text_display.setReadOnly(True)
     self.layout().addWidget(self.text_display)
     self.text_input = QLineEdit(self)
     self.text_input.returnPressed.connect(self.send_text)
     self.layout().addWidget(self.text_input)
     QWidget.setTabOrder(self.text_input, self.text_display)
     self.setEnabled(False)
     self.message.emit('Not connected')
     self._connection = None
Beispiel #26
0
    def __init__(self, parent=None):
        """
        Creates the widget.

        :param parent: Optional parent widget
        """
        QPlainTextEdit.__init__(self, parent)
        StyledObject.__init__(self)
        #: Tag member used to remeber the filename of the edited text if any
        self.tagFilename = None
        #: Tag member used to remeber the filename of the edited text if any
        self.tagEncoding = 'utf8'
        #: Weakref to the editor
        self.editor = None

        self.__originalText = ""

        #: dirty flag
        self.__dirty = False
        #: our custom context menu
        self.__context_menu = QMenu()
        #: The list of active extra-selections (TextDecoration)
        self.__selections = []
        self.__numBlocks = -1

        self.visible_blocks = []

        #: Shortcut to the fontMetrics
        self.fm = self.fontMetrics()

        self.textChanged.connect(self.__onTextChanged)
        self.blockCountChanged.connect(self.__onBlocksChanged)
        self.verticalScrollBar().valueChanged.connect(self.__onBlocksChanged)
        self.newTextSet.connect(self.__onBlocksChanged)
        self.cursorPositionChanged.connect(self.__onBlocksChanged)
        self.setLineWrapMode(QPlainTextEdit.NoWrap)
        self.setMouseTracking(True)

        self._onStyleChanged()
Beispiel #27
0
        def __init__(self, parent, *args):

            QPlainTextEdit.__init__(self, *args)
            self.parent = parent
            self.config_main = self.parent.config_main
            self.config_theme = self.parent.config_theme
            self.tools = self.parent.tools

            self._loaded = False

            self.setFrameStyle(QFrame.NoFrame)
            self.setLineWrapMode(QPlainTextEdit.NoWrap)

            self._setup_ui()

            self._casts_marked = False
            self._casts_selections = None

            self.cursorPositionChanged.connect(
                self._on_cursor_position_changed)

            self._bracket_info = include.helper.AttributeDict()
            self._bracket_info.saved_bracket = None
            self._bracket_info.depth = 0
            self._bracket_info.seeking_nl = False
            self._bracket_info.open_brackets = ['[', '{', '(']
            self._bracket_info.closed_brackets = [']', '}', ')']
            self._bracket_info.pairs_closed = {']': '[', '}': '{', ')': '('}
            self._bracket_info.pairs_open = {'[': ']', '{': '}', '(': ')'}
            self._bracket_info.ignore_stack_left = []
            self._bracket_info.ignore_stack_right = []

            self._left_selected_bracket = QTextEdit.ExtraSelection()
            self._right_selected_bracket = QTextEdit.ExtraSelection()

            self._min_marker_len = self.config_main.getint('editor',
                                                           'min_marker_len')
            return
Beispiel #28
0
    def keyPressEvent(self, event):
        """
        Performs indentation if tab key presed, else emits the keyPressed signal

        :param event: QKeyEvent
        """
        # assert isinstance(event, QKeyEvent)
        event.stop = False
        # replace tabs by space
        if event.key() == Qt.Key_Tab:
            cursor = self.textCursor()
            assert isinstance(cursor, QTextCursor)
            if not cursor.hasSelection():
                # insert tab at cursor pos
                cursor.insertText(" " * self.editor().TAB_SIZE)
            else:
                # indent whole selection
                self.indent(self.editor().TAB_SIZE)
            event.stop = True
        self.keyPressed.emit(event)
        if not event.stop:
            QPlainTextEdit.keyPressEvent(self, event)
        self.postKeyPressed.emit(event)
Beispiel #29
0
class Overall(QWizardPage):
    def __init__(self, parent):
        super(Overall, self).__init__(parent)

        self.setTitle("Overall")
        self.setSubTitle("Describe the individual overall.")

        self.comments = QPlainTextEdit(self)
        self.comments.textChanged.connect(self.overall_changed)

        self.registerField("overall.comments*",
                           self.comments,
                           "plainText",
                           SIGNAL("textChanged()"))

        layout = QGridLayout(self)

        layout.addWidget(QLabel(self.tr("Comments:"), self), 0, 0)
        layout.addWidget(self.comments,                      0, 1)

    def overall_changed(self):
        if len(self.comments.toPlainText()) >= 257:
            self.comments.textCursor().deletePreviousChar()
    def __init__(self, text):
        super(GosubPopupWidget, self).__init__()
        self.setWindowFlags(Qt.ToolTip)
        layout = QVBoxLayout()

        if text:
            self.text = QPlainTextEdit()
            self.text.setPlainText(text)

        else:
            self.text = QLabel('Invalid Gosub')
            self.text.setStyleSheet('QLabel {color: green; font-size: 30px}')

        layout.addWidget(self.text)
        self.setLayout(layout)
        self.resize(500, 300)
    def __init__(self):
        super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.xmega = XMEGAProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("xmega-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.statusLine.append = self.statusLine.appendPlainText
        layout.addWidget(self.statusLine)

        self.xmega._logging = self.statusLine.append

        # Set dialog layout
        self.setLayout(layout)
Beispiel #32
0
    def __init__(self, parent):
        super(Overall, self).__init__(parent)

        self.setTitle("Overall")
        self.setSubTitle("Describe the individual overall.")

        self.comments = QPlainTextEdit(self)
        self.comments.textChanged.connect(self.overall_changed)

        self.registerField("overall.comments*",
                           self.comments,
                           "plainText",
                           SIGNAL("textChanged()"))

        layout = QGridLayout(self)

        layout.addWidget(QLabel(self.tr("Comments:"), self), 0, 0)
        layout.addWidget(self.comments,                      0, 1)
Beispiel #33
0
class Ui_MainWindow(object):
    
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.setFixedSize(800, 600)
        self.centralwidget = QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.FilterLbl = QLabel(self.centralwidget)
        self.FilterLbl.setGeometry(QtCore.QRect(30, 150, 60, 15))
        self.FilterLbl.setObjectName("FilterLbl")
        self.FilterCB = QComboBox(self.centralwidget)
        self.FilterCB.setGeometry(QtCore.QRect(450, 150, 100, 22))
        self.FilterCB.setObjectName("FilterCB")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")
        self.FilterCB.addItem("")         
        self.FilterTF = QLineEdit(self.centralwidget)
        self.FilterTF.setGeometry(QtCore.QRect(100, 150, 320, 20))        
        self.tableView = QTableWidget(self.centralwidget)
        self.tableView.setGeometry(QtCore.QRect(10, 180, 781, 511))
        self.tableView.setObjectName("tableView")
        self.tableView.setColumnCount(4)
        self.tableView.setRowCount(0)
        item = QTableWidgetItem("Cena za kg/l")
        self.tableView.setHorizontalHeaderItem(0, item)
        item = QTableWidgetItem("Cena ze kus")
        self.tableView.setHorizontalHeaderItem(1, item)
        item = QTableWidgetItem(u"Gramaž")
        self.tableView.setHorizontalHeaderItem(2, item)
        item = QTableWidgetItem("Popis")
        item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter|QtCore.Qt.AlignCenter)
        font = QtGui.QFont()
        font.setPointSize(8)
        item.setFont(font)
        self.tableView.setHorizontalHeaderItem(3, item)
        self.tableView.horizontalHeader().setStretchLastSection(True)
        
        self.SaveBtn = QPushButton(self.centralwidget)
        self.SaveBtn.setGeometry(QtCore.QRect(30, 10, 100, 23))
        self.SaveBtn.setObjectName("SaveBtn")
        self.PrintSelectedToFileBtn = QPushButton(self.centralwidget)
        self.PrintSelectedToFileBtn.setGeometry(QtCore.QRect(225, 10, 100, 23))        
        self.PrintSelectedToFileBtn.setObjectName("PrintSelectedToFileBtn")
        self.PriceForUnitTF = QLineEdit(self.centralwidget)
        self.PriceForUnitTF.setGeometry(QtCore.QRect(100, 70, 113, 20))
        self.PriceForUnitTF.setObjectName("PriceForUnitTF")
        self.PriceForUnitLbl = QLabel(self.centralwidget)
        self.PriceForUnitLbl.setGeometry(QtCore.QRect(30, 70, 60, 13))
        self.PriceForUnitLbl.setObjectName("PriceForUnitLbl")
        self.ArtikelTF = QLineEdit(self.centralwidget)
        self.ArtikelTF.setGeometry(QtCore.QRect(100, 100, 113, 20))
        self.ArtikelTF.setObjectName("ArtikelTF")
        self.ArtikelLbl = QLabel(self.centralwidget)
        self.ArtikelLbl.setGeometry(QtCore.QRect(30, 100, 46, 13))
        self.ArtikelLbl.setObjectName("ArtikelLbl")
        self.DescriptionLbl = QLabel(self.centralwidget)
        self.DescriptionLbl.setGeometry(QtCore.QRect(455, 70, 75, 13))
        self.DescriptionLbl.setObjectName("DescriptionLbl")
        self.UnitLbl = QLabel(self.centralwidget)
        self.UnitLbl.setGeometry(QtCore.QRect(250, 70, 60, 15))
        self.UnitLbl.setObjectName("UnitLbl")
        self.WeightLbl = QLabel(self.centralwidget)
        self.WeightLbl.setGeometry(QtCore.QRect(250, 100, 60, 13))
        self.WeightLbl.setObjectName("UnitLbl")
        self.WeightTF = QLineEdit(self.centralwidget)
        self.WeightTF.setGeometry(QtCore.QRect(320, 100, 100, 20))
        self.WeightTF.setObjectName("WeightTF")        
        self.UnitCB = QComboBox(self.centralwidget)
        self.UnitCB.setGeometry(QtCore.QRect(320, 70, 100, 22))
        self.UnitCB.setObjectName("UnitCB")
        self.UnitCB.addItem("")
        self.UnitCB.addItem("")
        self.DescriptionTE = QPlainTextEdit(self.centralwidget)
        self.DescriptionTE.setGeometry(QtCore.QRect(540, 30, 241, 61))
        self.DescriptionTE.setObjectName("DescriptionTE")
        self.PrintToFileBtn = QPushButton(self.centralwidget)
        self.PrintToFileBtn.setGeometry(QtCore.QRect(140, 10, 75, 23))
        self.PrintToFileBtn.setObjectName("PrintToFileBtn")
        self.AddRecordBtn = QPushButton(self.centralwidget)
        self.AddRecordBtn.setGeometry(QtCore.QRect(450, 100, 75, 23))
        self.AddRecordBtn.setObjectName("AddRecordBtn")        
        self.SaveChangeBtn = QPushButton(self.centralwidget)
        self.SaveChangeBtn.setGeometry(QtCore.QRect(550, 100, 75, 23))
        self.SaveChangeBtn.setObjectName("SaveChangeBtn")
        self.DeleteRecordBtn = QPushButton(self.centralwidget)
        self.DeleteRecordBtn.setGeometry(QtCore.QRect(650, 100, 75, 23))
        self.DeleteRecordBtn.setObjectName("DeleteRecordBtn")
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName("menubar")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
   
        self.FilterTF.textChanged.connect(self.on_lineEdit_textChanged)
        self.FilterCB.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)
        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def myFilter(self,col=None):
        filt = self.FilterTF.text()
        for ix in range(self.tableView.rowCount()):
            match = False
            if col == None:
                for jx in range(self.tableView.columnCount()):
                    item = self.tableView.item(ix,jx)
                    if filt in item.text():
                        match = True
                        break
                self.tableView.setRowHidden(ix, not match)
            else:
                item = self.tableView.item(ix, col)
                if filt in item.text():
                    match = True
                self.tableView.setRowHidden(ix, not match)

    #@QtCore.pyqtSlot(str)
    def on_lineEdit_textChanged(self, text):
        self.myFilter()

    #@QtCore.pyqtSlot(int)
    def on_comboBox_currentIndexChanged(self, index):
        self.myFilter(col=index)
        
    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "Stitky - {0}".format(__version__)))
        self.SaveBtn.setText(_translate("MainWindow", "Uloz stav tabulky"))
        self.PrintSelectedToFileBtn.setText(_translate("MainWindow", "Tisk vybranych"))
        self.PriceForUnitLbl.setText(_translate("MainWindow", "Cena za kus:"))
        self.ArtikelLbl.setText(_translate("MainWindow", "Artikl:"))
        self.DescriptionLbl.setText(_translate("MainWindow", "Popis produktu:"))
        self.UnitLbl.setText(_translate("MainWindow", "Jednotka:"))
        self.FilterLbl.setText(_translate("MainWindow", "Filtr:"))
        self.WeightLbl.setText(_translate("MainWindow", "Hmotnost:"))
        self.PrintToFileBtn.setText(_translate("MainWindow", "Vytvor txt"))
        self.SaveChangeBtn.setText(_translate("MainWindow", "Uloz zmeny"))
        self.AddRecordBtn.setText(_translate("MainWindow", "Pridej zaznam"))
        self.DeleteRecordBtn.setText(_translate("MainWindow", "Smaz zaznam"))
        self.UnitCB.setItemText(0, _translate("MainWindow", "g"))
        self.UnitCB.setItemText(1, _translate("MainWindow", "ml"))
        self.FilterCB.setItemText(0, _translate("MainWindow", "Cena za kg/l"))
        self.FilterCB.setItemText(1, _translate("MainWindow", "Cena ze kus"))
        self.FilterCB.setItemText(2, _translate("MainWindow", "Gramaz"))
        self.FilterCB.setItemText(3, _translate("MainWindow", "Popis"))
Beispiel #34
0
  def setupUi(self, MainWindow):
      MainWindow.setObjectName("MainWindow")
      MainWindow.setFixedSize(800, 600)
      self.centralwidget = QWidget(MainWindow)
      self.centralwidget.setObjectName("centralwidget")
      self.FilterLbl = QLabel(self.centralwidget)
      self.FilterLbl.setGeometry(QtCore.QRect(30, 150, 60, 15))
      self.FilterLbl.setObjectName("FilterLbl")
      self.FilterCB = QComboBox(self.centralwidget)
      self.FilterCB.setGeometry(QtCore.QRect(450, 150, 100, 22))
      self.FilterCB.setObjectName("FilterCB")
      self.FilterCB.addItem("")
      self.FilterCB.addItem("")
      self.FilterCB.addItem("")
      self.FilterCB.addItem("")         
      self.FilterTF = QLineEdit(self.centralwidget)
      self.FilterTF.setGeometry(QtCore.QRect(100, 150, 320, 20))        
      self.tableView = QTableWidget(self.centralwidget)
      self.tableView.setGeometry(QtCore.QRect(10, 180, 781, 511))
      self.tableView.setObjectName("tableView")
      self.tableView.setColumnCount(4)
      self.tableView.setRowCount(0)
      item = QTableWidgetItem("Cena za kg/l")
      self.tableView.setHorizontalHeaderItem(0, item)
      item = QTableWidgetItem("Cena ze kus")
      self.tableView.setHorizontalHeaderItem(1, item)
      item = QTableWidgetItem(u"Gramaž")
      self.tableView.setHorizontalHeaderItem(2, item)
      item = QTableWidgetItem("Popis")
      item.setTextAlignment(QtCore.Qt.AlignHCenter|QtCore.Qt.AlignVCenter|QtCore.Qt.AlignCenter)
      font = QtGui.QFont()
      font.setPointSize(8)
      item.setFont(font)
      self.tableView.setHorizontalHeaderItem(3, item)
      self.tableView.horizontalHeader().setStretchLastSection(True)
      
      self.SaveBtn = QPushButton(self.centralwidget)
      self.SaveBtn.setGeometry(QtCore.QRect(30, 10, 100, 23))
      self.SaveBtn.setObjectName("SaveBtn")
      self.PrintSelectedToFileBtn = QPushButton(self.centralwidget)
      self.PrintSelectedToFileBtn.setGeometry(QtCore.QRect(225, 10, 100, 23))        
      self.PrintSelectedToFileBtn.setObjectName("PrintSelectedToFileBtn")
      self.PriceForUnitTF = QLineEdit(self.centralwidget)
      self.PriceForUnitTF.setGeometry(QtCore.QRect(100, 70, 113, 20))
      self.PriceForUnitTF.setObjectName("PriceForUnitTF")
      self.PriceForUnitLbl = QLabel(self.centralwidget)
      self.PriceForUnitLbl.setGeometry(QtCore.QRect(30, 70, 60, 13))
      self.PriceForUnitLbl.setObjectName("PriceForUnitLbl")
      self.ArtikelTF = QLineEdit(self.centralwidget)
      self.ArtikelTF.setGeometry(QtCore.QRect(100, 100, 113, 20))
      self.ArtikelTF.setObjectName("ArtikelTF")
      self.ArtikelLbl = QLabel(self.centralwidget)
      self.ArtikelLbl.setGeometry(QtCore.QRect(30, 100, 46, 13))
      self.ArtikelLbl.setObjectName("ArtikelLbl")
      self.DescriptionLbl = QLabel(self.centralwidget)
      self.DescriptionLbl.setGeometry(QtCore.QRect(455, 70, 75, 13))
      self.DescriptionLbl.setObjectName("DescriptionLbl")
      self.UnitLbl = QLabel(self.centralwidget)
      self.UnitLbl.setGeometry(QtCore.QRect(250, 70, 60, 15))
      self.UnitLbl.setObjectName("UnitLbl")
      self.WeightLbl = QLabel(self.centralwidget)
      self.WeightLbl.setGeometry(QtCore.QRect(250, 100, 60, 13))
      self.WeightLbl.setObjectName("UnitLbl")
      self.WeightTF = QLineEdit(self.centralwidget)
      self.WeightTF.setGeometry(QtCore.QRect(320, 100, 100, 20))
      self.WeightTF.setObjectName("WeightTF")        
      self.UnitCB = QComboBox(self.centralwidget)
      self.UnitCB.setGeometry(QtCore.QRect(320, 70, 100, 22))
      self.UnitCB.setObjectName("UnitCB")
      self.UnitCB.addItem("")
      self.UnitCB.addItem("")
      self.DescriptionTE = QPlainTextEdit(self.centralwidget)
      self.DescriptionTE.setGeometry(QtCore.QRect(540, 30, 241, 61))
      self.DescriptionTE.setObjectName("DescriptionTE")
      self.PrintToFileBtn = QPushButton(self.centralwidget)
      self.PrintToFileBtn.setGeometry(QtCore.QRect(140, 10, 75, 23))
      self.PrintToFileBtn.setObjectName("PrintToFileBtn")
      self.AddRecordBtn = QPushButton(self.centralwidget)
      self.AddRecordBtn.setGeometry(QtCore.QRect(450, 100, 75, 23))
      self.AddRecordBtn.setObjectName("AddRecordBtn")        
      self.SaveChangeBtn = QPushButton(self.centralwidget)
      self.SaveChangeBtn.setGeometry(QtCore.QRect(550, 100, 75, 23))
      self.SaveChangeBtn.setObjectName("SaveChangeBtn")
      self.DeleteRecordBtn = QPushButton(self.centralwidget)
      self.DeleteRecordBtn.setGeometry(QtCore.QRect(650, 100, 75, 23))
      self.DeleteRecordBtn.setObjectName("DeleteRecordBtn")
      MainWindow.setCentralWidget(self.centralwidget)
      self.menubar = QMenuBar(MainWindow)
      self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
      self.menubar.setObjectName("menubar")
      MainWindow.setMenuBar(self.menubar)
      self.statusbar = QStatusBar(MainWindow)
      self.statusbar.setObjectName("statusbar")
 
      self.FilterTF.textChanged.connect(self.on_lineEdit_textChanged)
      self.FilterCB.currentIndexChanged.connect(self.on_comboBox_currentIndexChanged)
      self.retranslateUi(MainWindow)
      QtCore.QMetaObject.connectSlotsByName(MainWindow)
Beispiel #35
0
class ChatWidget(QWidget):
    """
    A chatting widget.
    """

    #: A notification (not chat!) message for the user
    message = Signal(str)

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setLayout(QVBoxLayout(self))
        self.text_display = QPlainTextEdit(self)
        self.text_display.setReadOnly(True)
        self.layout().addWidget(self.text_display)
        self.text_input = QLineEdit(self)
        self.text_input.returnPressed.connect(self.send_text)
        self.layout().addWidget(self.text_input)
        QWidget.setTabOrder(self.text_input, self.text_display)
        self.setEnabled(False)
        self.message.emit('Not connected')
        self._connection = None

    @property
    def connected(self):
        """
        ``True``, if this chat widget is connected to some server, ``False``
        otherwise
        """
        return (self._connection and
                self._connection.state() == QTcpSocket.ConnectedState)

    @property
    def connection(self):
        """
        The connection used by this widget.
        """
        return self._connection

    @connection.setter
    def connection(self, connection):
        self._connection = connection
        if not self.connected:
            # wait for connection, if the connection isn't available yet
            self._connection.connected.connect(self._enable_chat)
        else:
            self._enable_chat()
        # handle errors, disconnects and incoming data
        self._connection.error.connect(self._handle_error)
        self._connection.disconnected.connect(self._handle_disconnect)
        self._connection.readyRead.connect(self._receive_text)

    def _enable_chat(self):
        """
        Enable the chat widget for chatting.
        """
        self.message.emit('connected')
        self.setEnabled(True)
        # remove all text from the previous connection
        self.text_display.clear()

    def _handle_disconnect(self):
        """
        Handle a disconnect.
        """
        self.message.emit('disconnected')
        # disable the user interface
        self.setEnabled(False)
        # and disconnect from all slots and eventually delete the connection
        # itself
        self._connection.readyRead.disconnect(self._receive_text)
        self._connection.deleteLater()
        self._connection = None

    def _handle_error(self):
        self.message.emit(self._connection.errorString())

    def _receive_text(self):
        text = _stream_for_connection(self.connection).readAll()
        self.text_display.insertPlainText('{0}'.format(text))

    def send_text(self, text=None):
        """
        Send ``text`` over the connection of this widget.  Does nothing, if
        the widget is not connected.

        If ``text`` is ``None`` (the default), use the current input form
        the user.
        """
        if self.connected:
            stream = _stream_for_connection(self.connection)
            if not text:
                text = self.text_input.text()
                self.text_input.clear()
            stream << text
Beispiel #36
0
    def _create_changes(self):
        c=QPlainTextEdit()
        c.setReadOnly(True)
        txt=''
        for i in range(10):
            for a,d,m in self.changes:
                txt+='<p>{} {}</p><p><b><pre> {}</pre></b></p>'.format(a,d, m)

        c.appendHtml(txt)
        cur=c.textCursor()
        cur.movePosition(QtGui.QTextCursor.Start)
        c.setTextCursor(cur)
        c.ensureCursorVisible()
        return c
Beispiel #37
0
class MainWindow(QWidget):
    def __init__(self, fixtures_folder, parent=None):
        QWidget.__init__(self, parent)
        self.current_fixture = None
        self.fixtures_folder = fixtures_folder
        self.setWindowTitle("Frangitron DMX program editor")

        self.text = QPlainTextEdit()
        font = QFont("Monospace")
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(16)
        self.text.setFont(font)
        self.text.setStyleSheet(
            "color: white; background-color: rgb(30, 30, 30)")

        self.combo_fixture = QComboBox()

        self.frame_programs = QWidget()
        self.checkboxes_programs = list()
        self.layout_programs = QGridLayout(self.frame_programs)

        self.spinner_offset = QSpinBox()
        self.spinner_offset.setMinimum(1)
        self.spinner_offset.setMaximum(512)
        self.spinner_offset.setValue(1)
        self.spinner_offset.valueChanged.connect(self.address_changed)

        self.doc = QPlainTextEdit()
        self.doc.setReadOnly(True)
        self.doc.setFont(font)

        self.status = QLabel()

        layout = QGridLayout(self)
        layout.addWidget(self.combo_fixture, 0, 1)
        layout.addWidget(self.spinner_offset, 0, 2)
        layout.addWidget(self.frame_programs, 1, 1)
        layout.addWidget(self.text, 0, 0, 3, 1)
        layout.addWidget(self.doc, 2, 1, 1, 2)
        layout.addWidget(self.status, 3, 0, 1, 3)
        layout.setColumnStretch(0, 60)
        layout.setColumnStretch(1, 40)

        self.resize(1280, 800)

        self.streamer = Streamer(self.fixtures_folder)

        self.combo_fixture.addItems(sorted(self.streamer.fixtures))
        self.combo_fixture.currentIndexChanged.connect(self.fixture_changed)

        self.timer = QTimer()
        self.timer.timeout.connect(self.tick)
        self.timer.start(500.0 / FRAMERATE)
        self.should_reload = True

        self.fixture_changed()

    def selected_programs(self):
        return [
            chk.text() for chk in self.checkboxes_programs if chk.isChecked()
        ]

    def update_programs(self):
        selected_programs = self.selected_programs()

        for checkbox_program in self.checkboxes_programs:
            self.layout_programs.removeWidget(checkbox_program)
            checkbox_program.deleteLater()
        self.checkboxes_programs = list()

        for i, program_name in enumerate(
                sorted(self.current_fixture.programs.keys())):
            column = i // 4
            row = i % 4

            new_checkbox = QCheckBox(program_name)
            new_checkbox.setChecked(program_name in selected_programs)

            self.layout_programs.addWidget(new_checkbox, row, column)
            self.checkboxes_programs.append(new_checkbox)

    def address_changed(self):
        self.current_fixture.address = self.spinner_offset.value()
        self.doc.setPlainText(self.current_fixture.doc())
        self.update_programs()

    def fixture_changed(self):
        self.current_fixture = self.streamer.fixtures[
            self.combo_fixture.currentText()]
        self.address_changed()
        self.streamer.reset_expressions()
        with open(self.current_fixture.programs_filepath, 'r') as f_programs:
            self.text.setPlainText(f_programs.read())

    def tick(self):
        if self.should_reload:
            self.current_fixture.reload_programs()
            self.update_programs()
            self.streamer.reset_state()
            program = PROGRAM.replace('__fixture__', self.current_fixture.name)
            program = program.replace('__address__',
                                      str(self.current_fixture.address))
            program = program.replace(
                '__programs__', ", ".join([
                    '"{}"'.format(prog) for prog in self.selected_programs()
                ]))
            self.streamer.load(programs_source=program)
            self.streamer.program_clicked("1")

        else:
            state = self.streamer.state

            if state:
                self.status.setStyleSheet(
                    "background-color: green; color: white; padding: 5px")
                self.status.setText(state.context)
            else:
                self.status.setStyleSheet(
                    "background-color: red; color: white; padding: 5px")
                self.status.setText("{} : {}".format(state.context,
                                                     state.exception))

            if self.current_fixture is None: return

            with open(self.current_fixture.programs_filepath,
                      'w') as f_programs:
                f_programs.write(self.text.toPlainText())

        self.should_reload = not self.should_reload

    def closeEvent(self, event):
        self.timer.stop()
        self.streamer.load(programs_source="")
        self.streamer.program_clicked("1")
        sleep(2.0 / float(FRAMERATE))
        self.streamer.stop()
        event.accept()
Beispiel #38
0
    def __init__(self):
        QMainWindow.__init__(self)

        # the user interface, consisting of a progress bar above a plain
        # text edit, which logs all actions.
        container = QWidget(self)
        container.setLayout(QVBoxLayout(container))
        self.setCentralWidget(container)
        progressbar = QProgressBar(container)
        container.layout().addWidget(progressbar)
        log = QPlainTextEdit(container)
        container.layout().addWidget(log)

        # the actual worker thread
        counter = Counter(100, self)

        # an action to quit the windows
        exit = QAction(QIcon.fromTheme('application-exit'), 'exit', self)

        # add two actions to start and stop the worker to the toolbar of the
        # main window
        start_counting = QAction(QIcon.fromTheme('media-playback-start'),
                                 'Start counting', self)
        stop_counting = QAction(QIcon.fromTheme('media-playback-stop'),
                                'Stop counting', self)
        # initially no counter runs, so we can disable the stop action
        stop_counting.setEnabled(False)

        # add all actions to a toolbar
        actions = self.addToolBar('Actions')
        actions.addAction(exit)
        actions.addSeparator()
        actions.addAction(start_counting)
        actions.addAction(stop_counting)

        # quit the application, if the quit action is triggered
        exit.triggered.connect(QApplication.instance().quit)

        # start and stop the counter, if the corresponding actions are
        # triggered.
        start_counting.triggered.connect(counter.start)
        stop_counting.triggered.connect(counter.stop)

        # adjust the minimum and the maximum of the progress bar, if
        # necessary.  Not really required in this snippet, but added for the
        # purpose of demonstrating it
        counter.minimumChanged.connect(progressbar.setMinimum)
        counter.maximumChanged.connect(progressbar.setMaximum)

        # switch the enabled states of the actions according to whether the
        # worker is running or not
        counter.started.connect(partial(start_counting.setEnabled, False))
        counter.started.connect(partial(stop_counting.setEnabled, True))
        counter.finished.connect(partial(start_counting.setEnabled, True))
        counter.finished.connect(partial(stop_counting.setEnabled, False))

        # update the progess bar continuously
        counter.progress.connect(progressbar.setValue)

        # log all actions in our logging widget
        counter.started.connect(
            partial(self.statusBar().showMessage, 'Counting'))
        counter.finished.connect(partial(self.statusBar().showMessage, 'Done'))
        # log a forced stop
        stop_counting.triggered.connect(partial(log.appendPlainText,
                                                'Stopped'))
        # log all counted values
        counter.progress.connect(lambda v: log.appendPlainText(str(v)))

        # and finally show the current state in the status bar.
        counter.started.connect(partial(log.appendPlainText, 'Counting'))
        counter.finished.connect(partial(log.appendPlainText, 'Done'))
Beispiel #39
0
class Truss(QMainWindow):
    def __init__(self, parent=None):
        super(Truss, self).__init__(parent)
        self.resize(800, 600)
        self.filename = None
        self.filetuple = None
        self.dirty = False  # Refers to Data Page only.
        centralwidget = QWidget(self)
        gridLayout = QGridLayout(centralwidget)
        self.tabWidget = QTabWidget(centralwidget)
        self.tab = QWidget()
        font = QFont()
        font.setFamily("Courier 10 Pitch")
        font.setPointSize(12)
        self.tab.setFont(font)
        gridLayout_3 = QGridLayout(self.tab)
        self.plainTextEdit = QPlainTextEdit(self.tab)
        gridLayout_3.addWidget(self.plainTextEdit, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab, "")
        self.tab_2 = QWidget()
        self.tab_2.setFont(font)
        gridLayout_2 = QGridLayout(self.tab_2)
        self.plainTextEdit_2 = QPlainTextEdit(self.tab_2)
        gridLayout_2.addWidget(self.plainTextEdit_2, 0, 0, 1, 1)
        self.tabWidget.addTab(self.tab_2, "")
        gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
        self.setCentralWidget(centralwidget)
        menubar = QMenuBar(self)
        menubar.setGeometry(QRect(0, 0, 800, 29))
        menu_File = QMenu(menubar)
        self.menu_Solve = QMenu(menubar)
        self.menu_Help = QMenu(menubar)
        self.setMenuBar(menubar)
        self.statusbar = QStatusBar(self)
        self.setStatusBar(self.statusbar)
        self.action_New = QAction(self)
        self.actionSave_As = QAction(self)
        self.action_Save = QAction(self)
        self.action_Open = QAction(self)
        self.action_Quit = QAction(self)
        self.action_About = QAction(self)
        self.actionShow_CCPL = QAction(self)
        self.action_Solve = QAction(self)
        self.action_CCPL = QAction(self)
        self.action_Help = QAction(self)
        menu_File.addAction(self.action_New)
        menu_File.addAction(self.action_Open)
        menu_File.addAction(self.actionSave_As)
        menu_File.addAction(self.action_Save)
        menu_File.addSeparator()
        menu_File.addAction(self.action_Quit)
        self.menu_Solve.addAction(self.action_Solve)
        self.menu_Help.addAction(self.action_About)
        self.menu_Help.addAction(self.action_CCPL)
        self.menu_Help.addAction(self.action_Help)
        menubar.addAction(menu_File.menuAction())
        menubar.addAction(self.menu_Solve.menuAction())
        menubar.addAction(self.menu_Help.menuAction())
        self.setWindowTitle("Main Window")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab),\
                                   "Data Page")
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),\
                                   "Solution Page")
        menu_File.setTitle("&File")
        self.menu_Solve.setTitle("&Solve")
        self.menu_Help.setTitle("&Help")
        self.tabWidget.setCurrentIndex(0)
        self.action_New.setText("&New")
        self.action_Open.setText("&Open")
        self.actionSave_As.setText("Save &As")
        self.action_Save.setText("&Save")
        self.action_Quit.setText("&Quit")
        self.action_Solve.setText("&Solve")
        self.action_About.setText("&About")
        self.action_CCPL.setText("&CCPL")
        self.action_Help.setText("&Help")
        self.action_Quit.triggered.connect(self.close)
        allToolBar = self.addToolBar("AllToolBar")
        allToolBar.setObjectName("AllToolBar")
        self.addActions(allToolBar, (self.action_Open, self.actionSave_As,\
                        self.action_Save, self.action_Solve,\
                        self.action_Quit ))
        self.action_New.triggered.connect(self.fileNew)
        self.action_Open.triggered.connect(self.fileOpen)
        self.actionSave_As.triggered.connect(self.fileSaveAs)
        self.action_Save.triggered.connect(self.fileSave)
        self.action_Solve.triggered.connect(self.trussSolve)
        self.action_About.triggered.connect(self.aboutBox)
        self.action_CCPL.triggered.connect(self.displayCCPL)
        self.action_Help.triggered.connect(self.help)
        self.plainTextEdit.textChanged.connect(self.setDirty)
        self.action_New = self.editAction(self.action_New, None,\
                            'ctrl+N', 'filenew', 'New File.')
        self.action_Open = self.editAction(self.action_Open, None, 'ctrl+O',
                                           'fileopen', 'Open File.')
        self.actionSave_As = self.editAction(self.actionSave_As,\
                            None, 'ctrl+A', 'filesaveas',\
                            'Save and Name File.')
        self.action_Save = self.editAction(self.action_Save, None, 'ctrl+S',
                                           'filesave', 'Save File.')
        self.action_Solve = self.editAction(self.action_Solve, None, 'ctrl+L',
                                            'solve', 'Solve Structure.')
        self.action_About = self.editAction(self.action_About, None, 'ctrl+B',
                                            'about', 'Pop About Box.')
        self.action_CCPL = self.editAction(self.action_CCPL, None, 'ctrl+G',
                                           'licence', 'Show Licence')
        self.action_Help = self.editAction(self.action_Help, None, 'ctrl+H',
                                           'help', 'Show Help Page.')
        self.action_Quit = self.editAction(self.action_Quit, None, 'ctrl+Q',
                                           'quit', 'Quit the program.')
        self.plainTextEdit_2.setReadOnly(True)

    def setDirty(self):
        '''On change of text in textEdit window, set the flag
        "dirty" to True'''
        index = self.tabWidget.currentIndex()
        if index is not 0:
            return
        if self.dirty:
            return True
        self.dirty = True
        self.updateStatus('self.dirty set to True')

    def clearDirty(self):
        'Clear dirty flag'
        self.dirty = False

    def fileNew(self):
        '''Clear both Data Page and Solution Page.'''
        self.plainTextEdit.setPlainText(' ')
        self.plainTextEdit_2.setPlainText(' ')
        self.clearDirty(self)

    def okToContinue(self):
        if self.dirty:
            reply = QMessageBox.question(
                self, "Data Loader - Unsaved Changes", "Save unsaved changes?",
                QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel)
            if reply == QMessageBox.Cancel:
                return False
            elif reply == QMessageBox.Yes:
                self.clearDirty()
                return self.fileSave()
        return True

    def okRead(self):
        'Pop-up a warning message.'
        reply = QMessageBox.warning(
            self, "Warning",
            '''\nFile Open and Save is possible only in Data Page!
\n\(Use SaveAs for Solution Page)''', QMessageBox.Ok)
        return True

    def fileOpen(self):
        '''Open a file in Data Page (with index == 0)'''
        if self.tabWidget.currentIndex():
            self.okRead()
            return
        if not self.okToContinue():
            return
        dir = (os.path.dirname(self.filename)
               if self.filename is not None else ".")
        self.filetuple = QFileDialog.getOpenFileName(self,\
                        "Open File", dir, \
                        "Data (*.dat *.txt)\nAll Files (*.*)")
        self.filename = self.filetuple[0]
        fname = self.filename
        #  QFileDialog returns a tuple x with x[0] = file name and
        #  x[1] = type of filter.
        if fname:
            self.loadFile(fname)
            self.filename = fname
            self.updateStatus('New file opened.')

    def loadFile(self, fname=None):
        fl = open(fname)
        text = fl.read()
        self.plainTextEdit.setPlainText(text)
        self.dirty = False

    def fileSave(self):
        '''Save file with current file name.'''
        if self.tabWidget.currentIndex():
            self.okRead()
            return
        if self.filename is None:
            return self.fileSaveAs()
        else:
            flname = self.filename
            if flname:
                try:
                    with open(flname, 'w') as fl:
                        fl.write(tempText)
                    self.dirty = False
                    self.updateStatus('File saved.')
                except IOError:
                    self.dirty = True
                    self.updateStatus('File not saved.')
                    return False
                return True
            else:
                self.updateStatus('Failed to save... ')
                return False
        self.filename = None
        self.dirty = False

    def fileSaveAs(self):
        '''Save file with a new name.'''
        qpr = self.qprintline
        fname = self.filename if self.filename is not None else\
        "NoName"
        self.filetuple = QFileDialog.getSaveFileName(
            self, "Truss program - Save File", fname, "Data File (*.*)")
        flname = self.filetuple[0]
        index = self.tabWidget.currentIndex()
        if index == 0:
            self.filename = flname
            if flname:
                fl = open(flname, 'w')
                tempText = self.plainTextEdit.toPlainText()
                fl.write(tempText)
                fl.close()
                self.dirty = False
                self.updateStatus('File saved.')
        elif index == 1:
            if flname:
                fl = open(flname, 'w')
                tempText = self.plainTextEdit_2.toPlainText()
                fl.write(tempText)
                fl.close()

    def trussSolve(self):
        '''Solve a statically determinate truss, specified in
        Data Page and display the results in the Solution Page.
        To start, make a copy of the Data Page with a header all
        shown on the Data Page.'''
        printline = self.qprintline
        dataBall = self.plainTextEdit.toPlainText()
        self.plainTextEdit_2.clear()
        printline('================================')
        flbase = os.path.basename(self.filename)
        printline('SOLUTION FOR ' + flbase)
        printline('================================')
        dataBall = self.plainTextEdit.toPlainText()
        ncrunch.main(printline, self.filename, dataBall)

    def aboutBox(self):
        '''Popup a box with about message.'''
        QMessageBox.about(self, "About PySide, Platform and the like",
                """<b>Part of Structural Analysis.</b> v %s
                <p>Copyright &copy; 2011 Algis Kabaila. 
                All rights reserved in accordance with
                Creative Commons Attribution Licence (CCPL) v3
                or later - NO WARRANTIES!
                <p>This progam finds bar forces in 
                statically determinate trusses.                
                <p>Python %s -  PySide version %s - Qt version %s on\
                %s""" % (__version__, platform.python_version(),\
                PySide.__version__,  PySide.QtCore.__version__,
                platform.system()))

    def displayCCPL(self):
        '''Read and display CCPL licence.'''
        self.plainTextEdit.setPlainText(open('CCPL.txt').read())
        self.dirty = False
        self.filename = 'COPYING.txt'
        self.updateStatus('CCPL displayed.')

    def help(self):
        '''Read and display a help file- currently the README.txt.'''
        self.plainTextEdit.setPlainText(open('README.md').read())
        self.dirty = False
        self.filename = 'README.txt'
        self.updateStatus('README displayed.')

    def addActions(self, target, actions):
        '''Actions are added to Tool Bar.'''
        for action in actions:
            if action is None:
                target.addSeparator()
            else:
                target.addAction(action)

    def editAction(self,
                   action,
                   slot=None,
                   shortcut=None,
                   icon=None,
                   tip=None):
        '''This method adds to action: icon, shortcut, ToolTip,\
        StatusTip and can connect triggered action to slot '''
        if icon is not None:
            action.setIcon(QIcon(":/%s.png" % (icon)))
        if shortcut is not None:
            action.setShortcut(shortcut)
        if tip is not None:
            action.setToolTip(tip)
            action.setStatusTip(tip)
        if slot is not None:
            action.triggered.connect(slot)
        return action

    def qreadline(self, lineNo):
        '''Read one line from Data Page (lineNo starts with 0)'''
        return str(self.plainTextEdit.document().\
            findBlockByLineNumber(lineNo).text()).rstrip()

    def qprintline(self, line):
        '''Append one line to Solution Page.'''
        self.plainTextEdit_2.appendPlainText(line.rstrip())

    def updateStatus(self, message):
        '''Keep status current.'''
        if self.filename is not None:
            flbase = os.path.basename(self.filename)
            self.setWindowTitle(str("Truss Analysis - " +\
                                         flbase + "[*]") )
            self.statusBar().showMessage(message, 5000)
            self.setWindowModified(self.dirty)
    def __init__(self):
        super(AVRProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)

        self.avr = AVRProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite AVR Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("avr-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        layoutFuse = QHBoxLayout()

        readFuseBut = QPushButton("Read Fuses")
        readFuseBut.clicked.connect(self.readFuses)
        writeFuseBut = QPushButton("Write Fuses")
        writeFuseBut.clicked.connect(self.writeFuses)

        self.lowfuseLine = QtFixes.QLineEdit("?")
        self.lowfuseLine.setMaxLength(2)
        self.lowfuseLine.setFixedWidth(25)
        self.highfuseLine = QtFixes.QLineEdit("?")
        self.highfuseLine.setMaxLength(2)
        self.highfuseLine.setFixedWidth(25)
        self.extfuseLine = QtFixes.QLineEdit("?")
        self.extfuseLine.setMaxLength(2)
        self.extfuseLine.setFixedWidth(25)

        # Don't allow use to change these fuses
        self.highfuseLine.setReadOnly(True)
        self.extfuseLine.setReadOnly(True)

        layoutFuse.addWidget(readFuseBut)
        layoutFuse.addWidget(QLabel("LOW:"))
        layoutFuse.addWidget(self.lowfuseLine)
        layoutFuse.addWidget(QLabel("HIGH:"))
        layoutFuse.addWidget(self.highfuseLine)
        layoutFuse.addWidget(QLabel("EXT:"))
        layoutFuse.addWidget(self.extfuseLine)
        layoutFuse.addWidget(writeFuseBut)
        layout.addLayout(layoutFuse)

        layoutExtra = QHBoxLayout()
        self.clockMode = QPushButton("Enable Slow Clock Mode")
        self.clockMode.setCheckable(True)
        self.clockMode.clicked.connect(self.toggleSlowClock)
        layoutExtra.addWidget(self.clockMode)
        layoutExtra.addStretch()
        layout.addLayout(layoutExtra)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.statusLine.append = self.statusLine.appendPlainText
        layout.addWidget(self.statusLine)

        self.avr._logging = self.statusLine.append

        # Set dialog layout
        self.setLayout(layout)
Beispiel #41
0
 def __init__(self, parent=None):
     super(Truss, self).__init__(parent)
     self.resize(800, 600)
     self.filename = None
     self.filetuple = None
     self.dirty = False  # Refers to Data Page only.
     centralwidget = QWidget(self)
     gridLayout = QGridLayout(centralwidget)
     self.tabWidget = QTabWidget(centralwidget)
     self.tab = QWidget()
     font = QFont()
     font.setFamily("Courier 10 Pitch")
     font.setPointSize(12)
     self.tab.setFont(font)
     gridLayout_3 = QGridLayout(self.tab)
     self.plainTextEdit = QPlainTextEdit(self.tab)
     gridLayout_3.addWidget(self.plainTextEdit, 0, 0, 1, 1)
     self.tabWidget.addTab(self.tab, "")
     self.tab_2 = QWidget()
     self.tab_2.setFont(font)
     gridLayout_2 = QGridLayout(self.tab_2)
     self.plainTextEdit_2 = QPlainTextEdit(self.tab_2)
     gridLayout_2.addWidget(self.plainTextEdit_2, 0, 0, 1, 1)
     self.tabWidget.addTab(self.tab_2, "")
     gridLayout.addWidget(self.tabWidget, 0, 0, 1, 1)
     self.setCentralWidget(centralwidget)
     menubar = QMenuBar(self)
     menubar.setGeometry(QRect(0, 0, 800, 29))
     menu_File = QMenu(menubar)
     self.menu_Solve = QMenu(menubar)
     self.menu_Help = QMenu(menubar)
     self.setMenuBar(menubar)
     self.statusbar = QStatusBar(self)
     self.setStatusBar(self.statusbar)
     self.action_New = QAction(self)
     self.actionSave_As = QAction(self)
     self.action_Save = QAction(self)
     self.action_Open = QAction(self)
     self.action_Quit = QAction(self)
     self.action_About = QAction(self)
     self.actionShow_CCPL = QAction(self)
     self.action_Solve = QAction(self)
     self.action_CCPL = QAction(self)
     self.action_Help = QAction(self)
     menu_File.addAction(self.action_New)
     menu_File.addAction(self.action_Open)
     menu_File.addAction(self.actionSave_As)
     menu_File.addAction(self.action_Save)
     menu_File.addSeparator()
     menu_File.addAction(self.action_Quit)
     self.menu_Solve.addAction(self.action_Solve)
     self.menu_Help.addAction(self.action_About)
     self.menu_Help.addAction(self.action_CCPL)
     self.menu_Help.addAction(self.action_Help)
     menubar.addAction(menu_File.menuAction())
     menubar.addAction(self.menu_Solve.menuAction())
     menubar.addAction(self.menu_Help.menuAction())
     self.setWindowTitle("Main Window")
     self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab),\
                                "Data Page")
     self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2),\
                                "Solution Page")
     menu_File.setTitle("&File")
     self.menu_Solve.setTitle("&Solve")
     self.menu_Help.setTitle("&Help")
     self.tabWidget.setCurrentIndex(0)
     self.action_New.setText("&New")
     self.action_Open.setText("&Open")
     self.actionSave_As.setText("Save &As")
     self.action_Save.setText("&Save")
     self.action_Quit.setText("&Quit")
     self.action_Solve.setText("&Solve")
     self.action_About.setText("&About")
     self.action_CCPL.setText("&CCPL")
     self.action_Help.setText("&Help")
     self.action_Quit.triggered.connect(self.close)
     allToolBar = self.addToolBar("AllToolBar")
     allToolBar.setObjectName("AllToolBar")
     self.addActions(allToolBar, (self.action_Open, self.actionSave_As,\
                     self.action_Save, self.action_Solve,\
                     self.action_Quit ))
     self.action_New.triggered.connect(self.fileNew)
     self.action_Open.triggered.connect(self.fileOpen)
     self.actionSave_As.triggered.connect(self.fileSaveAs)
     self.action_Save.triggered.connect(self.fileSave)
     self.action_Solve.triggered.connect(self.trussSolve)
     self.action_About.triggered.connect(self.aboutBox)
     self.action_CCPL.triggered.connect(self.displayCCPL)
     self.action_Help.triggered.connect(self.help)
     self.plainTextEdit.textChanged.connect(self.setDirty)
     self.action_New = self.editAction(self.action_New, None,\
                         'ctrl+N', 'filenew', 'New File.')
     self.action_Open = self.editAction(self.action_Open, None, 'ctrl+O',
                                        'fileopen', 'Open File.')
     self.actionSave_As = self.editAction(self.actionSave_As,\
                         None, 'ctrl+A', 'filesaveas',\
                         'Save and Name File.')
     self.action_Save = self.editAction(self.action_Save, None, 'ctrl+S',
                                        'filesave', 'Save File.')
     self.action_Solve = self.editAction(self.action_Solve, None, 'ctrl+L',
                                         'solve', 'Solve Structure.')
     self.action_About = self.editAction(self.action_About, None, 'ctrl+B',
                                         'about', 'Pop About Box.')
     self.action_CCPL = self.editAction(self.action_CCPL, None, 'ctrl+G',
                                        'licence', 'Show Licence')
     self.action_Help = self.editAction(self.action_Help, None, 'ctrl+H',
                                        'help', 'Show Help Page.')
     self.action_Quit = self.editAction(self.action_Quit, None, 'ctrl+Q',
                                        'quit', 'Quit the program.')
     self.plainTextEdit_2.setReadOnly(True)
Beispiel #42
0
    def keyPressEvent(self, event):
        if self.preKeyPress.get(event.key(), lambda x: False)(event):
            return

        QPlainTextEdit.keyPressEvent(self, event)
Beispiel #43
0
    def keyPressEvent(self, event):
        if self.preKeyPress.get(event.key(), lambda x: False)(event):
            return

        QPlainTextEdit.keyPressEvent(self, event)
Beispiel #44
0
 def resizeEvent(self, event):
     """ Updates visible blocks on resize """
     self.__onBlocksChanged()
     QPlainTextEdit.resizeEvent(self, event)
Beispiel #45
0
    def __init__(self):
        super(ConsoleWidget, self).__init__()
        self.setWindowTitle('1c query')

        self._connection = None

        self._home = os.path.expanduser('~/%s' % QApplication.applicationName())
        if not os.path.isdir(self._home):
            os.mkdir(self._home)

        self.queryToolBar = self.addToolBar('Query')
        self.queryAction = self.queryToolBar.addAction('Run', self.executeQuery)
        self.queryAction.setDisabled(True)

        uri_history = list()
        path = os.path.join(self._home, 'uri_history.txt')
        if os.path.isfile(path):
            uri_history = open(path, 'r').read().split('\n')

        self.connectionToolBar = self.addToolBar('Connection')
        self.connectionUriCombo = QComboBox(self)
        self.connectionUriCombo.setEditable(True)
        if not uri_history:
            self.connectionUriCombo.addItem('File="";usr="";pwd="";')
            self.connectionUriCombo.addItem('Srvr="{host}";Ref="{ref}";Usr="******";Pwd="{password}";')
        else:
            self.connectionUriCombo.addItems(uri_history)
            self.connectionUriCombo.setCurrentIndex(len(uri_history) - 1)
        self.connectionUriCombo.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Maximum)
        self.connectionToolBar.addWidget(self.connectionUriCombo)

        self.onesVersionCombo = QComboBox(self)
        self.onesVersionCombo.addItems(['8.3', '8.2', '8.1', '8.0'])
        self.onesVersionCombo.setCurrentIndex(0)
        self.connectionToolBar.addWidget(self.onesVersionCombo)
        self.connectAction = self.connectionToolBar.addAction('Connect', self.connectOneS)
        self.disconnectAction = self.connectionToolBar.addAction('Disconnect', self.disconnectOneS)
        self.disconnectAction.setDisabled(True)

        self.logEdit = QPlainTextEdit(self)
        self.logDock = QDockWidget('Log', self)
        self.logDock.setWidget(self.logEdit)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.logDock, Qt.Horizontal)

        self.splitter = QSplitter(Qt.Vertical, self)
        self.setCentralWidget(self.splitter)

        self.sqlEdit = QTextEdit(self)
        self.sqlEdit.setLineWrapMode(QTextEdit.NoWrap)

        path = os.path.join(self._home, 'last-sql.txt')
        if os.path.isfile(path):
            sql = open(path, 'r').read()
            self.sqlEdit.setText(sql)

        self.model = QStandardItemModel(self)
        self.tableView = QTableView(self)
        self.tableView.setModel(self.model)

        self.splitter.addWidget(self.sqlEdit)
        self.splitter.addWidget(self.tableView)
        self.splitter.setStretchFactor(0, 3)
        self.splitter.setStretchFactor(1, 2)
Beispiel #46
0
class ClassyWidget(QWidget):
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        layout = QVBoxLayout(self)
        horiz_layout = QHBoxLayout()
        self.conditional_legend_widget = EdgeWidget(self, True)
        self.conditional_legend_widget.setMinimumHeight(15)
        horiz_layout.addWidget(self.conditional_legend_widget)

        self.conditional_legend_label = QLabel("Conditional transition", self)
        horiz_layout.addWidget(self.conditional_legend_label)

        self.unconditional_legend_widget = EdgeWidget(self, False)
        self.unconditional_legend_widget.setMinimumHeight(15)
        horiz_layout.addWidget(self.unconditional_legend_widget)
        self.unconditional_legend_label = QLabel("Non-conditional transition",
                                                 self)
        horiz_layout.addWidget(self.unconditional_legend_label)

        layout.addLayout(horiz_layout)

        self.splitter = QSplitter(self)

        layout.addWidget(self.splitter)

        self.view = ClassyView(self.splitter)
        # layout.addWidget(self.view)
        self.scene = ClassyScene(self)
        self.view.setScene(self.scene)

        self._menu_bar = QMenuBar(self)
        self._menu = QMenu("&File")
        self._menu_bar.addMenu(self._menu)
        layout.setMenuBar(self._menu_bar)

        self.open_action = QAction("O&pen", self)
        self.exit_action = QAction("E&xit", self)
        self._menu.addAction(self.open_action)
        self._menu.addAction(self.exit_action)

        self.connect(self.open_action, SIGNAL("triggered()"), self.open_file)
        self.connect(self.exit_action, SIGNAL("triggered()"), self.close)

        self.settings = QSettings("CD Projekt RED", "TweakDB")

        self.log_window = QPlainTextEdit(self.splitter)
        self.splitter.setOrientation(Qt.Vertical)

        self.setWindowTitle("Classy nodes")

    @Slot()
    def open_file(self):
        last_dir = self.settings.value("last_dir")
        if last_dir is None:
            last_dir = ''
        # noinspection PyCallByClass
        file_path = QFileDialog.getOpenFileName(self, "Select tweakdb file",
                                                last_dir, "*.tweak")

        if file_path[0]:
            tweak_file = file_path[0]
            self.settings.setValue("last_dir", os.path.dirname(tweak_file))
        else:
            return

        try:
            self._process_db_file(file_path[0])
        except Exception as e:
            # noinspection PyCallByClass
            QMessageBox.critical(
                self, "Error",
                "Error while loading {0}: {1}".format(file_path, str(e)))
        self.setWindowTitle("Classy nodes - {0}".format(file_path[0]))

    @Slot(str)
    def log(self, value):
        self.log_window.appendPlainText(str(value))
        self.log_window.verticalScrollBar().scroll(
            0,
            self.log_window.verticalScrollBar().maximum())

    def _process_db_file(self, file_path):
        class TweakClass(object):
            def __init__(self, name, base=""):
                self.name = name
                self.base = base

                self.transitions_to = []
                self.transitions_conditions = []

            def has_transition(self, name):
                return name in self.transitions_to

            def transition_conditional(self, name):
                if len(self.transitions_to) != len(
                        self.transitions_conditions):
                    raise ValueError(
                        "Transitions length does not match conditions length in {0}"
                        .format(self.name))

                if name not in name:
                    raise ValueError(
                        "Class {0} has no transition to {1}".format(
                            self.name, name))

                return self.transitions_conditions[self.transitions_to.index(
                    name)]

        with open(file_path, "r") as f:
            contents = f.read()

        lines = contents.split("\n")

        is_in_class = False
        is_class_declared = False
        current_class = None

        classes = {}
        parsed_line = 0
        for line in lines:
            parsed_line += 1
            if line.startswith("package"):
                continue

            if line.startswith("using"):
                continue

            if not line.strip():
                continue

            if line.startswith("//"):
                continue

            if not is_in_class and not is_class_declared:
                if line.find("=") > 0:  # static variable
                    continue

                spl = [x.strip() for x in line.strip().split(":")]

                if len(spl) == 1:
                    c = TweakClass(spl[0])
                else:
                    c = TweakClass(spl[0], spl[1])

                is_class_declared = True
                current_class = c
                classes[c.name] = c
                continue

            if not is_in_class and not line.find("{") >= 0:
                raise ValueError(
                    "Failed to parse the file {0} in line: {1}".format(
                        file_path, parsed_line))
            else:
                is_in_class = True

            if line.find("}") >= 0:
                is_in_class = False
                is_class_declared = False
                continue

            if re.match(".+transitionTo( +||\t+)+=( +||\t+)+\[.+\]$",
                        line.strip()):

                spl = line.split("=")[1].strip()[1:-1]
                transitions = [x.strip().strip("\"") for x in spl.split(",")]
                current_class.transitions_to = transitions
                continue

            if re.match(".+transitionCondition( +||\t+)+=( +||\t+)+\[.+\]$",
                        line.strip()):
                spl = "=".join(line.split("=")[1:]).strip()[1:-1]
                transitions = [x.strip().strip("\"") for x in spl.split(",")]
                current_class.transitions_conditions = [
                    True if x.strip() == '=' else False for x in transitions
                ]
                continue

        self.scene.clear()

        # --- Create nodes
        for node_key in classes:
            # g.add_node(str(node_key),
            #            shape_fill="#aaaa33",
            #            shape="roundrectangle",
            #            font_style="bolditalic",
            #            label=classes.get(node_key).name)
            self.scene.add_node(node_key)

        edges_created = []
        # --- Create edges
        for node_key in classes:
            # --- Get each node
            current_node = classes.get(node_key)
            # --- Iterate it's "transition_to" list
            for t in current_node.transitions_to:
                # --- Find node to create transition edge to
                transition_to_node = classes.get(t)
                if transition_to_node is None:
                    self.log("Invalid transition in class {0} -> {1}".format(
                        node_key, t))
                    continue

                # --- Check if it's a two way transition
                two_way = False
                if transition_to_node.has_transition(node_key):
                    two_way = True

                # --- make sure that these edges were not created yet
                edges_to_create = ["{0}!@#{1}".format(node_key, t)]
                if two_way:
                    edges_to_create = ["{0}!@#{1}".format(t, node_key)]

                edge_already_created = False
                for e in edges_to_create:
                    if e in edges_created:
                        edge_already_created = True
                        break
                if edge_already_created:
                    continue

                # --- Check if the transitions are conditional or not
                try:
                    conditional_to = current_node.transition_conditional(t)
                except ValueError as e:
                    self.log(str(e))
                    continue

                conditional_from = False

                if two_way:
                    conditional_from = transition_to_node.transition_conditional(
                        node_key)

                self.scene.add_edge(current_node.name,
                                    transition_to_node.name,
                                    conditional_to=conditional_to,
                                    two_way=two_way,
                                    conditional_from=conditional_from)

                edges_created += edges_to_create

        self.scene.layout_nodes()
Beispiel #47
0
    def __init__(self):
        super(AVRProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)

        self.avr = AVRProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite AVR Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("avr-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        layoutFuse = QHBoxLayout()

        readFuseBut = QPushButton("Read Fuses")
        readFuseBut.clicked.connect(self.readFuses)
        writeFuseBut = QPushButton("Write Fuses")
        writeFuseBut.clicked.connect(self.writeFuses)

        self.lowfuseLine = QtFixes.QLineEdit("?")
        self.lowfuseLine.setMaxLength(2)
        self.lowfuseLine.setFixedWidth(25)
        self.highfuseLine = QtFixes.QLineEdit("?")
        self.highfuseLine.setMaxLength(2)
        self.highfuseLine.setFixedWidth(25)
        self.extfuseLine = QtFixes.QLineEdit("?")
        self.extfuseLine.setMaxLength(2)
        self.extfuseLine.setFixedWidth(25)

        # Don't allow use to change these fuses
        self.highfuseLine.setReadOnly(True)
        self.extfuseLine.setReadOnly(True)

        layoutFuse.addWidget(readFuseBut)
        layoutFuse.addWidget(QLabel("LOW:"))
        layoutFuse.addWidget(self.lowfuseLine)
        layoutFuse.addWidget(QLabel("HIGH:"))
        layoutFuse.addWidget(self.highfuseLine)
        layoutFuse.addWidget(QLabel("EXT:"))
        layoutFuse.addWidget(self.extfuseLine)
        layoutFuse.addWidget(writeFuseBut)
        layout.addLayout(layoutFuse)

        layoutExtra = QHBoxLayout()
        self.clockMode = QPushButton("Enable Slow Clock Mode")
        self.clockMode.setCheckable(True)
        self.clockMode.clicked.connect(self.toggleSlowClock)
        layoutExtra.addWidget(self.clockMode)
        layoutExtra.addStretch()
        layout.addLayout(layoutExtra)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        layout.addWidget(self.statusLine)
        self.avr.newTextLog.connect(self.append)

        # Set dialog layout
        self.setLayout(layout)
Beispiel #48
0
class XMEGAProgrammerDialog(QtFixes.QDialog):
    def __init__(self):
        super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.xmega = XMEGAProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("xmega-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.xmega.newTextLog.connect(self.append)
        layout.addWidget(self.statusLine)

        # Set dialog layout
        self.setLayout(layout)

    def append(self, text):
        self.statusLine.appendPlainText(text)

    def findFlash(self):
        fname, _ = QFileDialog.getOpenFileName(
            self, 'Find FLASH File',
            QSettings().value("xmega-flash-location"), '*.hex')
        if fname:
            self.flashLocation.setText(fname)
            QSettings().setValue("xmega-flash-location", fname)

    def readSignature(self, close=True):
        self.xmega.find()
        if close:
            self.xmega.close()

    def verifyFlash(self):
        pass

    def writeFlash(self, erase=True, verify=True):
        self.xmega.autoProgram(self.flashLocation.text(), erase, verify,
                               self.statusLine.appendPlainText,
                               QCoreApplication.processEvents)

    def setUSBInterface(self, iface):
        self.xmega.setUSBInterface(iface)
class XMEGAProgrammerDialog(QtFixes.QDialog):
    def __init__(self):
        super(XMEGAProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.xmega = XMEGAProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite XMEGA Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("xmega-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.statusLine.append = self.statusLine.appendPlainText
        layout.addWidget(self.statusLine)

        self.xmega._logging = self.statusLine.append

        # Set dialog layout
        self.setLayout(layout)

    def findFlash(self):
        fname, _ = QFileDialog.getOpenFileName(self, 'Find FLASH File', QSettings().value("xmega-flash-location"), '*.hex')
        if fname:
            self.flashLocation.setText(fname)
            QSettings().setValue("xmega-flash-location", fname)

    def readSignature(self, close=True):
        self.xmega.find()
        if close:
            self.xmega.close()

    def verifyFlash(self):
        pass

    def writeFlash(self, erase=True, verify=True):

        status = "FAILED"

        fname = self.flashLocation.text()
        self.statusLine.append("***Starting FLASH program process at %s***" % datetime.now().strftime('%H:%M:%S'))
        if (os.path.isfile(fname)):
            self.statusLine.append("File %s last changed on %s" % (fname, time.ctime(os.path.getmtime(fname))))
            QCoreApplication.processEvents()

            try:
                self.statusLine.append("Entering Programming Mode")
                QCoreApplication.processEvents()
                self.readSignature(close=False)

                if erase:
                    try:
                        self.statusLine.append("Erasing Chip")
                        QCoreApplication.processEvents()
                        self.xmega.erase()
                    except IOError:
                        self.statusLine.append("**chip-erase timeout, erasing application only**")
                        QCoreApplication.processEvents()
                        self.xmega.xmega.enablePDI(False)
                        self.xmega.xmega.enablePDI(True)
                        self.xmega.erase("app")

                QCoreApplication.processEvents()
                self.xmega.program(self.flashLocation.text(), memtype="flash", verify=verify)
                QCoreApplication.processEvents()
                self.statusLine.append("Exiting programming mode")
                self.xmega.close()
                QCoreApplication.processEvents()

                status = "SUCCEEDED"

            except IOError, e:
                self.statusLine.append("FAILED: %s" % str(e))
                try:
                    self.xmega.close()
                except IOError:
                    pass

        else:
Beispiel #50
0
class STM32FProgrammerDialog(QtFixes.QDialog):
    def __init__(self):
        super(STM32FProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)
        self.stm32f = STM32FProgrammer()

        self.setWindowTitle("Serial STM32F Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("stm32f-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        layoutsetting = QHBoxLayout()
        mode = QComboBox()
        mode.addItem("fast", False)
        mode.addItem("slow", True)
        mode.currentIndexChanged.connect(self.modechanged)
        layoutsetting.addWidget(QLabel("Speed:"))
        layoutsetting.addWidget(mode)

        blocksize = QComboBox()
        blocksize.addItem("256", False)
        blocksize.addItem("64", True)
        blocksize.currentIndexChanged.connect(self.blocksizechanged)
        layoutsetting.addStretch()
        layoutsetting.addWidget(QLabel("Read Block Size:"))
        layoutsetting.addWidget(blocksize)
        layout.addLayout(layoutsetting)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.stm32f.newTextLog.connect(self.append)
        layout.addWidget(self.statusLine)

        # Set dialog layout
        self.setLayout(layout)

    def modechanged(self, newmode):
        self.stm32f.slow_speed = newmode

    def blocksizechanged(self, use_small_block):
        self.stm32f.small_blocks = use_small_block

    def append(self, text):
        self.statusLine.appendPlainText(text)

    def findFlash(self):
        fname, _ = QFileDialog.getOpenFileName(
            self, 'Find FLASH File',
            QSettings().value("stm32f-flash-location"), '*.hex')
        if fname:
            self.flashLocation.setText(fname)
            QSettings().setValue("stm32f-flash-location", fname)

    def readSignature(self, close=True):
        self.stm32f.open_and_find(log_func=self.statusLine.appendPlainText)
        if close:
            self.stm32f.close()

    def verifyFlash(self):
        pass

    def writeFlash(self, erase=True, verify=True):
        self.stm32f.autoProgram(self.flashLocation.text(), erase, verify,
                                self.statusLine.appendPlainText,
                                QCoreApplication.processEvents)

    def setUSBInterface(self, iface):
        self.stm32f.setUSBInterface(iface)
class AVRProgrammerDialog(QtFixes.QDialog):
    def __init__(self):
        super(AVRProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)

        self.avr = AVRProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite AVR Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("avr-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        layoutFuse = QHBoxLayout()

        readFuseBut = QPushButton("Read Fuses")
        readFuseBut.clicked.connect(self.readFuses)
        writeFuseBut = QPushButton("Write Fuses")
        writeFuseBut.clicked.connect(self.writeFuses)

        self.lowfuseLine = QtFixes.QLineEdit("?")
        self.lowfuseLine.setMaxLength(2)
        self.lowfuseLine.setFixedWidth(25)
        self.highfuseLine = QtFixes.QLineEdit("?")
        self.highfuseLine.setMaxLength(2)
        self.highfuseLine.setFixedWidth(25)
        self.extfuseLine = QtFixes.QLineEdit("?")
        self.extfuseLine.setMaxLength(2)
        self.extfuseLine.setFixedWidth(25)

        # Don't allow use to change these fuses
        self.highfuseLine.setReadOnly(True)
        self.extfuseLine.setReadOnly(True)

        layoutFuse.addWidget(readFuseBut)
        layoutFuse.addWidget(QLabel("LOW:"))
        layoutFuse.addWidget(self.lowfuseLine)
        layoutFuse.addWidget(QLabel("HIGH:"))
        layoutFuse.addWidget(self.highfuseLine)
        layoutFuse.addWidget(QLabel("EXT:"))
        layoutFuse.addWidget(self.extfuseLine)
        layoutFuse.addWidget(writeFuseBut)
        layout.addLayout(layoutFuse)

        layoutExtra = QHBoxLayout()
        self.clockMode = QPushButton("Enable Slow Clock Mode")
        self.clockMode.setCheckable(True)
        self.clockMode.clicked.connect(self.toggleSlowClock)
        layoutExtra.addWidget(self.clockMode)
        layoutExtra.addStretch()
        layout.addLayout(layoutExtra)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        self.statusLine.append = self.statusLine.appendPlainText
        layout.addWidget(self.statusLine)

        self.avr._logging = self.statusLine.append

        # Set dialog layout
        self.setLayout(layout)

    def toggleSlowClock(self):
        if self.clockMode.isChecked():
            self.avr.avr.enableSlowClock(True)
            self.clockMode.setText("Disable Slow Clock Mode")
        else:
            self.avr.avr.enableSlowClock(False)
            self.clockMode.setText("Enable Slow Clock Mode")

    def reject(self):
        #Ensure we disable slow-clock mode
        if self.clockMode.isChecked():
            self.clockMode.setChecked(False)
            self.toggleSlowClock()
            
        #Release AVR
        self.avr.close()

        QDialog.reject(self)

    def findFlash(self):
        fname, _ = QFileDialog.getOpenFileName(self, 'Find FLASH File', QSettings().value("avr-flash-location"), '*.hex')
        if fname:
            self.flashLocation.setText(fname)
            QSettings().setValue("avr-flash-location", fname)

    def readSignature(self, close=True):
        self.avr.find()
        if close:
            self.avr.close()

    def readFuses(self):
        try:
            self.readSignature(close=False)
            self.statusLine.append("Reading fuses")
            lfuse = self.avr.avr.readFuse("low")
            hfuse = self.avr.avr.readFuse("high")
            efuse = self.avr.avr.readFuse("extended")
            self.statusLine.append("OK: %02x %02x %02x" % (lfuse, hfuse, efuse))
            self.lowfuseLine.setText("%02x" % lfuse)
            self.highfuseLine.setText("%02x" % hfuse)
            self.extfuseLine.setText("%02x" % efuse)
        except IOError:
            self.statusLine.append("Reading fuses failed")
            self.lowfuseLine.setText("?")
            self.highfuseLine.setText("?")
            self.extfuseLine.setText("?")
            self.avr.close()

    def writeFuses(self):
        lfuse = int(self.lowfuseLine.text(), 16)
        # hfuse = int(self.highfuseLine.text(), 16)
        # efuse = int(self.extfuseLine.text(), 16)

        self.statusLine.append("Writing fuse: not only 'low' fuse is written, as hfuse/efuse can disable device\n")

        try:
            self.readSignature(close=False)
            self.avr.avr.writeFuse("low", lfuse)
            # self.avr.avr.writeFuse("high", hfuse)
            # self.avr.avr.writeFuse("extended", efuse)
            # print("%x %x %x" % (lfuse, hfuse, efuse))
            self.avr.close()
        except:
            self.avr.close()
            raise

    def verifyFlash(self):
        self.statusLine.append("Verify not implemented")

    def writeFlash(self, erase=True, verify=True):
        status = "FAILED"
        fname = self.flashLocation.text()
        self.statusLine.append("***Starting FLASH program process at %s***" % datetime.now().strftime('%H:%M:%S'))
        if (os.path.isfile(fname)):
            self.statusLine.append("File %s last changed on %s" % (fname, time.ctime(os.path.getmtime(fname))))
            QCoreApplication.processEvents()

            try:
                self.statusLine.append("Entering Programming Mode")
                QCoreApplication.processEvents()
                self.readSignature(close=False)

                if erase:
                    self.statusLine.append("Erasing Chip")
                    QCoreApplication.processEvents()
                    self.avr.erase()
                    self.avr.close()
                    self.readSignature(close=False)

                QCoreApplication.processEvents()
                self.avr.program(self.flashLocation.text(), memtype="flash", verify=verify)
                QCoreApplication.processEvents()
                self.statusLine.append("Exiting programming mode")
                self.avr.close()
                QCoreApplication.processEvents()

                status = "SUCCEEDED"

            except IOError as e:
                self.statusLine.append("FAILED: %s" % str(e))
                try:
                    self.avr.close()
                except IOError:
                    pass

        else:
            self.statusLine.append("%s does not appear to be a file, check path" % fname)

        self.statusLine.append("***FLASH Program %s at %s***" % (status, datetime.now().strftime('%H:%M:%S')))

    def setUSBInterface(self, iface):
        self.avr.setUSBInterface(iface)
Beispiel #52
0
class AVRProgrammerDialog(QtFixes.QDialog):
    def __init__(self):
        super(AVRProgrammerDialog, self).__init__(CWMainGUI.getInstance())
        # self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)

        self.avr = AVRProgrammer()

        self.setWindowTitle("ChipWhisperer-Lite AVR Programmer")
        layout = QVBoxLayout()

        layoutFW = QHBoxLayout()
        self.flashLocation = QtFixes.QLineEdit()
        flashFileButton = QPushButton("Find")
        flashFileButton.clicked.connect(self.findFlash)
        layoutFW.addWidget(QLabel("FLASH File"))
        layoutFW.addWidget(self.flashLocation)
        layoutFW.addWidget(flashFileButton)
        layout.addLayout(layoutFW)

        self.flashLocation.setText(QSettings().value("avr-flash-location"))

        # Add buttons
        readSigBut = QPushButton("Check Signature")
        readSigBut.clicked.connect(self.readSignature)
        verifyFlashBut = QPushButton("Verify FLASH")
        verifyFlashBut.clicked.connect(self.verifyFlash)
        verifyFlashBut.setEnabled(False)
        progFlashBut = QPushButton("Erase/Program/Verify FLASH")
        progFlashBut.clicked.connect(self.writeFlash)

        layoutBut = QHBoxLayout()
        layoutBut.addWidget(readSigBut)
        layoutBut.addWidget(verifyFlashBut)
        layoutBut.addWidget(progFlashBut)
        layout.addLayout(layoutBut)

        layoutFuse = QHBoxLayout()

        readFuseBut = QPushButton("Read Fuses")
        readFuseBut.clicked.connect(self.readFuses)
        writeFuseBut = QPushButton("Write Fuses")
        writeFuseBut.clicked.connect(self.writeFuses)

        self.lowfuseLine = QtFixes.QLineEdit("?")
        self.lowfuseLine.setMaxLength(2)
        self.lowfuseLine.setFixedWidth(25)
        self.highfuseLine = QtFixes.QLineEdit("?")
        self.highfuseLine.setMaxLength(2)
        self.highfuseLine.setFixedWidth(25)
        self.extfuseLine = QtFixes.QLineEdit("?")
        self.extfuseLine.setMaxLength(2)
        self.extfuseLine.setFixedWidth(25)

        # Don't allow use to change these fuses
        self.highfuseLine.setReadOnly(True)
        self.extfuseLine.setReadOnly(True)

        layoutFuse.addWidget(readFuseBut)
        layoutFuse.addWidget(QLabel("LOW:"))
        layoutFuse.addWidget(self.lowfuseLine)
        layoutFuse.addWidget(QLabel("HIGH:"))
        layoutFuse.addWidget(self.highfuseLine)
        layoutFuse.addWidget(QLabel("EXT:"))
        layoutFuse.addWidget(self.extfuseLine)
        layoutFuse.addWidget(writeFuseBut)
        layout.addLayout(layoutFuse)

        layoutExtra = QHBoxLayout()
        self.clockMode = QPushButton("Enable Slow Clock Mode")
        self.clockMode.setCheckable(True)
        self.clockMode.clicked.connect(self.toggleSlowClock)
        layoutExtra.addWidget(self.clockMode)
        layoutExtra.addStretch()
        layout.addLayout(layoutExtra)

        # Add status stuff
        self.statusLine = QPlainTextEdit()
        self.statusLine.setReadOnly(True)
        # self.statusLine.setFixedHeight(QFontMetrics(self.statusLine.font()).lineSpacing() * 5 + 10)
        layout.addWidget(self.statusLine)
        self.avr.newTextLog.connect(self.append)

        # Set dialog layout
        self.setLayout(layout)

    def append(self, text):
        self.statusLine.appendPlainText(text)

    def toggleSlowClock(self):
        if self.clockMode.isChecked():
            self.avr.enableSlowClock(True)
            self.clockMode.setText("Disable Slow Clock Mode")
        else:
            self.avr.enableSlowClock(False)
            self.clockMode.setText("Enable Slow Clock Mode")

    def reject(self):
        #Ensure we disable slow-clock mode
        if self.clockMode.isChecked():
            self.clockMode.setChecked(False)
            self.toggleSlowClock()

        #Release AVR
        self.avr.close()

        QDialog.reject(self)

    def findFlash(self):
        fname, _ = QFileDialog.getOpenFileName(
            self, 'Find FLASH File',
            QSettings().value("avr-flash-location"), '*.hex')
        if fname:
            self.flashLocation.setText(fname)
            QSettings().setValue("avr-flash-location", fname)

    def readSignature(self, close=True):
        self.avr.find()
        if close:
            self.avr.close()

    def readFuses(self):
        try:
            self.readSignature(close=False)
            self.statusLine.appendPlainText("Reading fuses")
            lfuse = self.avr.readFuse("low")
            hfuse = self.avr.readFuse("high")
            efuse = self.avr.readFuse("extended")
            self.statusLine.appendPlainText("OK: %02x %02x %02x" %
                                            (lfuse, hfuse, efuse))
            self.lowfuseLine.setText("%02x" % lfuse)
            self.highfuseLine.setText("%02x" % hfuse)
            self.extfuseLine.setText("%02x" % efuse)
        except IOError:
            self.statusLine.appendPlainText("Reading fuses failed")
            self.lowfuseLine.setText("?")
            self.highfuseLine.setText("?")
            self.extfuseLine.setText("?")
            self.avr.close()

    def writeFuses(self):
        lfuse = int(self.lowfuseLine.text(), 16)
        # hfuse = int(self.highfuseLine.text(), 16)
        # efuse = int(self.extfuseLine.text(), 16)

        self.statusLine.appendPlainText(
            "Writing fuse: not only 'low' fuse is written, as hfuse/efuse can disable device\n"
        )

        try:
            self.readSignature(close=False)
            self.avr.writeFuse("low", lfuse)
            # self.avr.writeFuse("high", hfuse)
            # self.avr.writeFuse("extended", efuse)
            # print("%x %x %x" % (lfuse, hfuse, efuse))
            self.avr.close()
        except:
            self.avr.close()
            raise

    def verifyFlash(self):
        self.statusLine.appendPlainText("Verify not implemented")

    def writeFlash(self, erase=True, verify=True):
        self.avr.autoProgram(self.flashLocation.text(), erase, verify,
                             self.statusLine.appendPlainText,
                             QCoreApplication.processEvents)

    def setUSBInterface(self, iface):
        self.avr.setUSBInterface(iface)
Beispiel #53
0
    def keyPressEvent(self, event):
        self.dirty = True
        customKey = False
        #AutoTab
        if (event.key() == Qt.Key_Enter or event.key() == 16777220):
            customKey = True
            numTab = 0
            #new line
            newBlock = self.textCursor().block()
            currLine = newBlock.text()
            tabRE = QRegExp("^[\t]*")
            tabRE.indexIn(currLine)
            numTab = tabRE.matchedLength()
            if (currLine != "" and currLine.strip()[-1] == "{"):
                numTab += 1
            QPlainTextEdit.keyPressEvent(self, event)
            if (numTab > 0):
                tCursor = self.textCursor()
                for _ in range(0, numTab):
                    tCursor.insertText("\t")

                #automatic close brace
                if currLine != "" and currLine.strip()[-1] == "{":
                    tCursor.insertText("\n")
                    for _ in range(0, numTab - 1):
                        tCursor.insertText("\t")
                    tCursor.insertText("}")
                    tCursor.movePosition(QTextCursor.PreviousBlock)
                    tCursor.movePosition(QTextCursor.EndOfLine)
                    self.setTextCursor(tCursor)

        if event.key() == Qt.Key_Tab and self.textCursor().hasSelection():
            customKey = True
            selStart = self.textCursor().selectionStart()
            selEnd = self.textCursor().selectionEnd()
            cur = self.textCursor()
            endBlock = self.document().findBlock(selEnd)
            currBlock = self.document().findBlock(selStart)
            while currBlock.position() <= endBlock.position():
                cur.setPosition(currBlock.position())
                cur.insertText("\t")
                currBlock = currBlock.next()

        if event.key() == Qt.Key_Backtab and self.textCursor().hasSelection():
            customKey = True
            selStart = self.textCursor().selectionStart()
            selEnd = self.textCursor().selectionEnd()
            cur = self.textCursor()
            endBlock = self.document().findBlock(selEnd)
            currBlock = self.document().findBlock(selStart)
            while currBlock.position() <= endBlock.position():
                cur.setPosition(currBlock.position())
                if currBlock.text().left(1) == "\t":
                    cur.deleteChar()
                currBlock = currBlock.next()

        # Allow commenting and uncommenting of blocks of code
        if event.key() == Qt.Key_Slash and event.modifiers(
        ) == Qt.ControlModifier:
            customKey = True
            selStart = self.textCursor().selectionStart()
            selEnd = self.textCursor().selectionEnd()
            cur = self.textCursor()
            endBlock = self.document().findBlock(selEnd)
            currBlock = self.document().findBlock(selStart)

            while currBlock.position() <= endBlock.position():
                cur.setPosition(currBlock.position())

                if currBlock.text()[0] == "#":
                    cur.deleteChar()

                    # Make sure we remove extra spaces
                    while currBlock.text()[0] == " ":
                        cur.deleteChar()
                else:
                    cur.insertText("# ")

                currBlock = currBlock.next()

        # Open the text finder
        if event.key() == Qt.Key_F and event.modifiers() == Qt.ControlModifier:
            customKey = True
            print("Opening finder...")

        if not customKey:
            QPlainTextEdit.keyPressEvent(self, event)
 def __init__(self,*args,**kwargs):
     QPlainTextEdit.__init__(self,*args,**kwargs)
Beispiel #55
0
 def resizeEvent(self, event):
     QPlainTextEdit.resizeEvent(self, event)
     cr = self.contentsRect()
     self.lineNumberArea.setGeometry(
         QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(),
               cr.height()))