/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

Commit messages never contain config options

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
 
commit-notify     Start the graphical notifier of commits.
19
 
gannotate         GTK+ annotate. 
20
 
gbranch           GTK+ branching. 
21
 
gcheckout         GTK+ checkout. 
 
18
gannotate         GTK+ annotate.
 
19
gbranch           GTK+ branching.
 
20
gcheckout         GTK+ checkout.
22
21
gcommit           GTK+ commit dialog.
23
 
gconflicts        GTK+ conflicts. 
24
 
gdiff             Show differences in working tree in a GTK+ Window. 
 
22
gconflicts        GTK+ conflicts.
 
23
gdiff             Show differences in working tree in a GTK+ Window.
25
24
ginit             Initialise a new branch.
26
 
gmissing          GTK+ missing revisions dialog. 
27
 
gpreferences      GTK+ preferences dialog. 
 
25
gloom             GTK+ loom browse dialog
 
26
gmerge            GTK+ merge dialog
 
27
gmissing          GTK+ missing revisions dialog.
 
28
gpreferences      GTK+ preferences dialog.
28
29
gpush             GTK+ push.
29
30
gsend             GTK+ send merge directive.
30
31
gstatus           GTK+ status dialog.
31
32
gtags             Manage branch tags.
32
 
visualise         Graphically visualise this branch. 
 
33
visualise         Graphically visualise this branch.
33
34
"""
34
35
 
 
36
from __future__ import absolute_import
 
37
 
 
38
import os
35
39
import sys
36
40
 
 
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
 
37
54
import bzrlib
 
55
import bzrlib.api
 
56
from bzrlib.commands import plugin_cmds
38
57
 
39
 
version_info = (0, 93, 0, 'dev', 0)
 
58
from bzrlib.plugins.gtk.info import (
 
59
    bzr_plugin_version as version_info,
 
60
    bzr_compatible_versions,
 
61
    )
40
62
 
41
63
if version_info[3] == 'final':
42
64
    version_string = '%d.%d.%d' % version_info[:3]
44
66
    version_string = '%d.%d.%d%s%d' % version_info
45
67
__version__ = version_string
46
68
 
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
 
69
bzrlib.api.require_any_api(bzrlib, bzr_compatible_versions)
 
70
 
80
71
if __name__ != 'bzrlib.plugins.gtk':
 
72
    from bzrlib.trace import warning
81
73
    warning("Not running as bzrlib.plugins.gtk, things may break.")
82
74
 
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
 
 
107
75
 
108
76
def set_ui_factory():
109
 
    import_pygtk()
110
 
    from ui import GtkUIFactory
 
77
    from bzrlib.plugins.gtk.ui import GtkUIFactory
111
78
    import bzrlib.ui
112
79
    bzrlib.ui.ui_factory = GtkUIFactory()
113
80
 
114
81
 
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
 
        if revision is None:
254
 
            revid = br.last_revision()
255
 
            if revid is None:
256
 
                return
257
 
        else:
258
 
            (revno, revid) = revision[0].in_history(br)
259
 
 
260
 
        import gtk
261
 
        pp = start_viz_window(br, revid, limit)
262
 
        pp.connect("destroy", lambda w: gtk.main_quit())
263
 
        pp.show()
264
 
        gtk.main()
265
 
 
266
 
 
267
 
class cmd_gannotate(GTKCommand):
268
 
    """GTK+ annotate.
269
 
    
270
 
    Browse changes to FILENAME line by line in a GTK+ window.
