Web · Wiki · Activities · Blog · Lists · Chat · Meeting · Bugs · Git · Translate · Archive · People · Donate
1
import os
2
import gobject
3
import gtk
4
5
import sugar.activity.activity
6
import sugar.graphics.style
7
8
import pygame
9
import event
10
11
ACTIVITY = None
12
13
def get_activity():
14
    return ACTIVITY
15
16
class PygameActivity(sugar.activity.activity.Activity):
17
    def __init__(self, handle):
18
        super(PygameActivity, self).__init__(handle)
19
20
        self._socket = None
21
        self._screen = None
22
        
23
        # Fudge the toolbar size.
24
        TOOLBAR_HEIGHT = 75
25
        TAB_HEIGHT = 45
26
        self.width = gtk.gdk.screen_width()
27
        self.height = gtk.gdk.screen_height() - TOOLBAR_HEIGHT - TAB_HEIGHT
28
        
29
        global ACTIVITY
30
        ACTIVITY = self
31
32
    def build_canvas( self ):
33
        # Build the widget in which to embed Pygame.
34
        self._socket = gtk.Socket()
35
36
        eventbox = gtk.EventBox()
37
        eventbox.set_flags(gtk.CAN_FOCUS)
38
        eventbox.set_size_request(self.width, self.height)
39
        eventbox.add(self._socket)
40
        eventbox.show_all()
41
42
        self.set_canvas(eventbox)
43
44
        # Preinitialize Pygame so we can hook its methods.
45
        os.environ['SDL_WINDOWID'] = str(self._socket.get_id())
46
        pygame.init()
47
48
        # Hook certain Pygame functions with GTK equivalents.
49
        translator = event.Translator(self, eventbox)
50
        translator.hook_pygame()
51
52
        # Initialize the Pygame window.
53
        self._screen = pygame.display.set_mode((self.width,self.height))
54
55
        # Restore the default cursor.
56
        self._socket.get_window().set_cursor(None)
57
        
58
    def run_pygame(self, main_fn):
59
        # Run the main loop after a short delay.  The reason for the delay is that the
60
        # Sugar activity is not properly created until after its constructor returns.
61
        # If the Pygame main loop is called from the activity constructor, the 
62
        # constructor never returns and the activity freezes.
63
        gobject.idle_add(self._run_pygame_cb, main_fn)
64
        
65
    def _run_pygame_cb(self, main_fn):
66
        # Run the Pygame main loop.
67
        main_fn()
68
        return False
69
70
    def get_pygame_widget(self):
71
        return self._socket
72
73
    def get_pygame_screen(self):
74
        return self._screen
75