コード例 #1
0
 def setup(self):
     # Set the default font
     font = QFont()
     font.setFamily('Courier')
     font.setFixedPitch(True)
     font.setPointSize(10)
     self.setFont(font)
     self.setMarginsFont(font)
     fontmetrics = QFontMetrics(font)
     self.setMarginsFont(font)
     self.setMarginWidth(0, fontmetrics.width('0000'))
     self.setMarginLineNumbers(0, True)
     self.setMarginsBackgroundColor(QColor('#cccccc'))
     self.setMarginSensitivity(1, True)
     self.marginClicked.connect(self.on_margin_clicked)
     self.markerDefine(QsciScintilla.RightTriangle, self.ARROW_MARKER_NUM)
     self.setMarkerBackgroundColor(QColor('#ee1111'), self.ARROW_MARKER_NUM)
     self.markerDefine(QsciScintilla.Circle, self.REC_MARKER_NUM)
     self.setMarkerBackgroundColor(QColor('#87CEEB'), self.REC_MARKER_NUM)
     self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
     self.setCaretLineVisible(True)
     self.setCaretLineBackgroundColor(QColor('#FFA07A'))
     self.my_lexer = OrLexer(self)
     self.setLexer(self.my_lexer)
     self.setAutoCompletionThreshold(1)
     self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
     self.tracking_marker = None
コード例 #2
0
ファイル: widget.py プロジェクト: moceap/scribus
    def __init__(self, parent=None, text=None,
                 EditorHighlighterClass=PythonHighlighter,
                 indenter=PythonCodeIndenter):
        QPlainTextEdit.__init__(self, parent)
        self.setFrameStyle(QFrame.NoFrame)
        self.setTabStopWidth(4)
        self.setLineWrapMode(QPlainTextEdit.NoWrap)
        font = QFont()
        font.setFamily("lucidasanstypewriter")
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.highlighter = EditorHighlighterClass(self)
        if text:
            self.setPlainText(text)
        self.frame_style = self.frameStyle()
        self.draw_line = True
        self.print_width = self.fontMetrics().width("x"*78)
        self.line_pen = QPen(QColor("lightgrey"))
        self.last_row = self.last_col = -1
        self.last_block = None
        self.highlight_line = True
        self.highlight_color = self.palette().highlight().color().light(175)
        self.highlight_brush = QBrush(QColor(self.highlight_color))
        self.connect(self, SIGNAL("cursorPositionChanged()"), 
                        self.onCursorPositionChanged)
        self.indenter = indenter(RopeEditorWrapper(self))
        # True if you want to catch Emacs keys in actions
        self.disable_shortcuts = False

        self.prj = get_no_project()
        self.prj.root = None
        self.calltip = CallTip(self)
        self.autocomplete = AutoComplete(self)
コード例 #3
0
    def __init__(self, parent=None, text=None,
                 EditorHighlighterClass=PythonHighlighter,
                 indenter=PythonCodeIndenter):
        QPlainTextEdit.__init__(self, parent)
        self.setFrameStyle(QFrame.NoFrame)
        self.setTabStopWidth(4)
        self.setLineWrapMode(QPlainTextEdit.NoWrap)
        font = QFont()
        font.setFamily("lucidasanstypewriter")
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.highlighter = EditorHighlighterClass(self)
        if text:
            self.setPlainText(text)
        self.frame_style = self.frameStyle()
        self.draw_line = True
        self.print_width = self.fontMetrics().width("x"*78)
        self.line_pen = QPen(QColor("lightgrey"))
        self.last_row = self.last_col = -1
        self.last_block = None
        self.highlight_line = True
        self.highlight_color = self.palette().highlight().color().light(175)
        self.highlight_brush = QBrush(QColor(self.highlight_color))
        self.connect(self, SIGNAL("cursorPositionChanged()"), 
                        self.onCursorPositionChanged)
        self.indenter = indenter(RopeEditorWrapper(self))
        # True if you want to catch Emacs keys in actions
        self.disable_shortcuts = False

        self.prj = get_no_project()
        self.prj.root = None
        self.calltip = CallTip(self)
        self.autocomplete = AutoComplete(self)
コード例 #4
0
ファイル: statusbar.py プロジェクト: bogdanvuk/pyde
 def __init__(self, view: Amendment('view/', lambda v: hasattr(v, 'mode') and (v.mode.name == '__statusbar__') and (v.widget is None))):
     super().__init__()
     self.view = view
     self.view.widget = self
     font = QFont()
     font.setFamily('DejaVu Sans Mono')
     font.setFixedPitch(True)
     font.setPointSize(10)    
     self.setFont(font);
コード例 #5
0
ファイル: interpret.py プロジェクト: bogdanvuk/pyde
    def __init__(self, view: Amendment('view/', lambda v: hasattr(v, 'mode') and (v.mode.name == 'ipython') and (v.widget is None))): #, orig_editor=None):
        if view.widget is None:
            self.globals = {}
            self.globals['ddic'] = ddic
            for a in ddic['actions']:
                self.globals[a] = ddic['actions'][a]
                
            self.locals = {}
#             ddic.provide('interactive', -1)
        else:
            self.globals = view.widget.globals
            self.locals = view.widget.locals
        
        super().__init__(view)

        # Set the default font
        font = QFont()
        font.setFamily('DejaVu Sans Mono')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
#        self.parser = Parser(self, 'python3')
#         self.ca = PyInterpretContentAssist()
        fontmetrics = QFontMetrics(font)

        # Brace matching: enable for a brace immediately before or after
        # the current position
        #
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Current line visible with special background color
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor("#ffe4e4"))

        # Set Python lexer
        # Set style for Python comments (style number 1) to a fixed-width
        # courier.
        #
#         self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'DejaVu Sans Mono'.encode())
        

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented
        # here: http://www.scintilla.org/ScintillaDoc.html)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        self.SendScintilla(QsciScintilla.SCI_SETVSCROLLBAR, 0)
        
        self.setMinimumSize(fontmetrics.width("00000"), fontmetrics.height()+4)
        
        self.markerDefine(QsciScintilla.RightArrow,
            self.ARROW_MARKER_NUM)
#         self.setMarkerBackgroundColor(QColor("#ee1111"),
#             self.ARROW_MARKER_NUM)

        self.prompt_begin = 0
        self.focus_view = None
        self.interactive = False
コード例 #6
0
    def __init__(self, parent=None):
        super(MyQTextBrowser, self).__init__(parent)
        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)
        self.setUtf8(True)

        # Margin 0 is used for line numbers
        font_metrics = QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(0, font_metrics.width("000") + 4)
        self.setMarginLineNumbers(0, True)
        self.setMarginsBackgroundColor(QColor("#cccccc"))

        # Clickable margin 1 for showing markers
        self.setMarginSensitivity(1, True)
        self.connect(self,
                     SIGNAL('marginClicked(int, int, Qt::KeyboardModifiers)'),
                     self.on_margin_clicked)
        self.markerDefine(QsciScintilla.RightArrow,
                          self.ARROW_MARKER_NUM)
        self.setMarkerBackgroundColor(QColor("#ee1111"),
                                      self.ARROW_MARKER_NUM)

        # Brace matching: enable for a brace immediately before or after
        # the current position
        #
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Current line visible with special background color
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor("#ffe4e4"))

        # Set Python lexer
        # Set style for Python comments (style number 1) to a fixed-width
        # courier.
        #
        lexer = QsciLexerXML()
        lexer.setDefaultFont(font)
        self.setLexer(lexer)
        self.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier')

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented
        # here: http://www.scintilla.org/ScintillaDoc.html)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
        self.setHorizontalScrollBar(QScrollBar(self))

        self.fp = None
        self.item = None
        self.html_mapper = dict()
        self.setReadOnly(True)
コード例 #7
0
ファイル: orlistwidget.py プロジェクト: harry159821/orquesta
 def __init__(self, active=True, parent=None):
     self.active = active
     QListWidgetItem.__init__(self, parent)
     self.set_color()
     font = QFont(QFont.SansSerif)
     font.setStyleHint(QFont.Monospace)
     font.setPointSize(10)
     font.setFixedPitch(True)
     self.setFont(font)
     self.setTextAlignment(4)
コード例 #8
0
    def _load_code_editor_settings(self):
        """
        Load settings on the code editor like, font style, margins, scroll, etc.
        Based on the example from http://eli.thegreenplace.net/2011/04/01/sample-using-qscintilla-with-pyqt/
        """

        item = self.form.font_size.currentText()
        size = int(item)

        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(size)
        self._code_editor.setFont(font)
        self._code_editor.setMarginsFont(font)

        # Margin 0 is used for line numbers
        fontmetrics = QFontMetrics(font)
        self._code_editor.setMarginsFont(font)
        self._code_editor.setMarginWidth(0, fontmetrics.width("00000") + 6)
        self._code_editor.setMarginLineNumbers(0, True)
        self._code_editor.setMarginsBackgroundColor(QColor("#cccccc"))

        # Clickable margin 1 for showing markers
        self._code_editor.setMarginSensitivity(1, True)
        self._code_editor.marginClicked.connect(self.on_margin_clicked)
        self._code_editor.markerDefine(QsciScintilla.RightArrow,
                                       self.ARROW_MARKER_NUM)
        self._code_editor.setMarkerBackgroundColor(QColor("#ee1111"),
                                                   self.ARROW_MARKER_NUM)

        # Detect changes to text
        self._code_editor.modificationChanged.connect(
            self.on_modification_changed)

        # Brace matching: enable for a brace immediately before or after the current position
        self._code_editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Current line visible with special background color
        self._code_editor.setCaretLineVisible(True)
        self._code_editor.setCaretLineBackgroundColor(QColor("#ffe4e4"))

        # Set Python lexer
        # Set style for Python comments (style number 1) to a fixed-width Courier.
        lexer = self.lexer()
        lexer.setDefaultFont(font)
        self._code_editor.setLexer(lexer)
        self._code_editor.setIndentationWidth(4)
        # self._code_editor.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier')
        self._code_editor.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1)

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented here: http://www.scintilla.org/ScintillaDoc.html)
        self._code_editor.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
コード例 #9
0
ファイル: ScriptEdit.py プロジェクト: HeatherHillers/QGIS
    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(20)
        self.setFont(font)
        self.setMarginsFont(font)

        self.initLexer()

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        self.setFonts(10)
コード例 #10
0
ファイル: ScriptEdit.py プロジェクト: wsyscu/QGIS
    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(20)
        self.setFont(font)
        self.setMarginsFont(font)

        self.initLexer()

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        self.setFonts(10)
コード例 #11
0
ファイル: pqMsgs.py プロジェクト: jlg234bob/PPQT
def getMonoFont(fontsize=12, msg=False):
    monofont = QFont()
    monofont.setStyleStrategy(QFont.PreferAntialias+QFont.PreferMatch)
    monofont.setStyleHint(QFont.Courier)
    monofont.setFamily(IMC.fontFamily)
    monofont.setFixedPitch(True) # probably unnecessary
    monofont.setPointSize(fontsize)
    if msg and (monofont.family() != IMC.fontFamily):
        infoMsg("Font {0} not available, using {1}".format(
            IMC.fontFamily, monoinf.family()) )
    return monofont
コード例 #12
0
ファイル: xmleditor.py プロジェクト: benpope82/repoeditor
 def __init__(self):
     """Configures all the properties.
     """
     super().__init__()
     font = QFont()
     font.setFamily('Courier')
     font.setFixedPitch(True)
     font.setPointSize(10)
     metrics = QFontMetrics(font)
     self.setFont(font)
     self.setTabStopWidth(2 * metrics.width(' '))       
     self.highlighter = XmlHighlighter(self.document())
コード例 #13
0
ファイル: offsetItem.py プロジェクト: kzwkt/dff
class offsetItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
#        self.initShape()
        self.initPosition()
        self.initFont()

    def initPosition(self):
        self.setPos(0, 25)

    def initValues(self, whex):
        self.whex = whex
        self.heditor = self.whex.heditor
        #Buffer
        self.buffer = []
        self.bufferLines = 0 
        #Line
        self.currentLine = 0
        #Offset
        self.startOffset = 0
        self.fontPixel = 14

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.red))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        self.setFont(self.font)

    #Print Operations
    def printFullOffset(self, start, len):
        count = 0
        fullBuff = QString()

        while count <= len:
            if self.heditor.decimalview:
                fullBuff.append("%.10d" % start)
            else:
                fullBuff.append("%.10X" % start)
            fullBuff.append("\n")
            start += 16
            count += 1

        #Clear and set
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(fullBuff)
        cursor.movePosition(QTextCursor.Start)
コード例 #14
0
ファイル: offsetItem.py プロジェクト: halbbob/dff
class offsetItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
#        self.initShape()
        self.initPosition()
        self.initFont()

    def initPosition(self):
        self.setPos(0, 25)

    def initValues(self, whex):
        self.whex = whex
        self.bdiff = self.whex.bdiff
        #Buffer
        self.buffer = []
        self.bufferLines = 0 
        #Line
        self.currentLine = 0
        #Offset
        self.startOffset = 0
        self.fontPixel = 14

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.red))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        self.setFont(self.font)

    #Print Operations
    def printFullOffset(self, start, len):
        count = 0
        fullBuff = QString()

        while count <= len:
            if self.bdiff.opt_offsetBase == 1:
                fullBuff.append("%.10d" % start)
            elif self.bdiff.opt_offsetBase == 0:
                fullBuff.append("%.10X" % start)
            fullBuff.append("\n")
            start += 16
            count += 1

        #Clear and set
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(fullBuff)
        cursor.movePosition(QTextCursor.Start)
コード例 #15
0
ファイル: ControlCodeEditor.py プロジェクト: AlfiyaZi/pyforms
    def _load_code_editor_settings(self):
        """
        Load settings on the code editor like, font style, margins, scroll, etc.
        Based on the example from http://eli.thegreenplace.net/2011/04/01/sample-using-qscintilla-with-pyqt/
        """

        item = self.form.font_size.currentText()
        size = int(item)

        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(size)
        self._code_editor.setFont(font)
        self._code_editor.setMarginsFont(font)

        # Margin 0 is used for line numbers
        fontmetrics = QFontMetrics(font)
        self._code_editor.setMarginsFont(font)
        self._code_editor.setMarginWidth(0, fontmetrics.width("00000") + 6)
        self._code_editor.setMarginLineNumbers(0, True)
        self._code_editor.setMarginsBackgroundColor(QColor("#cccccc"))

        # Clickable margin 1 for showing markers
        self._code_editor.setMarginSensitivity(1, True)
        self._code_editor.marginClicked.connect(self.on_margin_clicked)
        self._code_editor.markerDefine(QsciScintilla.RightArrow, self.ARROW_MARKER_NUM)
        self._code_editor.setMarkerBackgroundColor(QColor("#ee1111"), self.ARROW_MARKER_NUM)

        # Detect changes to text
        self._code_editor.modificationChanged.connect(self.on_modification_changed)

        # Brace matching: enable for a brace immediately before or after the current position
        self._code_editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        # Current line visible with special background color
        self._code_editor.setCaretLineVisible(True)
        self._code_editor.setCaretLineBackgroundColor(QColor("#ffe4e4"))

        # Set Python lexer
        # Set style for Python comments (style number 1) to a fixed-width Courier.
        lexer = self.lexer()
        lexer.setDefaultFont(font)
        self._code_editor.setLexer(lexer)
        self._code_editor.setIndentationWidth(4)
        # self._code_editor.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1, 'Courier')
        self._code_editor.SendScintilla(QsciScintilla.SCI_STYLESETFONT, 1)

        # Don't want to see the horizontal scrollbar at all
        # Use raw message to Scintilla here (all messages are documented here: http://www.scintilla.org/ScintillaDoc.html)
        self._code_editor.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)
コード例 #16
0
        def __init__(self, parent=None):
            super(SimplePythonEditorWidget, self).__init__(parent)

            # Set the default font
            font = QFont()
            font.setFamily('Courier')
            font.setFixedPitch(True)
            font.setPointSize(10)
            self.setFont(font)
            self.setMarginsFont(font)

            # Margin 0 is used for line numbers
            fontmetrics = QFontMetrics(font)
            self.setMarginsFont(font)
            self.setMarginWidth(0, fontmetrics.width("00000") + 6)
            self.setMarginLineNumbers(0, True)
            self.setMarginsBackgroundColor(QColor("#cccccc"))

            # Clickable margin 1 for showing markers
            self.setMarginSensitivity(1, True)
            self.connect(
                self,
                QtCore.SIGNAL(
                    'marginClicked(int, int, Qt::KeyboardModifiers)'),
                self.on_margin_clicked)
            self.markerDefine(Qsci.QsciScintilla.RightArrow,
                              self.ARROW_MARKER_NUM)
            self.setMarkerBackgroundColor(QColor("#ee1111"),
                                          self.ARROW_MARKER_NUM)

            # Brace matching: enable for a brace immediately before or after
            # the current position
            self.setBraceMatching(Qsci.QsciScintilla.SloppyBraceMatch)

            # Current line visible with special background color
            self.setCaretLineVisible(True)
            self.setCaretLineBackgroundColor(QColor("#ffe4e4"))

            # Set Python lexer
            # Set style for Python comments (style number 1) to a fixed-width
            # courier.
            lexer = Qsci.QsciLexerPython()
            lexer.setDefaultFont(font)
            self.setLexer(lexer)
            self.SendScintilla(Qsci.QsciScintilla.SCI_STYLESETFONT, 1,
                               'Courier')

            # Don't want to see the horizontal scrollbar at all
            # Use raw message to Scintilla here (all messages are documented
            # here: http://www.scintilla.org/ScintillaDoc.html)
            self.SendScintilla(Qsci.QsciScintilla.SCI_SETHSCROLLBAR, 0)
コード例 #17
0
 def getFont(self,
             font_family,
             font_size=10,
             bold=False,
             italic=False,
             Underline=False):
     font = QFont()
     font.setFamily(_fromUtf8(font_family))
     font.setPixelSize(font_size)
     font.setFixedPitch(True)
     font.setBold(bold)
     font.setItalic(italic)
     font.setUnderline(Underline)
     return font
コード例 #18
0
ファイル: console_sci.py プロジェクト: Geoneer/QGIS
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)

        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black))))
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.api = QsciAPIs(self.lexer)
        chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True, type=bool)
        chekBoxPreparedAPI = self.settings.value("pythonConsole/usePreparedAPIFile", False, type=bool)
        if chekBoxAPI:
            pap = os.path.join(QgsApplication.pkgDataPath(), "python", "qsci_apis", "pyqgis.pap")
            self.api.loadPrepared(pap)
        elif chekBoxPreparedAPI:
            self.api.loadPrepared(self.settings.value("pythonConsole/preparedAPIFile"))
        else:
            apiPath = self.settings.value("pythonConsole/userAPI", [])
            for i in range(0, len(apiPath)):
                self.api.load(unicode(apiPath[i]))
            self.api.prepare()
            self.lexer.setAPIs(self.api)

        self.setLexer(self.lexer)
