/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: Curtis Hovey
  • Date: 2012-01-23 18:10:44 UTC
  • mto: This revision was merged to the branch mainline in revision 772.
  • Revision ID: sinzui.is@verizon.net-20120123181044-iflf8h79dg6y8fit
Update test to verify that the correct text is shown.

Show diffs side-by-side

added added

removed removed

Lines of Context:
5
5
"""
6
6
 
7
7
__copyright__ = "Copyright 2005 Canonical Ltd."
8
 
__author__ = "Scott James Remnant <scott@ubuntu.com>"
 
8
__author__    = "Scott James Remnant <scott@ubuntu.com>"
9
9
 
10
10
 
11
11
from cStringIO import StringIO
12
12
 
 
13
from gi.repository import Gtk
 
14
from gi.repository import Pango
 
15
import os
 
16
import re
13
17
import sys
14
18
import inspect
 
19
try:
 
20
    from xml.etree.ElementTree import Element, SubElement, tostring
 
21
except ImportError:
 
22
    from elementtree.ElementTree import Element, SubElement, tostring
15
23
 
16
 
from gi.repository import Gtk
17
 
from gi.repository import Pango
18
24
try:
19
25
    from gi.repository import GtkSource
20
26
    have_gtksourceview = True
21
27
except ImportError:
22
28
    have_gtksourceview = False
 
29
try:
 
30
    from gi.repository import GConf
 
31
    have_gconf = True
 
32
except ImportError:
 
33
    have_gconf = False
23
34
 
24
35
from bzrlib import (
25
36
    errors,
27
38
    osutils,
28
39
    urlutils,
29
40
    workingtree,
30
 
    )
 
41
)
31
42
from bzrlib.diff import show_diff_trees
32
43
from bzrlib.patches import parse_patches
 
44
from bzrlib.trace import warning
33
45
from bzrlib.plugins.gtk.dialog import (
34
46
    error_dialog,
35
47
    info_dialog,
55
67
class DiffFileView(Gtk.ScrolledWindow):
56
68
    """Window for displaying diffs from a diff file"""
57
69
 
58
 
    SHOW_WIDGETS = True
59
 
 
60
70
    def __init__(self):
61
71
        super(DiffFileView, self).__init__()
62
72
        self.construct()
70
80
            self.buffer = GtkSource.Buffer()
71
81
            lang_manager = GtkSource.LanguageManager.get_default()
72
82
            language = lang_manager.guess_language(None, "text/x-patch")
 
83
            if have_gconf:
 
84
                self.apply_gedit_colors(self.buffer)
 
85
            self.apply_colordiff_colors(self.buffer)
73
86
            self.buffer.set_language(language)
74
87
            self.buffer.set_highlight_syntax(True)
 
88
 
75
89
            self.sourceview = GtkSource.View(buffer=self.buffer)
76
90
        else:
77
91
            self.buffer = Gtk.TextBuffer()
78
92
            self.sourceview = Gtk.TextView(self.buffer)
79
93
 
80
94
        self.sourceview.set_editable(False)
81
 
        self.sourceview.override_font(Pango.FontDescription("Monospace"))
 
95
        self.sourceview.modify_font(Pango.FontDescription("Monospace"))
82
96
        self.add(self.sourceview)
83
 
        if self.SHOW_WIDGETS:
84
 
            self.sourceview.show()
 
97
        self.sourceview.show()
 
98
 
 
99
    @staticmethod
 
100
    def apply_gedit_colors(buf):
 
101
        """Set style to that specified in gedit configuration.
 
102
 
 
103
        This method needs the gconf module.
 
104
 
 
105
        :param buf: a GtkSource.Buffer object.
 
