/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: Markus Korn
  • Date: 2009-03-05 16:50:39 UTC
  • mto: (635.2.4 trunk)
  • mto: This revision was merged to the branch mainline in revision 639.
  • Revision ID: thekorn@gmx.de-20090305165039-h6xh48wr9lwe1661
* register BranchSelectionBox() as a gobject type to fix (LP: #294396)

Show diffs side-by-side

added added

removed removed

Lines of Context:
17
17
import os
18
18
import re
19
19
import sys
20
 
from xml.etree.ElementTree import Element, SubElement, tostring
21
20
 
22
21
try:
23
 
    import gtksourceview2
 
22
    import gtksourceview
24
23
    have_gtksourceview = True
25
24
except ImportError:
26
25
    have_gtksourceview = False
64
63
        self.set_shadow_type(gtk.SHADOW_IN)
65
64
 
66
65
        if have_gtksourceview:
67
 
            self.buffer = gtksourceview2.Buffer()
68
 
            slm = gtksourceview2.LanguageManager()
69
 
            gsl = slm.guess_language(content_type="text/x-patch")
 
66
            self.buffer = gtksourceview.SourceBuffer()
 
67
            slm = gtksourceview.SourceLanguagesManager()
 
68
            gsl = slm.get_language_from_mime_type("text/x-patch")
70
69
            if have_gconf:
71
 
                self.apply_gedit_colors(self.buffer)
72
 
            self.apply_colordiff_colors(self.buffer)
 
70
                self.apply_gedit_colors(gsl)
 
71
            self.apply_colordiff_colors(gsl)
73
72
            self.buffer.set_language(gsl)
74
 
            self.buffer.set_highlight_syntax(True)
 
73
            self.buffer.set_highlight(True)
75
74
 
76
 
            self.sourceview = gtksourceview2.View(self.buffer)
 
75
            self.sourceview = gtksourceview.SourceView(self.buffer)
77
76
        else:
78
77
            self.buffer = gtk.TextBuffer()
79
78
            self.sourceview = gtk.TextView(self.buffer)
84
83
        self.sourceview.show()
85
84
 
86
85
    @staticmethod
87
 
    def apply_gedit_colors(buf):
88
 
        """Set style to that specified in gedit configuration.
 
86
    def apply_gedit_colors(lang):
 
87
        """Set style for lang to that specified in gedit configuration.
89
88
 
90
89
        This method needs the gconf module.
91
90
 
92
 
        :param buf: a gtksourceview2.Buffer object.
 
91
        :param lang: a gtksourceview.SourceLanguage object.
93
92
        """
94
 
        GEDIT_SCHEME_PATH = '/apps/gedit-2/preferences/editor/colors/scheme'
 
93
        GEDIT_SYNTAX_PATH = '/apps/gedit-2/preferences/syntax_highlighting'
 
94
        GEDIT_LANG_PATH = GEDIT_SYNTAX_PATH + '/' + lang.get_id()
95
95
 
96
96
        client = gconf.client_get_default()
97
 
        style_scheme_name = client.get_string(GEDIT_SCHEME_PATH)
98
 
        if style_scheme_name is not None:
99
 
            style_scheme = gtksourceview2.StyleSchemeManager().get_scheme(style_scheme_name)
100
 
            
101
 
            buf.set_style_scheme(style_scheme)
 
97
        client.add_dir(GEDIT_LANG_PATH, gconf.CLIENT_PRELOAD_NONE)
 
98
 
 
99
        for tag in lang.get_tags():
 
100
            tag_id = tag.get_id()
 
101
            gconf_key = GEDIT_LANG_PATH + '/' + tag_id
 
102
            style_string = client.get_string(gconf_key)
 
103
 
 
104
            if style_string is None:
 
105
                continue
 
106
 
 
107
            # function to get a bool from a string that's either '0' or '1'
 
108
            string_bool = lambda x: bool(int(x))
 
109
 
 
110
            # style_string is a string like "2/#FFCCAA/#000000/0/1/0/0"
 
111
            # values are: mask, fg, bg, italic, bold, underline, strike
 
112
            # this packs them into (str_value, attr_name, conv_func) tuples
 
113
            items = zip(style_string.split('/'), ['mask', 'foreground',
 
114
                'background', 'italic', 'bold', 'underline', 'strikethrough' ],
 
115
                [ int, gtk.gdk.color_parse, gtk.gdk.color_parse, string_bool,
 
116
                    string_bool, string_bool, string_bool ]
 
117
            )
 
118
 
 
119
            style = gtksourceview.SourceTagStyle()
 
120
 
 
121
            # XXX The mask attribute controls whether the present values of
 
122
            # foreground and background color should in fact be used. Ideally
 
123
            # (and that's what gedit does), one could set all three attributes,
 
124
            # and let the TagStyle object figure out which colors to use.
 
125
            # However, in the GtkSourceview python bindings, the mask attribute
 
126
            # is read-only, and it's derived instead from the colors being
 
127
            # set or not. This means that we have to sometimes refrain from
 
128
            # setting fg or bg colors, depending on the value of the mask.
 
129
            # This code could go away if mask were writable.
 
130
            mask = int(items[0][0])
 
131
            if not (mask & 1): # GTK_SOURCE_TAG_STYLE_USE_BACKGROUND
 
132
                items[2:3] = []
 
133
            if not (mask & 2): # GTK_SOURCE_TAG_STYLE_USE_FOREGROUND
 
134
                items[1:2] = []
 
135
            items[0:1] = [] # skip the mask unconditionally
 
136
 
 
137
            for value, attr, func in items:
 
138
                try:
 
139
                    value = func(value)
 
140
                except ValueError:
 
141
                    warning('gconf key %s contains an invalid value: %s'
 
142
                            % gconf_key, value)
 
143
                else:
 
144
                    setattr(style, attr, value)
 
145
 
 
146
            lang.set_tag_style(tag_id, style)
102
147
 
103
148
    @classmethod
104
 
    def apply_colordiff_colors(klass, buf):
 
149
    def apply_colordiff_colors(klass, lang):
105
150
        """Set style colors for lang using the colordiff configuration file.
106
151
 
107
152
        Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
108
153
 
109
 
        :param buf: a "Diff" gtksourceview2.Buffer object.
 
154
        :param lang: a "Diff" gtksourceview.SourceLanguage object.
110
155
        """
111
 
        scheme_manager = gtksourceview2.StyleSchemeManager()
112
 
        style_scheme = scheme_manager.get_scheme('colordiff')
113
 
        
114
 
        # if style scheme not found, we'll generate it from colordiffrc
115
 
        # TODO: reload if colordiffrc has changed.
116
 
        if style_scheme is None:
117
 
            colors = {}
118
 
 
119
 
            for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
120
 
                f = os.path.expanduser(f)
121
 
                if os.path.exists(f):
122
 
                    try:
123
 
                        f = file(f)
124
 
                    except IOError, e:
125
 
                        warning('could not open file %s: %s' % (f, str(e)))
126
 
                    else:
127
 
                        colors.update(klass.parse_colordiffrc(f))
128
 
                        f.close()
129
 
 
130
 
            if not colors:
131
 
                # ~/.colordiffrc does not exist
132
 
                return
133
 
            
134
 
            mapping = {
135
 
                # map GtkSourceView2 scheme styles to colordiff names
 
156
        colors = {}
 
157
 
 
158
        for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
 
159
            f = os.path.expanduser(f)
 
160
            if os.path.exists(f):
 
161
                try:
 
162
                    f = file(f)
 
163
                except IOError, e:
 
164
                    warning('could not open file %s: %s' % (f, str(e)))
 
165
                else:
 
166
                    colors.update(klass.parse_colordiffrc(f))
 
167
                    f.close()
 
168
 
 
169
        if not colors:
 
170
            # ~/.colordiffrc does not exist
 
171
            return
 
172
 
 
173
        mapping = {
 
174
                # map GtkSourceView tags to colordiff names
136
175
                # since GSV is richer, accept new names for extra bits,
137
176
                # defaulting to old names if they're not present
138
 
                'diff:added-line': ['newtext'],
139
 
                'diff:removed-line': ['oldtext'],
140
 
                'diff:location': ['location', 'diffstuff'],
141
 
                'diff:file': ['file', 'diffstuff'],
142
 
                'diff:special-case': ['specialcase', 'diffstuff'],
143
 
            }
144
 
            
145
 
            converted_colors = {}
146
 
            for name, values in mapping.items():
147
 
                color = None
148
 
                for value in values:
149
 
                    color = colors.get(value, None)
150
 
                    if color is not None:
151
 
                        break
152
 
                if color is None:
153
 
                    continue
154
 
                converted_colors[name] = color
155
 
            
156
 
            # some xml magic to produce needed style scheme description
157
 
            e_style_scheme = Element('style-scheme')
158
 
            e_style_scheme.set('id', 'colordiff')
159
 
            e_style_scheme.set('_name', 'ColorDiff')
160
 
            e_style_scheme.set('version', '1.0')
161
 
            for name, color in converted_colors.items():
162
 
                style = SubElement(e_style_scheme, 'style')
163
 
                style.set('name', name)
164
 
                style.set('foreground', '#%s' % color)
165
 
            
166
 
            scheme_xml = tostring(e_style_scheme, 'UTF-8')
167
 
            if not os.path.exists(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles')):
168
 
                os.makedirs(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles'))
169
 
            file(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles/colordiff.xml'), 'w').write(scheme_xml)
170
 
            
171
 
            scheme_manager.force_rescan()
172
 
            style_scheme = scheme_manager.get_scheme('colordiff')
173
 
        
174
 
        buf.set_style_scheme(style_scheme)
 
177
                'Added@32@line': ['newtext'],
 
178
                'Removed@32@line': ['oldtext'],
 
179
                'Location': ['location', 'diffstuff'],
 
180
                'Diff@32@file': ['file', 'diffstuff'],
 
181
                'Special@32@case': ['specialcase', 'diffstuff'],
 
182
        }
 
183
 
 
184
        for tag in lang.get_tags():
 
185
            tag_id = tag.get_id()
 
186
            keys = mapping.get(tag_id, [])
 
187
            color = None
 
188
 
 
189
            for key in keys:
 
190
                color = colors.get(key, None)
 
191
                if color is not None:
 
192
                    break
 
193
 
 
194
            if color is None:
 
195
                continue
 
196
 
 
197
            style = gtksourceview.SourceTagStyle()
 
198
            try:
 
199
                style.foreground = gtk.gdk.color_parse(color)
 
200
            except ValueError:
 
201
                warning('not a valid color: %s' % color)
 
202
            else:
 
203
                lang.set_tag_style(tag_id, style)
175
204
 
176
205
    @staticmethod
177
206
    def parse_colordiffrc(fileobj):