Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/paintwithme.py
blob: 4a6d201574a7b6190590030d48cf7bda68dd33ac (plain)
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# -*- coding: utf-8 -*-
#
# Copyright 2012 Manuel QuiƱones
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

"""
PaintWithMe Activity

This is my testbed for a shareable painting activity.  It also
features Cairo painting and storing/restoring the tool being used.

"""

from gettext import gettext as _
import logging
import json

from sugar.activity import activity

import telepathy
from dbus.service import signal
from dbus.gobject_service import ExportedGObject
from sugar.presence import presenceservice
from sugar.presence.tubeconn import TubeConnection

from toolbar import PaintToolbar
from drawing import Drawing


SERVICE = 'org.sugarlabs.PaintWithMeActivity'
IFACE = SERVICE
PATH = '/org/augarlabs/PaintWithMeActivity'


class PaintWithMeActivity(activity.Activity):
    """A shareable painting activity."""

    def __init__(self, handle):
        """Init activity, add toolbars and area for drawing."""
        super(PaintWithMeActivity, self).__init__(handle)

        toolbar_box = PaintToolbar(self)
        self.set_toolbar_box(toolbar_box)
        toolbar_box.show()

        self._setup_dispatch_table()

        self._drawing = Drawing(parent=self)
        self.set_canvas(self._drawing)
        self._drawing.show()
        toolbar_box.set_drawing(self._drawing)

        self._setup_presence_service()

        # Once the canvas size is known, setup the drawing to fit it:

        def size_allocate_cb(widget, allocation):
            self.canvas.disconnect(self._setup_handle)
            self._drawing.setup(allocation.width, allocation.height)

        self._setup_handle = self.canvas.connect('size_allocate',
                                                 size_allocate_cb)

    def read_file(self, file_path):
        """Read from Sugar Journal."""
        self._drawing.load_png(file_path)

        state = json.loads(self.metadata['state'])
        logging.debug("read_file")
        logging.debug(state)
        self._drawing.set_stroke_color(state['color'])
        self._drawing.set_stroke_width(state['width'])

    def write_file(self, file_path):
        """Write to Sugar Journal."""
        self.metadata['mime_type'] = 'image/png'
        self._drawing.save_png(file_path)

        state = {}
        state['color'] = self._drawing.get_stroke_color()
        state['width'] = self._drawing.get_stroke_width()
        self.metadata['state'] = json.dumps(state)
        logging.debug("write_file")
        logging.debug(state)

    # Collaboration-related methods below:

    def _setup_presence_service(self):
        """Setup the Presence Service."""
        self.pservice = presenceservice.get_instance()
        self.initiating = None  # sharing (True) or joining (False)

        owner = self.pservice.get_owner()
        self.owner = owner
        self._share = ""
        self.connect('shared', self._shared_cb)
        self.connect('joined', self._joined_cb)

    def _shared_cb(self, activity):
        """Either set up initial share..."""
        self._new_tube_common(True)

    def _joined_cb(self, activity):
        """...or join an exisiting share."""
        self._new_tube_common(False)

    def _new_tube_common(self, sharer):
        """Joining and sharing are mostly the same..."""
        if self._shared_activity is None:
            logging.debug("Error: Failed to share or join activity ... \
                _shared_activity is null in _shared_cb()")
            return

        self.initiating = sharer
        self.waiting_for_hand = not sharer

        self.conn = self._shared_activity.telepathy_conn
        self.tubes_chan = self._shared_activity.telepathy_tubes_chan
        self.text_chan = self._shared_activity.telepathy_text_chan

        self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].connect_to_signal(
            'NewTube', self._new_tube_cb)

        if sharer:
            logging.debug('This is my activity: making a tube...')
            id = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube(
                SERVICE, {})
        else:
            logging.debug('I am joining an activity: waiting for a tube...')
            self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].ListTubes(
                reply_handler=self._list_tubes_reply_cb,
                error_handler=self._list_tubes_error_cb)
        self._drawing.set_sharing(True)

    def _list_tubes_reply_cb(self, tubes):
        """Reply to a list request."""
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        """Log errors."""
        logging.debug('Error: ListTubes() failed: %s' % (e))

    def _new_tube_cb(self, id, initiator, type, service, params, state):
        """Create a new tube."""
        logging.debug('New tube: ID=%d initator=%d type=%d service=%s \
params=%r state=%d' % (id, initiator, type, service, params, state))

        if (type == telepathy.TUBE_TYPE_DBUS and service == SERVICE):
            if state == telepathy.TUBE_STATE_LOCAL_PENDING:
                self.tubes_chan[ \
                              telepathy.CHANNEL_TYPE_TUBES].AcceptDBusTube(id)

            tube_conn = TubeConnection(self.conn,
                self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], id, \
                group_iface=self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP])

            self.chattube = ChatTube(tube_conn, self.initiating, \
                self.event_received_cb)

    def _setup_dispatch_table(self):
        """Associate tokens with commands."""
        self._processing_methods = {
            'n': [self._receive_new_drawing, 'get a new drawing'],
            'p': [self._receive_stroke, 'get a stroke'],
            }

    def event_received_cb(self, event_message):
        """Data from a tube has arrived."""
        if len(event_message) == 0:
            return
        try:
            command, payload = event_message.split('|', 2)
        except ValueError:
            logging.debug('Could not split event message %s' % (event_message))
            return
        self._processing_methods[command][0](payload)

    def send_new_drawing(self):
        """Send a new width, height to all players."""
        self.send_event('n|%s' % (json.dumps(self._drawing.get_size())))

    def _receive_new_drawing(self, payload):
        """Sharer can start a new drawing."""
        width, height = json.loads(payload)
        self._drawing.setup(width, height)

    def send_stroke(self, stroke_points, settings):
        """Send a new stroke to all the players."""
        self.send_event('p|%s' % (json.dumps((stroke_points, settings))))

    def _receive_stroke(self, payload):
        """When a stroke is finished, everyone should show it."""
        stroke_points, settings = json.loads(payload)
        self._drawing.remote_stroke(stroke_points, settings)

    def send_event(self, entry):
        """ Send event through the tube. """
        if hasattr(self, 'chattube') and self.chattube is not None:
            self.chattube.SendText(entry)


class ChatTube(ExportedGObject):
    """ Class for setting up tube for sharing """

    def __init__(self, tube, is_initiator, stack_received_cb):
        super(ChatTube, self).__init__(tube, PATH)
        self.tube = tube
        self.is_initiator = is_initiator  # Are we sharing or joining activity?
        self.stack_received_cb = stack_received_cb
        self.stack = ''

        self.tube.add_signal_receiver(self.send_stack_cb, 'SendText', IFACE,
                                      path=PATH, sender_keyword='sender')

    def send_stack_cb(self, text, sender=None):
        if sender == self.tube.get_unique_name():
            return
        self.stack = text
        self.stack_received_cb(text)

    @signal(dbus_interface=IFACE, signature='s')
    def SendText(self, text):
        self.stack = text