2
# -*- coding: UTF-8 -*-
5
This module contains the code to manage the diff window which shows
6
the changes made between two revisions on a branch.
9
__copyright__ = "Copyright © 2005 Canonical Ltd."
10
__author__ = "Scott James Remnant <scott@ubuntu.com>"
13
from cStringIO import StringIO
23
have_gtksourceview = True
25
have_gtksourceview = False
34
from bzrlib.diff import show_diff_trees
35
from bzrlib.errors import NoSuchFile
36
from bzrlib.trace import warning
39
class DiffWindow(gtk.Window):
42
This object represents and manages a single window containing the
43
differences between two revisions on a branch.
47
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
48
self.set_border_width(0)
49
self.set_title("bzrk diff")
51
# Use two thirds of the screen by default
52
screen = self.get_screen()
53
monitor = screen.get_monitor_geometry(0)
54
width = int(monitor.width * 0.66)
55
height = int(monitor.height * 0.66)
56
self.set_default_size(width, height)
61
"""Construct the window contents."""
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.
69
# The file hierarchy: a scrollable treeview
70
scrollwin = gtk.ScrolledWindow()
71
scrollwin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
72
scrollwin.set_shadow_type(gtk.SHADOW_IN)
76
self.model = gtk.TreeStore(str, str)
77
self.treeview = gtk.TreeView(self.model)
78
self.treeview.set_headers_visible(False)
79
self.treeview.set_search_column(1)
80
self.treeview.connect("cursor-changed", self._treeview_cursor_cb)
81
scrollwin.add(self.treeview)
84
cell = gtk.CellRendererText()
85
cell.set_property("width-chars", 20)
86
column = gtk.TreeViewColumn()
87
column.pack_start(cell, expand=True)
88
column.add_attribute(cell, "text", 0)
89
self.treeview.append_column(column)
91
# The diffs of the selected file: a scrollable source or
93
scrollwin = gtk.ScrolledWindow()
94
scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
95
scrollwin.set_shadow_type(gtk.SHADOW_IN)
99
if have_gtksourceview:
100
self.buffer = gtksourceview.SourceBuffer()
101
slm = gtksourceview.SourceLanguagesManager()
102
gsl = slm.get_language_from_mime_type("text/x-patch")
104
self.apply_gedit_colors(gsl)
105
self.apply_colordiff_colors(gsl)
106
self.buffer.set_language(gsl)
107
self.buffer.set_highlight(True)
109
sourceview = gtksourceview.SourceView(self.buffer)
111
self.buffer = gtk.TextBuffer()
112
sourceview = gtk.TextView(self.buffer)
114
sourceview.set_editable(False)
115
sourceview.modify_font(pango.FontDescription("Monospace"))
116
scrollwin.add(sourceview)
119
def set_diff(self, description, rev_tree, parent_tree):
120
"""Set the differences showed by this window.
122
Compares the two trees and populates the window with the
125
self.rev_tree = rev_tree
126
self.parent_tree = parent_tree
129
delta = self.rev_tree.changes_from(self.parent_tree)
131
self.model.append(None, [ "Complete Diff", "" ])
134
titer = self.model.append(None, [ "Added", None ])
135
for path, id, kind in delta.added:
136
self.model.append(titer, [ path, path ])
138
if len(delta.removed):
139
titer = self.model.append(None, [ "Removed", None ])
140
for path, id, kind in delta.removed:
141
self.model.append(titer, [ path, path ])
143
if len(delta.renamed):
144
titer = self.model.append(None, [ "Renamed", None ])
145
for oldpath, newpath, id, kind, text_modified, meta_modified \
147
self.model.append(titer, [ oldpath, newpath ])
149
if len(delta.modified):
150
titer = self.model.append(None, [ "Modified", None ])
151
for path, id, kind, text_modified, meta_modified in delta.modified:
152
self.model.append(titer, [ path, path ])
154
self.treeview.expand_all()
155
self.set_title(description + " - bzrk diff")
157
def set_file(self, file_path):
159
for data in self.model:
160
for child in data.iterchildren():
161
if child[0] == file_path or child[1] == file_path:
165
raise NoSuchFile(file_path)
166
self.treeview.set_cursor(tv_path)
167
self.treeview.scroll_to_cell(tv_path)
169
def _treeview_cursor_cb(self, *args):
170
"""Callback for when the treeview cursor changes."""
171
(path, col) = self.treeview.get_cursor()
172
specific_files = [ self.model[path][1] ]
173
if specific_files == [ None ]:
175
elif specific_files == [ "" ]:
179
show_diff_trees(self.parent_tree, self.rev_tree, s, specific_files)
180
self.buffer.set_text(s.getvalue().decode(sys.getdefaultencoding(), 'replace'))
183
def apply_gedit_colors(lang):
184
"""Set style for lang to that specified in gedit configuration.
186
This method needs the gconf module.
188
:param lang: a gtksourceview.SourceLanguage object.
190
GEDIT_SYNTAX_PATH = '/apps/gedit-2/preferences/syntax_highlighting'
191
GEDIT_LANG_PATH = GEDIT_SYNTAX_PATH + '/' + lang.get_id()
193
client = gconf.client_get_default()
194
client.add_dir(GEDIT_LANG_PATH, gconf.CLIENT_PRELOAD_NONE)
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)
201
if style_string is None:
204
# function to get a bool from a string that's either '0' or '1'
205
string_bool = lambda x: bool(int(x))
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 ]
216
style = gtksourceview.SourceTagStyle()
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
230
if not (mask & 2): # GTK_SOURCE_TAG_STYLE_USE_FOREGROUND
232
items[0:1] = [] # skip the mask unconditionally
234
for value, attr, func in items:
238
warning('gconf key %s contains an invalid value: %s'
241
setattr(style, attr, value)
243
lang.set_tag_style(tag_id, style)
246
def apply_colordiff_colors(lang):
247
"""Set style colors for lang using the colordiff configuration file.
249
Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
251
:param lang: a "Diff" gtksourceview.SourceLanguage object.
253
def parse_colordiffrc(fileobj):
254
"""Parse fileobj as a colordiff configuration file.
256
:return: A dict with the key -> value pairs.
260
if re.match(r'^\s*#', line):
262
key, val = line.split('=')
263
colors[key.strip()] = val.strip()
268
for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
269
f = os.path.expanduser(f)
270
if os.path.exists(f):
274
warning('could not open file %s: %s' % (f, str(e)))
276
colors.update(parse_colordiffrc(f))
280
# ~/.colordiffrc does not exist
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'],
294
for tag in lang.get_tags():
295
tag_id = tag.get_id()
296
keys = mapping.get(tag_id, [])
300
color = colors.get(key, None)
301
if color is not None:
307
style = gtksourceview.SourceTagStyle()
309
style.foreground = gtk.gdk.color_parse(color)
311
warning('not a valid color: %s' % color)
313
lang.set_tag_style(tag_id, style)