12
12
# along with this program; if not, write to the Free Software
 
13
13
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
 
"""Graphical support for Bazaar using GTK.
 
18
 
gannotate         GTK+ annotate. 
 
19
 
gbranch           GTK+ branching. 
 
20
 
gcheckout         GTK+ checkout. 
 
21
 
gcommit           GTK+ commit dialog.
 
22
 
gconflicts        GTK+ conflicts. 
 
23
 
gdiff             Show differences in working tree in a GTK+ Window. 
 
24
 
ginit             Initialise a new branch.
 
25
 
gmerge            GTK+ merge dialog
 
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. 
 
 
15
"""GTK+ frontends to Bazaar commands """
 
39
 
version_info = (0, 95, 0, 'dev', 1)
 
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, 3)
 
 
19
__version__ = '0.16.0'
 
 
20
version_info = tuple(int(n) for n in __version__.split('.'))
 
49
23
def check_bzrlib_version(desired):
 
50
24
    """Check that bzrlib is compatible.
 
52
26
    If version is < bzr-gtk version, assume incompatible.
 
 
27
    If version == bzr-gtk version, assume completely compatible
 
 
28
    If version == bzr-gtk version + 1, assume compatible, with deprecations
 
 
29
    Otherwise, assume incompatible.
 
 
31
    desired_plus = (desired[0], desired[1]+1)
 
54
32
    bzrlib_version = bzrlib.version_info[:2]
 
 
33
    if bzrlib_version == desired:
 
56
36
        from bzrlib.trace import warning
 
57
37
    except ImportError:
 
58
38
        # get the message out any way we can
 
59
39
        from warnings import warn as warning
 
60
40
    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'
 
 
