/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: Daniel Schierbeck
  • Date: 2007-12-06 23:37:06 UTC
  • mto: This revision was merged to the branch mainline in revision 417.
  • Revision ID: daniel.schierbeck@gmail.com-20071206233706-eeinks66w86r3gfm
Fixed bug in gmissing.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#!/usr/bin/python
2
 
 
3
1
# This program is free software; you can redistribute it and/or modify
4
2
# it under the terms of the GNU General Public License as published by
5
3
# the Free Software Foundation; either version 2 of the License, or
14
12
# along with this program; if not, write to the Free Software
15
13
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
14
 
17
 
"""GTK+ frontends to Bazaar commands """
 
15
"""Graphical support for Bazaar using GTK.
 
16
 
 
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. 
 
22
gcommit           GTK+ commit dialog.
 
23
gconflicts        GTK+ conflicts. 
 
24
gdiff             Show differences in working tree in a GTK+ Window. 
 
25
ginit             Initialise a new branch.
 
26
gmissing          GTK+ missing revisions dialog. 
 
27
gpreferences      GTK+ preferences dialog. 
 
28
gpush             GTK+ push.
 
29
gsend             GTK+ send merge directive.
 
30
gstatus           GTK+ status dialog.
 
31
gtags             Manage branch tags.
 
32
visualise         Graphically visualise this branch. 
 
33
"""
 
34
 
 
35
import sys
 
36
 
 
37
import bzrlib
 
38
 
 
39
version_info = (0, 93, 0, 'dev', 0)
 
40
 
 
41
if version_info[3] == 'final':
 
42
    version_string = '%d.%d.%d' % version_info[:3]
 
43
else:
 
44
    version_string = '%d.%d.%d%s%d' % version_info
 
45
__version__ = version_string
 
46
 
 
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
 
80
if __name__ != 'bzrlib.plugins.gtk':
 
81
    warning("Not running as bzrlib.plugins.gtk, things may break.")
 
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
""")
18
92
 
19
93
from bzrlib.commands import Command, register_command, display_command
20
94
from bzrlib.errors import NotVersionedError, BzrCommandError, NoSuchFile
21
 
from bzrlib.commands import Command, register_command
22
95
from bzrlib.option import Option
23
 
from bzrlib.branch import Branch
24
 
from bzrlib.workingtree import WorkingTree
25
 
from bzrlib.bzrdir import BzrDir
26
 
 
27
 
__version__ = '0.9.0'
28
 
 
29
 
class cmd_gbranch(Command):
 
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
 
 
108
def set_ui_factory():
 
109
    import_pygtk()
 
110
    from ui import GtkUIFactory
 
111
    import bzrlib.ui
 
112
    bzrlib.ui.ui_factory = GtkUIFactory()
 
113
 
 
114
 
 
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):
30
139
    """GTK+ branching.
31
140
    
32
141
    """
33
142
 
34
 
    def run(self):
35
 
        import pygtk
36
 
        pygtk.require("2.0")
37
 
        try:
38
 
            import gtk
39
 
        except RuntimeError, e:
40
 
            if str(e) == "could not open display":
41
 
                raise NoDisplayError
42
 
 
43
 
        from clone import CloneDialog
44
 
 
45
 
        window = CloneDialog()
46
 
        if window.run() == gtk.RESPONSE_OK:
47
 
            bzrdir = BzrDir.open(window.url)
48
 
            bzrdir.sprout(window.dest_path)
49
 
 
50
 
register_command(cmd_gbranch)
51
 
 
52
 
class cmd_gdiff(Command):
 
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):
53
175
    """Show differences in working tree in a GTK+ Window.
54
176
    
55
177
    Otherwise, all changes for the tree are listed.
59
181
 
60
182
    @display_command
61
183
    def run(self, revision=None, filename=None):
62
 
        wt = WorkingTree.open_containing(".")[0]
63
 
        branch = wt.branch
64
 
        if revision is not None:
65
 
            if len(revision) == 1:
 
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:
66
200
                tree1 = wt