コード例 #19
0
ファイル: editorbase.py プロジェクト: urban-ai/VIBe2UrbanSim
    def __init__(self, mainwindow):
        QsciScintilla.__init__(self, mainwindow)
        self.mainwindow = mainwindow
        ## define the font to use
        font = QFont()
        font.setFamily("Consolas")
        font.setFixedPitch(True)
        font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        fm = QFontMetrics(font)

        ## set the default font of the editor
        ## and take the same font for line numbers
        self.setFont(font)
        self.setMarginsFont(font)

        ## Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.setMarginWidth(0, fm.width( "00000" ) + 5)
        self.setMarginLineNumbers(0, True)

        ## Edge Mode shows a red vetical bar at 80 chars
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor("#CCCCCC"))

        ## Folding visual : we will use boxes
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        ## Braces matching
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        ## Editing line color
        #self.setCaretLineVisible(True)
        #self.setCaretLineBackgroundColor(QColor("#CDA869"))

        ## Margins colors
        # line numbers margin
        self.setMarginsBackgroundColor(QColor("#333333"))
        self.setMarginsForegroundColor(QColor("#CCCCCC"))

        # folding margin colors (foreground,background)
        #self.setFoldMarginColors(QColor("#99CC66"),QColor("#333300"))
        self.setFoldMarginColors(QColor("#CCCCCC"),QColor("#CCCCCC"))

        ## Choose a lexer
        lexer = QsciLexerPython()
        lexer.setDefaultFont(font)
        self.setLexer(lexer)
コード例 #20
0
ファイル: nippy.py プロジェクト: Aligorith/nippy
	def setup_ui(self):
		# Set the default font
		font = QFont('Consolas')
		#font.setFamily('Courier')
		font.setFixedPitch(True)
		font.setPointSize(10)
		self.setFont(font)
		self.setMarginsFont(font)

		# Margin 0 is used for line numbers
		fontmetrics = QFontMetrics(font)
		self.setMarginsFont(font)
		self.setMarginWidth(0, fontmetrics.width("0000") + 8)
		self.setMarginLineNumbers(0, True)
		self.setMarginsBackgroundColor(QColor("#dedede"))
		self.setMarginsForegroundColor(QColor("#555555"))
		
		# Clickable margin 1 for showing markers
		self.setMarginSensitivity(1, True)
		self.marginClicked.connect(self.on_margin_clicked)
		self.markerDefine(QsciScintilla.Circle, self.BOOKMARK_MARKER_NUM)
		self.setMarkerBackgroundColor(QColor("#FFD54D"), self.BOOKMARK_MARKER_NUM)
		self.setMarkerForegroundColor(QColor("#BB663D"), self.BOOKMARK_MARKER_NUM)
		
		# Brace matching: enable for a brace immediately before or after
		# the current position
		self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
		
		# Current line visible with special background color
		self.setCaretLineVisible(True)
		self.setCaretLineBackgroundColor(QColor("#eeeeee"))
		
		# Indent guides
		#SETINDENTATIONGUIDES
		self.setIndentationGuides(True)
		self.setIndentationGuidesForegroundColor(QColor("#aaaaaa"))
		
		self.setWhitespaceVisibility(QsciScintilla.WsVisible)
		self.setWhitespaceForegroundColor(QColor("#eeeeee"))
		
		# Indent size defaults
		self.setIndentationsUseTabs(True) # XXX: auto-detect - or per-file type
		
		self.setIndentationWidth(4) # used for the size of indent steps - hardcoded to my liking - make this per-file type
		self.setTabWidth(4) # used for the size of tabs - hardcoded to my liking - make this per-file type
		
		self.setAutoIndent(True)
コード例 #21
0
ファイル: RulesEditor.py プロジェクト: goc9000/baon
    def __init__(self, parent):
        super().__init__(parent)

        mono_font = QFont()
        mono_font.setFixedPitch(True)

        self.setFont(mono_font)
        self.setAcceptRichText(False)
        self.setTabChangesFocus(True)

        self._highlighter = RulesEditorHighlighter(self.document())

        self._quiescence_timer = QTimer(self)
        self._quiescence_timer.setSingleShot(True)
        self._quiescence_timer.setInterval(self.QUIESCENCE_TIME_MSEC)
        self._quiescence_timer.timeout.connect(self._on_quiescence_timer_timeout)

        self.document().contentsChanged.connect(self._on_contents_changed)
コード例 #22
0
    def __init__(self, parent=None, log=''):
        QTextEdit.__init__(self, parent)
        console.__init__(self)
	self.completion = completion.Completion(self)
	taskmanager = TaskManager()
        self.vfs = vfs.vfs()
        self.log = log or ''
        if parent is None:
            self.eofKey = Qt.Key_D
        else:
            self.eofKey = None
        self.line    = QString()
        self.lines   = []
        self.point   = 0
        self.more    = 0
        self.reading = 0
        self.pointer = 0
        self.cursor_pos   = 0
	font = QFont("Courier")
	font.setFixedPitch(1)
	fm = QFontMetrics(font)	
       	self.fontwidth = fm.averageCharWidth()
	self.setFont(font)
        self.bgcolor = QColor("black")
        self.fgcolor = QColor("white")
        self.selcolor = QColor("green")
        pal = QPalette()
        pal.setColor(pal.Base, self.bgcolor)
        pal.setColor(pal.Text, self.fgcolor)
        self.setPalette(pal)
        self.preloop()
        self.cwd = self.vfs.getcwd()
        self.ps1 = self.cwd.path + "/" + self.cwd.name + " > "
	self.redirect = RedirectIO()
	self.sig = "Sputtext"
	self.connect(self, SIGNAL(self.sig), self.puttext)
	self.redirect.addparent(self, ["ui.gui.widget.shell", "ui.console.console", "ui.console.completion", "ui.console.line_to_arguments", "api.taskmanager.taskmanager", "api.taskmanager.scheduler", "api.taskmanager.processus"], True)
        self.write('Welcome to dff shell\n')
        self.write(self.ps1)
コード例 #23
0
    def __init__(self, databaseFile, lastMathML, parent=None):
        QtGui.QWidget.__init__(self, parent)

        self.ui = Ui_PatternEditorWindow()
        self.ui.setupUi(self)

        # Make the fonts bigger
        font = QFont()
        font.setPointSize(12)
        font.setFamily('Consolas')
        font.setFixedPitch(True)
        self.ui.databaseEditor.setFont(font)
        self.ui.mathmlEditor.setFont(font)

        self.currentFile = databaseFile.strip()

        # If I actually got something, then let's load the file in
        if len(self.currentFile) > 0:
            try:
                f = open(self.currentFile, 'r')
                contents = f.read()
                f.close()
                self.ui.databaseEditor.setText(contents)
            except IOError:
                print 'Database file doesn\'t exist! Resetting to nothing...'
                self.currentFile = ''

        try:
            self.mathTTS = MathTTS(databaseFile)
        except Exception:
            self.mathTTS = None

#         self.stagesModel = QStandardItemModel()
#         self.stageTrees = []
#         self.updateStagesModel()

        self.ui.mathmlEditor.setText(unicode(lastMathML))

        self.connect_signals()
コード例 #24
0
ファイル: console_output.py プロジェクト: HeatherHillers/QGIS
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black))))
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7)
        self.lexer.setColor(QColor(Qt.red), 14)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 2)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.setLexer(self.lexer)
コード例 #25
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black))))
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7)
        self.lexer.setColor(QColor(Qt.red), 14)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 2)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.setLexer(self.lexer)
コード例 #26
0
ファイル: errorreporting.py プロジェクト: tomazc/orange3
    def __init__(self, data):
        icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning)
        F = self.DataField

        def _finished(*, key=(data.get(F.MODULE),
                              data.get(F.WIDGET_MODULE)),
                      filename=data.get(F.WIDGET_SCHEME)):
            self._cache.add(key)
            try: os.remove(filename)
            except Exception: pass

        super().__init__(None, Qt.Window, modal=True,
                         sizeGripEnabled=True, windowIcon=icon,
                         windowTitle='Unexpected Error',
                         finished=_finished)
        self._data = data

        layout = QVBoxLayout(self)
        self.setLayout(layout)
        labels = QWidget(self)
        labels_layout = QHBoxLayout(self)
        labels.setLayout(labels_layout)
        labels_layout.addWidget(QLabel(pixmap=icon.pixmap(50, 50)))
        labels_layout.addWidget(QLabel(
            'The program encountered an unexpected error. Please<br>'
            'report it anonymously to the developers.<br><br>'
            'The following data will be reported:'))
        labels_layout.addStretch(1)
        layout.addWidget(labels)
        font = QFont('Monospace', 10)
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        textbrowser = QTextBrowser(self,
                                   font=font,
                                   openLinks=False,
                                   lineWrapMode=QTextBrowser.NoWrap,
                                   anchorClicked=QDesktopServices.openUrl)
        layout.addWidget(textbrowser)

        def _reload_text():
            add_scheme = cb.isChecked()
            settings.setValue('error-reporting/add-scheme', add_scheme)
            lines = ['<table>']
            for k, v in data.items():
                if k.startswith('_'):
                    continue
                _v, v = v, escape(v)
                if k == F.WIDGET_SCHEME:
                    if not add_scheme:
                        continue
                    v = '<a href="{}">{}</a>'.format(urljoin('file:', pathname2url(_v)), v)
                if k == F.STACK_TRACE:
                    v = v.replace('\n', '<br>').replace(' ', '&nbsp;')
                lines.append('<tr><th align="left">{}:</th><td>{}</td></tr>'.format(k, v))
            lines.append('</table>')
            textbrowser.setHtml(''.join(lines))

        settings = QSettings()
        cb = QCheckBox(
            'Include workflow (data will NOT be transmitted)', self,
            checked=settings.value('error-reporting/add-scheme', True, type=bool))
        cb.stateChanged.connect(_reload_text)
        _reload_text()

        layout.addWidget(cb)
        buttons = QWidget(self)
        buttons_layout = QHBoxLayout(self)
        buttons.setLayout(buttons_layout)
        buttons_layout.addWidget(QPushButton('Send Report (Thanks!)', default=True, clicked=self.accept))
        buttons_layout.addWidget(QPushButton("Don't Send", default=False, clicked=self.reject))
        layout.addWidget(buttons)
コード例 #27
0
ファイル: textItem.py プロジェクト: johnjohnsp1/dff
class textItem(QTextEdit):
    def __init__(self, parent):
        QTextEdit.__init__(self)
        self.initValues(parent)
        self.initFont()

    #        self.initColors()
    #        self.initTab()

    def initTab(self):
        cursor = self.textCursor()
        #        self.tableformat = QTextTableFormat()
        self.table = cursor.insertTable(1, 3)
        self.printOffset(0)

    #        print self.table.rows()

    def initValues(self, parent):
        self.heditor = parent
        # Buffer
        self.buffer = []
        self.bufferLines = 0
        # Line
        self.currentLine = 0
        # Offset
        self.startOffset = 0

        self.row = {}
        self.line = []

        #        self.setAcceptsHoverEvents(True)

        self.document = QTextDocument()
        self.setDocument(self.document)

        self.cursor = self.textCursor()

    #        self.setTextCursor(self.cursor)

    def initFont(self):
        # Font
        self.font = QFont("Courier")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(14)
        self.setCurrentFont(self.font)
        # Cursor

    # Just after new read
    def formatBuffer(self, buff, offset):
        t = time.time()
        self.startOffset = offset

        del self.buffer
        pos = str(len(buff)) + "B"
        self.buffer = struct.unpack(pos, buff)
        self.bufferLines = len(self.buffer) / 16
        #        for index in block:
        #            byte = "%.2x" % index
        #            if count < 15:
        #                byte += " "
        #                count += 1
        #            else:
        #                byte += "\n"
        #                count = 0
        #            self.buffer.append(byte)
        print time.time() - t

    def printLine(self, line, offset):
        count = 0
        start = line * 16
        dline = self.buffer[start : start + 16]
        # Print Offset
        self.setTextColor(Qt.black)

        cell = self.table.cellAt(0, 1)
        cellCursor = cell.firstCursorPosition()

        cellCursor.insertText(" | ")
        for byte in dline:
            if count % 2 == 0:
                self.setTextColor(Qt.black)
                cellCursor.insertText("%.2x" % byte)
            else:
                self.setTextColor(Qt.blue)
                cellCursor.insertText("%.2x" % byte)
            cellCursor.insertText(" ")
            count += 1
        #            print count
        self.setTextColor(Qt.black)
        cellCursor.insertText("| ")
        # self.printAscii(dline)

        cellCursor.insertText("\n")

    #        print self.buffer
    #        self.setPlainText(self.buffer)
    #        self.colorizeText()

    def printOffset(self, offset):
        self.setCurrentFont(self.font)
        self.setTextColor(Qt.red)
        cell = self.table.cellAt(0, 0)
        cellCursor = cell.firstCursorPosition()
        #        cursor = self.table.cellAt(0, 0).firstCursorPosition()
        cellCursor.insertText("%.10d" % offset)

    def printAscii(self, line):
        for char in line:
            if str(char) in string.printable:
                self.insertPlainText(str(char))
            else:
                self.insertPlainText(".")

    def printBuffer(self):
        t = time.time()
        # Clean text
        self.moveCursor(QTextCursor.Start)
        self.moveCursor(QTextCursor.End, QTextCursor.KeepAnchor)

        self.setCurrentFont(self.font)

        offset = self.startOffset
        #        self.printOffset(offset)

        l = self.currentLine
        while l < self.bufferLines:
            self.printLine(l, offset)
            l += 1
            offset += 16

        print "E"
        self.moveCursor(QTextCursor.Start)
        print time.time() - t

    def initColors(self):
        # Blue Color
        self.blue = QBrush(QColor(Qt.blue))
        self.blueFormat = QTextCharFormat()
        self.blueFormat.setFont(self.font)
        self.blueFormat.setForeground(self.blue)

    def colorizeText(self):
        self.size = self.buffer.size()
        cur = self.textCursor()
        pos = cur.position()
        #        self.moveCursor(QTextCursor.Start)
        while pos < self.size:
            self.moveCursor(QTextCursor.NextWord)
            self.moveCursor(QTextCursor.EndOfWord, QTextCursor.KeepAnchor)

            cur = self.textCursor()
            #            self.setTextColor(QColor(Qt.blue))
            cur.setCharFormat(self.blueFormat)

            self.moveCursor(QTextCursor.NextWord)

            cur = self.textCursor()
            pos = cur.position()
        #            print pos

        self.moveCursor(QTextCursor.Start)
