Source

pyobjc / pyobjc-core / Lib / PyObjCTools / KeyValueCoding.py

Full commit
  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
"""
Support for Key-Value Coding in Python. This provides a simple functional
interface to Cocoa's Key-Value coding that also works for regular Python
objects.

Public API:

    setKey(obj, key, value) -> None
    setKeyPath (obj, keypath, value) -> None

    getKey(obj, key) -> value
    getKeyPath (obj, keypath) -> value

A keypath is a string containing a sequence of keys seperated by dots. The
path is followed by repeated calls to 'getKey'. This can be used to easily
access nested attributes.

This API is mirroring the 'getattr' and 'setattr' APIs in Python, this makes
it more natural to work with Key-Value coding from Python. It also doesn't
require changes to existing Python classes to make use of Key-Value coding,
making it easier to build applications as a platform independent core with
a Cocoa GUI layer.

See the Cocoa documentation on the Apple developer website for more
information on Key-Value coding. The protocol is basicly used to enable
weaker coupling between the view and model layers.
"""
from __future__ import unicode_literals
import sys

__all__ = ("getKey", "setKey", "getKeyPath", "setKeyPath")
if sys.version_info[0] == 2:
    __all__ = tuple(str(x) for x in __all__)


import objc
import types
import sys
import collections
import warnings

if sys.version_info[0] == 2:
    from itertools import imap as map
    pass

else:   # pragma: no cover (py3k)
    basestring = str

_null = objc.lookUpClass('NSNull').null()

def keyCaps(s):
    return s[:1].capitalize() + s[1:]

# From http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/393090
# Title: Binary floating point summation accurate to full precision
# Version no: 2.2

def msum(iterable):
    "Full precision summation using multiple floats for intermediate values"
    # sorted, non-overlapping partial sums
    partials = []
    for x in iterable:
        i = 0
        for y in partials:
            if abs(x) < abs(y):
                x, y = y, x
            hi = x + y
            lo = y - (hi - x)
            if lo:
                partials[i] = lo
                i += 1
            x = hi
        partials[i:] = [x]
    return sum(partials, 0.0)

class _ArrayOperators (object):

    @staticmethod
    def avg(obj, segments):
        path = '.'.join(segments)
        lst = getKeyPath(obj, path)
        count = len(lst)
        if count == 0:
            return 0.0
        return msum(float(x) if x is not _null else 0.0 for x in lst) / count

    @staticmethod
    def count(obj, segments):
        return len(obj)

    @staticmethod
    def distinctUnionOfArrays(obj, segments):
        path = '.'.join(segments)
        rval = []
        s = set()
        r = []
        for lst in obj:
            for item in [ getKeyPath(item, path) for item in lst ]:
                try:
                    if item in s or item in r:
                        continue
                    rval.append(item)
                    s.add(item)

                except TypeError:
                    if item in rval:
                        continue

                    rval.append(item)
                    r.append(item)
        return rval

    @staticmethod
    def distinctUnionOfSets(obj, segments):
        path = '.'.join(segments)
        rval = set()
        for lst in obj:
            for item in [ getKeyPath(item, path) for item in lst ]:
                rval.add(item)
        return rval

    @staticmethod
    def distinctUnionOfObjects(obj, segments):
        path = '.'.join(segments)
        rval = []
        s = set()
        r = []
        lst = [ getKeyPath(item, path) for item in obj ]
        for item in lst:
            try:
                if item in s or item in r:
                    continue

                rval.append(item)
                s.add(item)

            except TypeError:
                if item in rval: 
                    continue

                rval.append(item)
                r.append(item)
        return rval


    @staticmethod
    def max(obj, segments):
        path = '.'.join(segments)
        return max(x for x in getKeyPath(obj, path) if x is not _null)

    @staticmethod
    def min(obj, segments):
        path = '.'.join(segments)
        return min(x for x in getKeyPath(obj, path) if x is not _null)

    @staticmethod
    def sum(obj, segments):
        path = '.'.join(segments)
        lst = getKeyPath(obj, path)
        return msum(float(x) if x is not _null else 0.0 for x in lst)

    @staticmethod
    def unionOfArrays(obj, segments):
        path = '.'.join(segments)
        rval = []
        for lst in obj:
            rval.extend([ getKeyPath(item, path) for item in lst ])
        return rval


    @staticmethod
    def unionOfObjects(obj, segments):
        path = '.'.join(segments)
        return [ getKeyPath(item, path) for item in obj]




