/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 __init__.py

  • Committer: Jelmer Vernooij
  • Author(s): Kiddo
  • Date: 2007-11-28 18:00:03 UTC
  • mto: This revision was merged to the branch mainline in revision 410.
  • Revision ID: jelmer@samba.org-20071128180003-oq0m5cfuab52ekk1
Make toolbars follow GNOME standards.

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
"""Graphical support for Bazaar using GTK.
16
16
 
17
17
This plugin includes:
18
 
gannotate         GTK+ annotate.
19
 
gbranch           GTK+ branching.
20
 
gcheckout         GTK+ checkout.
 
18
commit-notify     Start the graphical notifier of commits.
 
19
gannotate         GTK+ annotate. 
 
20
gbranch           GTK+ branching. 
 
21
gcheckout         GTK+ checkout. 
21
22
gcommit           GTK+ commit dialog.
22
 
gconflicts        GTK+ conflicts.
23
 
gdiff             Show differences in working tree in a GTK+ Window.
 
23
gconflicts        GTK+ conflicts. 
 
24
gdiff             Show differences in working tree in a GTK+ Window. 
24
25
ginit             Initialise a new branch.
25
 
gloom             GTK+ loom browse dialog
26
 
gmerge            GTK+ merge dialog
27
 
gmissing          GTK+ missing revisions dialog.
28
 
gpreferences      GTK+ preferences dialog.
 
26
gmissing          GTK+ missing revisions dialog. 
 
27
gpreferences      GTK+ preferences dialog. 
29
28
gpush             GTK+ push.
30
29
gsend             GTK+ send merge directive.
31
30
gstatus           GTK+ status dialog.
32
31
gtags             Manage branch tags.
33
 
visualise         Graphically visualise this branch.
 
32
visualise         Graphically visualise this branch. 
34
33
"""
35
34
 
36
 
from __future__ import absolute_import
37
 
 
38
 
import os
39
35
import sys
40
36
 
41
 
if getattr(sys, "frozen", None) is not None: # we run bzr.exe
42
 
 
43
 
    # FIXME: Unless a better packaging solution is found, the following
44
 
    # provides a workaround for https://bugs.launchpad.net/bzr/+bug/388790 Also
45
 
    # see https://code.edge.launchpad.net/~vila/bzr-gtk/388790-windows-setup
46
 
    # for more details about while it's needed.
47
 
 
48
 
    # NOTE: _lib must be ahead of bzrlib or sax.saxutils (in olive) fails
49
 
    here = os.path.dirname(__file__)
50
 
    sys.path.insert(0, os.path.join(here, '_lib'))
51
 
    sys.path.append(os.path.join(here, '_lib/gtk-2.0'))
52
 
 
53
 
 
54
37
import bzrlib
55
 
import bzrlib.api
56
 
from bzrlib.commands import plugin_cmds
57
38
 
58
 
from bzrlib.plugins.gtk.info import (
59
 
    bzr_plugin_version as version_info,
60
 
    bzr_compatible_versions,
61
 
    )
 
39
version_info = (0, 93, 0, 'dev', 0)
62
40
 
63
41
if version_info[3] == 'final':
64
42
    version_string = '%d.%d.%d' % version_info[:3]
66
44
    version_string = '%d.%d.%d%s%d' % version_info
67
45
__version__ = version_string
68
46
 
69
 
bzrlib.api.require_any_api(bzrlib, bzr_compatible_versions)
70
 
 
 
47
def check_bzrlib_version(desired):
 
48
    """Check that bzrlib is compatible.
 
49
 
 
50
    If version is < bzr-gtk version, assume incompatible.
 
51
    If version == bzr-gtk version, assume completely compatible
 
52
    If version == bzr-gtk version + 1, assume compatible, with deprecations
 
53
    Otherwise, assume incompatible.
 
54
    """
 
55
    desired_plus = (desired[0], desired[1]+1)
 
56
    bzrlib_version = bzrlib.version_info[:2]
 
57
    if bzrlib_version == desired or (bzrlib_version == desired_plus and
 
58
                                     bzrlib.version_info[3] == 'dev'):
 
59
        return
 
60
    try:
 
61
        from bzrlib.trace import warning
 
62
    except ImportError:
 