コード例 #28
0
ファイル: python.py プロジェクト: pyros2097/SabelIDE
class Python(QsciLexerPython):
    def __init__(self, parent):
        QsciLexerPython.__init__(self, parent)
        self.parent = parent
        self.plainFont = QFont()
        self.plainFont.setFamily(config.fontName())
        self.plainFont.setFixedPitch(True)
        self.plainFont.setPointSize(config.fontSize())
        self.boldFont = QFont(self.plainFont)
        self.boldFont.setBold(True)
        self.setFoldCompact(True)

    def setColors(self, editStyle):
        self.base = QColor(editStyle["base"])  # This is the font color
        self.back = QColor(editStyle["back"])  # This is the bg color
        self.comment = QColor(editStyle["comment"])
        self.number = QColor(editStyle["number"])
        self.keyword = QColor(editStyle["keyword"])
        self.string = QColor(editStyle["string"])
        self.operator = QColor(editStyle["operator"])
        self.styles = [
            # index description color paper font eol
            QsciStyle(0, QString("base"), self.base, self.back, self.plainFont, True),
            QsciStyle(1, QString("comment"), self.comment, self.back, self.plainFont, True),
            QsciStyle(4, QString("number"), self.number, self.back, self.plainFont, True),
            QsciStyle(5, QString("Keyword"), self.keyword, self.back, self.boldFont, True),
            QsciStyle(6, QString("String"), self.string, self.back, self.plainFont, True),
            QsciStyle(10, QString("Operator"), self.operator, self.back, self.plainFont, False),
        ]

    def language(self):
        return "Python"

    def foldCompact(self):
        return self._foldcompact

    def setFoldCompact(self, enable):
        self._foldcompact = bool(enable)

    def description(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.description()
        return QString("")

    def defaultColor(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.color()
        return QsciLexerPython.defaultColor(self, ix)

    def defaultFont(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.font()
        return QsciLexerPython.defaultFont(self, ix)

    def defaultPaper(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.paper()
        return QsciLexerPython.defaultPaper(self, ix)

    def defaultEolFill(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.eolFill()
        return QsciLexerPython.defaultEolFill(self, ix)
コード例 #29
0
ファイル: qscintilla.py プロジェクト: pienkowb/omelette
    def set_up(self):
        """Widget configuration"""
        self.setToolTip("")
        self.setWhatsThis("")

        self.setUtf8(True)
        self.setEolMode(self.EolUnix)

        ##font to use
        font = QFont()
        font.setFamily("Consolas")
        font.setFixedPitch(True)
        font.setPointSize(10)

        ##font metrics to build margin width
        fm = QFontMetrics(font)

        ##default font for editor
        self.setFont(font)
        self.setMarginsFont(font)

        ##line numbers
        self.setMarginWidth(0, fm.width("00000") + 5)
        self.setMarginLineNumbers(0, True)

        ##folding visual
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        ##brace matching
        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        ##line color editing
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor("#CDA869"))

        ##margins color
        self.setMarginsBackgroundColor(QColor("#333333"))
        self.setMarginsForegroundColor(QColor("#CCCCCC"))

        ##folding margins color
        self.setFoldMarginColors(QColor("#99CC66"), QColor("#333300"))

        ##indentation
        self.setAutoIndent(True)
        self.setIndentationWidth(4)
        self.setIndentationGuides(True)
        self.setIndentationsUseTabs(False)

        ##code auto completion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsDocument)

        ##edge mode shows vertical line at 80 chars
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor("#FF0000"))

        ##choosing a lexer
        lexer = QsciLexerPython(self)
        lexer.setDefaultFont(font)
        self.setLexer(lexer)
コード例 #30
0
    def __init__(self, data):
        icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning)
        F = self.DataField

        def _finished(*,
                      key=(data.get(F.MODULE), data.get(F.WIDGET_MODULE)),
                      filename=data.get(F.WIDGET_SCHEME)):
            self._cache.add(key)
            try:
                os.remove(filename)
            except Exception:
                pass

        super().__init__(None,
                         Qt.Window,
                         modal=True,
                         sizeGripEnabled=True,
                         windowIcon=icon,
                         windowTitle='Unexpected Error',
                         finished=_finished)
        self._data = data

        layout = QVBoxLayout(self)
        self.setLayout(layout)
        labels = QWidget(self)
        labels_layout = QHBoxLayout(self)
        labels.setLayout(labels_layout)
        labels_layout.addWidget(QLabel(pixmap=icon.pixmap(50, 50)))
        labels_layout.addWidget(
            QLabel('The program encountered an unexpected error. Please<br>'
                   'report it anonymously to the developers.<br><br>'
                   'The following data will be reported:'))
        labels_layout.addStretch(1)
        layout.addWidget(labels)
        font = QFont('Monospace', 10)
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        textbrowser = QTextBrowser(self,
                                   font=font,
                                   openLinks=False,
                                   lineWrapMode=QTextBrowser.NoWrap,
                                   anchorClicked=QDesktopServices.openUrl)
        layout.addWidget(textbrowser)

        def _reload_text():
            add_scheme = cb.isChecked()
            settings.setValue('error-reporting/add-scheme', add_scheme)
            lines = ['<table>']
            for k, v in data.items():
                if k.startswith('_'):
                    continue
                _v, v = v, escape(v)
                if k == F.WIDGET_SCHEME:
                    if not add_scheme:
                        continue
                    v = '<a href="{}">{}</a>'.format(
                        urljoin('file:', pathname2url(_v)), v)
                if k == F.STACK_TRACE:
                    v = v.replace('\n', '<br>').replace(' ', '&nbsp;')
                lines.append(
                    '<tr><th align="left">{}:</th><td>{}</td></tr>'.format(
                        k, v))
            lines.append('</table>')
            textbrowser.setHtml(''.join(lines))

        settings = QSettings()
        cb = QCheckBox('Include workflow (data will NOT be transmitted)',
                       self,
                       checked=settings.value('error-reporting/add-scheme',
                                              True,
                                              type=bool))
        cb.stateChanged.connect(_reload_text)
        _reload_text()

        layout.addWidget(cb)
        buttons = QWidget(self)
        buttons_layout = QHBoxLayout(self)
        buttons.setLayout(buttons_layout)
        buttons_layout.addWidget(
            QPushButton('Send Report (Thanks!)',
                        default=True,
                        clicked=self.accept))
        buttons_layout.addWidget(
            QPushButton("Don't Send", default=False, clicked=self.reject))
        layout.addWidget(buttons)
コード例 #31
0
ファイル: hexView.py プロジェクト: halbbob/dff
class hexView(QGraphicsView):
    def __init__(self, parent):
        QGraphicsView.__init__(self)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.whex = parent
        self.bdiff = self.whex.bdiff
        #Init scene
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        #Get bdiff stuff
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setAlignment(Qt.AlignLeft)

    def setItems(self):
        self.scene.addItem(self.whex.offsetitem)
        self.scene.addItem(self.whex.hexitem)
        self.scene.addItem(self.whex.asciitem)

    def initShape(self):
        self.initHeads()
        #Line decoration
        offsetLine = QGraphicsLineItem(QLineF(90, 0, 90, 700))
        asciiLine = QGraphicsLineItem(QLineF(480, 0, 480, 700))
        #Add to scene
        self.scene.addItem(offsetLine)
        self.scene.addItem(asciiLine)

    def initHeads(self):
        self.offHead = QGraphicsTextItem()
        self.hexHead = QGraphicsTextItem()
        self.asciiHead = QGraphicsTextItem()
        #Set Color
        self.offHead.setDefaultTextColor(QColor(Qt.red))
        self.hexHead.setDefaultTextColor(QColor(Qt.black))
        self.asciiHead.setDefaultTextColor(QColor(Qt.darkCyan))
        #Create Font
        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(14)
        #Set Font
        self.offHead.setFont(self.font)
        self.hexHead.setFont(self.font)
        self.asciiHead.setFont(self.font)
        #Set Text
        self.offHead.setPlainText("Offset")
        self.hexHead.setPlainText("0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F")
        self.asciiHead.setPlainText("Ascii")
        #Position
        self.offHead.setPos(20, 0)
        self.hexHead.setPos(95, 0)
        self.asciiHead.setPos(520, 0)
        #Add to scene
        self.scene.addItem(self.offHead)
        self.scene.addItem(self.hexHead)
        self.scene.addItem(self.asciiHead)
        headLine = QGraphicsLineItem(QLineF(0, 20, 615, 20))
        self.scene.addItem(headLine)

    def setSyncView(self, whexview):
        self.whexviewsync = whexview

    def move(self, step, way):
        #step: line = 1 * bytesPerLine, page = pagesize, wheel = 3 * bytesPerLine
        offset = self.bdiff.currentOffset
#        print offset
        if way == 0:
        #UP
            if (offset - (step * self.bdiff.bytesPerLine)) >= 0:
                self.bdiff.readOffset(offset - (step * self.bdiff.bytesPerLine))
                if self.bdiff.scrollbar.isLFMOD():
                    self.bdiff.scrollbar.setValue(self.bdiff.scrollbar.offsetToValue(offset - (step * self.bdiff.bytesPerLine)))
                else:
                    self.bdiff.scrollbar.setValue(self.bdiff.scrollbar.value() - step)
            else:
                self.bdiff.readOffset(0)
                self.bdiff.scrollbar.setValue(0)
        elif way == 1:
       #Down
            if (offset + (step * self.bdiff.bytesPerLine)) <= (self.bdiff.masterFileSize - (step * self.bdiff.bytesPerLine)):
                self.bdiff.readOffset(offset + (step * self.bdiff.bytesPerLine))
                if self.bdiff.scrollbar.isLFMOD():
                    self.bdiff.scrollbar.setValue(self.bdiff.scrollbar.offsetToValue(offset + (step * self.bdiff.bytesPerLine)))
                else:
                    self.bdiff.scrollbar.setValue(self.bdiff.scrollbar.value() + step)
            else:
                self.bdiff.readOffset(self.bdiff.masterFileSize - 5 * (self.bdiff.bytesPerLine))             
                self.bdiff.scrollbar.setValue(self.bdiff.scrollbar.max)


####################################
#        Navigation Operations     #
####################################

    def wheelEvent(self, event):
        offset = self.bdiff.currentOffset
        if event.delta() > 0:
            self.move(3, 0)
            self.whexviewsync.move(3, 0)
        else:
            self.move(3, 1)
            self.whexviewsync.move(3, 1)


    def keyPressEvent(self, keyEvent):
        off = self.bdiff.currentOffset
        if keyEvent.matches(QKeySequence.MoveToNextPage):
            self.move(self.bdiff.pageSize / self.bdiff.bytesPerLine, 1)
            self.whexviewsync.move(self.bdiff.pageSize / self.bdiff.bytesPerLine, 1)
        elif keyEvent.matches(QKeySequence.MoveToPreviousPage):
            self.move(self.bdiff.pageSize / self.bdiff.bytesPerLine, 0)
            self.whexviewsync.move(self.bdiff.pageSize / self.bdiff.bytesPerLine, 0)
        elif keyEvent.matches(QKeySequence.MoveToNextLine):
            self.move(1, 1)
            self.whexviewsync.move(1, 1)
        elif keyEvent.matches(QKeySequence.MoveToPreviousLine):
            self.move(1, 0)
            self.whexviewsync.move(1, 0)
コード例 #32
0
class SqlEdit(QsciScintilla):

    LEXER_PYTHON = 0
    LEXER_R = 1

    def __init__(self, parent=None):
        QsciScintilla.__init__(self, parent)

        self.mylexer = None
        self.api = None

        self.setCommonOptions()
        self.initShortcuts()

    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
        self.setAutoCompletionCaseSensitivity(False)

        # Load font from Python console settings
        settings = QSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', 10))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setStretch(QFont.SemiCondensed)
        self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        self.defaultFont.setBold(False)

        self.boldFont = QFont(self.defaultFont)
        self.boldFont.setBold(True)

        self.italicFont = QFont(self.defaultFont)
        self.italicFont.setItalic(True)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

        self.initLexer()

    def initShortcuts(self):
        (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16)

        # Disable some shortcuts
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY,
                           ord('L') + ctrl + shift)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)

        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)

        # Use Ctrl+Space for autocompletion
        self.shortcutAutocomplete = QShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_Space), self)
        self.shortcutAutocomplete.setContext(Qt.WidgetShortcut)
        self.shortcutAutocomplete.activated.connect(self.autoComplete)

    def autoComplete(self):
        self.autoCompleteFromAll()

    def initLexer(self):
        self.mylexer = QsciLexerSQL()

        colorDefault = QColor('#2e3436')
        colorComment = QColor('#c00')
        colorCommentBlock = QColor('#3465a4')
        colorNumber = QColor('#4e9a06')
        colorType = QColor('#4e9a06')
        colorKeyword = QColor('#204a87')
        colorString = QColor('#ce5c00')

        self.mylexer.setDefaultFont(self.defaultFont)
        self.mylexer.setDefaultColor(colorDefault)

        self.mylexer.setColor(colorComment, 1)
        self.mylexer.setColor(colorNumber, 2)
        self.mylexer.setColor(colorString, 3)
        self.mylexer.setColor(colorString, 4)
        self.mylexer.setColor(colorKeyword, 5)
        self.mylexer.setColor(colorString, 6)
        self.mylexer.setColor(colorString, 7)
        self.mylexer.setColor(colorType, 8)
        self.mylexer.setColor(colorCommentBlock, 12)
        self.mylexer.setColor(colorString, 15)

        self.mylexer.setFont(self.italicFont, 1)
        self.mylexer.setFont(self.boldFont, 5)
        self.mylexer.setFont(self.boldFont, 8)
        self.mylexer.setFont(self.italicFont, 12)

        self.setLexer(self.mylexer)

    def lexer(self):
        return self.mylexer
コード例 #33
0
ファイル: asciiItem.py プロジェクト: kzwkt/dff
class asciiItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
        self.initFont()
        self.initMetricsValues()
#        self.initCursor()

    def initPosition(self):
        self.setPos(485, 25)
#        self.setTextInteractionFlags(Qt.TextSelectableByMouse)

    def initValues(self, whex):
        self.whex = whex
        self.heditor = self.whex.heditor
        #Buffer
        self.buffer = []
        self.bufferLines = 0
        #Line
        self.currentLine = 0
        #Offset
        self.startOffset = 0
        self.fontPixel = 14
        #Current Positions
        self.currentPos = 0

#    def initCursor(self):
#        self.cursor = asciiCursor(self)
#        self.heditor.scene.addItem(self.cursor)

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.darkCyan))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        self.setFont(self.font)
        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 1
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * 16)
#        print "start ASCII blank"
#        print self.startBlank

#Print Operations

    def printBuffer(self, buff):
        del self.buffer
        self.buffer = buff

        count = 0
        printer = QString()

        for char in buff:
            if char > "\x20" and char < "\x7e":
                printer.append(char)
            else:
                printer.append(".")
            if count < 15:
                count += 1
            else:
                printer.append("\n")
                count = 0

        #Clear and set
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(printer)
        cursor.movePosition(QTextCursor.Start)
        #Update pixel Informations

    def updateCurrentSelection(self, posx, posy):
        self.currentSelection = self.heditor.currentOffset + (
            (posy * 16) + posx)

    def getXPos(self, x):
        count = 0
        current = self.byteW + (self.startBlank / 2)
        while current < x:
            count += 1
            current = current + self.byteW
        return count

    def getYPos(self, y):
        count = 0
        current = self.byteH
        while current < y:
            count += 1
            current = current + self.byteH
        return count

    def mouseMoveEvent(self, event):
        pos = event.pos()
        x = pos.x()
        y = pos.y()
        xpos = self.getXPos(x)
        ypos = self.getYPos(y)
        self.heditor.selection.select(self.heditor.selection.xstart,
                                      self.heditor.selection.ystart, xpos,
                                      ypos)
        if not self.heditor.preview:
            self.heditor.infos.update()
            self.heditor.right.decode.update()

    def mousePressEvent(self, event):
        button = event.button()
        pos = event.pos()

        if event.button() == 1:
            #Get Clicked coordonates
            x = pos.x()
            y = pos.y()
            #Transform pixel into cursor position
            xpos = self.getXPos(x)
            ypos = self.getYPos(y)

            self.whex.asciicursor.draw(xpos, ypos)
            self.whex.hexcursor.draw(xpos, ypos)
            #Refresh hexadecimal cursor
            self.heditor.selection.select(xpos, ypos, xpos, ypos, True)
            if not self.heditor.preview:
                self.heditor.right.decode.update()
                self.heditor.infos.update()

    def mouseReleaseEvent(self, event):
        pass
コード例 #34
0
    def createWidgets(self):
        """
        QsciScintilla widget creation
        """
        self.setFrameShape(QFrame.NoFrame)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        # Lexer/Highlighter settings
        lexer = CustomPythonLexer(self)

        fontSettings = Settings.instance().readValue(
            key='Editor/font').split(",")
        font = fontSettings[0]
        fontSize = fontSettings[1]
        defaultFont = QFont(font, int(fontSize))
        defaultFont.setFixedPitch(True)

        lexer.setDefaultFont(defaultFont)

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        lexer.setIndentationWarning(QsciLexerPython.Inconsistent)

        if self.activePyLexer:
            self.setLexer(lexer)

            # api = QsciAPIs(lexer)
            # api.add('aLongString')
            # api.add('aLongerString')
            # api.add('aDifferentString')
            # api.add('sOmethingElse')
            # api.prepare()

            # self.setAutoCompletionThreshold(1)
            # self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        lexerProperties = QsciLexerProperties(self)
        if self.activePropertiesLexer:
            self.setLexer(lexerProperties)

        ## Editing line color
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(
            QColor(Settings.instance().readValue(
                key='Editor/color-current-line')))
        self.setUtf8(True)
        self.setAutoIndent(True)
        self.setTabWidth(2)
        self.setIndentationsUseTabs(True)
        self.setEolMode(QsciScintilla.EolUnix)
        self.activeFolding(False)
        self.setIndentationGuidesVisible(False)
        self.setTabIndents(True)

        # margins
        self.setMarginLineNumbers(1, False)
        self.setMarginWidth(1, 0)
        self.setMarginsBackgroundColor(Qt.gray)
        marginFont = QFont()
        marginFont.setBold(False)
        self.setMarginsFont(marginFont)
        self.setMarginsForegroundColor(Qt.white)

        # text wrapping
        if self.wrappingText: self.setWrappingMode(wrap=True)

        # folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # indicators
        if sys.version_info > (3, ):
            self.matchIndicator = self.indicatorDefine(
                QsciScintilla.INDIC_FULLBOX, 9)
            self.setIndicatorForegroundColor(
                QColor(Settings.instance().readValue(
                    key='Editor/color-indicator')), self.matchIndicator)
            self.setIndicatorDrawUnder(True, self.matchIndicator)

            self.findOccurenceThread = FindOccurenceThread()
            self.findOccurenceThread.markOccurrence.connect(self.markOccurence)

        # selection
        self.setSelectionBackgroundColor(
            QColor(Settings.instance().readValue(
                key='Editor/color-selection-background')))
