/b-gtk/fix-viz

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/b-gtk/fix-viz
0.1.1 by Dan Loda
First working version of xannotate.
1
# Copyright (C) 2005 Dan Loda <danloda@gmail.com>
2
3
# This program is free software; you can redistribute it and/or modify
4
# it under the terms of the GNU General Public License as published by
5
# the Free Software Foundation; either version 2 of the License, or
6
# (at your option) any later version.
7
8
# This program is distributed in the hope that it will be useful,
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
# GNU General Public License for more details.
12
13
# You should have received a copy of the GNU General Public License
14
# along with this program; if not, write to the Free Software
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
17
import time
18
0.1.1 by Dan Loda
First working version of xannotate.
19
import pygtk
20
pygtk.require("2.0")
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
21
import gobject
0.1.1 by Dan Loda
First working version of xannotate.
22
import gtk
23
import pango
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
24
import re
0.1.1 by Dan Loda
First working version of xannotate.
25
66.6.6 by Aaron Bentley
Support scrolling based on an offset
26
from bzrlib import patiencediff, tsort
0.1.1 by Dan Loda
First working version of xannotate.
27
from bzrlib.errors import NoSuchRevision
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
28
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
0.1.1 by Dan Loda
First working version of xannotate.
29
0.1.18 by Aaron Bentley
Switched to using pink backgrounds
30
from colormap import AnnotateColorMap, AnnotateColorSaturation
0.1.1 by Dan Loda
First working version of xannotate.
31
from logview import LogView
32
33
34
(
35
    REVISION_ID_COL,
36
    LINE_NUM_COL,
37
    COMMITTER_COL,
38
    REVNO_COL,
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
39
    HIGHLIGHT_COLOR_COL,
0.1.1 by Dan Loda
First working version of xannotate.
40
    TEXT_LINE_COL
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
41
) = range(6)
0.1.1 by Dan Loda
First working version of xannotate.
42
43
0.1.2 by Dan Loda
Rename plugin: xannotate => gannotate
44
class GAnnotateWindow(gtk.Window):
0.1.1 by Dan Loda
First working version of xannotate.
45
    """Annotate window."""
46
0.2.6 by Dan Loda
--plain option to disable highlighting. And update README
47
    def __init__(self, all=False, plain=False):
48
        self.all = all
49
        self.plain = plain
50
        
0.1.1 by Dan Loda
First working version of xannotate.
51
        gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
0.2.6 by Dan Loda
--plain option to disable highlighting. And update README
52
        
0.1.1 by Dan Loda
First working version of xannotate.
53
        self.set_icon(self.render_icon(gtk.STOCK_FIND, gtk.ICON_SIZE_BUTTON))
0.1.18 by Aaron Bentley
Switched to using pink backgrounds
54
        self.annotate_colormap = AnnotateColorSaturation()
0.1.1 by Dan Loda
First working version of xannotate.
55
56
        self._create()
57
        self.revisions = {}
0.1.17 by Dan Loda
A little refactoring.
58
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
59
    def annotate(self, tree, branch, file_id):
59.2.2 by Aaron Bentley
Annotate launches a diff for the particular revision
60
        self.annotations = []
61
        self.branch = branch
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
62
        self.tree = tree
59.2.3 by Aaron Bentley
Gannotate-launched diffs now jump to correct file
63
        self.file_id = file_id
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
64
        self.revision_id = getattr(tree, 'get_revision_id', 
65
                                   lambda: CURRENT_REVISION)()
0.1.1 by Dan Loda
First working version of xannotate.
66
        
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
67
        # [revision id, line number, committer, revno, highlight color, line]
0.1.17 by Dan Loda
A little refactoring.
68
        self.annomodel = gtk.ListStore(gobject.TYPE_STRING,
69
                                       gobject.TYPE_STRING,
70
                                       gobject.TYPE_STRING,
71
                                       gobject.TYPE_STRING,
72
                                       gobject.TYPE_STRING,
73
                                       gobject.TYPE_STRING)