63
        # get the message out any way we can
 
64
        from warnings import warn as warning
 
65
    if bzrlib_version < desired:
 
66
        from bzrlib.errors import BzrError
 
67
        warning('Installed Bazaar version %s is too old to be used with bzr-gtk'
 
68
                ' %s.' % (bzrlib.__version__, __version__))
 
69
        raise BzrError('Version mismatch: %r, %r' % (version_info, bzrlib.version_info) )
 
70
    else:
 
71
        warning('bzr-gtk is not up to date with installed bzr version %s.'
 
72
                ' \nThere should be a newer version available, e.g. %i.%i.' 
 
73
                % (bzrlib.__version__, bzrlib_version[0], bzrlib_version[1]))
 
74
 
 
75
 
 
76
if version_info[2] == "final":
 
77
    check_bzrlib_version(version_info[:2])
 
78
 
 
79
from bzrlib.trace import warning
71
80
if __name__ != 'bzrlib.plugins.gtk':
72
 
    from bzrlib.trace import warning
73
81
    warning("Not running as bzrlib.plugins.gtk, things may break.")
74
82
 
 
83
from bzrlib.lazy_import import lazy_import
 
84
lazy_import(globals(), """
 
85
from bzrlib import (
 
86
    branch,
 
87
    builtins,
 
88
    errors,
 
89
    workingtree,
 
90
    )
 
91
""")
 
92
 
 
93
from bzrlib.commands import Command, register_command, display_command
 
94
from bzrlib.errors import NotVersionedError, BzrCommandError, NoSuchFile
 
95
from bzrlib.option import Option
 
96
 
 
97
import os.path
 
98
 
 
99
def import_pygtk():
 
100
    try:
 
101
        import pygtk
 
102
    except ImportError:
 
103
        raise errors.BzrCommandError("PyGTK not installed.")
 
104
    pygtk.require('2.0')
 
105
    return pygtk
 
106
 
75
107
 
76
108
def set_ui_factory():
77
 
    from bzrlib.plugins.gtk.ui import GtkUIFactory
 
109
    import_pygtk()
 
110
    from ui import GtkUIFactory
78
111
    import bzrlib.ui
79
112
    bzrlib.ui.ui_factory = GtkUIFactory()
80
113
 
81
114
 
82
 
def data_basedirs():
83
 
    return [os.path.dirname(__file__),
84
 
             "/usr/share/bzr-gtk", 
85
 
             "/usr/local/share/bzr-gtk"]
86
 
 
87
 
 
88
 
def data_path(*args):
89
 
    for basedir in data_basedirs():
90
 
        path = os.path.join(basedir, *args)
91
 
        if os.path.exists(path):
92
 
            return path
93
 
    return None
94
 
 
95
 
 
96
 
def icon_path(*args):
97
 
    return data_path(os.path.join('icons', *args))
98
 
 
99
 
 
100
 
commands = {
101
 
    "gannotate": ["gblame", "gpraise"],
102
 
    "gbranch": [],
103
 
    "gcheckout": [],
104
 
    "gcommit": ["gci"],
105
 
    "gconflicts": [],
106
 
    "gdiff": [],
107
 
    "ginit": [],
108
 
    "gmerge": [],
109
 
    "gmissing": [],
110
 
    "gpreferences": [],
111
 
    "gpush": [],
112
 
    "gsend": [],
113
 
    "gstatus": ["gst"],
114
 
    "gtags": [],
115
 
    "visualise": ["visualize", "vis", "viz", 'glog'],
116
 
    }
117
 
 
118
 
try:
119
 
    from bzrlib.plugins import loom
120
 
except ImportError:
121
 
    pass # Loom plugin doesn't appear to be present
122
 
else:
123
 
    commands["gloom"] = []
124
 
 
125
 
for cmd, aliases in commands.iteritems():
126
 
    plugin_cmds.register_lazy("cmd_%s" % cmd, aliases,
127
 
                              "bzrlib.plugins.gtk.commands")
128
 
 
129
 
def save_commit_messages(*args):
130
 
    from bzrlib.plugins.gtk import commitmsgs
131
 
    commitmsgs.save_commit_messages(*args)
132
 
 
133
 
