FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/native_views/base.py at main · andevsr/pythonnative · GitHub
andevsr
pythonnative
Repository navigation
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
native_views
/
base.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
253 lines (200 loc) · 9.44 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
native_views
/
base.py
Copy path
File metadata and controls
253 lines (200 loc) · 9.44 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
"""Shared base classes and utilities for native-view handlers.
Provides the [`ViewHandler`][pythonnative.native_views.base.ViewHandler]
protocol implemented by Android and iOS handlers, plus the
[`parse_color_int`][pythonnative.native_views.base.parse_color_int]
helper shared across platforms.
Layout itself is *not* a handler responsibility. The pure-Python flex
engine in ``pythonnative.layout`` owns sizing and positioning;
handlers receive computed frames via
[`set_frame`][pythonnative.native_views.base.ViewHandler.set_frame] and
optionally expose an intrinsic-size hook via
[`measure_intrinsic`][pythonnative.native_views.base.ViewHandler.measure_intrinsic]
for content-sized leaves (text, buttons, images).
"""
import
math
from
typing
import
Any
,
Dict
,
Tuple
,
Union
class
ViewHandler
:
"""Protocol implemented by every native-view handler.
A `ViewHandler` knows how to create, update, re-parent, and destroy
native views of one element type. The reconciler never calls a
handler directly; it emits a batch of mutation ops
(`pythonnative.mutations`) that the
[`NativeViewRegistry`][pythonnative.native_views.NativeViewRegistry]
applies by dispatching to handlers. Handlers never need to know
about `Element` or `VNode`.
Event contract: props delivered to
[`create`][pythonnative.native_views.base.ViewHandler.create] /
[`update`][pythonnative.native_views.base.ViewHandler.update]
contain **no Python callables**. The set of event names wired on
the element arrives under the ``_pn_events`` key (see
[`event_names`][pythonnative.events.event_names]); handlers wire
platform listeners once at create time and forward firings through
[`dispatch_event`][pythonnative.events.dispatch_event] using the
tag passed to ``create``.
Subclasses must override ``create`` and ``update``. Container
handlers override the child-management methods; leaf handlers can
leave them as no-ops. Handlers whose intrinsic size depends on
content (text, buttons, images) override
[`measure_intrinsic`][pythonnative.native_views.base.ViewHandler.measure_intrinsic].
"""
def
create
(
self
,
tag
:
int
,
props
:
Dict
[
str
,
Any
])
->
Any
:
"""Create a fresh native view and apply initial *visual* props.
Layout-related props (``width``, ``height``, ``flex``, ``padding``,
etc.) are consumed by the layout engine and applied via
[`set_frame`][pythonnative.native_views.base.ViewHandler.set_frame],
so handlers should ignore them here.
Args:
tag: The reconciler-assigned identity for this view. Used
when dispatching events back into Python.
props: Initial props dict (callable-free; event names under
``_pn_events``).
Returns:
The platform-native view object.
Raises:
NotImplementedError: Subclasses must override.
"""
raise
NotImplementedError
def
update
(
self
,
native_view
:
Any
,
changed_props
:
Dict
[
str
,
Any
])
->
None
:
"""Apply only the *visual* props that changed since the last render.
Args:
native_view: The platform-native view to mutate.
changed_props: Props whose values changed (a value of
`None` indicates the prop was removed).
Raises:
NotImplementedError: Subclasses must override.
"""
raise
NotImplementedError
def
insert_child
(
self
,
parent
:
Any
,
child
:
Any
,
index
:
int
)
->
None
:
"""Ensure `child` sits at `index` among `parent`'s children.
Must be **move-aware**: when `child` is already attached to
`parent`, reposition it instead of attaching twice. Handlers
should clamp `index` to the current child count. No-op for
leaf handlers.
"""
def
remove_child
(
self
,
parent
:
Any
,
child
:
Any
)
->
None
:
"""Remove `child` from `parent` without destroying it. No-op for leaf handlers."""
def
destroy
(
self
,
native_view
:
Any
)
->
None
:
"""Release platform resources owned by ``native_view``.
Called exactly once when the reconciler unmounts the view.
The default is a no-op; override to detach listeners, cancel
in-flight work, or destroy widgets that the platform doesn't
garbage-collect.
"""
def
set_frame
(
self
,
native_view
:
Any
,
x
:
float
,
y
:
float
,
width
:
float
,
height
:
float
)
->
None
:
"""Position and size ``native_view`` relative to its parent.
Coordinates are in points and relative to the parent's content
origin. Default no-op so handlers that don't need explicit
positioning (e.g., `Modal`) can opt out.
Args:
native_view: The platform-native view.
x: X-coordinate (points) of the view's top-left corner
relative to its parent's content origin.
y: Y-coordinate (points) of the view's top-left corner.
width: View width in points.
height: View height in points.
"""
def
measure_intrinsic
(
self
,
native_view
:
Any
,
max_width
:
float
,
max_height
:
float
,
)
->
Tuple
[
float
,
float
]:
"""Return the natural ``(width, height)`` of a content-sized view.
Used by the layout engine for leaves whose size depends on
their content (text, buttons, images). Either ``max_width`` or
``max_height`` may be `math.inf` to indicate no constraint.
The default implementation returns ``(0, 0)``; override for
leaves whose size depends on their content. Container handlers
leave this alone; the engine sizes containers by laying out
their children.
Args:
native_view: The platform-native view to measure.
max_width: Maximum width in points (or `math.inf`).
max_height: Maximum height in points (or `math.inf`).
Returns:
``(width, height)`` in points.
"""
return
(
0.0
,
0.0
)
def
command
(
self
,
native_view
:
Any
,
name
:
str
,
args
:
Dict
[
str
,
Any
])
->
Any
:
"""Execute an imperative command (e.g. ``"scroll_to_offset"``).
Commands are the escape hatch for one-shot imperative actions
that don't fit declarative props: scrolling, focusing,
flashing indicators. Unknown commands should be ignored.
Args:
native_view: The platform-native view.
name: Command name.
args: Command arguments.
Returns:
An optional command-specific result.
"""
return
None
def
set_animated_property
(
self
,
native_view
:
Any
,
prop_name
:
str
,
value
:
Any
)
->
None
:
"""Apply one frame of a Python-driven animation immediately.
This is the fallback path used by the desktop preview and by
animations the platform cannot drive natively. ``prop_name``
is one of ``opacity``, ``background_color``, ``translate_x``,
``translate_y``, ``scale``, ``scale_x``, ``scale_y``,
``rotate``.
"""
def
start_animation
(
self
,
native_view
:
Any
,
anim_id
:
int
,
prop_name
:
str
,
spec
:
Dict
[
str
,
Any
],
)
->
bool
:
"""Start a natively-driven animation, if the platform supports it.
``spec`` describes the animation::
{"kind": "timing", "from": 0.0, "to": 1.0,
"duration_ms": 300.0, "easing": "ease_in_out"}
{"kind": "spring", "from": ..., "to": ...,
"stiffness": 100.0, "damping": 10.0, "mass": 1.0,
"initial_velocity": 0.0}
Implementations must invoke
``pythonnative.animated.native_animation_completed(anim_id, finished)``
when the animation completes or is cancelled.
Returns:
``True`` when the animation was started natively. ``False``
tells the caller to fall back to the Python ticker (the
default).
"""
return
False
def
cancel_animation
(
self
,
native_view
:
Any
,
anim_id
:
int
)
->
Any
:
"""Cancel a natively-driven animation.
Returns:
The property's current (presentation) value when the
platform can read it, else ``None``.
"""
return
None
# ======================================================================
# Color parsing
# ======================================================================
def
parse_color_int
(
color
:
Union
[
str
,
int
])
->
int
:
"""Parse a color value into a signed 32-bit ARGB int.
Accepts `"#RRGGBB"`, `"#AARRGGBB"`, or a raw integer. Java APIs
such as `setBackgroundColor` expect a signed 32-bit int, so values
with a high alpha byte (e.g., `0xFF......`) must be converted to
their negative two's-complement equivalent.
Args:
color: Hex string (with or without leading `#`) or an int.
Returns:
Signed 32-bit ARGB int suitable for Android's color APIs.
"""
if
isinstance
(
color
,
int
):
val
=
color
else
:
c
=
color
.
strip
().
lstrip
(
"#"
)
if
len
(
c
)
==
6
:
c
=
"FF"
+
c
val
=
int
(
c
,
16
)
if
val
>
0x7FFFFFFF
:
val
-=
0x100000000
return
val
# ======================================================================
# Helpers shared by Android and iOS measure callbacks
# ======================================================================
def
_safe_max
(
value
:
float
,
fallback
:
float
=
1e6
)
->
float
:
"""Clamp ``math.inf`` to a large finite value for native measure calls."""
if
not
math
.
isfinite
(
value
):
return
fallback
return
max
(
0.0
,
value
)
Back
|
FazBrowse Home
|
New Git URL