Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/activity.py
blob: da2b714691703e90290f9f7a0b544dc663d64122 (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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
#! /usr/bin/env python
#
#    Copyright (C) 2006, 2007, One Laptop Per Child
#
#    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., 675 Mass Ave, Cambridge, MA 02139, USA.
#

import logging
_logger = logging.getLogger('memorize-activity')

from gettext import gettext as _
from os.path import join, dirname
from os import environ

import dbus
import gtk
import pygtk
import pickle
import telepathy
import telepathy.client

from sugar.activity.activity import Activity, ActivityToolbox
from sugar.presence import presenceservice
from sugar.presence.tubeconn import TubeConnection

from sugar.graphics.xocolor import XoColor
from sugar import profile
import cardtable
import scoreboard
import game
import messenger
import memorizetoolbar
import createtoolbar
import cardlist
import createcardpanel



SERVICE = 'org.laptop.Memorize'
IFACE = SERVICE
PATH = '/org/laptop/Memorize'

_TOOLBAR_PLAY = 1
_TOOLBAR_CREATE = 2

class MemorizeActivity(Activity):
    
    def __init__(self, handle):
        Activity.__init__(self, handle)

        self.create_load = False
        self.play_mode = False
        
        toolbox = ActivityToolbox(self)
        activity_toolbar = toolbox.get_activity_toolbar()
        
        self._memorizeToolbar = memorizetoolbar.MemorizeToolbar(self)
        toolbox.add_toolbar(_('Play'), self._memorizeToolbar)
        self._memorizeToolbar.show()  

        self._createToolbar = createtoolbar.CreateToolbar(self)
        toolbox.add_toolbar(_('Create'), self._createToolbar)
        self._createToolbar.show()
        
        self.set_toolbox(toolbox)
        toolbox.show()
        
   
        
        
        # Play game mode
        self.table = cardtable.CardTable()
        self.scoreboard = scoreboard.Scoreboard()
        self.game = game.MemorizeGame()
        
        self.table.connect('key-press-event', self.table.key_press_event)        
        self.table.connect('card-flipped', self.game.card_flipped)
        self.table.connect('card-highlighted', self.game.card_highlighted)
        
        self.game.connect('set-border', self.table.set_border)
        self.game.connect('flop-card', self.table.flop_card)
        self.game.connect('flip-card', self.table.flip_card)
        self.game.connect('highlight-card', self.table.highlight_card)
        self.game.connect('load_mode', self.table.load_msg)
        
        self.game.connect('msg_buddy', self.scoreboard.set_buddy_message)
        self.game.connect('add_buddy', self.scoreboard.add_buddy)
        self.game.connect('rem_buddy', self.scoreboard.rem_buddy)
        self.game.connect('increase-score', self.scoreboard.increase_score)
        self.game.connect('wait_mode_buddy', self.scoreboard.set_wait_mode)
        self.game.connect('change-turn', self.scoreboard.set_selected)
        
        self.game.connect('reset_scoreboard', self.scoreboard.reset)
        self.game.connect('reset_table', self.table.reset)
        
        self.game.connect('load_game', self.table.load_game)
        self.game.connect('change_game', self.table.change_game)
        self.game.connect('load_game', self._memorizeToolbar.update_toolbar)
        self.game.connect('change_game', self._memorizeToolbar.update_toolbar)
        
        self._memorizeToolbar.connect('game_changed', self.game.change_game)
        
        self.hbox = gtk.HBox(False)
        self.hbox.pack_start(self.scoreboard, False, False)
        self.hbox.pack_start(self.table)
        self.set_canvas(self.hbox)

        # connect to the in/out events of the memorize activity
        self.connect('focus_in_event', self._focus_in)
        self.connect('focus_out_event', self._focus_out)
        self.connect('destroy', self._cleanup_cb)

        # start on the game toolbar, might change this to the create toolbar later
        self.toolbox.set_current_toolbar(_TOOLBAR_PLAY)
        toolbox.connect('current-toolbar-changed', self.change_mode)
        
        # Get the Presence Service
        self.pservice = presenceservice.get_instance()
        self.initiating = None
            
        # Buddy object for you
        owner = self.pservice.get_owner()
        self.owner = owner
        self.current = 0
        
        self.game.set_myself(self.owner)  
        self.connect('shared', self._shared_cb)
        
        # Owner.props.key
        if self._shared_activity:
            # We are joining the activity
            self.connect('joined', self._joined_cb)
            if self.get_shared():
                # We've already joined
                self._joined_cb()
        else:
            _logger.debug('buddy joined - __init__: %s', self.owner.props.nick)
            game_file = join(dirname(__file__),'demos','addition.zip')
            self.game.load_game(game_file, 4, 'demo')
            _logger.debug('loading conventional')       
            self.game.add_buddy(self.owner)
        self.show_all()
        
    def read_file(self, file_path):

        if self.metadata['mime_type'] == 'application/x-memorize-project':
            self.toolbox.set_current_toolbar(_TOOLBAR_PLAY)
            self.game.change_game(None, file_path, 4, 'file', self.metadata['title'], self.metadata['icon-color'])
            
    def change_mode(self, notebook, index):
        if index == _TOOLBAR_CREATE:
            if not self.create_load:
                # Create game mode
                self.cardlist = cardlist.CardList()
                self.createcardpanel = createcardpanel.CreateCardPanel()
                self.createcardpanel.connect('add-pair', self.cardlist.add_pair)
                self.createcardpanel.connect('update-pair', self.cardlist.update_selected)
                self.cardlist.connect('pair-selected', self.createcardpanel.load_pair)
                self.cardlist.connect('update-create-toolbar', self._createToolbar.update_create_toolbar)
                self.cardlist.connect('update-create-buttons', self._createToolbar.update_buttons_status)
                self._createToolbar.connect('create_new_game', self.cardlist.clean_list)
                self._createToolbar.connect('create_new_game', self.createcardpanel.clean)
                self._createToolbar.connect('create_load_game', self.cardlist.load_game)
                self._createToolbar.connect('create_save_game', self.cardlist.save_game)
                self._createToolbar.connect('create_equal_pairs', self.createcardpanel.change_equal_pairs)   
                self.create_load = True
 
            self.hbox.remove(self.scoreboard)
            self.hbox.remove(self.table)
            self.hbox.pack_start(self.createcardpanel)
            self.hbox.pack_start(self.cardlist, False, False)
            self.play_mode = False

        else:
        
            self.hbox.remove(self.createcardpanel)
            self.hbox.remove(self.cardlist)
            self.hbox.pack_start(self.scoreboard, False, False)
            self.hbox.pack_start(self.table)
            self.play_mode = True
                
    def restart(self, widget):
        self.game.reset()

    def change_game(self, game_name, size, title=None, color=None):
        self.game.change_game(game_name, size, title, color)
        
    def _shared_cb(self, activity):
        _logger.debug('My activity was shared')
        self.initiating = True
        self._sharing_setup()

        _logger.debug('This is my activity: making a tube...')
        id = self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES].OfferDBusTube(
            SERVICE, {})

    def _sharing_setup(self):
        if self._shared_activity is None:
            _logger.error('Failed to share or join activity')
            return
        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)
        
        self._shared_activity.connect('buddy-joined', self._buddy_joined_cb)
        self._shared_activity.connect('buddy-left', self._buddy_left_cb)

    def _list_tubes_reply_cb(self, tubes):
        for tube_info in tubes:
            self._new_tube_cb(*tube_info)

    def _list_tubes_error_cb(self, e):
        _logger.error('ListTubes() failed: %s', e)

    def _joined_cb(self, activity):
        if not self._shared_activity:
            return

        _logger.debug('Joined an existing shared activity')

        self.found = 0
        for buddy in self._shared_activity.get_joined_buddies():
            _logger.debug("buddy joined - _joined_cb: %s  (get buddies of activity and add them to my list)", buddy.props.nick)
            self.game.add_buddy(buddy)
            if buddy == self.owner:
                self.found = 1

        if self.found == 0:
            _logger.debug("buddy joined - _joined_cb: Not foud myself in buddy list - will add myself at end of the list.")
            self.game.add_buddy(self.owner)

        self.initiating = False
        self._sharing_setup()
        
        #self._shared_activity.connect('buddy-joined', self._buddy_joined_cb)
        #self._shared_activity.connect('buddy-left', self._buddy_left_cb)

        _logger.debug('This is not my 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)

    def _new_tube_cb(self, id, initiator, type, service, params, state):
        _logger.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)

            self.tube_conn = TubeConnection(self.conn, 
                self.tubes_chan[telepathy.CHANNEL_TYPE_TUBES], 
                id, group_iface=self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP])
            
            self.messenger = messenger.Messenger(self.tube_conn, self.initiating, self._get_buddy, self.game)         
            self.game.connect('flip-card-signal', self.messenger.flip_sender)
            self.game.connect('change_game_signal', self.messenger.change_game)

    def _get_buddy(self, cs_handle):
         """Get a Buddy from a channel specific handle."""
         group = self.text_chan[telepathy.CHANNEL_INTERFACE_GROUP]
         my_csh = group.GetSelfHandle()
         if my_csh == cs_handle:
             handle = self.conn.GetSelfHandle()
         else:
             handle = group.GetHandleOwners([cs_handle])[0]
             assert handle != 0
         return self.pservice.get_buddy_by_telepathy_handle(self.tp_conn_name, 
                 self.tp_conn_path, handle)
             
    def _buddy_joined_cb (self, activity, buddy):
        if buddy <> self.owner:
            if buddy.props.nick == '':
                _logger.debug("buddy joined - _buddy_joined_cb: buddy name empty nick=%s. Will not add." %(buddy.props.nick))
            else:
                _logger.debug("buddy joined - _buddy_joined_cb: %s", buddy.props.nick)
                self.game.add_buddy(buddy)

    def _buddy_left_cb (self, activity, buddy):
        if buddy.props.nick == '':
            _logger.debug("buddy joined - _buddy_left_cb: buddy name empty nick=%s. Will not remove" %(buddy.props.nick))
        else:
            _logger.debug("buddy left - _buddy_left_cb: %s", buddy.props.nick)
            self.game.rem_buddy(buddy)

    def _focus_in(self, event, data=None):        
        if self.game.sound == 1:
            self.game.cs.start()
            _logger.debug(" Memorize is visible: start csound server. ")        
        
    def _focus_out(self, event, data=None):                
        if self.game.sound == 1:
            self.game.cs.pause()
            _logger.debug(" Memorize is invisible: pause csound server. ")        
        
    def _cleanup_cb(self, data=None):        
        if self.game.sound == 1:
            self.game.cs.quit()        
            _logger.debug(" Memorize closes: close csound server. ")