コード例 #35
0
class Framework(QObject):

    X_RAFT_ID = 'X-RAFT-ID'

    def __init__(self, parent = None):
        QObject.__init__(self, parent)
        self._global_cookie_jar = InMemoryCookieJar(self, self)
        self._db = None
        self._contentExtractor = None
        self._networkAccessManager = None
        self._scopeController = None
        self._scopeConfig = None
        self._requestResponseFactory = None
        self.zoom_size = 0
        self.base_font = QFont()
        self.monospace_font = QFont('Courier New')
        self.monospace_font.setFixedPitch(True)
        self.monospace_font.setStyleHint(QFont.TypeWriter)
        pointSize = self.monospace_font.pointSize()
        basePointSize = self.base_font.pointSize()
        if pointSize <= basePointSize:
            pointSize = basePointSize + 2
            self.monospace_font.setPointSize(pointSize)
        self.python_code_font = QFont()
        self.python_code_font.setPointSize(pointSize)
        self.home_dir = QDir.toNativeSeparators(QDir.homePath())
        self.raft_dir = self.create_raft_directory(self.home_dir, '.raft')
        self.user_db_dir = self.create_raft_directory(self.raft_dir, 'db')
        self.user_data_dir = self.create_raft_directory(self.raft_dir, 'data')
        self.user_analyzer_dir = self.create_raft_directory(self.raft_dir, 'analyzers')
        self.user_web_path = self.create_raft_directory(self.raft_dir, 'web')
        self.web_db_path = self.user_web_path
        # TODO: there may be a Qt way to give executable path as well
        self._executable_path = os.path.abspath(os.path.dirname(sys.argv[0]))
        self._data_dir = os.path.join(self._executable_path, 'data')
        self._analyzer_dir = os.path.join(self._executable_path, 'analyzers')
        self._raft_config_cache = {}
        # configuration defaults
        self._default_useragent = 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_7; en-us) AppleWebKit/533.21.1 (KHTML, like Gecko) Version/5.0.5 Safari/533.21.1'
        # callbacks
        self._open_url_in_browser = None
        self._open_content_in_browser = None
        
    def create_raft_directory(self, basepath, dirname):
        dirtarget = os.path.join(basepath, dirname)
        if not os.path.exists(dirtarget):
            os.mkdir(dirtarget)
        return dirtarget

    def useragent(self):
        if self._db is None:
            return self._default_useragent
        if self.get_raft_config_value('browser_custom_user_agent', bool, False):
            return self.get_raft_config_value('browser_user_agent_value', str, self._default_useragent)
        else:
            return self._default_useragent

    def default_useragent(self):
        return self._default_useragent
        
    def getDB(self):
        if self._db is None:
            raise Exception('database is not initialized')
        return self._db

    def setDB(self, db, dbname):
        if self._db is not None:
            raise Exception('database is already initialized')
        self._db = db
        self._db_uuid = self._db.get_db_uuid()
        self.web_db_path = self.create_raft_directory(self.user_web_path, self._db_uuid)
        self._raft_config_cache = {}
        self.emit(SIGNAL('raftConfigPopulated()'))
        self.emit(SIGNAL('databaseAttached()'))

    def closeDB(self):
        self.emit(SIGNAL('databaseDetached()'))
        self._db = None

    def subscribe_database_events(self, attach_callback, detach_callback):
        QObject.connect(self, SIGNAL('databaseAttached()'), attach_callback, Qt.DirectConnection)
        QObject.connect(self, SIGNAL('databaseDetached()'), detach_callback, Qt.DirectConnection)
        # if database is already available, invoke attach callback directly
        if self._db is not None:
            attach_callback()

    def get_temp_db_filename(self):
        # default filename is temp.raftdb
        return os.path.join(self.user_db_dir, 'temp.raftdb')

    def get_web_db_path(self):
        return self.web_db_path

    def get_user_home_dir(self):
        return self.home_dir

    def get_analyzer_paths(self):
        return [self._analyzer_dir, self.user_analyzer_dir]

    def get_data_dir(self):
        return self._data_dir

    def getContentExtractor(self):
        return self._contentExtractor

    def setContentExtractor(self, contentExtractor):
        self._contentExtractor = contentExtractor

    def getRequestResponseFactory(self):
        return self._requestResponseFactory

    def setRequestResponseFactory(self, requestResponseFactory):
        self._requestResponseFactory = requestResponseFactory

    def getScopeController(self):
        return self._scopeController

    def setScopeController(self, scopeController):
        self._scopeController = scopeController

    def getSpiderConfig(self):
        return self._spiderConfig

    def setSpiderConfig(self, spiderConfig):
        self._spiderConfig = spiderConfig

    def getNetworkAccessManager(self):
        return self._networkAccessManager

    def setNetworkAccessManager(self, networkAccessManager):
        self._networkAccessManager = networkAccessManager

    def subscribe_response_data_added(self, callback):
        QObject.connect(self, SIGNAL('responseDataAdded()'), callback, Qt.DirectConnection) 

    def signal_response_data_added(self):
        self.emit(SIGNAL('responseDataAdded()'))
        QThread.yieldCurrentThread()

    def subscribe_zoom_in(self, callback):
        QObject.connect(self, SIGNAL('zoomIn()'), callback, Qt.DirectConnection) 

    def unsubscribe_zoom_in(self, callback):
        QObject.disconnect(self, SIGNAL('zoomIn()'), callback) 

    def get_zoom_size(self):
        return self.zoom_size

    def signal_zoom_in(self):
        self.zoom_size += 1
        self.emit(SIGNAL('zoomIn()'))

    def subscribe_zoom_out(self, callback):
        QObject.connect(self, SIGNAL('zoomOut()'), callback, Qt.DirectConnection) 

    def unsubscribe_zoom_out(self, callback):
        QObject.disconnect(self, SIGNAL('zoomOut()'), callback) 

    def signal_zoom_out(self):
        self.zoom_size -= 1
        self.emit(SIGNAL('zoomOut()'))

    def get_font(self):
        return self.base_font

    def get_monospace_font(self):
        return self.monospace_font

    def get_python_code_font(self):
        return self.python_code_font

    def subscribe_responses_cleared(self, callback):
        QObject.connect(self, SIGNAL('responsesCleared()'), callback, Qt.DirectConnection)

    def signal_responses_cleared(self):
        self.emit(SIGNAL('responsesCleared()'))

    def set_global_cookie_jar(self, cookie_jar):
        self._global_cookie_jar = cookie_jar

    def get_global_cookie_jar(self):
        return self._global_cookie_jar

    def signal_cookie_jar_updated(self):
        self.emit(SIGNAL('cookieJarUpdated()'))

    def import_raw_cookie_list(self, raw_cookie_list):
        cookieJar = self.get_global_cookie_jar()
        # merge cookies
        cookie_list = cookieJar.allCookies()
        for raw_cookie in raw_cookie_list:
            cookies = QNetworkCookie.parseCookies(raw_cookie)
            for cookie in cookies:
                if cookie not in cookie_list:
                    cookie_list.append(cookie)

        cookieJar.setAllCookies(cookie_list)
        self.signal_cookie_jar_updated()

    def subscribe_cookie_jar_updated(self, callback):
        QObject.connect(self, SIGNAL('cookieJarUpdated()'), callback, Qt.DirectConnection)

    def subscribe_raft_config_populated(self, callback):
        QObject.connect(self, SIGNAL('raftConfigPopulated()'), callback, Qt.DirectConnection)
        if self._db is not None:
            callback()

    def unsubscribe_raft_config_populated(self, callback):
        QObject.disconnect(self, SIGNAL('raftConfigPopulated()'), callback)

    def subscribe_raft_config_updated(self, callback):
        QObject.connect(self, SIGNAL('raftConfigUpdated(QString, QVariant)'), callback, Qt.DirectConnection)

    def unsubscribe_raft_config_updated(self, callback):
        QObject.disconnect(self, SIGNAL('raftConfigUpdated(QString, QVariant)'), callback)

    def set_raft_config_value(self, name, value):
        if name in self._raft_config_cache:
            if str(value) == str(self._raft_config_cache[name]):
                return
        cursor = self._db.allocate_thread_cursor()
        self._db.set_config_value(cursor, 'RAFT', name, value)
        cursor.close()
        self._db.release_thread_cursor(cursor)
        self._raft_config_cache[name] = value
        self.emit(SIGNAL('raftConfigUpdated(QString, QVariant)'), name, value)

    def get_raft_config_value(self, name, rtype = str, default_value = None):
        if name in self._raft_config_cache:
            value = self._raft_config_cache[name]
            if value is not None:
                return rtype(value)
            else:
                return default_value
        cursor = self._db.allocate_thread_cursor()
        value = self._db.get_config_value(cursor, 'RAFT', name, rtype, default_value)
        cursor.close()
        self._db.release_thread_cursor(cursor)
        self._raft_config_cache[name] = value
        return value

    def set_config_value(self, component, name, value):
        if 'RAFT' == component.upper():
            self.set_raft_config_value(name, value)
        else:
            cursor = self._db.allocate_thread_cursor()
            self._db.set_config_value(cursor, component, name, value)
            cursor.close()
            self._db.release_thread_cursor(cursor)

    def get_config_value(self, component, name, rtype = str, default_value = None):
        # TODO: implement config cache
        if 'RAFT' == component.upper():
            return self.get_raft_config_value(name, rtype, default_value)
        else:
            cursor = self._db.allocate_thread_cursor()
            value = self._db.get_config_value(cursor, component, name, rtype, default_value)
            cursor.close()
            self._db.release_thread_cursor(cursor)
            return value
    
    def clear_config_value(self, component, name=None):
        cursor = self._db.allocate_thread_cursor()
        value = self._db.clear_config_value(cursor, component, name)
        cursor.close()
        self._db.release_thread_cursor(cursor)
    
    @functools.lru_cache(maxsize=16, typed=False)
    def get_request_response(self, response_id):
        return self._requestResponseFactory.fill(response_id)

    def report_implementation_issue(self, message):
        self.send_log_message('INTERNAL ERROR', '\n'.join(message))
        print(('INTERNAL ERROR:\n%s' % message))

    def report_implementation_error(self, exc):
        message = traceback.format_exception(type(exc), exc, exc.__traceback__)
        self.send_log_message('INTERNAL ERROR', '\n'.join(message))
        print(('INTERNAL ERROR:\n%s' % message))

    def report_exception(self, exc):
        message = traceback.format_exception(type(exc), exc, exc.__traceback__)
        self.send_log_message('EXCEPTION', '\n'.join(message))
        print(('EXCEPTION:\n%s' % message))

    def log_warning(self, msg):
        self.send_log_message('WARNING', msg)
        print(('WARNING', msg))

    def console_log(self, msg):
        self.send_log_message('LOG', msg)
        print(msg)

    def debug_log(self, msg):
        self.send_log_message('DEBUG', msg)
        print(('DEBUG', msg))

    def subscribe_add_differ_response_id(self, callback):
        QObject.connect(self, SIGNAL('differAddResponseId(int)'), callback, Qt.DirectConnection)

    def send_response_id_to_differ(self, Id):
        # TODO: consider accepting cursor
        cursor = self._db.allocate_thread_cursor()
        if self._db.add_differ_item(cursor, int(Id)):
            self.emit(SIGNAL('differAddResponseId(int)'), int(Id))
        cursor.close()
        self._db.release_thread_cursor(cursor)

    def send_response_list_to_differ(self, id_list):
        # TODO: consider accepting cursor
        cursor = self._db.allocate_thread_cursor()
        added_list = self._db.add_differ_list(cursor, id_list)
        # TODO: send as whole list?
        for Id in added_list:
            self.emit(SIGNAL('differAddResponseId(int)'), int(Id))
        cursor.close()
        self._db.release_thread_cursor(cursor)

    def subscribe_populate_requester_response_id(self, callback):
        QObject.connect(self, SIGNAL('requesterPopulateResponseId(int)'), callback, Qt.DirectConnection)
        
    def subscribe_populate_bulk_requester_responses(self, callback):
        QObject.connect(self, SIGNAL('bulkRequesterPopulateResponses(QList<int>)'), callback, Qt.DirectConnection)
        
    def subscribe_populate_webfuzzer_response_id(self, callback):
        QObject.connect(self, SIGNAL('webfuzzerPopulateResponseId(int)'), callback, Qt.DirectConnection)

    def subscribe_populate_domfuzzer_response_id(self, callback):
        QObject.connect(self, SIGNAL('domfuzzerPopulateResponseId(int)'), callback, Qt.DirectConnection)

    def subscribe_populate_domfuzzer_response_list(self, callback):
        QObject.connect(self, SIGNAL('domfuzzerPopulateResponseList(QStringList)'), callback, Qt.DirectConnection)

    def subscribe_populate_spider_response_id(self, callback):
        QObject.connect(self, SIGNAL('spiderPopulateResponseId(int)'), callback, Qt.DirectConnection)

    def subscribe_populate_spider_response_list(self, callback):
        QObject.connect(self, SIGNAL('spiderPopulateResponseList(QStringList)'), callback, Qt.DirectConnection)

    def send_response_id_to_requester(self, Id):
        self.emit(SIGNAL('requesterPopulateResponseId(int)'), int(Id))

    def send_responses_to_bulk_requester(self, ids):
        self.emit(SIGNAL('bulkRequesterPopulateResponses(QList<int>)'), ids)
        
    def send_response_id_to_webfuzzer(self, Id):
        self.emit(SIGNAL('webfuzzerPopulateResponseId(int)'), int(Id))

    def send_response_id_to_domfuzzer(self, Id):
        self.emit(SIGNAL('domfuzzerPopulateResponseId(int)'), int(Id))

    def send_response_list_to_domfuzzer(self, id_list):
        self.emit(SIGNAL('domfuzzerPopulateResponseList(QStringList)'), id_list)

    def send_response_id_to_spider(self, Id):
        self.emit(SIGNAL('spiderPopulateResponseId(int)'), int(Id))

    def send_response_list_to_spider(self, id_list):
        self.emit(SIGNAL('spiderPopulateResponseList(QStringList)'), id_list)

    def subscribe_add_sequence_builder_response_id(self, callback):
        QObject.connect(self, SIGNAL('sequenceBuilderAddResponseId(int)'), callback, Qt.DirectConnection)

    def send_response_id_to_sequence_builder(self, Id):
        # TODO: consider accepting cursor
        cursor = self._db.allocate_thread_cursor()
        if self._db.add_sequence_builder_manual_item(cursor, int(Id)):
            self.emit(SIGNAL('sequenceBuilderAddResponseId(int)'), int(Id))
        cursor.close()
        self._db.release_thread_cursor(cursor)
        
    def subscribe_sequences_changed(self, callback):
        QObject.connect(self, SIGNAL('sequencesChanged()'), callback, Qt.DirectConnection)

    def signal_sequences_changed(self):
        self.emit(SIGNAL('sequencesChanged()'))

    def subscribe_populate_tester_csrf(self, callback):
        QObject.connect(self, SIGNAL('testerPopulateCSRFResponseId(int)'), callback, Qt.DirectConnection)

    def send_to_tester_csrf(self, Id):
        self.emit(SIGNAL('testerPopulateCSRFResponseId(int)'), int(Id))

    def subscribe_populate_tester_click_jacking(self, callback):
        QObject.connect(self, SIGNAL('testerPopulateClickJackingResponseId(int)'), callback, Qt.DirectConnection)

    def send_to_tester_click_jacking(self, Id):
        self.emit(SIGNAL('testerPopulateClickJackingResponseId(int)'), int(Id))

    def subscribe_log_events(self, callback):
        QObject.connect(self, SIGNAL('logMessageReceived(QString, QString)'), callback, Qt.DirectConnection)

    def send_log_message(self, message_type, message):
        self.emit(SIGNAL('logMessageReceived(QString, QString)'), message_type, message)

    def register_browser_openers(self, open_url, open_content):
        if self._open_url_in_browser is None:
            self._open_url_in_browser = open_url
            QObject.connect(self, SIGNAL('openUrlInBrowser(QString)'), self._open_url_in_browser, Qt.DirectConnection)

        if self._open_content_in_browser is None:
            self._open_content_in_browser = open_content
            QObject.connect(self, SIGNAL('openContentInBrowser(QString, QByteArray, QString)'), self._open_content_in_browser, Qt.DirectConnection)

    def open_url_in_browser(self, url):
        self.emit(SIGNAL('openUrlInBrowser(QString)'), url)

    def open_content_in_browser(self, url, body, mimetype=''):
        if isinstance(body, str):
            data = body.encode('utf-8') # TODO: vary based on mimetype ?
        else:
            data = body
        self.emit(SIGNAL('openContentInBrowser(QString, QByteArray, QString)'), url, data, mimetype)
コード例 #36
0
ファイル: hexItem.py プロジェクト: kzwkt/dff
class hexItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
        self.initFont()
        self.initMetricsValues()

    def initPosition(self):
        self.setPos(95, 25)

    def initValues(self, whex):
        self.whex = whex
        self.bdiff = self.whex.bdiff
        self.hexview = self.whex.view
        #Buffer
        self.buffer = []
        self.fontPixel = 14
        #Current Position

        self.bytesPerLine = self.bdiff.bytesPerLine
        self.groupBytes = self.bdiff.groupBytes

        #Selection
        self.select = False
        self.xsel = 0
        self.ysel = 0

    def initDocument(self):
        self.document = QTextDocument()
        self.setDocument(self.document)

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.black))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        #        self.setFont(self.font)
        self.setFont(self.font)

        #Search Highlight font
        self.sfont = QFont("Gothic")
        self.sfont.setFixedPitch(1)
        self.sfont.setBold(False)
        self.sfont.setPixelSize(self.fontPixel)

        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 2 * self.groupBytes
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * self.bytesPerLine) - (
            self.charW * (self.bytesPerLine - 1))

    #Print Operations

    def dumpHexBuffer(self, buff):
        self.printFullBuffer(buff)

    def dumpEOF(self):
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText("\t\tEnd of file")
        cursor.movePosition(QTextCursor.Start)

    def printFullBuffer(self, buff):
        del self.buffer
        pos = str(len(buff)) + 'B'
        self.buffer = struct.unpack(pos, buff)
        count = 0
        fullBuff = QString()
        for byte in self.buffer:
            fullBuff.append("%.2x" % byte)
            if count < 15:
                fullBuff.append(" ")
                count += 1
            else:
                fullBuff.append("\n")
                count = 0

        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(fullBuff)
        cursor.movePosition(QTextCursor.Start)

    def colorizeDiff(self, diffinfos):
        cursor = self.textCursor()
        cursor.setPosition(QTextCursor.Start)

        text = self.toPlainText()

        keys = diffinfos.keys()
        keys.sort()
        for offset in keys:
            difflen = diffinfos[offset]
            pos = (offset * 2) + offset
            count = difflen + (((offset + difflen) / 16) - (offset / 16))

            cursor.setPosition(pos, QTextCursor.MoveAnchor)
            cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor,
                                count)

            format = QTextCharFormat()
            format.setFont(self.sfont)
            format.setForeground(QBrush(QColor(Qt.red)))
            cursor.setCharFormat(format)
            cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor)
コード例 #37
0
class asciiItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
        self.initFont()
        self.initMetricsValues()
#        self.initCursor()

    def initPosition(self):
        self.setPos(485, 25)
#        self.setTextInteractionFlags(Qt.TextSelectableByMouse)

    def initValues(self, whex):
        self.whex = whex
        self.bdiff = self.whex.bdiff
        #Buffer
        self.buffer = []
        self.bufferLines = 0 
        #Line
        self.currentLine = 0
        #Offset
        self.startOffset = 0
        self.fontPixel = 14
        #Current Positions
        self.currentPos = 0

#    def initCursor(self):
#        self.cursor = asciiCursor(self)
#        self.bdiff.scene.addItem(self.cursor)

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.darkCyan))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        self.setFont(self.font)

        self.sfont = QFont("Gothic")
        self.sfont.setFixedPitch(1)
        self.sfont.setBold(False)
        self.sfont.setPixelSize(self.fontPixel)

        self.metric = QFontMetrics(self.font)

        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 1
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * 16)
#        print "start ASCII blank"
#        print self.startBlank

    #Print Operations
    def printBuffer(self, buff):
        del self.buffer
        self.buffer = buff

        count = 0
        printer = QString()

        for char in buff:
            if char > "\x20" and char < "\x7e":
               printer.append(char)
            else:
                printer.append(".")
            if count < 15:
                count += 1
            else:
                printer.append("\n")
                count = 0

        #Clear and set
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(printer)
        cursor.movePosition(QTextCursor.Start)


    def colorizeDiff(self, diffinfos):
        cursor = self.textCursor()
        cursor.setPosition(QTextCursor.Start)

        text = self.toPlainText()

        keys = diffinfos.keys()
        keys.sort()

        for offset in keys:
            difflen = diffinfos[offset]
            pos = offset + (offset / 16)
#            count =  offset / 16

#            print "offset ", offset, " count ", count

            count = difflen + (((offset + difflen) / 16) - (offset / 16))
#            count = difflen
            cursor.setPosition(pos, QTextCursor.MoveAnchor)
#            print "L", l, " len ", pos + difflen
            cursor.movePosition(QTextCursor.NextCharacter, QTextCursor.KeepAnchor, count)

            format = QTextCharFormat()
            format.setFont(self.sfont)
            format.setForeground(QBrush(QColor(Qt.red)))
            cursor.setCharFormat(format)
            cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor)
コード例 #38
0
ファイル: pageView.py プロジェクト: kzwkt/dff
class pageView(QGraphicsView):
    def __init__(self, wpage):
        QGraphicsView.__init__(self)
        self.init(wpage)
        self.initShape()

#        self.selection = pageSelection(self.heditor)

    def init(self, wpage):
        self.wpage = wpage
        self.heditor = wpage.heditor
        self.filesize = self.heditor.filesize
        self.start = True

        self.pagew = 20
        self.pageh = 20

        self.pageItems = []
        self.offsetItems = []
        self.displayLines = 0

    def initShape(self):
        #Scene
        self.scene = QGraphicsScene()
        self.setScene(self.scene)
        #Font
        self.initFont()
        #Headers
        self.setHeads(self.heditor.pagesPerBlock)

        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setAlignment(Qt.AlignLeft)

    def initFont(self):
        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(14)

    def setHeads(self, pagesPerBlock):
        if self.heditor.pageOffView:
            self.setOffsetHead()
        else:
            self.setBlockHead()
        self.setPageHead(self.heditor.pagesPerBlock)

        linesize = 95 + (self.heditor.pagesPerBlock * (self.pagew + 2))
        #Decoration
        headLine = QGraphicsLineItem(QLineF(0, 20, linesize, 20))
        self.scene.addItem(headLine)
        headOffLine = QGraphicsLineItem(QLineF(90, 0, 90, 700))
        self.scene.addItem(headOffLine)


    def setOffsetHead(self):
        self.offHead = QGraphicsTextItem()
        self.offHead.setDefaultTextColor(QColor(Qt.red))
        self.offHead.setFont(self.font)
        self.offHead.setPlainText("Offset(Kb)")
        self.offHead.setPos(5, 0)
        self.scene.addItem(self.offHead)

    def setPageHead(self, len):
        count = 0
        x = 95
        while count < len:
            item = QGraphicsSimpleTextItem()
            item.setFont(self.font)
            item.setText("%.2x" % count)
            item.setPos(x, 3)
            self.scene.addItem(item)
            x += self.pagew + 2
            count += 1

    def setBlockHead(self):
        self.blockHead = QGraphicsTextItem()
        self.blockHead.setDefaultTextColor(QColor(Qt.red))
        self.blockHead.setFont(self.font)
        self.blockHead.setPlainText("Block")
        self.blockHead.setPos(15, 0)
        self.scene.addItem(self.blockHead)

    def initOffsetItems(self):
        count = 0
        x = 0
        y = 25
        while count <= self.displayLines:
            item = QGraphicsTextItem()
            item.setDefaultTextColor(QColor(Qt.red))
            item.setFont(self.font)
            item.setPos(x, y)
            self.offsetItems.append(item)
            y += self.pageh + 2
            count += 1
        #Add Items in scene
        for item in self.offsetItems:
            self.scene.addItem(item)

    def initPageItems(self):
        id = 0
        countpage = 0
        startx = 95
        starty = 25
        x = startx
        y = starty
        line = 0
        while line <= self.displayLines:
            while countpage < self.heditor.pagesPerBlock:
                p = page(x, y, id, self)
                self.pageItems.append(p)
                id += 1
#                self.scene.addItem(sec)
                x += self.pagew + 2
                countpage += 1
            x = startx
            y += self.pageh + 2
            countpage = 0
            line += 1
        #Add items in scene
        for item in self.pageItems:
            self.scene.addItem(item)

    def hidePageItems(self, startid):
        end = len(self.pageItems)
        for item in self.pageItems[startid:end]:
            item.setVisible(False)

    def setAllPageItemsVisible(self):
        for item in self.pageItems:
            item.setVisible(True)

    def hideOffsetItems(self, startid):
        end = len(self.offsetItems)
        for item in self.offsetItems[startid:end]:
            item.setVisible(False)

    def setAllOffsetItemsVisible(self):
        for item in self.offsetItems:
            item.setVisible(True)

    def appendOffsetItems(self, linesToAppend):
        count = 0
        x = 0
        y = 25 + (len(self.offsetItems) * (self.pageh + 2))
