FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
pythonnative/src/pythonnative/screen.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
/
screen.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
2068 lines (1743 loc) · 81.3 KB
Breadcrumbs
pythonnative
/
src
/
pythonnative
/
screen.py
Copy path
File metadata and controls
2068 lines (1743 loc) · 81.3 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
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
"""Screen host: the bridge between native lifecycle and function components.
Users do not write screen classes by hand. Instead they write
``@component`` functions and the native template calls
[`create_screen`][pythonnative.create_screen] to obtain a host that
manages the reconciler and lifecycle for that screen.
The screen host owns:
- A [`Reconciler`][pythonnative.reconciler.Reconciler] backed by the
platform's native-view registry.
- A [`NavigationHandle`][pythonnative.hooks.NavigationHandle] (delivered to
components via the navigation context) so screens can push and pop
without holding a direct reference to native classes.
- Render scheduling. State changes during render are queued and drained
in batches so the reconciler runs at most a bounded number of passes
per user gesture.
Example:
User code defines a top-level component named ``App``:
```python
import pythonnative as pn
@pn.component
def App():
count, set_count = pn.use_state(0)
return pn.Column(
pn.Text(f"Count: {count}", style={"font_size": 24}),
pn.Button("Tap me", on_press=lambda: set_count(count + 1)),
style={"spacing": 12, "padding": 16},
)
```
The native template wires it in:
```python
host = pythonnative.screen.create_screen(
"app.main",
native_instance,
)
host.on_create()
```
"""
import
importlib
import
json
import
os
import
sys
import
threading
import
traceback
from
typing
import
Any
,
Dict
,
Optional
,
Sequence
,
Tuple
from
.
import
diagnostics
from
.
utils
import
IS_ANDROID
,
IS_DESKTOP
,
IS_IOS
,
set_android_context
_MAX_RENDER_PASSES
=
25
_DEBUG_ENV
=
"PYTHONNATIVE_DEBUG"
def
_debug_enabled
()
->
bool
:
return
os
.
environ
.
get
(
_DEBUG_ENV
,
""
).
lower
()
in
{
"1"
,
"true"
,
"yes"
,
"on"
}
def
_log_pn
(
msg
:
str
)
->
None
:
"""Emit optional diagnostics when ``PYTHONNATIVE_DEBUG`` is enabled."""
if
not
_debug_enabled
():
return
try
:
print
(
f"[PN]
{
msg
}
"
,
flush
=
True
)
except
Exception
:
pass
# ======================================================================
# Component path resolution
# ======================================================================
def
_resolve_component_path
(
component_ref
:
Any
)
->
str
:
"""Resolve a component function or string into a `module.name` path."""
if
isinstance
(
component_ref
,
str
):
return
component_ref
func
=
getattr
(
component_ref
,
"__wrapped__"
,
component_ref
)
module
=
getattr
(
func
,
"__module__"
,
None
)
name
=
getattr
(
func
,
"__name__"
,
None
)
if
module
and
name
:
return
f"
{
module
}
.
{
name
}
"
raise
ValueError
(
f"Cannot resolve component path for
{
component_ref
!r
}
"
)
def
_missing_module_is_target
(
exc
:
ModuleNotFoundError
,
dotted
:
str
)
->
bool
:
"""Return ``True`` when ``exc`` means ``dotted`` itself is absent.
Distinguishes "the component module/package cannot be found" (so the
caller should fall through to the next resolution strategy) from "the
module exists but raised :class:`ModuleNotFoundError` while importing
one of *its own* dependencies". The latter must propagate so the
developer sees the real missing import (e.g. ``No module named
'emoji'``) instead of a misleading "could not resolve component".
"""
missing
=
exc
.
name
or
""
return
missing
==
dotted
or
dotted
.
startswith
(
missing
+
"."
)
def
_import_component
(
component_path
:
str
)
->
Any
:
"""Import a component by module or dotted-attribute path.
PythonNative's entry-point convention is "define a function named
``App`` at the top of your module, and the native templates will
find it". So the templates pass a *module path* like
``"app.main"`` and this helper imports the module and returns its
``App`` attribute.
A dotted ``module.Attribute`` path is also accepted as an escape
hatch (e.g. ``"app.main.RootScreen"``) for users who want to
expose a differently-named component without renaming it to
``App``.
Resolution order:
1. If ``component_path`` resolves cleanly as a module, return its
``App`` attribute.
2. Otherwise split on the final ``.``: import the parent module
and return the named attribute.
Args:
component_path: Either ``"app.main"`` (module path with an
``App`` attribute) or ``"app.main.SomeComponent"`` (dotted
path to a specific component).
Returns:
The resolved component callable.
Raises:
ImportError: If the module or dotted path cannot be found.
Errors raised *inside* a resolvable module (such as a
missing third-party dependency it imports) propagate
unchanged so the real cause stays visible.
"""
try
:
module
=
importlib
.
import_module
(
component_path
)
except
ModuleNotFoundError
as
exc
:
if
not
_missing_module_is_target
(
exc
,
component_path
):
raise
module
=
None
if
module
is
not
None
:
component
=
getattr
(
module
,
"App"
,
None
)
if
component
is
not
None
:
return
component
if
"."
in
component_path
:
module_path
,
attr
=
component_path
.
rsplit
(
"."
,
1
)
try
:
parent
=
importlib
.
import_module
(
module_path
)
except
ModuleNotFoundError
as
exc
:
if
not
_missing_module_is_target
(
exc
,
module_path
):
raise
parent
=
None
if
parent
is
not
None
:
component
=
getattr
(
parent
,
attr
,
None
)
if
component
is
not
None
:
return
component
raise
ImportError
(
f"Could not resolve component
{
component_path
!r
}
. "
"Define a top-level `App` function in the module (e.g. "
"`app/main.py`) or pass an explicit dotted path like "
"`app.main.RootScreen`."
)
# ======================================================================
# Shared helpers
# ======================================================================
def
_init_host_common
(
host
:
Any
,
component_path
:
str
,
component_func
:
Any
)
->
None
:
host
.
_component_path
=
component_path
host
.
_component
=
component_func
host
.
_args
=
{}
host
.
_reconciler
=
None
host
.
_root_native_view
=
None
host
.
_nav_handle
=
None
host
.
_is_rendering
=
False
host
.
_render_queued
=
False
host
.
_render_scheduled
=
False
host
.
_hot_reload_manifest_path
=
None
host
.
_hot_reload_last_version
=
None
host
.
_layout_listener
=
None
# retained on Android to prevent GC
# RedBox state: a dedicated reconciler that mounts the dev error
# overlay in place of the app tree (see ``_show_redbox``).
host
.
_redbox_reconciler
=
None
host
.
_redbox_root
=
None
# Focus state: drives ``use_focus_effect``. Starts focused because
# a host is only created when the screen is being presented; the
# platform lifecycle hooks (``on_resume`` / ``on_pause``) flip this
# when the user navigates to / from another screen.
host
.
_is_focused
=
True
host
.
_focus_subscribers
=
[]
def
_set_host_focused
(
host
:
Any
,
focused
:
bool
)
->
None
:
"""Update ``host._is_focused`` and notify ``use_focus_effect`` subscribers."""
if
getattr
(
host
,
"_is_focused"
,
True
)
==
focused
:
return
host
.
_is_focused
=
focused
subscribers
=
list
(
getattr
(
host
,
"_focus_subscribers"
, ())
or
())
for
callback
in
subscribers
:
try
:
callback
(
focused
)
except
Exception
:
pass
def
_destroy_host
(
host
:
Any
)
->
None
:
"""Tear down a screen host when the native screen is destroyed for good.
Called from each platform's ``on_destroy``. Unmounting the
reconciler runs every pending effect cleanup, destroys the native
views (releasing their event registrations), and clears back
handlers, so a popped screen doesn't leak its whole tree. Also
unregisters the host's RedBox reporter so runtime errors from other
screens don't route to a dead overlay.
"""
_clear_redbox
(
host
,
reattach
=
False
)
diagnostics
.
set_error_reporter
(
host
,
None
)
reconciler
=
host
.
_reconciler
host
.
_reconciler
=
None
if
reconciler
is
not
None
:
try
:
reconciler
.
unmount
()
except
Exception
:
_log_pn
(
"_destroy_host: reconciler.unmount() failed"
)
root
=
host
.
_root_native_view
host
.
_root_native_view
=
None
if
root
is
not
None
:
try
:
host
.
_detach_root
(
root
)
except
Exception
:
pass
host
.
_nav_handle
=
None
host
.
_focus_subscribers
=
[]
def
_host_back_pressed
(
host
:
Any
)
->
bool
:
"""Offer the system back action to ``use_back_handler`` subscribers.
Called by the native templates before running the platform's
default back behavior. Returns ``True`` when a handler consumed
the event, in which case the platform must *not* pop the screen.
"""
reconciler
=
host
.
_reconciler
if
reconciler
is
None
:
return
False
try
:
return
bool
(
reconciler
.
dispatch_back_press
())
except
Exception
as
exc
:
if
not
diagnostics
.
report_error
(
exc
,
phase
=
"back handler"
):
traceback
.
print_exc
()
return
False
def
_push_viewport_size
(
host
:
Any
,
width
:
float
,
height
:
float
)
->
None
:
"""Forward a viewport-size change to the reconciler.
Called by the native template (or our injected layout listener
on Android, or `_attach_root` on iOS) whenever the screen
container's bounds change. Coordinates must be in points (not
raw pixels). Also publishes the new dimensions to
`pythonnative.platform_metrics` so the
[`use_window_dimensions`][pythonnative.use_window_dimensions]
hook re-renders subscribers.
"""
if
host
.
_reconciler
is
None
:
return
if
width
<=
0
or
height
<=
0
:
return
host
.
_reconciler
.
set_viewport_size
(
float
(
width
),
float
(
height
))
redbox
=
getattr
(
host
,
"_redbox_reconciler"
,
None
)
if
redbox
is
not
None
:
redbox
.
set_viewport_size
(
float
(
width
),
float
(
height
))
try
:
from
.
import
platform_metrics
platform_metrics
.
set_window_dimensions
(
float
(
width
),
float
(
height
))
except
Exception
:
pass
def
_get_component
(
host
:
Any
)
->
Any
:
"""Resolve the current component function from its dotted path."""
host
.
_component
=
_import_component
(
host
.
_component_path
)
return
host
.
_component
def
_render_app
(
host
:
Any
)
->
Any
:
"""Call the current root component and return its element tree."""
return
_get_component
(
host
)()
def
_new_reconciler
(
host
:
Any
)
->
Any
:
from
.
native_views
import
get_registry
from
.
reconciler
import
Reconciler
reconciler
=
Reconciler
(
get_registry
())
reconciler
.
_screen_re_render
=
lambda
:
_request_render
(
host
)
return
reconciler
def
_schedule_render_async
(
host
:
Any
)
->
bool
:
"""Schedule a render for a later platform turn, if supported."""
return
False
def
_flush_scheduled_renders
(
hosts
:
Sequence
[
Any
])
->
None
:
"""Run renders that were deferred out of a native event callback."""
for
host
in
hosts
:
host
.
_render_scheduled
=
False
if
host
.
_reconciler
is
None
:
continue
if
host
.
_is_rendering
:
host
.
_render_queued
=
True
_schedule_render_async
(
host
)
continue
_re_render
(
host
)
def
_seed_initial_viewport
(
host
:
Any
)
->
None
:
"""Give the reconciler a plausible viewport size *before* the first mount.
The authoritative size arrives right after attach (Android's
``OnLayoutChangeListener``, iOS ``viewDidLayoutSubviews``, the
desktop stage size), but by then the mount commit has already run:
without a viewport its layout pass is skipped, so mount-time
[`use_layout_effect`][pythonnative.use_layout_effect] callbacks
would observe no committed frames. Hosts opt in by providing
``_initial_viewport_size()``; the estimate only needs to be
plausible (screen-sized), not pixel-perfect.
"""
getter
=
getattr
(
host
,
"_initial_viewport_size"
,
None
)
if
not
callable
(
getter
):
return
try
:
size
=
getter
()
except
Exception
:
return
if
not
size
:
return
width
,
height
=
size
if
width
>
0
and
height
>
0
:
host
.
_reconciler
.
set_viewport_size
(
float
(
width
),
float
(
height
))
def
_on_create
(
host
:
Any
)
->
None
:
from
.
hooks
import
NavigationHandle
,
Provider
,
_NavigationContext
# ``on_create`` is idempotent across native-view recreations. On
# Android the FragmentManager destroys and recreates a screen's
# view every time the user pops back to it, and the platform
# template calls ``screen.on_create()`` again from
# ``onViewCreated``, but the Python screen object (and therefore
# the reconciler, hook state, focus subscribers, etc.) persists
# across that. Re-running the full mount path here would reset
# use_state, clobber use_focus_effect subscriptions, and break
# navigation handles held by existing components, which is why
# the focus counter never advanced past ``1`` before this guard.
# If we're already mounted, just re-attach the existing root view
# to the (newly created) native container; ``on_resume`` will
# fire the focus subscribers separately.
_register_redbox_reporter
(
host
)
if
host
.
_reconciler
is
not
None
and
host
.
_root_native_view
is
not
None
:
host
.
_attach_root
(
host
.
_root_native_view
)
return
host
.
_nav_handle
=
NavigationHandle
(
host
)
host
.
_reconciler
=
_new_reconciler
(
host
)
_seed_initial_viewport
(
host
)
try
:
app_element
=
_render_app
(
host
)
provider_element
=
Provider
(
_NavigationContext
,
host
.
_nav_handle
,
app_element
)
host
.
_is_rendering
=
True
try
:
host
.
_root_native_view
=
host
.
_reconciler
.
mount
(
provider_element
)
host
.
_attach_root
(
host
.
_root_native_view
)
_drain_renders
(
host
)
finally
:
host
.
_is_rendering
=
False
except
Exception
as
exc
:
if
not
diagnostics
.
is_dev
():
raise
_show_redbox
(
host
,
exc
,
phase
=
"mount"
)
def
_request_render
(
host
:
Any
)
->
None
:
"""Request a render pass.
If a render is already in progress (state changed mid-render or
inside an effect), the request is queued and drained at the end of
the current pass so the reconciler is never re-entered.
"""
if
host
.
_reconciler
is
None
:
return
if
host
.
_is_rendering
:
host
.
_render_queued
=
True
return
if
_schedule_render_async
(
host
):
return
_re_render
(
host
)
def
_re_render
(
host
:
Any
)
->
None
:
"""Run one *local* render pass, then drain any renders queued during it.
State setters mark only their own component subtree dirty (see
[`mark_dirty`][pythonnative.reconciler.Reconciler.mark_dirty]), so
this drains the reconciler's dirty set via
[`flush_dirty`][pythonnative.reconciler.Reconciler.flush_dirty]
instead of re-running the whole ``App`` from the root. The app's
element tree is only rebuilt from scratch on mount, navigation, and
hot reload.
"""
_log_pn
(
"_re_render: starting local render pass"
)
try
:
host
.
_is_rendering
=
True
try
:
host
.
_render_queued
=
False
_commit_dirty
(
host
)
_drain_renders
(
host
)
finally
:
host
.
_is_rendering
=
False
except
Exception
as
exc
:
if
not
diagnostics
.
is_dev
():
raise
_show_redbox
(
host
,
exc
,
phase
=
"render"
)
_log_pn
(
"_re_render: done"
)
def
_commit_dirty
(
host
:
Any
)
->
None
:
"""Flush the reconciler's dirty components and re-attach the root if it changed."""
new_root
=
host
.
_reconciler
.
flush_dirty
()
if
new_root
is
not
host
.
_root_native_view
:
_log_pn
(
f"_commit_dirty: ROOT VIEW CHANGED (
{
id
(
host
.
_root_native_view
)
}
->
{
id
(
new_root
)
}
); reattaching"
)
host
.
_detach_root
(
host
.
_root_native_view
)
host
.
_root_native_view
=
new_root
host
.
_attach_root
(
new_root
)
def
_drain_renders
(
host
:
Any
)
->
None
:
"""Flush additional renders queued by effects that set state.
Capped at `_MAX_RENDER_PASSES` to break runaway feedback loops
(e.g., an effect that unconditionally calls a setter).
"""
for
i
in
range
(
_MAX_RENDER_PASSES
):
if
not
host
.
_render_queued
:
break
_log_pn
(
f"_drain_renders: draining pass #
{
i
+
1
}
"
)
host
.
_render_queued
=
False
_commit_dirty
(
host
)
# ======================================================================
# RedBox (dev-mode error overlay)
# ======================================================================
#
# In dev mode (``pn preview``, ``pn run`` with hot reload, ``PN_DEV=1``)
# an uncaught error from a mount, render, effect, or event handler
# replaces the screen with a full-screen traceback instead of crashing
# the process or dying silently in the log. The overlay is a normal
# PythonNative element tree mounted by a *dedicated* reconciler so a
# broken app tree can't take the error display down with it. Fixing the
# code and saving clears it via hot reload; the Dismiss button restores
# the previous native root (which is still mounted underneath).
def
_redbox_element
(
exc
:
BaseException
,
phase
:
str
,
on_dismiss
:
Any
)
->
Any
:
"""Build the RedBox element tree for ``exc``."""
from
.
components
import
Button
,
Column
,
ScrollView
,
Text
trace
=
""
.
join
(
traceback
.
format_exception
(
type
(
exc
),
exc
,
exc
.
__traceback__
))
message
=
str
(
exc
)
or
"(no message)"
return
Column
(
Column
(
Text
(
f"
{
type
(
exc
).
__name__
}
in
{
phase
}
"
,
style
=
{
"color"
:
"#FFD3DA"
,
"font_size"
:
13
,
"bold"
:
True
},
),
Text
(
message
,
style
=
{
"color"
:
"#FFFFFF"
,
"font_size"
:
17
,
"bold"
:
True
}),
style
=
{
"background_color"
:
"#C4283C"
,
"padding"
:
16
,
"padding_top"
:
56
,
"spacing"
:
6
,
},
),
ScrollView
(
Text
(
trace
,
style
=
{
"color"
:
"#FF9AA8"
,
"font_size"
:
12
}),
style
=
{
"flex"
:
1
,
"padding"
:
12
},
),
Column
(
Button
(
"Dismiss"
,
on_press
=
on_dismiss
,
style
=
{
"color"
:
"#FFFFFF"
}),
Text
(
"Fix the error and save to reload."
,
style
=
{
"color"
:
"#8E8E93"
,
"font_size"
:
12
,
"text_align"
:
"center"
},
),
style
=
{
"padding"
:
12
,
"padding_bottom"
:
32
,
"spacing"
:
4
},
),
style
=
{
"flex"
:
1
,
"background_color"
:
"#1C1C1E"
},
)
def
_show_redbox
(
host
:
Any
,
exc
:
BaseException
,
phase
:
str
=
"render"
)
->
None
:
"""Mount the dev error overlay over the host's screen.
Safe to call repeatedly (a newer error replaces the current
overlay) and from any thread (the mount hops to the main thread).
Failures inside the RedBox itself fall back to printing both
tracebacks so the original error is never lost.
"""
_log_pn
(
f"_show_redbox:
{
type
(
exc
).
__name__
}
during
{
phase
}
"
)
try
:
print
(
f"[PN]
{
phase
}
error:"
,
file
=
sys
.
stderr
)
traceback
.
print_exception
(
type
(
exc
),
exc
,
exc
.
__traceback__
)
except
Exception
:
pass
def
_mount
()
->
None
:
try
:
_clear_redbox
(
host
,
reattach
=
False
)
from
.
native_views
import
get_registry
from
.
reconciler
import
Reconciler
redbox
=
Reconciler
(
get_registry
())
redbox
.
_screen_re_render
=
redbox
.
flush_dirty
element
=
_redbox_element
(
exc
,
phase
,
lambda
:
_clear_redbox
(
host
))
root
=
redbox
.
mount
(
element
)
width
,
height
=
(
0.0
,
0.0
)
if
host
.
_reconciler
is
not
None
:
width
,
height
=
host
.
_reconciler
.
_viewport_size
if
width
<=
0
or
height
<=
0
:
from
.
import
platform_metrics
dims
=
platform_metrics
.
get_window_dimensions
()
width
,
height
=
dims
.
width
,
dims
.
height
if
width
>
0
and
height
>
0
:
redbox
.
set_viewport_size
(
width
,
height
)
host
.
_redbox_reconciler
=
redbox
host
.
_redbox_root
=
root
if
host
.
_root_native_view
is
not
None
:
host
.
_detach_root
(
host
.
_root_native_view
)
host
.
_attach_root
(
root
)
except
Exception
:
print
(
"[PN] RedBox failed to mount:"
,
file
=
sys
.
stderr
)
traceback
.
print_exc
()
from
.
runtime
import
call_on_main_thread
call_on_main_thread
(
_mount
)
def
_clear_redbox
(
host
:
Any
,
reattach
:
bool
=
True
)
->
None
:
"""Tear down the RedBox overlay and optionally restore the app root."""
redbox
=
getattr
(
host
,
"_redbox_reconciler"
,
None
)
if
redbox
is
None
:
return
host
.
_redbox_reconciler
=
None
host
.
_redbox_root
=
None
try
:
redbox
.
unmount
()
except
Exception
:
pass
if
reattach
and
host
.
_root_native_view
is
not
None
:
try
:
host
.
_attach_root
(
host
.
_root_native_view
)
except
Exception
:
pass
def
_register_redbox_reporter
(
host
:
Any
)
->
None
:
"""Route runtime errors (events, async) for this host to the RedBox."""
if
not
diagnostics
.
is_dev
():
return
diagnostics
.
set_error_reporter
(
host
,
lambda
exc
,
phase
:
_show_redbox
(
host
,
exc
,
phase
))
def
_set_args
(
host
:
Any
,
args
:
Any
)
->
None
:
if
isinstance
(
args
,
str
):
try
:
host
.
_args
=
json
.
loads
(
args
)
or
{}
except
Exception
:
host
.
_args
=
{}
return
host
.
_args
=
args
if
isinstance
(
args
,
dict
)
else
{}
def
_enable_hot_reload
(
host
:
Any
,
manifest_path
:
str
)
->
None
:
host
.
_hot_reload_manifest_path
=
manifest_path
host
.
_hot_reload_last_version
=
None
# Hot reload only runs on debug builds, so treat it as the on-device
# dev-mode switch (validation warnings, hook-order checks, RedBox).
diagnostics
.
set_dev_mode
(
True
)
_register_redbox_reporter
(
host
)
def
_hot_reload_tick
(
host
:
Any
)
->
bool
:
manifest_path
=
getattr
(
host
,
"_hot_reload_manifest_path"
,
None
)
if
not
manifest_path
:
return
False
from
.
hot_reload
import
ModuleReloader
last
=
getattr
(
host
,
"_hot_reload_last_version"
,
None
)
manifest_exists
=
os
.
path
.
exists
(
manifest_path
)
if
not
manifest_exists
and
last
is
None
:
return
False
# The iOS template polls every 0.5s per UIViewController, so this
# tick fires several times per second per host. The per-tick log is
# gated behind ``PYTHONNATIVE_DEBUG`` to keep normal output quiet
# while preserving the breadcrumb when investigating reload races.
if
_debug_enabled
():
manifest_version
:
Optional
[
str
]
=
None
if
manifest_exists
:
try
:
with
open
(
manifest_path
,
encoding
=
"utf-8"
)
as
f
:
raw_version
=
json
.
load
(
f
).
get
(
"version"
,
""
)
manifest_version
=
str
(
raw_version
)
if
raw_version
else
None
except
Exception
:
manifest_version
=
None
action
=
"reload"
if
(
manifest_version
is
not
None
and
manifest_version
!=
last
)
else
"skip"
_log_pn
(
f"_hot_reload_tick: host=0x
{
id
(
host
):x
}
component=
{
host
.
_component_path
}
"
f"last=
{
last
!r
}
manifest=
{
manifest_version
!r
}
action=
{
action
}
"
)
next_version
=
ModuleReloader
.
reload_from_manifest
(
host
,
manifest_path
,
last_version
=
last
,
)
if
next_version
==
last
:
return
False
host
.
_hot_reload_last_version
=
next_version
return
True
def
_reload_host
(
host
:
Any
,
changed_modules
:
Optional
[
Sequence
[
str
]]
=
None
)
->
None
:
"""Reload modules and refresh the host's reconciler tree.
Tries **Fast Refresh** first: the changed modules are reloaded
and every ``element.type`` reference in the current ``VNode``
tree is rewritten to point at the new module's functions. The
next render then runs the new bodies through the existing hook
slots, so component state survives.
The reload set is **expanded** to include every currently-imported
module under the entry-point's top-level package (see
[`expand_reload_targets`][pythonnative.hot_reload.ModuleReloader.expand_reload_targets]).
This catches transitive ``from ... import`` bindings that would
otherwise remain stale: if ``app/main.py`` does
``from app.screens.home import HomeScreen`` and the user edits
``home.py``, reloading just ``app.screens.home`` leaves
``app.main.HomeScreen`` pointing at the pre-edit function, so the
new render emits stale element types and the reconciler is forced
to unmount and remount the screen (losing state and showing old
code). Reloading every user-app module in dependency-friendly
order, with the entry-point last, keeps every binding fresh.
If Fast Refresh fails (the new module raised at import time, no
replacements could be located, or the next render itself
threw), the host falls back to a full remount: a brand-new
reconciler tree is mounted into the same native root. State is
lost but the app keeps running so the developer can fix the
error and try again.
"""
from
.
hot_reload
import
ModuleReloader
requested
=
list
(
changed_modules
or
[])
targets
=
ModuleReloader
.
expand_reload_targets
(
requested
,
host
.
_component_path
)
pending_version
=
getattr
(
host
,
"_hot_reload_pending_version"
,
None
)
already_loaded
=
pending_version
is
not
None
and
pending_version
==
ModuleReloader
.
_last_reloaded_version
_log_pn
(
f"_reload_host: host=0x
{
id
(
host
):x
}
component=
{
host
.
_component_path
}
"
f"requested=
{
requested
!r
}
targets=
{
len
(
targets
)
}
version=
{
pending_version
!r
}
"
f"action=
{
'reuse_modules'
if
already_loaded
else
'reload_modules'
}
"
)
reloaded
=
ModuleReloader
.
reload_modules_for_version
(
targets
,
pending_version
)
if
not
reloaded
:
_log_pn
(
f"_reload_host: no modules could be reloaded from
{
targets
!r
}
; aborting"
)
return
try
:
new_component
=
_import_component
(
host
.
_component_path
)
except
Exception
as
exc
:
_log_pn
(
f"_reload_host: re-import failed:
{
exc
!r
}
; aborting reload"
)
if
diagnostics
.
is_dev
():
# A syntax error (or import-time crash) in the edited file:
# show it in the RedBox so the developer sees it on device
# instead of the app silently keeping the old code.
_show_redbox
(
host
,
exc
,
phase
=
"hot reload import"
)
return
host
.
_component
=
new_component
if
host
.
_reconciler
is
None
:
_log_pn
(
f"_reload_host: host=0x
{
id
(
host
):x
}
reconciler=None; skipping refresh"
)
return
# A reload always replaces whatever error state was on screen.
# Re-attach the current root now: Fast Refresh patches that tree in
# place (attach must happen regardless of whether it succeeds), and
# a full remount swaps in its own fresh root anyway.
_clear_redbox
(
host
)
if
_try_fast_refresh
(
host
,
reloaded
):
print
(
f"[hot-reload] Fast Refresh:
{
', '
.
join
(
requested
)
or
', '
.
join
(
reloaded
)
}
"
,
file
=
sys
.
stderr
)
return
try
:
_full_remount
(
host
,
reloaded
)
except
Exception
as
exc
:
if
not
diagnostics
.
is_dev
():
raise
_show_redbox
(
host
,
exc
,
phase
=
"hot reload"
)
def
_try_fast_refresh
(
host
:
Any
,
reloaded_modules
:
Sequence
[
str
])
->
bool
:
"""Attempt an in-place component swap + re-render.
Returns ``True`` only if the swap happened and the subsequent
render completed without raising. On exception we restore the
pre-render reconciler state so the caller can fall back to a
full remount.
"""
from
.
hooks
import
Provider
,
_NavigationContext
from
.
hot_reload
import
ModuleReloader
reconciler
=
host
.
_reconciler
if
reconciler
is
None
or
reconciler
.
_tree
is
None
:
return
False
rewrote
=
ModuleReloader
.
refresh_in_place
(
reconciler
,
reloaded_modules
)
if
not
rewrote
:
return
False
host
.
_is_rendering
=
True
try
:
app_element
=
_render_app
(
host
)
provider_element
=
Provider
(
_NavigationContext
,
host
.
_nav_handle
,
app_element
)
new_root
=
reconciler
.
reconcile
(
provider_element
)
if
new_root
is
not
host
.
_root_native_view
:
host
.
_detach_root
(
host
.
_root_native_view
)
host
.
_root_native_view
=
new_root
host
.
_attach_root
(
new_root
)
except
Exception
as
e
:
_log_pn
(
f"_try_fast_refresh: render failed after swap:
{
e
!r
}
; falling back to remount"
)
return
False
finally
:
host
.
_is_rendering
=
False
_drain_renders
(
host
)
return
True
def
_full_remount
(
host
:
Any
,
reloaded_modules
:
Sequence
[
str
])
->
None
:
"""Destroy the existing tree and mount a fresh one.
Used by [`_reload_host`][pythonnative.screen._reload_host] as the
fallback path when Fast Refresh cannot apply (e.g. the user
deleted a component that was on screen).
"""
from
.
hooks
import
NavigationHandle
,
Provider
,
_NavigationContext
old_reconciler
=
host
.
_reconciler
old_root
=
host
.
_root_native_view
old_nav
=
host
.
_nav_handle
new_reconciler
=
_new_reconciler
(
host
)
host
.
_reconciler
=
new_reconciler
host
.
_nav_handle
=
NavigationHandle
(
host
)
host
.
_is_rendering
=
True
try
:
app_element
=
_render_app
(
host
)
provider_element
=
Provider
(
_NavigationContext
,
host
.
_nav_handle
,
app_element
)
new_root
=
new_reconciler
.
mount
(
provider_element
)
except
Exception
:
host
.
_reconciler
=
old_reconciler
host
.
_nav_handle
=
old_nav
raise
finally
:
host
.
_is_rendering
=
False
if
old_reconciler
is
not
None
:
# ``unmount`` queues the DestroyOps *and* flushes them to the
# backend in one batch (releasing native views and their event
# registrations).
old_reconciler
.
unmount
()
if
old_root
is
not
None
:
host
.
_detach_root
(
old_root
)
host
.
_root_native_view
=
new_root
host
.
_attach_root
(
new_root
)
_drain_renders
(
host
)
print
(
f"[hot-reload] Remounted:
{
', '
.
join
(
reloaded_modules
)
}
"
,
file
=
sys
.
stderr
)
# ======================================================================
# Platform implementations
# ======================================================================
if
IS_ANDROID
:
from
java
import
dynamic_proxy
,
jclass
_ANDROID_SCHEDULED_RENDER_HOSTS
:
Dict
[
int
,
Any
]
=
{}
_android_render_scheduler_handler
:
Any
=
None
_android_render_scheduler_runnable
:
Any
=
None
_android_main_looper
:
Any
=
None
def
_is_android_main_thread
()
->
bool
:
"""Return True when running on Android's main looper thread."""
global
_android_main_looper
try
:
Looper
=
jclass
(
"android.os.Looper"
)
if
_android_main_looper
is
None
:
_android_main_looper
=
Looper
.
getMainLooper
()
return
Looper
.
myLooper
()
==
_android_main_looper
except
Exception
:
return
threading
.
current_thread
()
is
threading
.
main_thread
()
def
_flush_android_scheduled_renders
()
->
None
:
hosts
=
list
(
_ANDROID_SCHEDULED_RENDER_HOSTS
.
values
())
_ANDROID_SCHEDULED_RENDER_HOSTS
.
clear
()
_flush_scheduled_renders
(
hosts
)
def
_schedule_render_async
(
host
:
Any
)
->
bool
:
global
_android_render_scheduler_handler
,
_android_render_scheduler_runnable
if
not
IS_ANDROID
:
return
False
if
getattr
(
host
,
"_render_scheduled"
,
False
):
return
True
if
_is_android_main_thread
():
return
False
host
.
_render_scheduled
=
True
_ANDROID_SCHEDULED_RENDER_HOSTS
[
id
(
host
)]
=
host
try
:
if
_android_render_scheduler_handler
is
None
:
Handler
=
jclass
(
"android.os.Handler"
)
Looper
=
jclass
(
"android.os.Looper"
)
Runnable
=
jclass
(
"java.lang.Runnable"
)
_android_render_scheduler_handler
=
Handler
(
Looper
.
getMainLooper
())
class
_PNRenderRunnable
(
dynamic_proxy
(
Runnable
)):
# type: ignore[misc]
def
run
(
self
)
->
None
:
_flush_android_scheduled_renders
()
_android_render_scheduler_runnable
=
_PNRenderRunnable
()
_android_render_scheduler_handler
.
post
(
_android_render_scheduler_runnable
)
return
True
except
Exception
:
host
.
_render_scheduled
=
False
_ANDROID_SCHEDULED_RENDER_HOSTS
.
pop
(
id
(
host
),
None
)
return
False
def
_android_publish_window_insets
(
view
:
Any
)
->
None
:
"""Read system-bar insets from *view* and publish them to platform_metrics.
Most production Android themes already exclude the system
navigation bar from the activity content area, so the bottom
inset reported here is typically ``0`` on classic devices.
On edge-to-edge themes (or 3-button gesture nav strips), the
bottom inset is non-zero and the tab bar needs to claim that
space so the system gesture indicator does not overlap its
labels.
The function is best-effort: API levels < 30 expose
``getSystemWindowInsetBottom`` instead of the typed
``getInsets(systemBars())`` API, and very old phones may
not expose ``getRootWindowInsets`` at all. All branches are
wrapped in ``try/except`` because diagnostics here must
never crash a screen host.
"""
try
:
from
.
import
platform_metrics
except
Exception
:
return
try
:
insets_obj
=
view
.
getRootWindowInsets
()
if
insets_obj
is
None
:
return
density
=
float
(
view
.
getResources
().
getDisplayMetrics
().
density
)
or
1.0
top_px
=
0
left_px
=
0
bottom_px
=
0
right_px
=
0
try
:
WindowInsets
=
jclass
(
"android.view.WindowInsets"
)
Type
=
WindowInsets
.
Type
bars
=
Type
.
systemBars
()
typed
=
insets_obj
.
getInsets
(
bars
)
top_px
=
int
(
typed
.
top
)
left_px
=
int
(
typed
.
left
)
bottom_px
=
int
(
typed
.
bottom
)
right_px
=
int
(
typed
.
right
)
except
Exception
:
top_px
=
int
(
insets_obj
.
getSystemWindowInsetTop
()
or
0
)
left_px
=
int
(
insets_obj
.
getSystemWindowInsetLeft
()
or
0
)
bottom_px
=
int
(
insets_obj
.
getSystemWindowInsetBottom
()
or
0
)
right_px
=
int
(
insets_obj
.
getSystemWindowInsetRight
()
or
0
)
platform_metrics
.
set_safe_area_insets
(
top_px
/
density
,
left_px
/
density
,
bottom_px
/
density
,
right_px
/
density
,
)
# IME (soft keyboard) insets: API 30+ exposes them through
# the typed getInsets API. The keyboard overlaps the system
# navigation bar, so the visible keyboard height is the IME
# inset minus the permanent bottom bar inset. Older API
# levels don't report IME insets here; those devices rely
# on ``adjustResize`` shrinking the window (the viewport
# push handles the layout) and the height stays 0.
try
:
ime
=
insets_obj
.
getInsets
(
Type
.
ime
())
ime_px
=
max
(
0
,
int
(
ime
.
bottom
)
-
bottom_px
)
platform_metrics
.
set_keyboard_height
(
ime_px
/
density
)
except
Exception
:
pass
except
Exception
:
pass
def
_android_publish_color_scheme
(
activity
:
Any
)
->
None
:
"""Read the system night mode from the activity and publish it.
Android delivers appearance changes as a configuration change,
which recreates the activity by default, so publishing on
``on_create`` / ``on_resume`` covers both the initial value and
subsequent flips.
"""
try
:
from
.
import
appearance
Configuration
=
jclass
(
"android.content.res.Configuration"
)
ui_mode
=
int
(
activity
.
getResources
().
getConfiguration
().
uiMode
)
night
=
ui_mode
&
int
(
Configuration
.
UI_MODE_NIGHT_MASK
)
is_dark
=
night
==
int
(
Configuration
.
UI_MODE_NIGHT_YES
)
appearance
.
set_system_color_scheme
(
"dark"
if
is_dark
else
"light"
)
except
Exception
:
pass
def
_android_register_insets_listener
(
host
:
Any
,
view
:
Any
)
->
None
:
"""Re-publish insets whenever the window's insets change.
The ``OnLayoutChangeListener`` in ``_android_register_layout_listener``
only fires when the container is re-measured, which covers
``adjustResize`` keyboards but not inset-only changes (e.g. an
edge-to-edge window where the IME floats over the content).
``setOnApplyWindowInsetsListener`` fires on every insets pass,
so keyboard show/hide reaches ``platform_metrics`` immediately.
"""
try
:
View
=
jclass
(
"android.view.View"
)
class
_PNInsetsListener
(
dynamic_proxy
(
View
.
OnApplyWindowInsetsListener
)):
# type: ignore[misc]
def
onApplyWindowInsets
(
self
,
v
:
Any
,
insets
:
Any
)
->
Any
:
try
:
_android_publish_window_insets
(
v
)
except
Exception
:
pass
return
insets
listener
=
_PNInsetsListener
()
view
.
setOnApplyWindowInsetsListener
(
listener
)
host
.
_insets_listener
=
listener
# retain to prevent GC
except
Exception
:
pass
def
_android_register_layout_listener
(
host
:
Any
,
view
:
Any
)
->
None
:
"""Push the container's measured size into the reconciler whenever it changes."""
try
:
View
=
jclass
(
"android.view.View"
)
class
_PNLayoutChangeListener
(
dynamic_proxy
(
View
.
OnLayoutChangeListener
)):
# type: ignore[misc]
def
__init__
(
self
,
host_obj
:
Any
)
->
None
:
super
().
__init__
()
self
.
host_obj
=
host_obj
def
onLayoutChange
(
self
,
v
:
Any
,
left
:
int
,
top
:
int
,
right
:
int
,
bottom
:
int
,
old_left
:
int
,
old_top
:
int
,
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL