FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/hosts/native.py at main · pythonnative/pythonnative · GitHub
pythonnative
/
pythonnative
Public
Notifications
You must be signed in to change notification settings
Fork
23
Star
131
Code
Issues
11
Pull requests
4
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
hosts
/
native.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
330 lines (266 loc) · 12.1 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
hosts
/
native.py
Copy path
File metadata and controls
330 lines (266 loc) · 12.1 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
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
"""On-device application surface hosting, shared by iOS and Android.
Native hosts send asynchronous lifecycle, viewport, and back events keyed by
surface host ID. Python attaches the application root and publishes cached
restoration state through the Host module. Navigation owns logical Screen
children in that same application tree.
"""
from
__future__
import
annotations
import
json
import
threading
from
typing
import
Any
,
Dict
,
Optional
,
Sequence
,
Tuple
from
..
import
appearance
,
diagnostics
,
platform_metrics
from
..
bridge
import
codec
from
..
native_modules
.
registry
import
native_module
from
.
base
import
ScreenHost
,
flush_hosts
__all__
=
[
"NativeScreenHost"
,
"dispatch_host_event"
,
"host_for_screen"
,
"live_hosts"
]
_HOSTS
:
Dict
[
int
,
"NativeScreenHost"
]
=
{}
_SCHEDULED
:
Dict
[
int
,
ScreenHost
]
=
{}
_flush_pending
=
False
def
host_for_screen
(
screen_id
:
int
)
->
Optional
[
"NativeScreenHost"
]:
"""Return the host registered for ``screen_id`` (``None`` if unknown)."""
return
_HOSTS
.
get
(
int
(
screen_id
))
def
live_hosts
()
->
Sequence
[
"NativeScreenHost"
]:
"""Every host currently registered, in creation order."""
return
list
(
_HOSTS
.
values
())
def
_host_module
()
->
Any
:
return
native_module
(
"Host"
)
# ======================================================================
# Deferred renders
# ======================================================================
def
_flush_scheduled
()
->
None
:
global
_flush_pending
_flush_pending
=
False
hosts
=
list
(
_SCHEDULED
.
values
())
_SCHEDULED
.
clear
()
if
hosts
:
diagnostics
.
log
(
f"render_scheduler: flushing
{
len
(
hosts
)
}
host(s)"
)
flush_hosts
(
hosts
)
def
_request_flush
()
->
None
:
"""Queue one application-thread flush of every scheduled host."""
global
_flush_pending
if
_flush_pending
:
return
_flush_pending
=
True
from
..
runtime
import
call_threadsafe
call_threadsafe
(
_flush_scheduled
)
# ======================================================================
# Payload helpers
# ======================================================================
def
_optional_float
(
payload
:
Dict
[
str
,
Any
],
key
:
str
)
->
Optional
[
float
]:
"""Return ``payload[key]`` as a float, or ``None`` when absent or not a number."""
value
=
payload
.
get
(
key
)
if
isinstance
(
value
,
bool
)
or
not
isinstance
(
value
, (
int
,
float
)):
return
None
return
float
(
value
)
def
_publish_metrics
(
payload
:
Any
)
->
Tuple
[
float
,
float
]:
"""Publish viewport, insets, keyboard, density, and color scheme from a host payload.
The payload carries ``width`` and ``height`` (the window, in layout
units) and may carry ``scale``, ``font_scale``, ``screen_width``, and
``screen_height``. A missing density keeps the last published value
(``1.0`` initially); a missing screen size falls back to the window.
Returns the ``(width, height)`` it found (``0, 0`` when absent).
"""
if
not
isinstance
(
payload
,
dict
):
return
(
0.0
,
0.0
)
width
=
float
(
payload
.
get
(
"width"
)
or
0.0
)
height
=
float
(
payload
.
get
(
"height"
)
or
0.0
)
scale
=
_optional_float
(
payload
,
"scale"
)
font_scale
=
_optional_float
(
payload
,
"font_scale"
)
insets
=
payload
.
get
(
"insets"
)
if
isinstance
(
insets
,
dict
):
platform_metrics
.
set_safe_area_insets
(
float
(
insets
.
get
(
"top"
)
or
0.0
),
float
(
insets
.
get
(
"left"
)
or
0.0
),
float
(
insets
.
get
(
"bottom"
)
or
0.0
),
float
(
insets
.
get
(
"right"
)
or
0.0
),
)
if
"keyboard_height"
in
payload
:
platform_metrics
.
set_keyboard_height
(
float
(
payload
.
get
(
"keyboard_height"
)
or
0.0
))
scheme
=
payload
.
get
(
"color_scheme"
)
if
scheme
in
(
"light"
,
"dark"
):
appearance
.
set_system_color_scheme
(
str
(
scheme
))
if
width
>
0
and
height
>
0
:
platform_metrics
.
set_window_dimensions
(
width
,
height
,
scale
=
scale
,
font_scale
=
font_scale
)
screen_width
=
_optional_float
(
payload
,
"screen_width"
)
or
width
screen_height
=
_optional_float
(
payload
,
"screen_height"
)
or
height
platform_metrics
.
set_screen_dimensions
(
screen_width
,
screen_height
,
scale
=
scale
,
font_scale
=
font_scale
)
return
(
width
,
height
)
# ======================================================================
# Host
# ======================================================================
class
NativeScreenHost
(
ScreenHost
):
"""Screen host addressed by an integer ``screen_id`` on the bridge."""
def
__init__
(
self
,
screen_id
:
int
,
component_path
:
str
,
component
:
Any
)
->
None
:
super
().
__init__
(
int
(
screen_id
),
component_path
,
component
)
self
.
screen_id
=
int
(
screen_id
)
self
.
_pending_viewport
:
Optional
[
Tuple
[
float
,
float
]]
=
None
_HOSTS
[
self
.
screen_id
]
=
self
# -- lifecycle ------------------------------------------------------
def
on_destroy
(
self
)
->
None
:
"""Forget the screen id, then tear down the tree."""
_HOSTS
.
pop
(
self
.
screen_id
,
None
)
_SCHEDULED
.
pop
(
id
(
self
),
None
)
super
().
on_destroy
()
def
apply_metrics
(
self
,
payload
:
Any
)
->
None
:
"""Publish the metrics carried by a host event and resize the viewport."""
width
,
height
=
_publish_metrics
(
payload
)
if
width
>
0
and
height
>
0
:
self
.
_pending_viewport
=
(
width
,
height
)
self
.
set_viewport_size
(
width
,
height
)
# -- platform primitives -------------------------------------------
def
_show_error
(
self
,
payload
:
Dict
[
str
,
Any
])
->
None
:
from
..
bridge
import
get_transport
get_transport
().
call
(
"Host"
,
"show_error"
,
codec
.
dumps
({
"call_id"
:
0
,
"args"
:
payload
}))
def
_dismiss_error
(
self
)
->
None
:
from
..
bridge
import
get_transport
get_transport
().
call
(
"Host"
,
"dismiss_error"
,
codec
.
dumps
({
"call_id"
:
0
,
"args"
: {}}))
def
_initial_viewport_size
(
self
)
->
Optional
[
Tuple
[
float
,
float
]]:
if
self
.
_pending_viewport
is
not
None
:
return
self
.
_pending_viewport
dims
=
platform_metrics
.
get_window_dimensions
()
if
dims
.
width
>
0
and
dims
.
height
>
0
:
return
(
dims
.
width
,
dims
.
height
)
return
None
def
_schedule_render_async
(
self
)
->
bool
:
if
self
.
_render_scheduled
:
return
True
self
.
_render_scheduled
=
True
_SCHEDULED
[
id
(
self
)]
=
self
try
:
_request_flush
()
except
Exception
as
exc
:
self
.
_render_scheduled
=
False
_SCHEDULED
.
pop
(
id
(
self
),
None
)
diagnostics
.
log
(
f"request_render: bridge defer failed (
{
exc
!r
}
); rendering synchronously"
)
return
False
return
True
def
_attach_root
(
self
,
native_view
:
Any
)
->
None
:
tag
=
getattr
(
native_view
,
"tag"
,
None
)
if
tag
is
None
:
return
# Native answers with the viewport the root now occupies, which
# is the earliest exact size available on iOS.
result
=
_host_module
().
call
(
"attach_root"
,
screen
=
self
.
screen_id
,
tag
=
int
(
tag
))
if
isinstance
(
result
,
dict
):
self
.
apply_metrics
(
result
)
def
_detach_root
(
self
,
native_view
:
Any
)
->
None
:
tag
=
getattr
(
native_view
,
"tag"
,
None
)
if
tag
is
None
:
return
try
:
_host_module
().
call
(
"detach_root"
,
screen
=
self
.
screen_id
,
tag
=
int
(
tag
))
except
Exception
:
diagnostics
.
swallowed
(
"hosts.native.detach_root"
)
def
cache_navigation_state
(
self
,
state
:
Dict
[
str
,
Any
])
->
None
:
"""Cache navigation before the platform's synchronous state-saving callback."""
super
().
cache_navigation_state
(
state
)
_host_module
().
call
(
"cache_state"
,
screen
=
self
.
screen_id
,
state
=
json
.
dumps
(
self
.
args
))
def
_native_set_options
(
self
,
options
:
Dict
[
str
,
Any
])
->
None
:
_host_module
().
call
(
"set_options"
,
screen
=
self
.
screen_id
,
options
=
codec
.
to_jsonable
(
options
or
{}))
# ======================================================================
# Inbound host events
# ======================================================================
_create_lock
=
threading
.
Lock
()
def
dispatch_host_event
(
screen_id
:
int
,
event
:
str
,
payload
:
Any
)
->
Optional
[
str
]:
"""Route ``callback("host", screen_id, event, payload)`` to a host.
Events (payloads are what ``PNViewController`` and
``PNScreenFragment`` send):
- ``create`` ``{"path", "args", "restored_state", ...metrics}``:
import the component, create the host, and mount. ``path`` is the
dotted component path (``None`` means the app entry module) and
``args`` a JSON string. Returns ``{"root": tag}``.
- ``start`` / ``resume`` / ``pause`` / ``stop`` / ``destroy``:
lifecycle. ``resume`` and ``layout`` carry metrics.
- ``layout`` ``{width, height, insets, keyboard_height, color_scheme,
scale, font_scale, screen_width, screen_height}``.
- ``appearance`` ``{"color_scheme"}``.
- ``back_pressed``: returns ``"true"`` when a handler consumed it.
- ``save_state`` / ``restore_state``: instance-state hooks.
- ``flush``: run deferred renders now.
Returns a JSON string for request-style events, else ``None``.
"""
screen_id
=
int
(
screen_id
)
if
event
==
"create"
:
return
_create
(
screen_id
,
payload
if
isinstance
(
payload
,
dict
)
else
{})
if
event
==
"flush"
:
_flush_scheduled
()
return
None
if
event
==
"appearance"
:
_publish_metrics
(
payload
)
return
None
host
=
_HOSTS
.
get
(
screen_id
)
if
host
is
None
:
diagnostics
.
log
(
f"dispatch_host_event: no host for screen=
{
screen_id
}
event=
{
event
!r
}
"
)
return
None
if
event
==
"reload"
:
host
.
reload
()
return
None
if
event
==
"layout"
:
host
.
apply_metrics
(
payload
)
return
None
if
event
==
"resume"
:
host
.
apply_metrics
(
payload
)
host
.
on_resume
()
return
None
if
event
==
"pause"
:
host
.
on_pause
()
return
None
if
event
==
"back_pressed"
:
if
not
host
.
on_back_pressed
():
_host_module
().
call
(
"finish"
,
screen
=
host
.
screen_id
)
return
None
if
event
in
(
"save_state"
,
"restore_state"
):
# Restoration state is cached as Python publishes it; the host
# has nothing synchronous to do when the platform saves.
return
None
if
event
==
"destroy"
:
host
.
on_destroy
()
return
None
diagnostics
.
log
(
f"dispatch_host_event: unknown event
{
event
!r
}
"
)
return
None
def
_create
(
screen_id
:
int
,
payload
:
Dict
[
str
,
Any
])
->
Optional
[
str
]:
from
.
import
import_component
component_path
=
str
(
payload
.
get
(
"path"
)
or
payload
.
get
(
"component"
)
or
_entry_module
())
with
_create_lock
:
existing
=
_HOSTS
.
get
(
screen_id
)
if
existing
is
not
None
:
existing
.
apply_metrics
(
payload
)
existing
.
on_create
()
return
_root_json
(
existing
)
component
=
import_component
(
component_path
)
host
=
NativeScreenHost
(
screen_id
,
component_path
,
component
)
args
=
payload
.
get
(
"args"
)
if
args
:
host
.
set_args
(
args
)
if
not
(
payload
.
get
(
"width"
)
and
payload
.
get
(
"height"
)):
# ``create`` is sent before the first layout pass; ask native for
# its best guess so the first commit lays out at the right size.
try
:
viewport
=
_host_module
().
call
(
"viewport"
,
screen
=
screen_id
)
except
Exception
:
viewport
=
None
if
isinstance
(
viewport
,
dict
):
payload
=
{
**
viewport
,
**
payload
}
_publish_metrics
(
payload
)
width
=
float
(
payload
.
get
(
"width"
)
or
0.0
)
height
=
float
(
payload
.
get
(
"height"
)
or
0.0
)
if
width
>
0
and
height
>
0
:
host
.
_pending_viewport
=
(
width
,
height
)
restored
=
payload
.
get
(
"restored_state"
)
if
restored
:
decoded
=
codec
.
loads
(
restored
)
if
isinstance
(
restored
,
str
)
else
restored
if
isinstance
(
decoded
,
dict
):
host
.
args
=
decoded
host
.
on_create
()
return
_root_json
(
host
)
def
_entry_module
()
->
str
:
import
os
return
os
.
environ
.
get
(
"PN_ENTRY_MODULE"
)
or
"app.main"
def
_root_json
(
host
:
ScreenHost
)
->
str
:
tag
=
getattr
(
host
.
root_native_view
,
"tag"
,
None
)
return
codec
.
dumps
({
"root"
:
None
if
tag
is
None
else
int
(
tag
)})
def
_reset_for_tests
()
->
None
:
global
_flush_pending
_HOSTS
.
clear
()
_SCHEDULED
.
clear
()
_flush_pending
=
False
Back
|
FazBrowse Home
|
New Git URL