0.1.1 by Dan Loda
First working version of xannotate.
74
        
75
        last_seen = None
0.4.1 by Aaron Bentley
Updated performance, API use
76
        try:
77
            branch.lock_read()
78
            branch.repository.lock_read()
79
            for line_no, (revision, revno, line)\
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
80
                    in enumerate(self._annotate(tree, file_id)):
0.4.1 by Aaron Bentley
Updated performance, API use
81
                if revision.revision_id == last_seen and not self.all:
82
                    revno = committer = ""
83
                else:
84
                    last_seen = revision.revision_id
85
                    committer = revision.committer
86
87
                if revision.revision_id not in self.revisions:
88
                    self.revisions[revision.revision_id] = revision
89
90
                self.annomodel.append([revision.revision_id,
91
                                       line_no + 1,
92
                                       committer,
93
                                       revno,
94
                                       None,
95
                                       line.rstrip("\r\n")
96
                                      ])
59.2.2 by Aaron Bentley
Annotate launches a diff for the particular revision
97
                self.annotations.append(revision)
0.4.1 by Aaron Bentley
Updated performance, API use
98
99
            if not self.plain:
66.6.1 by Aaron Bentley
Remove usused span selector
100
                now = time.time()
101
                self.annomodel.foreach(self._highlight_annotation, now)
0.4.1 by Aaron Bentley
Updated performance, API use
102
        finally:
103
            branch.repository.unlock()
104
            branch.unlock()
0.2.6 by Dan Loda
--plain option to disable highlighting. And update README
105
0.1.17 by Dan Loda
A little refactoring.
106
        self.annoview.set_model(self.annomodel)
107
        self.annoview.grab_focus()
0.1.1 by Dan Loda
First working version of xannotate.
108
0.1.12 by Dan Loda
New --line option. Can now jump to a specific line number.
109
    def jump_to_line(self, lineno):
0.1.17 by Dan Loda
A little refactoring.
110
        if lineno > len(self.annomodel) or lineno < 1:
0.1.12 by Dan Loda
New --line option. Can now jump to a specific line number.
111
            row = 0
112
            # FIXME:should really deal with this in the gui. Perhaps a status
113
            # bar?
114
            print("gannotate: Line number %d does't exist. Defaulting to "
115
                  "line 1." % lineno)
79 by Jelmer Vernooij
Handle empty files more gracefully. Fixes #58951.
116
	    return
0.1.12 by Dan Loda
New --line option. Can now jump to a specific line number.
117
        else:
118
            row = lineno - 1
119
0.1.17 by Dan Loda
A little refactoring.
120
        self.annoview.set_cursor(row)
59.2.1 by Aaron Bentley
Gannotate takes a line number
121
        self.annoview.scroll_to_cell(row, use_align=True)
0.1.12 by Dan Loda
New --line option. Can now jump to a specific line number.
122
66.2.4 by Aaron Bentley
Use dotted revnos instead of 'merge' where possible
123
    def _dotted_revnos(self, repository, revision_id):
124
        """Return a dict of revision_id -> dotted revno
125
        
126
        :param repository: The repository to get the graph from
127
        :param revision_id: The last revision for which this info is needed
128
        """
129
        graph = repository.get_revision_graph(revision_id)
130
        dotted = {}
131
        for n, revision_id, d, revno, e in tsort.merge_sort(graph, 
132
            revision_id, generate_revno=True):
133
            dotted[revision_id] = '.'.join(str(num) for num in revno)
134
        return dotted
135
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
136
    def _annotate(self, tree, file_id):
137
        current_revision = FakeRevision(CURRENT_REVISION)
138
        current_revision.committer = self.branch.get_config().username()
139
        current_revision.timestamp = time.time()
140
        current_revision.message = '[Not yet committed]'
66.6.6 by Aaron Bentley
Support scrolling based on an offset
141
        current_revision.parent_ids = tree.get_parent_ids()
