/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 diff.py

  • Committer: Daniel Schierbeck
  • Date: 2007-11-07 14:19:09 UTC
  • mfrom: (330.3.5 trunk)
  • Revision ID: daniel.schierbeck@gmail.com-20071107141909-3zxf7nw5laldvfxi
Merged with mainline.

Show diffs side-by-side

added added

removed removed

Lines of Context:
30
30
except ImportError:
31
31
    have_gconf = False
32
32
 
33
 
import bzrlib
34
 
 
35
 
from bzrlib.diff import show_diff_trees
 
33
from bzrlib import osutils
 
34
from bzrlib.diff import show_diff_trees, internal_diff
36
35
from bzrlib.errors import NoSuchFile
37
36
from bzrlib.trace import warning
38
37
from bzrlib.plugins.gtk.window import Window
39
38
 
40
 
class DiffWindow(Window):
41
 
    """Diff window.
42
 
 
43
 
    This object represents and manages a single window containing the
44
 
    differences between two revisions on a branch.
45
 
    """
46
 
 
47
 
    def __init__(self, parent=None):
48
 
        Window.__init__(self, parent)
49
 
        self.set_border_width(0)
50
 
        self.set_title("Changes")
51
 
 
52
 
        # Use two thirds of the screen by default
53
 
        screen = self.get_screen()
54
 
        monitor = screen.get_monitor_geometry(0)
55
 
        width = int(monitor.width * 0.66)
56
 
        height = int(monitor.height * 0.66)
57
 
        self.set_default_size(width, height)
 
39
 
 
40
class DiffView(gtk.ScrolledWindow):
 
41
    """This is the soft and chewy filling for a DiffWindow."""
 
42
 
 
43
    def __init__(self):
 
44
        gtk.ScrolledWindow.__init__(self)
58
45
 
59
46
        self.construct()
 
47
        self.rev_tree = None
 
48
        self.parent_tree = None
60
49
 
61
50
    def construct(self):
62
 
        """Construct the window contents."""
63
 
        # The   window  consists  of   a  pane   containing:  the
64
 
        # hierarchical list  of files on  the left, and  the diff
65
 
        # for the currently selected file on the right.
66
 
        pane = gtk.HPaned()
67
 
        self.add(pane)
68
 
        pane.show()
69
 
 
70
 
        # The file hierarchy: a scrollable treeview
71
 
        scrollwin = gtk.ScrolledWindow()
72
 
        scrollwin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
73
 
        scrollwin.set_shadow_type(gtk.SHADOW_IN)
74
 
        pane.pack1(scrollwin)
75
 
        scrollwin.show()
76
 
 
77
 
        self.model = gtk.TreeStore(str, str)
78
 
        self.treeview = gtk.TreeView(self.model)
79
 
        self.treeview.set_headers_visible(False)
80
 
        self.treeview.set_search_column(1)
81
 
        self.treeview.connect("cursor-changed", self._treeview_cursor_cb)
82
 
        scrollwin.add(self.treeview)
83
 
        self.treeview.show()
84
 
 
85
 
        cell = gtk.CellRendererText()
86
 
        cell.set_property("width-chars", 20)
87
 
        column = gtk.TreeViewColumn()
88
 
        column.pack_start(cell, expand=True)
89
 
        column.add_attribute(cell, "text", 0)
90
 
        self.treeview.append_column(column)
91
 
 
92
 
        # The diffs of the  selected file: a scrollable source or
93
 
        # text view
94
 
        scrollwin = gtk.ScrolledWindow()
95
 
        scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
96
 
        scrollwin.set_shadow_type(gtk.SHADOW_IN)
97
 
        pane.pack2(scrollwin)
98
 
        scrollwin.show()
 
51
        self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
 
52
        self.set_shadow_type(gtk.SHADOW_IN)
99
53
 
100
54
        if have_gtksourceview:
101
55
            self.buffer = gtksourceview.SourceBuffer()
114
68
 
115
69
        sourceview.set_editable(False)
116
70
        sourceview.modify_font(pango.FontDescription("Monospace"))
117
 
        scrollwin.add(sourceview)
 
71
        self.add(sourceview)
118
72
        sourceview.show()
119
73
 
120
 
    def set_diff(self, description, rev_tree, parent_tree):
121
 
        """Set the differences showed by this window.
122
 
 
123
 
        Compares the two trees and populates the window with the
124
 
        differences.
125
 
        """
126
 
        self.rev_tree = rev_tree