271
 
    """
272
 
 
273
 
    takes_args = ["filename", "line?"]
274
 
    takes_options = [
275
 
        Option("all", help="Show annotations on all lines."),
276
 
        Option("plain", help="Don't highlight annotation lines."),
277
 
        Option("line", type=int, argname="lineno",
278
 
               help="Jump to specified line number."),
279
 
        "revision",
280
 
    ]
281
 
    aliases = ["gblame", "gpraise"]
282
 
    
283
 
    def run(self, filename, all=False, plain=False, line='1', revision=None):
284
 
        gtk = self.open_display()
285
 
 
286
 
        try:
287
 
            line = int(line)
288
 
        except ValueError:
289
 
            raise BzrCommandError('Line argument ("%s") is not a number.' % 
290
 
                                  line)
291
 
 
292
 
        from annotate.gannotate import GAnnotateWindow
293
 
        from annotate.config import GAnnotateConfig
294
 
        from bzrlib.bzrdir import BzrDir
295
 
 
296
 
        wt, br, path = BzrDir.open_containing_tree_or_branch(filename)
297
 
        if wt is not None:
298
 
            tree = wt
299
 
        else:
300
 
            tree = br.basis_tree()
301
 
 
302
 
        file_id = tree.path2id(path)
303
 
 
304
 
        if file_id is None:
305
 
            raise NotVersionedError(filename)
306
 
        if revision is not None:
307
 
            if len(revision) != 1:
308
 
                raise BzrCommandError("Only 1 revion may be specified.")
309
 
            revision_id = revision[0].in_history(br).rev_id
310
 
            tree = br.repository.revision_tree(revision_id)
311
 
        else:
312
 
            revision_id = getattr(tree, 'get_revision_id', lambda: None)()
313
 
 
314
 
        window = GAnnotateWindow(all, plain)
315
 
        window.connect("destroy", lambda w: gtk.main_quit())
316
 
        window.set_title(path + " - gannotate")
317
 
        config = GAnnotateConfig(window)
318
 
        window.show()
319
 
        br.lock_read()
320
 
        if wt is not None:
321
 
            wt.lock_read()
322
 
        try:
323
 
            window.annotate(tree, br, file_id)
324
 
            window.jump_to_line(line)
325
 
            gtk.main()
326
 
        finally:
327
 
            br.unlock()
328
 
            if wt is not None:
329
 
                wt.unlock()
330
 
 
331
 
 
332
 
 
333
 
class cmd_gcommit(GTKCommand):
334
 
    """GTK+ commit dialog
335
 
 
336
 
    Graphical user interface for committing revisions"""
337
 
 
338
 
    aliases = [ "gci" ]
339
 
    takes_args = []
340
 
    takes_options = []
341
 
 
342
 
    def run(self, filename=None):
343
 
        import os
344
 
        self.open_display()
345
 
        from commit import CommitDialog
346
 
        from bzrlib.errors import (BzrCommandError,
347
 
                                   NotBranchError,
348
 
                                   NoWorkingTree)
349
 
 
350
 
        wt = None
351
 
        br = None
352
 
        try:
353
 
            (wt, path) = workingtree.WorkingTree.open_containing(filename)
354
 
            br = wt.branch
355
 
        except NoWorkingTree, e:
356
 
            from dialog import error_dialog
357
 
            error_dialog(_('Directory does not have a working tree'),
358
 
                         _('Operation aborted.'))
359
 
            return 1 # should this be retval=3?
360
 
 
361
 
        # It is a good habit to keep things locked for the duration, but it
362
 
        # could cause difficulties if someone wants to do things in another
363
 
        # window... We could lock_read() until we actually go to commit
364
 
        # changes... Just a thought.
365
 
        wt.lock_write()
366
 
        try:
367
 
            dlg = CommitDialog(wt)
368
 
            return dlg.run()
369
 
        finally:
370
 
            wt.unlock()
371
 
 
372
 
 
373
 
class cmd_gstatus(GTKCommand):
374
 
    """GTK+ status dialog
375
 
 
376
 
    Graphical user interface for showing status 
377
 
    information."""
378
 
    
379
 
    aliases = [ "gst" ]
380
 
    takes_args = ['PATH?']
381
 
    takes_options = []
382
 
 
383
 
    def run(self, path='.'):
384
 
        import os
385
 
        gtk = self.open_display()
386
 
        from status import StatusDialog
387
 
        (wt, wt_path) = workingtree.WorkingTree.open_containing(path)
388
 
        status = StatusDialog(wt, wt_path)
389
 
        status.connect("destroy", gtk.main_quit)
390
 
        status.run()
391
 
 
392
 
 
393
 
class cmd_gsend(GTKCommand):
394
 
    """GTK+ send merge directive.
