/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: Jelmer Vernooij
  • Date: 2007-07-16 23:25:54 UTC
  • mfrom: (232.1.4 bzr-gtk)
  • Revision ID: jelmer@samba.org-20070716232554-xq4mypahdh0pv0tn
Merge support for color diff configuration from Adeodato.

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
17
19
import sys
18
20
 
19
21
try:
21
23
    have_gtksourceview = True
22
24
except ImportError:
23
25
    have_gtksourceview = False
 
26
try:
 
27
    import gconf
 
28
    have_gconf = True
 
29
except ImportError:
 
30
    have_gconf = False
24
31
 
25
32
import bzrlib
26
33
 
27
34
from bzrlib.diff import show_diff_trees
28
35
from bzrlib.errors import NoSuchFile
 
36
from bzrlib.trace import warning
29
37
 
30
38
 
31
39
class DiffWindow(gtk.Window):
92
100
            self.buffer = gtksourceview.SourceBuffer()
93
101
            slm = gtksourceview.SourceLanguagesManager()
94
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)
95
106
            self.buffer.set_language(gsl)
96
107
            self.buffer.set_highlight(True)
97
108
 
167
178
        s = StringIO()
168
179
        show_diff_trees(self.parent_tree, self.rev_tree, s, specific_files)
169
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
        colors = {}
 
254
 
 
255
        for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
 
256
            f = os.path.expanduser(f)
 
257
            if os.path.exists(f):
 
258
                try:
 
259
                    f = file(f)
 
260
                except IOError, e:
 
261
                    warning('could not open file %s: %s' % (f, str(e)))
 
262
                else:
 
263
                    colors.update(DiffWindow.parse_colordiffrc(f))
 
264
                    f.close()
 
265
 
 
266
        if not colors:
 
267
            # ~/.colordiffrc does not exist
 
268
            return
 
269
 
 
270
        mapping = {
 
271
                # map GtkSourceView tags to colordiff names
 
272
                # since GSV is richer, accept new names for extra bits,
 
273
                # defaulting to old names if they're not present
 
274
                'Added@32@line': ['newtext'],
 
275
                'Removed@32@line': ['oldtext'],
 
276
                'Location': ['location', 'diffstuff'],
 
277
                'Diff@32@file': ['file', 'diffstuff'],
 
278
                'Special@32@case': ['specialcase', 'diffstuff'],
 
279
        }
 
280
 
 
281
        for tag in lang.get_tags():
 
282
            tag_id = tag.get_id()
 
283
            keys = mapping.get(tag_id, [])
 
284
            color = None
 
285
 
 
286
            for key in keys:
 
287
                color = colors.get(key, None)
 
288
                if color is not None:
 
289
                    break
 
290
 
 
291
            if color is None:
 
292
                continue
 
293
 
 
294
            style = gtksourceview.SourceTagStyle()
 
295
            try:
 
296
                style.foreground = gtk.gdk.color_parse(color)
 
297
            except ValueError:
 
298
                warning('not a valid color: %s' % color)
 
299
            else:
 
300
                lang.set_tag_style(tag_id, style)
 
301
 
 
302
    @staticmethod
 
303
    def parse_colordiffrc(fileobj):
 
304
        """Parse fileobj as a colordiff configuration file.
 
305
        
 
306
        :return: A dict with the key -> value pairs.
 
307
        """
 
308
        colors = {}
 
309
        for line in fileobj:
 
310
            if re.match(r'^\s*#', line):
 
311
                continue
 
312
            if '=' not in line:
 
313
                continue
 
314
            key, val = line.split('=', 1)
 
315
            colors[key.strip()] = val.strip()
 
316
        return colors
 
317