try:
134
 
    from bzrlib.hooks import install_lazy_named_hook
135
 
except ImportError:
136
 
    from bzrlib.branch import Branch
137
 
    Branch.hooks.install_named_hook('post_uncommit',
138
 
                                    save_commit_messages,
139
 
                                    "Saving commit messages for gcommit")
140
 
else:
141
 
    install_lazy_named_hook("bzrlib.branch", "Branch.hooks",
142
 
        'post_uncommit', save_commit_messages, "Saving commit messages for gcommit")
143
 
 
144
 
try:
145
 
    from bzrlib.registry import register_lazy
146
 
except ImportError:
147
 
    from bzrlib import config
148
 
    option_registry = getattr(config, "option_registry", None)
149
 
    if option_registry is not None:
150
 
        config.option_registry.register_lazy('nautilus_integration',
151
 
                'bzrlib.plugins.gtk.config', 'opt_nautilus_integration')
152
 
else:
153
 
    register_lazy("bzrlib.config", "option_registry",
154
 
        'nautilus_integration', 'bzrlib.plugins.gtk.config',
155
 
        'opt_nautilus_integration')
156
 
 
157
 
 
158
 
def load_tests(basic_tests, module, loader):
159
 
    testmod_names = [
160
 
        'tests',
161
 
        ]
 
115
def data_path():
 
116
    return os.path.dirname(__file__)
 
117
 
 
118
 
 
119
class GTKCommand(Command):
 
120
    """Abstract class providing GTK specific run commands."""
 
121
 
 
122
    def open_display(self):
 
123
        pygtk = import_pygtk()
 
124
        try:
 
125
            import gtk
 
126
        except RuntimeError, e:
 
127
            if str(e) == "could not open display":
 
128
                raise NoDisplayError
 
129
        set_ui_factory()
 
130
        return gtk
 
131
 
 
132
    def run(self):
 
133
        self.open_display()
 
134
        dialog = self.get_gtk_dialog(os.path.abspath('.'))
 
135
        dialog.run()
 
136
 
 
137
 
 
138
class cmd_gbranch(GTKCommand):
 
139
    """GTK+ branching.
 
140
    
 
141
    """
 
142
 
 
143
    def get_gtk_dialog(self, path):
 
144
        from bzrlib.plugins.gtk.branch import BranchDialog
 
145
        return BranchDialog(path)
 
146
 
 
147
 
 
148
class cmd_gcheckout(GTKCommand):
 
149
    """ GTK+ checkout.
 
150
    
 
151
    """
 
152
    
 
153
    def get_gtk_dialog(self, path):
 
154
        from bzrlib.plugins.gtk.checkout import CheckoutDialog
 
155
        return CheckoutDialog(path)
 
156
 
 
157
 
 
158
 
 
159
class cmd_gpush(GTKCommand):
 
160
    """ GTK+ push.
 
161
    
 
162
    """
 
163
    takes_args = [ "location?" ]
 
164
 
 
165
    def run(self, location="."):
 
166
        (br, path) = branch.Branch.open_containing(location)
 
167
        self.open_display()
 
168
        from push import PushDialog
 
169
        dialog = PushDialog(br.repository, br.last_revision(), br)
 
170
        dialog.run()
 
171
 
 
172
 
 
173
 
 
174
class cmd_gdiff(GTKCommand):
 
175
    """Show differences in working tree in a GTK+ Window.
 
176
    
 
177
    Otherwise, all changes for the tree are listed.
 
178
    """
 
179
    takes_args = ['filename?']
 
180
    takes_options = ['revision']
 
181
 
 
182
    @display_command
 
183
    def run(self, revision=None, filename=None):
 
184
        set_ui_factory()
 
185
        wt = workingtree.WorkingTree.open_containing(".")[0]
 
186
        wt.lock_read()
 
187
        try:
 
188
            branch = wt.branch
 
189
            if revision is not None:
 
190
                if len(revision) == 1:
 
191
                    tree1 = wt
 
192
                    revision_id = revision[0].in_history(branch).rev_id
 
193
                    tree2 = branch.repository.revision_tree(revision_id)
 
194
                elif len(revision) == 2:
 
195
                    revision_id_0 = revision[0].in_history(branch).rev_id
 
