/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: Szilveszter Farkas
  • Date: 2009-05-27 09:40:13 UTC
  • mfrom: (635.3.4 sourceview2)
  • mto: This revision was merged to the branch mainline in revision 639.
  • Revision ID: szilveszter.farkas@gmail.com-20090527094013-h8uwips9hr8ybx4e
Merge GtkSourceView2 migration patch.

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
20
21
 
21
22
try:
22
 
    import gtksourceview
 
23
    import gtksourceview2
23
24
    have_gtksourceview = True
24
25
except ImportError:
25
26
    have_gtksourceview = False
63
64
        self.set_shadow_type(gtk.SHADOW_IN)
64
65
 
65
66
        if have_gtksourceview:
66
 
            self.buffer = gtksourceview.SourceBuffer()
67
 
            slm = gtksourceview.SourceLanguagesManager()
68
 
            gsl = slm.get_language_from_mime_type("text/x-patch")
 
67
            self.buffer = gtksourceview2.Buffer()
 
68
            slm = gtksourceview2.LanguageManager()
 
69
            gsl = slm.guess_language(content_type="text/x-patch")
69
70
            if have_gconf:
70
 
                self.apply_gedit_colors(gsl)
71
 
            self.apply_colordiff_colors(gsl)
 
71
                self.apply_gedit_colors(self.buffer)
 
72
            self.apply_colordiff_colors(self.buffer)
72
73
            self.buffer.set_language(gsl)
73
 
            self.buffer.set_highlight(True)
 
74
            self.buffer.set_highlight_syntax(True)
74
75
 
75
 
            self.sourceview = gtksourceview.SourceView(self.buffer)
 
76
            self.sourceview = gtksourceview2.View(self.buffer)
76
77
        else:
77
78
            self.buffer = gtk.TextBuffer()
78
79
            self.sourceview = gtk.TextView(self.buffer)
83
84
        self.sourceview.show()
84
85
 
85
86
    @staticmethod
86
 
    def apply_gedit_colors(lang):
87
 
        """Set style for lang to that specified in gedit configuration.
 
87
    def apply_gedit_colors(buf):
 
88
        """Set style to that specified in gedit configuration.
88
89
 
89
90
        This method needs the gconf module.
90
91
 
91
 
        :param lang: a gtksourceview.SourceLanguage object.
 
92
        :param buf: a gtksourceview2.Buffer object.
92
93
        """
93
 
        GEDIT_SYNTAX_PATH = '/apps/gedit-2/preferences/syntax_highlighting'
94
 
        GEDIT_LANG_PATH = GEDIT_SYNTAX_PATH + '/' + lang.get_id()
 
94
        GEDIT_SCHEME_PATH = '/apps/gedit-2/preferences/editor/colors/scheme'
95
95
 
96
96
        client = gconf.client_get_default()
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)
 
97
        style_scheme_name = client.get_string(GEDIT_SCHEME_PATH)
 
98
        style_scheme = gtksourceview2.StyleSchemeManager().get_scheme(style_scheme_name)
 
99
        
 
100
        buf.set_style_scheme(style_scheme)
147
101
 
148
102
    @classmethod
149
 
    def apply_colordiff_colors(klass, lang):
 
103
    def apply_colordiff_colors(klass, buf):
150
104
        """Set style colors for lang using the colordiff configuration file.
151
105
 
152
106
        Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
153
107
 
154
 
        :param lang: a "Diff" gtksourceview.SourceLanguage object.
 
108
        :param buf: a "Diff" gtksourceview2.Buffer object.
155
109
        """
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
 
110
        scheme_manager = gtksourceview2.StyleSchemeManager()
 
111
        style_scheme = scheme_manager.get_scheme('colordiff')
 
112
        
 
113
        # if style scheme not found, we'll generate it from colordiffrc
 
114
        # TODO: reload if colordiffrc has changed.
 
115
        if style_scheme is None:
 
116
            colors = {}
 
117
 
 
118
            for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
 
119
                f = os.path.expanduser(f)
 
120
                if os.path.exists(f):
 
121
                    try:
 
122
                        f = file(f)
 
123
                    except IOError, e:
 
124
                        warning('could not open file %s: %s' % (f, str(e)))
 
125
                    else:
 
126
                        colors.update(klass.parse_colordiffrc(f))
 
127
                        f.close()
 
128
 
 
129
            if not colors:
 
130
                # ~/.colordiffrc does not exist
 
131
                return
 
132
            
 
133
            mapping = {
 
134
                # map GtkSourceView2 scheme styles to colordiff names
175
135
                # since GSV is richer, accept new names for extra bits,
176
136
                # defaulting to old names if they're not present
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)
 
137
                'diff:added-line': ['newtext'],
 
138
                'diff:removed-line': ['oldtext'],
 
139
                'diff:location': ['location', 'diffstuff'],
 
140
                'diff:file': ['file', 'diffstuff'],
 
141
                'diff:special-case': ['specialcase', 'diffstuff'],
 
142
            }
 
143
            
 
144
            converted_colors = {}
 
145
            for name, values in mapping.items():
 
146
                color = None
 
147
                for value in values:
 
148
                    color = colors.get(value, None)
 
149
                    if color is not None:
 
150
                        break
 
151
                if color is None:
 
152
                    continue
 
153
                converted_colors[name] = color
 
154
            
 
155
            # some xml magic to produce needed style scheme description
 
156
            e_style_scheme = Element('style-scheme')
 
157
            e_style_scheme.set('id', 'colordiff')
 
158
            e_style_scheme.set('_name', 'ColorDiff')
 
159
            e_style_scheme.set('version', '1.0')
 
160
            for name, color in converted_colors.items():
 
161
                style = SubElement(e_style_scheme, 'style')
 
162
                style.set('name', name)
 
163
                style.set('foreground', '#%s' % color)
 
164
            
 
165
            scheme_xml = tostring(e_style_scheme, 'UTF-8')
 
166
            if not os.path.exists(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles')):
 
167
                os.makedirs(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles'))
 
168
            file(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles/colordiff.xml'), 'w').write(scheme_xml)
 
169
            
 
170
            scheme_manager.force_rescan()
 
171
            style_scheme = scheme_manager.get_scheme('colordiff')
 
172
        
 
173
        buf.set_style_scheme(style_scheme)
204
174
 
205
175
    @staticmethod
206
176
    def parse_colordiffrc(fileobj):