1
# This program is free software; you can redistribute it and/or modify
 
 
2
# it under the terms of the GNU General Public License as published by
 
 
3
# the Free Software Foundation; either version 2 of the License, or
 
 
4
# (at your option) any later version.
 
 
6
# This program is distributed in the hope that it will be useful,
 
 
7
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
 
8
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
 
9
# GNU General Public License for more details.
 
 
11
# You should have received a copy of the GNU General Public License
 
 
12
# along with this program; if not, write to the Free Software
 
 
13
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
 
15
"""Graphical support for Bazaar using GTK.
 
 
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. 
 
 
29
gsend             GTK+ send merge directive.
 
 
30
gstatus           GTK+ status dialog.
 
 
31
gtags             Manage branch tags.
 
 
32
visualise         Graphically visualise this branch. 
 
 
39
version_info = (0, 94, 0, 'dev', 0)
 
 
41
if version_info[3] == 'final':
 
 
42
    version_string = '%d.%d.%d' % version_info[:3]
 
 
44
    version_string = '%d.%d.%d%s%d' % version_info
 
 
45
__version__ = version_string
 
 
47
required_bzrlib = (1, 0)
 
 
49
def check_bzrlib_version(desired):
 
 
50
    """Check that bzrlib is compatible.
 
 
52
    If version is < bzr-gtk version, assume incompatible.
 
 
54
    bzrlib_version = bzrlib.version_info[:2]
 
 
56
        from bzrlib.trace import warning
 
 
58
        # get the message out any way we can
 
 
59
        from warnings import warn as warning
 
 
60
    if bzrlib_version < desired:
 
 
61
        from bzrlib.errors import BzrError
 
 
62
        warning('Installed Bazaar version %s is too old to be used with bzr-gtk'
 
 
63
                ' %s.' % (bzrlib.__version__, __version__))
 
 
64
        raise BzrError('Version mismatch: %r, %r' % (version_info, bzrlib.version_info) )
 
 
67
if version_info[2] == "final":
 
 
68
    check_bzrlib_version(required_bzrlib)
 
 
70
from bzrlib.trace import warning
 
 
71
if __name__ != 'bzrlib.plugins.gtk':
 
 
72
    warning("Not running as bzrlib.plugins.gtk, things may break.")
 
 
