1
# -*- coding: UTF-8 -*-
4
This module contains the code to manage the diff window which shows
5
the changes made between two revisions on a branch.
8
__copyright__ = "Copyright © 2005 Canonical Ltd."
9
__author__ = "Scott James Remnant <scott@ubuntu.com>"
12
from cStringIO import StringIO
24
have_gtksourceview = True
26
have_gtksourceview = False
35
from bzrlib.diff import show_diff_trees
36
from bzrlib.errors import NoSuchFile
37
from bzrlib.trace import warning
40
class DiffWindow(gtk.Window):
43
This object represents and manages a single window containing the
44
differences between two revisions on a branch.
47
def __init__(self, parent=None):
48
gtk.Window.__init__(self, gtk.WINDOW_TOPLEVEL)
49
self.set_border_width(0)
50
self.set_title("bzrk diff")
52
# Use two thirds of the screen by default
53
screen = self.get_screen()
54
monitor = screen.get_monitor_geometry(0)
55
width = int(monitor.width * 0.66)
56
height = int(monitor.height * 0.66)
57
self.set_default_size(width, height)
60
self.connect('key-press-event', self._on_key_pressed)
62
self.connect('delete-event', gtk.main_quit)
67
"""Construct the window contents."""
68
# The window consists of a pane containing: the
69
# hierarchical list of files on the left, and the diff
70
# for the currently selected file on the right.
75
# The file hierarchy: a scrollable treeview
76
scrollwin = gtk.ScrolledWindow()
77
scrollwin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
78
scrollwin.set_shadow_type(gtk.SHADOW_IN)
82
self.model = gtk.TreeStore(str, str)
83
self.treeview = gtk.TreeView(self.model)
84
self.treeview.set_headers_visible(False)
85
self.treeview.set_search_column(1)
86
self.treeview.connect("cursor-changed", self._treeview_cursor_cb)
87
scrollwin.add(self.treeview)
90
cell = gtk.CellRendererText()
91
cell.set_property("width-chars", 20)
92
column = gtk.TreeViewColumn()
93
column.pack_start(cell, expand=True)
94
column.add_attribute(cell, "text", 0)
95
self.treeview.append_column(column)
97
# The diffs of the selected file: a scrollable source or
99
scrollwin = gtk.ScrolledWindow()
100
scrollwin.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
101
scrollwin.set_shadow_type(gtk.SHADOW_IN)
102
pane.pack2(scrollwin)
105
if have_gtksourceview:
106
self.buffer = gtksourceview.SourceBuffer()
107
slm = gtksourceview.SourceLanguagesManager()
108
gsl = slm.get_language_from_mime_type("text/x-patch")
110
self.apply_gedit_colors(gsl)
111
self.apply_colordiff_colors(gsl)
112
self.buffer.set_language(gsl)
113
self.buffer.set_highlight(True)
115
sourceview = gtksourceview.SourceView(self.buffer)
117
self.buffer = gtk.TextBuffer()
118
sourceview = gtk.TextView(self.buffer)
120
sourceview.set_editable(False)
121
sourceview.modify_font(pango.FontDescription("Monospace"))
122
scrollwin.add(sourceview)
125
def set_diff(self, description, rev_tree, parent_tree):
126
"""Set the differences showed by this window.
128
Compares the two trees and populates the window with the
131
self.rev_tree = rev_tree
132
self.parent_tree = parent_tree
135
delta = self.rev_tree.changes_from(self.parent_tree)
137
self.model.append(None, [ "Complete Diff", "" ])
140
titer = self.model.append(None, [ "Added", None ])
141
for path, id, kind in delta.added:
142
self.model.append(titer, [ path, path ])
144
if len(delta.removed):
145
titer = self.model.append(None, [ "Removed", None ])
146
for path, id, kind in delta.removed:
147
self.model.append(titer, [ path, path ])
149
if len(delta.renamed):
150
titer = self.model.append(None, [ "Renamed", None ])
151
for oldpath, newpath, id, kind, text_modified, meta_modified \
153
self.model.append(titer, [ oldpath, newpath ])
155
if len(delta.modified):
156
titer = self.model.append(None, [ "Modified", None ])
157
for path, id, kind, text_modified, meta_modified in delta.modified:
158
self.model.append(titer, [ path, path ])
160
self.treeview.expand_all()
161
self.set_title(description + " - bzrk diff")
163
def set_file(self, file_path):
165
for data in self.model:
166
for child in data.iterchildren():
167
if child[0] == file_path or child[1] == file_path:
171
raise NoSuchFile(file_path)
172
self.treeview.set_cursor(tv_path)
173
self.treeview.scroll_to_cell(tv_path)
175
def _treeview_cursor_cb(self, *args):
176
"""Callback for when the treeview cursor changes."""
177
(path, col) = self.treeview.get_cursor()
178
specific_files = [ self.model[path][1] ]
179
if specific_files == [ None ]:
181
elif specific_files == [ "" ]:
182
specific_files = None
185
show_diff_trees(self.parent_tree, self.rev_tree, s, specific_files)
186
self.buffer.set_text(s.getvalue().decode(sys.getdefaultencoding(), 'replace'))
189
def apply_gedit_colors(lang):
190
"""Set style for lang to that specified in gedit configuration.
192
This method needs the gconf module.
194
:param lang: a gtksourceview.SourceLanguage object.
196
GEDIT_SYNTAX_PATH = '/apps/gedit-2/preferences/syntax_highlighting'
197
GEDIT_LANG_PATH = GEDIT_SYNTAX_PATH + '/' + lang.get_id()
199
client = gconf.client_get_default()
200
client.add_dir(GEDIT_LANG_PATH, gconf.CLIENT_PRELOAD_NONE)
202
for tag in lang.get_tags():
203
tag_id = tag.get_id()
204
gconf_key = GEDIT_LANG_PATH + '/' + tag_id
205
style_string = client.get_string(gconf_key)
207
if style_string is None:
210
# function to get a bool from a string that's either '0' or '1'
211
string_bool = lambda x: bool(int(x))
213
# style_string is a string like "2/#FFCCAA/#000000/0/1/0/0"
214
# values are: mask, fg, bg, italic, bold, underline, strike
215
# this packs them into (str_value, attr_name, conv_func) tuples
216
items = zip(style_string.split('/'), ['mask', 'foreground',
217
'background', 'italic', 'bold', 'underline', 'strikethrough' ],
218
[ int, gtk.gdk.color_parse, gtk.gdk.color_parse, string_bool,
219
string_bool, string_bool, string_bool ]
222
style = gtksourceview.SourceTagStyle()
224
# XXX The mask attribute controls whether the present values of
225
# foreground and background color should in fact be used. Ideally
226
# (and that's what gedit does), one could set all three attributes,
227
# and let the TagStyle object figure out which colors to use.
228
# However, in the GtkSourceview python bindings, the mask attribute
229
# is read-only, and it's derived instead from the colors being
230
# set or not. This means that we have to sometimes refrain from
231
# setting fg or bg colors, depending on the value of the mask.
232
# This code could go away if mask were writable.
233
mask = int(items[0][0])
234
if not (mask & 1): # GTK_SOURCE_TAG_STYLE_USE_BACKGROUND
236
if not (mask & 2): # GTK_SOURCE_TAG_STYLE_USE_FOREGROUND
238
items[0:1] = [] # skip the mask unconditionally
240
for value, attr, func in items:
244
warning('gconf key %s contains an invalid value: %s'
247
setattr(style, attr, value)
249
lang.set_tag_style(tag_id, style)
252
def apply_colordiff_colors(lang):
253
"""Set style colors for lang using the colordiff configuration file.
255
Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
257
:param lang: a "Diff" gtksourceview.SourceLanguage object.
261
for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
262
f = os.path.expanduser(f)
263
if os.path.exists(f):
267
warning('could not open file %s: %s' % (f, str(e)))
269
colors.update(DiffWindow.parse_colordiffrc(f))
273
# ~/.colordiffrc does not exist
277
# map GtkSourceView tags to colordiff names
278
# since GSV is richer, accept new names for extra bits,
279
# defaulting to old names if they're not present
280
'Added@32@line': ['newtext'],
281
'Removed@32@line': ['oldtext'],
282
'Location': ['location', 'diffstuff'],
283
'Diff@32@file': ['file', 'diffstuff'],
284
'Special@32@case': ['specialcase', 'diffstuff'],
287
for tag in lang.get_tags():
288
tag_id = tag.get_id()
289
keys = mapping.get(tag_id, [])
293
color = colors.get(key, None)
294
if color is not None:
300
style = gtksourceview.SourceTagStyle()
302
style.foreground = gtk.gdk.color_parse(color)
304
warning('not a valid color: %s' % color)
306
lang.set_tag_style(tag_id, style)
309
def parse_colordiffrc(fileobj):
310
"""Parse fileobj as a colordiff configuration file.
312
:return: A dict with the key -> value pairs.
316
if re.match(r'^\s*#', line):
320
key, val = line.split('=', 1)
321
colors[key.strip()] = val.strip()
324
def _on_key_pressed(self, widget, event):
325
""" Key press event handler. """
326
keyname = gtk.gdk.keyval_name(event.keyval)
327
func = getattr(self, '_on_key_press_' + keyname, None)
331
def _on_key_press_w(self, event):
332
if event.state & gtk.gdk.CONTROL_MASK:
334
if self._parent is None:
337
def _on_key_press_q(self, event):
338
if event.state & gtk.gdk.CONTROL_MASK: