~hid-iwata/qbzr/qdiff-with-filelist

« back to all changes in this revision

Viewing changes to lib/widgets/texteditaccessory.py

  • Committer: Alexander Belchenko
  • Date: 2012-02-02 10:41:32 UTC
  • mfrom: (1451.2.6 textedit-guidebar)
  • Revision ID: bialix@ukr.net-20120202104132-b6a3uythbhn4jn3k
Implemented changes markers in qdiff, qannotate as a side guidebar for fast navigation. (IWATA Hidetaka)

Show diffs side-by-side

added added

removed removed

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