#        print "Y append offset ", y
        while count <= linesToAppend:
            item = QGraphicsTextItem()
            item.setDefaultTextColor(QColor(Qt.red))
            item.setFont(self.font)
            item.setPos(x, y)
            self.offsetItems.append(item)
            self.scene.addItem(item)
            y += self.pageh + 2
            count += 1

    def appendPageItems(self, linesToAppend):
        count = 0
        cp = 0
        x = 95
        y = 25 + ((len(self.pageItems) / self.heditor.pagesPerBlock) * (self.pageh + 2))
        id = len(self.pageItems)

        while count <= linesToAppend:
            while cp < self.heditor.pagesPerBlock:
                item = page(x, y, id, self)
                self.pageItems.append(item)
                self.scene.addItem(item)
                id += 1
                x += self.pagew + 2
                cp += 1
            count += 1
            x = 95
            y += self.pageh + 2

    def refreshOffsetItems(self, offset):
        #Check if end of pages or if number of pages < display pages
        self.setAllOffsetItemsVisible()

        block = (offset / self.heditor.pageSize) / self.heditor.pagesPerBlock
        startBlockOffset = block * (self.heditor.pagesPerBlock * self.heditor.pageSize)


        lineToDisplay = ((self.filesize - offset) / self.heditor.pageSize) / self.heditor.pagesPerBlock


        if ((self.filesize - offset) / self.heditor.pageSize) % self.heditor.pagesPerBlock > 0:
            lineToDisplay += 1

        if lineToDisplay >= self.displayLines:
            offset = startBlockOffset
            for item in self.offsetItems[0:self.displayLines]:
                if self.heditor.decimalview:
                    if self.heditor.pageOffView:
                        offlabel = QString("%.10d" % (offset / 1024))
                    else:
                        offlabel = QString("%.10d" % (offset / (self.heditor.pageSize * self.heditor.pagesPerBlock)))
                else:
                    if self.heditor.pageOffView:
                        offlabel = QString("%.10x" % (offset / 1024))
                    else:
                        offlabel = QString("%.10x" % (offset / (self.heditor.pageSize * self.heditor.pagesPerBlock)))
                item.setPlainText(offlabel)
                offset = offset + (self.heditor.pagesPerBlock * self.heditor.pageSize)
            self.heditor.startBlockOffset = startBlockOffset
        else:
            if lineToDisplay == 0:
                lineToDisplay = 5
                offset = startBlockOffset - (lineToDisplay * self.heditor.pagesPerBlock * self.heditor.pageSize)
                if ((self.filesize - offset) / self.heditor.pageSize) % self.heditor.pagesPerBlock > 0:
                    lineToDisplay += 1

                self.heditor.startBlockOffset = offset

            for item in self.offsetItems[0:lineToDisplay]:
                if self.heditor.decimalview:
                    if self.heditor.pageOffView:
                        offlabel = QString("%.10d" % (offset / 1024))
                    else:
                        offlabel = QString("%.10d" % (offset / (self.heditor.pageSize * self.heditor.pagesPerBlock)))
                else:
                    if self.heditor.pageOffView:
                        offlabel = QString("%.10x" % (offset / 1024))
                    else:
                        offlabel = QString("%.10x" % (offset / (self.heditor.pageSize * self.heditor.pagesPerBlock)))
                item.setPlainText(offlabel)
                offset = offset + (self.heditor.pagesPerBlock * self.heditor.pageSize)
            self.hideOffsetItems(lineToDisplay)

    def refreshPageItems(self, offset):
        self.setAllPageItemsVisible()
        maxpages = self.displayLines * self.heditor.pagesPerBlock
        displaypages = (self.filesize - offset) / self.heditor.pageSize

        if displaypages <= maxpages:
            if displaypages == 0:
                startline = self.lines - 5
                startOffset = startline * (self.heditor.pageSize * self.heditor.pagesPerBlock)
                rangeOffset = self.filesize - startOffset
                newdisplaypages = rangeOffset / self.heditor.pageSize
                if rangeOffset % self.heditor.pageSize > 0:
                    newdisplaypages += 1

                self.hidePageItems(newdisplaypages)
                self.heditor.startBlockOffset = startOffset
            else:
                rangeOffset = self.filesize - offset
                rangePages = rangeOffset / self.heditor.pageSize
                rangeLines = rangePages / self.heditor.pagesPerBlock
                newdisplaypages = rangeOffset / self.heditor.pageSize

                if rangeOffset % self.heditor.pageSize > 0:
                    newdisplaypages += 1
 
                self.hidePageItems(newdisplaypages)
                self.heditor.startBlockOffset = offset
        else:
            self.heditor.startBlockOffset = offset

        self.heditor.pageselection.update()

    def refreshAllContent(self):
        self.scene.clear()
        del self.offsetItems[:]
        del self.pageItems[:]

        self.setHeads(self.heditor.pagesPerBlock)
        self.initOffsetItems()
        self.initPageItems()
        self.refreshOffsetItems(self.heditor.startBlockOffset)
        self.refreshPageItems(self.heditor.startBlockOffset)

    def lineToOffset(self, line):
        offset = (line * (self.heditor.pagesPerBlock * self.heditor.pageSize))
        return offset
 
    def lineToOffsetKb(self, line):
        offset = (line * (self.heditor.pagesPerBlock * self.heditor.pageSize)) / 1024
        return offset

    def lineToOffsetMb(self, line):
        offset = ((line * (self.heditor.pagesPerBlock * self.heditor.pageSize)) / 1024) / 1024
        return offset

    def lineToOffsetGb(self, line):
        offset = (((line * (self.heditor.pagesPerBlock * self.heditor.pageSize)) / 1024) / 1024) / 1024
        return offset

############################
#       Colorize Pages     #
############################

    def refreshPagesColor(self, id):
#        print "Refresh: ", id
        self.cleanSelection()
        self.pageItems[id].setBrush(QBrush(Qt.green, Qt.SolidPattern))

    def cleanSelection(self):
        item = self.pageItems[self.selectedPage]
        item.setBrush(item.brush)


############################
#       Resize Event       #
############################

    def resizeEvent(self, sizEvent):
        y = sizEvent.size().height()
        disline = (y / self.pageh)
        #Start
        if self.start == True:
            if self.height() < self.heditor.mainWindow.height():
                if disline > self.displayLines:
                    self.displayLines = (y / self.pageh)
                    #Lines
                    self.lines = self.filesize / (self.heditor.pagesPerBlock * self.heditor.pageSize)
                    #Init
                    self.initOffsetItems()
                    self.initPageItems()
                    #Refresh
                    self.refreshOffsetItems(0)
                    self.refreshPageItems(0)

                    if self.lines > self.displayLines:
                        self.wpage.setScrollBar()
                    else:
                        self.wpage.scroll = False
                    self.start = False
        else:
            range = disline - self.displayLines
            if range > 0:
                self.displayLines = (y / self.pageh)
                #Append
                self.appendOffsetItems(range)
                self.appendPageItems(range)
                #Refresh
            self.refreshOffsetItems(self.heditor.startBlockOffset)
            self.refreshPageItems(self.heditor.startBlockOffset)
#            self.heditor.footer.pixel.view.resizeEvent(sizEvent)


############################
#       CallBacks          #
############################

    def wheelEvent(self, event):
        offset = self.heditor.startBlockOffset
#        up = False
        if self.wpage.scroll:
            if event.delta() > 0:
            #UP
                subOffset = 3 * self.heditor.pagesPerBlock * self.heditor.pageSize
                if offset - subOffset > 0:
                    offset = offset - subOffset
                else:
                    offset = 0
            else:
            #DOWN
                addOffset = 3 * self.heditor.pagesPerBlock * self.heditor.pageSize
                if offset + addOffset < self.filesize:
                    offset = offset + addOffset
                else:
                    offset = self.filesize - (5 * self.heditor.pagesPerBlock * self.heditor.pageSize)
        #Set ScrollBar value:
            if offset < self.filesize - (5 * self.heditor.pagesPerBlock * self.heditor.pageSize):
                value = self.wpage.scroll.offsetToValue(offset)
                self.wpage.scroll.setValue(value)
                
                self.refreshOffsetItems(offset)
                self.refreshPageItems(offset)


    def keyPressEvent(self, keyEvent):
	pass
        #if keyEvent.matches(QKeySequence.MoveToNextPage):
            #print "Next block"
        #elif keyEvent.matches(QKeySequence.MoveToPreviousPage):
            #print "Previous block"
        #elif keyEvent.matches(QKeySequence.MoveToNextLine):
            #print "Next Line"
        #elif keyEvent.matches(QKeySequence.MoveToPreviousLine):
            #print "Previous Line"
        #else:
            #pass

    def resetSelection(self):
        for item in self.pageItems:
            item.setBrush(item.brush)

    def getPageID(self, x, y):
        startx = 95
        starty = 25

        #Set scrollbar seek
        hscroll = self.horizontalScrollBar()
        if hscroll.value() > 0:
            startx -= hscroll.value()

        xrange = x - startx
        if xrange > 0:
            xcut = (xrange / (self.pagew + 2))
#            print xcut
        else:
            xcut = 0

        yrange = y - starty
        if yrange > 0:
            ycut = yrange / (self.pageh + 2)
        else:
            ycut = 0
        id = (ycut * self.heditor.pagesPerBlock) + xcut
        return id

    def mousePressEvent(self, event):
        button = event.button()
        pos = event.pos()
        if event.button() == 1:
            #Get CLicked coordonates
            x = pos.x()
            y = pos.y()
            id = self.getPageID(x, y)
            self.resetSelection()
            self.heditor.pageselection.select(id, self.heditor.startBlockOffset, 0)

    def mouseMoveEvent(self, event):
        pos = event.pos()
        x = pos.x()
        y = pos.y()
        if self.heditor.pageselection.mode == 1:
            id = self.getPageID(x, y)
            self.resetSelection()
            self.heditor.pageselection.select(id, self.heditor.startBlockOffset, 1)
#        else:
#            id = self.getPageID(x, y)
#            self.pageItems[id].setBrush(self)
        
    def mouseReleaseEvent(self, event):
        self.heditor.pageselection.mode = 0
コード例 #39
0
ファイル: hexItem.py プロジェクト: halbbob/dff
class hexItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
        self.initFont()
        self.initMetricsValues()

    def initPosition(self):
        self.setPos(95, 25)

    def initValues(self, whex):
        self.whex = whex
        self.bdiff = self.whex.bdiff
        self.hexview = self.whex.view
        #Buffer
        self.buffer = []
        self.fontPixel = 14
        #Current Position

        self.bytesPerLine = self.bdiff.bytesPerLine
        self.groupBytes = self.bdiff.groupBytes

        #Selection
        self.select = False
        self.xsel = 0
        self.ysel = 0

    def initDocument(self):
        self.document = QTextDocument()
        self.setDocument(self.document)

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.black))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
#        self.setFont(self.font)
        self.setFont(self.font)

        #Search Highlight font
        self.sfont = QFont("Gothic")
        self.sfont.setFixedPitch(1)
        self.sfont.setBold(False)
        self.sfont.setPixelSize(self.fontPixel)

        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 2 * self.groupBytes
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * self.bytesPerLine) - (self.charW * (self.bytesPerLine - 1))

    #Print Operations

    def dumpHexBuffer(self, buff):
        self.printFullBuffer(buff)

    def dumpEOF(self):
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText("\t\tEnd of file")
        cursor.movePosition(QTextCursor.Start)

            
    def printFullBuffer(self, buff):
        del self.buffer
        pos = str(len(buff)) + 'B'
        self.buffer = struct.unpack(pos, buff)
        count = 0
        fullBuff = QString()
        for byte in self.buffer:
            fullBuff.append("%.2x" % byte)
            if count < 15:
                fullBuff.append(" ")
                count += 1
            else:
                fullBuff.append("\n")
                count = 0

        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(fullBuff)
        cursor.movePosition(QTextCursor.Start)

    def colorizeDiff(self, diffinfos):
        cursor = self.textCursor()
        cursor.setPosition(QTextCursor.Start)

        text = self.toPlainText()

        keys = diffinfos.keys()
        keys.sort()
        for offset in keys:
            difflen = diffinfos[offset]
            pos = (offset * 2) + offset
            count = difflen + (((offset + difflen) / 16) - (offset / 16))

            cursor.setPosition(pos, QTextCursor.MoveAnchor)
            cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor, count)

            format = QTextCharFormat()
            format.setFont(self.sfont)
            format.setForeground(QBrush(QColor(Qt.red)))
            cursor.setCharFormat(format)
            cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor)
