ginsfsm / ginsfsm / gobj.py

The default branch has multiple heads

  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
# -*- encoding: utf-8 -*-
"""
These module provides support for:

* creating new derived :class:`GObj` class with your
  :term:`simple-machine`.
* creating :term:`gobj`'s with :func:`create_gobj` factory function.

The :class:`GObj` class provides support for:

* sending events:

    * sending events by direct delivery: :meth:`GObj.send_event`.
    * sending events by queues: :meth:`GObj.post_event`.
    * sending events to subscribers: :meth:`GObj.broadcast_event`.

* receiving events:

    * directly from another :term:`gobj`'s who knows you.
    * subscribing to events by the :meth:`GObj.subscribe_event` method.
    * you can filtering events being broadcasting with
      :meth:`GObj.set_owned_event_filter` method.

.. autoclass:: Event
    :members:

.. autoclass:: GObj
    :members: start_up, create_gobj, destroy_gobj,
        send_event, post_event, broadcast_event,
        subscribe_event, delete_subscription, set_owned_event_filter,
        find_unique_gobj,
        overwrite_parameters, overwrite_few_parameters

    .. attribute:: name

        My name.

        Set by :meth:`create_gobj`.

    .. attribute:: parent

        My parent, destination of my events... or not.

        Set by :meth:`create_gobj`.

    .. attribute:: dl_childs

        Set of my gobj childs. Me too like be parent!.


    .. method:: set_new_state

        Set a new state.
        Method to used inside actions, to force the change of state.

        :param new_state: new state to set.

        ``new_state`` must match some of the state names of the
        machine's :term:`state-list` or a :exc:`StateError` exception
        will be raised.

    .. method:: get_current_state

        Return the name of the current state.

        If there is no state it returns ``None``.

    .. method:: get_input_event_list

       Return the list with the :term:`input-event`'s names.

    .. method:: get_output_event_list

       Return the list with the :term:`output-event`'s names.


.. autoexception:: ParentError

.. autoexception:: DestinationError

.. autoexception:: GObjError

.. autoexception:: EventError

.. autoexception:: StateError

.. autoexception:: MachineError

.. autoexception:: EventNotAcceptedError

.. autoexception:: QueueError

"""
import threading
import logging
import re
import ginsfsm.globals  # made it import available

from ginsfsm.compat import string_types

from ginsfsm.smachine import (
    SMachine,
    EventError,
    EventNotAcceptedError,  # made it import available
    StateError,  # made it import available
    MachineError,  # made it import available
)

from ginsfsm.gconfig import (
    GConfig,
    add_gconfig,
)


class ParentError(Exception):
    """ Raised when parent is already defined."""


class DestinationError(Exception):
    """ Raised when destination is not know."""


class GObjError(Exception):
    """ Raised when an object is not a GObj type, and must be!."""


class GAplicError(Exception):
    """ Raised when an object has not a GAplic, and must be!.
        If you use unique named gobjs, you need a gaplic environment.
    """


class QueueError(Exception):
    """ Raised when there is no support for enqueue objs, i.e., use of
        GObj.post_event() method.
    """


class Event(object):
    """ Collect event properties. This is the argument received by actions.

    :param destination: destination gobj whom to send the event.
    :param event_name: event name.
    :param source: list with path of gobj sources. Firt item ``source[0]``
        is the original sender gobj. Last item ``source[-1]`` is the
        nearest sender gobj.
    :param kw: keyword arguments with associated data to event.
    """
    # For now, event_factory is private. Automatically using by send_event...
    #Use the :meth:`GObj.event_factory` factory function to create Event
    #instances.
    def __init__(self, destination, event_name, source, **kw):
        self.destination = destination
        self.event_name = event_name
        if not isinstance(source, (list, tuple)):
            source = [source]
        self.source = source
        self.kw = kw
        self.__dict__.update(**kw)

    def __str__(self):
        return 'Event object: name %s, destination: %s, kw: %s' % (
            self.event_name,
            self.destination,
            self.kw,
        )


