Debian Codegraph @

lib/widgets/texteditaccessory.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 #
3 # QBrz - Qt frontend to Breezy commands
4 # Copyright (C) 2011 QBzr Developers
5 #
6 # This program is free software; you can redistribute it and/or
7 # modify it under the terms of the GNU General Public License
8 # as published by the Free Software Foundation; either version 2
9 # of the License, or (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19
20 from PyQt5 import QtCore, QtGui, QtWidgets
21
22 GBAR_LEFT = 1
23 GBAR_RIGHT = 2
24
25
26 class _Entry(object):
27 """
28 Represent each group of guide bar.
29
30 :key: string key to identify this group
31 :color: color or marker
32 :data: marker positions, list of tuple (block index, num of blocks)
33 :index: index of the column to render this entry.
34 * Two or more groups can be rendered on same columns.
35 * If index == -1, the group is renderd on all columns.
36 """
37 __slots__ = ['key', 'color', 'data', 'index']
38
39 def __init__(self, key, color, index=0):
40 self.key = key
41 self.color = color
42 self.data = []
43 self.index = index
44
45
46 class PlainTextEditHelper(QtCore.QObject):
47 """
48 Helper class to encapsulate gap between QPlainTextEdit and QTextEdit
49 """
50 updateRequest = QtCore.pyqtSignal()
51
52 def __init__(self, edit):
53 QtCore.QObject.__init__(self)
54 if not isinstance(edit, QtWidgets.QPlainTextEdit):
55 raise ValueError('edit must be QPlainTextEdit')
56 self.edit = edit
57 edit.updateRequest[QtCore.QRect, int].connect(self.onUpdateRequest)
58
59 def onUpdateRequest(self, rect, dy):
60 self.updateRequest.emit()
61
62 def center_block(self, block):
63 """
64 scroll textarea as specified block locates to center
65
66 NOTE: This code is based on Qt source code (qplaintextedit.cpp)
67 """
68 edit = self.edit
69 height = edit.viewport().rect().height() / 2
70 h = self.edit.blockBoundingRect(block).center().y()
71
72 def iter_visible_block_backward(b):
73 while True:
74 b = b.previous()
75 if not b.isValid():
76 return
77 if b.isVisible():
78 yield b
79
80 for block in iter_visible_block_backward(block):
81 h += edit.blockBoundingRect(block).height()
82 if height < h:
83 break
84 edit.verticalScrollBar().setValue(block.firstLineNumber())
85
86
87 class TextEditHelper(QtCore.QObject):
88 """
89 Helper class to encapsulate gap between QPlainTextEdit and QTextEdit
90 """
91 updateRequest = QtCore.pyqtSignal()
92
93 def __init__(self, edit):
94 QtCore.QObject.__init__(self)
95 if not isinstance(edit, QtWidgets.QTextEdit):
96 raise ValueError('edit must be QTextEdit')
97 self.edit = edit
98 edit.verticalScrollBar().valueChanged[int].connect(self.onVerticalScroll)
99
100 def onVerticalScroll(self, value):
101 self.updateRequest.emit()
102
103 def center_block(self, block):
104 """
105 scroll textarea as specified block locates to center
106 """
107 y = block.layout().position().y()
108 vscroll = self.edit.verticalScrollBar()
109 vscroll.setValue(int(y - vscroll.pageStep() / 2))
110
111
112 def get_edit_helper(edit):
113 if isinstance(edit, QtWidgets.QPlainTextEdit):
114 return PlainTextEditHelper(edit)
115 if isinstance(edit, QtWidgets.QTextEdit):
116 return TextEditHelper(edit)
117 raise ValueError("edit is unsupported type.")
118
119
120 class GuideBar(QtWidgets.QWidget):
121 """
122 Vertical bar attached to TextEdit.
123 This shows that where changed or highlighted lines are.
124
125 Guide bar can have multiple columns.
126 """
127 def __init__(self, edit, base_width=10, parent=None):
128 """
129 :edit: target widget, must be QPlainTextEdit or QTextEdit
130 :base_width: width of each column.
131 """
132 QtWidgets.QWidget.__init__(self, parent)
133 self.base_width = base_width
134 self.edit = edit
135 self._helper = get_edit_helper(edit)
136 self.block_count = 0
137
138 edit.documentChangeFinished.connect(self.reset_gui)
139 edit.verticalScrollBar().rangeChanged[int, int].connect(self.vscroll_rangeChanged)
140
141 self._helper.updateRequest.connect(self.update)
142
143 self.entries = {}
144 self.vscroll_visible = None
145
146 def add_entry(self, key, color, index=0):
147 """
148 Add marker group
149 """
150 entry = _Entry(key, color, index)
151 self.entries[key] = entry
152
153 def vscroll_rangeChanged(self, min_scroll, max_scroll):
154 vscroll_visible = (min_scroll < max_scroll)
155 if self.vscroll_visible != vscroll_visible:
156 self.vscroll_visible = vscroll_visible
157 self.reset_gui()
158 self.update()
159
160 def reset_gui(self):
161 """
162 Determine show or hide, and num of columns.
163 """
164 # Hide when vertical scrollbar is not shown.
165 if not self.vscroll_visible:
166 self.setVisible(False)
167 return
168 valid_entries = [e for e in self.entries.values() if e.data]
169 if not valid_entries:
170 self.setVisible(False)
171 return
172
173 self.setVisible(True)
174 self.repeats = len(set([e.index for e in valid_entries if e.index >= 0]))
175 if self.repeats == 0:
176 self.repeats = 1
177 self.setFixedWidth(self.repeats * self.base_width + 4)
178
179 self.block_count = self.edit.document().blockCount()
180 self.update()
181
182 def update_data(self, **data):
183 """
184 Update each marker positions.
185
186 :arg_name: marker key
187 :value: list of marker positions.
188 Each position is tuple of (block index, num of blocks).
189 """
190 for key, value in data.items():
191 self.entries[key].data[:] = value
192 self.reset_gui()
193
194 def get_visible_block_range(self):
195 """
196 Return tuple of (index of first visible block, num of visible block)
197 """
198 pos = QtCore.QPoint(0, 1)
199 block = self.edit.cursorForPosition(pos).block()
200 first_visible_block = block.blockNumber()
201
202 y = self.edit.viewport().height()
203
204 pos = QtCore.QPoint(0, y)
205 block = self.edit.cursorForPosition(pos).block()
206 if block.isValid():
207 visible_blocks = block.blockNumber() - first_visible_block + 1
208 else:
209 visible_blocks = self.block_count - first_visible_block + 1
210
211 return first_visible_block, visible_blocks
212
213 def paintEvent(self, event):
214 QtWidgets.QWidget.paintEvent(self, event)
215 painter = QtGui.QPainter(self)
216 painter.fillRect(event.rect(), QtCore.Qt.white)
217 if self.block_count == 0:
218 return
219 block_height = float(self.height()) / self.block_count
220
221 def get_top_and_height(index, num):
222 y, height = index * block_height, num * block_height
223 # Inflate height if it is smaller than 1.
224 if height < 1:
225 return y - (1-height)/2, 1
226 else:
227 return y, height
228
229 # Draw entries
230 x_origin = 2
231 index = -1
232 prev_index = -1
233 for e in sorted(iter(self.entries.values()),
234 key=lambda x:x.index if x.index >= 0 else 999):
235 if not e.data:
236 continue
237 if e.index < 0:
238 x, width = 0, self.width()
239 else:
240 if e.index != prev_index:
241 index += 1
242 prev_index = e.index
243 x, width = x_origin + index * self.base_width, self.base_width
244 for block_index, block_num in e.data:
245 y, height = get_top_and_height(block_index, block_num)
246 painter.fillRect(QtCore.QRectF(x, y, width, height), e.color)
247
248 # Draw scroll indicator.
249 x, width = 0, self.width()
250 first_block, visible_blocks = self.get_visible_block_range()
251 y, height = get_top_and_height(first_block, visible_blocks)
252 painter.fillRect(QtCore.QRectF(x, y, width, height), QtGui.QColor(0, 0, 0, 24))
253
254 def mousePressEvent(self, event):
255 QtWidgets.QWidget.mousePressEvent(self, event)
256 if event.button() == QtCore.Qt.LeftButton:
257 self.scroll_to_pos(event.y())
258
259 def mouseMoveEvent(self, event):
260 QtWidgets.QWidget.mouseMoveEvent(self, event)
261 self.scroll_to_pos(event.y())
262
263 def scroll_to_pos(self, y):
264 block_no = int(float(y) / self.height() * self.block_count)
265 block = self.edit.document().findBlockByNumber(block_no)
266 if not block.isValid():
267 return
268 self._helper.center_block(block)
269
270
271 class GuideBarPanel(QtWidgets.QWidget):
272 """
273 Composite widget of TextEdit and GuideBar
274 """
275 def __init__(self, edit, base_width=10, align=GBAR_RIGHT, parent=None):
276 QtWidgets.QWidget.__init__(self, parent)
277 hbox = QtWidgets.QHBoxLayout(self)
278 hbox.setSpacing(0)
279 hbox.setContentsMargins(0, 0, 0, 0)
280 self.bar = GuideBar(edit, base_width=base_width, parent=parent)
281 self.edit = edit
282 if align == GBAR_RIGHT:
283 hbox.addWidget(self.edit)
284 hbox.addWidget(self.bar)
285 else:
286 hbox.addWidget(self.bar)
287 hbox.addWidget(self.edit)
288
289 def add_entry(self, key, color, index=0):
290 self.bar.add_entry(key, color, index)
291
292 def reset_gui(self):
293 self.bar.reset_gui()
294
295 def update_data(self, **data):
296 return self.bar.update_data(**data)
297
298
299 def setup_guidebar_for_find(guidebar, find_toolbar, index=0):
300 """
301 Make guidebar enable to show positions that highlighted by FindToolBar
302 """
303 def on_highlight_changed():
304 if guidebar.edit in find_toolbar.text_edits:
305 guidebar.update_data(find=[(n, 1) for n in guidebar.edit.highlight_lines])
306 guidebar.add_entry('find', QtGui.QColor(255, 196, 0), index) # Gold
307 find_toolbar.highlightChanged.connect(on_highlight_changed)