コード例 #40
0
ファイル: lexersquirrel.py プロジェクト: dreadpiratepj/Sabel
class LexerSquirrel(QsciLexerPython):
    words1 = [
        "base",
        "break",
        "case",
        "catch",
        "class",
        "clone",
        "continue",
        "const",
        "default",
        "delete",
        "else",
        "enum",
        "extends",
        "for",
        "foreach",
        "function",
        " if",
        " in",
        "local",
        "null",
        "resume",
        "return",
        "switch",
        "this",
        "throw",
        "try",
        "typeof",
        "while",
        "yield",
        "constructor",
        "instanceof",
        "true",
        "false",
        "static",
    ]

    words2 = [
        "init",
        "dest",
        "onLoad",
        "onDispose",
        "onGainedFocus",
        "onMotionEvent",
        "onLostFocus",
        "onUpdate",
        "onFps",
        "onKeyEvent",
        "onSensorEvent",
        "onControlEvent",
        "onDrawFrame",
        "onError",
        "onLowMemory",
        "onNetCallBack",
    ]

    words3 = [
        "rawdelete",
        "rawin",
        "array",
        "seterrorhandler",
        "setdebughook",
        "enabledebuginfo",
        "getroottable",
        "setroottable",
        "getconsttable",
        "setconsttable",
        "assert",
        "print",
        "compilestring",
        "collectgarbage",
        "type",
        "getstackinfos",
        "newthread",
        "tofloat",
        "tostring",
        "tointeger",
        "tochar",
        "weakref",
        "slice",
        "find",
        "tolower",
        "toupper",
        "len",
        "rawget",
        "rawset",
        "clear",
        "append",
        "push",
        "extend",
        "pop",
        "top",
        "insert",
        "remove",
        "resize",
        "sort",
        "reverse",
        "call",
        "pcall",
        "acall",
        "pacall",
        "bindenv",
        "instance",
        "getattributes",
        "getclass",
        "getstatus",
        "ref",
    ]

    def __init__(self, colorStyle, parent=None):
        QsciLexerPython.__init__(self, parent)
        # self.parent = parent
        # self.sci = self.parent
        self.colorStyle = colorStyle
        self.plainFont = QFont()
        self.plainFont.setFamily(fontName)
        self.plainFont.setFixedPitch(True)
        self.plainFont.setPointSize(fontSize)
        self.marginFont = QFont()
        self.marginFont.setPointSize(10)
        self.marginFont.setFamily("MS Dlg")
        self.boldFont = QFont(self.plainFont)
        self.boldFont.setBold(True)
        """    
        enum {
          Default = 0, Comment = 1, Number = 2,
          DoubleQuotedString = 3, SingleQuotedString = 4, Keyword = 5,
          TripleSingleQuotedString = 6, TripleDoubleQuotedString = 7, ClassName = 8,
          FunctionMethodName = 9, Operator = 10, Identifier = 11,
          CommentBlock = 12, UnclosedString = 13, HighlightedIdentifier = 14,
          Decorator = 15
        }
        enum IndentationWarning {
          NoWarning = 0, Inconsistent = 1, TabsAfterSpaces = 2,
          Spaces = 3, Tabs = 4
        } 
        """
        self.styles = [
            # index description color paper font eol
            QsciStyle(0, QString("base"), self.colorStyle.color, self.colorStyle.paper, self.plainFont, True),
            QsciStyle(1, QString("comment"), QColor("#008000"), self.colorStyle.paper, self.plainFont, True),
            QsciStyle(2, QString("number"), QColor("#008000"), self.colorStyle.paper, self.boldFont, False),
            QsciStyle(3, QString("DoubleQuotedString"), QColor("#008000"), self.colorStyle.paper, self.plainFont, True),
            QsciStyle(4, QString("SingleQuotedString"), QColor("#008000"), self.colorStyle.paper, self.plainFont, True),
            QsciStyle(5, QString("Keyword"), QColor("#000000"), self.colorStyle.paper, self.boldFont, True),
            QsciStyle(
                6, QString("TripleSingleQuotedString"), QColor("#ffd0d0"), self.colorStyle.paper, self.plainFont, True
            ),
            QsciStyle(
                7, QString("TripleDoubleQuotedString"), QColor("#001111"), self.colorStyle.paper, self.plainFont, False
            ),
            QsciStyle(8, QString("ClassName"), QColor("#000000"), self.colorStyle.paper, self.plainFont, False),
            QsciStyle(
                9, QString("FunctionMethodName"), QColor("#000000"), self.colorStyle.paper, self.plainFont, False
            ),
            QsciStyle(10, QString("Operator"), QColor("#ff00ff"), self.colorStyle.paper, self.plainFont, False),
            QsciStyle(11, QString("Identifier"), QColor("#000000"), self.colorStyle.paper, self.plainFont, False),
            QsciStyle(12, QString("CommentBlock"), QColor("#000000"), self.colorStyle.paper, self.plainFont, False),
            QsciStyle(13, QString("UnclosedString"), QColor("#010101"), self.colorStyle.paper, self.plainFont, False),
            QsciStyle(
                14, QString("HighlightedIdentifier"), QColor("#0000ff"), self.colorStyle.paper, self.plainFont, False
            ),
            QsciStyle(15, QString("Decorator"), QColor("#ff00ff"), self.colorStyle.paper, self.plainFont, False)
            # QsciStyle(7, QString("MultiComment_start"), QColor("#ff00ff"), QColor("#001111"), self.plainFont, False),
            # QsciStyle(8, QString("MultiComment"), QColor("#ff00ff"), QColor("#001111"), self.plainFont, False),
            # QsciStyle(9, QString("MultiComment_stop"), QColor("#ff00ff"), QColor("#001111"), self.plainFont, False)
        ]
        self._foldcompact = True

    def setColorStyle(self, cs):
        self.colorStyle = cs
        for i in self.styles:
            i.setPaper(self.colorStyle.paper)
        self.styles[0].setColor(self.colorStyle.color)

    def language(self):
        return "Squirrel"

    def foldCompact(self):
        return self._foldcompact

    def setFoldCompact(self, enable):
        self._foldcompact = bool(enable)

    def description(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.description()
        return QString("")

    def defaultColor(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.color()
        return QsciLexerCustom.defaultColor(self, ix)

    def defaultFont(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.font()
        return QsciLexerCustom.defaultFont(self, ix)

    def defaultPaper(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.paper()
        return QsciLexerCustom.defaultPaper(self, ix)

    def defaultEolFill(self, ix):
        for i in self.styles:
            if i.style() == ix:
                return i.eolFill()
        return QsciLexerCustom.defaultEolFill(self, ix)

    def styleText(self, start, end):
        editor = self.editor()
        if editor is None:
            return

        SCI = editor.SendScintilla
        GETFOLDLEVEL = QsciScintilla.SCI_GETFOLDLEVEL
        SETFOLDLEVEL = QsciScintilla.SCI_SETFOLDLEVEL
        HEADERFLAG = QsciScintilla.SC_FOLDLEVELHEADERFLAG
        LEVELBASE = QsciScintilla.SC_FOLDLEVELBASE
        NUMBERMASK = QsciScintilla.SC_FOLDLEVELNUMBERMASK
        WHITEFLAG = QsciScintilla.SC_FOLDLEVELWHITEFLAG
        set_style = self.setStyling

        source = ""
        if end > editor.length():
            end = editor.length()
        if end > start:
            source = bytearray(end - start)
            SCI(QsciScintilla.SCI_GETTEXTRANGE, start, end, source)
        if not source:
            return

        compact = self.foldCompact()
        index = SCI(QsciScintilla.SCI_LINEFROMPOSITION, start)
        if index > 0:
            pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index - 1)
            prevState = SCI(QsciScintilla.SCI_GETSTYLEAT, pos)
        else:
            prevState = self.styles[0]

        self.startStyling(start, 0x1F)
        for line in source.splitlines(True):
            #  print line
            length = len(line)
            # We must take care of empty lines.This is done here.
            if length == 1:
                if prevState == self.styles[8] or prevState == self.styles[7]:
                    newState = self.styles[8]
                else:
                    newState = self.styles[0]
            # if line.startswith('#'):
            #    newState = self.styles[3]
            # elif line.startswith('\t+') or line.startswith('    +'):
            #    newState = self.styles[3]
            # We work with a non empty line.
            else:
                if line.startswith("@"):
                    newState = self.styles[7]
                elif line.startswith("@"):
                    if prevState == self.styles[8] or prevState == self.styles[7]:
                        newState = self.styles[9]
                    else:
                        newState = self.styles[0]
                # elif line.startswith('//'):
                #    if prevState == self.styles[8] or prevState == self.styles[7]:
                #        newState = self.styles[8]
                #    else:
                #        newState = self.styles[8]
                elif prevState == self.styles[8] or prevState == self.styles[7]:
                    newState = self.styles[8]
                else:
                    newState = self.styles[0]
                # set_style(length, newState)
                pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index) - length + 1
                i = 0
                while i < length:
                    wordLength = 1

                    self.startStyling(i + pos, 0x1F)
                    newState = self.styles[0]

                    for word in self.words2:
                        if line[i:].startswith(word):
                            newState = self.styles[4]
                            wordLength = len(word)

                    if chr(line[i]) in "0123456789":
                        newState = self.styles[4]
                    else:
                        if line[i:].startswith("class"):
                            newState = self.styles[2]
                            wordLength = len("class")
                        elif line[i:].startswith("function"):
                            newState = self.styles[3]
                            wordLength = len("function")
                        elif line[i:].startswith(" if"):
                            newState = self.styles[4]
                            wordLength = len(" if")
                        elif line[i:].startswith("#"):
                            newState = self.styles[4]
                            wordLength = length
                        elif line[i:].startswith("//"):
                            newState = self.styles[4]
                            wordLength = length
                        elif line[i:].startswith("/*"):
                            newState = self.styles[4]
                            wordLength = length
                        elif line[i:].startswith("*/"):
                            newState = self.styles[4]
                            wordLength = length
                        # else:
                        # newState = self.styles[0]

                    i += wordLength
                    set_style(wordLength, newState)
                newState = None

            if newState:
                set_style(length, newState)

            # Folding
            # folding implementation goes here
            # levelFolder = editor.SendScintilla(editor.SCI_GETFOLDLEVEL, index-1)
            # if line.startswith('+'):
            #     SCI(SETFOLDLEVEL, index, levelFolder + 1)
            #     #editor.SendScintilla(editor.SCI_SETFOLDLEVEL, index, levelFolder + 1)
            # elif line.startswith('function'):
            #     SCI(SETFOLDLEVEL, index, levelFolder + 1)
            # editor.SendScintilla(editor.SCI_SETFOLDLEVEL, index, levelFolder + 1)
            """
            if newState == self.styles[7]:
                if prevState == self.styles[8]:
                    level = LEVELBASE + 1
                else:
                    level = LEVELBASE | HEADERFLAG
            elif newState == self.styles[8] or newState == self.styles[9]:
                level = LEVELBASE + 1
            else:
                level = LEVELBASE

            SCI(SETFOLDLEVEL, index, level)

            pos = SCI(QsciScintilla.SCI_GETLINEENDPOSITION, index)
            prevState = SCI(QsciScintilla.SCI_GETSTYLEAT, pos)"""
            index += 1
コード例 #41
0
class textItem(QTextEdit):
    def __init__(self, parent):
        QTextEdit.__init__(self)
        self.initValues(parent)
        self.initFont()
#        self.initColors()
#        self.initTab()

    def initTab(self):
        cursor = self.textCursor()
        #        self.tableformat = QTextTableFormat()
        self.table = cursor.insertTable(1, 3)
        self.printOffset(0)

#        print self.table.rows()

    def initValues(self, parent):
        self.heditor = parent
        #Buffer
        self.buffer = []
        self.bufferLines = 0
        #Line
        self.currentLine = 0
        #Offset
        self.startOffset = 0

        self.row = {}
        self.line = []

        #        self.setAcceptsHoverEvents(True)

        self.document = QTextDocument()
        self.setDocument(self.document)

        self.cursor = self.textCursor()
#        self.setTextCursor(self.cursor)

    def initFont(self):
        #Font
        self.font = QFont("Courier")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(14)
        self.setCurrentFont(self.font)
        #Cursor

    #Just after new read
    def formatBuffer(self, buff, offset):
        t = time.time()
        self.startOffset = offset

        del self.buffer
        pos = str(len(buff)) + 'B'
        self.buffer = struct.unpack(pos, buff)
        self.bufferLines = len(self.buffer) / 16
        #        for index in block:
        #            byte = "%.2x" % index
        #            if count < 15:
        #                byte += " "
        #                count += 1
        #            else:
        #                byte += "\n"
        #                count = 0
        #            self.buffer.append(byte)
        print time.time() - t

    def printLine(self, line, offset):
        count = 0
        start = line * 16
        dline = self.buffer[start:start + 16]
        #Print Offset
        self.setTextColor(Qt.black)

        cell = self.table.cellAt(0, 1)
        cellCursor = cell.firstCursorPosition()

        cellCursor.insertText(" | ")
        for byte in dline:
            if count % 2 == 0:
                self.setTextColor(Qt.black)
                cellCursor.insertText("%.2x" % byte)
            else:
                self.setTextColor(Qt.blue)
                cellCursor.insertText("%.2x" % byte)
            cellCursor.insertText(" ")
            count += 1
#            print count
        self.setTextColor(Qt.black)
        cellCursor.insertText("| ")
        #self.printAscii(dline)

        cellCursor.insertText("\n")

#        print self.buffer
#        self.setPlainText(self.buffer)
#        self.colorizeText()

    def printOffset(self, offset):
        self.setCurrentFont(self.font)
        self.setTextColor(Qt.red)
        cell = self.table.cellAt(0, 0)
        cellCursor = cell.firstCursorPosition()
        #        cursor = self.table.cellAt(0, 0).firstCursorPosition()
        cellCursor.insertText("%.10d" % offset)

    def printAscii(self, line):
        for char in line:
            if str(char) in string.printable:
                self.insertPlainText(str(char))
            else:
                self.insertPlainText(".")

    def printBuffer(self):
        t = time.time()
        #Clean text
        self.moveCursor(QTextCursor.Start)
        self.moveCursor(QTextCursor.End, QTextCursor.KeepAnchor)

        self.setCurrentFont(self.font)

        offset = self.startOffset
        #        self.printOffset(offset)

        l = self.currentLine
        while l < self.bufferLines:
            self.printLine(l, offset)
            l += 1
            offset += 16

        print "E"
        self.moveCursor(QTextCursor.Start)
        print time.time() - t

    def initColors(self):
        #Blue Color
        self.blue = QBrush(QColor(Qt.blue))
        self.blueFormat = QTextCharFormat()
        self.blueFormat.setFont(self.font)
        self.blueFormat.setForeground(self.blue)

    def colorizeText(self):
        self.size = self.buffer.size()
        cur = self.textCursor()
        pos = cur.position()
        #        self.moveCursor(QTextCursor.Start)
        while pos < self.size:
            self.moveCursor(QTextCursor.NextWord)
            self.moveCursor(QTextCursor.EndOfWord, QTextCursor.KeepAnchor)

            cur = self.textCursor()
            #            self.setTextColor(QColor(Qt.blue))
            cur.setCharFormat(self.blueFormat)

            self.moveCursor(QTextCursor.NextWord)

            cur = self.textCursor()
            pos = cur.position()
#            print pos

        self.moveCursor(QTextCursor.Start)
コード例 #42
0
    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
        self.setAutoCompletionCaseSensitivity(False)

        # Load font from Python console settings
        settings = QSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', 10))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setStretch(QFont.SemiCondensed)
        self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        self.defaultFont.setBold(False)

        self.boldFont = QFont(self.defaultFont)
        self.boldFont.setBold(True)

        self.italicFont = QFont(self.defaultFont)
        self.italicFont.setItalic(True)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

        self.initLexer()
コード例 #43
0
ファイル: sqledit.py プロジェクト: Ariki/QGIS
    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
        self.setAutoCompletionCaseSensitivity(False)

        # Load font from Python console settings
        settings = QSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', 10))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setStretch(QFont.SemiCondensed)
        self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        self.defaultFont.setBold(False)

        self.boldFont = QFont(self.defaultFont)
        self.boldFont.setBold(True)

        self.italicFont = QFont(self.defaultFont)
        self.italicFont.setItalic(True)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

        self.initLexer()
コード例 #44
0
ファイル: MainWindow.py プロジェクト: arneboe/codecomment
    def __init__(self):
        QMainWindow.__init__(self)


        self.data = Data(0)
        self.save_folder = "."
        self.load_yaml()

        # Set up the user interface from qt designer file
        self.ui = uic.loadUi('gui/ui_MainWindow.ui')

        #metadata about the comments, filled every time a comment is added
        self.commentMetaData = {}
        #maps from list widget items to comments
        self.comments = {}
        #maps from marker to marker meta data
        self.markerMetaData = {}

        #initialize the highlighter
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(self.data.fontSize)
        self.ui.plainTextEditCode.setFont(font)
        self.highlighter = Highlighter(self.ui.plainTextEditCode.document())

        #important because otherwise the mapping from block to line breaks
        self.ui.plainTextEditCode.setWordWrapMode(QTextOption.NoWrap)

        #make sure that the cursor is always in the center (improves readability when clickig on comments)
        self.ui.plainTextEditCode.setCenterOnScroll(True)
        self.ui.plainTextEditCode.setReadOnly(True)

        self.labelGroup = QLabel("Group No.")
        self.ui.toolBar.addWidget(self.labelGroup)
        self.lineEditGroup = QLineEdit()
        self.lineEditGroup.setFixedWidth(60)
        self.lineEditGroup.setText(self.data.group_no)
        self.lineEditGroup.textChanged.connect(self.group_no_changed)
        self.ui.toolBar.addWidget(self.lineEditGroup)

        self.labelSheet = QLabel("Sheet No.")
        self.ui.toolBar.addWidget(self.labelSheet)
        self.lineEditSheet = QLineEdit()
        self.lineEditSheet.setFixedWidth(60)
        self.lineEditSheet.setText(self.data.sheet_no)
        self.lineEditSheet.textChanged.connect(self.sheet_no_changed)
        self.ui.toolBar.addWidget(self.lineEditSheet)

        self.labelTutor = QLabel("Tutor")
        self.ui.toolBar.addWidget(self.labelTutor)
        self.lineEditTutor = QLineEdit()
        self.lineEditTutor.setText(self.data.tutor_name)
        self.lineEditTutor.textChanged.connect(self.tutor_name_changed)
        self.ui.toolBar.addWidget(self.lineEditTutor)


        self.ui.actionOpen.triggered.connect(self.open)
        self.ui.actionAdd_Comment.setEnabled(False)#will be enabeled as soon as  a file is added
        self.ui.actionAdd_Comment.triggered.connect(self.add_comment)
        self.ui.actionAdd_Comment_radius_0.setEnabled(False)
        self.ui.actionAdd_Comment_radius_0.triggered.connect(self.add_comment_0_radius)
        self.ui.actionRemove_Comment.setEnabled(False)
        self.ui.actionRemove_Comment.triggered.connect(self.remove_comment)
        self.ui.actionExport.triggered.connect(self.export)
        self.ui.actionExport.setEnabled(False)
        self.ui.actionSave.setEnabled(False)
        self.ui.actionSave.triggered.connect(self.save)
        self.ui.actionLoad.triggered.connect(self.load)

        self.ui.listWidgetFiles.currentItemChanged.connect(self.selected_file_changed)
        self.ui.listWidgetComments.currentItemChanged.connect(self.selected_comment_changed)
        self.ui.plainTextEditComment.textChanged.connect(self.comment_text_changed)
        self.ui.plainTextEditComment.setReadOnly(True)
        self.next_comment_no = 0

        self.ui.spinBoxEndLine.setEnabled(False)
        self.ui.spinBoxStartLine.setEnabled(False)
        self.ui.spinBoxStartLine.valueChanged.connect(self.start_line_changed)
        self.ui.spinBoxEndLine.valueChanged.connect(self.end_line_changed)

        self.ui.action_textbf.triggered.connect(self.textbf)
        self.ui.action_textit.triggered.connect(self.textit)
        self.ui.action_texttt.triggered.connect(self.texttt)
        self.ui.action_lstinline.triggered.connect(self.lstinline)
        self.ui.action_emph.triggered.connect(self.emph)
        self.ui.action_0_25.triggered.connect(self.plus025)
        self.ui.action_0_25_minus.triggered.connect(self.minus025)
        self.ui.action0_5_0_5.triggered.connect(self.points05_05)
        self.ui.action0_0_5.triggered.connect(self.points0_05)


        self.current_comment = None #the currently selected comment, if any

        self.color_names = ["coral", "cornflowerblue", "darksalmon", "darkseagreen",
                            "greenyellow", "plum", "rosybrown", "mistyrose"]

        self.default_color = self.ui.plainTextEditCode.palette().color(QPalette.Base)

        self.save_name = "" #file name used for saving
        self.ui.show();
コード例 #45
0
ファイル: asciiItem.py プロジェクト: udgover/modules
class asciiItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
        self.initFont()
        self.initMetricsValues()
#        self.initCursor()

    def initPosition(self):
        self.setPos(485, 25)
#        self.setTextInteractionFlags(Qt.TextSelectableByMouse)

    def initValues(self, whex):
        self.whex = whex
        self.heditor = self.whex.heditor
        #Buffer
        self.buffer = []
        self.bufferLines = 0 
        #Line
        self.currentLine = 0
        #Offset
        self.startOffset = 0
        self.fontPixel = 14
        #Current Positions
        self.currentPos = 0

#    def initCursor(self):
#        self.cursor = asciiCursor(self)
#        self.heditor.scene.addItem(self.cursor)

    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.darkCyan))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
        self.setFont(self.font)
        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 1
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * 16)
#        print "start ASCII blank"
#        print self.startBlank

    #Print Operations
    def printBuffer(self, buff):
        del self.buffer
        self.buffer = buff

        count = 0
        printer = QString()

        for char in buff:
            if char > "\x20" and char < "\x7e":
               printer.append(char)
            else:
                printer.append(".")
            if count < 15:
                count += 1
            else:
                printer.append("\n")
                count = 0

        #Clear and set
        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(printer)
        cursor.movePosition(QTextCursor.Start)
        #Update pixel Informations

    def updateCurrentSelection(self, posx, posy):
        self.currentSelection = self.heditor.currentOffset + ((posy * 16) + posx)

    def getXPos(self, x):
        count = 0
        current = self.byteW + (self.startBlank / 2)
        while current < x:
            count += 1
            current = current + self.byteW
        return count

    def getYPos(self, y):
        count = 0
        current = self.byteH
        while current < y:
            count += 1
            current = current + self.byteH
        return count

    def mouseMoveEvent(self, event):
        pos = event.pos()
        x = pos.x()
        y = pos.y()
        xpos = self.getXPos(x)
        ypos = self.getYPos(y)
        self.heditor.selection.select(self.heditor.selection.xstart, self.heditor.selection.ystart, xpos, ypos)
	if not self.heditor.preview:
          self.heditor.infos.update()
          self.heditor.right.decode.update()

    def mousePressEvent(self, event):
        button = event.button()
        pos = event.pos()

        if event.button() == 1:
            #Get Clicked coordonates
            x = pos.x()
            y = pos.y()
            #Transform pixel into cursor position
            xpos = self.getXPos(x)
            ypos = self.getYPos(y)

            self.whex.asciicursor.draw(xpos, ypos)
            self.whex.hexcursor.draw(xpos, ypos)
            #Refresh hexadecimal cursor
            self.heditor.selection.select(xpos, ypos, xpos, ypos, True)
	    if not self.heditor.preview:
              self.heditor.right.decode.update()
              self.heditor.infos.update()


    def mouseReleaseEvent(self, event):
        pass