66.2.15 by Aaron Bentley
fix future revno
142
        current_revno = '%d?' % (self.branch.revno() + 1)
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
143
        repository = self.branch.repository
144
        if self.revision_id == CURRENT_REVISION:
145
            revision_id = self.branch.last_revision()
146
        else:
147
            revision_id = self.revision_id
66.2.4 by Aaron Bentley
Use dotted revnos instead of 'merge' where possible
148
        dotted = self._dotted_revnos(repository, revision_id)
66.6.5 by Aaron Bentley
Speed up the 'back' operation
149
        revision_cache = RevisionCache(repository, self.revisions)
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
150
        for origin, text in tree.annotate_iter(file_id):
0.4.1 by Aaron Bentley
Updated performance, API use
151
            rev_id = origin
66.6.7 by Aaron Bentley
Handle current revision better
152
            if rev_id == CURRENT_REVISION:
153
                revision = current_revision
154
                revno = current_revno
155
            else:
156
                try:
157
                    revision = revision_cache.get_revision(rev_id)
158
                    revno = dotted.get(rev_id, 'merge')
159
                    if len(revno) > 15:
160
                        revno = 'merge'
161
                except NoSuchRevision:
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
162
                    revision = FakeRevision(rev_id)
163
                    revno = "?"
0.1.1 by Dan Loda
First working version of xannotate.
164
165
            yield revision, revno, text
166
0.2.2 by Dan Loda
Add file's age as default span
167
    def _highlight_annotation(self, model, path, iter, now):
168
        revision_id, = model.get(iter, REVISION_ID_COL)
169
        revision = self.revisions[revision_id]
0.2.5 by Dan Loda
Use granny-like colors as default and rename ColorMap => AnnotateColorMap.
170
        model.set(iter, HIGHLIGHT_COLOR_COL,
0.1.19 by Aaron Bentley
Different colours for different committers
171
                  self.annotate_colormap.get_color(revision, now))
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
172
66.6.4 by Aaron Bentley
Add back button to see older versions
173
    def _selected_revision(self):
0.1.17 by Dan Loda
A little refactoring.
174
        (path, col) = self.annoview.get_cursor()
79 by Jelmer Vernooij
Handle empty files more gracefully. Fixes #58951.
175
        if path is None:
66.6.4 by Aaron Bentley
Add back button to see older versions
176
            return None
177
        return self.annomodel[path][REVISION_ID_COL]
178
179
    def _show_log(self, w):
180
        rev_id = self._selected_revision()
181
        if rev_id is None:
79 by Jelmer Vernooij
Handle empty files more gracefully. Fixes #58951.
182
            return
0.1.1 by Dan Loda
First working version of xannotate.
183
        self.logview.set_revision(self.revisions[rev_id])
184
185
    def _create(self):
0.1.17 by Dan Loda
A little refactoring.
186
        self.logview = self._create_log_view()
187
        self.annoview = self._create_annotate_view()
188
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
189
        vbox = gtk.VBox(False, 12)
190
        vbox.set_border_width(12)
191
        vbox.show()
0.1.17 by Dan Loda
A little refactoring.
192
193
        sw = gtk.ScrolledWindow()
194
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
195
        sw.set_shadow_type(gtk.SHADOW_IN)
196
        sw.add(self.annoview)
59.2.2 by Aaron Bentley
Annotate launches a diff for the particular revision
197
        self.annoview.gwindow = self
0.1.17 by Dan Loda
A little refactoring.
198
        sw.show()
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
199
        
0.1.8 by Dan Loda
Remember window state. This introduces the gannotate.conf configuration file,
200
        self.pane = pane = gtk.VPaned()
0.1.17 by Dan Loda
A little refactoring.
201
        pane.add1(sw)
202
        pane.add2(self.logview)
0.1.1 by Dan Loda
First working version of xannotate.
203
        pane.show()
204
        vbox.pack_start(pane, expand=True, fill=True)
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
205
206
        self._search = SearchBox()
