/b-gtk/fix-viz

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/b-gtk/fix-viz
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
1
# -*- coding: UTF-8 -*-
2
"""Difference window.
3
4
This module contains the code to manage the diff window which shows
5
the changes made between two revisions on a branch.
6
"""
7
8
__copyright__ = "Copyright © 2005 Canonical Ltd."
9
__author__    = "Scott James Remnant <scott@ubuntu.com>"
10
11
12
from cStringIO import StringIO
13
252 by Aaron Bentley
Fix test suite
14
import pygtk
15
pygtk.require("2.0")
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
16
import gtk
17
import pango
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
18
import os
19
import re
76 by Jelmer Vernooij
Replace non-UTF8 characters rather than generating an exception (fixes #44677).
20
import sys
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
21
22
try:
23
    import gtksourceview
24
    have_gtksourceview = True
25
except ImportError:
26
    have_gtksourceview = False
232.1.3 by Adeodato Simó
Support setting diff colors from gedit's syntax highlighting config too.
27
try:
28
    import gconf
29
    have_gconf = True
30
except ImportError:
31
    have_gconf = False
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
32
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
33
from bzrlib import osutils
34
from bzrlib.diff import show_diff_trees, internal_diff
59.2.4 by Aaron Bentley
Teach gdiff to accept a single file argument
35
from bzrlib.errors import NoSuchFile
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
36
from bzrlib.trace import warning
298.2.1 by Daniel Schierbeck
Refactored the GTK window code, creating a single base window class that handles keyboard events.
37
from bzrlib.plugins.gtk.window import Window
38
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
39
278.1.12 by John Arbash Meinel
Delay computing the delta, and clean up some of the diff view names.
40
class DiffView(gtk.ScrolledWindow):
278.1.4 by John Arbash Meinel
Just playing around.
41
    """This is the soft and chewy filling for a DiffWindow."""
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
42
51 by Jelmer Vernooij
Rework some of the parameters to DiffWindow.set_diff() to be
43
    def __init__(self):
278.1.4 by John Arbash Meinel
Just playing around.
44
        gtk.ScrolledWindow.__init__(self)
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
45
46
        self.construct()
278.1.4 by John Arbash Meinel
Just playing around.
47
        self.rev_tree = None
48
        self.parent_tree = None
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
49
50
    def construct(self):
278.1.4 by John Arbash Meinel
Just playing around.
51
        self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
52
        self.set_shadow_type(gtk.SHADOW_IN)
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
53
54
        if have_gtksourceview:
55
            self.buffer = gtksourceview.SourceBuffer()
56
            slm = gtksourceview.SourceLanguagesManager()
57
            gsl = slm.get_language_from_mime_type("text/x-patch")
232.1.3 by Adeodato Simó
Support setting diff colors from gedit's syntax highlighting config too.
58
            if have_gconf:
59
                self.apply_gedit_colors(gsl)
232.1.2 by Adeodato Simó
Rename apply_colordiffrc to apply_colordiff_colors, improve docstring.
60
            self.apply_colordiff_colors(gsl)
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
61
            self.buffer.set_language(gsl)
62
            self.buffer.set_highlight(True)
63
64
            sourceview = gtksourceview.SourceView(self.buffer)
65
        else:
66
            self.buffer = gtk.TextBuffer()
67
            sourceview = gtk.TextView(self.buffer)
68
69
        sourceview.set_editable(False)
70
        sourceview.modify_font(pango.FontDescription("Monospace"))
278.1.4 by John Arbash Meinel
Just playing around.
71
        self.add(sourceview)
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
72
        sourceview.show()
73
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
74
    @staticmethod
232.1.3 by Adeodato Simó
Support setting diff colors from gedit's syntax highlighting config too.
75
    def apply_gedit_colors(lang):
76
        """Set style for lang to that specified in gedit configuration.
77
78
        This method needs the gconf module.
278.1.4 by John Arbash Meinel
Just playing around.
79
232.1.3 by Adeodato Simó
Support setting diff colors from gedit's syntax highlighting config too.
80
        :param lang: a gtksourceview.SourceLanguage object.
81
        """
82
        GEDIT_SYNTAX_PATH = '/apps/gedit-2/preferences/syntax_highlighting'
83
        GEDIT_LANG_PATH = GEDIT_SYNTAX_PATH + '/' + lang.get_id()
84
85
        client = gconf.client_get_default()
86
        client.add_dir(GEDIT_LANG_PATH, gconf.CLIENT_PRELOAD_NONE)
87
88
        for tag in lang.get_tags():
89
            tag_id = tag.get_id()
90
            gconf_key = GEDIT_LANG_PATH + '/' + tag_id
91
            style_string = client.get_string(gconf_key)
92
93
            if style_string is None:
94
                continue
95
96
            # function to get a bool from a string that's either '0' or '1'
97
            string_bool = lambda x: bool(int(x))
98
99
            # style_string is a string like "2/#FFCCAA/#000000/0/1/0/0"
100
            # values are: mask, fg, bg, italic, bold, underline, strike
101
            # this packs them into (str_value, attr_name, conv_func) tuples
102
            items = zip(style_string.split('/'), ['mask', 'foreground',
103
                'background', 'italic', 'bold', 'underline', 'strikethrough' ],
104
                [ int, gtk.gdk.color_parse, gtk.gdk.color_parse, string_bool,
105
                    string_bool, string_bool, string_bool ]
106
            )
107
108
            style = gtksourceview.SourceTagStyle()
109
110
            # XXX The mask attribute controls whether the present values of
111
            # foreground and background color should in fact be used. Ideally
112
            # (and that's what gedit does), one could set all three attributes,
113
            # and let the TagStyle object figure out which colors to use.
114
            # However, in the GtkSourceview python bindings, the mask attribute
115
            # is read-only, and it's derived instead from the colors being
116
            # set or not. This means that we have to sometimes refrain from
117
            # setting fg or bg colors, depending on the value of the mask.
118
            # This code could go away if mask were writable.
119
            mask = int(items[0][0])
120
            if not (mask & 1): # GTK_SOURCE_TAG_STYLE_USE_BACKGROUND
121
                items[2:3] = []
122
            if not (mask & 2): # GTK_SOURCE_TAG_STYLE_USE_FOREGROUND
123
                items[1:2] = []
124
            items[0:1] = [] # skip the mask unconditionally
125
126
            for value, attr, func in items:
127
                try:
128
                    value = func(value)
129
                except ValueError:
130
                    warning('gconf key %s contains an invalid value: %s'
131
                            % gconf_key, value)
132
                else:
133
                    setattr(style, attr, value)
134
135
            lang.set_tag_style(tag_id, style)
136
137
    @staticmethod
232.1.2 by Adeodato Simó
Rename apply_colordiffrc to apply_colordiff_colors, improve docstring.
138
    def apply_colordiff_colors(lang):
139
        """Set style colors for lang using the colordiff configuration file.
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
140
141
        Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
142
232.1.2 by Adeodato Simó
Rename apply_colordiffrc to apply_colordiff_colors, improve docstring.
143
        :param lang: a "Diff" gtksourceview.SourceLanguage object.
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
144
        """
145
        colors = {}
146
147
        for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
148
            f = os.path.expanduser(f)
149
            if os.path.exists(f):
150
                try:
151
                    f = file(f)
152
                except IOError, e:
153
                    warning('could not open file %s: %s' % (f, str(e)))
154
                else:
278.1.12 by John Arbash Meinel
Delay computing the delta, and clean up some of the diff view names.
155
                    colors.update(DiffView.parse_colordiffrc(f))
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
156
                    f.close()
157
158
        if not colors:
159
            # ~/.colordiffrc does not exist
160
            return
161
162
        mapping = {
163
                # map GtkSourceView tags to colordiff names
164
                # since GSV is richer, accept new names for extra bits,
165
                # defaulting to old names if they're not present
166
                'Added@32@line': ['newtext'],
167
                'Removed@32@line': ['oldtext'],
168
                'Location': ['location', 'diffstuff'],
169
                'Diff@32@file': ['file', 'diffstuff'],
170
                'Special@32@case': ['specialcase', 'diffstuff'],
171
        }
172
173
        for tag in lang.get_tags():
174
            tag_id = tag.get_id()
175
            keys = mapping.get(tag_id, [])
176
            color = None
177
178
            for key in keys:
179
                color = colors.get(key, None)
180
                if color is not None:
181
                    break
182
183
            if color is None:
184
                continue
185
186
            style = gtksourceview.SourceTagStyle()
187
            try:
188
                style.foreground = gtk.gdk.color_parse(color)
189
            except ValueError:
190
                warning('not a valid color: %s' % color)
191
            else:
192
                lang.set_tag_style(tag_id, style)
232.1.4 by Adeodato Simó
Add a test for parse_colordiffrc, and fix the function to handle empty lines.
193
194
    @staticmethod
195
    def parse_colordiffrc(fileobj):
196
        """Parse fileobj as a colordiff configuration file.
278.1.4 by John Arbash Meinel
Just playing around.
197
232.1.4 by Adeodato Simó
Add a test for parse_colordiffrc, and fix the function to handle empty lines.
198
        :return: A dict with the key -> value pairs.
199
        """
200
        colors = {}
201
        for line in fileobj:
202
            if re.match(r'^\s*#', line):
203
                continue
204
            if '=' not in line:
205
                continue
206
            key, val = line.split('=', 1)
207
            colors[key.strip()] = val.strip()
208
        return colors
209
278.1.4 by John Arbash Meinel
Just playing around.
210
    def set_trees(self, rev_tree, parent_tree):
211
        self.rev_tree = rev_tree
212
        self.parent_tree = parent_tree
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
213
#        self._build_delta()
214
215
#    def _build_delta(self):
216
#        self.parent_tree.lock_read()
217
#        self.rev_tree.lock_read()
218
#        try:
219
#            self.delta = _iter_changes_to_status(self.parent_tree, self.rev_tree)
220
#            self.path_to_status = {}
221
#            self.path_to_diff = {}
222
#            source_inv = self.parent_tree.inventory
223
#            target_inv = self.rev_tree.inventory
224
#            for (file_id, real_path, change_type, display_path) in self.delta:
225
#                self.path_to_status[real_path] = u'=== %s %s' % (change_type, display_path)
226
#                if change_type in ('modified', 'renamed and modified'):
227
#                    source_ie = source_inv[file_id]
228
#                    target_ie = target_inv[file_id]
229
#                    sio = StringIO()
230
#                    source_ie.diff(internal_diff, *old path, *old_tree,
231
#                                   *new_path, target_ie, self.rev_tree,
232
#                                   sio)
233
#                    self.path_to_diff[real_path] = 
234
#
235
#        finally:
236
#            self.rev_tree.unlock()
237
#            self.parent_tree.unlock()
278.1.4 by John Arbash Meinel
Just playing around.
238
239
    def show_diff(self, specific_files):
240
        s = StringIO()
278.1.18 by John Arbash Meinel
Start checking the diff view is correct.
241
        show_diff_trees(self.parent_tree, self.rev_tree, s, specific_files,
242
                        old_label='', new_label='',
243
                        # path_encoding=sys.getdefaultencoding()
244
                        # The default is utf-8, but we interpret the file
245
                        # contents as getdefaultencoding(), so we should
246
                        # probably try to make the paths in the same encoding.
247
                        )
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
248
        # str.decode(encoding, 'replace') doesn't do anything. Because if a
249
        # character is not valid in 'encoding' there is nothing to replace, the
250
        # 'replace' is for 'str.encode()'
251
        try:
252
            decoded = s.getvalue().decode(sys.getdefaultencoding())
253
        except UnicodeDecodeError:
254
            try:
255
                decoded = s.getvalue().decode('UTF-8')
256
            except UnicodeDecodeError:
257
                decoded = s.getvalue().decode('iso-8859-1')
258
                # This always works, because every byte has a valid
259
                # mapping from iso-8859-1 to Unicode
260
        # TextBuffer must contain pure UTF-8 data
261
        self.buffer.set_text(decoded.encode('UTF-8'))
278.1.4 by John Arbash Meinel
Just playing around.
262
263
322.1.1 by Jelmer Vernooij
Merge Johns' gcommit improvements and fix conflicts against trunk.
264
class DiffWindow(Window):
278.1.4 by John Arbash Meinel
Just playing around.
265
    """Diff window.
266
267
    This object represents and manages a single window containing the
268
    differences between two revisions on a branch.
269
    """
270
322.1.1 by Jelmer Vernooij
Merge Johns' gcommit improvements and fix conflicts against trunk.
271
    def __init__(self, parent=None):
272
        Window.__init__(self, parent)
278.1.4 by John Arbash Meinel
Just playing around.
273
        self.set_border_width(0)
274
        self.set_title("bzrk diff")
275
276
        # Use two thirds of the screen by default
277
        screen = self.get_screen()
278
        monitor = screen.get_monitor_geometry(0)
279
        width = int(monitor.width * 0.66)
280
        height = int(monitor.height * 0.66)
281
        self.set_default_size(width, height)
282
283
        self.construct()
284
285
    def construct(self):
286
        """Construct the window contents."""
287
        # The   window  consists  of   a  pane   containing:  the
288
        # hierarchical list  of files on  the left, and  the diff
289
        # for the currently selected file on the right.
290
        pane = gtk.HPaned()
291
        self.add(pane)
292
        pane.show()
293
294
        # The file hierarchy: a scrollable treeview
295
        scrollwin = gtk.ScrolledWindow()
296
        scrollwin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
297
        scrollwin.set_shadow_type(gtk.SHADOW_IN)
298
        pane.pack1(scrollwin)
299
        scrollwin.show()
300
301
        self.model = gtk.TreeStore(str, str)
302
        self.treeview = gtk.TreeView(self.model)
303
        self.treeview.set_headers_visible(False)
304
        self.treeview.set_search_column(1)
305
        self.treeview.connect("cursor-changed", self._treeview_cursor_cb)
306
        scrollwin.add(self.treeview)
307
        self.treeview.show()
308
309
        cell = gtk.CellRendererText()
310
        cell.set_property("width-chars", 20)
311
        column = gtk.TreeViewColumn()
312
        column.pack_start(cell, expand=True)
313
        column.add_attribute(cell, "text", 0)
314
        self.treeview.append_column(column)
315
316
        # The diffs of the  selected file: a scrollable source or
317
        # text view
278.1.12 by John Arbash Meinel
Delay computing the delta, and clean up some of the diff view names.
318
        self.diff_view = DiffView()
319
        pane.pack2(self.diff_view)
320
        self.diff_view.show()
278.1.4 by John Arbash Meinel
Just playing around.
321
322
    def set_diff(self, description, rev_tree, parent_tree):
323
        """Set the differences showed by this window.
324
325
        Compares the two trees and populates the window with the
326
        differences.
327
        """
278.1.12 by John Arbash Meinel
Delay computing the delta, and clean up some of the diff view names.
328
        self.diff_view.set_trees(rev_tree, parent_tree)
278.1.4 by John Arbash Meinel
Just playing around.
329
        self.rev_tree = rev_tree
330
        self.parent_tree = parent_tree
331
332
        self.model.clear()
333
        delta = self.rev_tree.changes_from(self.parent_tree)
334
335
        self.model.append(None, [ "Complete Diff", "" ])
336
337
        if len(delta.added):
338
            titer = self.model.append(None, [ "Added", None ])
339
            for path, id, kind in delta.added:
340
                self.model.append(titer, [ path, path ])
341
342
        if len(delta.removed):
343
            titer = self.model.append(None, [ "Removed", None ])
344
            for path, id, kind in delta.removed:
345
                self.model.append(titer, [ path, path ])
346
347
        if len(delta.renamed):
348
            titer = self.model.append(None, [ "Renamed", None ])
349
            for oldpath, newpath, id, kind, text_modified, meta_modified \
350
                    in delta.renamed:
351
                self.model.append(titer, [ oldpath, newpath ])
352
353
        if len(delta.modified):
354
            titer = self.model.append(None, [ "Modified", None ])
355
            for path, id, kind, text_modified, meta_modified in delta.modified:
356
                self.model.append(titer, [ path, path ])
357
358
        self.treeview.expand_all()
359
        self.set_title(description + " - bzrk diff")
360
361
    def set_file(self, file_path):
362
        tv_path = None
363
        for data in self.model:
364
            for child in data.iterchildren():
365
                if child[0] == file_path or child[1] == file_path:
366
                    tv_path = child.path
367
                    break
368
        if tv_path is None:
369
            raise NoSuchFile(file_path)
370
        self.treeview.set_cursor(tv_path)
371
        self.treeview.scroll_to_cell(tv_path)
372
373
    def _treeview_cursor_cb(self, *args):
374
        """Callback for when the treeview cursor changes."""
375
        (path, col) = self.treeview.get_cursor()
376
        specific_files = [ self.model[path][1] ]
377
        if specific_files == [ None ]:
378
            return
379
        elif specific_files == [ "" ]:
380
            specific_files = None
381
278.1.12 by John Arbash Meinel
Delay computing the delta, and clean up some of the diff view names.
382
        self.diff_view.show_diff(specific_files)
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
383
384
385
def _iter_changes_to_status(source, target):
386
    """Determine the differences between trees.
387
388
    This is a wrapper around _iter_changes which just yields more
389
    understandable results.
390
391
    :param source: The source tree (basis tree)
392
    :param target: The target tree
393
    :return: A list of (file_id, real_path, change_type, display_path)
394
    """
395
    added = 'added'
396
    removed = 'removed'
397
    renamed = 'renamed'
398
    renamed_and_modified = 'renamed and modified'
399
    modified = 'modified'
400
    kind_changed = 'kind changed'
401
402
    # TODO: Handle metadata changes
403
404
    status = []
405
    target.lock_read()
406
    try:
407
        source.lock_read()
408
        try:
409
            for (file_id, paths, changed_content, versioned, parent_ids, names,
410
                 kinds, executables) in target._iter_changes(source):
411
412
                # Skip the root entry if it isn't very interesting
413
                if parent_ids == (None, None):
414
                    continue
415
416
                change_type = None
417
                if kinds[0] is None:
418
                    source_marker = ''
419
                else:
420
                    source_marker = osutils.kind_marker(kinds[0])
421
                if kinds[1] is None:
422
                    assert kinds[0] is not None
423
                    marker = osutils.kind_marker(kinds[0])
424
                else:
425
                    marker = osutils.kind_marker(kinds[1])
426
427
                real_path = paths[1]
428
                if real_path is None:
429
                    real_path = paths[0]
430
                assert real_path is not None
431
                display_path = real_path + marker
432
433
                present_source = versioned[0] and kinds[0] is not None
434
                present_target = versioned[1] and kinds[1] is not None
435
436
                if present_source != present_target:
437
                    if present_target:
438
                        change_type = added
439
                    else:
440
                        assert present_source
441
                        change_type = removed
442
                elif names[0] != names[1] or parent_ids[0] != parent_ids[1]:
443
                    # Renamed
444
                    if changed_content or executables[0] != executables[1]:
445
                        # and modified
446
                        change_type = renamed_and_modified
447
                    else:
448
                        change_type = renamed
449
                    display_path = (paths[0] + source_marker
450
                                    + ' => ' + paths[1] + marker)
451
                elif kinds[0] != kinds[1]:
452
                    change_type = kind_changed
453
                    display_path = (paths[0] + source_marker
454
                                    + ' => ' + paths[1] + marker)
455
                elif changed_content is True or executables[0] != executables[1]:
456
                    change_type = modified
457
                else:
458
                    assert False, "How did we get here?"
459
460
                status.append((file_id, real_path, change_type, display_path))
461
        finally:
462
            source.unlock()
463
    finally:
464
        target.unlock()
465
466
    return status