コード例 #46
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext",
                                       "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)

        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(
            QColor(
                self.settings.value("pythonConsole/defaultFontColor",
                                    QColor(Qt.black))))
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/commentFontColor",
                                    QColor(Qt.gray))), 1)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/keywordFontColor",
                                    QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/classFontColor",
                                    QColor(Qt.blue))), 8)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/methodFontColor",
                                    QColor(Qt.darkGray))), 9)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/decorFontColor",
                                    QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/commentBlockFontColor",
                                    QColor(Qt.gray))), 12)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/singleQuoteFontColor",
                                    QColor(Qt.blue))), 4)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/doubleQuoteFontColor",
                                    QColor(Qt.blue))), 3)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/tripleSingleQuoteFontColor",
                                    QColor(Qt.blue))), 6)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/tripleDoubleQuoteFontColor",
                                    QColor(Qt.blue))), 7)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(
                self.settings.value("pythonConsole/paperBackgroundColor",
                                    QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.api = QsciAPIs(self.lexer)
        chekBoxAPI = self.settings.value("pythonConsole/preloadAPI",
                                         True,
                                         type=bool)
        chekBoxPreparedAPI = self.settings.value(
            "pythonConsole/usePreparedAPIFile", False, type=bool)
        if chekBoxAPI:
            pap = os.path.join(QgsApplication.pkgDataPath(), "python",
                               "qsci_apis", "pyqgis.pap")
            self.api.loadPrepared(pap)
        elif chekBoxPreparedAPI:
            self.api.loadPrepared(
                self.settings.value("pythonConsole/preparedAPIFile"))
        else:
            apiPath = self.settings.value("pythonConsole/userAPI", [])
            for i in range(0, len(apiPath)):
                self.api.load(unicode(apiPath[i]))
            self.api.prepare()
            self.lexer.setAPIs(self.api)

        self.setLexer(self.lexer)
コード例 #47
0
ファイル: squirrel.py プロジェクト: pyros2097/SabelIDE
class Squirrel(QsciLexerJavaScript):
    words1 = [
         'base','break','case','catch','class','clone',
         'continue','const','default','delete','else','enum',
         'extends','for','foreach','function',' if',' in',
         'local','null','resume','return','switch','this',
         'throw','try','typeof','while','yield','constructor',
         'instanceof','true','false','static'
        ]
        
    words2 = [
         'init', 'dest', 'onLoad', 'onDispose', 'onGainedFocus','onMotionEvent',
         'onLostFocus','onUpdate','onFps','onKeyEvent','onSensorEvent',
         'onControlEvent','onDrawFrame','onError','onLowMemory','onNetCallBack'
        ]

    words3 = [
        'rawdelete', 'rawin', 'array', 'seterrorhandler', 'setdebughook',
        'enabledebuginfo', 'getroottable', 'setroottable', 'getconsttable',
        'setconsttable', 'assert', 'print', 'compilestring', 'collectgarbage',
        'type', 'getstackinfos', 'newthread', 'tofloat', 'tostring',
        'tointeger', 'tochar', 'weakref', 'slice', 'find', 'tolower',
        'toupper', 'len', 'rawget', 'rawset', 'clear', 'append', 'push',
        'extend', 'pop', 'top', 'insert', 'remove', 'resize', 'sort',
        'reverse', 'call', 'pcall', 'acall', 'pacall', 'bindenv', 'instance',
        'getattributes', 'getclass', 'getstatus', 'ref'
        ]
        
    def __init__(self,parent):
        QsciLexerJavaScript.__init__(self, parent)
        self.parent = parent
        self.plainFont = QFont()
        self.plainFont.setFamily(config.fontName())
        self.plainFont.setFixedPitch(True)
        self.plainFont.setPointSize(config.fontSize())
        self.boldFont = QFont(self.plainFont)
        self.boldFont.setBold(True)
        self.setFoldCompact(True)
        
    def setColors(self, editStyle):
        self.base = QColor(editStyle["base"]) #This is the font color
        self.back = QColor(editStyle["back"]) #This is the bg color
        self.comment = QColor(editStyle["comment"])
        self.number = QColor(editStyle["number"])
        self.keyword = QColor(editStyle["keyword"])
        self.string =  QColor(editStyle["string"])
        self.operator =  QColor(editStyle["operator"])
        self.styles = [
          #index description color paper font eol 
          QsciStyle(0, QString("base"), self.base, self.back, self.plainFont, True),
          QsciStyle(1, QString("comment"), self.comment, self.back, self.plainFont, True),
          QsciStyle(4, QString("number"), self.number, self.back, self.plainFont, True),
          QsciStyle(5, QString("Keyword"), self.keyword, self.back, self.boldFont, True),
          QsciStyle(6, QString("String"), self.string,self.back, self.plainFont, True),
          QsciStyle(10, QString("Operator"), self.operator, self.back, self.plainFont, False)    
        ]
        
    def language(self):
        return 'Squirrel'
    
    def foldCompact(self):
        return self._foldcompact

    def setFoldCompact(self, enable):
        self._foldcompact = bool(enable)

    def description(self, ix):
        for i in self.styles:
          if i.style() == ix:
            return i.description()
        return QString("")
    
    def defaultColor(self, ix):
        for i in self.styles:
          if i.style() == ix:
            return i.color()
        return QsciLexerCPP.defaultColor(self, ix)

    def defaultFont(self, ix):
        for i in self.styles:
          if i.style() == ix:
            return i.font()
        return QsciLexerCPP.defaultFont(self, ix)

    def defaultPaper(self, ix):
        for i in self.styles:
          if i.style() == ix:
            return i.paper()
        return QsciLexerCPP.defaultPaper(self, ix)

    def defaultEolFill(self, ix):
        for i in self.styles:
          if i.style() == ix:
            return i.eolFill()
        return QsciLexerCPP.defaultEolFill(self, ix)
コード例 #48
0
ファイル: console_output.py プロジェクト: HeatherHillers/QGIS
    def __init__(self, parent=None):
        super(ShellOutputScintilla, self).__init__(parent)
        self.parent = parent
        self.shell = self.parent.shell

        self.settings = QSettings()

        # Creates layout for message bar
        self.layout = QGridLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # messageBar instance
        self.infoBar = QgsMessageBar()
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # Enable non-ascii chars for editor
        self.setUtf8(True)

        sys.stdout = writeOut(self, sys.stdout)
        sys.stderr = writeOut(self, sys.stderr, "_traceback")

        self.insertInitText()
        self.refreshSettingsOutput()
        self.setReadOnly(True)

        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)
        # Margin 0 is used for line numbers
        self.setMarginWidth(0, 0)
        self.setMarginWidth(1, 0)
        self.setMarginWidth(2, 0)
        #fm = QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(1, "00000")
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor("#3E3EE3"))
        self.setMarginsBackgroundColor(QColor("#f9f9f9"))
        self.setCaretLineVisible(True)
        self.setCaretWidth(0)

        self.setMinimumHeight(120)

        self.setWrapMode(QsciScintilla.WrapCharacter)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self)
        self.runScut.setContext(Qt.WidgetShortcut)
        self.runScut.activated.connect(self.enteredSelected)
        # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view
        self.copyShortcut = QShortcut(QKeySequence.Copy, self)
        self.copyShortcut.activated.connect(self.copy)
        self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self)
        self.selectAllShortcut.activated.connect(self.selectAll)
コード例 #49
0
    def __init__(self, parent=None):
        super(ShellOutputScintilla, self).__init__(parent)
        self.parent = parent
        self.shell = self.parent.shell

        self.settings = QSettings()

        # Creates layout for message bar
        self.layout = QGridLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # messageBar instance
        self.infoBar = QgsMessageBar()
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # Enable non-ascii chars for editor
        self.setUtf8(True)

        sys.stdout = writeOut(self, sys.stdout)
        sys.stderr = writeOut(self, sys.stderr, "_traceback")

        self.insertInitText()
        self.refreshSettingsOutput()
        self.setReadOnly(True)

        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)
        # Margin 0 is used for line numbers
        self.setMarginWidth(0, 0)
        self.setMarginWidth(1, 0)
        self.setMarginWidth(2, 0)
        #fm = QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(1, "00000")
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor("#3E3EE3"))
        self.setMarginsBackgroundColor(QColor("#f9f9f9"))
        self.setCaretLineVisible(True)
        self.setCaretWidth(0)

        self.setMinimumHeight(120)

        self.setWrapMode(QsciScintilla.WrapCharacter)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self)
        self.runScut.setContext(Qt.WidgetShortcut)
        self.runScut.activated.connect(self.enteredSelected)
        # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view
        self.copyShortcut = QShortcut(QKeySequence.Copy, self)
        self.copyShortcut.activated.connect(self.copy)
        self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self)
        self.selectAllShortcut.activated.connect(self.selectAll)
コード例 #50
0
ファイル: hexItem.py プロジェクト: palaniyappanBala/dff
class hexItem(QGraphicsTextItem):
    def __init__(self, whex):
        QGraphicsTextItem.__init__(self)
        self.initValues(whex)
        self.initPosition()
#        self.initDocument()
        self.initFont()
        self.initMetricsValues()
#        self.initCursor()

    def initPosition(self):
        self.setPos(95, 25)

    def initValues(self, whex):
        self.whex = whex
        self.heditor = self.whex.heditor
        self.hexview = self.whex.view
        #Buffer
        self.buffer = []
        self.fontPixel = 14
        #Current Position

        self.bytesPerLine = self.heditor.bytesPerLine
        self.groupBytes = self.heditor.groupBytes

        #Selection
        self.select = False
        self.xsel = 0
        self.ysel = 0

    def initDocument(self):
        self.document = QTextDocument()
        self.setDocument(self.document)

#    def initSyntaxHighlighter(self):
#        self.search = self.heditor.right.search
#        self.highlighter = highlighter(self)

#    def initCursor(self):
#        self.cursor = hexCursor(self)
#        self.heditor.whex.view.scene.addItem(self.cursor)
 
    def initFont(self):
        self.setDefaultTextColor(QColor(Qt.black))

        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(self.fontPixel)
#        self.setFont(self.font)
        self.setFont(self.font)

        #Search Highlight font
        self.sfont = QFont("Gothic")
        self.sfont.setFixedPitch(1)
        self.sfont.setBold(False)
        self.sfont.setPixelSize(self.fontPixel)

        self.metric = QFontMetrics(self.font)

    def initMetricsValues(self):
        #Calibrate
        calibrate = QString("A")
        self.charsByByte = 2 * self.groupBytes
        self.charW = self.metric.width(calibrate)
        self.charH = self.metric.height()

        self.byteW = self.charW * self.charsByByte
        self.byteH = self.charH

    def initStartBlank(self):
        self.lineW = self.boundingRect().width()
        self.startBlank = self.lineW - (self.byteW * self.bytesPerLine) - (self.charW * (self.bytesPerLine - 1))
#        print "start blank"
#        print self.startBlank

#    def getPatternOffsets(self, buff):
#       plist = self.search.searchedPatterns
#        startoffset = self.heditor.currentOffset
#        offlist = {}

#        for pattern, offsetlist  in plist.iteritems():
#            for offset in offsetlist:
#                if offset >= startoffset and offset <= startoffset + self.heditor.readSize:
#                    offlist[offset - self.heditor.currentOffset] = len(pattern) / 2
#        return offlist

    #Print Operations

    def dumpHexBuffer(self, buff):
        self.printFullBuffer(buff)
#        searchofflist = self.getPatternOffsets(buff)
#        if len(searchofflist) > 0:
#            highoffsets = searchofflist.keys()
#            highoffsets.sort()
#            self.highlighter(searchofflist)
            
    def printFullBuffer(self, buff):
        del self.buffer
        pos = str(len(buff)) + 'B'
        self.buffer = struct.unpack(pos, buff)
        count = 0
        fullBuff = QString()
        for byte in self.buffer:
            fullBuff.append("%.2x" % byte)
            if count < 15:
                fullBuff.append(" ")
                count += 1
            else:
                fullBuff.append("\n")
                count = 0

        cursor = self.textCursor()
        cursor.movePosition(QTextCursor.Start)
        cursor.movePosition(QTextCursor.End, QTextCursor.KeepAnchor)
        self.setPlainText(fullBuff)
        cursor.movePosition(QTextCursor.Start)
#        if len(self.search.searchedPatterns) > 0:
#            self.highlighter.highlightBlock(self.document.toPlainText())

    def getXPos(self, x):
        count = 0
        current = self.byteW + (self.charW / 2) + (self.startBlank / 2)
        while current < x:
            count += 1
            current = current + self.byteW + self.charW
        return count

    def getYPos(self, y):
        count = 0
        current = self.byteH
        while current < y:
            count += 1
            current = current + self.byteH
        return count

    def highlighter(self, searchofflist):
        offsets = searchofflist.keys()
        cursor = self.textCursor()
        cursor.setPosition(QTextCursor.Start)
        for offset in offsets:
            len = searchofflist[offset]
            pos = (offset * 2) + offset
            cursor.setPosition(pos, QTextCursor.MoveAnchor)
            l = 0
            while l < len:
                cursor.movePosition(QTextCursor.NextWord, QTextCursor.KeepAnchor)
                l += 1

            format = QTextCharFormat()
            format.setFont(self.sfont)
            format.setForeground(QBrush(QColor(Qt.red)))
            cursor.setCharFormat(format)
            cursor.setPosition(QTextCursor.Start, QTextCursor.MoveAnchor)



    ############## #
    # MOUSE EVENTS # ###########################
    ############## #

    def mouseMoveEvent(self, event):
        pos = event.pos()
        x = pos.x()
        y = pos.y()
        xpos = self.getXPos(x)
        ypos = self.getYPos(y)
        self.heditor.selection.select(self.heditor.selection.xstart, self.heditor.selection.ystart, xpos, ypos)
        self.heditor.infos.update()
        self.heditor.right.decode.update()

    def mousePressEvent(self, event):
        button = event.button()
        pos = event.pos()
        if event.button() == 1:
            #Get CLicked coordonates
            x = pos.x()
            y = pos.y()
            xpos = self.getXPos(x)
            ypos = self.getYPos(y)
            #refresh cursors
            self.whex.hexcursor.draw(xpos, ypos)
            self.whex.asciicursor.draw(xpos, ypos)

            self.heditor.selection.select(xpos, ypos, xpos, ypos, True)
            self.heditor.right.decode.update()
            self.heditor.infos.update()

    def mouseReleaseEvent(self, event):
        pass
コード例 #51
0
class hexView(QGraphicsView):
    def __init__(self, parent):
        QGraphicsView.__init__(self, None, parent)
        self.init(parent)
        self.initShape()

    def init(self, parent):
        self.whex = parent
        self.heditor = self.whex.heditor
        #Init scene
        self.__scene = QGraphicsScene(self)
        self.setScene(self.__scene)

        #Get heditor stuff
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setAlignment(Qt.AlignLeft)

    def setItems(self):
        self.__scene.addItem(self.whex.offsetitem)
        self.__scene.addItem(self.whex.hexitem)
        self.__scene.addItem(self.whex.asciitem)

    def initShape(self):
        self.initHeads()
        #Line decoration
        offsetLine = QGraphicsLineItem(QLineF(90, 0, 90, 700))
        asciiLine = QGraphicsLineItem(QLineF(480, 0, 480, 700))
        #Add to scene
        self.__scene.addItem(offsetLine)
        self.__scene.addItem(asciiLine)

    def setCursors(self):
        self.__scene.addItem(self.whex.hexcursor)
        self.__scene.addItem(self.whex.asciicursor)

    def initHeads(self):
        self.offHead = QGraphicsTextItem()
        self.hexHead = QGraphicsTextItem()
        self.asciiHead = QGraphicsTextItem()
        #Set Color
        self.offHead.setDefaultTextColor(QColor(Qt.red))
        self.hexHead.setDefaultTextColor(QColor(Qt.black))
        self.asciiHead.setDefaultTextColor(QColor(Qt.darkCyan))
        #Create Font
        self.font = QFont("Gothic")
        self.font.setFixedPitch(1)
        self.font.setBold(False)
        self.font.setPixelSize(14)
        #Set Font
        self.offHead.setFont(self.font)
        self.hexHead.setFont(self.font)
        self.asciiHead.setFont(self.font)
        #Set Text
        self.offHead.setPlainText("Offset")
        self.hexHead.setPlainText(
            "0  1  2  3  4  5  6  7  8  9  A  B  C  D  E  F")
        self.asciiHead.setPlainText("Ascii")
        #Position
        self.offHead.setPos(20, 0)
        self.hexHead.setPos(95, 0)
        self.asciiHead.setPos(520, 0)
        #Add to scene
        self.__scene.addItem(self.offHead)
        self.__scene.addItem(self.hexHead)
        self.__scene.addItem(self.asciiHead)
        headLine = QGraphicsLineItem(QLineF(0, 20, 615, 20))
        self.__scene.addItem(headLine)

    def move(self, step, way):
        #step: line = 1 * bytesPerLine, page = pagesize, wheel = 3 * bytesPerLine
        offset = self.heditor.currentOffset
        if way == 0:
            #UP
            if (offset - (step * self.heditor.bytesPerLine)) >= 0:
                self.heditor.readOffset(offset -
                                        (step * self.heditor.bytesPerLine))
                if self.whex.isLFMOD():
                    self.whex.scroll.setValue(
                        self.whex.offsetToValue(offset - step *
                                                (self.heditor.bytesPerLine)))
                else:
                    self.whex.scroll.setValue(self.whex.scroll.value() - step)
            else:
                self.heditor.readOffset(0)
                self.whex.scroll.setValue(0)
        elif way == 1:
            #Down
            if (offset + (step * self.heditor.bytesPerLine)) <= (
                    self.heditor.filesize -
                (step * self.heditor.bytesPerLine)):
                self.heditor.readOffset(offset +
                                        (step * self.heditor.bytesPerLine))
                if self.whex.isLFMOD():
                    self.whex.scroll.setValue(
                        self.whex.offsetToValue(offset + step *
                                                (self.heditor.bytesPerLine)))
                else:
                    self.whex.scroll.setValue(self.whex.scroll.value() + step)
            else:
                self.heditor.readOffset(self.heditor.filesize - 5 *
                                        (self.heditor.bytesPerLine))
                self.whex.scroll.setValue(self.whex.scroll.max)

####################################
#        Navigation Operations     #
####################################

    def wheelEvent(self, event):
        offset = self.heditor.currentOffset
        if event.delta() > 0:
            self.move(3, 0)
        else:
            self.move(3, 1)

    def keyPressEvent(self, keyEvent):
        #        off = self.heditor.currentOffset
        if keyEvent.matches(QKeySequence.MoveToNextPage):
            self.move(self.heditor.pageSize / self.heditor.bytesPerLine, 1)
        elif keyEvent.matches(QKeySequence.MoveToPreviousPage):
            self.move(self.heditor.pageSize / self.heditor.bytesPerLine, 0)
        elif keyEvent.matches(QKeySequence.MoveToNextWord):
            print "Next Word"
        elif keyEvent.matches(QKeySequence.MoveToPreviousWord):
            print "Previous word"
        elif keyEvent.matches(QKeySequence.MoveToNextLine):
            print "Next Line"
        elif keyEvent.matches(QKeySequence.MoveToPreviousLine):
            print "Previous Line"
コード例 #52
0
ファイル: ScriptEdit.py プロジェクト: HeatherHillers/QGIS
class ScriptEdit(QsciScintilla):

    LEXER_PYTHON = 0
    LEXER_R = 1

    def __init__(self, parent=None):
        QsciScintilla.__init__(self, parent)

        self.lexer = None
        self.api = None
        self.lexerType = -1

        self.setCommonOptions()
        self.initShortcuts()

    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(20)
        self.setFont(font)
        self.setMarginsFont(font)

        self.initLexer()

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        self.setFonts(10)

    def setFonts(self, size):

        # Load font from Python console settings
        settings = QSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', size))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setStretch(QFont.SemiCondensed)
        self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        self.defaultFont.setBold(False)

        self.boldFont = QFont(self.defaultFont)
        self.boldFont.setBold(True)

        self.italicFont = QFont(self.defaultFont)
        self.italicFont.setItalic(True)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

    def initShortcuts(self):
        (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16)

        # Disable some shortcuts
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl
                           + shift)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)

        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)

        # Use Ctrl+Space for autocompletion
        self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL
                                                           + Qt.Key_Space), self)
        self.shortcutAutocomplete.setContext(Qt.WidgetShortcut)
        self.shortcutAutocomplete.activated.connect(self.autoComplete)

    def autoComplete(self):
        self.autoCompleteFromAll()

    def setLexerType(self, lexerType):
        self.lexerType = lexerType
        self.initLexer()

    def initLexer(self):
        if self.lexerType == self.LEXER_PYTHON:
            self.lexer = QsciLexerPython()

            colorDefault = QColor('#2e3436')
            colorComment = QColor('#c00')
            colorCommentBlock = QColor('#3465a4')
            colorNumber = QColor('#4e9a06')
            colorType = QColor('#4e9a06')
            colorKeyword = QColor('#204a87')
            colorString = QColor('#ce5c00')

            self.lexer.setDefaultFont(self.defaultFont)
            self.lexer.setDefaultColor(colorDefault)

            self.lexer.setColor(colorComment, 1)
            self.lexer.setColor(colorNumber, 2)
            self.lexer.setColor(colorString, 3)
            self.lexer.setColor(colorString, 4)
            self.lexer.setColor(colorKeyword, 5)
            self.lexer.setColor(colorString, 6)
            self.lexer.setColor(colorString, 7)
            self.lexer.setColor(colorType, 8)
            self.lexer.setColor(colorCommentBlock, 12)
            self.lexer.setColor(colorString, 15)

            self.lexer.setFont(self.italicFont, 1)
            self.lexer.setFont(self.boldFont, 5)
            self.lexer.setFont(self.boldFont, 8)
            self.lexer.setFont(self.italicFont, 12)

            self.api = QsciAPIs(self.lexer)

            settings = QSettings()
            useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI',
                                                True))
            if useDefaultAPI:
                # Load QGIS API shipped with Python console
                self.api.loadPrepared(
                    os.path.join(QgsApplication.pkgDataPath(),
                                 'python', 'qsci_apis', 'pyqgis.pap'))
            else:
                # Load user-defined API files
                apiPaths = settings.value('pythonConsole/userAPI', [])
                for path in apiPaths:
                    self.api.load(path)
                self.api.prepare()
                self.lexer.setAPIs(self.api)
        elif self.lexerType == self.LEXER_R:
            # R lexer
            self.lexer = LexerR()

        self.setLexer(self.lexer)