196
                    tree2 = branch.repository.revision_tree(revision_id_0)
 
197
                    revision_id_1 = revision[1].in_history(branch).rev_id
 
198
                    tree1 = branch.repository.revision_tree(revision_id_1)
 
199
            else:
 
200
                tree1 = wt
 
201
                tree2 = tree1.basis_tree()
 
202
 
 
203
            from diff import DiffWindow
 
204
            import gtk
 
205
            window = DiffWindow()
 
206
            window.connect("destroy", gtk.main_quit)
 
207
            window.set_diff("Working Tree", tree1, tree2)
 
208
            if filename is not None:
 
209
                tree_filename = wt.relpath(filename)
 
210
                try:
 
211
                    window.set_file(tree_filename)
 
212
                except NoSuchFile:
 
213
                    if (tree1.path2id(tree_filename) is None and 
 
214
                        tree2.path2id(tree_filename) is None):
 
215
                        raise NotVersionedError(filename)
 
216
                    raise BzrCommandError('No changes found for file "%s"' % 
 
217
                                          filename)
 
218
            window.show()
 
219
 
 
220
            gtk.main()
 
221
        finally:
 
222
            wt.unlock()
 
223
 
 
224
 
 
225
def start_viz_window(branch, revision, limit=None):
 
226
    """Start viz on branch with revision revision.
 
227
    
 
228
    :return: The viz window object.
 
229
    """
 
230
    from viz.branchwin import BranchWindow
 
231
    return BranchWindow(branch, revision, limit)
 
232
 
 
233
 
 
234
class cmd_visualise(Command):
 
235
    """Graphically visualise this branch.
 
236
 
 
237
    Opens a graphical window to allow you to see the history of the branch
 
238
    and relationships between revisions in a visual manner,
 
239
 
 
240
    The default starting point is latest revision on the branch, you can
 
241
    specify a starting point with -r revision.
 
242
    """
 
243
    takes_options = [
 
244
        "revision",
 
245
        Option('limit', "Maximum number of revisions to display.",
 
246
               int, 'count')]
 
247
    takes_args = [ "location?" ]
 
248
    aliases = [ "visualize", "vis", "viz" ]
 
249
 
 
250
    def run(self, location=".", revision=None, limit=None):
 
251
        set_ui_factory()
 
252
        (br, path) = branch.Branch.open_containing(location)
 
253
        br.lock_read()
 
254
        try:
 
255
            if revision is None:
 
256
                revid = br.last_revision()
 
257
                if revid is None:
 
258
                    return
 
259
            else:
 
260
                (revno, revid) = revision[0].in_history(br)
 
261
 
 
262
            import gtk
 
263
            pp = start_viz_window(br, revid, limit)
 
264
            pp.connect("destroy", lambda w: gtk.main_quit())
 
265
            pp.show()
 
266
            gtk.main()
 
267
        finally:
 
268
            br.unlock()
 
269
 
 
270
 
 
271
class cmd_gannotate(GTKCommand):
 
272
    """GTK+ annotate.
 
273
    
 
274
    Browse changes to FILENAME line by line in a GTK+ window.
 
275
    """
 
276
 
 
277
    takes_args = ["filename", "line?"]
 
278
    takes_options = [
 
279
        Option("all", help="Show annotations on all lines."),
 
280
        Option("plain", help="Don't highlight annotation lines."),
 
281
        Option("line", type=int, argname="lineno",
 
282
               help="Jump to specified line number."),
 
283
        "revision",
 
284
    ]
 
285
    aliases = ["gblame", "gpraise"]
 
286
    
 
287
    def run(self, filename, all=False, plain=False, line='1', revision=None):
 
288
        gtk = self.open_display()
 
289
 
 
290
        try:
 
291
            line = int(line)
 
292
        except ValueError:
 
293
            raise BzrCommandError('Line argument ("%s") is not a number.' % 
 
294
                                  line)
 
295
 
 
296
        from annotate.gannotate import GAnnotateWindow
 
297
        from annotate.config import GAnnotateConfig
 
298
        from bzrlib.bzrdir import BzrDir
 
299
 
 
300
        wt, br, path = BzrDir.open_containing_tree_or_branch(filename)
 
301
        if wt is not None:
 