207
        vbox.pack_start(self._search, expand=False, fill=True)
208
        accels = gtk.AccelGroup()
209
        accels.connect_group(gtk.keysyms.f, gtk.gdk.CONTROL_MASK,
210
                             gtk.ACCEL_LOCKED,
211
                             self._search_by_text)
212
        accels.connect_group(gtk.keysyms.g, gtk.gdk.CONTROL_MASK,
213
                             gtk.ACCEL_LOCKED,
214
                             self._search_by_line)
215
        self.add_accel_group(accels)
216
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
217
        hbox = gtk.HBox(True, 6)
66.6.4 by Aaron Bentley
Add back button to see older versions
218
        hbox.pack_start(self._create_prev_button(), expand=False, fill=True)
219
        hbox.pack_end(self._create_button_box(), expand=False, fill=True)
0.2.1 by Dan Loda
first go at emacs vc-annotate like highlighting
220
        hbox.show()
221
        vbox.pack_start(hbox, expand=False, fill=True)
222
0.1.1 by Dan Loda
First working version of xannotate.
223
        self.add(vbox)
224
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
225
    def _search_by_text(self, accel_group, window, key, modifiers):
226
        self._search.show_for('text')
66.5.3 by v.ladeuil+lp at free
Realbetter fix for bug #73965.
227
        self._search.set_target(self.annoview, TEXT_LINE_COL)
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
228
229
    def _search_by_line(self, accel_group, window, key, modifiers):
230
        self._search.show_for('line')
66.5.3 by v.ladeuil+lp at free
Realbetter fix for bug #73965.
231
        self._search.set_target(self.annoview, LINE_NUM_COL)
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
232
59.2.2 by Aaron Bentley
Annotate launches a diff for the particular revision
233
    def row_diff(self, tv, path, tvc):
234
        row = path[0]
235
        revision = self.annotations[row]
65 by Aaron Bentley
Handle first revision properly
236
        repository = self.branch.repository
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
237
        if revision.revision_id == CURRENT_REVISION:
238
            tree1 = self.tree
239
            tree2 = self.tree.basis_tree()
65 by Aaron Bentley
Handle first revision properly
240
        else:
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
241
            tree1 = repository.revision_tree(revision.revision_id)
242
            if len(revision.parent_ids) > 0:
243
                tree2 = repository.revision_tree(revision.parent_ids[0])
244
            else:
245
                tree2 = repository.revision_tree(NULL_REVISION)
59.2.2 by Aaron Bentley
Annotate launches a diff for the particular revision
246
        from bzrlib.plugins.gtk.viz.diffwin import DiffWindow
247
        window = DiffWindow()
66 by Aaron Bentley
Fix annotate diff window title
248
        window.set_diff("Diff for row %d" % (row+1), tree1, tree2)
59.2.3 by Aaron Bentley
Gannotate-launched diffs now jump to correct file
249
        window.set_file(tree1.id2path(self.file_id))
59.2.2 by Aaron Bentley
Annotate launches a diff for the particular revision
250
        window.show()
251
252
0.1.1 by Dan Loda
First working version of xannotate.
253
    def _create_annotate_view(self):
0.1.17 by Dan Loda
A little refactoring.
254
        tv = gtk.TreeView()
255
        tv.set_rules_hint(False)
256
        tv.connect("cursor-changed", self._show_log)
257
        tv.show()
59.2.2 by Aaron Bentley
Annotate launches a diff for the particular revision
258
        tv.connect("row-activated", self.row_diff)
0.1.1 by Dan Loda
First working version of xannotate.
259
260
        cell = gtk.CellRendererText()
261
        cell.set_property("xalign", 1.0)
262
        cell.set_property("ypad", 0)
263
        cell.set_property("family", "Monospace")
264
        cell.set_property("cell-background-gdk",
0.1.17 by Dan Loda
A little refactoring.
265
                          tv.get_style().bg[gtk.STATE_NORMAL])
0.1.1 by Dan Loda
First working version of xannotate.
266
        col = gtk.TreeViewColumn()
267
        col.set_resizable(False)
268
        col.pack_start(cell, expand=True)
269
        col.add_attribute(cell, "text", LINE_NUM_COL)
0.1.17 by Dan Loda
A little refactoring.
270
        tv.append_column(col)
0.1.1 by Dan Loda
First working version of xannotate.
271
272
        cell = gtk.CellRendererText()
273
        cell.set_property("ypad", 0)
274
        cell.set_property("ellipsize", pango.ELLIPSIZE_END)
275
        cell.set_property("cell-background-gdk",
276
                          self.get_style().bg[gtk.STATE_NORMAL])
277
        col = gtk.TreeViewColumn("Committer")
278
        col.set_resizable(True)
279
        col.pack_start(cell, expand=True)
280
        col.add_attribute(cell, "text", COMMITTER_COL)
0.1.17 by Dan Loda
A little refactoring.
281
        tv.append_column(col)
0.1.1 by Dan Loda
First working version of xannotate.
282
283
        cell = gtk.CellRendererText()
284
        cell.set_property("xalign", 1.0)
285
        cell.set_property("ypad", 0)
286
        cell.set_property("cell-background-gdk",
287
                          self.get_style().bg[gtk.STATE_NORMAL])
288
        col = gtk.TreeViewColumn("Revno")
289
        col.set_resizable(False)
290
        col.pack_start(cell, expand=True)
291
        col.add_attribute(cell, "markup", REVNO_COL)
0.1.17 by Dan Loda
A little refactoring.
292
        tv.append_column(col)
0.1.1 by Dan Loda
First working version of xannotate.
293
294
        cell = gtk.CellRendererText()
295
        cell.set_property("ypad", 0)
296
        cell.set_property("family", "Monospace")
297
        col = gtk.TreeViewColumn()
298
        col.set_resizable(False)
299
        col.pack_start(cell, expand=True)
0.1.18 by Aaron Bentley
Switched to using pink backgrounds
300
#        col.add_attribute(cell, "foreground", HIGHLIGHT_COLOR_COL)
301
        col.add_attribute(cell, "background", HIGHLIGHT_COLOR_COL)
0.1.1 by Dan Loda
First working version of xannotate.
302
        col.add_attribute(cell, "text", TEXT_LINE_COL)
0.1.17 by Dan Loda
A little refactoring.
303
        tv.append_column(col)
0.1.1 by Dan Loda
First working version of xannotate.
304
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
305
        # FIXME: Now that C-f is now used for search by text we
306
        # may as well disable the auto search.
307
        tv.set_search_column(LINE_NUM_COL)
66.5.1 by v.ladeuil+lp at free
Minimal fix for bug #73965.
308
0.1.17 by Dan Loda
A little refactoring.
309
        return tv
0.1.1 by Dan Loda
First working version of xannotate.
310
311
    def _create_log_view(self):
0.1.17 by Dan Loda
A little refactoring.
312
        lv = LogView()
313
        lv.show()
314
315
        return lv
0.1.1 by Dan Loda
First working version of xannotate.
316
317
    def _create_button_box(self):
318
        box = gtk.HButtonBox()
319
        box.set_layout(gtk.BUTTONBOX_END)
320
        box.show()
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
321
0.1.1 by Dan Loda
First working version of xannotate.
322
        button = gtk.Button()
323
        button.set_use_stock(True)
324
        button.set_label("gtk-close")
325
        button.connect("clicked", lambda w: self.destroy())
326
        button.show()
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
327
0.1.1 by Dan Loda
First working version of xannotate.
328
        box.pack_start(button, expand=False, fill=False)
0.2.4 by Dan Loda
Extract class SpanSelector out of GAnnotateWindow.
329
0.1.1 by Dan Loda
First working version of xannotate.
330
        return box
331
66.6.4 by Aaron Bentley
Add back button to see older versions
332
    def _create_prev_button(self):
333
        box = gtk.HButtonBox()
