File: codeeditor.py

package info (click to toggle)
rst2pdf 0.16-2
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 6,828 kB
  • sloc: python: 17,981; makefile: 809; sh: 92
file content (163 lines) | stat: -rw-r--r-- 5,655 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
# -*- coding: utf-8 -*-

import sys
from PyQt4 import QtGui, QtCore

class LineNumberArea(QtGui.QWidget):

    def __init__(self,editor):
        self.codeEditor=editor
        QtGui.QWidget.__init__(self, editor)

    def sizeHint(self):
        return QtCore.QSize(self.codeEditor.lineNumberAreaWidth(),0)

    def paintEvent(self, event):
        self.codeEditor.lineNumberAreaPaintEvent(event)



class CodeEditor(QtGui.QPlainTextEdit):
    
    def __init__(self,parent=None):
        QtGui.QPlainTextEdit.__init__(self,parent)
        self.lineNumberArea = LineNumberArea (self)
        self.connect(self, QtCore.SIGNAL("blockCountChanged(int)"), 
                     self.updateLineNumberAreaWidth)
            
        self.connect(self, QtCore.SIGNAL("updateRequest(const QRect &, int)"), 
                     self.updateLineNumberArea)
                
        self.connect(self, QtCore.SIGNAL("cursorPositionChanged()"), 
                     self.highlightCurrentLine)

        self.updateLineNumberAreaWidth(0)
        self.errorPos=None
        self.highlightCurrentLine()
        
    def lineNumberAreaPaintEvent(self, event):
        painter=QtGui.QPainter(self.lineNumberArea)
        painter.fillRect(event.rect(), QtCore.Qt.lightGray)
        
        block = self.firstVisibleBlock()
        blockNumber = block.blockNumber();
        top = int(self.blockBoundingGeometry(block).translated(self.contentOffset()).top())
        bottom = top + int(self.blockBoundingRect(block).height())
        
        while block.isValid() and top <= event.rect().bottom():
            
            
            if block.isVisible() and bottom >= event.rect().top():
                number = str(blockNumber + 1)
                painter.setPen(QtCore.Qt.black)
                painter.drawText(0, top, self.lineNumberArea.width(), 
                    self.fontMetrics().height(),
                    QtCore.Qt.AlignRight, number)

            block = block.next()
            top = bottom
            bottom = top + int(self.blockBoundingRect(block).height())
            blockNumber+=1
        
    def lineNumberAreaWidth(self):
        digits = 1
        _max = max (1, self.blockCount())
        while (_max >= 10):
            _max = _max/10
            digits+=1
        space = 5 + self.fontMetrics().width('9') * digits
        return space
    
    def updateLineNumberAreaWidth(self, newBlockCount):
        self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)


    def updateLineNumberArea(self, rect, dy):
        
        if dy:
            self.lineNumberArea.scroll(0, dy);
        else:
            self.lineNumberArea.update(0, rect.y(), 
                self.lineNumberArea.width(), rect.height())

        if rect.contains(self.viewport().rect()):
            self.updateLineNumberAreaWidth(0)

    def resizeEvent(self, e):
        QtGui.QPlainTextEdit.resizeEvent(self,e)
        self.cr = self.contentsRect()
        self.lineNumberArea.setGeometry(self.cr.left(), 
                                        self.cr.top(), 
                                        self.lineNumberAreaWidth(), 
                                        self.cr.height())
                                        
    def highlightError(self,pos):
        self.errorPos=pos
        self.highlightCurrentLine()

             
    def highlightCurrentLine(self):         
        extraSelections=[]
        if not self.isReadOnly():             
            selection = QtGui.QTextEdit.ExtraSelection()
            lineColor = QtGui.QColor(QtCore.Qt.yellow).lighter(160)
            selection.format.setBackground(lineColor)
            selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
            selection.cursor = self.textCursor()
            selection.cursor.clearSelection()
            extraSelections.append(selection)
            
            if self.errorPos is not None:
                errorSel = QtGui.QTextEdit.ExtraSelection()
                lineColor = QtGui.QColor(QtCore.Qt.red).lighter(160)
                errorSel.format.setBackground(lineColor)
                errorSel.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
                errorSel.cursor = QtGui.QTextCursor(self.document())
                errorSel.cursor.setPosition(self.errorPos)
                errorSel.cursor.clearSelection()
                extraSelections.append(errorSel)

        self.setExtraSelections(extraSelections)

if __name__ == "__main__":
    
    try:
        import json
    except ImportError:
        import simplejson as json
    from highlighter import Highlighter
    
    app = QtGui.QApplication(sys.argv)

    js = CodeEditor()
    js.setWindowTitle('javascript')
    hl=Highlighter(js.document(),"javascript")
    js.show()

    def validateJSON():
        style=unicode(js.toPlainText())
        if not style.strip(): #no point in validating an empty string
            return
        pos=None
        try:
            json.loads(style)
        except ValueError, e:
            s=str(e)
            print s
            if s == 'No JSON object could be decoded':
                pos=0
            elif s.startswith('Expecting '):
                pos=int(s.split(' ')[-1][:-1])
            elif s.startswith('Extra data'):
                pos=int(s.split(' ')[-3])
            else:
                print 'UNKNOWN ERROR'
                
        # This makes a red bar appear in the line
        # containing position pos
        js.highlightError(pos)

    # Run validateJSON on every keypress
    js.connect(js,QtCore.SIGNAL('textChanged()'),validateJSON)

    sys.exit(app.exec_())