302
            tree = wt
 
303
        else:
 
304
            tree = br.basis_tree()
 
305
 
 
306
        file_id = tree.path2id(path)
 
307
 
 
308
        if file_id is None:
 
309
            raise NotVersionedError(filename)
 
310
        if revision is not None:
 
311
            if len(revision) != 1:
 
312
                raise BzrCommandError("Only 1 revion may be specified.")
 
313
            revision_id = revision[0].in_history(br).rev_id
 
314
            tree = br.repository.revision_tree(revision_id)
 
315
        else:
 
316
            revision_id = getattr(tree, 'get_revision_id', lambda: None)()
 
317
 
 
318
        window = GAnnotateWindow(all, plain)
 
319
        window.connect("destroy", lambda w: gtk.main_quit())
 
320
        window.set_title(path + " - gannotate")
 
321
        config = GAnnotateConfig(window)
 
322
        window.show()
 
323
        br.lock_read()
 
324
        if wt is not None:
 
325
            wt.lock_read()
 
326
        try:
 
327
            window.annotate(tree, br, file_id)
 
328
            window.jump_to_line(line)
 
329
            gtk.main()
 
330
        finally:
 
331
            br.unlock()
 
332
            if wt is not None:
 
333
                wt.unlock()
 
334
 
 
335
 
 
336
 
 
337
class cmd_gcommit(GTKCommand):
 
338
    """GTK+ commit dialog
 
339
 
 
340
    Graphical user interface for committing revisions"""
 
341
 
 
342
    aliases = [ "gci" ]
 
343
    takes_args = []
 
344
    takes_options = []
 
345
 
 
346
    def run(self, filename=None):
 
347
        import os
 
348
        self.open_display()
 
349
        from commit import CommitDialog
 
350
        from bzrlib.errors import (BzrCommandError,
 
351
                                   NotBranchError,
 
352
                                   NoWorkingTree)
 
353
 
 
354
        wt = None
 
355
        br = None
 
356
        try:
 
357
            (wt, path) = workingtree.WorkingTree.open_containing(filename)
 
358
            br = wt.branch
 
359
        except NoWorkingTree, e:
 
360
            from dialog import error_dialog
 
361
            error_dialog(_('Directory does not have a working tree'),
 
362
                         _('Operation aborted.'))
 
363
            return 1 # should this be retval=3?
 
364
 
 
365
        # It is a good habit to keep things locked for the duration, but it
 
366
        # could cause difficulties if someone wants to do things in another
 
367
        # window... We could lock_read() until we actually go to commit
 
368
        # changes... Just a thought.
 
369
        wt.lock_write()
 
370
        try:
 
371
            dlg = CommitDialog(wt)
 
372
            return dlg.run()
 
373
        finally:
 
374
            wt.unlock()
 
375
 
 
376
 
 
377
class cmd_gstatus(GTKCommand):
 
378
    """GTK+ status dialog
 
379
 
 
380
    Graphical user interface for showing status 
 
381
    information."""
 
382
    
 
383
    aliases = [ "gst" ]
 
384
    takes_args = ['PATH?']
 
385
    takes_options = []
 
386
 
 
387
    def run(self, path='.'):
 
388
        import os
 
389
        gtk = self.open_display()
 
390
        from status import StatusDialog
 
391
        (wt, wt_path) = workingtree.WorkingTree.open_containing(path)
 
392
        status = StatusDialog(wt, wt_path)
 
393
        status.connect("destroy", gtk.main_quit)
 
394
        status.run()
 
395
 
 
396
 
 
397
class cmd_gsend(GTKCommand):
 
398
    """GTK+ send merge directive.
 
399
 
 
400
    """
 
401
    def run(self):
 
402
        (br, path) = branch.Branch.open_containing(".")
 
403
        gtk = self.open_display()
 
404
        from bzrlib.plugins.gtk.mergedirective import SendMergeDirectiveDialog
 
405
        from StringIO import StringIO
 
406
        dialog = SendMergeDirectiveDialog(br)
 
407
        if dialog.run() == gtk.RESPONSE_OK:
 
408
            outf = StringIO()
 
409
            outf.writelines(dialog.get_merge_directive().to_lines())
 
410
            mail_client = br.get_config().get_mail_client()
 
