Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/src/sugar/tutorius/core.py
blob: 9d0cba2d9366f1e44e53e1989aa9cc46d027c739 (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
# Copyright (C) 2009, Tutorius.org
# Copyright (C) 2009, Vincent Vinet <vince.vinet@gmail.com>
#
# 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
"""
Core

This module contains the core classes for tutorius

"""

import gtk
import logging

from sugar.tutorius.dialog import TutoriusDialog
from sugar.tutorius.gtkutils import find_widget

logger = logging.getLogger("tutorius")

class Tutorial (object):
    """
    Tutorial Class, used to run through the FSM.
    """

    def __init__(self, name, fsm):
        """Create an unattached tutorial
        """
        object.__init__(self)
        self.name = name
        self.state_machine = fsm
        self.state = None

        self.handlers = []
        self.activity = None
        #Rest of initialisation happens when attached

    def attach(self, activity):
        """Attach to a running activity
        @param activity the activity to attach to
        """
        #For now, absolutely detach if a previous one!
        if self.activity:
            self.detach()
        self.activity = activity
        self.set_state("INIT")

    def detach(self):
        """Detach from the current activity"""
        #Remove handlers 
        for eventfilter in self.state_machine.get(self.state,{}).get("EventFilters",()):
            eventfilter.remove_handlers()

        #Undo actions
        for act in self.state_machine.get(self.state,{}).get("Actions",()):
            act.undo()

        #FIXME There should be some amount of resetting done here...
        self.activity = None
        

    def set_state(self, name):
        """Switch to a new state"""
        if not self.state_machine.has_key(name):
            return
        logger.debug("====NEW STATE: %s====" % name)
        
        #Remove handlers 
        for eventfilter in self.state_machine.get(self.state,{}).get("EventFilters",()):
            eventfilter.remove_handlers()

        #Undo actions
        for act in self.state_machine.get(self.state,{}).get("Actions",()):
            act.undo()
            
        #Switch to new state
        self.state = name
        newstate = self.state_machine.get(name)

        #Register handlers for eventfilters
        for eventfilter in newstate["EventFilters"]:
            eventfilter.install_handlers(self._eventfilter_state_done, 
                activity=self.activity)

        #Do actions
        for act in newstate.get("Actions",()):
            act.do()

    def _eventfilter_state_done(self, eventfilter):
        """Callback handler for eventfilter to notify
        when we must go to the next state."""
        #XXX Tests should be run here normally

        #Swith to the next state pointed by the eventfilter
        self.set_state(eventfilter.get_next_state())

#    def register_signal(self, handler, obj_fqdn, signal_name):
#        """Register a signal handler onto a specific widget
#        @param handler function to attach as a handler
#        @param obj_fqdn fqdn-style object name
#        @param signal_name signal name to connect to
#
#        Side effects:
#        the object found and the handler id obtained by connect() are
#        appended in self.handlers
#        """
#        obj = find_widget(self.activity, obj_fqdn)
#        self.handlers.append( \
#            (obj, obj.connect(signal_name, handler, (signal_name, obj_fqdn) ))\
#        )

class State:
    """This is a step in a tutorial. The state represents a collection of 
    actions to undertake when entering the state, and a series of event filters
    with associated actions that point to a possible next state."""
    
    def __init__(self, action_list=[], event_filter_list=[]):
        """Initializes the content of the state, as in loading the actions
        that are required and building the correct tests.
        
        @param action_list The list of actions to execute when entering this
        state
        @param event_filter_list A list of tuples of the form 
        (event_filter, next_state_name), that explains the outgoing links for
        this state"""
        self._actions = action_list
        
        # Unused for now
        #self.tests = []
        
        self._event_filters = event_filter_list
        
    
    def setup(self):
        """Install the state itself. This is the best time to pop-up a dialog
        that has to remain for the duration of the state."""
        for action in self._actions:
            act.do()
    
    def teardown(self):
        """Undo every action that was installed for this state. This means 
        removing dialogs that were displayed, removing highlights, etc..."""
        for act in self._actions:
            act.undo()
    
    # Unused for now
##    def verify(self):
##        """Run the internal tests to see if one of them passes. If it does, 
##        then do the associated processing to go in the next state.""" 
##        for test in self.tests:
##            if test.verify() == True:
##                actions = test.get_actions()
##                for act in actions:
##                    act.do()
##                # Now that we execute the actions related to a test, we might
##                # want to undo them right after --- should we use a callback or
##                # a timer?
    
class FiniteStateMachine(State):
    """This is a collection of states, with a start state and an end callback.
    It is used to simplify the development of the various tutorials by 
    encapsulating a collection of states that represent a given learning 
    process."""
    
    def __init__(self, state_dict={}, start_state_name="INIT", setup_actions=[]):
        """The constructor for a FSM. Pass in the start state and the setup
        actions that need to be taken when the FSM itself start (which may be
        different from what is done in the first state of the machine).
        
        @param state_dict A dictionary containing the state names as keys and
        the state themselves as entries.
        @param start_state_name The name of the starting state, if different
        from "INIT"
        @param setup_actions The actions to undertake when initializing the FSM
        """
        State.__init__(self)

        # Dictionnary of states contained in the FSM
        self._states = state_dict
        
        # Remember the initial state - we might want to reset
        # or rewind the FSM at a later moment
        self.start_state = state_dict[start_state]
        
        # Register the actions for the FSM - They will be processed at the
        # FSM level, meaning that when the FSM will start, it will first
        # execute those actions. When the FSM closes, it will tear down the
        # inner actions of the state, then close its own actions
        self.actions = setup_actions
        
        self.current_state = self.start_state
        
        # Flag to mention that the FSM was initialized
        self._fsm_setup_done = False
        # Flag that must be raised when the FSM is to be teared down
        self._fsm_teardown_done = False
        # Flag used to declare that the FSM has reached an end state
        self._fsm_has_finished = False
        
    
    def setup(self):
        """
        Set up the FSM the first time, then setup the inner state
        """
        # If we never initialized the FSM itself, then we need to run all the
        # actions associated with the FSM.
        if self._fsm_setup_done == False:
            # Flag the FSM level setup as done
            self._fsm_setup_done = True
            # Execute all the FSM level actions
            for act in self.actions:
                act.do()
            
        # Then, we need to run the setup of the current state
        self.current_state.setup()
    
    def set_state(self, new_state_name):
        """
        This functions changes the current state of the finite state machine.
        
        @param new_state The identifier of the state we need to go to
        """
        # Pass in the name to the internal state - it might be a FSM and
        # this name will apply to it
        self.current_state.set_state(new_state_name)
        
        # Make sure the given state is owned by the FSM
        if not self._states.haskey(new_state_name):
            # If we did not recognize the name, then we do not possess any
            # state by that name - we must ignore this state change request as
            # it will be done elsewhere in the hierarchy (or it's just bogus).
            return
        
        new_state = self._states[new_state_name]
        
        # Undo the actions of the old state
        self.current_state.teardown()
        
        # Insert the new state
        self.current_state = new_state
        
        # Call the initial actions in the new state
        self.current_state.setup()
        
    
    def teardown(self):
        """
        Revert any changes done by setup()
        """
        # Teardown the current state
        self.current_state.teardown()
        
        # If we just finished the whole FSM, we need to also call the teardown
        # on the FSM level actions
        if self._fsm_has_finished == True:
            # Flag the FSM teardown as not needed anymore
            self._fsm_teardown_done = False
            # Undo all the FSM level actions here
            for act in self.actions:
                act.undo()

    #Unused for now
##    def verify(self):
##        """Verify if the current state passes its tests"""
##        return self.current_state.verify()