/b-gtk/fix-viz

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/b-gtk/fix-viz

« back to all changes in this revision

Viewing changes to annotate/gannotate.py

  • Committer: Jelmer Vernooij
  • Date: 2006-05-19 16:37:13 UTC
  • Revision ID: jelmer@samba.org-20060519163713-be77b31c72cbc7e8
Move visualisation code to a separate directory, preparing for bundling 
the GTK+ plugins for bzr.

Show diffs side-by-side

added added

removed removed

Lines of Context:
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
 
 
17
 
import time
18
 
 
19
 
import pygtk
20
 
pygtk.require("2.0")
21
 
import gobject
22
 
import gtk
23
 
import pango
24
 
import re
25
 
 
26
 
from bzrlib import patiencediff, tsort
27
 
from bzrlib.errors import NoSuchRevision
28
 
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
29
 
 
30
 
from colormap import AnnotateColorMap, AnnotateColorSaturation
31
 
from bzrlib.plugins.gtk.logview import LogView
32
 
 
33
 
 
34
 
(
35
 
    REVISION_ID_COL,
36
 
    LINE_NUM_COL,
37
 
    COMMITTER_COL,
38
 
    REVNO_COL,
39
 
    HIGHLIGHT_COLOR_COL,
40
 
    TEXT_LINE_COL
41
 
) = range(6)
42
 
 
43
 
 
44
 
class GAnnotateWindow(gtk.Window):
45
 
    """Annotate window."""
46
 
 
47
 
    def __init__(self, all=False, plain=False):
48
 
        self.all = all
49
 
        self.plain = plain
50
 
        
51
 
        gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
52
 
        
53
 
        self.set_icon(self.render_icon(gtk.STOCK_FIND, gtk.ICON_SIZE_BUTTON))
54
 
        self.annotate_colormap = AnnotateColorSaturation()
55
 
 
56
 
        self._create()
57
 
        self.revisions = {}
58
 
 
59
 
    def annotate(self, tree, branch, file_id):
60
 
        self.annotations = []
61
 
        self.branch = branch
62
 
        self.tree = tree
63
 
        self.file_id = file_id
64
 
        self.revision_id = getattr(tree, 'get_revision_id', 
65
 
                                   lambda: CURRENT_REVISION)()
66
 
        
67
 
        # [revision id, line number, committer, revno, highlight color, line]
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)
74
 
        
75
 
        last_seen = None
76
 
        try:
77
 
            branch.lock_read()
78
 
            branch.repository.lock_read()
79
 
            for line_no, (revision, revno, line)\
80
 
                    in enumerate(self._annotate(tree, file_id)):
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
 
                                      ])
97
 
                self.annotations.append(revision)
98
 
 
99
 
            if not self.plain:
100
 
                now = time.time()
101
 
                self.annomodel.foreach(self._highlight_annotation, now)
102
 
        finally:
103
 
            branch.repository.unlock()
104
 
            branch.unlock()
105
 
 
106
 
        self.annoview.set_model(self.annomodel)
107
 
        self.annoview.grab_focus()
108
 
 
109
 
    def jump_to_line(self, lineno):
110
 
        if lineno > len(self.annomodel) or lineno < 1:
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)
116
 
            return
117
 
        else:
118
 
            row = lineno - 1
119
 
 
120
 
        self.annoview.set_cursor(row)
121
 
        self.annoview.scroll_to_cell(row, use_align=True)
122
 
 
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
 
 
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]'
141
 
        current_revision.parent_ids = tree.get_parent_ids()
142
 
        current_revno = '%d?' % (self.branch.revno() + 1)
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
148
 
        dotted = self._dotted_revnos(repository, revision_id)
149
 
        revision_cache = RevisionCache(repository, self.revisions)
150
 
        for origin, text in tree.annotate_iter(file_id):
151
 
            rev_id = origin
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:
162
 
                    revision = FakeRevision(rev_id)
163
 
                    revno = "?"
164
 
 
165
 
            yield revision, revno, text
166
 
 
167
 
    def _highlight_annotation(self, model, path, iter, now):
168
 
        revision_id, = model.get(iter, REVISION_ID_COL)
169
 
        revision = self.revisions[revision_id]
170
 
        model.set(iter, HIGHLIGHT_COLOR_COL,
171
 
                  self.annotate_colormap.get_color(revision, now))
172
 
 
173
 
    def _selected_revision(self):
174
 
        (path, col) = self.annoview.get_cursor()
175
 
        if path is None:
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:
182
 
            return
183
 
        self.logview.set_revision(self.revisions[rev_id])
184
 
 
185
 
    def _create(self):
186
 
        self.logview = self._create_log_view()
187
 
        self.annoview = self._create_annotate_view()
188
 
 
189
 
        vbox = gtk.VBox(False, 12)
190
 
        vbox.set_border_width(12)
191
 
        vbox.show()
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)
197
 
        self.annoview.gwindow = self
198
 
        sw.show()
199
 
        
200
 
        self.pane = pane = gtk.VPaned()
201
 
        pane.add1(sw)
202
 
        pane.add2(self.logview)
203
 
        pane.show()
204
 
        vbox.pack_start(pane, expand=True, fill=True)
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
 
 
217
 
        hbox = gtk.HBox(True, 6)
218
 
        hbox.pack_start(self._create_prev_button(), expand=False, fill=True)