411
            mail_client.compose_merge_request(dialog.get_mail_to(), "[MERGE]", 
 
412
                outf.getvalue())
 
413
 
 
414
            
 
415
 
 
416
 
 
417
class cmd_gconflicts(GTKCommand):
 
418
    """GTK+ conflicts.
 
419
    
 
420
    Select files from the list of conflicts and run an external utility to
 
421
    resolve them.
 
422
    """
 
423
    def run(self):
 
424
        (wt, path) = workingtree.WorkingTree.open_containing('.')
 
425
        self.open_display()
 
426
        from bzrlib.plugins.gtk.conflicts import ConflictsDialog
 
427
        dialog = ConflictsDialog(wt)
 
428
        dialog.run()
 
429
 
 
430
 
 
431
class cmd_gpreferences(GTKCommand):
 
432
    """ GTK+ preferences dialog.
 
433
 
 
434
    """
 
435
    def run(self):
 
436
        self.open_display()
 
437
        from bzrlib.plugins.gtk.preferences import PreferencesWindow
 
438
        dialog = PreferencesWindow()
 
439
        dialog.run()
 
440
 
 
441
 
 
442
class cmd_gmissing(Command):
 
443
    """ GTK+ missing revisions dialog.
 
444
 
 
445
    """
 
446
    takes_args = ["other_branch?"]
 
447
    def run(self, other_branch=None):
 
448
        pygtk = import_pygtk()
 
449
        try:
 
450
            import gtk
 
451
        except RuntimeError, e:
 
452
            if str(e) == "could not open display":
 
453
                raise NoDisplayError
 
454
 
 
455
        from bzrlib.plugins.gtk.missing import MissingWindow
 
456
        from bzrlib.branch import Branch
 
457
 
 
458
        local_branch = Branch.open_containing(".")[0]
 
459
        if other_branch is None:
 
460
            other_branch = local_branch.get_parent()
 
461
            
 
462
            if other_branch is None:
 
463
                raise errors.BzrCommandError("No peer location known or specified.")
 
464
        remote_branch = Branch.open_containing(other_branch)[0]
 
465
        set_ui_factory()
 
466
        local_branch.lock_read()
 
467
        try:
 
468
            remote_branch.lock_read()
 
469
            try:
 
470
                dialog = MissingWindow(local_branch, remote_branch)
 
471
                dialog.run()
 
472
            finally:
 
473
                remote_branch.unlock()
 
474
        finally:
 
475
            local_branch.unlock()
 
476
 
 
477
 
 
478
class cmd_ginit(GTKCommand):
 
479
    def run(self):
 
480
        self.open_display()
 
481
        from initialize import InitDialog
 
482
        dialog = InitDialog(os.path.abspath(os.path.curdir))
 
483
        dialog.run()
 
484
 
 
485
 
 
486
class cmd_gtags(GTKCommand):
 
487
    def run(self):
 
488
        br = branch.Branch.open_containing('.')[0]
 
489
        
 
490
        gtk = self.open_display()
 
491
        from tags import TagsWindow
 
492
        window = TagsWindow(br)
 
493
        window.show()
 
494
        gtk.main()
 
495
 
 
496
 
 
497
commands = [
 
498
    cmd_gannotate, 
 
499
    cmd_gbranch,
 
500
    cmd_gcheckout, 
 
501
    cmd_gcommit, 
 
502
    cmd_gconflicts, 
 
503
    cmd_gdiff,
 
504
    cmd_ginit,
 
505
    cmd_gmissing, 
 
506
    cmd_gpreferences, 
 
507
    cmd_gpush, 
 
508
    cmd_gsend,
 
509
    cmd_gstatus,
 
510
    cmd_gtags,
 
511
    cmd_visualise
 
512
    ]
 
513
 
 
514
for cmd in commands:
 
515
    register_command(cmd)
 
516
 
 
517
 
 
518
class cmd_commit_notify(GTKCommand):
 
519
    """Run the bzr commit notifier.
 
520
 
 
521
    This is a background program which will pop up a notification on the users
 
522
    screen when a commit occurs.
 
523
    """
 
524
 
 
525
    def run(self):
 
526
        from notify import NotifyPopupMenu
 