127
 
        self.parent_tree = parent_tree
128
 
 
129
 
        self.model.clear()
130
 
        delta = self.rev_tree.changes_from(self.parent_tree)
131
 
 
132
 
        self.model.append(None, [ "All Changes", "" ])
133
 
 
134
 
        if len(delta.added):
135
 
            titer = self.model.append(None, [ "Added", None ])
136
 
            for path, id, kind in delta.added:
137
 
                self.model.append(titer, [ path, path ])
138
 
 
139
 
        if len(delta.removed):
140
 
            titer = self.model.append(None, [ "Removed", None ])
141
 
            for path, id, kind in delta.removed:
142
 
                self.model.append(titer, [ path, path ])
143
 
 
144
 
        if len(delta.renamed):
145
 
            titer = self.model.append(None, [ "Renamed", None ])
146
 
            for oldpath, newpath, id, kind, text_modified, meta_modified \
147
 
                    in delta.renamed:
148
 
                self.model.append(titer, [ oldpath, newpath ])
149
 
 
150
 
        if len(delta.modified):
151
 
            titer = self.model.append(None, [ "Modified", None ])
152
 
            for path, id, kind, text_modified, meta_modified in delta.modified:
153
 
                self.model.append(titer, [ path, path ])
154
 
 
155
 
        self.treeview.expand_all()
156
 
        self.set_title(description + " - Changes")
157
 
 
158
 
    def set_file(self, file_path):
159
 
        tv_path = None
160
 
        for data in self.model:
161
 
            for child in data.iterchildren():
162
 
                if child[0] == file_path or child[1] == file_path:
163
 
                    tv_path = child.path
164
 
                    break
165
 
        if tv_path is None:
166
 
            raise NoSuchFile(file_path)
167
 
        self.treeview.set_cursor(tv_path)
168
 
        self.treeview.scroll_to_cell(tv_path)
169
 
 
170
 
    def _treeview_cursor_cb(self, *args):
171
 
        """Callback for when the treeview cursor changes."""
172
 
        (path, col) = self.treeview.get_cursor()
173
 
        specific_files = [ self.model[path][1] ]
174
 
        if specific_files == [ None ]:
175
 
            return
176
 
        elif specific_files == [ "" ]:
177
 
            specific_files = None
178
 
 
179
 
        s = StringIO()
180
 
        show_diff_trees(self.parent_tree, self.rev_tree, s, specific_files)
181
 
        self.buffer.set_text(s.getvalue().decode(sys.getdefaultencoding(), 'replace'))
182
 
 
183
74
    @staticmethod
184
75
    def apply_gedit_colors(lang):
185
76
        """Set style for lang to that specified in gedit configuration.
186
77
 
187
78
        This method needs the gconf module.
188
 
        
 
79
 
189
80
        :param lang: a gtksourceview.SourceLanguage object.
190
81
        """
191
82
        GEDIT_SYNTAX_PATH = '/apps/gedit-2/preferences/syntax_highlighting'
261
152
                except IOError, e:
262
153
                    warning('could not open file %s: %s' % (f, str(e)))
263
154
                else:
264
 
                    colors.update(DiffWindow.parse_colordiffrc(f))
 
155
                    colors.update(DiffView.parse_colordiffrc(f))
265
156
                    f.close()
266
157
 
267
158
        if not colors:
303
194
    @staticmethod
304
195
    def parse_colordiffrc(fileobj):
305
196
        """Parse fileobj as a colordiff configuration file.
306
 
        
 
197
 
307
198
        :return: A dict with the key -> value pairs.
308
199
        """
309
200
        colors = {}
316
207
            colors[key.strip()] = val.strip()
317
208
        return colors
318
209
 
 
210
    def set_trees(self, rev_tree, parent_tree):
 
211
        self.rev_tree = rev_tree
 
212
        self.parent_tree = parent_tree
 
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()
 
238
 
 
239
    def show_diff(self, specific_files):
 
240
        s = StringIO()
 
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
                        )
 
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'))
 
262
 
 
263
 
 
264
class DiffWindow(Window):
 
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
 
 
271
    def __init__(self, parent=None):
 
272
        Window.__init__(self, parent)
 
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
 
318
        self.diff_view = DiffView()
 
319
        pane.pack2(self.diff_view)
 
320
        self.diff_view.show()
 
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
        """
 
328
        self.diff_view.set_trees(rev_tree, parent_tree)
 
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
 
 
382
        self.diff_view.show_diff(specific_files)
 
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