74
from bzrlib.lazy_import import lazy_import
 
 
75
lazy_import(globals(), """
 
 
84
from bzrlib.commands import Command, register_command, display_command
 
 
85
from bzrlib.errors import NotVersionedError, BzrCommandError, NoSuchFile
 
 
86
from bzrlib.option import Option
 
 
94
        raise errors.BzrCommandError("PyGTK not installed.")
 
 
101
    from ui import GtkUIFactory
 
 
103
    bzrlib.ui.ui_factory = GtkUIFactory()
 
 
107
    return os.path.dirname(__file__)
 
 
110
class GTKCommand(Command):
 
 
111
    """Abstract class providing GTK specific run commands."""
 
 
113
    def open_display(self):
 
 
114
        pygtk = import_pygtk()
 
 
117
        except RuntimeError, e:
 
 
118
            if str(e) == "could not open display":
 
 
125
        dialog = self.get_gtk_dialog(os.path.abspath('.'))
 
 
129
class cmd_gbranch(GTKCommand):
 
 
134
    def get_gtk_dialog(self, path):
 
 
135
        from bzrlib.plugins.gtk.branch import BranchDialog
 
 
136
        return BranchDialog(path)
 
 
139
class cmd_gcheckout(GTKCommand):
 
 
144
    def get_gtk_dialog(self, path):
 
 
145
        from bzrlib.plugins.gtk.checkout import CheckoutDialog
 
 
146
        return CheckoutDialog(path)
 
 
150
class cmd_gpush(GTKCommand):
 
 
154
    takes_args = [ "location?" ]
 
 
156
    def run(self, location="."):
 
 
157
        (br, path) = branch.Branch.open_containing(location)
 
 
159
        from push import PushDialog
 
 
160
        dialog = PushDialog(br.repository, br.last_revision(), br)
 
 
165
class cmd_gdiff(GTKCommand):
 
 
166
    """Show differences in working tree in a GTK+ Window.
 
 
168
    Otherwise, all changes for the tree are listed.
 
 
170
    takes_args = ['filename?']
 
 
171
    takes_options = ['revision']
 
 
174
    def run(self, revision=None, filename=None):
 
 
176
        wt = workingtree.WorkingTree.open_containing(".")[0]
 
 
180
            if revision is not None:
 
 
181
                if len(revision) == 1:
 
 
183
                    revision_id = revision[0].in_history(branch).rev_id
 
 
184
                    tree2 = branch.repository.revision_tree(revision_id)
 
 
185
                elif len(revision) == 2:
 
 
186
                    revision_id_0 = revision[0].in_history(branch).rev_id
 
 
187
                    tree2 = branch.repository.revision_tree(revision_id_0)
 
 
188
                    revision_id_1 = revision[1].in_history(branch).rev_id
 
 
189
                    tree1 = branch.repository.revision_tree(revision_id_1)
 
 
192
                tree2 = tree1.basis_tree()
 
 
194
            from diff import DiffWindow
 
 
196
            window = DiffWindow()
 
 
197
            window.connect("destroy", gtk.main_quit)
 
 
198
            window.set_diff("Working Tree", tree1, tree2)
 
 
199
            if filename is not None:
 
 
200
                tree_filename = wt.relpath(filename)
 
 
202
                    window.set_file(tree_filename)
 
 
204
                    if (tree1.path2id(tree_filename) is None and 
 
 
205
                        tree2.path2id(tree_filename) is None):
 
 
206
                        raise NotVersionedError(filename)
 
 
207
                    raise BzrCommandError('No changes found for file "%s"' % 
 
 
216
def start_viz_window(branch, revision, limit=None):
 
 
217
    """Start viz on branch with revision revision.
 
 
219
    :return: The viz window object.
 
 
221
    from viz.branchwin import BranchWindow
 
 
222
    return BranchWindow(branch, revision, limit)
 
 
225
class cmd_visualise(Command):
 
 
226
    """Graphically visualise this branch.
 
 
228
    Opens a graphical window to allow you to see the history of the branch
 
 
229
    and relationships between revisions in a visual manner,
 
 
231
    The default starting point is latest revision on the branch, you can
 
 
232
    specify a starting point with -r revision.
 
 
236
        Option('limit', "Maximum number of revisions to display.",
 
 
238
    takes_args = [ "location?" ]
 
 
239
    aliases = [ "visualize", "vis", "viz" ]
 
 
241
    def run(self, location=".", revision=None, limit=None):
 
 
243
        (br, path) = branch.Branch.open_containing(location)
 
 
245
            revid = br.last_revision()
 
 
249
            (revno, revid) = revision[0].in_history(br)
 
 
252
        pp = start_viz_window(br, revid, limit)
 
 
253
        pp.connect("destroy", lambda w: gtk.main_quit())
 
 
258
class cmd_gannotate(GTKCommand):
 
 
261
    Browse changes to FILENAME line by line in a GTK+ window.
 
 
264
    takes_args = ["filename", "line?"]
 
 
266
        Option("all", help="Show annotations on all lines."),
 
 
267
        Option("plain", help="Don't highlight annotation lines."),
 
 
268
        Option("line", type=int, argname="lineno",
 
 
269
               help="Jump to specified line number."),
 
 
272
    aliases = ["gblame", "gpraise"]
 
 
274
    def run(self, filename, all=False, plain=False, line='1', revision=None):
 
 
275
        gtk = self.open_display()
 
 
280
            raise BzrCommandError('Line argument ("%s") is not a number.' % 
 
 
283
        from annotate.gannotate import GAnnotateWindow
 
 
284
        from annotate.config import GAnnotateConfig
 
 
285
        from bzrlib.bzrdir import BzrDir
 
 
287
        wt, br, path = BzrDir.open_containing_tree_or_branch(filename)
 
 
291
            tree = br.basis_tree()
 
 
293
        file_id = tree.path2id(path)
 
 
296
            raise NotVersionedError(filename)
 
 
297
        if revision is not None:
 
 
298
            if len(revision) != 1:
 
 
299
                raise BzrCommandError("Only 1 revion may be specified.")
 
 
300
            revision_id = revision[0].in_history(br).rev_id
 
 
301
            tree = br.repository.revision_tree(revision_id)
 
 
303
            revision_id = getattr(tree, 'get_revision_id', lambda: None)()
 
 
305
        window = GAnnotateWindow(all, plain)
 
 
306
        window.connect("destroy", lambda w: gtk.main_quit())
 
 
307
        window.set_title(path + " - gannotate")
 
 
308
        config = GAnnotateConfig(window)
 
 
314
            window.annotate(tree, br, file_id)
 
 
315
            window.jump_to_line(line)
 
 
324
class cmd_gcommit(GTKCommand):
 
 
325
    """GTK+ commit dialog
 
 
327
    Graphical user interface for committing revisions"""
 
 
333
    def run(self, filename=None):
 
 
336
        from commit import CommitDialog
 
 
337
        from bzrlib.errors import (BzrCommandError,
 
 
344
            (wt, path) = workingtree.WorkingTree.open_containing(filename)
 
 
346
        except NoWorkingTree, e:
 
 
347
            from dialog import error_dialog
 
 
348
            error_dialog(_('Directory does not have a working tree'),
 
 
349
                         _('Operation aborted.'))
 
 
350
            return 1 # should this be retval=3?
 
 
352
        # It is a good habit to keep things locked for the duration, but it
 
 
353
        # could cause difficulties if someone wants to do things in another
 
 
354
        # window... We could lock_read() until we actually go to commit
 
 
355
        # changes... Just a thought.
 
 
358
            dlg = CommitDialog(wt)
 
 
364
class cmd_gstatus(GTKCommand):
 
 
365
    """GTK+ status dialog
 
 
367
    Graphical user interface for showing status 
 
 
371
    takes_args = ['PATH?']
 
 
374
    def run(self, path='.'):
 
 
376
        gtk = self.open_display()
 
 
377
        from status import StatusDialog
 
 
378
        (wt, wt_path) = workingtree.WorkingTree.open_containing(path)
 
 
379
        status = StatusDialog(wt, wt_path)
 
 
380
        status.connect("destroy", gtk.main_quit)
 
 
384
class cmd_gsend(GTKCommand):
 
 
385
    """GTK+ send merge directive.
 
 
389
        (br, path) = branch.Branch.open_containing(".")
 
 
390
        gtk = self.open_display()
 
 
391
        from bzrlib.plugins.gtk.mergedirective import SendMergeDirectiveDialog
 
 
392
        from StringIO import StringIO
 
 
393
        dialog = SendMergeDirectiveDialog(br)
 
 
394
        if dialog.run() == gtk.RESPONSE_OK:
 
 
396
            outf.writelines(dialog.get_merge_directive().to_lines())
 
 
397
            mail_client = br.get_config().get_mail_client()
 
 
398
            mail_client.compose_merge_request(dialog.get_mail_to(), "[MERGE]", 
 
 
404
class cmd_gconflicts(GTKCommand):
 
 
407
    Select files from the list of conflicts and run an external utility to
 
 
411
        (wt, path) = workingtree.WorkingTree.open_containing('.')
 
 
413
        from bzrlib.plugins.gtk.conflicts import ConflictsDialog
 
 
414
        dialog = ConflictsDialog(wt)
 
 
418
class cmd_gpreferences(GTKCommand):
 
 
419
    """ GTK+ preferences dialog.
 
 
424
        from bzrlib.plugins.gtk.preferences import PreferencesWindow
 
 
425
        dialog = PreferencesWindow()
 
 
429
class cmd_gmissing(Command):
 
 
430
    """ GTK+ missing revisions dialog.
 
 
433
    takes_args = ["other_branch?"]
 
 
434
    def run(self, other_branch=None):
 
 
435
        pygtk = import_pygtk()
 
 
438
        except RuntimeError, e:
 
 
439
            if str(e) == "could not open display":
 
 
442
        from bzrlib.plugins.gtk.missing import MissingWindow
 
 
443
        from bzrlib.branch import Branch
 
 
445
        local_branch = Branch.open_containing(".")[0]
 
 
446
        if other_branch is None:
 
 
447
            other_branch = local_branch.get_parent()
 
 
449
            if other_branch is None:
 
 
450
                raise errors.BzrCommandError("No peer location known or specified.")
 
 
451
        remote_branch = Branch.open_containing(other_branch)[0]
 
 
453
        local_branch.lock_read()
 
 
455
            remote_branch.lock_read()
 
 
457
                dialog = MissingWindow(local_branch, remote_branch)
 
 
460
                remote_branch.unlock()
 
 
462
            local_branch.unlock()
 
 
465
class cmd_ginit(GTKCommand):
 
 
468
        from initialize import InitDialog
 
 
469
        dialog = InitDialog(os.path.abspath(os.path.curdir))
 
 
473
class cmd_gtags(GTKCommand):
 
 
475
        br = branch.Branch.open_containing('.')[0]
 
 
477
        gtk = self.open_display()
 
 
478
        from tags import TagsWindow
 
 
479
        window = TagsWindow(br)
 
 
502
    register_command(cmd)
 
 
505
class cmd_commit_notify(GTKCommand):
 
 
506
    """Run the bzr commit notifier.
 
 
508
    This is a background program which will pop up a notification on the users
 
 
509
    screen when a commit occurs.
 
 
513
        from notify import NotifyPopupMenu
 
 
514
        gtk = self.open_display()
 
 
515
        menu = NotifyPopupMenu()
 
 
516
        icon = gtk.status_icon_new_from_file(os.path.join(data_path(), "bzr-icon-64.png"))
 
 
517
        icon.connect('popup-menu', menu.display)
 
 
523
        from bzrlib.bzrdir import BzrDir
 
 
524
        from bzrlib import errors
 
 
525
        from bzrlib.osutils import format_date
 
 
526
        from bzrlib.transport import get_transport
 
 
527
        if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
 
 
529
        from bzrlib.plugins.dbus import activity
 
 
530
        bus = dbus.SessionBus()
 
 
531
        # get the object so we can subscribe to callbacks from it.
 
 
532
        broadcast_service = bus.get_object(
 
 
533
            activity.Broadcast.DBUS_NAME,
 
 
534
            activity.Broadcast.DBUS_PATH)
 
 
536
        def catch_branch(revision_id, urls):
 
 
537
            # TODO: show all the urls, or perhaps choose the 'best'.
 
 
540
                if isinstance(revision_id, unicode):
 
 
541
                    revision_id = revision_id.encode('utf8')
 
 
542
                transport = get_transport(url)
 
 
543
                a_dir = BzrDir.open_from_transport(transport)
 
 
544
                branch = a_dir.open_branch()
 
 
545
                revno = branch.revision_id_to_revno(revision_id)
 
 
546
                revision = branch.repository.get_revision(revision_id)
 
 
547
                summary = 'New revision %d in %s' % (revno, url)
 
 
548
                body  = 'Committer: %s\n' % revision.committer
 
 
549
                body += 'Date: %s\n' % format_date(revision.timestamp,
 
 
552
                body += revision.message
 
 
553
                body = cgi.escape(body)
 
 
554
                nw = pynotify.Notification(summary, body)
 
 
555
                def start_viz(notification=None, action=None, data=None):
 
 
556
                    """Start the viz program."""
 
 
557
                    pp = start_viz_window(branch, revision_id)
 
 
559
                def start_branch(notification=None, action=None, data=None):
 
 
560
                    """Start a Branch dialog"""
 
 
561
                    from bzrlib.plugins.gtk.branch import BranchDialog
 
 
562
                    bd = BranchDialog(remote_path=url)
 
 
564
                nw.add_action("inspect", "Inspect", start_viz, None)
 
 
565
                nw.add_action("branch", "Branch", start_branch, None)
 
 
571
        broadcast_service.connect_to_signal("Revision", catch_branch,
 
 
572
            dbus_interface=activity.Broadcast.DBUS_INTERFACE)
 
 
573
        pynotify.init("bzr commit-notify")
 
 
576
register_command(cmd_commit_notify)
 
 
579
class cmd_gselftest(GTKCommand):
 
 
580
    """Version of selftest that displays a notification at the end"""
 
 
582
    takes_args = builtins.cmd_selftest.takes_args
 
 
583
    takes_options = builtins.cmd_selftest.takes_options
 
 
584
    _see_also = ['selftest']
 
 
586
    def run(self, *args, **kwargs):
 
 
589
        default_encoding = sys.getdefaultencoding()
 
 
590
        # prevent gtk from blowing up later
 
 
592
        # prevent gtk from messing with default encoding
 
 
594
        if sys.getdefaultencoding() != default_encoding:
 
 
596
            sys.setdefaultencoding(default_encoding)
 
 
597
        result = builtins.cmd_selftest().run(*args, **kwargs)
 
 
600
            body = 'Selftest succeeded in "%s"' % os.getcwd()
 
 
603
            body = 'Selftest failed in "%s"' % os.getcwd()
 
 
604
        pynotify.init("bzr gselftest")
 
 
605
        note = pynotify.Notification(cgi.escape(summary), cgi.escape(body))
 
 
606
        note.set_timeout(pynotify.EXPIRES_NEVER)
 
 
610
register_command(cmd_gselftest)
 
 
613
class cmd_test_gtk(GTKCommand):
 
 
614
    """Version of selftest that just runs the gtk test suite."""
 
 
616
    takes_options = ['verbose',
 
 
617
                     Option('one', short_name='1',
 
 
618
                            help='Stop when one test fails.'),
 
 
619
                     Option('benchmark', help='Run the benchmarks.'),
 
 
620
                     Option('lsprof-timed',
 
 
621
                     help='Generate lsprof output for benchmarked'
 
 
622
                          ' sections of code.'),
 
 
624
                     help='List the tests instead of running them.'),
 
 
625
                     Option('randomize', type=str, argname="SEED",
 
 
626
                     help='Randomize the order of tests using the given'
 
 
627
                          ' seed or "now" for the current time.'),
 
 
629
    takes_args = ['testspecs*']
 
 
631
    def run(self, verbose=None, one=False, benchmark=None,
 
 
632
            lsprof_timed=None, list_only=False, randomize=None,
 
 
633
            testspecs_list=None):
 
 
634
        from bzrlib import __path__ as bzrlib_path
 
 
635
        from bzrlib.tests import selftest
 
 
637
        print '%10s: %s' % ('bzrlib', bzrlib_path[0])
 
 
639
            print 'No benchmarks yet'
 
 
642
            test_suite_factory = bench_suite
 
 
645
            # TODO: should possibly lock the history file...
 
 
646
            benchfile = open(".perf_history", "at", buffering=1)
 
 
648
            test_suite_factory = test_suite
 
 
653
        if testspecs_list is not None:
 
 
654
            pattern = '|'.join(testspecs_list)
 
 
659
            result = selftest(verbose=verbose,
 
 
662
                              test_suite_factory=test_suite_factory,
 
 
663
                              lsprof_timed=lsprof_timed,
 
 
664
                              bench_history=benchfile,
 
 
666
                              random_seed=randomize,
 
 
669
            if benchfile is not None:
 
 
672
register_command(cmd_test_gtk)
 
 
676
gettext.install('olive-gtk')
 
 
679
class NoDisplayError(BzrCommandError):
 
 
680
    """gtk could not find a proper display"""
 
 
683
        return "No DISPLAY. Unable to run GTK+ application."
 
 
687
    from unittest import TestSuite
 
 
690
    default_encoding = sys.getdefaultencoding()
 
 
695
        except errors.BzrCommandError:
 
 
697
        result.addTest(tests.test_suite())
 
 
699
        if sys.getdefaultencoding() != default_encoding:
 
 
701
            sys.setdefaultencoding(default_encoding)