-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathios.py
More file actions
2714 lines (2335 loc) · 100 KB
/
ios.py
File metadata and controls
2714 lines (2335 loc) · 100 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
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
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""iOS native-view handlers (rubicon-objc).
Each handler class maps a PythonNative element type to a UIKit view,
implementing view creation, property updates, child management, and
frame application. Handlers are registered with the
[`NativeViewRegistry`][pythonnative.native_views.NativeViewRegistry] by
[`register_handlers`][pythonnative.native_views.ios.register_handlers].
Layout is owned by the pure-Python flex engine in
[`pythonnative.layout`][pythonnative.layout]: container handlers create
plain `UIView`s, the engine computes per-child frames in points, and
[`set_frame`][pythonnative.native_views.ios.IOSViewHandler.set_frame]
applies those frames via UIKit's classic ``frame`` property (with Auto
Layout disabled). Handlers therefore only deal with *visual* props and
ignore everything in
[`pythonnative.layout.LAYOUT_STYLE_KEYS`][pythonnative.layout.LAYOUT_STYLE_KEYS].
This module is only imported on iOS at runtime. Desktop tests inject a
mock registry via
[`set_registry`][pythonnative.native_views.set_registry] and never
trigger this import path.
"""
import ctypes as _ct
import math
import threading
from typing import Any, Callable, Dict, List, Optional, Tuple
from rubicon.objc import SEL, ObjCClass, objc_method
from . import _tripwire_log
from .base import ViewHandler, _safe_max, parse_color_int
def _safe_finite(value: Any, default: float = 0.0) -> float:
"""Coerce ``value`` to a finite float, falling back to ``default``.
Used as a defensive guard around every call into UIKit that takes a
geometry value. Without this, a single NaN or inf produced upstream
(layout edge case, stale prop during a reload, etc.) crashes the
process via `CALayerInvalidGeometry`. Clamping to ``default``
converts that into a recoverable visual glitch and lets the
`[set_frame:nan]` / `[set_transform:nan]` tripwire logs surface
where the bad value came from.
"""
try:
f = float(value)
except (TypeError, ValueError):
return default
return f if math.isfinite(f) else default
NSObject = ObjCClass("NSObject")
UIColor = ObjCClass("UIColor")
UIFont = ObjCClass("UIFont")
def _objc_ptr(obj: Any) -> Optional[int]:
"""Return the raw Objective-C pointer for a Rubicon object."""
if obj is None:
return None
if isinstance(obj, int):
return obj
ptr = getattr(obj, "ptr", None)
if isinstance(ptr, int):
return ptr
if isinstance(ptr, (bytes, bytearray)):
try:
return int.from_bytes(ptr, byteorder="little", signed=False)
except Exception:
return None
value = getattr(ptr, "value", None)
if isinstance(value, int):
return value
try:
return int(ptr) if ptr is not None else None
except Exception:
return None
# ======================================================================
# Raw libobjc helpers
# ======================================================================
#
# rubicon-objc's ``@objc_method`` FFI bridge is unreliable on iOS arm64
# for some delegate callback shapes — in particular when UIKit passes
# tagged pointers (e.g. NSIndexPath) or invokes selectors that return
# objects, the FFI closure ends up in CPython's ``_ctypes.O_get`` and
# crashes on bogus PyObject* dereferences.
#
# These helpers let us bypass rubicon-objc entirely: allocate a brand
# new ObjC class via ``objc_allocateClassPair``, attach plain
# CFUNCTYPE-wrapped Python functions as ``IMP``s, and dispatch via
# ``objc_msgSend``. Every delegate that takes ObjC object arguments
# beyond ``UITableView*`` / plain integers should use this pattern
# (UITabBar's selection delegate and UITableView's data source both do).
_libobjc = _ct.cdll.LoadLibrary("libobjc.A.dylib")
_sel_reg = _libobjc.sel_registerName
_sel_reg.restype = _ct.c_void_p
_sel_reg.argtypes = [_ct.c_char_p]
_get_cls = _libobjc.objc_getClass
_get_cls.restype = _ct.c_void_p
_get_cls.argtypes = [_ct.c_char_p]
_alloc_cls = _libobjc.objc_allocateClassPair
_alloc_cls.restype = _ct.c_void_p
_alloc_cls.argtypes = [_ct.c_void_p, _ct.c_char_p, _ct.c_size_t]
_reg_cls = _libobjc.objc_registerClassPair
_reg_cls.argtypes = [_ct.c_void_p]
_add_method = _libobjc.class_addMethod
_add_method.restype = _ct.c_bool
_add_method.argtypes = [_ct.c_void_p, _ct.c_void_p, _ct.c_void_p, _ct.c_char_p]
_objc_msgSend = _libobjc.objc_msgSend
_SEL_ALLOC = _sel_reg(b"alloc")
_SEL_INIT = _sel_reg(b"init")
_SEL_RETAIN = _sel_reg(b"retain")
_SEL_SET_DELEGATE = _sel_reg(b"setDelegate:")
_SEL_SET_DATA_SOURCE = _sel_reg(b"setDataSource:")
_SEL_TAG = _sel_reg(b"tag")
_SEL_ROW = _sel_reg(b"row")
_SEL_DESELECT_ROW = _sel_reg(b"deselectRowAtIndexPath:animated:")
_SEL_TEXT = _sel_reg(b"text")
_SEL_UTF8STRING = _sel_reg(b"UTF8String")
_SEL_ADD_TARGET_ACTION_EVENTS = _sel_reg(b"addTarget:action:forControlEvents:")
_SEL_ON_EDIT = _sel_reg(b"onEdit:")
_SEL_ON_SUBMIT = _sel_reg(b"onSubmit:")
_NS_OBJECT_CLS = _get_cls(b"NSObject")
# ======================================================================
# Shared visual helpers
# ======================================================================
_pn_view_border_radius_map: dict = {}
_SHADOW_STYLE_KEYS = ("shadow_color", "shadow_offset", "shadow_opacity", "shadow_radius", "elevation")
def _has_shadow_props(props: Dict[str, Any]) -> bool:
return any(key in props and props[key] is not None for key in _SHADOW_STYLE_KEYS)
def _uicolor(color: Any) -> Any:
"""Convert a color value to a `UIColor` instance."""
argb = parse_color_int(color)
if argb < 0:
argb += 0x100000000
a = ((argb >> 24) & 0xFF) / 255.0
r = ((argb >> 16) & 0xFF) / 255.0
g = ((argb >> 8) & 0xFF) / 255.0
b = (argb & 0xFF) / 255.0
return UIColor.colorWithRed_green_blue_alpha_(r, g, b, a)
def _cgcolor(color: Any) -> Any:
"""Convert a color value to a `CGColorRef` for layer-level APIs."""
return _uicolor(color).CGColor
def _apply_border(layer: Any, props: Dict[str, Any]) -> None:
"""Apply border_radius / border_width / border_color to a CALayer."""
if "border_radius" in props and props["border_radius"] is not None:
try:
layer.setCornerRadius_(float(props["border_radius"]))
# Without ``masksToBounds`` rounded corners only clip if
# ``overflow: "hidden"`` is set; that's the RN default for
# corner-radius use cases. Honor it implicitly when the user
# asks for corners (matches iOS UIKit common practice).
layer.setMasksToBounds_(True)
except Exception:
pass
if "border_width" in props and props["border_width"] is not None:
try:
layer.setBorderWidth_(float(props["border_width"]))
except Exception:
pass
if "border_color" in props and props["border_color"] is not None:
try:
layer.setBorderColor_(_cgcolor(props["border_color"]))
except Exception:
pass
def _apply_view_border(view: Any, props: Dict[str, Any]) -> None:
"""Apply border props and remember requested radius for frame-time clamping."""
if "border_radius" in props and props["border_radius"] is not None:
try:
requested = float(props["border_radius"])
_pn_view_border_radius_map[id(view)] = requested
radius = 0.0
try:
bounds = view.bounds
width = float(bounds.size.width)
height = float(bounds.size.height)
if width > 0.0 and height > 0.0:
radius = min(requested, min(width, height) / 2.0)
except Exception:
pass
border_props = dict(props)
border_props["border_radius"] = radius
_apply_border(view.layer, border_props)
return
except Exception:
pass
_apply_border(view.layer, props)
def _clamp_view_corner_radius(view: Any, width: float, height: float) -> None:
"""Clamp oversized pill radii to the view's rendered bounds."""
requested = _pn_view_border_radius_map.get(id(view))
if requested is None:
return
max_radius = max(0.0, min(float(width), float(height)) / 2.0)
if max_radius <= 0.0:
return
try:
view.layer.setCornerRadius_(min(float(requested), max_radius))
except Exception:
pass
def _clamp_layer_corner_radius(layer: Any, width: float, height: float) -> None:
try:
requested = float(layer.cornerRadius)
except Exception:
return
if requested <= 0.0:
return
max_radius = max(0.0, min(float(width), float(height)) / 2.0)
if max_radius <= 0.0:
return
try:
layer.setCornerRadius_(min(requested, max_radius))
except Exception:
pass
def _apply_shadow(view: Any, props: Dict[str, Any]) -> None:
"""Apply shadow_color/shadow_offset/shadow_opacity/shadow_radius via the view's layer.
Shadows on iOS require ``masksToBounds=False`` on the layer, so a
shadowed view cannot also clip its children unless ``overflow:
hidden`` is explicitly requested.
"""
layer = view.layer
if _has_shadow_props(props) and props.get("overflow") != "hidden":
try:
layer.setMasksToBounds_(False)
view.setClipsToBounds_(False)
except Exception:
pass
if "shadow_color" in props and props["shadow_color"] is not None:
try:
layer.setShadowColor_(_cgcolor(props["shadow_color"]))
except Exception:
pass
if "shadow_opacity" in props and props["shadow_opacity"] is not None:
try:
layer.setShadowOpacity_(float(props["shadow_opacity"]))
except Exception:
pass
if "shadow_radius" in props and props["shadow_radius"] is not None:
try:
layer.setShadowRadius_(float(props["shadow_radius"]))
except Exception:
pass
if "shadow_offset" in props and props["shadow_offset"] is not None:
offset = props["shadow_offset"]
try:
if isinstance(offset, dict):
w = float(offset.get("width", 0))
h = float(offset.get("height", 0))
else:
w, h = float(offset[0]), float(offset[1])
layer.setShadowOffset_((w, h))
except Exception:
pass
def _make_transform(spec: Any) -> Any:
"""Build a `CGAffineTransform` from a list of transform dicts.
Each dict has exactly one of ``rotate`` (degrees), ``scale`` (uniform),
``scale_x``, ``scale_y``, ``translate_x``, ``translate_y``.
"""
try:
from rubicon.objc.api import objc_const # noqa: F401
except Exception:
pass
# rubicon-objc doesn't expose CGAffineTransformIdentity directly;
# we reconstruct it via the C struct.
ct = _ct
libc = ct.cdll.LoadLibrary("/usr/lib/libobjc.A.dylib") # noqa: F841
class CGAffineTransform(ct.Structure):
_fields_ = [
("a", ct.c_double),
("b", ct.c_double),
("c", ct.c_double),
("d", ct.c_double),
("tx", ct.c_double),
("ty", ct.c_double),
]
coregraphics = ct.cdll.LoadLibrary(
"/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics",
)
coregraphics.CGAffineTransformMakeIdentity = getattr(coregraphics, "CGAffineTransformMakeIdentity", None)
coregraphics.CGAffineTransformRotate = coregraphics.CGAffineTransformRotate
coregraphics.CGAffineTransformRotate.restype = CGAffineTransform
coregraphics.CGAffineTransformRotate.argtypes = [CGAffineTransform, ct.c_double]
coregraphics.CGAffineTransformScale = coregraphics.CGAffineTransformScale
coregraphics.CGAffineTransformScale.restype = CGAffineTransform
coregraphics.CGAffineTransformScale.argtypes = [CGAffineTransform, ct.c_double, ct.c_double]
coregraphics.CGAffineTransformTranslate = coregraphics.CGAffineTransformTranslate
coregraphics.CGAffineTransformTranslate.restype = CGAffineTransform
coregraphics.CGAffineTransformTranslate.argtypes = [CGAffineTransform, ct.c_double, ct.c_double]
# Identity matrix.
transform = CGAffineTransform(1.0, 0.0, 0.0, 1.0, 0.0, 0.0)
if spec is None:
return transform
entries = spec if isinstance(spec, list) else [spec]
for entry in entries:
if not isinstance(entry, dict):
continue
if "rotate" in entry:
v = entry["rotate"]
if isinstance(v, str) and v.endswith("deg"):
angle = math.radians(float(v[:-3]))
elif isinstance(v, str) and v.endswith("rad"):
angle = float(v[:-3])
else:
angle = math.radians(float(v))
transform = coregraphics.CGAffineTransformRotate(transform, angle)
if "scale" in entry:
s = float(entry["scale"])
transform = coregraphics.CGAffineTransformScale(transform, s, s)
if "scale_x" in entry:
transform = coregraphics.CGAffineTransformScale(transform, float(entry["scale_x"]), 1.0)
if "scale_y" in entry:
transform = coregraphics.CGAffineTransformScale(transform, 1.0, float(entry["scale_y"]))
if "translate_x" in entry or "translate_y" in entry:
tx = float(entry.get("translate_x", 0.0))
ty = float(entry.get("translate_y", 0.0))
transform = coregraphics.CGAffineTransformTranslate(transform, tx, ty)
return transform
def _apply_transform(view: Any, props: Dict[str, Any]) -> None:
"""Apply the ``transform`` style prop via ``view.transform = ...``."""
if "transform" not in props:
return
spec = props["transform"]
if spec is None:
try:
view.setTransform_((1.0, 0.0, 0.0, 1.0, 0.0, 0.0))
except Exception:
pass
return
try:
transform = _make_transform(spec)
a = float(transform.a)
b = float(transform.b)
c = float(transform.c)
d = float(transform.d)
tx = float(transform.tx)
ty = float(transform.ty)
if not (
math.isfinite(a)
and math.isfinite(b)
and math.isfinite(c)
and math.isfinite(d)
and math.isfinite(tx)
and math.isfinite(ty)
):
# Tripwire: a NaN/inf transform crashes UIKit. Log
# (rate-limited to avoid 60 Hz spam from stuck Animated
# values) and fall back to identity so the app keeps
# running.
_tripwire_log(
"set_transform:nan",
f"[set_transform:nan] spec={spec!r} -> " f"(a={a!r}, b={b!r}, c={c!r}, d={d!r}, tx={tx!r}, ty={ty!r})",
)
view.setTransform_((1.0, 0.0, 0.0, 1.0, 0.0, 0.0))
return
# rubicon-objc accepts the C struct as a tuple of its fields.
view.setTransform_((a, b, c, d, tx, ty))
except Exception:
pass
def _apply_accessibility(view: Any, props: Dict[str, Any]) -> None:
"""Apply accessibility_label / hint / role / accessible to a view."""
if "accessible" in props:
try:
view.setIsAccessibilityElement_(bool(props["accessible"]))
except Exception:
pass
if "accessibility_label" in props:
v = props["accessibility_label"]
try:
view.setAccessibilityLabel_(str(v) if v is not None else "")
except Exception:
pass
if "accessibility_hint" in props:
v = props["accessibility_hint"]
try:
view.setAccessibilityHint_(str(v) if v is not None else "")
except Exception:
pass
if "accessibility_role" in props and props["accessibility_role"] is not None:
# UIAccessibilityTraits bitmask.
traits = {
"button": 1 << 0,
"link": 1 << 1,
"image": 1 << 2,
"search": 1 << 3,
"header": 1 << 28,
"summary_element": 1 << 6,
"selected": 1 << 5,
"static_text": 1 << 4,
"none": 0,
}
trait = traits.get(str(props["accessibility_role"]).lower())
if trait is not None:
try:
view.setAccessibilityTraits_(trait)
except Exception:
pass
def _apply_common_visual(view: Any, props: Dict[str, Any]) -> None:
"""Apply visual properties shared across many handlers."""
if "background_color" in props and props["background_color"] is not None:
color = _uicolor(props["background_color"])
view.setBackgroundColor_(color)
try:
view.layer.setBackgroundColor_(color.CGColor)
except Exception:
pass
if "overflow" in props:
view.setClipsToBounds_(props["overflow"] == "hidden")
if "opacity" in props and props["opacity"] is not None:
try:
view.setAlpha_(float(props["opacity"]))
except Exception:
pass
_apply_view_border(view, props)
_apply_shadow(view, props)
_apply_transform(view, props)
_apply_accessibility(view, props)
# Properties that handlers can animate via
# [`set_animated_property`][pythonnative.native_views.ios.IOSViewHandler.set_animated_property].
_ANIMATABLE_PROPS = {
"opacity",
"translate_x",
"translate_y",
"scale",
"scale_x",
"scale_y",
"rotate", # degrees
"background_color",
}
# ======================================================================
# Base class with shared frame/measure implementations
# ======================================================================
class IOSViewHandler(ViewHandler):
"""Base class providing the shared `set_frame` / measure contract.
All iOS handlers go through `set_frame` to apply the layout
engine's computed frames via classic ``CGRect`` positioning (Auto
Layout off). Child management defaults to UIKit's
`addSubview_:` / `removeFromSuperview` API.
"""
def set_frame(self, native_view: Any, x: float, y: float, width: float, height: float) -> None:
if native_view is None:
return
try:
frame_x = _safe_finite(x, 0.0)
frame_y = _safe_finite(y, 0.0)
frame_w = max(0.0, _safe_finite(width, 0.0))
frame_h = max(0.0, _safe_finite(height, 0.0))
native_view.setTranslatesAutoresizingMaskIntoConstraints_(True)
native_view.setFrame_(((frame_x, frame_y), (frame_w, frame_h)))
_clamp_view_corner_radius(native_view, frame_w, frame_h)
try:
_clamp_layer_corner_radius(native_view.layer, frame_w, frame_h)
except Exception:
pass
try:
parent = native_view.superview
set_content_size = getattr(parent, "setContentSize_", None)
if set_content_size is not None:
bounds = parent.bounds
content_w = max(float(bounds.size.width), frame_x + frame_w)
content_h = max(float(bounds.size.height), frame_y + frame_h)
set_content_size((content_w, content_h))
except Exception:
pass
except Exception:
pass
def measure_intrinsic(
self,
native_view: Any,
max_width: float,
max_height: float,
) -> Tuple[float, float]:
try:
mw = _safe_max(max_width, fallback=10000.0)
mh = _safe_max(max_height, fallback=10000.0)
size = native_view.sizeThatFits_((mw, mh))
w = float(size.width)
h = float(size.height)
if math.isfinite(max_width):
w = min(w, max_width)
return (w, h)
except Exception:
return (0.0, 0.0)
def set_animated_property(
self,
native_view: Any,
prop_name: str,
value: Any,
duration_ms: float = 0.0,
easing: str = "linear",
) -> None:
"""Apply ``prop_name`` to ``native_view`` immediately or animated.
Used by ``Animated.View`` to bypass the reconciler when the
bound `Animated.Value` ticks. When
``duration_ms > 0``, the change is wrapped in
``UIView.animate(withDuration:)`` so UIKit interpolates between
the current and target value at 60 FPS without further Python
involvement.
Args:
native_view: The target ``UIView``-derived instance.
prop_name: One of ``opacity``, ``translate_x``,
``translate_y``, ``scale``, ``scale_x``, ``scale_y``,
``rotate`` (degrees), ``background_color``.
value: The new property value.
duration_ms: Optional UIKit animation duration in ms; ``0``
applies the change immediately.
easing: Easing curve name (``linear``, ``ease_in``,
``ease_out``, ``ease_in_out``).
"""
if native_view is None:
return
try:
applier = _animated_applier_for(prop_name, value)
except Exception:
return
if applier is None:
return
if duration_ms <= 0:
try:
applier(native_view)
except Exception:
pass
return
try:
UIView = ObjCClass("UIView")
options = {
"linear": 1 << 16,
"ease_in": 1 << 17,
"ease_out": 1 << 18,
"ease_in_out": 0,
}.get(easing, 0)
UIView.animateWithDuration_delay_options_animations_completion_(
duration_ms / 1000.0,
0.0,
options,
lambda: applier(native_view),
None,
)
except Exception:
try:
applier(native_view)
except Exception:
pass
def _animated_applier_for(prop: str, value: Any) -> Optional[Callable[[Any], None]]:
if prop == "opacity":
v = float(value)
def _apply(view: Any) -> None:
view.setAlpha_(v)
return _apply
if prop == "background_color":
def _apply(view: Any) -> None:
view.setBackgroundColor_(_uicolor(value))
return _apply
if prop in ("translate_x", "translate_y", "scale", "scale_x", "scale_y", "rotate"):
spec = {prop: value} if prop != "rotate" else {"rotate": value}
def _apply(view: Any) -> None:
_apply_transform(view, {"transform": [spec]})
return _apply
return None
# ======================================================================
# ObjC callback targets (retained at module level)
# ======================================================================
_pn_btn_handler_map: dict = {}
_pn_btn_callback_map: dict = {}
_pn_retained_views: list = []
class _PNButtonTarget(NSObject): # type: ignore[valid-type]
@objc_method
def onTap_(self, sender: object) -> None:
# Do not introspect ``sender`` here. On rubicon-objc 0.5.x the
# selector trampoline can hand this callback a raw ObjC pointer;
# calling ``getattr(sender, "ptr", ...)`` has been observed to
# segfault before the user's callback runs.
cb = _pn_btn_callback_map.get(id(self))
if cb is not None:
cb()
_pn_tf_change_callback_map: dict = {}
_pn_tf_submit_callback_map: dict = {}
_pn_tf_raw_target_map: dict = {}
_PN_TEXTFIELD_TARGET_CLS: Optional[int] = None
_textfield_edit_imp_ref: Any = None
_textfield_submit_imp_ref: Any = None
def _textfield_text(sender_ptr: int) -> str:
if not sender_ptr:
return ""
try:
_objc_msgSend.restype = _ct.c_void_p
_objc_msgSend.argtypes = [_ct.c_void_p, _ct.c_void_p]
nsstring_ptr = _objc_msgSend(_ct.c_void_p(sender_ptr), _SEL_TEXT)
if not nsstring_ptr:
return ""
_objc_msgSend.restype = _ct.c_char_p
_objc_msgSend.argtypes = [_ct.c_void_p, _ct.c_void_p]
raw = _objc_msgSend(_ct.c_void_p(nsstring_ptr), _SEL_UTF8STRING)
if not raw:
return ""
return raw.decode("utf-8", errors="replace")
except Exception:
return ""
def _textfield_on_edit_imp(self_ptr: int, _cmd: int, sender_ptr: int) -> None:
cb = _pn_tf_change_callback_map.get(int(self_ptr))
if cb is None:
return
text = _textfield_text(int(sender_ptr or 0))
try:
cb(text)
except Exception:
pass
def _textfield_on_submit_imp(self_ptr: int, _cmd: int, sender_ptr: int) -> None:
cb = _pn_tf_submit_callback_map.get(int(self_ptr))
if cb is None:
return
text = _textfield_text(int(sender_ptr or 0))
try:
cb(text)
except Exception:
pass
def _ensure_textfield_target_class() -> Optional[int]:
global _PN_TEXTFIELD_TARGET_CLS, _textfield_edit_imp_ref, _textfield_submit_imp_ref
if _PN_TEXTFIELD_TARGET_CLS is not None:
return _PN_TEXTFIELD_TARGET_CLS
existing = _get_cls(b"PNTextFieldActionTarget")
if existing:
_PN_TEXTFIELD_TARGET_CLS = int(existing)
return _PN_TEXTFIELD_TARGET_CLS
cls = _alloc_cls(_NS_OBJECT_CLS, b"PNTextFieldActionTarget", 0)
if not cls:
return None
action_type = _ct.CFUNCTYPE(None, _ct.c_void_p, _ct.c_void_p, _ct.c_void_p)
_textfield_edit_imp_ref = action_type(_textfield_on_edit_imp)
_textfield_submit_imp_ref = action_type(_textfield_on_submit_imp)
_add_method(cls, _SEL_ON_EDIT, _ct.cast(_textfield_edit_imp_ref, _ct.c_void_p), b"v@:@")
_add_method(cls, _SEL_ON_SUBMIT, _ct.cast(_textfield_submit_imp_ref, _ct.c_void_p), b"v@:@")
_reg_cls(cls)
_PN_TEXTFIELD_TARGET_CLS = int(cls)
return _PN_TEXTFIELD_TARGET_CLS
def _new_textfield_target() -> Optional[int]:
cls = _ensure_textfield_target_class()
if not cls:
return None
_objc_msgSend.restype = _ct.c_void_p
_objc_msgSend.argtypes = [_ct.c_void_p, _ct.c_void_p]
raw = _objc_msgSend(_ct.c_void_p(cls), _SEL_ALLOC)
raw = _objc_msgSend(_ct.c_void_p(raw), _SEL_INIT)
raw = _objc_msgSend(_ct.c_void_p(raw), _SEL_RETAIN)
return int(raw) if raw else None
def _attach_textfield_raw_target(tf: Any, props: Dict[str, Any]) -> None:
tf_ptr = _objc_ptr(tf)
if not tf_ptr:
return
target_ptr = _pn_tf_raw_target_map.get(id(tf))
if target_ptr is None:
target_ptr = _new_textfield_target()
if not target_ptr:
return
_pn_tf_raw_target_map[id(tf)] = target_ptr
_pn_retained_views.append(target_ptr)
_objc_msgSend.restype = None
_objc_msgSend.argtypes = [
_ct.c_void_p,
_ct.c_void_p,
_ct.c_void_p,
_ct.c_void_p,
_ct.c_ulong,
]
_objc_msgSend(
_ct.c_void_p(tf_ptr),
_SEL_ADD_TARGET_ACTION_EVENTS,
_ct.c_void_p(target_ptr),
_SEL_ON_EDIT,
1 << 17,
)
_objc_msgSend(
_ct.c_void_p(tf_ptr),
_SEL_ADD_TARGET_ACTION_EVENTS,
_ct.c_void_p(target_ptr),
_SEL_ON_SUBMIT,
1 << 6,
)
if "on_change" in props:
_pn_tf_change_callback_map[int(target_ptr)] = props["on_change"]
if "on_submit" in props:
_pn_tf_submit_callback_map[int(target_ptr)] = props["on_submit"]
_pn_switch_handler_map: dict = {}
class _PNSwitchTarget(NSObject): # type: ignore[valid-type]
_callback: Optional[Callable[[bool], None]] = None
@objc_method
def onToggle_(self, sender: object) -> None:
if self._callback is not None:
try:
self._callback(bool(sender.isOn()))
except Exception:
pass
_pn_slider_handler_map: dict = {}
class _PNSliderTarget(NSObject): # type: ignore[valid-type]
_callback: Optional[Callable[[float], None]] = None
@objc_method
def onSlide_(self, sender: object) -> None:
if self._callback is not None:
try:
self._callback(float(sender.value))
except Exception:
pass
_pn_pressable_state: dict = {}
class _PNPressableTarget(NSObject): # type: ignore[valid-type]
@objc_method
def onTouchDown_(self, sender: object) -> None:
info = _pn_pressable_state.get(id(self))
if not info:
return
view = info.get("view")
opacity = info.get("pressed_opacity", 0.6)
if view is not None:
try:
UIView = ObjCClass("UIView")
UIView.animateWithDuration_animations_(0.05, lambda: view.setAlpha_(float(opacity)))
except Exception:
pass
@objc_method
def onTouchUp_(self, sender: object) -> None:
info = _pn_pressable_state.get(id(self))
if not info:
return
view = info.get("view")
cb = info.get("on_press")
if view is not None:
try:
UIView = ObjCClass("UIView")
UIView.animateWithDuration_animations_(0.1, lambda: view.setAlpha_(1.0))
except Exception:
pass
if cb is not None:
try:
cb()
except Exception:
pass
@objc_method
def onTouchCancel_(self, sender: object) -> None:
info = _pn_pressable_state.get(id(self))
if not info:
return
view = info.get("view")
if view is not None:
try:
UIView = ObjCClass("UIView")
UIView.animateWithDuration_animations_(0.1, lambda: view.setAlpha_(1.0))
except Exception:
pass
@objc_method
def onLongPress_(self, sender: object) -> None:
info = _pn_pressable_state.get(id(self))
if not info:
return
# UILongPressGestureRecognizer fires on state Began (state==1).
try:
state = int(sender.state)
except Exception:
state = 1
if state != 1:
return
cb = info.get("on_long_press")
if cb is not None:
try:
cb()
except Exception:
pass
# ======================================================================
# Flex container handler (shared by Column, Row, View)
# ======================================================================
class FlexContainerHandler(IOSViewHandler):
"""Container for flex layout — a bare `UIView`.
All flex semantics (direction, alignment, distribution, padding)
are computed by the layout engine and applied via
[`set_frame`][pythonnative.native_views.ios.IOSViewHandler.set_frame].
"""
def create(self, props: Dict[str, Any]) -> Any:
v = ObjCClass("UIView").alloc().init()
v.setTranslatesAutoresizingMaskIntoConstraints_(True)
_apply_common_visual(v, props)
return v
def update(self, native_view: Any, changed: Dict[str, Any]) -> None:
_apply_common_visual(native_view, changed)
def add_child(self, parent: Any, child: Any) -> None:
try:
child.setTranslatesAutoresizingMaskIntoConstraints_(True)
except Exception:
pass
parent.addSubview_(child)
def remove_child(self, parent: Any, child: Any) -> None:
child.removeFromSuperview()
def insert_child(self, parent: Any, child: Any, index: int) -> None:
try:
child.setTranslatesAutoresizingMaskIntoConstraints_(True)
except Exception:
pass
parent.insertSubview_atIndex_(child, index)
# ======================================================================
# Leaf handlers
# ======================================================================
class TextHandler(IOSViewHandler):
def create(self, props: Dict[str, Any]) -> Any:
label = ObjCClass("UILabel").alloc().init()
label.setNumberOfLines_(0)
label.setTranslatesAutoresizingMaskIntoConstraints_(True)
self._apply(label, props)
return label
def update(self, native_view: Any, changed: Dict[str, Any]) -> None:
self._apply(native_view, changed)
def _font_for(self, size: float, weight: Any, family: Optional[str], italic: bool) -> Any:
"""Resolve a UIFont from family/weight/italic/size keys."""
size = float(size)
if family:
font = UIFont.fontWithName_size_(str(family), size)
if font is not None:
if italic:
desc = font.fontDescriptor.fontDescriptorWithSymbolicTraits_(2) # italic trait
if desc is not None:
font = UIFont.fontWithDescriptor_size_(desc, size)
return font
# Numeric weight: 100..900. UIFontWeight constants are:
# ultraLight=-0.8, thin=-0.6, light=-0.4, regular=0, medium=0.23,
# semibold=0.3, bold=0.4, heavy=0.56, black=0.62.
weight_const = 0.0
if isinstance(weight, str):
named = {
"ultralight": -0.8,
"thin": -0.6,
"light": -0.4,
"regular": 0.0,
"normal": 0.0,
"medium": 0.23,
"semibold": 0.3,
"bold": 0.4,
"heavy": 0.56,
"black": 0.62,
}
weight_const = named.get(weight.lower(), 0.0)
elif isinstance(weight, (int, float)):
n = max(100.0, min(900.0, float(weight)))
mapping = [
(100, -0.8),
(200, -0.6),
(300, -0.4),
(400, 0.0),
(500, 0.23),
(600, 0.3),
(700, 0.4),
(800, 0.56),
(900, 0.62),
]
for w, c in mapping:
if n <= w:
weight_const = c
break
font = UIFont.systemFontOfSize_weight_(size, weight_const)
if italic:
try:
desc = font.fontDescriptor.fontDescriptorWithSymbolicTraits_(2)
if desc is not None:
font = UIFont.fontWithDescriptor_size_(desc, size)
except Exception:
pass
return font
def _apply(self, label: Any, props: Dict[str, Any]) -> None:
if "text" in props:
label.setText_(str(props["text"]) if props["text"] is not None else "")
# Font requires combining size + weight + family + italic + bold.
font_keys_present = any(k in props for k in ("font_size", "font_weight", "font_family", "italic", "bold"))
if font_keys_present:
current = label.font
try:
current_size = float(current.pointSize) if current is not None else 17.0
except Exception:
current_size = 17.0
size = float(props.get("font_size", current_size)) if props.get("font_size") is not None else current_size
weight = props.get("font_weight")
if weight is None and props.get("bold"):
weight = "bold"
family = props.get("font_family")
italic = bool(props.get("italic"))
label.setFont_(self._font_for(size, weight, family, italic))
if "color" in props and props["color"] is not None:
label.setTextColor_(_uicolor(props["color"]))