527
        gtk = self.open_display()
 
528
        menu = NotifyPopupMenu()
 
529
        icon = gtk.status_icon_new_from_file(os.path.join(data_path(), "bzr-icon-64.png"))
 
530
        icon.connect('popup-menu', menu.display)
 
531
 
 
532
        import cgi
 
533
        import dbus
 
534
        import dbus.service
 
535
        import pynotify
 
536
        from bzrlib.bzrdir import BzrDir
 
537
        from bzrlib import errors
 
538
        from bzrlib.osutils import format_date
 
539
        from bzrlib.transport import get_transport
 
540
        if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
 
541
            import dbus.glib
 
542
        from bzrlib.plugins.dbus import activity
 
543
        bus = dbus.SessionBus()
 
544
        # get the object so we can subscribe to callbacks from it.
 
545
        broadcast_service = bus.get_object(
 
546
            activity.Broadcast.DBUS_NAME,
 
547
            activity.Broadcast.DBUS_PATH)
 
548
 
 
549
        def catch_branch(revision_id, urls):
 
550
            # TODO: show all the urls, or perhaps choose the 'best'.
 
551
            url = urls[0]
 
552
            try:
 
553
                if isinstance(revision_id, unicode):
 
554
                    revision_id = revision_id.encode('utf8')
 
555
                transport = get_transport(url)
 
556
                a_dir = BzrDir.open_from_transport(transport)
 
557
                branch = a_dir.open_branch()
 
558
                revno = branch.revision_id_to_revno(revision_id)
 
559
                revision = branch.repository.get_revision(revision_id)
 
560
                summary = 'New revision %d in %s' % (revno, url)
 
561
                body  = 'Committer: %s\n' % revision.committer
 
562
                body += 'Date: %s\n' % format_date(revision.timestamp,
 
563
                    revision.timezone)
 
564
                body += '\n'
 
565
                body += revision.message
 
566
                body = cgi.escape(body)
 
567
                nw = pynotify.Notification(summary, body)
 
568
                def start_viz(notification=None, action=None, data=None):
 
569
                    """Start the viz program."""
 
570
                    pp = start_viz_window(branch, revision_id)
 
571
                    pp.show()
 
572
                def start_branch(notification=None, action=None, data=None):
 
573
                    """Start a Branch dialog"""
 
574
                    from bzrlib.plugins.gtk.branch import BranchDialog
 
575
                    bd = BranchDialog(remote_path=url)
 
576
                    bd.run()
 
577
                nw.add_action("inspect", "Inspect", start_viz, None)
 
578
                nw.add_action("branch", "Branch", start_branch, None)
 
579
                nw.set_timeout(5000)
 
580
                nw.show()
 
581
            except Exception, e:
 
582
                print e
 
583
                raise
 
584
        broadcast_service.connect_to_signal("Revision", catch_branch,
 
585
            dbus_interface=activity.Broadcast.DBUS_INTERFACE)
 
586
        pynotify.init("bzr commit-notify")
 
587
        gtk.main()
 
588
 
 
589
register_command(cmd_commit_notify)
 
590
 
 
591
 
 
592
class cmd_gselftest(GTKCommand):
 
593
    """Version of selftest that displays a notification at the end"""
 
594
 
 
595
    takes_args = builtins.cmd_selftest.takes_args
 
596
    takes_options = builtins.cmd_selftest.takes_options
 
597
    _see_also = ['selftest']
 
598
 
 
599
    def run(self, *args, **kwargs):
 
600
        import cgi
 
601
        import sys
 
602
        default_encoding = sys.getdefaultencoding()
 
603
        # prevent gtk from blowing up later
 
604
        gtk = import_pygtk()
 
605
        # prevent gtk from messing with default encoding
 
606
        import pynotify
 
607
        if sys.getdefaultencoding() != default_encoding:
 
608
            reload(sys)
 
609
            sys.setdefaultencoding(default_encoding)
 
610
        result = builtins.cmd_selftest().run(*args, **kwargs)
 
611
        if result == 0:
 
612
            summary = 'Success'
 
613
            body = 'Selftest succeeded in "%s"' % os.getcwd()
 
614
        if result == 1:
 
615
            summary = 'Failure'
 