334
        box.set_layout(gtk.BUTTONBOX_START)
335
        box.show()
336
        
337
        button = gtk.Button()
338
        button.set_use_stock(True)
339
        button.set_label("gtk-go-back")
340
        button.connect("clicked", lambda w: self.go_back())
341
        button.show()
342
        box.pack_start(button, expand=False, fill=False)
343
        return box
344
345
    def go_back(self):
346
        rev_id = self._selected_revision()
347
        parent_id = self.revisions[rev_id].parent_ids[0]
348
        tree = self.branch.repository.revision_tree(parent_id)
349
        if self.file_id in tree:
66.6.6 by Aaron Bentley
Support scrolling based on an offset
350
            offset = self.get_scroll_offset(tree)
351
            (row,), col = self.annoview.get_cursor()
66.6.4 by Aaron Bentley
Add back button to see older versions
352
            self.annotate(tree, self.branch, self.file_id)
66.6.6 by Aaron Bentley
Support scrolling based on an offset
353
            self.annoview.set_cursor(row+offset)
354
355
    def get_scroll_offset(self, tree):
356
        old = self.tree.get_file(self.file_id)
357
        new = tree.get_file(self.file_id)
358
        (row,), col = self.annoview.get_cursor()
359
        matcher = patiencediff.PatienceSequenceMatcher(None, old.readlines(),
360
                                                       new.readlines())
361
        for i, j, n in matcher.get_matching_blocks():
362
            if i + n >= row:
363
                return j - i
364
66.6.4 by Aaron Bentley
Add back button to see older versions
365
0.1.1 by Dan Loda
First working version of xannotate.
366
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
367
class FakeRevision:
0.1.1 by Dan Loda
First working version of xannotate.
368
    """ A fake revision.
369
370
    For when a revision is referenced but not present.
371
    """
372
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
373
    def __init__(self, revision_id, committer='?'):
0.1.1 by Dan Loda
First working version of xannotate.
374
        self.revision_id = revision_id
375
        self.parent_ids = []
66.2.14 by Aaron Bentley
Annotate showing uncommitted changes
376
        self.committer = committer
0.1.1 by Dan Loda
First working version of xannotate.
377
        self.message = "?"
378
        self.timestamp = 0.0
379
        self.timezone = 0
380
0.1.23 by Aaron Bentley
Added revision caching to initial annotation
381
382
class RevisionCache(object):
383
    """A caching revision source"""
66.6.5 by Aaron Bentley
Speed up the 'back' operation
384
    def __init__(self, real_source, seed_cache=None):
0.1.23 by Aaron Bentley
Added revision caching to initial annotation
385
        self.__real_source = real_source
66.6.5 by Aaron Bentley
Speed up the 'back' operation
386
        if seed_cache is None:
387
            self.__cache = {}
388
        else:
389
            self.__cache = dict(seed_cache)
0.1.23 by Aaron Bentley
Added revision caching to initial annotation
390
391
    def get_revision(self, revision_id):
392
        if revision_id not in self.__cache:
393
            revision = self.__real_source.get_revision(revision_id)
394
            self.__cache[revision_id] = revision
395
        return self.__cache[revision_id]
66.5.2 by v.ladeuil+lp at free
Better fix for bug #73965.
396
397
class SearchBox(gtk.HBox):
398
    """A button box for searching in text or lines of annotations"""
399
    def __init__(self):
400
        gtk.HBox.__init__(self, False, 6)
401
402
        # Close button
403
        button = gtk.Button()
404
        image = gtk.Image()
405
        image.set_from_stock('gtk-stop', gtk.ICON_SIZE_BUTTON)
406
        button.set_image(image)
407
        button.set_relief(gtk.RELIEF_NONE)
408
        button.connect("clicked", lambda w: self.hide_all())
409
        self.pack_start(button, expand=False, fill=False)
410
411
        # Search entry
412
        label = gtk.Label()
413
        self._label = label
