Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/tutorius/TProbe.py
blob: 7f717f1ccc238f4bb8a67dfcb5a937a09f499dde (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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
# Copyright (C) 2009, Tutorius.org
#
# 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 1 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

import logging
LOGGER = logging.getLogger("sugar.tutorius.TProbe")
import os
import gtk

import gobject

import dbus.service
import cPickle as pickle

from functools import partial

from jarabe.model.shell import get_model
from sugar.bundle.activitybundle import ActivityBundle

from . import addon

from .dbustools import save_args, ignore, logError
from .gtkutils import find_widget, raddr_lookup
import copy

"""
  --------------------
  |  ProbeManager    |
  --------------------
           |
           V
  --------------------                ----------
  |    ProbeProxy    |<---- DBus ---->| TProbe |
  --------------------                ----------

"""

#Prefix separator for action/event addresses
PSEP=":"

#TODO Add stub error handling for remote calls in the classes so that it will
# be clearer how errors can be handled in the future.


class TProbe(dbus.service.Object):
    """ Tutorius Probe
        Defines an entry point for Tutorius into activities that allows
        performing actions and registering events onto an activity via 
        a DBUS Interface.
    """

    def __init__(self, widget, activity_name, unique_id, overlayer=None, service_proxy=None):
        """
        Create and register a TProbe for an activity.

        @param widget top widget reference, must be a gtk container
        @param activity_name generic name for the activity
        @param unique_id specific name for this instance
        @param overlayer overlayer to draw actions on
        @param service_proxy A Service proxy object to do the registering 
        """
        self._activity = widget
        
        #Legacy way to access the overlayer, do it here instead of everywhere
        self._overlayer = overlayer or getattr(self._activity, "_overlayer", None)
        
        if service_proxy == None:
            from .service import ServiceProxy 

        self._service_proxy = service_proxy or ServiceProxy()

        self._activity_name = activity_name
        self._unique_id = unique_id

        LOGGER.debug("TProbe :: Creating TProbe for %s (%d)", self._activity_name, os.getpid())
        LOGGER.debug("TProbe :: Current gobject context: %s", str(gobject.main_context_default()))
        LOGGER.debug("TProbe :: Current gobject depth: %s", str(gobject.main_depth()))
        self._session_bus = dbus.SessionBus()

        # Giving a new name because _name is already used by dbus
        self._name2 = dbus.service.BusName(self._activity_name, self._session_bus)
        dbus.service.Object.__init__(self, self._session_bus, "/tutorius/Probe/"+str(self._unique_id))

        # Add the dictionary we will use to store which actions and events
        # are known
        self._installedActions = {}
        self._subscribedEvents = {}

        LOGGER.debug("TProbe :: registering '%s' with unique_id '%s'", self._activity_name, self._unique_id)
        self._service_proxy.register_probe(self._activity_name, self._unique_id)

    def start(self):
        """
        Optional method to call if the probe is not inserted into an
        existing activity. Starts a gobject mainloop
        """
        mainloop = gobject.MainLoop()
        mainloop.run()

    def stop(self):
        """
        Clean up the probe when finished.  Should be called just
        before a process ends
        """
        from .service import ServiceProxy
        LOGGER.debug("TProbe :: unregistering '%s' with unique_id '%s'", self._activity_name, self._unique_id)
        ServiceProxy().unregister_probe(self._unique_id)

    @dbus.service.method("org.tutorius.ProbeInterface",
                         in_signature='s', out_signature='')
    def registered(self, service):
        print ("Registered with: " + str(service))

    @dbus.service.method("org.tutorius.ProbeInterface",
                         in_signature='', out_signature='s')
    def ping(self):
        """ 
        Allows testing the connection to a Probe 
        @return string "alive"
        """
        return "alive"

    # ------------------ Action handling --------------------------------------
    @dbus.service.method("org.tutorius.ProbeInterface",
                         in_signature='sb', out_signature='s')
    def install(self, pickled_action, is_editing):
        """ 
        Install an action on the Activity
        @param pickled_action string pickled action
        @param is_editing whether this action comes from the editor
        @return string address of installed action
        """
        loaded_action = pickle.loads(str(pickled_action))
        action = addon.create(loaded_action.__class__.__name__)

        address = self._generate_action_reference(action)

        self._installedActions[address] = action
        updated_props = {}

        if action._props:
            action._props.update(loaded_action._props)

        if not is_editing:
            action.do(activity=self._activity, probe=self, overlayer=self._overlayer)
        else:
            # force mandatory props
            addon_name = addon.get_name_from_type(type(action))
            meta = addon.get_addon_meta(addon_name)
            for propname in meta['mandatory_props']:
                if getattr(action, propname) != None:
                    continue
                prop = getattr(type(action), propname)
                prop.widget_class.run_dialog(self._activity,
                                             action,
                                             propname)
                updated_props[propname] = getattr(action, propname)

            action.enter_editmode(overlayer=self._overlayer)
            action.set_notification_cb(partial(self.update_action, address))

        pickled_value = pickle.dumps((address, updated_props))
        return pickled_value

    @dbus.service.method("org.tutorius.ProbeInterface",
                         in_signature='ssb', out_signature='')
    def update(self, address, action_props, is_editing):
        """
        Update an already registered action
        @param address string address returned by install()
        @param action_props pickled action properties
        @param is_editing whether this action comes from the editor
        @return None
        """
        action = self._installedActions[address]

        if action._props:
            props = pickle.loads(str(action_props))
            action._props.update(props)
            if not is_editing:
                action.undo()
                action.do(activity=self._activity, overlayer=self._overlayer)
            else:
                action.exit_editmode()
                action.enter_editmode(overlayer=self._overlayer)

    @dbus.service.method("org.tutorius.ProbeInterface",
                         in_signature='sb', out_signature='')
    def uninstall(self, address, is_editing):
        """
        Uninstall an action
        @param address string address returned by install()
        @param is_editing whether this action comes from the editor
        @return None
        """
        if self._installedActions.has_key(address):
            action = self._installedActions[address]
            if not is_editing:
                action.undo()
            else:
                action.exit_editmode()
            self._installedActions.pop(address)
    

    # ------------------ Event handling ---------------------------------------
    @dbus.service.method("org.tutorius.ProbeInterface",
                         in_signature='s', out_signature='s')
    def create_event(self, addon_name):
        # avoid recursive imports
        event = addon.create(addon_name)
        addonname = type(event).__name__
        meta = addon.get_addon_meta(addonname)
        for propname in meta['mandatory_props']:
            prop = getattr(type(event), propname)
            prop.widget_class.run_dialog(self._activity, event, propname)

        return pickle.dumps(event)

    @dbus.service.method("org.tutorius.ProbeInterface",
                         in_signature='s', out_signature='s')
    def subscribe(self, pickled_event):
        """ 
        Subscribe to an Event
        @param pickled_event string pickled EventFilter
        @return string unique name of registered event
        """
        #TODO Perform event unmapping once Tutorials use abstract events 
        #   instead of concrete EventFilters that are tied to their 
        #   implementation.
        eventfilter = pickle.loads(str(pickled_event))

        # The callback uses the event defined previously and each
        # successive call to subscribe will register a different
        # callback that references a different event
        def callback(*args):
            self.notify(eventfilter)

        eventfilter.install_handlers(callback, activity=self._activity, probe=self, overlayer=self._overlayer)

        name = self._generate_event_reference(eventfilter)
        self._subscribedEvents[name] = eventfilter
        
        return name

    @dbus.service.method("org.tutorius.ProbeInterface",
                         in_signature='s', out_signature='')
    def unsubscribe(self, address):
        """
        Remove subscription to an event
        @param address string adress returned by subscribe()
        @return None
        """
        if self._subscribedEvents.has_key(address):
            eventfilter = self._subscribedEvents[address]
            eventfilter.remove_handlers()
            self._subscribedEvents.pop(address)

    @dbus.service.signal("org.tutorius.ProbeInterface")
    def eventOccured(self, event):
        # We need no processing now, the signal will be sent
        # when the method exit
        pass

    # The actual method we will call on the probe to send events
    def notify(self, event):
        LOGGER.debug("TProbe :: notify event %s", str(event))
        #Check that this event is even allowed
        if event in self._subscribedEvents.values():
            self.eventOccured(pickle.dumps(event))
        else:
            raise RuntimeWarning("Attempted to raise an unregistered event")

    @dbus.service.signal("org.tutorius.ProbeInterface")
    def addonUpdated(self, addon_address, pickled_diff_dict):
        # Don't do any added processing, the signal will be sent
        # when the method exits
        pass

    def update_action(self, addon_address, diff_dict):
        LOGGER.debug("TProbe :: Trying to update action %s with new property dict %s"%(addon_address, str(diff_dict)))
        # Check that this action is installed
        if addon_address in self._installedActions.keys():
            LOGGER.debug("TProbe :: Updating action %s"%(addon_address))
            self.addonUpdated(addon_address, pickle.dumps(diff_dict))
        else:
            raise RuntimeWarning("Attempted to updated an action that wasn't installed")

    # Return a unique name for this action 
    def _generate_action_reference(self, action):
        # TODO elavoie 2009-07-25 Should return a universal address
        name = action.__class__.__name__
        suffix = 1

        base_name = self._unique_id + PSEP + name
        while self._installedActions.has_key(base_name+str(suffix)):
            suffix += 1

        return base_name + str(suffix)


    # Return a unique name for this event
    def _generate_event_reference(self, event):
        # TODO elavoie 2009-07-25 Should return a universal address
        name = event.__class__.__name__
        #Keep the counter to avoid looping all the time
        suffix = getattr(self, '_event_ref_suffix', 0 ) + 1

        base_name = self._unique_id + PSEP + name
        while self._subscribedEvents.has_key(base_name+str(suffix)):
            suffix += 1
        
        return base_name + str(suffix)

    # ------------------ Helper functions specific to a component --------------
    def find_widget(self, base, path, ignore_errors=True):
        """
        Finds a widget from a base object. Symmetric with retrieve_path

        @param base the parent widget
        @param path fqdn-style target object name

        @return widget found
        """
        return find_widget(base, path, ignore_errors)

    def retrieve_path(self, widget):
        """
        Retrieve the path to access a specific widget.
        Symmetric with find_widget.

        @param widget the widget to find a path for

        @return path to the widget
        """
        return raddr_lookup(widget)

class FrameProbe(TProbe):
    """
    Identical to the base probe except that helper functions are redefined
    to handle the four windows that are part of the Frame. 
    """
    # ------------------ Helper functions specific to a component --------------
    def find_widget(self, base, path, ignore_errors=True):
        """
        Finds a widget from a base object. Symmetric with retrieve_path

        format for the path for the frame should be:

        frame://<panel>/<path>
        where panel: top | bottom | left | right
              path: number[.number]*

        @param base the parent widget
        @param path fqdn-style target object name

        @return widget found
        """
        protocol, p = path.split("://")
        assert protocol == "frame"
 
        window, object_id = p.split("/")
        if window == "top":
            return find_widget(base._top_panel, object_id, ignore_errors)
        elif window == "bottom":
            return find_widget(base._bottom_panel, object_id, ignore_errors)
        elif window == "left":
            return find_widget(base._left_panel, object_id, ignore_errors)
        elif window == "right":
            return find_widget(base._right_panel, object_id, ignore_errors)
        else:
            raise RuntimeWarning("Invalid frame panel: '%s'"%window)

    def retrieve_path(self, widget):
        """
        Retrieve the path to access a specific widget.
        Symmetric with find_widget.

        format for the path for the frame should be:

        frame://<panel>/<path>
        where panel: top | bottom | left | right
              path: number[.number]*

        @param widget the widget to find a path for

        @return path to the widget
        """
        name = []
        child = widget
        parent = widget.parent
        while parent:
            name.append(str(parent.get_children().index(child)))
            child = parent
            parent = child.parent

        name.append("0") # root object itself
        name.reverse()
 
        window = ""
        if parent._position == gtk.POS_TOP:
            window = "top"
        elif parent._position == gtk.POS_BOTTOM:
            window = "bottom"
        elif parent._position == gtk.POS_LEFT:
            window = "left"
        elif parent._position == gtk.POS_RIGHT:
            window = "right"
        else:
            raise RuntimeWarning("Invalid root panel in frame: %s"%str(parent))

        return "frame://"+window+"/"+(".".join(name))

class DesktopProbe(TProbe):
    """
    Identical to the base probe except that helper functions are redefined
    to handle the four windows that are part of the Frame. 
    """
    # ------------------ Helper functions specific to a component --------------
    def find_widget(self, base, path, ignore_errors=True):
        """
        Finds a widget from a base object. Symmetric with retrieve_path

        format for the path for the frame should be:

        desktop://<view>/<path>
        where view: home | group | mesh
              path: number[.number]*

        @param base the parent widget
        @param path fqdn-style target object name

        @return widget found
        """
        protocol, p = path.split("://")
        assert protocol == "desktop"
 
        window, object_id = p.split("/")
        if window == "home":
            return find_widget(base._top_panel, object_id, ignore_errors)
        elif window == "group":
            return find_widget(base._bottom_panel, object_id, ignore_errors)
        elif window == "mesh":
            return find_widget(base._left_panel, object_id, ignore_errors)
        else:
            raise RuntimeWarning("Invalid frame panel: '%s'"%window)
      
        return find_widget(base, path, ignore_errors)

    def retrieve_path(self, widget):
        """
        Retrieve the path to access a specific widget.
        Symmetric with find_widget.

        format for the path for the frame should be:

        desktop://<view>/<path>
        where view: home | group | mesh
              path: number[.number]*

        @param widget the widget to find a path for

        @return path to the widget
        """
        name = []
        child = widget
        parent = widget.parent
        while parent:
            name.insert(0,str(parent.get_children().index(child)))
            child = parent
            parent = child.parent

        name.insert(0,"0") # root object itself
 
        window = ""
        if parent._position == gtk.POS_TOP:
            window = "top"
        elif parent._position == gtk.POS_BOTTOM:
            window = "bottom"
        elif parent._position == gtk.POS_LEFT:
            window = "left"
        elif parent._position == gtk.POS_RIGHT:
            window = "right"
        else:
            raise RuntimeWarning("Invalid root panel in frame: %s"%str(parent))

        return "desktop://"+window+"/"+(".".join(name))


class ProbeProxy:
    """
    ProbeProxy is a Proxy class for connecting to a remote TProbe.

    It provides an object interface to the TProbe, which requires pickled
    strings, across a DBus communication.
    """
    def __init__(self, activityName, unique_id):
        """
        Constructor
        @param activityName generic activity name. Must be a valid dbus bus name.
        @param unique_id unique id specific to an instance of an activity
        """
        LOGGER.debug("ProbeProxy :: Creating ProbeProxy for %s (%d)", activityName, os.getpid())
        LOGGER.debug("ProbeProxy :: Current gobject context: %s", str(gobject.main_context_default()))
        LOGGER.debug("ProbeProxy :: Current gobject depth: %s", str(gobject.main_depth()))
        bus = dbus.SessionBus()
        self._object = bus.get_object(activityName, "/tutorius/Probe/"+str(unique_id))
        self._probe = dbus.Interface(self._object, "org.tutorius.ProbeInterface")
        
        self._actions = {}
        self._edition_callbacks = {}
        # We keep those two data structures to be able to have multiple callbacks
        # for the same event and be able to remove them independently
        # _subscribedEvents holds a list of callback addresses's for each event
        # _registeredCallbacks holds the functions to call for each address
        self._subscribedEvents = {}
        self._registeredCallbacks = {}

        self._object.connect_to_signal("eventOccured", self._handle_signal, dbus_interface="org.tutorius.ProbeInterface")
        self._object.connect_to_signal("addonUpdated", self._handle_update_signal, dbus_interface="org.tutorius.ProbeInterface")

    def _handle_update_signal(self, addon_address, pickled_diff_dict):
        address = str(addon_address)
        diff_dict = pickle.loads(str(pickled_diff_dict))
        LOGGER.debug("ProbeProxy :: Received update property for action %s"%(address))
        # Launch the callback to warn the upper layers of a modification of the addon
        # from a widget inside the activity
        if self._edition_callbacks.has_key(address):
            LOGGER.debug("ProbeProxy :: Executing update callback...")
            self._edition_callbacks[address](address, diff_dict)
    
    def _handle_signal(self, pickled_event):
        event = pickle.loads(str(pickled_event))
        LOGGER.debug("ProbeProxy :: Received Event : %s %s", str(event), str(event._props.items()))

        LOGGER.debug("ProbeProxy :: Currently %d events registered", len(self._registeredCallbacks))
        if self._registeredCallbacks.has_key(event):
            for callback in self._registeredCallbacks[event].values():
                callback(event)
        else:
            for event in self._registeredCallbacks.keys():
                LOGGER.debug("==== %s", str(event._props.items()))
            LOGGER.debug("ProbeProxy :: Event does not appear to be registered")

    def isAlive(self):
        try:
            return self._probe.ping() == "alive"
        except:
            return False

    def __update_action(self, action, callback, editing_cb, address_values):
        address, values = pickle.loads(str(address_values))
        LOGGER.debug("ProbeProxy :: Updating action %s with address %s", str(action), str(address))
        address = str(address)
        # Store the action
        self._actions[address] = action
        # Propagate the action installed callback upwards in the stack
        callback(address)
        # Store the edition callback
        if editing_cb:
            self._edition_callbacks[address] = editing_cb
            editing_cb(address, values)

    def __clear_action(self, address):
        # Remove the action installed at this address
        self._actions.pop(address, None)
        # Remove the edition callback
        self._edition_callbacks.pop(address, None)

    def install(self, action, action_installed_cb, error_cb, is_editing=False, editing_cb=None):
        """
        Install an action on the TProbe's activity
        @param action Action to install
        @param action_installed_cb The callback function to call once the action is installed
        @param error_cb The callback function to call when an error happens
        @param is_editing whether this action comes from the editor
        @param editing_cb The function to execute when the action is updated
                        (this is only done in edition mode)
        @return None
        """
        self._probe.install(pickle.dumps(action),
                            is_editing,
                            reply_handler=save_args(self.__update_action, action, action_installed_cb, editing_cb),
                            error_handler=save_args(error_cb, action))

    def update(self, action_address, newaction, is_editing=False):
        """
        Update an already installed action's properties and run it again
        @param action_address The address of the action to update. This is 
                            provided by the install callback method.
        @param newaction Action to update it with
        @param is_editing whether this action comes from the editor
        @return None
        """
        #TODO review how to make this work well
        if not action_address in self._actions.keys():
            raise RuntimeWarning("Action not installed")
        #TODO Check error handling
        return self._probe.update(action_address, pickle.dumps(newaction._props),
                                    is_editing,
                                    reply_handler=ignore,
                                    error_handler=logError)

    def uninstall(self, action_address, is_editing):
        """
        Uninstall an installed action
        @param action_address The address of the action to uninstall. This address was given
                                on action installation
        @param is_editing whether this action comes from the editor
        """
        if action_address in self._actions:
            self._actions.pop(action_address, None)
            self._probe.uninstall(action_address, is_editing, reply_handler=ignore, error_handler=logError)

    def __update_event(self, event, callback, event_subscribed_cb, address):
        LOGGER.debug("ProbeProxy :: Registered event %s with address %s", str(hash(event)), str(address))
        # Since multiple callbacks could be associated to the same
        # event signature, we will store multiple callbacks
        # in a dictionary indexed by the unique address
        # given for this subscribtion and access this
        # dictionary from another one indexed by event
        address = str(address)

        # We use the event object as a key
        if not self._registeredCallbacks.has_key(event):
            self._registeredCallbacks[event] = {}

        # TODO elavoie 2009-07-25 decide on a proper exception
        # taxonomy
        if self._registeredCallbacks[event].has_key(address):
            # Oops, how come we have two similar addresses?
            # send the bad news!
            raise Exception("Probe subscribe exception, the following address already exists: " + str(address))

        self._registeredCallbacks[event][address] = callback

        # We will keep another dictionary to remember the
        # event that was associated to this unique address
        # Let's copy to make sure that even if the event
        # passed in is modified later it won't screw up
        # our dictionary (python pass arguments by reference)
        self._subscribedEvents[address] = copy.copy(event)

        event_subscribed_cb(address)
        return address

    def __clear_event(self, address):
        LOGGER.debug("ProbeProxy :: Unregistering adress %s", str(address))
        address = str(address)
        # Cleanup everything
        if self._subscribedEvents.has_key(address):
            event = self._subscribedEvents[address]
            
            if self._registeredCallbacks.has_key(event)\
            and self._registeredCallbacks[event].has_key(address):
                self._registeredCallbacks[event].pop(address)

            if self._registeredCallbacks[event] == {}:
                self._registeredCallbacks.pop(event)

            self._subscribedEvents.pop(address)
        else:
            LOGGER.debug("ProbeProxy :: unsubsribe address %s inconsistency : not registered", address)

    def create_event(self, addon_name):
        """
        Create an event on the app side and request the user to fill the
        properties before returning it.

        @param addon_name: the add-on name of the event
        @returns: an eventfilter instance
        """
        return pickle.loads(str(self._probe.create_event(addon_name)))

    def subscribe(self, event, notification_cb, event_subscribed_cb, error_cb):

        """
        Register an event listener
        @param event Event to listen for
        @param notification_cb callable that will be called when the event occurs
        @param event_installed_cb callable that will be called once the event is subscribed to
        @param error_cb callable that will be called if the subscription fails
        @return address identifier used for unsubscribing
        """
        LOGGER.debug("ProbeProxy :: Registering event %s", str(hash(event)))

        # TODO elavoie 2009-07-25 When we will allow for patterns both
        # for event types and sources, we will need to revise the lookup
        # mecanism for which callback function to call
        self._probe.subscribe(pickle.dumps(event),
            reply_handler=save_args(self.__update_event, event, notification_cb, event_subscribed_cb),
            error_handler=save_args(error_cb, event))

    def unsubscribe(self, address):
        """
        Unregister an event listener
        @param address identifier given by subscribe()
        @return None
        """
        LOGGER.debug("ProbeProxy :: Unregister adress %s issued", str(address))
        if address in self._subscribedEvents.keys():
            self.__clear_event(address)
            self._probe.unsubscribe(address,
                                    reply_handler=save_args(self.__clear_event, address),
                                    error_handler=logError)
        else:
            LOGGER.debug("ProbeProxy :: unsubscribe address %s failed : not registered", address)

    def detach(self):
        """
        Detach the ProbeProxy from it's TProbe. All installed actions and 
        subscribed events should be removed.
        """
        for action_addr in self._actions.keys():
            # TODO : Make sure there is a way for each action to be properly
            # uninstalled according to its right edition mode
            self.uninstall(action_addr, True)

        for address in self._subscribedEvents.keys():
            self.unsubscribe(address)

class ProbeManager(object):
    """
    The ProbeManager provides multiplexing across multiple activity ProbeProxies

    For now, it only handles one at a time, though.
    Actually it doesn't do much at all. But it keeps your encapsulation happy
    """
    _LOGGER = logging.getLogger("sugar.tutorius.ProbeManager")

    def __init__(self, proxy_class=ProbeProxy):
        """Constructor
        @param proxy_class Class to use for creating Proxies to activities.
            The class should support the same interface as ProbeProxy. Exists
            to make this class unit-testable by replacing the Proxy with a mock
        """
        dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)

        self._ProxyClass = proxy_class
        self._probes = {}
        self._current_activity = None

        ProbeManager._LOGGER.debug("__init__()")

    def setCurrentActivity(self, activity_id):
        if not activity_id in self._probes:
            raise RuntimeError("Activity not attached, id : %s"%activity_id)
        self._current_activity = activity_id

    def getCurrentActivity(self):
        if self._current_activity == "org.laptop.JournalActivity":
            return self._current_activity
        # TODO : Insert the correct call to remember the current activity,
        # taking the views and frame into account
        current_act = get_model().get_active_activity()
        bundle_path = current_act.get_bundle_path()
        if bundle_path:
            current_act_bundle = ActivityBundle(bundle_path)
            current_act_id = current_act_bundle.get_bundle_id()
            self._current_activity = current_act_id
            return self._current_activity
        else:
            # Temp hack for Journal
            self._current_activity = 'org.laptop.JournalActivity'#current_act.get_bundle_id()
            return self._current_activity

    currentActivity = property(fget=getCurrentActivity, fset=setCurrentActivity)

    def get_source_activity(self, propc):
        if hasattr(propc, "source"):
            return propc.source
        else:
            return None

    def install(self, action, action_installed_cb, error_cb, is_editing=False, editing_cb=None):
        """
        Install an action on the current activity
        @param action Action to install
        @param action_installed_cb The callback to call once the action is installed
        @param error_cb The callback that will be called if there is an error during installation
        @param is_editing whether this action comes from the editor
        @param editing_cb The function to execute when propagating changes on
                        this action (only used when is_editing is true)
        @return None
        """
        activity = self.get_source_activity(action)
        #Allow the creator to look for the current activity
        if activity is None and is_editing:
            activity = self.currentActivity

        if activity:
            return self._first_proxy(activity).install(
                action=action,
                is_editing=is_editing,
                action_installed_cb=action_installed_cb,
                error_cb=error_cb,
                editing_cb=editing_cb)
        else:
            raise RuntimeWarning("No activity attached")

    def update(self, action_address, newaction, is_editing=False):
        """
        Update an already installed action's properties and run it again
        @param action_address Action to update
        @param newaction Action to update it with
        @param is_editing whether this action comes from the editor
        @return None
        """
        probe_id, sep, small_address = action_address.rpartition(PSEP)
        if probe_id:
            probe = self._get_proxy_by_unique_id(probe_id)
            if probe is None:
                #TODO What happens if the Probe is gone??
                raise RuntimeWarning("ProbeProxy containing action address is gone")
            else:
                return probe.update(action_address, newaction, is_editing)

        else:
            raise RuntimeWarning("No activity attached")

    def uninstall(self, action_address, is_editing=False):
        """
        Uninstall an installed action
        @param action_address Action to uninstall
        @param is_editing whether this action comes from the editor
        """
        probe_id, sep, small_address = action_address.rpartition(PSEP)
        if probe_id:
            probe = self._get_proxy_by_unique_id(probe_id)
            if probe is None:
                logging.warning(
                    "ProbeProxy for address %s is gone, assuming uninstall not necessary" % \
                        action_address)
            else:
                return probe.uninstall(action_address, is_editing)

        else:
            raise RuntimeWarning("No activity attached")

    def create_event(self, addon_name):
        """
        Create an event on the app side and request the user to fill the
        properties before returning it.

        @param addon_name: the add-on name of the event
        @returns: an eventfilter instance
        """
        if self.currentActivity:
            return self._first_proxy(self.currentActivity).create_event(addon_name)
        else:
            raise RuntimeWarning("No activity attached")

    def subscribe(self, event, notification_cb, event_subscribed_cb, error_cb):
        """
        Register an event listener
        @param event Event to listen for
        @param notification_cb callable that will be called when the event occurs
        @param subscribe_cb callable that will be called once the action has been
                            installed
        @param error_cb callable that will be called if an error happens during
                        installation
        @return address identifier used for unsubscribing
        """
        activity = self.get_source_activity(event)

        if activity:
            return self._first_proxy(activity).subscribe(event, notification_cb,\
                                                            event_subscribed_cb, error_cb)
        else:
            raise RuntimeWarning("No activity attached")

    def unsubscribe(self, address):
        """
        Unregister an event listener
        @param address identifier given by subscribe()
        @return None
        """
        probe_id, sep, small_address = address.rpartition(PSEP)
        if probe_id:
            probe = self._get_proxy_by_unique_id(probe_id)
            if probe is None:
                logging.warning(
                    "ProbeProxy for address %s is gone, assuming unsubscribe not necessary" % \
                        address)
            else:
                return probe.unsubscribe(address)
        else:
            raise RuntimeWarning("No activity attached")

    def register_probe(self, process_name, unique_id):
        """ Adds a probe to the known probes, to be used by a tutorial. 

            A generic name for a process (like an Activity) is passed
            so that the execution of a tutorial will use that generic
            name. However, a unique id is also passed to differentiate
            between many instances of the same process.
            
            @param process_name The generic name of a process
            @param unique_id The unique identification associated to this 
                             process
        """
        # Converting dbus.String back to Python strings
        process_name = str(process_name)
        unique_id = str(unique_id)
        ProbeManager._LOGGER.debug("register_probe(%s,%s)", process_name, unique_id)
        if process_name not in self._probes: 
            self._probes[process_name] = [(unique_id,self._ProxyClass(process_name, unique_id))]
        else:
            self._probes[process_name].append((unique_id,self._ProxyClass(process_name, unique_id)))
        

    def unregister_probe(self, unique_id):
        """ Remove a probe from the known probes.
            
            @param unique_id The unique identification associated to this 
                             process
        """
        unique_id = str(unique_id)
        ProbeManager._LOGGER.debug("unregister_probe(%s)", unique_id)
        for process_name, proxies in self._probes.items():
            for id, proxy in proxies:
                if unique_id == id:
                    proxy.detach()
                    proxies.remove((id,proxy))
                if len(proxies) == 0:
                    self._probes.pop(process_name)

    def get_registered_probes_list(self, process_name=None):
        if process_name == None:
            probe_list = []
            for probes in self._probes.itervalues():
                probe_list.extend(probes)
            return probe_list
        else:
            if process_name in self._probes:
                return self._probes[process_name]
            else:
                return []

    def _first_proxy(self, process_name):
        """
        Returns the oldest probe connected under the process_name
        @param process_name The generic process name under which the probe
                            is connected
        """
        if process_name in self._probes:
            return self._probes[process_name][0][1]
        else:
            raise RuntimeWarning("No activity attached under '%s'", process_name)

    def _get_proxy_by_unique_id(self, unique_id):
        """
        Get a probe proxy by it's unique id.
        @param unique_id The unique id of the probe
        @return the probe proxy or None if not found
        """
        for probes in self._probes.values():
            for id, probe in probes:
                if id == unique_id:
                    return probe
        return None