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