/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: Vincent Ladeuil
  • Date: 2009-05-06 11:51:38 UTC
  • mfrom: (628.1.2 gtk)
  • Revision ID: v.ladeuil+lp@free.fr-20090506115138-7abxvg2qz4gzraup
UpgradeĀ COMPATIBLE_BZR_VERSIONS

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
 
try:
21
 
    from xml.etree.ElementTree import Element, SubElement, tostring
22
 
except ImportError:
23
 
    from elementtree.ElementTree import Element, SubElement, tostring
24
20
 
25
21
try:
26
 
    import gtksourceview2
 
22
    import gtksourceview
27
23
    have_gtksourceview = True
28
24
except ImportError:
29
25
    have_gtksourceview = False
34
30
    have_gconf = False
35
31
 
36
32
from bzrlib import (
37
 
    errors,
38
33
    merge as _mod_merge,
39
34
    osutils,
 
35
    progress,
40
36
    urlutils,
41
37
    workingtree,
42
38
)
43
39
from bzrlib.diff import show_diff_trees, internal_diff
 
40
from bzrlib.errors import NoSuchFile
44
41
from bzrlib.patches import parse_patches
45
42
from bzrlib.trace import warning
46
43
from bzrlib.plugins.gtk import _i18n
48
45
from dialog import error_dialog, info_dialog, warning_dialog
49
46
 
50
47
 
51
 
def fallback_guess_language(slm, content_type):
52
 
    for lang_id in slm.get_language_ids():
53
 
        lang = slm.get_language(lang_id)
54
 
        if "text/x-patch" in lang.get_mime_types():
55
 
            return lang
56
 
    return None
57
 
 
58
 
 
59
48
class SelectCancelled(Exception):
60
49
 
61
50
    pass
74
63
        self.set_shadow_type(gtk.SHADOW_IN)
75
64
 
76
65
        if have_gtksourceview:
77
 
            self.buffer = gtksourceview2.Buffer()
78
 
            slm = gtksourceview2.LanguageManager()
79
 
            guess_language = getattr(gtksourceview2.LanguageManager, 
80
 
                "guess_language", fallback_guess_language)
81
 
            gsl = guess_language(slm, 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")
82
69
            if have_gconf:
83
 
                self.apply_gedit_colors(self.buffer)
84
 
            self.apply_colordiff_colors(self.buffer)
 
70
                self.apply_gedit_colors(gsl)
 
71
            self.apply_colordiff_colors(gsl)
85
72
            self.buffer.set_language(gsl)
86
 
            self.buffer.set_highlight_syntax(True)
 
73
            self.buffer.set_highlight(True)
87
74
 
88
 
            self.sourceview = gtksourceview2.View(self.buffer)
 
75
            self.sourceview = gtksourceview.SourceView(self.buffer)
89
76
        else:
90
77
            self.buffer = gtk.TextBuffer()
91
78
            self.sourceview = gtk.TextView(self.buffer)
96
83
        self.sourceview.show()
97
84
 
98
85
    @staticmethod
99
 
    def apply_gedit_colors(buf):
100
 
        """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.
101
88
 
102
89
        This method needs the gconf module.
103
90
 
104
 
        :param buf: a gtksourceview2.Buffer object.
 
91
        :param lang: a gtksourceview.SourceLanguage object.
105
92
        """
106
 
        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()
107
95
 
108
96
        client = gconf.client_get_default()
109
 
        style_scheme_name = client.get_string(GEDIT_SCHEME_PATH)
110
 
        if style_scheme_name is not None:
111
 
            style_scheme = gtksourceview2.StyleSchemeManager().get_scheme(style_scheme_name)
112
 
            
113
 
            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)
114
147
 
115
148
    @classmethod
116
 
    def apply_colordiff_colors(klass, buf):
 
149
    def apply_colordiff_colors(klass, lang):