106
        """
 
107
        GEDIT_SCHEME_PATH = '/apps/gedit-2/preferences/editor/colors/scheme'
 
108
        GEDIT_USER_STYLES_PATH = os.path.expanduser('~/.gnome2/gedit/styles')
 
109
 
 
110
        client = GConf.Client.get_default()
 
111
        style_scheme_name = client.get_string(GEDIT_SCHEME_PATH)
 
112
        if style_scheme_name is not None:
 
113
            style_scheme_mgr = GtkSource.StyleSchemeManager()
 
114
            style_scheme_mgr.append_search_path(GEDIT_USER_STYLES_PATH)
 
115
            
 
116
            style_scheme = style_scheme_mgr.get_scheme(style_scheme_name)
 
117
            
 
118
            if style_scheme is not None:
 
119
                buf.set_style_scheme(style_scheme)
 
120
 
 
121
    @classmethod
 
122
    def apply_colordiff_colors(klass, buf):
 
123
        """Set style colors for lang using the colordiff configuration file.
 
124
 
 
125
        Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
 
126
 
 
127
        :param buf: a "Diff" GtkSource.Buffer object.
 
128
        """
 
129
        scheme_manager = GtkSource.StyleSchemeManager()
 
130
        style_scheme = scheme_manager.get_scheme('colordiff')
 
131
        
 
132
        # if style scheme not found, we'll generate it from colordiffrc
 
133
        # TODO: reload if colordiffrc has changed.
 
134
        if style_scheme is None:
 
135
            colors = {}
 
136
 
 
137
            for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
 
138
                f = os.path.expanduser(f)
 
139
                if os.path.exists(f):
 
140
                    try:
 
141
                        f = file(f)
 
142
                    except IOError, e:
 
143
                        warning('could not open file %s: %s' % (f, str(e)))
 
144
                    else:
 
145
                        colors.update(klass.parse_colordiffrc(f))
 
146
                        f.close()
 
147
 
 
148
            if not colors:
 
149
                # ~/.colordiffrc does not exist
 
150
                return
 
151
            
 
152
            mapping = {
 
153
                # map GtkSourceView2 scheme styles to colordiff names
 
154
                # since GSV is richer, accept new names for extra bits,
 
155
                # defaulting to old names if they're not present
 
156
                'diff:added-line': ['newtext'],
 
157
                'diff:removed-line': ['oldtext'],
 
158
                'diff:location': ['location', 'diffstuff'],
 
159
                'diff:file': ['file', 'diffstuff'],
 
160
                'diff:special-case': ['specialcase', 'diffstuff'],
 
161
            }
 
162
            
 
163
            converted_colors = {}
 
164
            for name, values in mapping.items():
 
165
                color = None
 
166
                for value in values:
 
167
                    color = colors.get(value, None)
 
168
                    if color is not None:
 
169
                        break
 
170
                if color is None:
 
171
                    continue
 
172
                converted_colors[name] = color
 
173
            
 
174
            # some xml magic to produce needed style scheme description
 
175
            e_style_scheme = Element('style-scheme')
 
176
            e_style_scheme.set('id', 'colordiff')
 
177
            e_style_scheme.set('_name', 'ColorDiff')
 
178
            e_style_scheme.set('version', '1.0')
 
179
            for name, color in converted_colors.items():
 
180
                style = SubElement(e_style_scheme, 'style')
 
181
                style.set('name', name)
 
182
                style.set('foreground', '#%s' % color)
 
183
            
 
184
            scheme_xml = tostring(e_style_scheme, 'UTF-8')
 
185
            if not os.path.exists(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles')):
 
186
                os.makedirs(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles'))
 
187
            file(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles/colordiff.xml'), 'w').write(scheme_xml)
 
188
            
 
189
            scheme_manager.force_rescan()
 
190
            style_scheme = scheme_manager.get_scheme('colordiff')
 
191
        
 
192
        buf.set_style_scheme(style_scheme)
 
193
 
 
194
    @staticmethod
 
195
    def parse_colordiffrc(fileobj):
 
196
        """Parse fileobj as a colordiff configuration file.
 
197
 
 
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
85
209
 