class _Subscription(object):
    """ Collect subscriber properties
    `event_name`: event name.
    `subscriber_gobj`: subcriber gobj to sending event.
    `kw`: event parameters
    """
    def __init__(self, event_name, subscriber_gobj, **kw):
        self.event_name = event_name
        self.subscriber_gobj = subscriber_gobj
        self.kw = kw
        self.__dict__.update(**kw)


# Attributes that a gaplic can update.
GOBJ_GCONFIG = {
    'gaplic': [None, None, 0, None, ''],
    're_name': [str, None, 0, None,
        'Regular expression name to search the gobj in the resource tree.'
        'Used in Pyramid traversal.'],
    'ini_settings': [dict, {}, 0, None,
        'The ini settings will be set to all new created gobj'
        ' by overwrite_parameters() function'],
    # trace_mach is inherited from SMachine.
    'trace_mach': [bool, False, 0, None, 'Display simple machine activity'],
    # logger is inherited from SMachine.
    'logger': [None, None, 0, None, ''],
    'create_gobj': [None, None, 0, None, ''],
    'destroy_gobj': [None, None, 0, None, ''],
    'enqueue_event': [None, None, 0, None, ''],
    '_increase_inside': [None, None, 0, None, ''],
    '_decrease_inside': [None, None, 0, None, ''],
    '_tab': [None, None, 0, None, ''],
}

_urandom_name = 0