395
 
 
396
 
    """
397
 
    def run(self):
398
 
        (br, path) = branch.Branch.open_containing(".")
399
 
        gtk = self.open_display()
400
 
        from bzrlib.plugins.gtk.mergedirective import SendMergeDirectiveDialog
401
 
        from StringIO import StringIO
402
 
        dialog = SendMergeDirectiveDialog(br)
403
 
        if dialog.run() == gtk.RESPONSE_OK:
404
 
            outf = StringIO()
405
 
            outf.writelines(dialog.get_merge_directive().to_lines())
406
 
            mail_client = br.get_config().get_mail_client()
407
 
            mail_client.compose_merge_request(dialog.get_mail_to(), "[MERGE]", 
408
 
                outf.getvalue())
409
 
 
410
 
            
411
 
 
412
 
 
413
 
class cmd_gconflicts(GTKCommand):
414
 
    """GTK+ conflicts.
415
 
    
416
 
    Select files from the list of conflicts and run an external utility to
417
 
    resolve them.
418
 
    """
419
 
    def run(self):
420
 
        (wt, path) = workingtree.WorkingTree.open_containing('.')
421
 
        self.open_display()
422
 
        from bzrlib.plugins.gtk.conflicts import ConflictsDialog
423
 
        dialog = ConflictsDialog(wt)
424
 
        dialog.run()
425
 
 
426
 
 
427
 
class cmd_gpreferences(GTKCommand):
428
 
    """ GTK+ preferences dialog.
429
 
 
430
 
    """
431
 
    def run(self):
432
 
        self.open_display()
433
 
        from bzrlib.plugins.gtk.preferences import PreferencesWindow
434
 
        dialog = PreferencesWindow()
435
 
        dialog.run()
436
 
 
437
 
 
438
 
class cmd_gmissing(Command):
439
 
    """ GTK+ missing revisions dialog.
440
 
 
441
 
    """
442
 
    takes_args = ["other_branch?"]
443
 
    def run(self, other_branch=None):
444
 
        pygtk = import_pygtk()
445
 
        try:
446
 
            import gtk
447
 
        except RuntimeError, e:
448
 
            if str(e) == "could not open display":
449
 
                raise NoDisplayError
450
 
 
451
 
        from bzrlib.plugins.gtk.missing import MissingWindow
452
 
        from bzrlib.branch import Branch
453
 
 
454
 
        local_branch = Branch.open_containing(".")[0]
455
 
        if other_branch is None:
456
 
            other_branch = local_branch.get_parent()
457
 
            
458
 
            if other_branch is None:
459
 
                raise errors.BzrCommandError("No peer location known or specified.")
460
 
        remote_branch = Branch.open_containing(other_branch)[0]
461
 
        set_ui_factory()
462
 
        local_branch.lock_read()
463
 
        try:
464
 
            remote_branch.lock_read()
465
 
            try:
466
 
                dialog = MissingWindow(local_branch, remote_branch)
467
 
                dialog.run()
468
 
            finally:
469
 
                remote_branch.unlock()
470
 
        finally:
471
 
            local_branch.unlock()
472
 
 
473
 
 
474
 
class cmd_ginit(GTKCommand):
475
 
    def run(self):
476
 
        self.open_display()
477
 
        from initialize import InitDialog
478
 
        dialog = InitDialog(os.path.abspath(os.path.curdir))
479
 
        dialog.run()
480
 
 
481
 
 
482
 
class cmd_gtags(GTKCommand):
483
 
    def run(self):
484
 
        br = branch.Branch.open_containing('.')[0]
485
 
        
486
 
        gtk = self.open_display()
487
 
        from tags import TagsWindow
488
 
        window = TagsWindow(br)
489
 
        window.show()
490
 
        gtk.main()
491
 
 
492
 
 
493
 
commands = [
494
 
    cmd_gannotate, 
495
 
    cmd_gbranch,
496
 
    cmd_gcheckout, 
497
 
    cmd_gcommit, 
498
 
    cmd_gconflicts, 
499
 
    cmd_gdiff,
500
 
    cmd_ginit,
501
 
    cmd_gmissing, 
502
 
    cmd_gpreferences, 
503
 
    cmd_gpush, 
504
 
    cmd_gsend,
505
 
    cmd_gstatus,
506
 
    cmd_gtags,
507
 
    cmd_visualise
508
 
    ]
509
 
 
510
 
for cmd in commands:
511
 
    register_command(cmd)
512
 
 
513
 
 
514
 
class cmd_commit_notify(GTKCommand):
515
 
    """Run the bzr commit notifier.
516
 
 
517
 
    This is a background program which will pop up a notification on the users
518
 
    screen when a commit occurs.
519
 
    """
520
 
 
521
 
    def run(self):
522
 
        from notify import NotifyPopupMenu
523
 
        gtk = self.open_display()
524
 
        menu = NotifyPopupMenu()
525
 
        icon = gtk.status_icon_new_from_file(os.path.join(data_path(), "bzr-icon-64.png"))
526
 
        icon.connect('popup-menu', menu.display)
527
 
 
528
 
        import cgi
529
 
        import dbus
530
 
        import dbus.service
531
 
        import pynotify
532
 
        from bzrlib.bzrdir import BzrDir
533
 
        from bzrlib import errors
534
 
        from bzrlib.osutils import format_date
535
 
        from bzrlib.transport import get_transport
536
 
        if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
537
 
            import dbus.glib
538
 
        from bzrlib.plugins.dbus import activity
539
 
        bus = dbus.SessionBus()
540
 
        # get the object so we can subscribe to callbacks from it.
541
 
        broadcast_service = bus.get_object(
542
 
            activity.Broadcast.DBUS_NAME,
543
 
            activity.Broadcast.DBUS_PATH)
544
 
 
545
 
        def catch_branch(revision_id, urls):
546
 
            # TODO: show all the urls, or perhaps choose the 'best'.
547
 
            url = urls[0]
548
 
            try:
549
 
                if isinstance(revision_id, unicode):
550
 
                    revision_id = revision_id.encode('utf8')
551
 
                transport = get_transport(url)
552
 
                a_dir = BzrDir.open_from_transport(transport)
553
 
                branch = a_dir.open_branch()
554
 
                revno = branch.revision_id_to_revno(revision_id)
555
 
                revision = branch.repository.get_revision(revision_id)
556
 
                summary = 'New revision %d in %s' % (revno, url)
557
 
                body  = 'Committer: %s\n' % revision.committer
558
 
                body += 'Date: %s\n' % format_date(revision.timestamp,
559
 
                    revision.timezone)
560
 
                body += '\n'
561
 
                body += revision.message
562
 
                body = cgi.escape(body)
563
 
                nw = pynotify.Notification(summary, body)
564
 
                def start_viz(notification=None, action=None, data=None):
565
 
                    """Start the viz program."""
566
 
                    pp = start_viz_window(branch, revision_id)
567
 
                    pp.show()
568
 
                def start_branch(notification=None, action=None, data=None):
569
 
                    """Start a Branch dialog"""
570
 
                    from bzrlib.plugins.gtk.branch import BranchDialog
571
 
                    bd = BranchDialog(remote_path=url)
572
 
                    bd.run()
573
 
                nw.add_action("inspect", "Inspect", start_viz, None)
574
 
                nw.add_action("branch", "Branch", start_branch, None)
575
 
                nw.set_timeout(5000)
576
 
                nw.show()
577
 
            except Exception, e:
578
 
                print e
579
 
                raise
580
 
        broadcast_service.connect_to_signal("Revision", catch_branch,
581
 
            dbus_interface=activity.Broadcast.DBUS_INTERFACE)
582
 
        pynotify.init("bzr commit-notify")
583
 
        gtk.main()
584
 
 
585
 
register_command(cmd_commit_notify)
586
 
 
587
 
 
588
 
class cmd_gselftest(GTKCommand):
589
 
    """Version of selftest that displays a notification at the end"""
590
 
 
591
 
    takes_args = builtins.cmd_selftest.takes_args
592
 
    takes_options = builtins.cmd_selftest.takes_options
593
 
    _see_also = ['selftest']
594
 
 
595
 
    def run(self, *args, **kwargs):
596
 
        import cgi
597
 
        import sys
598
 
        default_encoding = sys.getdefaultencoding()
599
 
        # prevent gtk from blowing up later
600
 
        gtk = import_pygtk()
601
 
        # prevent gtk from messing with default encoding
602
 
        import pynotify
603
 
        if sys.getdefaultencoding() != default_encoding:
604
 
            reload(sys)
605
 
            sys.setdefaultencoding(default_encoding)
606
 
        result = builtins.cmd_selftest().run(*args, **kwargs)
607
 
        if result == 0:
608
 
            summary = 'Success'
609
 
            body = 'Selftest succeeded in "%s"' % os.getcwd()
610
 
        if result == 1:
611
 
            summary = 'Failure'
612
 
            body = 'Selftest failed in "%s"' % os.getcwd()
613
 
        pynotify.init("bzr gselftest")
614
 
        note = pynotify.Notification(cgi.escape(summary), cgi.escape(body))
615
 
        note.set_timeout(pynotify.EXPIRES_NEVER)
616
 
        note.show()
617
 
 
618
 
 
619
 
register_command(cmd_gselftest)
620
 
 
621
 
 
622
 
class cmd_test_gtk(GTKCommand):
623
 
    """Version of selftest that just runs the gtk test suite."""
624
 
 
625
 
    takes_options = ['verbose',
626
 
                     Option('one', short_name='1',
627
 
                            help='Stop when one test fails.'),
628
 
                     Option('benchmark', help='Run the benchmarks.'),
629
 
                     Option('lsprof-timed',
630
 
                     help='Generate lsprof output for benchmarked'
631
 
                          ' sections of code.'),
632
 
                     Option('list-only',
633
 
                     help='List the tests instead of running them.'),
634
 
                     Option('randomize', type=str, argname="SEED",
635
 
                     help='Randomize the order of tests using the given'
636
 
                          ' seed or "now" for the current time.'),
637
 
                    ]
638
 
    takes_args = ['testspecs*']
639
 
 
640
 
    def run(self, verbose=None, one=False, benchmark=None,
641
 
            lsprof_timed=None, list_only=False, randomize=None,
642
 
            testspecs_list=None):
643
 
        from bzrlib import __path__ as bzrlib_path
644
 
        from bzrlib.tests import selftest
645
 
 
646
 
        print '%10s: %s' % ('bzrlib', bzrlib_path[0])
647
 
        if benchmark:
648
 
            print 'No benchmarks yet'
649
 
            return 3
650
 
 
651
 
            test_suite_factory = bench_suite
652
 
            if verbose is None:
653
 
                verbose = True
654
 
            # TODO: should possibly lock the history file...
655
 
            benchfile = open(".perf_history", "at", buffering=1)
656
 
        else:
657
 
            test_suite_factory = test_suite
658
 
            if verbose is None:
659
 
                verbose = False
660
 
            benchfile = None
661
 
 
662
 
        if testspecs_list is not None:
663
 
            pattern = '|'.join(testspecs_list)
664
 
        else:
665
 
            pattern = ".*"
666
 
 
667
 
        try:
668
 
            result = selftest(verbose=verbose,
669
 
                              pattern=pattern,
670
 
                              stop_on_failure=one,
671
 
                              test_suite_factory=test_suite_factory,
672
 
                              lsprof_timed=lsprof_timed,
673
 
                              bench_history=benchfile,
674
 
                              list_only=list_only,
675
 
                              random_seed=randomize,
676
 
                             )
677
 
        finally:
678
 
            if benchfile is not None:
679
 
                benchfile.close()
680
 
 
681
 
register_command(cmd_test_gtk)
682
 
 
683
 
 
684
 
import gettext
685
 
gettext.install('olive-gtk')
686
 
 
687
 
 
688
 
class NoDisplayError(BzrCommandError):
689
 
    """gtk could not find a proper display"""
690
 
 
691
 
    def __str__(self):
692
 
        return "No DISPLAY. Unable to run GTK+ application."
693
 
 
694
 
 
695
 
def test_suite():
696
 
    from unittest import TestSuite
697
 
    import tests
 
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
        ]
698
162
    import sys
699
163
    default_encoding = sys.getdefaultencoding()
700
164
    try:
701
 
        result = TestSuite()
 
165
        result = basic_tests
702
166
        try:
703
 
            import_pygtk()
704
 
        except errors.BzrCommandError:
705
 
            return result
706
 
        result.addTest(tests.test_suite())
 
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
172
    finally:
708
173
        if sys.getdefaultencoding() != default_encoding:
709
174
            reload(sys)
710
175
            sys.setdefaultencoding(default_encoding)
711
 
    return result
 
176
    return basic_tests
 
177