Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 222 lines (168 sloc) 6.833 kb
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
""" Context holding multiple subcontexts.
"""

from itertools import chain
from UserDict import DictMixin

from traits.api import (Instance, List, Str, Undefined, implements,
    on_trait_change)
from traits.protocols.api import adapt

from data_context import DataContext, ListenableMixin, PersistableMixin
from i_context import (ICheckpointable, IListenableContext,
    IPersistableContext, IRestrictedContext)
from utils import safe_repr



class MultiContext(ListenableMixin, PersistableMixin, DictMixin):
    """ Wrap several subcontexts.
"""

    implements(ICheckpointable, IListenableContext, IPersistableContext, IRestrictedContext)

    # The name of the context.
    name = Str("multidummy")

    # The underlying dictionary.
    subcontexts = List(Instance(IRestrictedContext, factory=DataContext,
        adapt='yes'))


    def __init__(self, *subcontexts, **traits):
        subcontexts = list(subcontexts)
        super(MultiContext, self).__init__(subcontexts=subcontexts, **traits)


    #### IContext interface ####################################################

    def __contains__(self, key):
        for c in self.subcontexts:
            if key in c:
                return True
        return False

    def __delitem__(self, key):
        """ Remove the given key with [] access.

Only deletes the first instance of the key.

Parameters
----------
key : str

Raises
------
KeyError if the kew is not available in the context.
"""
        for c in self.subcontexts:
            try:
                del c[key]
                return
            except KeyError:
                continue
        raise KeyError(key)

    def __getitem__(self, key):
        for c in self.subcontexts:
            try:
                return c[key]
            except KeyError:
                continue
        raise KeyError(key)

    def __setitem__(self, key, value):
        """ Set item with [] access.

The first subcontext which allows the key/value pair will get it. If an
earlier subcontext has the key, but does not allow the assignment, then
that key will be deleted. Later contexts with the key will be untouched.

If the key/value pair cannot be assigned to anything, no deletion will
take place.

Parameters
----------
key : str
value : object

Raises
------
ValueError if the key is not permitted to be assigned that value.
"""

        # Let subtypes dictate compatibility independently of contained contexts
        if not self.allows(value, key):
            raise ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value)))

        set = False
        blocking_contexts = []
        for c in self.subcontexts:
            if not set:
                if c.allows(value, key):
                    if key in c:
                        added = []
                        current_value = c[key]
                        try:
                            is_modified = bool(current_value != value)
                        except Exception:
                            is_modified = current_value is not value
                        if is_modified:
                            modified = [key]
                            c[key] = value
                        else:
                            modified = []
                    else:
                        added = [key]
                        modified = []
                        c[key] = value

                    set = True
                    break
                elif key in c:
                    # Record this context as blocking access to the final
                    # location of the value.
                    blocking_contexts.append(c)

        # Remove all blocking instances.
        for c in blocking_contexts:
            del c[key]

        if not set:
            raise ValueError('Disallowed mapping: %s = %s' % (key, safe_repr(value)))

    def keys(self):
        return list(set(chain(*[c.keys() for c in self.subcontexts])))


    # Expose DictMixin's get method over HasTraits'.
    get = DictMixin.get

    def __str__(self):
        # Maybe a good default string
        subcontext_str = '[%s]' % ', '.join([str(x) for x in self.subcontexts])
        return '%s(name=%r, subcontexts=%s)' % (type(self).__name__, self.name,
            subcontext_str)

    def __repr__(self):
        # Maybe a good default representation
        return '%s(name=%r)' % (type(self).__name__, self.name)


    #### IRestrictedContext interface ##########################################

    def allows(self, value, name=None):
        for c in self.subcontexts:
            if c.allows(value, name=name):
                return True
        return False


    #### Trait Event Handlers ##################################################

    @on_trait_change('subcontexts:items_modified')
    def subcontexts_items_modified(self, event):
        """ Pass events up.
"""
        if event is Undefined:
            # Nothing to do.
            return

        event.veto = True

        self._fire_event(added=event.added, removed=event.removed,
            modified=event.modified, context=event.context)

    def _subcontexts_items_changed(self, event):
        """ Trait listener for items of subcontexts list.
"""
        added = []
        removed = []

        # Add to the list of items added
        if len(event.added):
            for context in event.added:
                added.extend(context.keys())

        # Add to the list of items removed
        if len(event.removed):
            for context in event.removed:
                removed.extend(context.keys())

        self._fire_event(added=added, removed=removed)

    #### ICheckpointable interface ############################################

    def checkpoint(self):
        """ Make a shallow copy of the context.

Technically, this is actually a fairly deep copy. All of the object
structure should be replicated, but the actual dictionary storage will
be shallowly copied::

copy = context.shallow_copy()
copy[key] is context[key] for key in context.keys()

These semantics are useful for saving out checkpointed versions of the
context for implementing an undo/redo stack. They may not be useful for
other purposes.

Returns
-------
copy : IContext
"""
        copy = self.clone_traits()
        new_subcontexts = []
        for context in self.subcontexts:
            checkpointable_subcontext = adapt(context, ICheckpointable)
            new_subcontexts.append(checkpointable_subcontext.checkpoint())
        copy.subcontexts = new_subcontexts
        return copy

Something went wrong with that request. Please try again.