class GObj(SMachine, GConfig):
    """ Well, yes, I'm a very simple brain. Only a machine.
    But write a good FSM, and I never fail you. Derive me, and write my FSM.

    Sample GObj::

        class MyGObj(GObj):
            def __init__(self):
                GObj.__init__(self, FSM, GCONFIG)

            def start_up(self):
                ''' Initialization zone.'''

    :param fsm: FSM :term:`simple-machine`.
    :param gconfig: GCONFIG :term:`gconfig-template`.
    """

    # name and parent attributes must be Location-Aware Resources
    # for Pyramid framework compatibility:
    # changed to point to __name__ and __parent__.
    @property
    def name(self):
        return self.__name__

    @name.setter
    def name(self, name):
        self.__name__ = name

    @property
    def parent(self):
        return self.__parent__

    @parent.setter
    def parent(self, parent):
        self.__parent__ = parent

    def __init__(self, fsm, gconfig=None):
        SMachine.__init__(self, fsm)

        self.name = ''
        """ My name.
        Set by :meth:`create_gobj`
        """
        self.parent = None
        """My parent, destination of my events... or not.
        Set by :meth:`create_gobj`
        """
        self.dl_childs = set()        # my childs... me too like be parent.
        """List of gobj childs.
        """
        self.owned_event_filter = None  # TODO debe ser una lista de filtros
        """Filter to broadcast_event function to check the owner of events.
        """

        self._dl_subscriptions = set()      # uauuu, how many fans!!
        self._some_subscriptions = False
        self._destroyed = False  # mark as destroyed when destroy_gobj()
        self._re_compiled_name = ''  # re compiled name when using re_name
        self.re_matched_name = ''  # matched name when using re_name

        gconfig = add_gconfig(gconfig, GOBJ_GCONFIG)
        GConfig.__init__(self, gconfig)

    def __str__(self):
        name = self.name
        parent = self.parent
        while(parent):
            name = parent.name + '.' + name
            parent = parent.parent
        return "%s" % (name)

    def __repr__(self):
        name = "%s:%s" % (self.__class__.__name__, self.name)
        parent = self.parent
        while(parent):
            parent_name = "%s:%s" % (parent.__class__.__name__, parent.name)
            name = parent_name + '.' + name
            parent = parent.parent
        return "%s" % (name)

        return "%s:%s" % (self.__class__.__name__, self.__name__)

    def create_gobj(self, name, gclass, parent, **kw):
        """ Factory function to create gobj's instances.

        :param name: Name of the gobj.

        :param gclass: `gclass` is the :class:`GObj` type used to create
            the new gobj. It's must be a derived class of :class:`GObj`
            otherwise a :exc:`GObjError` exception will be raised.

        :param parent: parent of the new :term:`gobj`. ``None`` if it has no
            parent. If it's not ``None``, then must be a derived class
            of :class:`GObj` otherwise a :exc:`GObjError`
            exception will be raised.

        :param kw: Attributes that are added to the new :term:`gobj`.
            All the keyword arguments used in the function
            **are added as attributes** to the created :term:`gobj`,
            You must consult the attributes supported
            by each `gclass` type.
            The attributes must be defined in the gclass GCONFIG,
            otherwise they are ignored.
            TODO: doc re_name

        :rtype: new gobj instance.

        The factory funcion does:

        * Add the :term:`gobj` to their parent child list
          :attr:`GObj.dl_childs`,
        * If it's a :term:`named-gobj` call the
          :meth:`GObj.register_unique_gobj`.
        * Call :meth:`GObj.start_up`.
        * Add to the :term:`gobj` several attributes:

            * **name**: name of the created :term:`gobj`.
            * **parent**: the parent :term:`gobj` of the created :term:`gobj`.

        .. warning:: the :meth:`GObj.register`, :meth:`GObj.deregister`
            and :meth:`GObj.search` methods must be override and supplied by a
            superior instance, like :term:`gaplic`,
            otherwise :term:`named-gobj` objects cannot be used.
        """

        if gclass is None:
            raise GObjError(
                '''ERROR create_gobj(): No GObj class supplied.''')
        if not issubclass(gclass, GObj):
            raise GObjError(
                '''ERROR create_gobj(): class '%s' is NOT a GObj subclass''' %
                (repr(gclass)))

        if parent is not None:
            if not isinstance(parent, GObj):
                raise GObjError(
                    '''ERROR create_gobj(): parent '%s' '''
                    '''is NOT a GObj subclass''' % (
                        repr(gclass)))

        if self.logger:
            self.logger.debug("Creating '%s'" % name)

        gobj = gclass()

        if name:
            gobj.name = name

        # Who wins? arguments or file ini settings?
        gobj.write_parameters(**kw)
        if self.ini_settings is not None:
            # ini global win.
            gobj.overwrite_parameters(0, **self.ini_settings)

        if parent is not None:
            parent._add_child(gobj)

        if gobj.re_name:
            gobj._re_compiled_name = re.compile(gobj.re_name)

        gobj.start_up()

        if self.logger:
            self.logger.debug("Created  '%s'" % repr(gobj))

        return gobj

    def get_random_name(self, prefix):
        global _urandom_name
        _urandom_name += 1
        return '%s_%d' % (prefix, _urandom_name)

    def create_random_named_gobj(self, name, gclass, parent, **kw):
        # TODO: perhaps it's better to use this
        # as '__unique_name__' attributes in gaplic
        """ Same as :meth:`create_gobj` function,
        but it generates a random name if name it's not supplied.
        """
        name = self.get_random_name(name)
        return self.create_gobj(name, gclass, parent, **kw)

    def destroy_gobj(self, gobj):
        """ Destroy a gobj
        """
        if gobj.parent is not None:
            gobj.parent._remove_child(gobj)

        while len(gobj.dl_childs):
            try:
                for child in gobj.dl_childs:
                    self.destroy_gobj(child)
            except RuntimeError:
                pass  # "Set changed size during iteration" is OK

        gobj.delete_all_subscriptions()
        gobj._destroyed = True
        del gobj

    def start_up(self):
        """ Initialization zone.

        Well, the __init__ method is used to build the FSM so I need another
        function to initialize the new gobj.
        Please, **override me**, and write here all the code you need to
        start up the machine: create your owns childs, etc.
        This function is called by :meth:`create_gobj`
        after creating the gobj instance.
        """

    def _resolv_destination(self, destination):
        """ Resolv the destination :term:`gobj`.

        :param destination: destination gobj whom to send the event.
        :rtype: Return the destination :term:`gobj` instance.

        If ``destination`` is a `string`then
        it will be search in the current :term:`gaplic` domain
        with :meth:`find_unique_gobj` method.
        If it is not found a :exc:`DestinationError` exception will be raised.
        """
        if not (isinstance(destination, string_types) or
                isinstance(destination, GObj)):
            raise DestinationError(
                '_resolv_destination() BAD TYPE destination %s in %s' %
                (repr(destination), repr(self)))

        if isinstance(destination, string_types):
            if not self.gaplic:
                raise GAplicError(
                    '_resolv_destination() WITHOUT GAPLIC, %s in %s' %
                    (repr(destination), repr(self))
                )
            named_gobj = self.gaplic.find_unique_gobj(destination)
            if not named_gobj:
                raise DestinationError(
                    '_resolv_destination() destination %s NOT FOUND in %s'
                    '\nCurrent named-gobjs: %s'
                    % (repr(destination),
                       repr(self),
                       ' '.join(sorted(self.gaplic.get_unique_named_gobjs())),
                       )
                    )
            destination = named_gobj
        return destination

    def _event_factory(self, destination, event, **kw):
        """ Factory to create Event instances.

        :param destination: destination gobj whom to send the event.
        :param event: an :term:`event`.
        :param kw: keyword arguments with associated data to event.
        :rtype: Return Event instance.

        ``event`` must be a `string` or :class:`Event` types, otherwise a
        :exc:`EventError` will be raised.

        If ``event`` is an :class:`Event` instance, a new :class:`Event`
        duplicated instance is returned, but it will be updated with
        the new ``destination`` and ``kw`` keyword arguments.

        .. note::
            All the keyword arguments used in the factory function
            **are added as attributes** to the created :term:`event` instance.
            You must consult the attributes supported by each machine's event.
        """
        if not (isinstance(event, string_types) or
                isinstance(event, Event)):
            raise EventError('_event_factory() BAD TYPE event %s in %s' %
                (repr(event), repr(self)))

        # if destination is not None:
        if not (isinstance(destination, string_types) or
                isinstance(destination, GObj)):
            raise DestinationError(
                '_event_factory() BAD TYPE destination %s in %s' %
                (repr(destination), repr(self)))

        if isinstance(event, Event):
            # duplicate the event
            if event.source[-1] != self:
                event.source.append(self)
            event = Event(event.destination, event.event_name,
                    event.source, **event.kw)
            if len(kw):
                event.__dict__.update(**kw)
            if destination is not None:
                event.destination = destination
        else:
            event = Event(destination, event, self, **kw)

        return event

    def send_event(self, destination, event, **kw):
        """
        Send **right now** the :term:`event` ``event`` to the
        destination gobj ``destination``, with associated data ``kw``.

        :param event: :term:`event` to send.
        :param destination: destination :term:`gobj` of the event.
        :param kw: keyword argument with data associated to event.
        :rtype: return the returned value from the executed action.

            .. note::
                All the keyword arguments **are added as attributes** to
                the sent :term:`event`.

        If ``event`` argument is a string type, then the internal
        :func:`_event_factory` function  is called, to create a :class:`Event`
        instance.

        The algorithm to calculate the destination :term:`gobj` will be:

            1. ``destination`` if the ``destination`` argument is not ``None``.
            2. ``event.destination`` if ``event`` is a Event instance and
               ``event.destination`` is not ``None``.
            3. If ``destination`` and ``event.destination`` is None, then
               a :exc:`DestinationError` exception will be raised.

        If the :term:`event-name` exists in the machine, but it's not accepted
        by the current state, then no exception is raised but the
        function **returns** :exc:`EventNotAcceptedError`.

            .. note:: The :meth:`inject_event` method doesn't
                **raise** :exc:`EventNotAcceptedError` because a
                :term:`machine` should run under any circumstances.
                In any way an action can raise exceptions.

        If ``destination`` is a :term:`named-gobj`,
        i.e. a string, then the gobj will be search
        with :meth:`search_gobj` method.
        This method must be supplied and override by superior instance,
        like :term:`gaplic`.

        ``destination`` must be a `string` or :class:`GObj` types, otherwise a
        :exc:`GObjError` will be raised.

        If ``destination`` if the recipient runs
        in another :term:`gaplic` that the sender,
        the :meth:`post_event` method will be used.

        ``event`` must be a `string` or :class:`Event` types, otherwise a
        :exc:`EventError` will be raised.

        If ``event`` is an :class:`Event` instance, a new :class:`Event`
        duplicated instance is returned, but it will be updated with
        the new ``destination`` and ``kw`` keyword arguments.

        .. note::
            All the keyword arguments used in the factory function
            **are added as attributes** to the created :term:`event` instance.
            You must consult the attributes supported by each machine's event.
        """
        destination = self._resolv_destination(destination)
        event = self._event_factory(destination, event, **kw)
        if destination._destroyed:
            logging.error("GObj ERROR internal: "
                "sending event %s to a destroyed gobj", event.event_name
            )
            return -1

        if self.gaplic:
            cur_ident = threading.current_thread().ident
            cur_name = threading.current_thread().name
            if self.gaplic._thread_ident and \
                    cur_ident != self.gaplic._thread_ident:
                logging.error("ERROR internal: "
                    "current thread '%s' is not the sender thread '%s'",
                    cur_name, self.gaplic.thread_name
                )

            dst_ident = destination.gaplic._thread_ident
            if dst_ident and cur_ident != dst_ident:
                return self.post_event(destination, event)

        ret = destination.inject_event(event)
        return ret

    def post_event(self, destination, event, **kw):
        """ Post the event in the event queue. To use with domains like
        :term:`gaplic` because it's necessary to override :meth:`enqueue_event`
        in order to supply a queue system.

        :param event: :term:`event` to send.
        :param destination: destination :term:`gobj` of the event.
        :param kw: keyword argument with data associated to event.

            .. note::
                All the keyword arguments **are added as attributes** to
                the sent :term:`event`.

        ``destination`` must be a `string` or :class:`GObj` types, otherwise a
        :exc:`GObjError` will be raised.

        ``event`` must be a `string` or :class:`Event` types, otherwise a
        :exc:`EventError` will be raised.

        If ``event`` is an :class:`Event` instance, a new :class:`Event`
        duplicated instance is returned, but it will be updated with
        the new ``destination`` and ``kw`` keyword arguments.

        .. note::
            All the keyword arguments used in the factory function
            **are added as attributes** to the created :term:`event` instance.
            You must consult the attributes supported by each machine's event.
        """
        event = self._event_factory(destination, event, **kw)
        self.enqueue_event(event)

    def enqueue_event(self, event):
        """ Enqueue a event to send by queue system.
        To be overriden by :term:`gaplic` or similar
        """
        raise QueueError('enqueue_event() no support in %s' % (repr(self)))

    def broadcast_event(self, event, **kw):
        """ Broadcast the ``event`` to all subscribers.

        :param event: :term:`event` to send.
        :param kw: keyword argument with data associated to event.

            .. note::
                All the keyword arguments **are added as attributes** to
                the sent :term:`event`.

        Use this function when you don't know who are your event's clients,
        when you don't know the :term:`gobj` destination of
        your :term:`output-event`'s

        If there is no subscriptors, the event is not sent.

        When an event has several subscriptors, there is a mechanism called
        :term:`event-filter` that allows to a subcriptor to own the event
        and no further spread by more subscribers.

        The filter function set by :meth:`set_owned_event_filter` method,
        is call with the returned value of an :term:`action` as argument:
        If the filter function return ``True``, the event is owned, and the
        :func:`ginsfsm.gobj.GObj.broadcast_event` function doesn't continue
        sending the event to other subscribers.

        .. note:: If :func:`ginsfsm.gobj.GObj.broadcast_event` function
           uses :func:`ginsfsm.gobj.GObj.post_event`,
           the :term:`event-filter` cannot be applied.
        """
        if self._some_subscriptions:
            subscriptions = self._dl_subscriptions.copy()
            sended_gobj = set()  # don't repeat events
            for sub in subscriptions:
                if sub.subscriber_gobj in sended_gobj:
                    continue

                oevent = self._event_factory(sub.subscriber_gobj, event, **kw)
                if None in sub.event_name or \
                        oevent.event_name in sub.event_name:

                    if hasattr(sub, 'change_original_event_name'):
                        oevent.name = sub.change_original_event_name

                    ret = False
                    if hasattr(sub, 'use_callback'):
                        # outside world
                        if hasattr(sub, 'callback_fn'):
                            callback = sub.callback_fn
                            if hasattr(sub, 'callback_param'):
                                callback_param = sub.callback_param
                                callback(callback_param)
                            else:
                                callback()
                            ## TODO: callback(oevent): debería convertir
                            # a oevent en json? pues claro que sí.
                            # No obligues a que te conozcan
                            # Eso sí: que acepten 1 param.
                            # MEJORA:
                            # Pero por otro, si ya tienen que conocer
                            # el gobj-ecosistema para poder enviar eventos.
                            # Si son casi hermanos, no estamos tratando
                            # con entes de otro ecosistema físicamente externo,
                            # entre los que sí se entiende, y no puede ser
                            # de otra manera, que se tengan que intercambiar
                            # los datos en formato aséptico, es decir, json.

                            # Al callback no le pasamos el oevent,
                            # él ya sabe a qué evento se ha suscrito.
                            # Le pasamos el parámetro que él ha elegido.
                        else:
                            self.logger.error(
                                "ERROR use_callback without callback_fn"
                            )
                    else:
                        # gobj-ecosistema
                        if hasattr(sub, 'use_post_event'):
                            ret = self.post_event(sub.subscriber_gobj, oevent)
                        else:
                            ret = self.send_event(sub.subscriber_gobj, oevent)
                    sended_gobj.add(sub.subscriber_gobj)
                    if self.owned_event_filter:
                        ret = self.owned_event_filter(ret)
                        if ret is True:
                            return True  # propietary event, retorno otra cosa?

    def subscribe_event(self, event_name, subscriber_gobj, **kw):
        """ Subscribe to event.

        :param event_name: string event name or tuple/list of string
            event names.  If ``event_name`` is ``None`` then it subscribe
            to all events. If it's not ``None`` then it must be a valid event
            name from the :term:`output-event` list,
            otherwise a :exc:`EventError` will be raised.
        :param subscriber_gobj: subscriber obj that wants receive the event.
            If ``subscriber`` is ``None`` then the subscriber is the parent.
            ``subscriber_gobj`` must be `None` or a `string` or a
            :class:`GObj` types, otherwise a :exc:`GObjError` will be raised.
        :param kw: keyword argument with data associated to subscription.

        **kw** values:
            * `use_post_event`:
              You must set it to `True` in order to broadcast the events
              using `post-event` instead of `send-event`.

            * `change_original_event_name`:
              You can change the output original event name..

        """
        if subscriber_gobj is None:
            subscriber_gobj = self.__parent__

        if subscriber_gobj is not None:
            if not (isinstance(subscriber_gobj, string_types) or
                    isinstance(subscriber_gobj, GObj)):
                raise GObjError(
                    'subcribe_event(): BAD TYPE subscriber_gobj %s in %s'
                    % (repr(subscriber_gobj), repr(self)))

            if isinstance(subscriber_gobj, string_types):
                if not self.gaplic:
                    raise GAplicError(
                        'subscribe_event() WITHOUT GAPLIC, %s in %s' %
                        (repr(subscriber_gobj), repr(self)))
                named_gobj = self.gaplic.find_unique_gobj(subscriber_gobj)
                if not named_gobj:
                    raise GObjError(
                        'subscribe_event() subscriber NOT FOUND in %s'
                        '\nCurrent named-gobjs: %s'
                        % (repr(self),
                           ' '.join(sorted(
                                self.gaplic.get_unique_named_gobjs())),
                           )
                        )
                subscriber_gobj = named_gobj

        output_events = self.get_output_event_list()

        if not isinstance(event_name, (list, tuple)):
            event_name = (event_name,)

        for name in event_name:
            if name is None:
                continue
            if not isinstance(name, string_types):
                raise EventError(
                    'subscribe_event(): event %s is not string in %s'
                    % (repr(name), repr(self)))

            if name not in output_events:
                raise EventError(
                    'subscribe_event(): output-event %s not defined in'
                    ' %s' % (repr(event_name), repr(self)))

        existing_subs = self._find_subscription(event_name, subscriber_gobj)
        if existing_subs:
            # avoid duplication subscriptions
            self.delete_subscription(event_name, subscriber_gobj)
        subscription = _Subscription(event_name, subscriber_gobj, **kw)
        self._dl_subscriptions.add(subscription)
        self._some_subscriptions = True

    def _find_subscription(self, event_name, subscriber_gobj):
        """ Find a subscription by event_name and subscriber gobj.
        Internal use to avoid duplicates subscriptions.
        """
        if not isinstance(event_name, (list, tuple)):
            event_name = (event_name,)
        for sub in self._dl_subscriptions:
            if list(sub.event_name).sort() == list(event_name).sort() and \
                sub.subscriber_gobj == subscriber_gobj:
                    return sub

    def delete_subscription(self, event_name, subscriber_gobj):
        """ Remove `subscription`.

        :param event_name: string event name or tuple/list of string
            event names.
        :param subscriber_gobj: subscriber gobj.
        """
        existing_subs = self._find_subscription(event_name, subscriber_gobj)
        if existing_subs:
            self._dl_subscriptions.remove(existing_subs)
            if len(self._dl_subscriptions) == 0:
                self._some_subscriptions = False
            return True
        logging.error("ERROR delete_subscription(): '%s' NOT FOUND " %
            event_name)

        return False

    def delete_all_subscriptions(self):
        """ Remove all subscriptions.
        """
        while len(self._dl_subscriptions):
            try:
                for subs in self._dl_subscriptions:
                    self._dl_subscriptions.remove(subs)
            except RuntimeError:
                pass  # "Set changed size during iteration" is OK

    def set_owned_event_filter(self, filter):
        """ Set a filter function to be used
        by :meth:`broadcast_event` function to check the owner of events.
        """
        self.owned_event_filter = filter

    def _add_child(self, gobj):
        """ Add a child ``gobj``.

        :param gobj: :term:`gobj` child to add.

        Raise :exc:`ParentError` is ``gobj`` already has a parent.
        This function is called by :meth:`create_gobj`
        after creating the gobj instance.
        """
        if gobj.parent:
            raise ParentError(
                '_add_child(): gobj already has parent in %s' % (repr(self)))
        self.dl_childs.add(gobj)
        gobj.parent = self

    def _remove_child(self, gobj):
        """ Remove the child ``gobj``.

        :param gobj: :term:`gobj` child to remove.

        This function is called by :meth:`destroy_gobj`.
        """
        if gobj in self.dl_childs:
            self.dl_childs.remove(gobj)
            gobj.parent = None

    def __getitem__(self, name):
        """ Enable gobjs tree to work with Pyramid traversal URL dispatch.
        """
        if name is None:
            raise KeyError('No such child named None')
        for gobj in self.dl_childs:
            if gobj.re_name:
                if gobj._re_compiled_name.match(name) is not None:
                    # this gobj has been got as re_matched_name.
                    gobj.re_matched_name = name
                    return gobj
            else:
                if gobj.name == name:
                    return gobj
        raise KeyError('No such child named %s' % name)

    def __iter__(self):
        """ Iterates over child elements.
        """
        return self.dl_childs.__iter__()

    # helper for pyramid
    def resource_path(self, separator='/'):
        """ Same as Pyramid traversal.resource_path, but without escaping.
        """
        path = [loc.__name__ or '' for loc in lineage(self)]
        path.reverse()
        return path and separator.join([x for x in path]) or separator

    def overwrite_parameters(self, level, **settings):
        """ The parameters in settings must be defined in the gobj.

        :param level: level trace of childs.
            indicates the depth of the childs as far to change.

            * `0` only this gobj.
            * `-1` all tree of childs.

        :param settings: parameters and their values.

        The settings are filtered by the named-gobj
        or gclass name of this gobj.
        The parameter name in settings, must be a dot-named,
        with the first item being the named-gobj o gclass name.
        """
        parameters = self.filter_parameters(**settings)
        self.write_parameters(**parameters)
        if level:
            for child in self.dl_childs:
                child.overwrite_parameters(level - 1, **settings)

    def overwrite_few_parameters(self, parameter_list, **settings):
        """ The parameters in settings must be defined in the gobj.

        :param parameter_list: write only the parameters in ``parameter_list``.

        :param settings: parameters and their values.

        The settings are filtered by the named-gobj
        or gclass name of this gobj.
        The parameter name in settings, must be a dot-named,
        with the first item being the named-gobj o gclass name.
        """
        parameters = self.filter_parameters(**settings)
        self.write_few_parameters(parameter_list, **parameters)