414
        self.pack_start(label, expand=False, fill=False)
415
416
        entry = gtk.Entry()
417
        self._entry = entry
418
        entry.connect("activate", lambda w, d: self._do_search(d),
419
                      'forward')
420
        self.pack_start(entry, expand=False, fill=False)
421
422
        # Next/previous buttons
423
        button = gtk.Button('_Next')
424
        image = gtk.Image()
425
        image.set_from_stock('gtk-go-forward', gtk.ICON_SIZE_BUTTON)
426
        button.set_image(image)
427
        button.connect("clicked", lambda w, d: self._do_search(d),
428
                       'forward')
429
        self.pack_start(button, expand=False, fill=False)
430
431
        button = gtk.Button('_Previous')
432
        image = gtk.Image()
433
        image.set_from_stock('gtk-go-back', gtk.ICON_SIZE_BUTTON)
434
        button.set_image(image)
435
        button.connect("clicked", lambda w, d: self._do_search(d),
436
                       'backward')
437
        self.pack_start(button, expand=False, fill=False)
438
439
        # Search options
440
        check = gtk.CheckButton('Match case')
441
        self._match_case = check
442
        self.pack_start(check, expand=False, fill=False)
443
444
        check = gtk.CheckButton('Regexp')
445
        check.connect("toggled", lambda w: self._set_label())
446
        self._regexp = check
447
        self.pack_start(check, expand=False, fill=False)
448
449
        self._view = None
450
        self._column = None
451
        # Note that we stay hidden (we do not call self.show_all())
452
453
454
    def show_for(self, kind):
455
        self._kind = kind
456
        self.show_all()
457
        self._set_label()
458
        # Hide unrelated buttons
459
        if kind == 'line':
460
            self._match_case.hide()
461
            self._regexp.hide()
462
        # Be ready
463
        self._entry.grab_focus()
464
465
    def _set_label(self):
466
        if self._kind == 'line':
467
            self._label.set_text('Find Line: ')
468
        else:
469
            if self._regexp.get_active():
470
                self._label.set_text('Find Regexp: ')
471
            else:
472
                self._label.set_text('Find Text: ')
473
474
    def set_target(self, view,column):
475
        self._view = view
476
        self._column = column
477
478
    def _match(self, model, iterator, column):
479
        matching_case = self._match_case.get_active()
480
        string, = model.get(iterator, column)
481
        key = self._entry.get_text()
482
        if self._regexp.get_active():
483
            if matching_case:
484
                match = re.compile(key).search(string, 1)
485
            else:
486
                match = re.compile(key, re.I).search(string, 1)
487
        else:
488
            if not matching_case:
489
                string = string.lower()
490
                key = key.lower()
491
            match = string.find(key) != -1
492
493
        return match
494
495
    def _iterate_rows_forward(self, model, start):
496
        model_size = len(model)
497
        current = start + 1
498
        while model_size != 0:
499
            if current >= model_size: current =  0
500
            yield model.get_iter_from_string('%d' % current)
501
            if current == start: raise StopIteration
502
            current += 1
503
504
    def _iterate_rows_backward(self, model, start):
505
        model_size = len(model)
506
        current = start - 1
507
        while model_size != 0:
508
            if current < 0: current = model_size - 1
509
            yield model.get_iter_from_string('%d' % current)
510
            if current == start: raise StopIteration
511
            current -= 1
512
513
    def _do_search(self, direction):
514
        if direction == 'forward':
515
            iterate = self._iterate_rows_forward
516
        else:
517
            iterate = self._iterate_rows_backward
518
519
        model, sel = self._view.get_selection().get_selected()
520
        if sel is None:
521
            start = 0
522
        else:
523
            path = model.get_string_from_iter(sel)
524
            start = int(path)
525
526
        for row in iterate(model, start):
527
            if self._match(model, row, self._column):
528
                path = model.get_path(row)
529
                self._view.set_cursor(path)
530
                self._view.scroll_to_cell(path, use_align=True)
531
                break