117
150
        """Set style colors for lang using the colordiff configuration file.
118
151
 
119
152
        Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
120
153
 
121
 
        :param buf: a "Diff" gtksourceview2.Buffer object.
 
154
        :param lang: a "Diff" gtksourceview.SourceLanguage object.
122
155
        """
123
 
        scheme_manager = gtksourceview2.StyleSchemeManager()
124
 
        style_scheme = scheme_manager.get_scheme('colordiff')
125
 
        
126
 
        # if style scheme not found, we'll generate it from colordiffrc
127
 
        # TODO: reload if colordiffrc has changed.
128
 
        if style_scheme is None:
129
 
            colors = {}
130
 
 
131
 
            for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
132
 
                f = os.path.expanduser(f)
133
 
                if os.path.exists(f):
134
 
                    try:
135
 
                        f = file(f)
136
 
                    except IOError, e:
137
 
                        warning('could not open file %s: %s' % (f, str(e)))
138
 
                    else:
139
 
                        colors.update(klass.parse_colordiffrc(f))
140
 
                        f.close()
141
 
 
142
 
            if not colors:
143
 
                # ~/.colordiffrc does not exist
144
 
                return
145
 
            
146
 
            mapping = {
147
 
                # 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
148
175
                # since GSV is richer, accept new names for extra bits,
149
176
                # defaulting to old names if they're not present
150
 
                'diff:added-line': ['newtext'],
151
 
                'diff:removed-line': ['oldtext'],
152
 
                'diff:location': ['location', 'diffstuff'],
153
 
                'diff:file': ['file', 'diffstuff'],
154
 
                'diff:special-case': ['specialcase', 'diffstuff'],
155
 
            }
156
 
            
157
 
            converted_colors = {}
158
 
            for name, values in mapping.items():
159
 
                color = None
160
 
                for value in values:
161
 
                    color = colors.get(value, None)
162
 
                    if color is not None:
163
 
                        break
164
 
                if color is None:
165
 
                    continue
166
 
                converted_colors[name] = color
167
 
            
168
 
            # some xml magic to produce needed style scheme description
169
 
            e_style_scheme = Element('style-scheme')
170
 
            e_style_scheme.set('id', 'colordiff')
171
 
            e_style_scheme.set('_name', 'ColorDiff')
172
 
            e_style_scheme.set('version', '1.0')
173
 
            for name, color in converted_colors.items():
174
 
                style = SubElement(e_style_scheme, 'style')
175
 
                style.set('name', name)
176
 
                style.set('foreground', '#%s' % color)
177
 
            
178
 
            scheme_xml = tostring(e_style_scheme, 'UTF-8')
179
 
            if not os.path.exists(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles')):
180
 
                os.makedirs(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles'))
181
 
            file(os.path.expanduser('~/.local/share/gtksourceview-2.0/styles/colordiff.xml'), 'w').write(scheme_xml)
182
 
            
183
 
            scheme_manager.force_rescan()
184
 
            style_scheme = scheme_manager.get_scheme('colordiff')
185
 
        
186
 
        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)
187
204
 
188
205
    @staticmethod
189
206
    def parse_colordiffrc(fileobj):
375
392
                    tv_path = child.path
376
393
                    break
377
394
        if tv_path is None:
378
 
            raise errors.NoSuchFile(file_path)
 
395
            raise NoSuchFile(file_path)
379
396
        self.treeview.set_cursor(tv_path)
380
397
        self.treeview.scroll_to_cell(tv_path)
381
398
 
583
600
        tree.lock_write()
584
601
        try:
585
602
            try:
586
 
                if tree.has_changes():
587
 
                    raise errors.UncommittedChanges(tree)
588
 
                merger, verified = _mod_merge.Merger.from_mergeable(
589
 
                    tree, self.directive, pb=None)
 
603
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
604
                    self.directive, progress.DummyProgress())
 
605
                merger.check_basis(True)
590
606
                merger.merge_type = _mod_merge.Merge3Merger
591
607
                conflict_count = merger.do_merge()
592
608
                merger.set_pending()