fastcocoa 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fastcocoa/__init__.py +482 -0
- fastcocoa/appkit.py +7 -0
- fastcocoa/avfoundation.py +7 -0
- fastcocoa/contacts.py +7 -0
- fastcocoa/eventkit.py +7 -0
- fastcocoa/foundation.py +7 -0
- fastcocoa/photos.py +7 -0
- fastcocoa/sdk.py +204 -0
- fastcocoa/speech.py +7 -0
- fastcocoa/surface.py +214 -0
- fastcocoa/swifttool.py +139 -0
- fastcocoa-0.1.0.dist-info/METADATA +65 -0
- fastcocoa-0.1.0.dist-info/RECORD +16 -0
- fastcocoa-0.1.0.dist-info/WHEEL +5 -0
- fastcocoa-0.1.0.dist-info/licenses/LICENSE +202 -0
- fastcocoa-0.1.0.dist-info/top_level.txt +1 -0
fastcocoa/__init__.py
ADDED
|
@@ -0,0 +1,482 @@
|
|
|
1
|
+
"""Cocoa that reads like Swift: properties, kwarg selectors, and value bridging on top of pyobjc.
|
|
2
|
+
|
|
3
|
+
`pyobjc` has twenty years of irreplaceable metadata (C function signatures, `(value, error)` out-param tupling, block signatures), but Cocoa code written with it reads as ceremony: `f.setDateFormat_('yyyy')`, `str(e.title())`, `saveEvent_span_error_`. Swift's niceness over the same APIs is a finite list of mechanical transforms, and `fastcocoa` applies them to `pyobjc` classes in place:
|
|
4
|
+
|
|
5
|
+
from fastcocoa.eventkit import EKEvent, EKEventStore
|
|
6
|
+
s = EKEventStore()
|
|
7
|
+
ev = EKEvent(eventStore=s, title=title, startDate=start)
|
|
8
|
+
s.save(ev, span='thisEvent')
|
|
9
|
+
|
|
10
|
+
Everything is real `pyobjc` underneath: the same objects, delegates, and framework coverage.
|
|
11
|
+
|
|
12
|
+
## Setup: import through the stubs
|
|
13
|
+
|
|
14
|
+
Importing a class through a framework stub pythonifies it, and no other setup exists. Stubs exist for `foundation`, `appkit`, `eventkit`, `contacts`, `photos`, `avfoundation`, and `speech`; for anything else, `pythonify(cls, mod=Framework)` is the primitive they wrap. Named imports only: `import *` from a stub sweeps nothing.
|
|
15
|
+
|
|
16
|
+
## The bridge
|
|
17
|
+
|
|
18
|
+
- Declared properties are real Python descriptors, generated from the ObjC runtime's own metadata. `ev.title = t` writes, and reads convert: `NSString` to `str`, `NSDate` to `datetime`, `NSData` to `bytes`, `NSNumber` to `bool`/`int`/`float`, containers recursively, lists to `fastcore`'s `L`.
|
|
19
|
+
- Keyword arguments are assembled into selectors: `o.saveEvent(ev, span=x)` calls `saveEvent:span:error:`, and a trailing `error:` out-param raises instead of returning (`chk` does the same for raw calls). A string passed where an integer enum belongs resolves by unique constant suffix, so `span='thisEvent'` finds `EKSpanThisEvent`.
|
|
20
|
+
- Constructor kwargs reach class factories, `initWith...` initializers, and settable properties in one call: `EKEvent(eventStore=s, title=t, startDate=d)`.
|
|
21
|
+
- Indexed collections (`count`/`objectAtIndex:`) get `len`, indexing, lazy iteration, and an `L`-style `map`, so `first(PHAsset.fetchAssets(options=o))` and `.map(f)` both work.
|
|
22
|
+
- Every object returned through the bridge is swept (pythonified) on the way out, so private cluster subclasses and KVO-swizzled instances behave like their public ancestors.
|
|
23
|
+
|
|
24
|
+
## Swift names
|
|
25
|
+
|
|
26
|
+
Beyond the runtime's own metadata, `fastcocoa` reads Apple's Swift symbol graphs, so methods also answer to their curated Swift names, with the argument labels every Swift tutorial shows:
|
|
27
|
+
|
|
28
|
+
s.save(ev, span='thisEvent', commit=True) # saveEvent:span:commit:error:
|
|
29
|
+
f.string(from_=d) # stringFromDate: (a keyword label takes a trailing underscore)
|
|
30
|
+
await store.requestFullAccessToEvents() # the importer's async variant, as an awaitable
|
|
31
|
+
EKSpan.thisEvent # enum cases as namespaces, importable from the stubs
|
|
32
|
+
|
|
33
|
+
Where Swift knows a parameter's class, an omitted one is built from leftover kwargs: `session.dataTask(URL=u)` constructs the `NSURLRequest` for `dataTask(with:)`. The ObjC spellings keep working, and remain the only spelling for selectors outside the public SDK surface. Extraction runs once per SDK version and needs the Xcode Command Line Tools; without a toolchain, `fastcocoa` warns once and the ObjC spellings still work.
|
|
34
|
+
|
|
35
|
+
## Browse and search the SDK
|
|
36
|
+
|
|
37
|
+
The same tables carry Apple's header docs, so the surface is discoverable without leaving Python:
|
|
38
|
+
|
|
39
|
+
- A pending call documents itself: `doc(s.save)`, `s.save?`, and `inspect.signature` show the real labels, parameter classes, per-parameter docs, and a developer.apple.com link, with overloads stacked in the docstring. `dir(o)` includes the Swift heads.
|
|
40
|
+
- `sdkclass('EKEventStore')` is one class as a markdown reference: methods and inits with signatures and abstracts, plus declared properties.
|
|
41
|
+
- `sdkgroups('EventKit')` is a whole framework as an attribute-chained tree, and `full_docs(sdkgroups('EventKit'))` renders it as one markdown document, sized for LLM context.
|
|
42
|
+
- `sdksearch(pattern, frameworks=None, kind=None)` searches methods, inits, enums, and properties across extracted frameworks, matching names, labels, param and property types, and doc text, so "which methods take a `PHFetchOptions`" is `sdksearch('PHFetchOptions')` and "delete a reminder" is `sdksearch('remove.*reminder')`. `kind=` filters `'im'`/`'cm'`/`'init'`/`'protocol'`/`'enum'`/`'property'`. Search never extracts a table silently; pass `frameworks=` to opt in.
|
|
43
|
+
|
|
44
|
+
The search flow, end to end:
|
|
45
|
+
|
|
46
|
+
hits = sdksearch('capture.*screen|screen.*captur')
|
|
47
|
+
hits # numbered previews: 1 AVCaptureScreenInput.init(displayID): *Creates an ...*
|
|
48
|
+
hits[1] # that hit in full: line, docs URL, typed params
|
|
49
|
+
c = hits[1].caller(AVCaptureScreenInput) # the hit's call bound to a receiver: for an init hit the class itself, else a caller documented as that exact overload
|
|
50
|
+
c(displayID=CGMainDisplayID()) # construct it
|
|
51
|
+
|
|
52
|
+
## Helpers
|
|
53
|
+
|
|
54
|
+
`sortd('-creationDate,title')` builds `NSSortDescriptor` lists. `nsurl`/`nsdate`/`pydate`/`topy` convert values by hand where needed. `Sig` awaits a Cocoa callback from the event loop; `wait_cb` is its blocking twin for worker threads, with a `...` argument marking where the callback goes. `camera` is a running capture session as a context manager. `fastcocoa.swifttool` holds the symbol-graph extractor plus Swift build/sign/bundle helpers for making small signed apps. The escape hatch from all conversion is `pyobjc`'s own: `o.pyobjc_instanceMethods.title()` bypasses every descriptor."""
|
|
55
|
+
|
|
56
|
+
__version__ = "0.1.0"
|
|
57
|
+
|
|
58
|
+
import asyncio, sys, threading
|
|
59
|
+
from contextlib import contextmanager
|
|
60
|
+
from datetime import datetime
|
|
61
|
+
|
|
62
|
+
import objc
|
|
63
|
+
from fastcore.utils import *
|
|
64
|
+
from Foundation import NSArray, NSData, NSDate, NSDictionary, NSNumber, NSSortDescriptor, NSURL
|
|
65
|
+
|
|
66
|
+
from .sdk import _tables, enumns, sdktable, swiftkey
|
|
67
|
+
from .surface import full_docs, sdkclass, sdkgroups, sdkops, sdksearch
|
|
68
|
+
|
|
69
|
+
__all__ = ['chk', 'sortd', 'nsurl', 'nsdate', 'pydate', 'topy', 'pythonify', 'modattr', 'Sig', 'wait_cb', 'camera', 'sdkclass', 'sdkgroups', 'sdksearch', 'full_docs']
|
|
70
|
+
|
|
71
|
+
_INTS = b'cCsSiIlLqQB'
|
|
72
|
+
objc.registerListType(L) # so an `L` (which every bridged list return is) passes back into Cocoa as NSArray
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def chk(res):
|
|
76
|
+
"Unpack a Cocoa `(value, error)` or `(ok, error)` out-param pair, raising on a reported failure"
|
|
77
|
+
v, err = res
|
|
78
|
+
if err is not None or v is False: raise RuntimeError(str(err) if err is not None else 'call failed')
|
|
79
|
+
return v
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def sortd(
|
|
83
|
+
spec:str # Comma-separated keys, each optionally prefixed `-` for descending, e.g. `'-creationDate'`
|
|
84
|
+
):
|
|
85
|
+
"An `NSSortDescriptor` list from a compact spec, for the many Cocoa APIs that take one"
|
|
86
|
+
return [NSSortDescriptor.sortDescriptorWithKey_ascending_(k.lstrip('-'), not k.startswith('-')) for k in spec.split(',')]
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def nsurl(path): return NSURL.fileURLWithPath_(str(Path(path).expanduser()))
|
|
90
|
+
def nsdate(dt): return NSDate.dateWithTimeIntervalSince1970_(dt.timestamp())
|
|
91
|
+
def pydate(d): return datetime.fromtimestamp(d.timeIntervalSince1970()) if d is not None else None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
def topy(o):
|
|
95
|
+
"A Cocoa value as its Python equivalent, recursively; other Cocoa objects pass through with their live class swept"
|
|
96
|
+
if isinstance(o, str): return str(o)
|
|
97
|
+
if isinstance(o, NSDate): return pydate(o)
|
|
98
|
+
if isinstance(o, NSData): return bytes(o)
|
|
99
|
+
if isinstance(o, NSNumber):
|
|
100
|
+
if o.objCType() in (b'c', b'B'): return bool(o)
|
|
101
|
+
return int(o) if float(o) == int(o) else float(o)
|
|
102
|
+
if isinstance(o, NSDictionary): return {topy(k): topy(v) for k,v in o.items()}
|
|
103
|
+
if isinstance(o, (NSArray, list)): return L(topy(v) for v in o) # a stored Python list round-trips as itself, not NSArray
|
|
104
|
+
return _sweep(o)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _sweep(o):
|
|
108
|
+
"Pythonify the live class of a pass-through Cocoa object, so private subclasses work like their public ancestors"
|
|
109
|
+
if isinstance(o, objc.objc_object): pythonify(type(o), mod=_findmod(type(o)))
|
|
110
|
+
return o
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
_mods, _skip, _heads, _dirs = {}, None, {}, {}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _enum(mod, s):
|
|
117
|
+
"The unique constant in `mod` whose name ends with `s` capitalized, so `'thisEvent'` finds `EKSpanThisEvent`"
|
|
118
|
+
if mod is None: raise ValueError(f'cannot resolve {s!r}: pass `mod=` to `pythonify` for enum name lookup')
|
|
119
|
+
names = _dirs.setdefault(mod.__name__, dir(mod))
|
|
120
|
+
suf = s[0].upper()+s[1:]
|
|
121
|
+
cands = [n for n in names if n.endswith(suf)]
|
|
122
|
+
if len(cands) != 1: raise ValueError(f'{s!r} matches {cands or "no constants"} in {mod.__name__}')
|
|
123
|
+
return getattr(mod, cands[0])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _findmod(cls):
|
|
127
|
+
"The framework module for `cls`: a pythonified ancestor's, else the loaded table whose classes its runtime ancestry hits"
|
|
128
|
+
if (m := first(m for c in cls.__mro__ if (m := _mods.get(c)) is not None)) is not None: return m
|
|
129
|
+
names = {c.__name__ for c in cls.__mro__}
|
|
130
|
+
mn = first(mn for mn, t in _tables.items() if names & t.get('classes', {}).keys())
|
|
131
|
+
return sys.modules.get(mn) if mn else None
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _table(klass):
|
|
135
|
+
"The distilled Swift-name table for `klass`'s framework, or empty when the class was never stubbed with one"
|
|
136
|
+
mod = _findmod(klass)
|
|
137
|
+
return sdktable(mod.__name__) if mod is not None else {}
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _entries(klass, head, side=None):
|
|
141
|
+
"Swift-name entries for `head` on `klass`: nearest ancestor's row, else any row whose selector the class answers (facade classes like NSURLSessionDownloadTask aren't in the runtime ancestry)"
|
|
142
|
+
cs = _table(klass).get('classes', {})
|
|
143
|
+
for k in klass.__mro__:
|
|
144
|
+
if (es := cs.get(k.__name__, {}).get(head)): return [e for e in es if side is None or e['side'] == side]
|
|
145
|
+
return [e for e in _headindex(klass).get(head, []) if (side is None or e['side'] == side) and _responds(klass, e)]
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
_headidx = {}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _headindex(klass):
|
|
152
|
+
"Framework-wide `head -> entries` index for `klass`'s table"
|
|
153
|
+
mod = _findmod(klass)
|
|
154
|
+
if mod is None: return {}
|
|
155
|
+
if mod.__name__ not in _headidx:
|
|
156
|
+
idx = {}
|
|
157
|
+
for hs in _table(klass).get('classes', {}).values():
|
|
158
|
+
for h, es in hs.items(): idx.setdefault(h, []).extend(es)
|
|
159
|
+
_headidx[mod.__name__] = idx
|
|
160
|
+
return _headidx[mod.__name__]
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _responds(klass, e):
|
|
164
|
+
"Does `klass` actually answer entry `e`'s selector, on the right side?"
|
|
165
|
+
if e['side'] == 'im': return klass.instancesRespondToSelector_(e['sel'])
|
|
166
|
+
return getattr(klass.pyobjc_classMethods, e['sel'].replace(':', '_'), None) is not None
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
_healed = set()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _healmeta(klass, e):
|
|
173
|
+
"pyobjc scopes selector metadata by class, so a private tree detached from its facade (download tasks) misses block signatures: copy the facade's Apple-curated metadata onto the runtime class"
|
|
174
|
+
key = (klass.__name__, e['sel'])
|
|
175
|
+
if key in _healed: return
|
|
176
|
+
_healed.add(key)
|
|
177
|
+
try: pub = objc.lookUpClass(e['cls'])
|
|
178
|
+
except objc.error: return
|
|
179
|
+
m = getattr(pub.pyobjc_instanceMethods, e['sel'].replace(':', '_'), None)
|
|
180
|
+
if m is None: return
|
|
181
|
+
md = m.__metadata__()
|
|
182
|
+
args = {i: a for i, a in enumerate(md['arguments']) if isinstance(a, dict) and 'callable' in a}
|
|
183
|
+
if args: objc.registerMetaDataForSelector(klass.__name__.encode(), e['sel'].encode(), dict(arguments=args))
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _swiftmatch(klass, head, args, kwargs, side=None):
|
|
187
|
+
"The Swift-name entry matching this call shape, with values ordered per its labels; an omitted labeled param may be fused from leftover kwargs"
|
|
188
|
+
ks = {swiftkey(k): v for k, v in kwargs.items()}
|
|
189
|
+
for e in _entries(klass, head, side):
|
|
190
|
+
labs = e['labels']
|
|
191
|
+
if len(args) > len(labs) or any(l != '_' for l in labs[:len(args)]): continue
|
|
192
|
+
rem = labs[len(args):]
|
|
193
|
+
if [k for k in ks if k in rem] != [l for l in rem if l in ks]: continue # label order is Swift's
|
|
194
|
+
extra = {k: v for k, v in ks.items() if k not in rem}
|
|
195
|
+
gaps = [l for l in rem if l not in ks]
|
|
196
|
+
if not gaps and not extra: return e, [*args, *(ks[l] for l in rem)]
|
|
197
|
+
if len(gaps) == 1 and gaps[0] != '_' and extra and (o := _fuse(e, len(args) + rem.index(gaps[0]), extra)) is not None:
|
|
198
|
+
return e, [*args, *(o if l == gaps[0] else ks[l] for l in rem)]
|
|
199
|
+
return None, None
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _fuse(e, i, extra):
|
|
203
|
+
"Construct entry `e`'s param `i` from leftover kwargs, when its class exists and they are all settable properties of it"
|
|
204
|
+
if (tn := e['ptypes'][i]) is None: return None
|
|
205
|
+
try: cls = objc.lookUpClass(tn)
|
|
206
|
+
except objc.error: return None
|
|
207
|
+
pythonify(cls, mod=_findmod(cls))
|
|
208
|
+
if not all(_settable(cls, k) for k in extra): return None
|
|
209
|
+
return cls(**extra)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def _enumvals(m, vals, klass):
|
|
213
|
+
"String args destined for integer-typed slots resolved to enum constants, via `m`'s metadata"
|
|
214
|
+
md = m.__metadata__()['arguments']
|
|
215
|
+
return [_enum(_findmod(klass), v) if isinstance(v, str) and md[i+2]['type'][:1] in _INTS else v for i, v in enumerate(vals)]
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _acall(m, vals, throws):
|
|
219
|
+
"An awaitable for an importer-generated async twin: call `m` with a completion callback, resolve with its converted args"
|
|
220
|
+
async def go():
|
|
221
|
+
loop = asyncio.get_running_loop()
|
|
222
|
+
fut = loop.create_future()
|
|
223
|
+
def cb(*a): loop.call_soon_threadsafe(_finish, fut, a, throws)
|
|
224
|
+
m(*vals, cb)
|
|
225
|
+
return await fut
|
|
226
|
+
return go()
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _finish(fut, a, throws):
|
|
230
|
+
if fut.cancelled(): return
|
|
231
|
+
a = list(a)
|
|
232
|
+
if throws and a:
|
|
233
|
+
err = a.pop()
|
|
234
|
+
if err is not None: return fut.set_exception(RuntimeError(str(err)))
|
|
235
|
+
a = [topy(o) for o in a]
|
|
236
|
+
fut.set_result(a[0] if len(a) == 1 else tuple(a) if a else None)
|
|
237
|
+
|
|
238
|
+
|
|
239
|
+
def _swiftinit(cls, kwargs):
|
|
240
|
+
"An instance from the Swift `init(...)` table row matching `kwargs`: a class factory or `initWith...` selector"
|
|
241
|
+
e, vals = _swiftmatch(cls, 'init', (), kwargs)
|
|
242
|
+
if e is None: return None
|
|
243
|
+
attr = e['sel'].replace(':', '_')
|
|
244
|
+
m = getattr(cls.pyobjc_classMethods, attr, None) if e['side'] == 'cm' else getattr(cls.alloc(), attr, None)
|
|
245
|
+
if m is None: return None
|
|
246
|
+
vals = _enumvals(m, vals, cls)
|
|
247
|
+
return chk(m(*vals, None)) if e.get('throws') and e['sel'].endswith('error:') else m(*vals)
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def modattr(mod, n):
|
|
251
|
+
"Framework stub `__getattr__`: classes arrive pythonified, and ObjC enum type names arrive as case namespaces"
|
|
252
|
+
try: return enumns(mod, n)
|
|
253
|
+
except AttributeError: pass
|
|
254
|
+
v = getattr(mod, n)
|
|
255
|
+
if isinstance(v, objc.objc_class): pythonify(v, mod=mod)
|
|
256
|
+
return v
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _with_join(name, ks): return f"{name}With{ks[0][0].upper()}{ks[0][1:]}_" + ''.join(f'{k}_' for k in ks[1:])
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
class _Caller:
|
|
263
|
+
# A pending kwarg-selector call from `pythonify`'s `__getattr__`: `o.saveEvent(ev, span=x)` shapes.
|
|
264
|
+
# The class comment lives here because `__doc__` below is the instance's own documentation.
|
|
265
|
+
def __init__(self, o, name, pin=None): self.o, self.name, self.pin = o, name, pin # `pin`: an `SdkOp` fixing which overload documents this caller (dispatch is unaffected)
|
|
266
|
+
def __repr__(self): return f'<fastcocoa caller {self.name!r} of {self.o!r}>'
|
|
267
|
+
|
|
268
|
+
def _ops(self):
|
|
269
|
+
"Table records for this head, as documented `SdkOp`s (empty when the head has no Swift-name rows)"
|
|
270
|
+
isc = isinstance(self.o, objc.objc_class)
|
|
271
|
+
klass = self.o if isc else type(self.o)
|
|
272
|
+
es = _entries(klass, self.name, 'cm' if isc else 'im')
|
|
273
|
+
mod = _findmod(klass)
|
|
274
|
+
return sdkops(mod.__name__, self.name, es) if es and mod is not None else []
|
|
275
|
+
|
|
276
|
+
@property
|
|
277
|
+
def __signature__(self):
|
|
278
|
+
if self.pin is not None: return self.pin.__signature__
|
|
279
|
+
ops = self._ops()
|
|
280
|
+
if not ops: raise AttributeError('__signature__') # inspect falls back to the generic shape
|
|
281
|
+
return ops[0].__signature__
|
|
282
|
+
|
|
283
|
+
@property
|
|
284
|
+
def __doc__(self):
|
|
285
|
+
ops = [self.pin] if self.pin is not None else self._ops()
|
|
286
|
+
return ops[0].__doc__ if ops else None
|
|
287
|
+
def __call__(self, *args, **kwargs):
|
|
288
|
+
isc = isinstance(self.o, objc.objc_class)
|
|
289
|
+
klass = self.o if isc else type(self.o)
|
|
290
|
+
ms = self.o.pyobjc_classMethods if isc else self.o.pyobjc_instanceMethods
|
|
291
|
+
e, vals = _swiftmatch(klass, self.name, args, kwargs, 'cm' if isc else 'im')
|
|
292
|
+
if e is not None:
|
|
293
|
+
if not isc and e['cls'] not in {c.__name__ for c in klass.__mro__}: _healmeta(klass, e)
|
|
294
|
+
if e is not None and (m := getattr(ms, e['sel'].replace(':', '_'), None)) is not None:
|
|
295
|
+
vals = _enumvals(m, vals, klass)
|
|
296
|
+
if e.get('async'): return _acall(m, vals, e.get('throws'))
|
|
297
|
+
return topy(chk(m(*vals, None)) if e.get('throws') and e['sel'].endswith('error:') else m(*vals))
|
|
298
|
+
ks = list(kwargs)
|
|
299
|
+
if len(args) == 1: cands = ['_'.join([self.name, *ks]) + '_']
|
|
300
|
+
elif not args and ks: cands = [_with_join(self.name, ks)] # no positional: the head absorbs the first label
|
|
301
|
+
else: raise TypeError(f'{self.name}: pass at most one positional argument; label the rest')
|
|
302
|
+
m, autoerr = None, False
|
|
303
|
+
for c in cands:
|
|
304
|
+
if (m := getattr(ms, c, None)) is not None: break
|
|
305
|
+
if (m := getattr(ms, c+'error_', None)) is not None:
|
|
306
|
+
autoerr = True
|
|
307
|
+
break
|
|
308
|
+
if m is None: raise AttributeError(f"{klass.__name__} has no selector like {' or '.join(cands)}")
|
|
309
|
+
vals = _enumvals(m, [*args, *kwargs.values()], klass)
|
|
310
|
+
res = chk(m(*vals, None)) if autoerr else m(*vals)
|
|
311
|
+
return topy(res)
|
|
312
|
+
|
|
313
|
+
|
|
314
|
+
def _headset(klass, classside=False):
|
|
315
|
+
"The selector-family heads `klass` answers on one side: dir-derived head shapes plus the table's Swift names"
|
|
316
|
+
key = (klass, classside)
|
|
317
|
+
if key not in _heads:
|
|
318
|
+
sels = dir(klass.pyobjc_classMethods) if classside else objc.objc_class.__dir__(klass) # the raw dir: our metaclass `__dir__` calls back in here
|
|
319
|
+
hs = {s.split('With')[0].split('_')[0] for s in sels} | {s.split('_')[0] for s in sels}
|
|
320
|
+
cs, side = _table(klass).get('classes', {}), 'cm' if classside else 'im'
|
|
321
|
+
for k in klass.__mro__: hs |= {h for h, es in cs.get(k.__name__, {}).items() if any(e['side'] == side for e in es)}
|
|
322
|
+
for h, es in _headindex(klass).items():
|
|
323
|
+
if h not in hs and any(e['side'] == side and _responds(klass, e) for e in es): hs.add(h)
|
|
324
|
+
_heads[key] = hs
|
|
325
|
+
return _heads[key]
|
|
326
|
+
|
|
327
|
+
|
|
328
|
+
def _head_ok(klass, name, classside=False): return name in _headset(klass, classside)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _fc_dir(self): return [*objc.objc_object.__dir__(self), *_headset(type(self))]
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _fc_mdir(cls): return [*objc.objc_class.__dir__(cls), *_headset(cls), *_headset(cls, True)]
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _fc_getattr(self, name):
|
|
338
|
+
if name.startswith('_'): raise AttributeError(name)
|
|
339
|
+
if not _head_ok(type(self), name): raise AttributeError(f'{type(self).__name__} has no property or selector family {name!r}')
|
|
340
|
+
return _Caller(self, name)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _fc_mgetattr(cls, name):
|
|
344
|
+
if name.startswith('_') or name.startswith('pyobjc'): raise AttributeError(name)
|
|
345
|
+
if not _head_ok(cls, name, classside=True): raise AttributeError(f'{cls.__name__} has no property or selector family {name!r}')
|
|
346
|
+
return _Caller(cls, name)
|
|
347
|
+
|
|
348
|
+
|
|
349
|
+
def _fc_call(cls, *args, **kwargs):
|
|
350
|
+
"""Metaclass `__call__`: pyobjc's init handling first; then the longest leading kwarg run that names a class
|
|
351
|
+
factory or `initWith...` (with or without a trailing `error:`), with every remaining kwarg assigned as a
|
|
352
|
+
settable property - so `EKEvent(eventStore=s, title=t)` constructs and configures in one call"""
|
|
353
|
+
try: return _sweep(objc.objc_class.__call__(cls, *args, **kwargs))
|
|
354
|
+
except TypeError:
|
|
355
|
+
if kwargs and not args:
|
|
356
|
+
if (o := _swiftinit(cls, kwargs)) is not None: return _sweep(o)
|
|
357
|
+
base = re.sub(r'^[A-Z]+(?=[A-Z])', '', cls.__name__)
|
|
358
|
+
ks = list(kwargs)
|
|
359
|
+
for n in range(len(ks), 0, -1):
|
|
360
|
+
lead, rest = ks[:n], ks[n:]
|
|
361
|
+
if not all(_settable(cls, k) for k in rest): continue
|
|
362
|
+
if (o := _construct(cls, base, lead, [kwargs[k] for k in lead])) is None: continue
|
|
363
|
+
_sweep(o) # rest-property setters need the live class swept (cluster instances are private subclasses)
|
|
364
|
+
for k in rest: setattr(o, k, kwargs[k])
|
|
365
|
+
return o
|
|
366
|
+
if all(_settable(cls, k) for k in ks):
|
|
367
|
+
o = _sweep(objc.objc_class.__call__(cls))
|
|
368
|
+
for k,v in kwargs.items(): setattr(o, k, v)
|
|
369
|
+
return o
|
|
370
|
+
raise
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def _construct(cls, base, ks, vals):
|
|
374
|
+
"An instance from a class factory or `initWith...` named by kwarg run `ks`, or None when neither exists"
|
|
375
|
+
for head in (base[0].lower()+base[1:], base):
|
|
376
|
+
if (m := getattr(cls.pyobjc_classMethods, _with_join(head, ks), None)) is not None: return m(*vals)
|
|
377
|
+
init = _with_join('init', ks)
|
|
378
|
+
if cls.instancesRespondToSelector_(init.replace('_', ':')): return getattr(cls.alloc(), init)(*vals)
|
|
379
|
+
if cls.instancesRespondToSelector_(init.replace('_', ':') + 'error:'): return chk(getattr(cls.alloc(), init + 'error_')(*vals, None))
|
|
380
|
+
return None
|
|
381
|
+
|
|
382
|
+
|
|
383
|
+
def _settable(cls, k):
|
|
384
|
+
p = _mroprop(cls, k)
|
|
385
|
+
return isinstance(p, property) and p.fset is not None
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def _mroprop(cls, name): return first(p for k in cls.__mro__ if (p := k.__dict__.get(name)) is not None)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def _mkprop(p):
|
|
392
|
+
g = p.get('getter', p['name'].encode()).decode()
|
|
393
|
+
def fget(self): return topy(getattr(self.pyobjc_instanceMethods, g)())
|
|
394
|
+
if p.get('readonly'): return property(fget)
|
|
395
|
+
s = p.get('setter', f"set{p['name'][0].upper()}{p['name'][1:]}:".encode()).decode().replace(':', '_')
|
|
396
|
+
def fset(self, v): getattr(self.pyobjc_instanceMethods, s)(v)
|
|
397
|
+
return property(fget, fset)
|
|
398
|
+
|
|
399
|
+
|
|
400
|
+
_VALS = {'NSString', 'NSArray', 'NSDictionary', 'NSDate', 'NSData', 'NSNumber'}
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def pythonify(*classes,
|
|
404
|
+
mod=None # The framework module (e.g. `EventKit`), for resolving string enum names in calls
|
|
405
|
+
):
|
|
406
|
+
"""Give Cocoa classes Swift-grade Python ergonomics, in place: declared properties become real (converted)
|
|
407
|
+
attributes, `o.saveEvent(ev, span=x)` assembles `saveEvent:span:error:` (a trailing error out-param raises
|
|
408
|
+
instead of returning), and `EKEvent(eventStore=s)` reaches class factory methods and settable properties.
|
|
409
|
+
The whole ancestry's declared properties land on the class itself, base to derived: pyobjc caches resolved
|
|
410
|
+
selectors into leaf class dicts, so only own-dict descriptors reliably win the lookup. Classes reached
|
|
411
|
+
through declared object properties are swept too. Idempotent, and the rest of pyobjc is untouched."""
|
|
412
|
+
if _skip is None: _init_skip()
|
|
413
|
+
nso = objc.lookUpClass('NSObject')
|
|
414
|
+
for cls in classes:
|
|
415
|
+
if cls is nso: continue # patching NSObject itself would change every ObjC object
|
|
416
|
+
if cls in _mods: continue
|
|
417
|
+
_mods[cls] = mod
|
|
418
|
+
for k in reversed([k for k in cls.__mro__ if k is not nso and isinstance(k, type) and issubclass(k, nso)]):
|
|
419
|
+
for p in objc.propertiesForClass(k):
|
|
420
|
+
if p['name'] in _skip: continue
|
|
421
|
+
setattr(cls, p['name'], _mkprop(p))
|
|
422
|
+
if 'classname' in p and p['classname'] not in _VALS:
|
|
423
|
+
try: pythonify(objc.lookUpClass(p['classname']), mod=mod)
|
|
424
|
+
except objc.error: pass # private classes are unreachable by name, and unneeded
|
|
425
|
+
if cls.instancesRespondToSelector_('objectAtIndex:') and cls.instancesRespondToSelector_('count'):
|
|
426
|
+
cls.__len__ = objc.python_method(lambda self: self.pyobjc_instanceMethods.count())
|
|
427
|
+
cls.__getitem__ = objc.python_method(lambda self, i: topy(self.pyobjc_instanceMethods.objectAtIndex_(i)))
|
|
428
|
+
cls.__iter__ = objc.python_method(lambda self: (self[i] for i in range(len(self))))
|
|
429
|
+
if not cls.instancesRespondToSelector_('map') and not cls.instancesRespondToSelector_('map:'):
|
|
430
|
+
cls.map = objc.python_method(lambda self, f, *args, **kw: L(self).map(f, *args, **kw))
|
|
431
|
+
cls.__getattr__ = objc.python_method(_fc_getattr)
|
|
432
|
+
type(cls).__call__ = _fc_call
|
|
433
|
+
type(cls).__getattr__ = _fc_mgetattr
|
|
434
|
+
type(cls).__dir__ = _fc_mdir
|
|
435
|
+
cls.__dir__ = objc.python_method(_fc_dir) # completion shows the Swift heads beside the ObjC spellings
|
|
436
|
+
return classes[0] if len(classes) == 1 else classes
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _init_skip():
|
|
440
|
+
global _skip
|
|
441
|
+
_skip = {p['name'] for p in objc.propertiesForClass(objc.lookUpClass('NSObject'))}
|
|
442
|
+
|
|
443
|
+
|
|
444
|
+
class Sig:
|
|
445
|
+
"Await a Cocoa callback from the loop: pass `sig.set` (any thread or queue) and `await sig.wait(secs)`"
|
|
446
|
+
def __init__(self): self.loop, self.evt = asyncio.get_running_loop(), asyncio.Event()
|
|
447
|
+
def set(self): self.loop.call_soon_threadsafe(self.evt.set)
|
|
448
|
+
async def wait(self,
|
|
449
|
+
secs:float # Seconds before TimeoutError
|
|
450
|
+
): await asyncio.wait_for(self.evt.wait(), secs)
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def wait_cb(
|
|
454
|
+
f, # Called as `f(*args, **kwargs)` with each `...` replaced by the completion callback
|
|
455
|
+
*args, # Positional args for `f`; `...` marks the callback slot
|
|
456
|
+
secs:float=10, # Seconds before TimeoutError
|
|
457
|
+
**kwargs # Keyword args for `f`; `...` marks the callback slot
|
|
458
|
+
):
|
|
459
|
+
"Blocking twin of `Sig` for worker-thread bodies: call `f`, return the callback's args as Python values"
|
|
460
|
+
got, evt = [], threading.Event()
|
|
461
|
+
def cb(*a):
|
|
462
|
+
got.extend(a)
|
|
463
|
+
evt.set()
|
|
464
|
+
if not any(v is ... for v in (*args, *kwargs.values())): raise ValueError('mark the callback slot with `...`')
|
|
465
|
+
f(*(cb if v is ... else v for v in args), **{k: cb if v is ... else v for k,v in kwargs.items()})
|
|
466
|
+
if not evt.wait(secs): raise TimeoutError('Cocoa callback did not arrive')
|
|
467
|
+
return topy(got)
|
|
468
|
+
|
|
469
|
+
|
|
470
|
+
@contextmanager
|
|
471
|
+
def camera():
|
|
472
|
+
"A running capture session on the default camera, yielding its photo output"
|
|
473
|
+
from AVFoundation import AVCaptureDevice, AVCaptureDeviceInput, AVCapturePhotoOutput, AVCaptureSession, AVMediaTypeVideo
|
|
474
|
+
dev = AVCaptureDevice.defaultDeviceWithMediaType_(AVMediaTypeVideo)
|
|
475
|
+
if dev is None: raise RuntimeError('no camera')
|
|
476
|
+
sess = AVCaptureSession.alloc().init()
|
|
477
|
+
sess.addInput_(chk(AVCaptureDeviceInput.deviceInputWithDevice_error_(dev, None)))
|
|
478
|
+
outp = AVCapturePhotoOutput.alloc().init()
|
|
479
|
+
sess.addOutput_(outp)
|
|
480
|
+
sess.startRunning()
|
|
481
|
+
try: yield _sweep(outp) # the session KVO-swizzles the output, so only the live type carries the ergonomics
|
|
482
|
+
finally: sess.stopRunning()
|
fastcocoa/appkit.py
ADDED
fastcocoa/contacts.py
ADDED
fastcocoa/eventkit.py
ADDED
fastcocoa/foundation.py
ADDED