def inside(resource1, resource2):
    """Is ``resource1`` 'inside' ``resource2``?  Return ``True`` if so, else
    ``False``.

    ``resource1`` is 'inside' ``resource2`` if ``resource2`` is a
    :term:`lineage` ancestor of ``resource1``.  It is a lineage ancestor
    if its parent (or one of its parent's parents, etc.) is an
    ancestor.
    """
    while resource1 is not None:
        if resource1 is resource2:
            return True
        resource1 = resource1.__parent__

    return False


def lineage(resource):
    """
    Return a generator representing the :term:`lineage` of the
    :term:`resource` object implied by the ``resource`` argument.  The
    generator first returns ``resource`` unconditionally.  Then, if
    ``resource`` supplies a ``__parent__`` attribute, return the resource
    represented by ``resource.__parent__``.  If *that* resource has a
    ``__parent__`` attribute, return that resource's parent, and so on,
    until the resource being inspected either has no ``__parent__``
    attribute or which has a ``__parent__`` attribute of ``None``.
    For example, if the resource tree is::

      thing1 = Thing()
      thing2 = Thing()
      thing2.__parent__ = thing1

    Calling ``lineage(thing2)`` will return a generator.  When we turn
    it into a list, we will get::

      list(lineage(thing2))
      [ <Thing object at thing2>, <Thing object at thing1> ]
    """
    while resource is not None:
        yield resource
        # The common case is that the AttributeError exception below
        # is exceptional as long as the developer is a "good citizen"
        # who has a root object with a __parent__ of None.  Using an
        # exception here instead of a getattr with a default is an
        # important micro-optimization, because this function is
        # called in any non-trivial application over and over again to
        # generate URLs and paths.
        try:
            resource = resource.__parent__
        except AttributeError:
            resource = None
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.