616
            body = 'Selftest failed in "%s"' % os.getcwd()
 
617
        pynotify.init("bzr gselftest")
 
618
        note = pynotify.Notification(cgi.escape(summary), cgi.escape(body))
 
619
        note.set_timeout(pynotify.EXPIRES_NEVER)
 
620
        note.show()
 
621
 
 
622
 
 
623
register_command(cmd_gselftest)
 
624
 
 
625
 
 
626
class cmd_test_gtk(GTKCommand):
 
627
    """Version of selftest that just runs the gtk test suite."""
 
628
 
 
629
    takes_options = ['verbose',
 
630
                     Option('one', short_name='1',
 
631
                            help='Stop when one test fails.'),
 
632
                     Option('benchmark', help='Run the benchmarks.'),
 
633
                     Option('lsprof-timed',
 
634
                     help='Generate lsprof output for benchmarked'
 
635
                          ' sections of code.'),
 
636
                     Option('list-only',
 
637
                     help='List the tests instead of running them.'),
 
638
                     Option('randomize', type=str, argname="SEED",
 
639
                     help='Randomize the order of tests using the given'
 
640
                          ' seed or "now" for the current time.'),
 
641
                    ]
 
642
    takes_args = ['testspecs*']
 
643
 
 
644
    def run(self, verbose=None, one=False, benchmark=None,
 
645
            lsprof_timed=None, list_only=False, randomize=None,
 
646
            testspecs_list=None):
 
647
        from bzrlib import __path__ as bzrlib_path
 
648
        from bzrlib.tests import selftest
 
649
 
 
650
        print '%10s: %s' % ('bzrlib', bzrlib_path[0])
 
651
        if benchmark:
 
652
            print 'No benchmarks yet'
 
653
            return 3
 
654
 
 
655
            test_suite_factory = bench_suite
 
656
            if verbose is None:
 
657
                verbose = True
 
658
            # TODO: should possibly lock the history file...
 
659
            benchfile = open(".perf_history", "at", buffering=1)
 
660
        else:
 
661
            test_suite_factory = test_suite
 
662
            if verbose is None:
 
663
                verbose = False
 
664
            benchfile = None
 
665
 
 
666
        if testspecs_list is not None:
 
667
            pattern = '|'.join(testspecs_list)
 
668
        else:
 
669
            pattern = ".*"
 
670
 
 
671
        try:
 
672
            result = selftest(verbose=verbose,
 
673
                              pattern=pattern,
 
674
                              stop_on_failure=one,
 
675
                              test_suite_factory=test_suite_factory,
 
676
                              lsprof_timed=lsprof_timed,
 
677
                              bench_history=benchfile,
 
678
                              list_only=list_only,
 
679
                              random_seed=randomize,
 
680
                             )
 
681
        finally:
 
682
            if benchfile is not None:
 
683
                benchfile.close()
 
684
 
 
685
register_command(cmd_test_gtk)
 
686
 
 
687
 
 
688
import gettext
 
689
gettext.install('olive-gtk')
 
690
 
 
691
 
 
692
class NoDisplayError(BzrCommandError):
 
693
    """gtk could not find a proper display"""
 
694
 
 
695
    def __str__(self):
 
696
        return "No DISPLAY. Unable to run GTK+ application."
 
697
 
 
698
 
 
699
def test_suite():
 
700
    from unittest import TestSuite
 
701
    import tests
162
702
    import sys
163
703
    default_encoding = sys.getdefaultencoding()
164
704
    try:
165
 
        result = basic_tests
 
705
        result = TestSuite()
166
706
        try:
167
 
            import gi.repository.Gtk
168
 
        except ImportError:
169
 
            return basic_tests
170
 
        basic_tests.addTest(loader.loadTestsFromModuleNames(
171
 
                ["%s.%s" % (__name__, tmn) for tmn in testmod_names]))
 
707
            import_pygtk()
 
708
        except errors.BzrCommandError:
 
709
            return result
 
710
        result.addTest(tests.test_suite())
172
711
    finally:
173
712
        if sys.getdefaultencoding() != default_encoding:
174
713
            reload(sys)
175
714
            sys.setdefaultencoding(default_encoding)
176
 
    return basic_tests
177
 
 
 
715
    return result