86
210
    def set_trees(self, rev_tree, parent_tree):
87
211
        self.rev_tree = rev_tree
92
216
#        self.parent_tree.lock_read()
93
217
#        self.rev_tree.lock_read()
94
218
#        try:
95
 
#            self.delta = iter_changes_to_status(
96
 
#               self.parent_tree, self.rev_tree)
 
219
#            self.delta = iter_changes_to_status(self.parent_tree, self.rev_tree)
97
220
#            self.path_to_status = {}
98
221
#            self.path_to_diff = {}
99
222
#            source_inv = self.parent_tree.inventory
100
223
#            target_inv = self.rev_tree.inventory
101
224
#            for (file_id, real_path, change_type, display_path) in self.delta:
102
 
#                self.path_to_status[real_path] = u'=== %s %s' % (
103
 
#                    change_type, display_path)
 
225
#                self.path_to_status[real_path] = u'=== %s %s' % (change_type, display_path)
104
226
#                if change_type in ('modified', 'renamed and modified'):
105
227
#                    source_ie = source_inv[file_id]
106
228
#                    target_ie = target_inv[file_id]
108
230
#                    source_ie.diff(internal_diff, *old path, *old_tree,
109
231
#                                   *new_path, target_ie, self.rev_tree,
110
232
#                                   sio)
111
 
#                    self.path_to_diff[real_path] =
 
233
#                    self.path_to_diff[real_path] = 
112
234
#
113
235
#        finally:
114
236
#            self.rev_tree.unlock()
175
297
        self.pack1(scrollwin)
176
298
        if self.SHOW_WIDGETS:
177
299
            scrollwin.show()
178
 
 
 
300
        
179
301
        self.model = Gtk.TreeStore(str, str)
180
302
        self.treeview = Gtk.TreeView(model=self.model)
181
303
        self.treeview.set_headers_visible(False)
231
353
        self.model.clear()
232
354
        delta = self.rev_tree.changes_from(self.parent_tree)
233
355
 
234
 
        self.model.append(None, ["Complete Diff", ""])
 
356
        self.model.append(None, [ "Complete Diff", "" ])
235
357
 
236
358
        if len(delta.added):
237
 
            titer = self.model.append(None, ["Added", None])
 
359
            titer = self.model.append(None, [ "Added", None ])
238
360
            for path, id, kind in delta.added:
239
 
                self.model.append(titer, [path, path])
 
361
                self.model.append(titer, [ path, path ])
240
362
 
241
363
        if len(delta.removed):
242
 
            titer = self.model.append(None, ["Removed", None])
 
364
            titer = self.model.append(None, [ "Removed", None ])
243
365
            for path, id, kind in delta.removed:
244
 
                self.model.append(titer, [path, path])
 
366
                self.model.append(titer, [ path, path ])
245
367
 
246
368
        if len(delta.renamed):
247
 
            titer = self.model.append(None, ["Renamed", None])
 
369
            titer = self.model.append(None, [ "Renamed", None ])
248
370
            for oldpath, newpath, id, kind, text_modified, meta_modified \
249
371
                    in delta.renamed:
250
 
                self.model.append(titer, [oldpath, newpath])
 
372
                self.model.append(titer, [ oldpath, newpath ])
251
373
 
252
374
        if len(delta.modified):
253
 
            titer = self.model.append(None, ["Modified", None])
 
375
            titer = self.model.append(None, [ "Modified", None ])
254
376
            for path, id, kind, text_modified, meta_modified in delta.modified:
255
 
                self.model.append(titer, [path, path])
 
377
                self.model.append(titer, [ path, path ])
256
378
 
257
379
        self.treeview.expand_all()
258
380
        self.diff_view.show_diff(None)
275
397
        (path, col) = self.treeview.get_cursor()
276
398
        if path is None:
277
399
            return
278
 
        specific_files = [self.model[path][1]]
279
 
        if specific_files == [None]:
 
400
        specific_files = [ self.model[path][1] ]
 
401
        if specific_files == [ None ]:
280
402
            return
281
 
        elif specific_files == [""]:
 
403
        elif specific_files == [ "" ]:
282
404
            specific_files = None
283
 
 
 
405
        
284
406
        self.diff_view.show_diff(specific_files)
285
 
 
 
407
    
286
408
    def _on_wraplines_toggled(self, widget=None, wrap=False):
287
409
        """Callback for when the wrap lines checkbutton is toggled"""
288
410
        if wrap or widget.get_active():
290
412
        else:
291
413
            self.diff_view.sourceview.set_wrap_mode(Gtk.WrapMode.NONE)
292
414
 
293
 
 
294
415
class DiffWindow(Window):
295
416
    """Diff window.
296
417
 
298
419
    differences between two revisions on a branch.
299
420
    """
300
421
 
301
 
    SHOW_WIDGETS = True
302
 
 
303
422
    def __init__(self, parent=None, operations=None):
304
423
        super(DiffWindow, self).__init__(parent=parent)
305
424
        self.set_border_width(0)
306
 
        self.set_title("bzr diff")
 
425
        self.set_title("bzrk diff")
307
426
 
308
427
        # Use two thirds of the screen by default
309
428
        screen = self.get_screen()
317
436
        """Construct the window contents."""
318
437
        self.vbox = Gtk.VBox()
319
438
        self.add(self.vbox)
320
 
        if self.SHOW_WIDGETS:
321
 
            self.vbox.show()
 
439
        self.vbox.show()
322
440
        self.diff = DiffWidget()
323
441
        self.vbox.pack_end(self.diff, True, True, 0)
324
 
        if self.SHOW_WIDGETS:
325
 
            self.diff.show_all()
 
442
        self.diff.show_all()
326
443
        # Build after DiffWidget to connect signals
327
444
        menubar = self._get_menu_bar()
328
445
        self.vbox.pack_start(menubar, False, False, 0)
329
446
        hbox = self._get_button_bar(operations)
330
447
        if hbox is not None:
331
448
            self.vbox.pack_start(hbox, False, True, 0)
332
 
 
 
449
        
 
450
    
333
451
    def _get_menu_bar(self):
334
452
        menubar = Gtk.MenuBar()
335
453
        # View menu
338
456
        mb_view_wrapsource = Gtk.CheckMenuItem.new_with_mnemonic(
339
457
            _i18n("Wrap _Long Lines"))
340
458
        mb_view_wrapsource.connect('activate', self.diff._on_wraplines_toggled)
 
459
        mb_view_wrapsource.show()
341
460
        mb_view_menu.append(mb_view_wrapsource)
 
461
        mb_view.show()
342
462
        mb_view.set_submenu(mb_view_menu)
 
463
        mb_view.show()
343
464
        menubar.append(mb_view)
344
 
        if self.SHOW_WIDGETS:
345
 
            menubar.show_all()
 
465
        menubar.show()
346
466
        return menubar
347
 
 
 
467
    
348
468
    def _get_button_bar(self, operations):
349
469
        """Return a button bar to use.
350
470
 
356
476
        hbox.set_layout(Gtk.ButtonBoxStyle.START)
357
477
        for title, method in operations:
358
478
            merge_button = Gtk.Button(title)
359
 
            if self.SHOW_WIDGETS:
360
 
                merge_button.show()
 
479
            merge_button.show()
361
480
            merge_button.set_relief(Gtk.ReliefStyle.NONE)
362
481
            merge_button.connect("clicked", method)
363
 
            hbox.pack_start(merge_button, False, True, 0)
364
 
        if self.SHOW_WIDGETS:
365
 
            hbox.show()
 
482
            hbox.pack_start(merge_button, expand=False, fill=True)
 
483
        hbox.show()
366
484
        return hbox
367
485
 
368
486
    def _get_merge_target(self):