def getKey(obj, key):
    """
    Get the attribute referenced by 'key'. The key is used
    to build the name of an attribute, or attribute accessor method.

    The following attributes and accesors are tried (in this order):

    - Accessor 'getKey'
    - Accesoor 'get_key'
    - Accessor or attribute 'key'
    - Accessor or attribute 'isKey'
    - Attribute '_key'

    If none of these exist, raise KeyError
    """
    if obj is None:
        return None
    if isinstance(obj, (objc.objc_object, objc.objc_class)):
        return obj.valueForKey_(key)

    # check for dict-like objects
    getitem = getattr(obj, '__getitem__', None)
    if getitem is not None:
        try:
            return getitem(key)
        except (KeyError, IndexError, TypeError):
            pass

    # check for array-like objects
    if isinstance(obj, (collections.Sequence, collections.Set)) and not isinstance(obj, (basestring, collections.Mapping)):
        def maybe_get(obj, key):
            try:
                return getKey(obj, key)
            except KeyError:
                return _null
        return [maybe_get(obj, key) for obj in iter(obj)]

    try:
        m = getattr(obj, "get" + keyCaps(key))
    except AttributeError:
        pass
    else:
        return m()

    try:
        m = getattr(obj, "get_" + key)
    except AttributeError:
        pass
    else:
        return m()

    for keyName in (key, "is" + keyCaps(key)):
        try:
            m = getattr(obj, keyName)
        except AttributeError:
            continue

        if isinstance(m, types.MethodType) and m.__self__ is obj:
            return m()

        elif isinstance(m, types.BuiltinMethodType):
            # Can't access the bound self of methods of builtin classes :-(
            return m()

        elif isinstance(m, objc.selector) and m.self is obj:
            return m()

        else:
            return m

    try:
        return getattr(obj, "_" + key)
    except AttributeError:
        raise KeyError("Key %s does not exist" % (key,))


def setKey(obj, key, value):
    """
    Set the attribute referenced by 'key' to 'value'. The key is used
    to build the name of an attribute, or attribute accessor method.

    The following attributes and accessors are tried (in this order):
    - Mapping access (that is __setitem__ for collection.Mapping instances)
    - Accessor 'setKey_'
    - Accessor 'setKey'
    - Accessor 'set_key'
    - Attribute '_key'
    - Attribute 'key'

    Raises KeyError if the key doesn't exist.
    """
    if obj is None:
        return
    if isinstance(obj, (objc.objc_object, objc.objc_class)):
        obj.setValue_forKey_(value, key)
        return

    if isinstance(obj, collections.Mapping):
        obj[key] = value
        return

    aBase = 'set' + keyCaps(key)
    for accessor in (aBase + '_', aBase, 'set_' + key):
        m = getattr(obj, accessor, None)
        if m is None:
            continue
        try:
            m(value)
            return
        except TypeError:
            pass

    try:
        m = getattr(obj, key)
    except AttributeError:
        pass

    else:
        if isinstance(m, types.MethodType) and m.__self__ is obj:
            # This looks like a getter method, don't call setattr
            pass

        else:
            try:
                setattr(obj, key, value)
                return
            except AttributeError:
                raise KeyError("Key %s does not exist" % (key,))
    
    try:
        getattr(obj, "_" + key)
    except AttributeError:
        pass
    else:
        setattr(obj, "_" + key, value)
        return

    try:
        setattr(obj, key, value)
    except AttributeError:
        raise KeyError("Key %s does not exist" % (key,))

def getKeyPath(obj, keypath):
    """
    Get the value for the keypath. Keypath is a string containing a
    path of keys, path elements are seperated by dots.
    """
    if not keypath:
        raise KeyError

    if obj is None:
        return None


    if isinstance(obj, (objc.objc_object, objc.objc_class)):
        return obj.valueForKeyPath_(keypath)

    elements = keypath.split('.')
    cur = obj
    elemiter = iter(elements)
    for e in elemiter:
        if e[:1] == '@':
            try:
                oper = getattr(_ArrayOperators, e[1:])
            except AttributeError:
                raise KeyError("Array operator %s not implemented" % (e,))
            return oper(cur, elemiter)
        cur = getKey(cur, e)
    return cur

def setKeyPath(obj, keypath, value):
    """
    Set the value at 'keypath'. The keypath is a string containing a
    path of keys, seperated by dots.
    """
    if obj is None:
        return

    if isinstance(obj, (objc.objc_object, objc.objc_class)):
        return obj.setValue_forKeyPath_(value, keypath)

    elements = keypath.split('.')
    cur = obj
    for e in elements[:-1]:
        cur = getKey(cur, e)

    return setKey(cur, elements[-1], value)


class kvc(object):
    def __init__(self, obj):
        self.__pyobjc_object__ = obj

    def __getattr__(self, attr):
        return getKey(self.__pyobjc_object__, attr)

    def __repr__(self):
        return repr(self.__pyobjc_object__)

    def __setattr__(self, attr, value):
        if not attr.startswith('_'):
            setKey(self.__pyobjc_object__, attr, value)

        else:
            object.__setattr__(self, attr, value)

    def __getitem__(self, item):
        if not isinstance(item, basestring):
            raise TypeError('Keys must be strings')
        return getKeyPath(self.__pyobjc_object__, item)

    def __setitem__(self, item, value):
        if not isinstance(item, basestring):
            raise TypeError('Keys must be strings')
        setKeyPath(self.__pyobjc_object__, item, value)



# XXX: Undocumented and deprecated functions, only present because these had public
#      names in previous releases and the module has suboptimal documentation.
#      To be removed in PyObjC 3.0
class ArrayOperators (_ArrayOperators):
    def __init__(self):
        warnings.warn("Don't use PyObjCTools.KeyValueCoding.ArrayOperators", DeprecationWarning)

class _Deprecated (object):
    def __getattr__(self, nm):
        warnings.warn("Don't use PyObjCTools.KeyValueCoding.arrayOperators", DeprecationWarning)
        return getattr(_ArrayOperators, nm)

arrayOperators = _Deprecated()