/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: Adeodato Simó
  • Date: 2007-07-05 19:50:44 UTC
  • mto: This revision was merged to the branch mainline in revision 234.
  • Revision ID: dato@net.com.org.es-20070705195044-rcrj8f27i386cvrv
Support setting diff colors from gedit's syntax highlighting config too.

Show diffs side-by-side

added added

removed removed

Lines of Context:
14
14
 
15
15
import gtk
16
16
import pango
 
17
import os
 
18
import re
 
19
import sys
17
20
 
18
21
try:
19
22
    import gtksourceview
20
23
    have_gtksourceview = True
21
24
except ImportError:
22
25
    have_gtksourceview = False
 
26
try:
 
27
    import gconf
 
28
    have_gconf = True
 
29
except ImportError:
 
30
    have_gconf = False
23
31
 
24
32
import bzrlib
25
 
if bzrlib.version_info < (0, 9):
26
 
    # function deprecated in 0.9
27
 
    from bzrlib.delta import compare_trees
28
33
 
29
34
from bzrlib.diff import show_diff_trees
30
35
from bzrlib.errors import NoSuchFile
 
36
from bzrlib.trace import warning
31
37
 
32
38
 
33
39
class DiffWindow(gtk.Window):
53
59
 
54
60
    def construct(self):
55
61
        """Construct the window contents."""
56
 
        hbox = gtk.HBox(spacing=6)
57
 
        hbox.set_border_width(0)
58
 
        self.add(hbox)
59
 
        hbox.show()
 
62
        # The   window  consists  of   a  pane   containing:  the
 
63
        # hierarchical list  of files on  the left, and  the diff
 
64
        # for the currently selected file on the right.
 
65
        pane = gtk.HPaned()
 
66
        self.add(pane)
 
67
        pane.show()
60
68
 
 
69
        # The file hierarchy: a scrollable treeview
61
70
        scrollwin = gtk.ScrolledWindow()
62
71
        scrollwin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
63
72
        scrollwin.set_shadow_type(gtk.SHADOW_IN)
64
 
        hbox.pack_start(scrollwin, expand=False, fill=True)
 
73
        pane.pack1(scrollwin)
65
74
        scrollwin.show()
66
75
 
67
76
        self.model = gtk.TreeStore(str, str)
79
88
        column.add_attribute(cell, "text", 0)
80
89
        self.treeview.append_column(column)
81
90
 
82
 
 
 
91
        # The diffs of the  selected file: a scrollable source or
 
92
        # text view
83
93
        scrollwin = gtk.ScrolledWindow()
84
94
        scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
85
95
        scrollwin.set_shadow_type(gtk.SHADOW_IN)
86
 
        hbox.pack_start(scrollwin, expand=True, fill=True)
 
96
        pane.pack2(scrollwin)
87
97
        scrollwin.show()
88
98
 
89
99
        if have_gtksourceview:
90
100
            self.buffer = gtksourceview.SourceBuffer()
91
101
            slm = gtksourceview.SourceLanguagesManager()
92
102
            gsl = slm.get_language_from_mime_type("text/x-patch")
 
103
            if have_gconf:
 
104
                self.apply_gedit_colors(gsl)
 
105
            self.apply_colordiff_colors(gsl)
93
106
            self.buffer.set_language(gsl)
94
107
            self.buffer.set_highlight(True)
95
108
 
113
126
        self.parent_tree = parent_tree
114
127
 
115
128
        self.model.clear()
116
 
        if bzrlib.version_info < (0, 9):
117
 
            delta = compare_trees(self.parent_tree, self.rev_tree)
118
 
        else:
119
 
            delta = self.rev_tree.changes_from(self.parent_tree)
 
129
        delta = self.rev_tree.changes_from(self.parent_tree)
120
130
 
121
131
        self.model.append(None, [ "Complete Diff", "" ])
122
132
 
167
177
 
168
178
        s = StringIO()
169
179
        show_diff_trees(self.parent_tree, self.rev_tree, s, specific_files)
170
 
        self.buffer.set_text(s.getvalue())
 
180
        self.buffer.set_text(s.getvalue().decode(sys.getdefaultencoding(), 'replace'))
 
181
 
 
182
    @staticmethod
 
183
    def apply_gedit_colors(lang):
 
184
        """Set style for lang to that specified in gedit configuration.
 
185
 
 
186
        This method needs the gconf module.
 
187
        
 
188
        :param lang: a gtksourceview.SourceLanguage object.
 
189
        """
 
190
        GEDIT_SYNTAX_PATH = '/apps/gedit-2/preferences/syntax_highlighting'
 
191
        GEDIT_LANG_PATH = GEDIT_SYNTAX_PATH + '/' + lang.get_id()
 
192
 
 
193
        client = gconf.client_get_default()
 
194
        client.add_dir(GEDIT_LANG_PATH, gconf.CLIENT_PRELOAD_NONE)
 
195
 
 
196
        for tag in lang.get_tags():
 
197
            tag_id = tag.get_id()
 
198
            gconf_key = GEDIT_LANG_PATH + '/' + tag_id
 
199
            style_string = client.get_string(gconf_key)
 
200
 
 
201
            if style_string is None:
 
202
                continue
 
203
 
 
204
            # function to get a bool from a string that's either '0' or '1'
 
205
            string_bool = lambda x: bool(int(x))
 
206
 
 
207
            # style_string is a string like "2/#FFCCAA/#000000/0/1/0/0"
 
208
            # values are: mask, fg, bg, italic, bold, underline, strike
 
209
            # this packs them into (str_value, attr_name, conv_func) tuples
 
210
            items = zip(style_string.split('/'), ['mask', 'foreground',
 
211
                'background', 'italic', 'bold', 'underline', 'strikethrough' ],
 
212
                [ int, gtk.gdk.color_parse, gtk.gdk.color_parse, string_bool,
 
213
                    string_bool, string_bool, string_bool ]
 
214
            )
 
215
 
 
216
            style = gtksourceview.SourceTagStyle()
 
217
 
 
218
            # XXX The mask attribute controls whether the present values of
 
219
            # foreground and background color should in fact be used. Ideally
 
220
            # (and that's what gedit does), one could set all three attributes,
 
221
            # and let the TagStyle object figure out which colors to use.
 
222
            # However, in the GtkSourceview python bindings, the mask attribute
 
223
            # is read-only, and it's derived instead from the colors being
 
224
            # set or not. This means that we have to sometimes refrain from
 
225
            # setting fg or bg colors, depending on the value of the mask.
 
226
            # This code could go away if mask were writable.
 
227
            mask = int(items[0][0])
 
228
            if not (mask & 1): # GTK_SOURCE_TAG_STYLE_USE_BACKGROUND
 
229
                items[2:3] = []
 
230
            if not (mask & 2): # GTK_SOURCE_TAG_STYLE_USE_FOREGROUND
 
231
                items[1:2] = []
 
232
            items[0:1] = [] # skip the mask unconditionally
 
233
 
 
234
            for value, attr, func in items:
 
235
                try:
 
236
                    value = func(value)
 
237
                except ValueError:
 
238
                    warning('gconf key %s contains an invalid value: %s'
 
239
                            % gconf_key, value)
 
240
                else:
 
241
                    setattr(style, attr, value)
 
242
 
 
243
            lang.set_tag_style(tag_id, style)
 
244
 
 
245
    @staticmethod
 
246
    def apply_colordiff_colors(lang):
 
247
        """Set style colors for lang using the colordiff configuration file.
 
248
 
 
249
        Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
 
250
 
 
251
        :param lang: a "Diff" gtksourceview.SourceLanguage object.
 
252
        """
 
253
        def parse_colordiffrc(fileobj):
 
254
            """Parse fileobj as a colordiff configuration file.
 
255
            
 
256
            :return: A dict with the key -> value pairs.
 
257
            """
 
258
            colors = {}
 
259
            for line in fileobj:
 
260
                if re.match(r'^\s*#', line):
 
261
                    continue
 
262
                key, val = line.split('=')
 
263
                colors[key.strip()] = val.strip()
 
264
            return colors
 
265
 
 
266
        colors = {}
 
267
 
 
268
        for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
 
269
            f = os.path.expanduser(f)
 
270
            if os.path.exists(f):
 
271
                try:
 
272
                    f = file(f)
 
273
                except IOError, e:
 
274
                    warning('could not open file %s: %s' % (f, str(e)))
 
275
                else:
 
276
                    colors.update(parse_colordiffrc(f))
 
277
                    f.close()
 
278
 
 
279
        if not colors:
 
280
            # ~/.colordiffrc does not exist
 
281
            return
 
282
 
 
283
        mapping = {
 
284
                # map GtkSourceView tags to colordiff names
 
285
                # since GSV is richer, accept new names for extra bits,
 
286
                # defaulting to old names if they're not present
 
287
                'Added@32@line': ['newtext'],
 
288
                'Removed@32@line': ['oldtext'],
 
289
                'Location': ['location', 'diffstuff'],
 
290
                'Diff@32@file': ['file', 'diffstuff'],
 
291
                'Special@32@case': ['specialcase', 'diffstuff'],
 
292
        }
 
293
 
 
294
        for tag in lang.get_tags():
 
295
            tag_id = tag.get_id()
 
296
            keys = mapping.get(tag_id, [])
 
297
            color = None
 
298
 
 
299
            for key in keys:
 
300
                color = colors.get(key, None)
 
301
                if color is not None:
 
302
                    break
 
303
 
 
304
            if color is None:
 
305
                continue
 
306
 
 
307
            style = gtksourceview.SourceTagStyle()
 
308
            try:
 
309
                style.foreground = gtk.gdk.color_parse(color)
 
310
            except ValueError:
 
311
                warning('not a valid color: %s' % color)
 
312
            else:
 
313
                lang.set_tag_style(tag_id, style)