コード例 #53
0
class ScintillaPythonEditBox(QsciScintilla, BasePythonEditBox):
    def __init__(self, parent=None):
        QsciScintilla.__init__(self, parent)

        self.lexer = None
        self.api = None
        self.lexerType = -1

        self.setCommonOptions()
        self.initShortcuts()

    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        # Load font from Python console settings
        settings = QSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', 10))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setStretch(QFont.SemiCondensed)
        self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        self.defaultFont.setBold(False)

        self.boldFont = QFont(self.defaultFont)
        self.boldFont.setBold(True)

        self.italicFont = QFont(self.defaultFont)
        self.italicFont.setItalic(True)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

        self.initLexer()

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAll)

    def initShortcuts(self):
        (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16)

        # Disable some shortcuts
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY,
                           ord('L') + ctrl + shift)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)

        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)

        # Use Ctrl+Space for autocompletion
        self.shortcutAutocomplete = QShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_Space), self)
        self.shortcutAutocomplete.setContext(Qt.WidgetShortcut)
        self.shortcutAutocomplete.activated.connect(self.autoComplete)

    def autoComplete(self):
        self.autoCompleteFromAll()

    def setLexerType(self, lexerType):
        self.lexerType = lexerType
        self.initLexer()

    def initLexer(self):
        self.lexer = QsciLexerPython()

        colorDefault = QColor('#2e3436')
        colorComment = QColor('#c00')
        colorCommentBlock = QColor('#3465a4')
        colorNumber = QColor('#4e9a06')
        colorType = QColor('#4e9a06')
        colorKeyword = QColor('#204a87')
        colorString = QColor('#ce5c00')

        self.lexer.setDefaultFont(self.defaultFont)
        self.lexer.setDefaultColor(colorDefault)

        self.lexer.setColor(colorComment, 1)
        self.lexer.setColor(colorNumber, 2)
        self.lexer.setColor(colorString, 3)
        self.lexer.setColor(colorString, 4)
        self.lexer.setColor(colorKeyword, 5)
        self.lexer.setColor(colorString, 6)
        self.lexer.setColor(colorString, 7)
        self.lexer.setColor(colorType, 8)
        self.lexer.setColor(colorCommentBlock, 12)
        self.lexer.setColor(colorString, 15)

        self.lexer.setFont(self.italicFont, 1)
        self.lexer.setFont(self.boldFont, 5)
        self.lexer.setFont(self.boldFont, 8)
        self.lexer.setFont(self.italicFont, 12)

        self.api = QsciAPIs(self.lexer)

        settings = QSettings()
        useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI', True))
        if useDefaultAPI:
            # Load QGIS API shipped with Python console
            self.api.loadPrepared(
                os.path.join(QgsApplication.pkgDataPath(), 'python',
                             'qsci_apis', 'pyqgis.pap'))
        else:
            # Load user-defined API files
            apiPaths = settings.value('pythonConsole/userAPI', [])
            for path in apiPaths:
                self.api.load(path)
            self.api.prepare()
            self.lexer.setAPIs(self.api)

        self.setLexer(self.lexer)

    #impliment base editor
    def insertPlainText(self, text):
        self.insert(text)
        pos = self.getCursorPosition()
        self.setCursorPosition(pos[0], pos[1] + len(text))

    def toPlainText(self):
        return self.text()

    def get_font_size(self):
        return self.font().pointSize()

    def set_font_size(self, new_point_size):
        font = self.font()
        self.setFont(QFont(font.family(), new_point_size))

    def wheelEvent(self, event):
        if event.modifiers() == Qt.ControlModifier:
            self.emit(SIGNAL("wheelEvent(QWheelEvent)"), event)
        else:
            super(ScintillaPythonEditBox, self).wheelEvent(event)
コード例 #54
0
ファイル: qtztextwidget.py プロジェクト: parapente/PiFi
class ZTextWidget(QWidget):
    upper_buf = []
    upper_buf_height = 0
    upper_win_cursor = [] # Upper win cursor x,y
    lower_win_cursor = 1 # Lower win cursor x (y cannot be changed!)
    fixed_font = None
    fixed_font_metrics = None
    fixed_font_width = 0
    fixed_font_height = 0
    buf = []
    width = 80
    height = 26
    cur_win = 0 # Default win is the lower (1 is for upper win)
    cur_fg = 10
    cur_bg = 2
    cur_style = 0
    max_char = 0
    start_pos = 0
    top_pos = 0
    cur_pos = 0
    input_buf = []
    _cursor_visible = False
    _ostream = None
    returnPressed = pyqtSignal(QString)
    keyPressed = pyqtSignal(int)

    def __init__(self,parent = None,flags = Qt.Widget):
        super(ZTextWidget,self).__init__(parent,flags)
        sp = QSizePolicy()
        sp.setHorizontalPolicy(QSizePolicy.Fixed)
        sp.setVerticalPolicy(QSizePolicy.Fixed)
        self.set_fixed_font("DeJa Vu Sans Mono", 9)
        self.setSizePolicy(sp)
        self.setFocusPolicy(Qt.StrongFocus)
        self._ostream = [ZStream(), ZStream(), ZStream(), ZStream()]
        self._ostream[0].selected = True
        for i in xrange(self.width *  self.height * 4):
            self.buf.append(0)

    def paintEvent(self,e):
        painter = QPainter(self)
        painter.fillRect(0, 0, self.width * self.fixed_font_width + 2, self.height * self.fixed_font_height, Qt.black)
        painter.setPen(Qt.gray)
        painter.setRenderHint(QPainter.TextAntialiasing)
        painter.setFont(self.fixed_font)
        painter.setBackgroundMode(Qt.OpaqueMode)
        # Print main window
        l = self.height
        while (l > 0):
            c = 1
            while (c <= self.width):
                y = self.fixed_font_metrics.ascent() + (l - 1) * self.fixed_font_height
                x = 1 + ((c - 1) * self.fixed_font_width)
                #print "**",l,"**",c
                if self.buf[(((self.height - l) * self.width) + c - 1) * 4] == 0:
                    painter.setPen(self.ztoq_color(self.cur_fg))
                else:
                    painter.setPen(self.ztoq_color(self.buf[(((self.height - l) * self.width) + c - 1) * 4]))
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1] == 0:
                    painter.setBackground(QBrush(self.ztoq_color(self.cur_bg)))
                else:
                    painter.setBackground(QBrush(self.ztoq_color(self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1])))
                # Set appropriate font style
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] == 0:
                    f = painter.font()
                    f.setBold(False)
                    f.setItalic(False)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 1: # Reverse video
                    painter.setPen(self.ztoq_color(self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 1]))
                    painter.setBackground(QBrush(self.ztoq_color(self.buf[(((self.height - l) * self.width) + c - 1) * 4])))
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 2: # Bold
                    f = painter.font()
                    f.setBold(True)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 2] & 4: # Italic
                    f = painter.font()
                    f.setItalic(True)
                    painter.setFont(f)
                if self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 3] <> 0:
                    painter.drawText(x,y,self.buf[((((self.height - l) * self.width) + c - 1) * 4) + 3])
                c += 1
            l -= 1
            c = 1
        # Print upper window
        if self.upper_buf <> []:
            l = 1
            while (l <= self.upper_buf_height):
                c = 1
                while (c <= self.width):
                    y = self.fixed_font_metrics.ascent() + (l - 1) * self.fixed_font_height
                    x = 1 + ((c - 1) * self.fixed_font_width)
                    #print "**",l,"**",c
                    if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 3] <> 0:
                        painter.setPen(self.ztoq_color(self.upper_buf[(((l - 1) * self.width) + c - 1) * 4]))
                        painter.setBackground(QBrush(self.ztoq_color(self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 1])))
                        # Set appropriate font style
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] == 0:
                            f = painter.font()
                            f.setBold(False)
                            f.setItalic(False)
                            painter.setFont(f)
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 1: # Reverse video
                            painter.setPen(self.ztoq_color(self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 1]))
                            painter.setBackground(QBrush(self.ztoq_color(self.upper_buf[(((l - 1) * self.width) + c - 1) * 4])))
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 2: # Bold
                            f = painter.font()
                            f.setBold(True)
                            painter.setFont(f)
                        if self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 2] & 4: # Italic
                            f = painter.font()
                            f.setItalic(True)
                            painter.setFont(f)
                        painter.drawText(x,y,self.upper_buf[((((l - 1) * self.width) + c - 1) * 4) + 3])
                    c += 1
                l += 1
        # Print cursor if visible
        if self._cursor_visible:
            self.display_cursor()

    def sizeHint(self):
        size = QSize()
        size.setWidth(self.width * self.fixed_font_width + 2)
        size.setHeight(self.height * self.fixed_font_height)
        return size

    def set_fixed_font(self,name,size):
        self.fixed_font = QFont(name, size)
        self.fixed_font.setFixedPitch(True)
        self.fixed_font.setKerning(False)
        self.fixed_font_metrics = QFontMetrics(self.fixed_font)
        self.fixed_font_width = self.fixed_font_metrics.averageCharWidth()
        self.fixed_font_height = self.fixed_font_metrics.height()
        #print self.fixed_font_width, self.fixed_font_height

    def ztoq_color(self,c):
        if c == 2:
            return Qt.black
        elif c == 3:
            return Qt.red
        elif c == 4:
            return Qt.green
        elif c == 5:
            return Qt.yellow
        elif c == 6:
            return Qt.blue
        elif c == 7:
            return Qt.magenta
        elif c == 8:
            return Qt.cyan
        elif c == 9:
            return Qt.white
        elif c == 10:
            return Qt.lightGray
        elif c == 11:
            return Qt.gray
        elif c == 12:
            return Qt.darkGray

    def set_cursor(self,x,y):
        self.upper_win_cursor = [x,y]

    def set_window(self,w):
        if w < 2:
            self.cur_win = w
        else:
            sys.exit("Unknown window {0}!?!".args(w))

    def prints(self,txt):
        if self._ostream[0].selected:
            if self.cur_win == 0: # Lower win
                # TODO: Buffering
                c = self.lower_win_cursor
                i = 0
                total = len(txt)
                #print "Total -", total
                while (i < total):
                    s = ""
                    while (i < total) and (txt[i] <> '\n') and (c <= self.width):
                        s += txt[i]
                        i += 1
                        c += 1
                    self.print_line(s)
                    #print "--> [i, c, total]", i, c, total, " ++ ", s
                    if c > self.width:
                        self.insert_new_line()
                        self.lower_win_cursor = 1
                        c = 1
                    elif (i < total) and (txt[i] == '\n'):
                        self.insert_new_line()
                        self.lower_win_cursor = 1
                        c = 1
                        i += 1
                    #elif (i == total) and (txt[i-1] <> '\n'):
                    else:
                        self.lower_win_cursor += len(s)
            else:
                i = self.upper_win_cursor[0]
                j = 0
                l = self.upper_win_cursor[1]
                #print "-", i, l, "-", txt
                #print "len upperbuf=", len(self.upper_buf)
                while (i <= self.width) and (j < len(txt)):
                    if txt[j] <> '\n':
                        self.upper_buf[(((l - 1) * self.width) + (i - 1)) * 4] = self.cur_fg
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 1] = self.cur_bg
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 2] = self.cur_style
                        self.upper_buf[((((l - 1) * self.width) + (i - 1)) * 4) + 3] = txt[j]
                        i += 1
                        j += 1
                    else:
                        self.upper_win_cursor = [1,l + 1]
                        i = 1
                        l += 1
                        j += 1
                self.upper_win_cursor[0] += j
            self.update()

    def print_line(self,txt):
        col = self.lower_win_cursor
        #print "Column:", col, txt
        if self.cur_win == 0: # Lower win
            for i in xrange(len(txt)):
                self.buf[(col - 1 + i) * 4] = self.cur_fg
                self.buf[((col - 1 + i) * 4) + 1] = self.cur_bg
                self.buf[((col - 1 + i) * 4) + 2] = self.cur_style
                self.buf[((col - 1 + i) * 4) + 3] = txt[i]

    def print_char(self,c):
        col = self.lower_win_cursor
        if self.cur_win == 0: # Lower win
            if c <> '\n':
                self.buf[(col - 1) * 4] = self.cur_fg
                self.buf[((col - 1) * 4) + 1] = self.cur_bg
                self.buf[((col - 1) * 4) + 2] = self.cur_style
                self.buf[((col - 1) * 4) + 3] = c
                self.lower_win_cursor += 1
            if self.lower_win_cursor > self.width: # If we exceed screen width
                #print "I insert a newline"
                self.insert_new_line()
                self.lower_win_cursor = 1
            elif c == '\n':
                self.insert_new_line()
                self.lower_win_cursor = 1
        self.update()

    def set_max_input(self,m):
        self.max_char = m

    def show_cursor(self):
        self.cur_pos = self.lower_win_cursor
        self.top_pos = self.cur_pos
        self.start_pos = self.cur_pos
        self.input_buf = []
        self._cursor_visible = True
        self.update()

    def hide_cursor(self):
        self._cursor_visible = False
        self.update()

    def display_cursor(self):
        painter = QPainter(self)
        col = self.cur_pos
        y = self.fixed_font_metrics.ascent() + ((self.height - 1) * self.fixed_font_height)
        x = 1 + ((col - 1) * self.fixed_font_width)
        painter.setPen(self.ztoq_color(self.cur_fg))
        painter.setBackground(QBrush(self.ztoq_color(self.cur_bg)))
        painter.drawText(x,y,unichr(0x2581))

    def keyPressEvent(self,e):
        if e.key() == Qt.Key_Left:
            if self.cur_pos > self.start_pos:
                self.cur_pos -= 1
                self.update()
            e.accept()
            self.keyPressed.emit(131)
        elif e.key() == Qt.Key_Right:
            if self.cur_pos < self.top_pos:
                self.cur_pos += 1
                self.update()
            e.accept()
            self.keyPressed.emit(132)
        elif e.key() == Qt.Key_Up:
            # TODO: Up in history
            e.accept()
            self.keyPressed.emit(129)
            pass
        elif e.key() == Qt.Key_Down:
            # TODO: Down in history
            e.accept()
            self.keyPressed.emit(130)
            pass
        elif e.key() == Qt.Key_Backspace:
            if self.cur_pos > self.start_pos:
                self.cur_pos -= 1
                self.top_pos -= 1
                col = self.cur_pos - 1
                for i in xrange(4):
                    self.buf[col * 4 + i] = 0
                del self.input_buf[self.cur_pos - self.start_pos]
                #print self.input_buf
                self.lower_win_cursor -= 1
                self.update()
            # self.keyPressed.emit() # No keycode available for zscii
            e.accept()
        elif e.key() == Qt.Key_Delete:
            # TODO: Fix it!
            if self.cur_pos < self.top_pos:
                self.top_pos -= 1
                col = self.cur_pos - 1
                for i in xrange(4):
                    self.buf[col * 4 + i] = 0
                del self.input_buf[self.cur_pos - self.start_pos]
                self.lower_win_cursor -= 1
                self.update()
            e.accept()
            self.keyPressed.emit(8)
        elif (e.key() == Qt.Key_Return) or (e.key() == Qt.Key_Enter):
            # TODO: Learn how to properly convert a list of chars to a string. There MUST be another way! >:-S
            text = ""
            for i in xrange(len(self.input_buf)):
                text += self.input_buf[i]
            #print text
            self.print_char('\n')
            self.hide_cursor()
            self.keyPressed.emit(13)
            self.returnPressed.emit(text)
            e.accept()
        elif ((e.key() >= Qt.Key_F1) and (e.key() <= Qt.Key_F12)):
            e.accept()
            self.keyPressed.emit(133 + e.key() - Qt.Key_F1)
        elif e.key() == Qt.Key_Escape:
            e.accept()
            self.keyPressed.emit(27)
        elif e.text().isEmpty() == False:
            #print self.cur_pos, self.start_pos, self.max_char
            if (self.cur_pos - self.start_pos) < self.max_char:
                self.cur_pos += 1
                self.top_pos += 1
                if (self.cur_pos - self.start_pos) <= len(self.input_buf):
                    self.input_buf.insert(self.cur_pos - self.start_pos - 1, unicode(e.text()))
                    #print "CurPos:", self.cur_pos
                    col = self.cur_pos - 2
                    self.buf[col * 4 + 3] = unicode(e.text())
                    self.buf[col * 4 + 2] = 0
                    self.buf[col * 4 + 1] = self.cur_bg
                    self.buf[col * 4] = self.cur_fg
                    self.lower_win_cursor += 1
                else:
                    self.input_buf.append(unicode(e.text()))
                    self.print_char(e.text())
                #print self.input_buf
                self.update()
            e.accept()
            t = ord(str(e.text()))
            if ((t > 31) and (t < 127)) or ((t > 154) and (t <252)):
                self.keyPressed.emit(t)
        else:
            e.ignore()

    def set_text_colour(self,fg):
        self.cur_fg = fg

    def set_text_background_colour(self,bg):
        self.cur_bg = bg

    def set_font_style(self,s):
        if s == 0:
            self.cur_style = 0
        else:
            self.cur_style |= s

    def clear(self):
        for i in xrange(self.width *  self.height * 4):
            self.buf[i] = 0
        self.upper_buf = []
        self.upper_buf_height = 0
        self.upper_win_cursor = [] # Upper win cursor x,y
        self.lower_win_cursor = 1 # Lower win cursor x (y cannot be changed!)
        self.cur_win = 0 # Default win is the lower (1 is for upper win)

    def split_window(self,lines,ver):
        if self.upper_buf_height > lines: # New upper win is smaller. I should copy the rest of the buffer to main buffer
            #print "Copying..."
            l = lines + 1
            while l <= self.upper_buf_height:
                for i in xrange(self.width * 4):
                    self.buf[(((self.height - l + 1) * self.width) * 4) + i] = self.upper_buf[(((l - 1) * self.width) * 4) + i]
                l += 1
        self.upper_buf_height = lines
        if (self.upper_buf == []) or (ver == 3):
            for i in xrange(self.upper_buf_height*self.width*4): # It isn't necessary to occupy that much memory but it helps to be prepared! :-P
                self.upper_buf.append(0)
        if (self.upper_win_cursor == []) or (self.upper_win_cursor[1] > lines):
            self.upper_win_cursor = [1,1]

    def select_ostream(self,n):
        if n <> 0:
            self._ostream[n - 1].selected = True

    def deselect_ostream(self,n):
        self._ostream[n - 1].selected = False

    def insert_new_line(self):
        #print "New line"
        # TODO: Not just insert new lines but also remove old unwanted ones
        for i in xrange(self.width * 4):
            self.buf.insert(0, 0)

    def read_line(self, callback):
        QObject.connect(self, SIGNAL("returnPressed(QString)"), callback)

    def disconnect_read_line(self, callback):
        QObject.disconnect(self, SIGNAL("returnPressed(QString)"), callback)

    def read_char(self, callback):
        QObject.connect(self, SIGNAL("keyPressed(int)"), callback)
        print 'Connect char'

    def disconnect_read_char(self, callback):
        QObject.disconnect(self, SIGNAL("keyPressed(int)"), callback)
        print 'Disconnect char'

    def selected_ostreams(self):
        s = []
        for i in xrange(4):
            if self._ostream[i].selected == True:
                s.append(i+1)
        return s

    def new_line(self):
        if self._ostream[0].selected:
            if self.cur_win == 0: # Lower win
                self.insert_new_line()
                self.lower_win_cursor = 1
            else: # Upper win
                l = self.upper_win_cursor[1]
                self.upper_win_cursor = [1,l + 1]
コード例 #55
0
ファイル: editor.py プロジェクト: kzwkt/dff
 def configureFont(self):
     font = QFont()
     font.setFamily('Helvetica')
     font.setFixedPitch(True)
     font.setPointSize(11)
     self.setFont(font)