~torkvemada/+junk/bzr-cimage

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
'''Plugin to provide useful information about commiter.
In the internet noone knows you're a cat. This plugin
is intented to fix this issue. It takes your webcam image
each time you commit something and stores it in the commit
metadata. Then everyone who will clone your branch can just
look at your commit photo and understand, were you a cat,
an idiot or just you were drunk writing that code.'''

from bzrlib import hooks, commands, lazy_import
import gobject
import base64
import gtk
import gtk.gdk
lazy_import.lazy_import(globals(), '''
import gobject
import base64
from bzrlib.workingtree import WorkingTree
from bzrlib.branch import Branch
from bzrlib.revisionspec import RevisionSpec
from bzrlib import errors
from bzrlib.option import custom_help
from bzrlib.i18n import gettext
''')

version_info = (0, 2, 0)

IWIDTH = 320
IHEIGHT = 240

def fetch_cam_image():
    import gst
    from os import tmpfile
    import threading
    outf = tmpfile()
    caps = 'video/x-raw-rgb, width=%d, height=%d, depth=24, bpp=24' % (IWIDTH, IHEIGHT)
    pipe = gst.parse_launch('v4l2src num-buffers=10 ! videoscale ! %s ! pngenc ! fdsink fd=%d' % (caps, outf.fileno()))
    bus = pipe.get_bus()

    def start_snap():
        pipe.set_state(gst.STATE_PLAYING)

    t = threading.Thread(target=start_snap)
    t.start()
    evt = bus.poll(gst.MESSAGE_EOS, -1)
    pipe.set_state(gst.STATE_NULL)
    outf.seek(0)
    return outf.read()

def commit_start_commit_hook(commit):
    commit.revprops['user-photo'] = base64.b64encode(fetch_cam_image())

class cmd_cimage(commands.Command):
    """Display commit image for a revision.

      The commit image is taken automatically from webcam,
      when commit is performed. With this command one can
      easily check, who've done the commit and how the
      commiter was looking.
      """

    takes_args = ['revision_info?']
    takes_options = [custom_help('directory', help='Branch to examine, current working directory by default')]

    class ImageViewer(object):
        def __init__(self, initial_revision, branch):
            self.revision = initial_revision
            self.branch = branch
            self.revision_history = []

            self.loop = gobject.MainLoop()
            self.window = gtk.Window()
            self.window.set_property('width-request', IWIDTH)
            self.window.set_property('height-request', IHEIGHT)
            self.window.set_title(gettext('Commit image'))
            self.image = gtk.Image()
            self.window.add(self.image)
            self.window.connect('destroy', lambda x: self.loop.quit())
            from pprint import pprint
            self.window.connect('key-press-event', self._process_keypress)
            self._fetch_revision()

        def _process_keypress(self, window, event):
            key = gtk.gdk.keyval_name(event.keyval)
            if key == 'Left':
                revision = self.branch.repository.get_revision(self.revision)
                while True:
                    if not len(revision.parent_ids):
                        return
                    revision = self.branch.repository.get_revision(revision.parent_ids[0])
                    if 'user-photo' in revision.properties:
                        break
                self.revision_history.append(self.revision)
                self.revision = revision.revision_id
                self._fetch_revision()
            elif key == 'Right':
                if len(self.revision_history):
                    self.revision = self.revision_history.pop()
                    self._fetch_revision()

        def _show_image(self, image_data):
            pbloader = gtk.gdk.pixbuf_loader_new_with_mime_type('image/png')
            pbloader.write(image_data)
            pbloader.close()
            pb = pbloader.get_pixbuf()
            self.image.set_from_pixbuf(pb)

        def _fetch_revision(self):
            try:
                revision = self.branch.repository.get_revision(self.revision)
            except errors.NoSuchRevision:
                raise Exception(gettext('No such revision'))
            if 'user-photo' not in revision.properties:
                raise Exception(gettext('No photo is attached to revision'))
            try:
                image_data = base64.b64decode(revision.properties['user-photo'])
                self._show_image(image_data)
            except:
                raise Exception(gettext('Photo information is not readable'))

        def run(self):
            self.image.show()
            self.window.show()
            self.loop.run()

    @commands.display_command
    def run(self, revision_info=None, directory=u'.'):
        try:
            wt = WorkingTree.open_containing(directory)[0]
            b = wt.branch
            self.add_cleanup(wt.lock_read().unlock)
        except (errors.NoWorkingTree, errors.NotLocalUrl):
            wt = None
            b = Branch.open_containing(directory)[0]
            self.add_cleanup(b.lock_read().unlock)
        if revision_info is not None:
            revision = RevisionSpec.from_string(revision_info).as_revision_id(b)
        else:
            revision = b.last_revision()
        try:
            cmd_cimage.ImageViewer(revision, b).run()
        except Exception, e:
            self.outf.write('[%s] %s\n' % (gettext('ERROR'), e))

hooks.install_lazy_named_hook('bzrlib.commit', 'Commit.hooks', 'start_commit', commit_start_commit_hook, 'Take a picture of the user during the commit')
commands.register_command(cmd_cimage)