41
        warning('Installed bzr version %s is too old to be used with bzr-gtk'
 
63
42
                ' %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)
 
 
43
        # Not using BzrNewError, because it may not exist.
 
 
44
        raise Exception, ('Version mismatch', version_info)
 
 
46
        warning('bzr-gtk is not up to date with installed bzr version %s.'
 
 
47
                ' \nThere should be a newer version available, e.g. %i.%i.' 
 
 
48
                % (bzrlib.__version__, bzrlib_version[0], bzrlib_version[1]))
 
 
49
        if bzrlib_version != desired_plus:
 
 
50
            raise Exception, 'Version mismatch'
 
 
53
check_bzrlib_version(version_info[:2])
 
70
55
from bzrlib.trace import warning
 
71
56
if __name__ != 'bzrlib.plugins.gtk':
 
 
100
85
def set_ui_factory():
 
 
86
    pygtk = import_pygtk()
 
102
87
    from ui import GtkUIFactory
 
104
89
    bzrlib.ui.ui_factory = GtkUIFactory()
 
108
 
    return [os.path.dirname(__file__),
 
109
 
             "/usr/share/bzr-gtk", 
 
110
 
             "/usr/local/share/bzr-gtk"]
 
113
 
def data_path(*args):
 
114
 
    for basedir in data_basedirs():
 
115
 
        path = os.path.join(basedir, *args)
 
116
 
        if os.path.exists(path):
 
121
 
def icon_path(*args):
 
122
 
    return data_path(os.path.join('icons', *args))
 
126
 
    pygtk = import_pygtk()
 
129
 
    except RuntimeError, e:
 
130
 
        if str(e) == "could not open display":
 
136
 
class GTKCommand(Command):
 
137
 
    """Abstract class providing GTK specific run commands."""
 
141
 
        dialog = self.get_gtk_dialog(os.path.abspath('.'))
 
145
 
class cmd_gbranch(GTKCommand):
 
 
92
class cmd_gbranch(Command):
 
146
93
    """GTK+ branching.
 
150
 
    def get_gtk_dialog(self, path):
 
 
98
        pygtk = import_pygtk()
 
 
101
        except RuntimeError, e:
 
 
102
            if str(e) == "could not open display":
 
151
105
        from bzrlib.plugins.gtk.branch import BranchDialog
 
152
 
        return BranchDialog(path)
 
155
 
class cmd_gcheckout(GTKCommand):
 
 
108
        dialog = BranchDialog(os.path.abspath('.'))
 
 
111
register_command(cmd_gbranch)
 
 
113
class cmd_gcheckout(Command):
 
156
114
    """ GTK+ checkout.
 
160
 
    def get_gtk_dialog(self, path):
 
 
119
        pygtk = import_pygtk()
 
 
122
        except RuntimeError, e:
 
 
123
            if str(e) == "could not open display":
 
161
126
        from bzrlib.plugins.gtk.checkout import CheckoutDialog
 
162
 
        return CheckoutDialog(path)
 
166
 
class cmd_gpush(GTKCommand):
 
 
129
        dialog = CheckoutDialog(os.path.abspath('.'))
 
 
132
register_command(cmd_gcheckout)
 
 
134
class cmd_gpush(Command):
 
 
250
219
    takes_options = [
 
252
 
        Option('limit', "Maximum number of revisions to display.",
 
 
221
        Option('limit', "maximum number of revisions to display",
 
254
 
    takes_args = [ "locations*" ]
 
 
223
    takes_args = [ "location?" ]
 
255
224
    aliases = [ "visualize", "vis", "viz" ]
 
257
 
    def run(self, locations_list, revision=None, limit=None):
 
 
226
    def run(self, location=".", revision=None, limit=None):
 
259
 
        if locations_list is None:
 
260
 
            locations_list = ["."]
 
262
 
        for location in locations_list:
 
263
 
            (br, path) = branch.Branch.open_containing(location)
 
 
228
        (br, path) = branch.Branch.open_containing(location)
 
 
230
        br.repository.lock_read()
 
264
232
            if revision is None:
 
265
 
                revids.append(br.last_revision())
 
 
233
                revid = br.last_revision()
 
267
 
                revids.append(revision[0].as_revision_id(br))
 
269
 
        pp = start_viz_window(br, revids, limit)
 
270
 
        pp.connect("destroy", lambda w: gtk.main_quit())
 
275
 
class cmd_gannotate(GTKCommand):
 
 
237
                (revno, revid) = revision[0].in_history(br)
 
 
239
            from viz.branchwin import BranchWindow
 
 
243
            pp.set_branch(br, revid, limit)
 
 
244
            pp.connect("destroy", lambda w: gtk.main_quit())
 
 
248
            br.repository.unlock()
 
 
252
register_command(cmd_visualise)
 
 
254
class cmd_gannotate(Command):
 
276
255
    """GTK+ annotate.
 
278
257
    Browse changes to FILENAME line by line in a GTK+ window.
 
 
335
321
            if wt is not None:
 
340
 
class cmd_gcommit(GTKCommand):
 
 
324
register_command(cmd_gannotate)
 
 
326
class cmd_gcommit(Command):
 
341
327
    """GTK+ commit dialog
 
343
329
    Graphical user interface for committing revisions"""
 
345
331
    aliases = [ "gci" ]
 
347
333
    takes_options = []
 
349
335
    def run(self, filename=None):
 
 
337
        pygtk = import_pygtk()
 
 
341
        except RuntimeError, e:
 
 
342
            if str(e) == "could not open display":
 
352
346
        from commit import CommitDialog
 
 
347
        from bzrlib.commit import Commit
 
353
348
        from bzrlib.errors import (BzrCommandError,
 
360
358
            (wt, path) = workingtree.WorkingTree.open_containing(filename)
 
 
360
        except NotBranchError, e:
 
362
362
        except NoWorkingTree, e:
 
363
 
            from dialog import error_dialog
 
364
 
            error_dialog(_i18n('Directory does not have a working tree'),
 
365
 
                         _i18n('Operation aborted.'))
 
366
 
            return 1 # should this be retval=3?
 
368
 
        # It is a good habit to keep things locked for the duration, but it
 
369
 
        # could cause difficulties if someone wants to do things in another
 
370
 
        # window... We could lock_read() until we actually go to commit
 
371
 
        # changes... Just a thought.
 
374
 
            dlg = CommitDialog(wt)
 
380
 
class cmd_gstatus(GTKCommand):
 
 
365
                (br, path) = branch.Branch.open_containing(path)
 
 
366
            except NotBranchError, e:
 
 
370
        commit = CommitDialog(wt, path, not br)
 
 
373
register_command(cmd_gcommit)
 
 
375
class cmd_gstatus(Command):
 
381
376
    """GTK+ status dialog
 
383
378
    Graphical user interface for showing status 
 
 
386
381
    aliases = [ "gst" ]
 
387
382
    takes_args = ['PATH?']
 
388
 
    takes_options = ['revision']
 
390
 
    def run(self, path='.', revision=None):
 
 
385
    def run(self, path='.'):
 
 
387
        pygtk = import_pygtk()
 
 
391
        except RuntimeError, e:
 
 
392
            if str(e) == "could not open display":
 
393
396
        from status import StatusDialog
 
394
397
        (wt, wt_path) = workingtree.WorkingTree.open_containing(path)
 
396
 
        if revision is not None:
 
398
 
                revision_id = revision[0].as_revision_id(wt.branch)
 
400
 
                from bzrlib.errors import BzrError
 
401
 
                raise BzrError('Revision %r doesn\'t exist' % revision[0].user_spec )
 
405
 
        status = StatusDialog(wt, wt_path, revision_id)
 
 
398
        status = StatusDialog(wt, wt_path)
 
406
399
        status.connect("destroy", gtk.main_quit)
 
410
 
class cmd_gsend(GTKCommand):
 
411
 
    """GTK+ send merge directive.
 
415
 
        (br, path) = branch.Branch.open_containing(".")
 
417
 
        from bzrlib.plugins.gtk.mergedirective import SendMergeDirectiveDialog
 
418
 
        from StringIO import StringIO
 
419
 
        dialog = SendMergeDirectiveDialog(br)
 
420
 
        if dialog.run() == gtk.RESPONSE_OK:
 
422
 
            outf.writelines(dialog.get_merge_directive().to_lines())
 
423
 
            mail_client = br.get_config().get_mail_client()
 
424
 
            mail_client.compose_merge_request(dialog.get_mail_to(), "[MERGE]", 
 
430
 
class cmd_gconflicts(GTKCommand):
 
 
402
register_command(cmd_gstatus)
 
 
404
class cmd_gconflicts(Command):
 
433
 
    Select files from the list of conflicts and run an external utility to
 
437
409
        (wt, path) = workingtree.WorkingTree.open_containing('.')
 
 
411
        pygtk = import_pygtk()
 
 
414
        except RuntimeError, e:
 
 
415
            if str(e) == "could not open display":
 
439
418
        from bzrlib.plugins.gtk.conflicts import ConflictsDialog
 
440
421
        dialog = ConflictsDialog(wt)
 
444
 
class cmd_gpreferences(GTKCommand):
 
445
 
    """ GTK+ preferences dialog.
 
450
 
        from bzrlib.plugins.gtk.preferences import PreferencesWindow
 
451
 
        dialog = PreferencesWindow()
 
455
 
class cmd_gmerge(Command):
 
456
 
    """ GTK+ merge dialog
 
459
 
    takes_args = ["merge_from_path?"]
 
460
 
    def run(self, merge_from_path=None):
 
461
 
        from bzrlib import workingtree
 
462
 
        from bzrlib.plugins.gtk.dialog import error_dialog
 
463
 
        from bzrlib.plugins.gtk.merge import MergeDialog
 
465
 
        (wt, path) = workingtree.WorkingTree.open_containing('.')
 
466
 
        old_tree = wt.branch.repository.revision_tree(wt.branch.last_revision())
 
467
 
        delta = wt.changes_from(old_tree)
 
468
 
        if len(delta.added) or len(delta.removed) or len(delta.renamed) or len(delta.modified):
 
469
 
            error_dialog(_i18n('There are local changes in the branch'),
 
470
 
                         _i18n('Please commit or revert the changes before merging.'))
 
472
 
            parent_branch_path = wt.branch.get_parent()
 
473
 
            merge = MergeDialog(wt, path, parent_branch_path)
 
474
 
            response = merge.run()
 
478
 
class cmd_gmissing(Command):
 
479
 
    """ GTK+ missing revisions dialog.
 
482
 
    takes_args = ["other_branch?"]
 
483
 
    def run(self, other_branch=None):
 
484
 
        pygtk = import_pygtk()
 
487
 
        except RuntimeError, e:
 
488
 
            if str(e) == "could not open display":
 
491
 
        from bzrlib.plugins.gtk.missing import MissingWindow
 
492
 
        from bzrlib.branch import Branch
 
494
 
        local_branch = Branch.open_containing(".")[0]
 
495
 
        if other_branch is None:
 
496
 
            other_branch = local_branch.get_parent()
 
498
 
            if other_branch is None:
 
499
 
                raise errors.BzrCommandError("No peer location known or specified.")
 
500
 
        remote_branch = Branch.open_containing(other_branch)[0]
 
502
 
        local_branch.lock_read()
 
504
 
            remote_branch.lock_read()
 
506
 
                dialog = MissingWindow(local_branch, remote_branch)
 
509
 
                remote_branch.unlock()
 
511
 
            local_branch.unlock()
 
514
 
class cmd_ginit(GTKCommand):
 
517
 
        from initialize import InitDialog
 
518
 
        dialog = InitDialog(os.path.abspath(os.path.curdir))
 
522
 
class cmd_gtags(GTKCommand):
 
524
 
        br = branch.Branch.open_containing('.')[0]
 
527
 
        from tags import TagsWindow
 
528
 
        window = TagsWindow(br)
 
552
 
    register_command(cmd)
 
555
 
class cmd_gselftest(GTKCommand):
 
556
 
    """Version of selftest that displays a notification at the end"""
 
558
 
    takes_args = builtins.cmd_selftest.takes_args
 
559
 
    takes_options = builtins.cmd_selftest.takes_options
 
560
 
    _see_also = ['selftest']
 
562
 
    def run(self, *args, **kwargs):
 
565
 
        default_encoding = sys.getdefaultencoding()
 
566
 
        # prevent gtk from blowing up later
 
568
 
        # prevent gtk from messing with default encoding
 
570
 
        if sys.getdefaultencoding() != default_encoding:
 
572
 
            sys.setdefaultencoding(default_encoding)
 
573
 
        result = builtins.cmd_selftest().run(*args, **kwargs)
 
576
 
            body = 'Selftest succeeded in "%s"' % os.getcwd()
 
579
 
            body = 'Selftest failed in "%s"' % os.getcwd()
 
580
 
        pynotify.init("bzr gselftest")
 
581
 
        note = pynotify.Notification(cgi.escape(summary), cgi.escape(body))
 
582
 
        note.set_timeout(pynotify.EXPIRES_NEVER)
 
586
 
register_command(cmd_gselftest)
 
589
 
class cmd_test_gtk(GTKCommand):
 
590
 
    """Version of selftest that just runs the gtk test suite."""
 
592
 
    takes_options = ['verbose',
 
593
 
                     Option('one', short_name='1',
 
594
 
                            help='Stop when one test fails.'),
 
595
 
                     Option('benchmark', help='Run the benchmarks.'),
 
596
 
                     Option('lsprof-timed',
 
597
 
                     help='Generate lsprof output for benchmarked'
 
598
 
                          ' sections of code.'),
 
600
 
                     help='List the tests instead of running them.'),
 
601
 
                     Option('randomize', type=str, argname="SEED",
 
602
 
                     help='Randomize the order of tests using the given'
 
603
 
                          ' seed or "now" for the current time.'),
 
605
 
    takes_args = ['testspecs*']
 
607
 
    def run(self, verbose=None, one=False, benchmark=None,
 
608
 
            lsprof_timed=None, list_only=False, randomize=None,
 
609
 
            testspecs_list=None):
 
610
 
        from bzrlib import __path__ as bzrlib_path
 
611
 
        from bzrlib.tests import selftest
 
613
 
        print '%10s: %s' % ('bzrlib', bzrlib_path[0])
 
615
 
            print 'No benchmarks yet'
 
618
 
            test_suite_factory = bench_suite
 
621
 
            # TODO: should possibly lock the history file...
 
622
 
            benchfile = open(".perf_history", "at", buffering=1)
 
624
 
            test_suite_factory = test_suite
 
629
 
        if testspecs_list is not None:
 
630
 
            pattern = '|'.join(testspecs_list)
 
635
 
            result = selftest(verbose=verbose,
 
638
 
                              test_suite_factory=test_suite_factory,
 
639
 
                              lsprof_timed=lsprof_timed,
 
640
 
                              bench_history=benchfile,
 
642
 
                              random_seed=randomize,
 
645
 
            if benchfile is not None:
 
648
 
register_command(cmd_test_gtk)
 
 
424
register_command(cmd_gconflicts)
 
653
427
gettext.install('olive-gtk')
 
655
 
# Let's create a specialized alias to protect '_' from being erased by other
 
656
 
# uses of '_' as an anonymous variable (think pdb for one).
 
657
 
_i18n = gettext.gettext
 
659
429
class NoDisplayError(BzrCommandError):
 
660
430
    """gtk could not find a proper display"""
 
662
432
    def __str__(self):
 
663
433
        return "No DISPLAY. Unable to run GTK+ application."
 
666
435
def test_suite():
 
667
436
    from unittest import TestSuite