219
 
        hbox.pack_end(self._create_button_box(), expand=False, fill=True)
220
 
        hbox.show()
221
 
        vbox.pack_start(hbox, expand=False, fill=True)
222
 
 
223
 
        self.add(vbox)
224
 
 
225
 
    def _search_by_text(self, accel_group, window, key, modifiers):
226
 
        self._search.show_for('text')
227
 
        self._search.set_target(self.annoview, TEXT_LINE_COL)
228
 
 
229
 
    def _search_by_line(self, accel_group, window, key, modifiers):
230
 
        self._search.show_for('line')
231
 
        self._search.set_target(self.annoview, LINE_NUM_COL)
232
 
 
233
 
    def row_diff(self, tv, path, tvc):
234
 
        row = path[0]
235
 
        revision = self.annotations[row]
236
 
        repository = self.branch.repository
237
 
        if revision.revision_id == CURRENT_REVISION:
238
 
            tree1 = self.tree
239
 
            tree2 = self.tree.basis_tree()
240
 
        else:
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)
246
 
        from bzrlib.plugins.gtk.diff import DiffWindow
247
 
        window = DiffWindow()
248
 
        window.set_diff("Diff for row %d" % (row+1), tree1, tree2)
249
 
        window.set_file(tree1.id2path(self.file_id))
250
 
        window.show()
251
 
 
252
 
 
253
 
    def _create_annotate_view(self):
254
 
        tv = gtk.TreeView()
255
 
        tv.set_rules_hint(False)
256
 
        tv.connect("cursor-changed", self._show_log)
257
 
        tv.show()
258
 
        tv.connect("row-activated", self.row_diff)
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",
265
 
                          tv.get_style().bg[gtk.STATE_NORMAL])
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)
270
 
        tv.append_column(col)
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)
281
 
        tv.append_column(col)
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)
292
 
        tv.append_column(col)
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)
300
 
#        col.add_attribute(cell, "foreground", HIGHLIGHT_COLOR_COL)
301
 
        col.add_attribute(cell, "background", HIGHLIGHT_COLOR_COL)
302
 
        col.add_attribute(cell, "text", TEXT_LINE_COL)
303
 
        tv.append_column(col)
304
 
 
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)
308
 
 
309
 
        return tv
310
 
 
311
 
    def _create_log_view(self):
312
 
        lv = LogView()
313
 
        lv.show()
314
 
        return lv
315
 
 
316
 
    def _create_button_box(self):
317
 
        box = gtk.HButtonBox()
318
 
        box.set_layout(gtk.BUTTONBOX_END)
319
 
        box.show()
320
 
 
321
 
        button = gtk.Button()
322
 
        button.set_use_stock(True)
323
 
        button.set_label("gtk-close")
324
 
        button.connect("clicked", lambda w: self.destroy())
325
 
        button.show()
326
 
 
327
 
        box.pack_start(button, expand=False, fill=False)
328
 
 
329
 
        return box
330
 
 
331
 
    def _create_prev_button(self):
332
 
        box = gtk.HButtonBox()
333
 
        box.set_layout(gtk.BUTTONBOX_START)
334
 
        box.show()
335
 
        
336
 
        button = gtk.Button()
337
 
        button.set_use_stock(True)
338
 
        button.set_label("gtk-go-back")
339
 
        button.connect("clicked", lambda w: self.go_back())
340
 
        button.show()
341
 
        box.pack_start(button, expand=False, fill=False)
342
 
        return box
343
 
 
344
 
    def go_back(self):
345
 
        rev_id = self._selected_revision()
346
 
        parent_id = self.revisions[rev_id].parent_ids[0]
347
 
        tree = self.branch.repository.revision_tree(parent_id)
348
 
        if self.file_id in tree:
349
 
            offset = self.get_scroll_offset(tree)
350
 
            (row,), col = self.annoview.get_cursor()
351
 
            self.annotate(tree, self.branch, self.file_id)
352
 
            self.annoview.set_cursor(row+offset)
353
 
 
354
 
    def get_scroll_offset(self, tree):
355
 
        old = self.tree.get_file(self.file_id)
356
 
        new = tree.get_file(self.file_id)
357
 
        (row,), col = self.annoview.get_cursor()
358
 
        matcher = patiencediff.PatienceSequenceMatcher(None, old.readlines(),
359
 
                                                       new.readlines())
360
 
        for i, j, n in matcher.get_matching_blocks():
361
 
            if i + n >= row:
362
 
                return j - i
363
 
 
364
 
 
365
 
 
366
 
class FakeRevision:
367
 
    """ A fake revision.
368
 
 
369
 
    For when a revision is referenced but not present.
370
 
    """
371
 
 
372
 
    def __init__(self, revision_id, committer='?'):
373
 
        self.revision_id = revision_id
374
 
        self.parent_ids = []
375
 
        self.committer = committer
376
 
        self.message = "?"
377
 
        self.timestamp = 0.0
378
 
        self.timezone = 0
379
 
        self.properties = []
380
 
 
381
 
 
382
 
class RevisionCache(object):
383
 
    """A caching revision source"""
384
 
    def __init__(self, real_source, seed_cache=None):
385
 
        self.__real_source = real_source
386
 
        if seed_cache is None:
387
 
            self.__cache = {}
388
 
        else:
389
 
            self.__cache = dict(seed_cache)
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]
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