67
 
                revision_id = revision[0].in_history(branch).rev_id
68
 
                tree2 = branch.repository.revision_tree(revision_id)
69
 
            elif len(revision) == 2:
70
 
                revision_id_0 = revision[0].in_history(branch).rev_id
71
 
                tree2 = branch.repository.revision_tree(revision_id_0)
72
 
                revision_id_1 = revision[1].in_history(branch).rev_id
73
 
                tree1 = branch.repository.revision_tree(revision_id_1)
74
 
        else:
75
 
            tree1 = wt
76
 
            tree2 = tree1.basis_tree()
77
 
 
78
 
        from bzrlib.plugins.gtk.viz.diffwin import DiffWindow
79
 
        import gtk
80
 
        window = DiffWindow()
81
 
        window.connect("destroy", lambda w: gtk.main_quit())
82
 
        window.set_diff("Working Tree", tree1, tree2)
83
 
        if filename is not None:
84
 
            tree_filename = tree1.relpath(filename)
85
 
            try:
86
 
                window.set_file(tree_filename)
87
 
            except NoSuchFile:
88
 
                if (tree1.inventory.path2id(tree_filename) is None and 
89
 
                    tree2.inventory.path2id(tree_filename) is None):
90
 
                    raise NotVersionedError(filename)
91
 
                raise BzrCommandError('No changes found for file "%s"' % 
92
 
                                      filename)
93
 
        window.show()
94
 
 
95
 
        gtk.main()
96
 
 
97
 
register_command(cmd_gdiff)
 
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
 
98
233
 
99
234
class cmd_visualise(Command):
100
235
    """Graphically visualise this branch.
107
242
    """
108
243
    takes_options = [
109
244
        "revision",
110
 
        Option('limit', "maximum number of revisions to display",
 
245
        Option('limit', "Maximum number of revisions to display.",
111
246
               int, 'count')]
112
247
    takes_args = [ "location?" ]
113
248
    aliases = [ "visualize", "vis", "viz" ]
114
249
 
115
250
    def run(self, location=".", revision=None, limit=None):
116
 
        (branch, path) = Branch.open_containing(location)
117
 
        branch.lock_read()
118
 
        branch.repository.lock_read()
119
 
        try:
120
 
            if revision is None:
121
 
                revid = branch.last_revision()
122
 
                if revid is None:
123
 
                    return
124
 
            else:
125
 
                (revno, revid) = revision[0].in_history(branch)
126
 
 
127
 
            from viz.bzrkapp import BzrkApp
128
 
                
129
 
            app = BzrkApp()
130
 
            app.show(branch, revid, limit)
131
 
        finally:
132
 
            branch.repository.unlock()
133
 
            branch.unlock()
134
 
        app.main()
135
 
 
136
 
 
137
 
register_command(cmd_visualise)
138
 
 
139
 
class cmd_gannotate(Command):
 
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):
140
268
    """GTK+ annotate.
141
269
    
142
270
    Browse changes to FILENAME line by line in a GTK+ window.
144
272
 
145
273
    takes_args = ["filename", "line?"]
146
274
    takes_options = [
147
 
        Option("all", help="show annotations on all lines"),
148
 
        Option("plain", help="don't highlight annotation lines"),
 
275
        Option("all", help="Show annotations on all lines."),
 
276
        Option("plain", help="Don't highlight annotation lines."),
149
277
        Option("line", type=int, argname="lineno",
150
 
               help="jump to specified line number")
 
278
               help="Jump to specified line number."),
 
279
        "revision",
151
280
    ]
152
281
    aliases = ["gblame", "gpraise"]
153
282
    
154
 
    def run(self, filename, all=False, plain=False, line='1'):
155
 
        import pygtk
156
 
        pygtk.require("2.0")
157
 
 
158
 
        try:
159
 
            import gtk
160
 
        except RuntimeError, e:
161
 
            if str(e) == "could not open display":
162
 
                raise NoDisplayError
 
283
    def run(self, filename, all=False, plain=False, line='1', revision=None):
 
284
        gtk = self.open_display()
163
285
 
164
286
        try:
165
287
            line = int(line)
169
291
 
170
292
        from annotate.gannotate import GAnnotateWindow
171
293
        from annotate.config import GAnnotateConfig
172
 
 
173
 
        (wt, path) = WorkingTree.open_containing(filename)
174
 
        branch = wt.branch
175
 
 
176
 
        file_id = wt.path2id(path)
 
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)
177
303
 
178
304
        if file_id is None:
179
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)()
180
313
 
181
314
        window = GAnnotateWindow(all, plain)
182
315
        window.connect("destroy", lambda w: gtk.main_quit())
183
316
        window.set_title(path + " - gannotate")
184
317
        config = GAnnotateConfig(window)
185
318
        window.show()
186
 
        branch.lock_read()
 
319
        br.lock_read()
 
320
        if wt is not None:
 
321
            wt.lock_read()
187
322
        try:
188
 
            window.annotate(branch, file_id)
 
323
            window.annotate(tree, br, file_id)
 
324
            window.jump_to_line(line)
 
325
            gtk.main()
189
326
        finally:
190
 
            branch.unlock()
191
 
        window.jump_to_line(line)
192
 
        
193
 
        gtk.main()
194
 
 
195
 
register_command(cmd_gannotate)
196
 
 
197
 
class cmd_gcommit(Command):
 
327
            br.unlock()
 
328
            if wt is not None:
 
329
                wt.unlock()
 
330
 
 
331
 
 
332
 
 
333
class cmd_gcommit(GTKCommand):
198
334
    """GTK+ commit dialog
