1
# Copyright (C) 2005 Dan Loda <danloda@gmail.com>
 
 
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.
 
 
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.
 
 
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
 
 
26
from bzrlib import patiencediff, tsort
 
 
27
from bzrlib.errors import NoSuchRevision
 
 
28
from bzrlib.revision import NULL_REVISION, CURRENT_REVISION
 
 
30
from colormap import AnnotateColorMap, AnnotateColorSaturation
 
 
31
from bzrlib.plugins.gtk.logview import LogView
 
 
44
class GAnnotateWindow(gtk.Window):
 
 
45
    """Annotate window."""
 
 
47
    def __init__(self, all=False, plain=False):
 
 
51
        gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
 
 
53
        self.set_icon(self.render_icon(gtk.STOCK_FIND, gtk.ICON_SIZE_BUTTON))
 
 
54
        self.annotate_colormap = AnnotateColorSaturation()
 
 
59
    def annotate(self, tree, branch, file_id):
 
 
63
        self.file_id = file_id
 
 
64
        self.revision_id = getattr(tree, 'get_revision_id', 
 
 
65
                                   lambda: CURRENT_REVISION)()
 
 
67
        # [revision id, line number, committer, revno, highlight color, line]
 
 
68
        self.annomodel = gtk.ListStore(gobject.TYPE_STRING,
 
 
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 = ""
 
 
84
                    last_seen = revision.revision_id
 
 
85
                    committer = revision.committer
 
 
87
                if revision.revision_id not in self.revisions:
 
 
88
                    self.revisions[revision.revision_id] = revision
 
 
90
                self.annomodel.append([revision.revision_id,
 
 
97
                self.annotations.append(revision)
 
 
101
                self.annomodel.foreach(self._highlight_annotation, now)
 
 
103
            branch.repository.unlock()
 
 
106
        self.annoview.set_model(self.annomodel)
 
 
107
        self.annoview.grab_focus()
 
 
109
    def jump_to_line(self, lineno):
 
 
110
        if lineno > len(self.annomodel) or lineno < 1:
 
 
112
            # FIXME:should really deal with this in the gui. Perhaps a status
 
 
114
            print("gannotate: Line number %d does't exist. Defaulting to "
 
 
120
        self.annoview.set_cursor(row)
 
 
121
        self.annoview.scroll_to_cell(row, use_align=True)
 
 
123
    def _dotted_revnos(self, repository, revision_id):
 
 
124
        """Return a dict of revision_id -> dotted revno
 
 
126
        :param repository: The repository to get the graph from
 
 
127
        :param revision_id: The last revision for which this info is needed
 
 
129
        graph = repository.get_revision_graph(revision_id)
 
 
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)
 
 
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_revision.properties['branch-nick'] = self.branch.nick
 
 
143
        current_revno = '%d?' % (self.branch.revno() + 1)
 
 
144
        repository = self.branch.repository
 
 
145
        if self.revision_id == CURRENT_REVISION:
 
 
146
            revision_id = self.branch.last_revision()
 
 
148
            revision_id = self.revision_id
 
 
149
        dotted = self._dotted_revnos(repository, revision_id)
 
 
150
        revision_cache = RevisionCache(repository, self.revisions)
 
 
151
        for origin, text in tree.annotate_iter(file_id):
 
 
153
            if rev_id == CURRENT_REVISION:
 
 
154
                revision = current_revision
 
 
155
                revno = current_revno
 
 
158
                    revision = revision_cache.get_revision(rev_id)
 
 
159
                    revno = dotted.get(rev_id, 'merge')
 
 
162
                except NoSuchRevision:
 
 
163
                    revision = FakeRevision(rev_id)
 
 
166
            yield revision, revno, text
 
 
168
    def _highlight_annotation(self, model, path, iter, now):
 
 
169
        revision_id, = model.get(iter, REVISION_ID_COL)
 
 
170
        revision = self.revisions[revision_id]
 
 
171
        model.set(iter, HIGHLIGHT_COLOR_COL,
 
 
172
                  self.annotate_colormap.get_color(revision, now))
 
 
174
    def _selected_revision(self):
 
 
175
        (path, col) = self.annoview.get_cursor()
 
 
178
        return self.annomodel[path][REVISION_ID_COL]
 
 
180
    def _show_log(self, w):
 
 
181
        rev_id = self._selected_revision()
 
 
184
        self.logview.set_revision(self.revisions[rev_id])
 
 
187
        self.logview = self._create_log_view()
 
 
188
        self.annoview = self._create_annotate_view()
 
 
190
        vbox = gtk.VBox(False, 12)
 
 
191
        vbox.set_border_width(12)
 
 
194
        sw = gtk.ScrolledWindow()
 
 
195
        sw.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
 
 
196
        sw.set_shadow_type(gtk.SHADOW_IN)
 
 
197
        sw.add(self.annoview)
 
 
198
        self.annoview.gwindow = self
 
 
201
        self.pane = pane = gtk.VPaned()
 
 
203
        pane.add2(self.logview)
 
 
205
        vbox.pack_start(pane, expand=True, fill=True)
 
 
207
        self._search = SearchBox()
 
 
208
        vbox.pack_start(self._search, expand=False, fill=True)
 
 
209
        accels = gtk.AccelGroup()
 
 
210
        accels.connect_group(gtk.keysyms.f, gtk.gdk.CONTROL_MASK,
 
 
212
                             self._search_by_text)
 
 
213
        accels.connect_group(gtk.keysyms.g, gtk.gdk.CONTROL_MASK,
 
 
215
                             self._search_by_line)
 
 
216
        self.add_accel_group(accels)
 
 
218
        hbox = gtk.HBox(True, 6)
 
 
219
        hbox.pack_start(self._create_prev_button(), expand=False, fill=True)
 
 
220
        hbox.pack_end(self._create_button_box(), expand=False, fill=True)
 
 
222
        vbox.pack_start(hbox, expand=False, fill=True)
 
 
226
    def _search_by_text(self, accel_group, window, key, modifiers):
 
 
227
        self._search.show_for('text')
 
 
228
        self._search.set_target(self.annoview, TEXT_LINE_COL)
 
 
230
    def _search_by_line(self, accel_group, window, key, modifiers):
 
 
231
        self._search.show_for('line')
 
 
232
        self._search.set_target(self.annoview, LINE_NUM_COL)
 
 
234
    def row_diff(self, tv, path, tvc):
 
 
236
        revision = self.annotations[row]
 
 
237
        repository = self.branch.repository
 
 
238
        if revision.revision_id == CURRENT_REVISION:
 
 
240
            tree2 = self.tree.basis_tree()
 
 
242
            tree1 = repository.revision_tree(revision.revision_id)
 
 
243
            if len(revision.parent_ids) > 0:
 
 
244
                tree2 = repository.revision_tree(revision.parent_ids[0])
 
 
246
                tree2 = repository.revision_tree(NULL_REVISION)
 
 
247
        from bzrlib.plugins.gtk.diff import DiffWindow
 
 
248
        window = DiffWindow()
 
 
249
        window.set_diff("Diff for row %d" % (row+1), tree1, tree2)
 
 
250
        window.set_file(tree1.id2path(self.file_id))
 
 
254
    def _create_annotate_view(self):
 
 
256
        tv.set_rules_hint(False)
 
 
257
        tv.connect("cursor-changed", self._show_log)
 
 
259
        tv.connect("row-activated", self.row_diff)
 
 
261
        cell = gtk.CellRendererText()
 
 
262
        cell.set_property("xalign", 1.0)
 
 
263
        cell.set_property("ypad", 0)
 
 
264
        cell.set_property("family", "Monospace")
 
 
265
        cell.set_property("cell-background-gdk",
 
 
266
                          tv.get_style().bg[gtk.STATE_NORMAL])
 
 
267
        col = gtk.TreeViewColumn()
 
 
268
        col.set_resizable(False)
 
 
269
        col.pack_start(cell, expand=True)
 
 
270
        col.add_attribute(cell, "text", LINE_NUM_COL)
 
 
271
        tv.append_column(col)
 
 
273
        cell = gtk.CellRendererText()
 
 
274
        cell.set_property("ypad", 0)
 
 
275
        cell.set_property("ellipsize", pango.ELLIPSIZE_END)
 
 
276
        cell.set_property("cell-background-gdk",
 
 
277
                          self.get_style().bg[gtk.STATE_NORMAL])
 
 
278
        col = gtk.TreeViewColumn("Committer")
 
 
279
        col.set_resizable(True)
 
 
280
        col.pack_start(cell, expand=True)
 
 
281
        col.add_attribute(cell, "text", COMMITTER_COL)
 
 
282
        tv.append_column(col)
 
 
284
        cell = gtk.CellRendererText()
 
 
285
        cell.set_property("xalign", 1.0)
 
 
286
        cell.set_property("ypad", 0)
 
 
287
        cell.set_property("cell-background-gdk",
 
 
288
                          self.get_style().bg[gtk.STATE_NORMAL])
 
 
289
        col = gtk.TreeViewColumn("Revno")
 
 
290
        col.set_resizable(False)
 
 
291
        col.pack_start(cell, expand=True)
 
 
292
        col.add_attribute(cell, "markup", REVNO_COL)
 
 
293
        tv.append_column(col)
 
 
295
        cell = gtk.CellRendererText()
 
 
296
        cell.set_property("ypad", 0)
 
 
297
        cell.set_property("family", "Monospace")
 
 
298
        col = gtk.TreeViewColumn()
 
 
299
        col.set_resizable(False)
 
 
300
        col.pack_start(cell, expand=True)
 
 
301
#        col.add_attribute(cell, "foreground", HIGHLIGHT_COLOR_COL)
 
 
302
        col.add_attribute(cell, "background", HIGHLIGHT_COLOR_COL)
 
 
303
        col.add_attribute(cell, "text", TEXT_LINE_COL)
 
 
304
        tv.append_column(col)
 
 
306
        # FIXME: Now that C-f is now used for search by text we
 
 
307
        # may as well disable the auto search.
 
 
308
        tv.set_search_column(LINE_NUM_COL)
 
 
312
    def _create_log_view(self):
 
 
317
    def _create_button_box(self):
 
 
318
        box = gtk.HButtonBox()
 
 
319
        box.set_layout(gtk.BUTTONBOX_END)
 
 
322
        button = gtk.Button()
 
 
323
        button.set_use_stock(True)
 
 
324
        button.set_label("gtk-close")
 
 
325
        button.connect("clicked", lambda w: self.destroy())
 
 
328
        box.pack_start(button, expand=False, fill=False)
 
 
332
    def _create_prev_button(self):
 
 
333
        box = gtk.HButtonBox()
 
 
334
        box.set_layout(gtk.BUTTONBOX_START)
 
 
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())
 
 
342
        box.pack_start(button, expand=False, fill=False)
 
 
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:
 
 
350
            offset = self.get_scroll_offset(tree)
 
 
351
            (row,), col = self.annoview.get_cursor()
 
 
352
            self.annotate(tree, self.branch, self.file_id)
 
 
353
            self.annoview.set_cursor(row+offset)
 
 
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(),
 
 
361
        for i, j, n in matcher.get_matching_blocks():
 
 
370
    For when a revision is referenced but not present.
 
 
373
    def __init__(self, revision_id, committer='?', nick=None):
 
 
374
        self.revision_id = revision_id
 
 
376
        self.committer = committer
 
 
383
class RevisionCache(object):
 
 
384
    """A caching revision source"""
 
 
385
    def __init__(self, real_source, seed_cache=None):
 
 
386
        self.__real_source = real_source
 
 
387
        if seed_cache is None:
 
 
390
            self.__cache = dict(seed_cache)
 
 
392
    def get_revision(self, revision_id):
 
 
393
        if revision_id not in self.__cache:
 
 
394
            revision = self.__real_source.get_revision(revision_id)
 
 
395
            self.__cache[revision_id] = revision
 
 
396
        return self.__cache[revision_id]
 
 
398
class SearchBox(gtk.HBox):
 
 
399
    """A button box for searching in text or lines of annotations"""
 
 
401
        gtk.HBox.__init__(self, False, 6)
 
 
404
        button = gtk.Button()
 
 
406
        image.set_from_stock('gtk-stop', gtk.ICON_SIZE_BUTTON)
 
 
407
        button.set_image(image)
 
 
408
        button.set_relief(gtk.RELIEF_NONE)
 
 
409
        button.connect("clicked", lambda w: self.hide_all())
 
 
410
        self.pack_start(button, expand=False, fill=False)
 
 
415
        self.pack_start(label, expand=False, fill=False)
 
 
419
        entry.connect("activate", lambda w, d: self._do_search(d),
 
 
421
        self.pack_start(entry, expand=False, fill=False)
 
 
423
        # Next/previous buttons
 
 
424
        button = gtk.Button('_Next')
 
 
426
        image.set_from_stock('gtk-go-forward', gtk.ICON_SIZE_BUTTON)
 
 
427
        button.set_image(image)
 
 
428
        button.connect("clicked", lambda w, d: self._do_search(d),
 
 
430
        self.pack_start(button, expand=False, fill=False)
 
 
432
        button = gtk.Button('_Previous')
 
 
434
        image.set_from_stock('gtk-go-back', gtk.ICON_SIZE_BUTTON)
 
 
435
        button.set_image(image)
 
 
436
        button.connect("clicked", lambda w, d: self._do_search(d),
 
 
438
        self.pack_start(button, expand=False, fill=False)
 
 
441
        check = gtk.CheckButton('Match case')
 
 
442
        self._match_case = check
 
 
443
        self.pack_start(check, expand=False, fill=False)
 
 
445
        check = gtk.CheckButton('Regexp')
 
 
446
        check.connect("toggled", lambda w: self._set_label())
 
 
448
        self.pack_start(check, expand=False, fill=False)
 
 
452
        # Note that we stay hidden (we do not call self.show_all())
 
 
455
    def show_for(self, kind):
 
 
459
        # Hide unrelated buttons
 
 
461
            self._match_case.hide()
 
 
464
        self._entry.grab_focus()
 
 
466
    def _set_label(self):
 
 
467
        if self._kind == 'line':
 
 
468
            self._label.set_text('Find Line: ')
 
 
470
            if self._regexp.get_active():
 
 
471
                self._label.set_text('Find Regexp: ')
 
 
473
                self._label.set_text('Find Text: ')
 
 
475
    def set_target(self, view,column):
 
 
477
        self._column = column
 
 
479
    def _match(self, model, iterator, column):
 
 
480
        matching_case = self._match_case.get_active()
 
 
481
        string, = model.get(iterator, column)
 
 
482
        key = self._entry.get_text()
 
 
483
        if self._regexp.get_active():
 
 
485
                match = re.compile(key).search(string, 1)
 
 
487
                match = re.compile(key, re.I).search(string, 1)
 
 
489
            if not matching_case:
 
 
490
                string = string.lower()
 
 
492
            match = string.find(key) != -1
 
 
496
    def _iterate_rows_forward(self, model, start):
 
 
497
        model_size = len(model)
 
 
499
        while model_size != 0:
 
 
500
            if current >= model_size: current =  0
 
 
501
            yield model.get_iter_from_string('%d' % current)
 
 
502
            if current == start: raise StopIteration
 
 
505
    def _iterate_rows_backward(self, model, start):
 
 
506
        model_size = len(model)
 
 
508
        while model_size != 0:
 
 
509
            if current < 0: current = model_size - 1
 
 
510
            yield model.get_iter_from_string('%d' % current)
 
 
511
            if current == start: raise StopIteration
 
 
514
    def _do_search(self, direction):
 
 
515
        if direction == 'forward':
 
 
516
            iterate = self._iterate_rows_forward
 
 
518
            iterate = self._iterate_rows_backward
 
 
520
        model, sel = self._view.get_selection().get_selected()
 
 
524
            path = model.get_string_from_iter(sel)
 
 
527
        for row in iterate(model, start):
 
 
528
            if self._match(model, row, self._column):
 
 
529
                path = model.get_path(row)
 
 
530
                self._view.set_cursor(path)
 
 
531
                self._view.scroll_to_cell(path, use_align=True)