/b-gtk/fix-viz

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/b-gtk/fix-viz
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
1
# -*- coding: UTF-8 -*-
2
"""Difference window.
3
4
This module contains the code to manage the diff window which shows
5
the changes made between two revisions on a branch.
6
"""
7
8
__copyright__ = "Copyright © 2005 Canonical Ltd."
9
__author__    = "Scott James Remnant <scott@ubuntu.com>"
10
11
12
from cStringIO import StringIO
13
252 by Aaron Bentley
Fix test suite
14
import pygtk
15
pygtk.require("2.0")
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
16
import gtk
17
import pango
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
18
import os
19
import re
76 by Jelmer Vernooij
Replace non-UTF8 characters rather than generating an exception (fixes #44677).
20
import sys
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
21
22
try:
23
    import gtksourceview
24
    have_gtksourceview = True
25
except ImportError:
26
    have_gtksourceview = False
232.1.3 by Adeodato Simó
Support setting diff colors from gedit's syntax highlighting config too.
27
try:
28
    import gconf
29
    have_gconf = True
30
except ImportError:
31
    have_gconf = False
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
32
428 by Aaron Bentley
Get merging working
33
from bzrlib import merge as _mod_merge, osutils, progress, workingtree
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
34
from bzrlib.diff import show_diff_trees, internal_diff
59.2.4 by Aaron Bentley
Teach gdiff to accept a single file argument
35
from bzrlib.errors import NoSuchFile
426 by Aaron Bentley
Start support for Merge Directives
36
from bzrlib.patches import parse_patches
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
37
from bzrlib.trace import warning
298.2.1 by Daniel Schierbeck
Refactored the GTK window code, creating a single base window class that handles keyboard events.
38
from bzrlib.plugins.gtk.window import Window
430 by Aaron Bentley
Handle conflicts appropriately
39
from dialog import error_dialog, info_dialog, warning_dialog
428 by Aaron Bentley
Get merging working
40
41
42
class SelectCancelled(Exception):
43
44
    pass
298.2.1 by Daniel Schierbeck
Refactored the GTK window code, creating a single base window class that handles keyboard events.
45
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
46
424 by Aaron Bentley
Add ghandle-patch
47
class DiffFileView(gtk.ScrolledWindow):
432 by Aaron Bentley
Misc updates
48
    """Window for displaying diffs from a diff file"""
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
49
51 by Jelmer Vernooij
Rework some of the parameters to DiffWindow.set_diff() to be
50
    def __init__(self):
278.1.4 by John Arbash Meinel
Just playing around.
51
        gtk.ScrolledWindow.__init__(self)
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
52
        self.construct()
424 by Aaron Bentley
Add ghandle-patch
53
        self._diffs = {}
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
54
55
    def construct(self):
278.1.4 by John Arbash Meinel
Just playing around.
56
        self.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
57
        self.set_shadow_type(gtk.SHADOW_IN)
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
58
59
        if have_gtksourceview:
60
            self.buffer = gtksourceview.SourceBuffer()
61
            slm = gtksourceview.SourceLanguagesManager()
62
            gsl = slm.get_language_from_mime_type("text/x-patch")
232.1.3 by Adeodato Simó
Support setting diff colors from gedit's syntax highlighting config too.
63
            if have_gconf:
64
                self.apply_gedit_colors(gsl)
232.1.2 by Adeodato Simó
Rename apply_colordiffrc to apply_colordiff_colors, improve docstring.
65
            self.apply_colordiff_colors(gsl)
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
66
            self.buffer.set_language(gsl)
67
            self.buffer.set_highlight(True)
68
69
            sourceview = gtksourceview.SourceView(self.buffer)
70
        else:
71
            self.buffer = gtk.TextBuffer()
72
            sourceview = gtk.TextView(self.buffer)
73
74
        sourceview.set_editable(False)
75
        sourceview.modify_font(pango.FontDescription("Monospace"))
278.1.4 by John Arbash Meinel
Just playing around.
76
        self.add(sourceview)
10 by Scott James Remnant
Add an extra window type, clicking the little icons next to a parent
77
        sourceview.show()
78
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
79
    @staticmethod
232.1.3 by Adeodato Simó
Support setting diff colors from gedit's syntax highlighting config too.
80
    def apply_gedit_colors(lang):
81
        """Set style for lang to that specified in gedit configuration.
82
83
        This method needs the gconf module.
278.1.4 by John Arbash Meinel
Just playing around.
84
232.1.3 by Adeodato Simó
Support setting diff colors from gedit's syntax highlighting config too.
85
        :param lang: a gtksourceview.SourceLanguage object.
86
        """
87
        GEDIT_SYNTAX_PATH = '/apps/gedit-2/preferences/syntax_highlighting'
88
        GEDIT_LANG_PATH = GEDIT_SYNTAX_PATH + '/' + lang.get_id()
89
90
        client = gconf.client_get_default()
91
        client.add_dir(GEDIT_LANG_PATH, gconf.CLIENT_PRELOAD_NONE)
92
93
        for tag in lang.get_tags():
94
            tag_id = tag.get_id()
95
            gconf_key = GEDIT_LANG_PATH + '/' + tag_id
96
            style_string = client.get_string(gconf_key)
97
98
            if style_string is None:
99
                continue
100
101
            # function to get a bool from a string that's either '0' or '1'
102
            string_bool = lambda x: bool(int(x))
103
104
            # style_string is a string like "2/#FFCCAA/#000000/0/1/0/0"
105
            # values are: mask, fg, bg, italic, bold, underline, strike
106
            # this packs them into (str_value, attr_name, conv_func) tuples
107
            items = zip(style_string.split('/'), ['mask', 'foreground',
108
                'background', 'italic', 'bold', 'underline', 'strikethrough' ],
109
                [ int, gtk.gdk.color_parse, gtk.gdk.color_parse, string_bool,
110
                    string_bool, string_bool, string_bool ]
111
            )
112
113
            style = gtksourceview.SourceTagStyle()
114
115
            # XXX The mask attribute controls whether the present values of
116
            # foreground and background color should in fact be used. Ideally
117
            # (and that's what gedit does), one could set all three attributes,
118
            # and let the TagStyle object figure out which colors to use.
119
            # However, in the GtkSourceview python bindings, the mask attribute
120
            # is read-only, and it's derived instead from the colors being
121
            # set or not. This means that we have to sometimes refrain from
122
            # setting fg or bg colors, depending on the value of the mask.
123
            # This code could go away if mask were writable.
124
            mask = int(items[0][0])
125
            if not (mask & 1): # GTK_SOURCE_TAG_STYLE_USE_BACKGROUND
126
                items[2:3] = []
127
            if not (mask & 2): # GTK_SOURCE_TAG_STYLE_USE_FOREGROUND
128
                items[1:2] = []
129
            items[0:1] = [] # skip the mask unconditionally
130
131
            for value, attr, func in items:
132
                try:
133
                    value = func(value)
134
                except ValueError:
135
                    warning('gconf key %s contains an invalid value: %s'
136
                            % gconf_key, value)
137
                else:
138
                    setattr(style, attr, value)
139
140
            lang.set_tag_style(tag_id, style)
141
424 by Aaron Bentley
Add ghandle-patch
142
    @classmethod
143
    def apply_colordiff_colors(klass, lang):
232.1.2 by Adeodato Simó
Rename apply_colordiffrc to apply_colordiff_colors, improve docstring.
144
        """Set style colors for lang using the colordiff configuration file.
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
145
146
        Both ~/.colordiffrc and ~/.colordiffrc.bzr-gtk are read.
147
232.1.2 by Adeodato Simó
Rename apply_colordiffrc to apply_colordiff_colors, improve docstring.
148
        :param lang: a "Diff" gtksourceview.SourceLanguage object.
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
149
        """
150
        colors = {}
151
152
        for f in ('~/.colordiffrc', '~/.colordiffrc.bzr-gtk'):
153
            f = os.path.expanduser(f)
154
            if os.path.exists(f):
155
                try:
156
                    f = file(f)
157
                except IOError, e:
158
                    warning('could not open file %s: %s' % (f, str(e)))
159
                else:
424 by Aaron Bentley
Add ghandle-patch
160
                    colors.update(klass.parse_colordiffrc(f))
232.1.1 by Adeodato Simó
Read ~/.colordiffrc to set colors in the diff window.
161
                    f.close()
162
163
        if not colors:
164
            # ~/.colordiffrc does not exist
165
            return
166
167
        mapping = {
168
                # map GtkSourceView tags to colordiff names
169
                # since GSV is richer, accept new names for extra bits,
170
                # defaulting to old names if they're not present
171
                'Added@32@line': ['newtext'],
172
                'Removed@32@line': ['oldtext'],
173
                'Location': ['location', 'diffstuff'],
174
                'Diff@32@file': ['file', 'diffstuff'],
175
                'Special@32@case': ['specialcase', 'diffstuff'],
176
        }
177
178
        for tag in lang.get_tags():
179
            tag_id = tag.get_id()
180
            keys = mapping.get(tag_id, [])
181
            color = None
182
183
            for key in keys:
184
                color = colors.get(key, None)
185
                if color is not None:
186
                    break
187
188
            if color is None:
189
                continue
190
191
            style = gtksourceview.SourceTagStyle()
192
            try:
193
                style.foreground = gtk.gdk.color_parse(color)
194
            except ValueError:
195
                warning('not a valid color: %s' % color)
196
            else:
197
                lang.set_tag_style(tag_id, style)
232.1.4 by Adeodato Simó
Add a test for parse_colordiffrc, and fix the function to handle empty lines.
198
199
    @staticmethod
200
    def parse_colordiffrc(fileobj):
201
        """Parse fileobj as a colordiff configuration file.
278.1.4 by John Arbash Meinel
Just playing around.
202
232.1.4 by Adeodato Simó
Add a test for parse_colordiffrc, and fix the function to handle empty lines.
203
        :return: A dict with the key -> value pairs.
204
        """
205
        colors = {}
206
        for line in fileobj:
207
            if re.match(r'^\s*#', line):
208
                continue
209
            if '=' not in line:
210
                continue
211
            key, val = line.split('=', 1)
212
            colors[key.strip()] = val.strip()
213
        return colors
214
278.1.4 by John Arbash Meinel
Just playing around.
215
    def set_trees(self, rev_tree, parent_tree):
216
        self.rev_tree = rev_tree
217
        self.parent_tree = parent_tree
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
218
#        self._build_delta()
219
220
#    def _build_delta(self):
221
#        self.parent_tree.lock_read()
222
#        self.rev_tree.lock_read()
223
#        try:
224
#            self.delta = _iter_changes_to_status(self.parent_tree, self.rev_tree)
225
#            self.path_to_status = {}
226
#            self.path_to_diff = {}
227
#            source_inv = self.parent_tree.inventory
228
#            target_inv = self.rev_tree.inventory
229
#            for (file_id, real_path, change_type, display_path) in self.delta:
230
#                self.path_to_status[real_path] = u'=== %s %s' % (change_type, display_path)
231
#                if change_type in ('modified', 'renamed and modified'):
232
#                    source_ie = source_inv[file_id]
233
#                    target_ie = target_inv[file_id]
234
#                    sio = StringIO()
235
#                    source_ie.diff(internal_diff, *old path, *old_tree,
236
#                                   *new_path, target_ie, self.rev_tree,
237
#                                   sio)
238
#                    self.path_to_diff[real_path] = 
239
#
240
#        finally:
241
#            self.rev_tree.unlock()
242
#            self.parent_tree.unlock()
278.1.4 by John Arbash Meinel
Just playing around.
243
244
    def show_diff(self, specific_files):
426 by Aaron Bentley
Start support for Merge Directives
245
        sections = []
246
        if specific_files is None:
247
            self.buffer.set_text(self._diffs[None])
248
        else:
249
            for specific_file in specific_files:
250
                sections.append(self._diffs[specific_file])
251
            self.buffer.set_text(''.join(sections))
424 by Aaron Bentley
Add ghandle-patch
252
253
254
class DiffView(DiffFileView):
255
    """This is the soft and chewy filling for a DiffWindow."""
256
257
    def __init__(self):
258
        DiffFileView.__init__(self)
259
        self.rev_tree = None
260
        self.parent_tree = None
261
262
    def show_diff(self, specific_files):
432 by Aaron Bentley
Misc updates
263
        """Show the diff for the specified files"""
278.1.4 by John Arbash Meinel
Just playing around.
264
        s = StringIO()
278.1.18 by John Arbash Meinel
Start checking the diff view is correct.
265
        show_diff_trees(self.parent_tree, self.rev_tree, s, specific_files,
266
                        old_label='', new_label='',
267
                        # path_encoding=sys.getdefaultencoding()
268
                        # The default is utf-8, but we interpret the file
269
                        # contents as getdefaultencoding(), so we should
270
                        # probably try to make the paths in the same encoding.
271
                        )
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
272
        # str.decode(encoding, 'replace') doesn't do anything. Because if a
273
        # character is not valid in 'encoding' there is nothing to replace, the
274
        # 'replace' is for 'str.encode()'
275
        try:
276
            decoded = s.getvalue().decode(sys.getdefaultencoding())
277
        except UnicodeDecodeError:
278
            try:
279
                decoded = s.getvalue().decode('UTF-8')
280
            except UnicodeDecodeError:
281
                decoded = s.getvalue().decode('iso-8859-1')
282
                # This always works, because every byte has a valid
283
                # mapping from iso-8859-1 to Unicode
284
        # TextBuffer must contain pure UTF-8 data
285
        self.buffer.set_text(decoded.encode('UTF-8'))
278.1.4 by John Arbash Meinel
Just playing around.
286
287
423.8.1 by Jelmer Vernooij
Allow using the diff control as a widget
288
class DiffWidget(gtk.HPaned):
289
    """Diff widget
278.1.4 by John Arbash Meinel
Just playing around.
290
291
    """
423.8.1 by Jelmer Vernooij
Allow using the diff control as a widget
292
    def __init__(self):
293
        super(DiffWidget, self).__init__()
278.1.4 by John Arbash Meinel
Just playing around.
294
295
        # The file hierarchy: a scrollable treeview
296
        scrollwin = gtk.ScrolledWindow()
297
        scrollwin.set_policy(gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
298
        scrollwin.set_shadow_type(gtk.SHADOW_IN)
423.8.1 by Jelmer Vernooij
Allow using the diff control as a widget
299
        self.pack1(scrollwin)
278.1.4 by John Arbash Meinel
Just playing around.
300
        scrollwin.show()
301
302
        self.model = gtk.TreeStore(str, str)
303
        self.treeview = gtk.TreeView(self.model)
304
        self.treeview.set_headers_visible(False)
305
        self.treeview.set_search_column(1)
306
        self.treeview.connect("cursor-changed", self._treeview_cursor_cb)
307
        scrollwin.add(self.treeview)
308
        self.treeview.show()
309
310
        cell = gtk.CellRendererText()
311
        cell.set_property("width-chars", 20)
312
        column = gtk.TreeViewColumn()
313
        column.pack_start(cell, expand=True)
314
        column.add_attribute(cell, "text", 0)
315
        self.treeview.append_column(column)
316
429 by Aaron Bentley
Merge from mainline
317
    def set_diff_text(self, lines):
432 by Aaron Bentley
Misc updates
318
        """Set the current diff from a list of lines
319
320
        :param lines: The diff to show, in unified diff format
321
        """
278.1.4 by John Arbash Meinel
Just playing around.
322
        # The diffs of the  selected file: a scrollable source or
323
        # text view
424 by Aaron Bentley
Add ghandle-patch
324
        self.diff_view = DiffFileView()
278.1.12 by John Arbash Meinel
Delay computing the delta, and clean up some of the diff view names.
325
        self.diff_view.show()
429 by Aaron Bentley
Merge from mainline
326
        self.pack2(self.diff_view)
424 by Aaron Bentley
Add ghandle-patch
327
        self.model.append(None, [ "Complete Diff", "" ])
426 by Aaron Bentley
Start support for Merge Directives
328
        self.diff_view._diffs[None] = ''.join(lines)
329
        for patch in parse_patches(lines):
330
            oldname = patch.oldname.split('\t')[0]
331
            newname = patch.newname.split('\t')[0]
332
            self.model.append(None, [oldname, newname])
333
            self.diff_view._diffs[newname] = str(patch)
427 by Aaron Bentley
Add merge button when displaying merge directives
334
        self.diff_view.show_diff(None)
278.1.4 by John Arbash Meinel
Just playing around.
335
429 by Aaron Bentley
Merge from mainline
336
    def set_diff(self, rev_tree, parent_tree):
278.1.4 by John Arbash Meinel
Just playing around.
337
        """Set the differences showed by this window.
338
339
        Compares the two trees and populates the window with the
340
        differences.
341
        """
424 by Aaron Bentley
Add ghandle-patch
342
        self.diff_view = DiffView()
423.8.1 by Jelmer Vernooij
Allow using the diff control as a widget
343
        self.pack2(self.diff_view)
424 by Aaron Bentley
Add ghandle-patch
344
        self.diff_view.show()
278.1.12 by John Arbash Meinel
Delay computing the delta, and clean up some of the diff view names.
345
        self.diff_view.set_trees(rev_tree, parent_tree)
278.1.4 by John Arbash Meinel
Just playing around.
346
        self.rev_tree = rev_tree
347
        self.parent_tree = parent_tree
348
349
        self.model.clear()
350
        delta = self.rev_tree.changes_from(self.parent_tree)
351
352
        self.model.append(None, [ "Complete Diff", "" ])
353
354
        if len(delta.added):
355
            titer = self.model.append(None, [ "Added", None ])
356
            for path, id, kind in delta.added:
357
                self.model.append(titer, [ path, path ])
358
359
        if len(delta.removed):
360
            titer = self.model.append(None, [ "Removed", None ])
361
            for path, id, kind in delta.removed:
362
                self.model.append(titer, [ path, path ])
363
364
        if len(delta.renamed):
365
            titer = self.model.append(None, [ "Renamed", None ])
366
            for oldpath, newpath, id, kind, text_modified, meta_modified \
367
                    in delta.renamed:
368
                self.model.append(titer, [ oldpath, newpath ])
369
370
        if len(delta.modified):
371
            titer = self.model.append(None, [ "Modified", None ])
372
            for path, id, kind, text_modified, meta_modified in delta.modified:
373
                self.model.append(titer, [ path, path ])
374
375
        self.treeview.expand_all()
376
377
    def set_file(self, file_path):
432 by Aaron Bentley
Misc updates
378
        """Select the current file to display"""
278.1.4 by John Arbash Meinel
Just playing around.
379
        tv_path = None
380
        for data in self.model:
381
            for child in data.iterchildren():
382
                if child[0] == file_path or child[1] == file_path:
383
                    tv_path = child.path
384
                    break
385
        if tv_path is None:
386
            raise NoSuchFile(file_path)
387
        self.treeview.set_cursor(tv_path)
388
        self.treeview.scroll_to_cell(tv_path)
389
390
    def _treeview_cursor_cb(self, *args):
391
        """Callback for when the treeview cursor changes."""
392
        (path, col) = self.treeview.get_cursor()
393
        specific_files = [ self.model[path][1] ]
394
        if specific_files == [ None ]:
395
            return
396
        elif specific_files == [ "" ]:
397
            specific_files = None
398
278.1.12 by John Arbash Meinel
Delay computing the delta, and clean up some of the diff view names.
399
        self.diff_view.show_diff(specific_files)
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
400
401
423.8.1 by Jelmer Vernooij
Allow using the diff control as a widget
402
class DiffWindow(Window):
403
    """Diff window.
404
405
    This object represents and manages a single window containing the
406
    differences between two revisions on a branch.
407
    """
408
409
    def __init__(self, parent=None):
410
        Window.__init__(self, parent)
411
        self.set_border_width(0)
412
        self.set_title("bzrk diff")
413
414
        # Use two thirds of the screen by default
415
        screen = self.get_screen()
416
        monitor = screen.get_monitor_geometry(0)
417
        width = int(monitor.width * 0.66)
418
        height = int(monitor.height * 0.66)
419
        self.set_default_size(width, height)
420
421
        self.construct()
422
423
    def construct(self):
424
        """Construct the window contents."""
429 by Aaron Bentley
Merge from mainline
425
        self.vbox = gtk.VBox()
426
        self.add(self.vbox)
427
        self.vbox.show()
428
        hbox = self._get_button_bar()
429
        if hbox is not None:
430
            self.vbox.pack_start(hbox, expand=False, fill=True)
423.8.1 by Jelmer Vernooij
Allow using the diff control as a widget
431
        self.diff = DiffWidget()
429 by Aaron Bentley
Merge from mainline
432
        self.vbox.add(self.diff)
423.8.1 by Jelmer Vernooij
Allow using the diff control as a widget
433
        self.diff.show_all()
434
429 by Aaron Bentley
Merge from mainline
435
    def _get_button_bar(self):
432 by Aaron Bentley
Misc updates
436
        """Return a button bar to use.
437
438
        :return: None, meaning that no button bar will be used.
439
        """
429 by Aaron Bentley
Merge from mainline
440
        return None
441
442
    def set_diff_text(self, description, lines):
432 by Aaron Bentley
Misc updates
443
        """Set the diff from a text.
444
445
        The diff must be in unified diff format, and will be parsed to
446
        determine filenames.
447
        """
429 by Aaron Bentley
Merge from mainline
448
        self.diff.set_diff_text(lines)
449
        self.set_title(description + " - bzrk diff")
450
423.8.1 by Jelmer Vernooij
Allow using the diff control as a widget
451
    def set_diff(self, description, rev_tree, parent_tree):
452
        """Set the differences showed by this window.
453
454
        Compares the two trees and populates the window with the
455
        differences.
456
        """
457
        self.diff.set_diff(rev_tree, parent_tree)
458
        self.set_title(description + " - bzrk diff")
459
460
    def set_file(self, file_path):
461
        self.diff.set_file(file_path)
462
463
427 by Aaron Bentley
Add merge button when displaying merge directives
464
class MergeDirectiveWindow(DiffWindow):
465
428 by Aaron Bentley
Get merging working
466
    def __init__(self, directive, parent=None):
467
        DiffWindow.__init__(self, parent)
468
        self._merge_target = None
469
        self.directive = directive
470
427 by Aaron Bentley
Add merge button when displaying merge directives
471
    def _get_button_bar(self):
432 by Aaron Bentley
Misc updates
472
        """The button bar has only the Merge button"""
427 by Aaron Bentley
Add merge button when displaying merge directives
473
        merge_button = gtk.Button('Merge')
474
        merge_button.show()
475
        merge_button.set_relief(gtk.RELIEF_NONE)
428 by Aaron Bentley
Get merging working
476
        merge_button.connect("clicked", self.perform_merge)
477
427 by Aaron Bentley
Add merge button when displaying merge directives
478
        hbox = gtk.HButtonBox()
479
        hbox.set_layout(gtk.BUTTONBOX_START)
480
        hbox.pack_start(merge_button, expand=False, fill=True)
481
        hbox.show()
482
        return hbox
483
428 by Aaron Bentley
Get merging working
484
    def perform_merge(self, window):
485
        try:
486
            tree = self._get_merge_target()
487
        except SelectCancelled:
488
            return
489
        tree.lock_write()
490
        try:
491
            try:
492
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
493
                    self.directive, progress.DummyProgress())
494
                merger.check_basis(True)
495
                merger.merge_type = _mod_merge.Merge3Merger
430 by Aaron Bentley
Handle conflicts appropriately
496
                conflict_count = merger.do_merge()
428 by Aaron Bentley
Get merging working
497
                merger.set_pending()
430 by Aaron Bentley
Handle conflicts appropriately
498
                if conflict_count == 0:
499
                    # No conflicts found.
500
                    info_dialog(_('Merge successful'),
501
                                _('All changes applied successfully.'))
502
                else:
503
                    # There are conflicts to be resolved.
504
                    warning_dialog(_('Conflicts encountered'),
505
                                   _('Please resolve the conflicts manually'
506
                                     ' before committing.'))
428 by Aaron Bentley
Get merging working
507
                self.destroy()
508
            except Exception, e:
509
                error_dialog('Error', str(e))
510
        finally:
511
            tree.unlock()
512
513
    def _get_merge_target(self):
514
        if self._merge_target is not None:
515
            return self._merge_target
516
        d = gtk.FileChooserDialog('Merge branch', self,
517
                                  gtk.FILE_CHOOSER_ACTION_SELECT_FOLDER,
518
                                  buttons=(gtk.STOCK_OK, gtk.RESPONSE_OK,
519
                                           gtk.STOCK_CANCEL,
520
                                           gtk.RESPONSE_CANCEL,))
521
        try:
522
            result = d.run()
432 by Aaron Bentley
Misc updates
523
            if result != gtk.RESPONSE_OK:
428 by Aaron Bentley
Get merging working
524
                raise SelectCancelled()
432 by Aaron Bentley
Misc updates
525
            uri = d.get_current_folder_uri()
428 by Aaron Bentley
Get merging working
526
        finally:
527
            d.destroy()
432 by Aaron Bentley
Misc updates
528
        return workingtree.WorkingTree.open(uri)
428 by Aaron Bentley
Get merging working
529
427 by Aaron Bentley
Add merge button when displaying merge directives
530
278.1.29 by John Arbash Meinel
Start testing with Unicode data.
531
def _iter_changes_to_status(source, target):
532
    """Determine the differences between trees.
533
534
    This is a wrapper around _iter_changes which just yields more
535
    understandable results.
536
537
    :param source: The source tree (basis tree)
538
    :param target: The target tree
539
    :return: A list of (file_id, real_path, change_type, display_path)
540
    """
541
    added = 'added'
542
    removed = 'removed'
543
    renamed = 'renamed'
544
    renamed_and_modified = 'renamed and modified'
545
    modified = 'modified'
546
    kind_changed = 'kind changed'
547
548
    # TODO: Handle metadata changes
549
550
    status = []
551
    target.lock_read()
552
    try:
553
        source.lock_read()
554
        try:
555
            for (file_id, paths, changed_content, versioned, parent_ids, names,
556
                 kinds, executables) in target._iter_changes(source):
557
558
                # Skip the root entry if it isn't very interesting
559
                if parent_ids == (None, None):
560
                    continue
561
562
                change_type = None
563
                if kinds[0] is None:
564
                    source_marker = ''
565
                else:
566
                    source_marker = osutils.kind_marker(kinds[0])
567
                if kinds[1] is None:
568
                    assert kinds[0] is not None
569
                    marker = osutils.kind_marker(kinds[0])
570
                else:
571
                    marker = osutils.kind_marker(kinds[1])
572
573
                real_path = paths[1]
574
                if real_path is None:
575
                    real_path = paths[0]
576
                assert real_path is not None
577
                display_path = real_path + marker
578
579
                present_source = versioned[0] and kinds[0] is not None
580
                present_target = versioned[1] and kinds[1] is not None
581
582
                if present_source != present_target:
583
                    if present_target:
584
                        change_type = added
585
                    else:
586
                        assert present_source
587
                        change_type = removed
588
                elif names[0] != names[1] or parent_ids[0] != parent_ids[1]:
589
                    # Renamed
590
                    if changed_content or executables[0] != executables[1]:
591
                        # and modified
592
                        change_type = renamed_and_modified
593
                    else:
594
                        change_type = renamed
595
                    display_path = (paths[0] + source_marker
596
                                    + ' => ' + paths[1] + marker)
597
                elif kinds[0] != kinds[1]:
598
                    change_type = kind_changed
599
                    display_path = (paths[0] + source_marker
600
                                    + ' => ' + paths[1] + marker)
601
                elif changed_content is True or executables[0] != executables[1]:
602
                    change_type = modified
603
                else:
604
                    assert False, "How did we get here?"
605
606
                status.append((file_id, real_path, change_type, display_path))
607
        finally:
608
            source.unlock()
609
    finally:
610
        target.unlock()
611
612
    return status