199
335
 
200
336
    Graphical user interface for committing revisions"""
201
 
    
 
337
 
 
338
    aliases = [ "gci" ]
202
339
    takes_args = []
203
340
    takes_options = []
204
341
 
205
342
    def run(self, filename=None):
206
 
        import pygtk
207
 
        pygtk.require("2.0")
208
 
 
 
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()
209
445
        try:
210
446
            import gtk
211
447
        except RuntimeError, e:
212
448
            if str(e) == "could not open display":
213
449
                raise NoDisplayError
214
450
 
215
 
        from commit import GCommitDialog
216
 
        from bzrlib.commit import Commit
217
 
        from bzrlib.errors import (BzrCommandError, PointlessCommit, ConflictsInTree, 
218
 
           StrictCommitFailed)
219
 
 
220
 
        (wt, path) = WorkingTree.open_containing(filename)
221
 
        branch = wt.branch
222
 
 
223
 
        file_id = wt.path2id(path)
224
 
 
225
 
        if file_id is None:
226
 
            raise NotVersionedError(filename)
227
 
 
228
 
        dialog = GCommitDialog(wt)
229
 
        dialog.set_title(path + " - Commit")
230
 
        if dialog.run() != gtk.RESPONSE_CANCEL:
231
 
            Commit().commit(working_tree=wt,message=dialog.message,
232
 
                specific_files=dialog.specific_files)
233
 
 
234
 
register_command(cmd_gcommit)
 
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
 
235
687
 
236
688
class NoDisplayError(BzrCommandError):
237
689
    """gtk could not find a proper display"""
238
690
 
239
691
    def __str__(self):
240
 
        return "No DISPLAY. gannotate is disabled."
 
692
        return "No DISPLAY. Unable to run GTK+ application."
 
693
 
 
694
 
 
695
def test_suite():
 
696
    from unittest import TestSuite
 
697
    import tests
 
698
    import sys
 
699
    default_encoding = sys.getdefaultencoding()
 
700
    try:
 
701
        result = TestSuite()
 
702
        try:
 
703
            import_pygtk()
 
704
        except errors.BzrCommandError:
 
705
            return result
 
706
        result.addTest(tests.test_suite())
 
707
    finally:
 
708
        if sys.getdefaultencoding() != default_encoding:
 
709
            reload(sys)
 
710
            sys.setdefaultencoding(default_encoding)
 
711
    return result