-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdisplay_driver.py
More file actions
1516 lines (1311 loc) · 53.2 KB
/
Copy pathdisplay_driver.py
File metadata and controls
1516 lines (1311 loc) · 53.2 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
# SPDX-FileCopyrightText: 2024 Brad Barnett
# SPDX-FileCopyrightText: 2021 Amir Gonnen (event_loop; MIT)
#
# SPDX-License-Identifier: MIT
"""
display_driver.py - LVGL displaydev/input wiring and event loop for PyDevices.
Canonical copy lives in PyDevices/lvgl-bindings (``python/display_driver.py``).
Consumer repos (lvgl-micropython, lvgl-circuitpython, lvgl-python)
vendor a synced copy; do not edit those copies directly.
Note that a change here is a release trigger: this path is watched by
``.github/workflows/trigger-lvgl-python-release.yml``, which dispatches
lvgl-python's sync, and that publishes a new version when the sync produces a
diff. Even a comment-only edit ships a release.
Requires a valid ``board_config.py`` on the path. Importing this module creates
an ``appdev.App`` coordinator, starts ``event_loop``, and registers display flush
and input devices.
``event_loop`` was adapted from upstream lv_utils (Amir Gonnen). Integration
changes:
* Periodic tick driven by ``appdev.App.every``.
* ``asyncio`` from ``multimer``.
* Sync path runs ``lv.task_handler()`` from the tick callback (re-entrancy
guarded); the app timer delivers on the main thread.
* Async mode arms the refresh task lazily on the first timer tick so module-top
``import display_driver`` is safe before any event loop exists.
* Application lifecycle driven by ``appdev.App.run()``.
Interactive desktop (librt + REPL): ``task_handler`` / indev reads are paced at
``LVGL_PERIOD_MS`` (10 ms) with a wall-clock gate. Display refresh stays at
LVGL's ``LV_DEF_REFR_PERIOD`` (~33 ms). PARTIAL ``show()`` is gated to that
refresh cadence so presents do not track the faster task loop. The App
timer stays at 10 ms; a host-pump subscription drains SDL/keys every tick so
the window cannot stall while LVGL is paused or slow.
"""
import gc
import sys
import board_config
display_drv = board_config.display_drv
import lvgl as lv
import appdev
import events
import keys
try:
from multimer import asyncio, loop_running, ticks_add, ticks_diff, ticks_ms
except ImportError:
asyncio = None
loop_running = None
ticks_add = None
ticks_diff = None
ticks_ms = None
asyncio_available = asyncio is not None
LVGL_PERIOD_MS = 10
# Match LV_DEF_REFR_PERIOD in lv_conf.h — PARTIAL present cadence / display refresh.
LVGL_REFR_PERIOD_MS = 33
_driver_ref = None # primary DisplayDriver (compat)
_drivers = [] # all DisplayDriver instances
_host_pump_sub = None
_present_next_ok_ms = None
HOST = appdev.HOST
POINTER = appdev.POINTER
ENCODER = appdev.ENCODER
KEYPAD = appdev.KEYPAD
JOYSTICK = appdev.JOYSTICK
class InputDevice:
"""Small input adapter used only by the LVGL bridge."""
type = -1
responses = events.filter
def __init__(self, read=None, data=None, read2=None, data2=None):
self._read = read if read is not None else lambda: None
self._data = data
self._read2 = read2 if read2 is not None else lambda: None
self._data2 = data2
self._state = None
self._app = None
self._user_data = None
self._callbacks = []
@property
def app(self):
return self._app
@app.setter
def app(self, value):
self._app = value
@property
def user_data(self):
return self._user_data
@user_data.setter
def user_data(self, value):
self._user_data = value
def subscribe(self, callback, event_types=None):
if not callable(callback):
raise ValueError("callback is not callable")
item = (callback, event_types)
if item not in self._callbacks:
self._callbacks.append(item)
def unsubscribe(self, callback, event_types=None):
self._callbacks = [item for item in self._callbacks if item[0] is not callback]
def poll(self, *args):
raw = self._poll()
if raw is None:
return []
result = raw if isinstance(raw, list) else [raw]
result = [event for event in result if event.type in events.filter]
for event in result:
for callback, event_types in tuple(self._callbacks):
if event_types is None or event.type in event_types:
callback(event, *args)
return result
class HostInput(InputDevice):
"""Adapt a host display's ``get_events`` callback for LVGL."""
type = HOST
def __init__(self, host_read, display=None, event_filter=None):
super().__init__(read=host_read, data=display, data2=event_filter or events.filter)
self.scale = getattr(display, "touch_scale", 1) if display is not None else 1
self._quit_chord_ok = hasattr(display, "quit_chord")
def _touch_scale_for(self, window_id):
panel = self._data
if window_id is not None and self._app is not None:
for candidate in self._app.displays:
if getattr(candidate, "_window_id", None) == window_id:
panel = candidate
break
scale = getattr(panel, "touch_scale", None) if panel is not None else None
if scale is None:
return self.scale
self.scale = scale
return scale
def _poll(self):
incoming = self._read()
if incoming is None:
return None
result = []
quit_chord = self._data.quit_chord if self._quit_chord_ok else None
chord_key = quit_chord[0] if quit_chord else None
for event in incoming:
if event.type == events.KEYDOWN and keys.chord_matches(
quit_chord, event.key, event.mod
):
event = events.Quit(events.QUIT)
elif event.type == events.KEYUP and quit_chord and event.key == chord_key:
continue
if event.type not in self._data2:
continue
if event.type in (
events.MOUSEMOTION,
events.MOUSEBUTTONDOWN,
events.MOUSEBUTTONUP,
):
scale = self._touch_scale_for(getattr(event, "window", None))
if scale and scale != 1:
pos = (int(event.pos[0] // scale), int(event.pos[1] // scale))
if event.type == events.MOUSEMOTION:
event = events.Motion(
event.type,
pos,
(event.rel[0] // scale, event.rel[1] // scale),
event.buttons,
event.touch,
event.window,
)
else:
event = events.Button(
event.type, pos, event.button, event.touch, event.window
)
result.append(event)
return result or None
_DEFAULT_TOUCH_ROTATION_TABLE = (0b000, 0b101, 0b110, 0b011)
_SWAP_XY = 0b001
_REVERSE_X = 0b010
_REVERSE_Y = 0b100
def _normalize_points(sample):
if not sample:
return ()
if isinstance(sample[0], int):
return (tuple(sample),)
return tuple(tuple(point) for point in sample)
class TouchInput(InputDevice):
"""Adapt a board touch callable to pointer events for LVGL."""
type = POINTER
responses = (events.MOUSEMOTION, events.MOUSEBUTTONDOWN, events.MOUSEBUTTONUP)
def __init__(self, read, display, rotation_table=None):
super().__init__(read=read, data=display, data2=rotation_table)
self._data2 = self._data2 or _DEFAULT_TOUCH_ROTATION_TABLE
self.rotation = display.rotation
try:
display.touch_device = self
except Exception:
pass
self.points = ()
@property
def rotation(self):
return self._rotation
@rotation.setter
def rotation(self, value):
self._rotation = value % 360
self._mask = self._data2[self._rotation // 90]
def _map_point(self, point):
x, y = int(point[0]), int(point[1])
if self._mask & _SWAP_XY:
x, y = y, x
if self._mask & _REVERSE_X:
x = self._data.width - x - 1
if self._mask & _REVERSE_Y:
y = self._data.height - y - 1
return (x, y) + tuple(point[2:]) if len(point) > 2 else (x, y)
def _poll(self):
try:
mapped = tuple(self._map_point(point) for point in _normalize_points(self._read()))
except OSError:
return None
self.points = mapped
if mapped:
x, y = int(mapped[0][0]), int(mapped[0][1])
previous = self._state
self._state = (x, y)
if previous is None:
return events.Button(events.MOUSEBUTTONDOWN, self._state, 1, False, None)
return events.Motion(
events.MOUSEMOTION,
self._state,
(x - previous[0], y - previous[1]),
(1, 0, 0),
False,
None,
)
if self._state is not None:
previous = self._state
self._state = None
return events.Button(events.MOUSEBUTTONUP, previous, 1, False, None)
return None
class KeypadInput(InputDevice):
"""Adapt a pressed-key collection to KEYDOWN/KEYUP events."""
type = KEYPAD
responses = (events.KEYDOWN, events.KEYUP)
def __init__(self, read):
super().__init__(read=read)
self._state = set()
@staticmethod
def _name(key):
name = keys.keyname(key)
if name != "Unknown":
return name
if isinstance(key, int) and 32 <= key <= 126:
return chr(key)
return "0x%x" % key if isinstance(key, int) else str(key)
def _poll(self):
current = set(self._read())
released = self._state - current
if released:
key = released.pop()
self._state.remove(key)
return events.Key(events.KEYUP, self._name(key), key, 0, 0, None)
pressed = current - self._state
if pressed:
key = pressed.pop()
self._state.add(key)
return events.Key(events.KEYDOWN, self._name(key), key, 0, 0, None)
return None
class EncoderInput(InputDevice):
"""Adapt an encoder position and optional button to LVGL events."""
type = ENCODER
responses = (events.MOUSEWHEEL, events.MOUSEBUTTONDOWN, events.MOUSEBUTTONUP)
def __init__(self, read, button_read=None, button=2):
super().__init__(read=read, read2=button_read, data=button)
self._state = (0, False)
def _poll(self):
last_pos, last_pressed = self._state
pressed = self._read2()
if pressed != last_pressed:
self._state = (last_pos, pressed)
return events.Button(
events.MOUSEBUTTONDOWN if pressed else events.MOUSEBUTTONUP,
(0, 0),
self._data,
False,
None,
)
pos = self._read()
if pos != last_pos:
steps = pos - last_pos
self._state = (pos, last_pressed)
if self._data % 2 == 0:
return events.Wheel(events.MOUSEWHEEL, False, 0, steps, 0, steps, False, None)
return events.Wheel(events.MOUSEWHEEL, False, steps, 0, steps, 0, False, None)
return None
_virtual_peers = {}
_virtual_pending = {}
class VirtualDevices:
"""Fan one host input into LVGL pointer, encoder, and keypad inputs."""
class VirtualDevice:
def __init__(self, owner, device_type):
self._owner = owner
self.type = device_type
self.user_data = None
self._fifo = []
self._callbacks = []
self._active_key_event = None
self.points = ()
self._fingers = {}
def subscribe(self, callback, event_types=None):
if callback not in self._callbacks:
self._callbacks.append(callback)
def unsubscribe(self, callback, event_types=None):
if callback in self._callbacks:
self._callbacks.remove(callback)
@property
def has_pending(self):
return bool(self._fifo)
def poll(self, *args):
self._owner.poll_host_device()
event = self._fifo.pop(0) if self._fifo else None
for callback in tuple(self._callbacks):
callback(event, *args)
def add_event(self, event):
if (
event.type == events.MOUSEMOTION
and self._fifo
and self._fifo[-1].type == events.MOUSEMOTION
):
self._fifo[-1] = event
return
if (
event.type == events.KEYDOWN
and self._fifo
and self._fifo[-1].type == events.KEYDOWN
and getattr(self._fifo[-1], "key", None) == getattr(event, "key", None)
):
self._fifo[-1] = event
return
if self.type == KEYPAD:
key = getattr(event, "key", None)
active = self._active_key_event
active_key = getattr(active, "key", None)
if event.type == events.KEYDOWN:
if active is not None and active_key != key:
self._fifo.append(
events.Key(
events.KEYUP,
active.name,
active.key,
active.mod,
active.scancode,
active.window,
)
)
self._active_key_event = event
elif event.type == events.KEYUP:
if active is not None and active_key != key:
return
self._active_key_event = None
self._fifo.append(event)
def _set_finger(self, finger_id, point):
if point is None:
self._fingers.pop(finger_id, None)
else:
self._fingers[finger_id] = point
self.points = tuple(
(pos[0], pos[1], fid) for fid, pos in self._fingers.items()
)
def __init__(self, host_device, window_id=None):
self._host_device = host_device
self._window_id = window_id
self._vd_pointer = self.VirtualDevice(self, POINTER)
self._vd_encoder = self.VirtualDevice(self, ENCODER)
self._vd_keypad = self.VirtualDevice(self, KEYPAD)
self.devices = [self._vd_pointer, self._vd_encoder, self._vd_keypad]
peers = _virtual_peers.setdefault(id(host_device), [])
peers.append(self)
self._peers = peers
def _accepts_window(self, event):
if self._window_id is None:
return True
window = getattr(event, "window", None)
return window is None or window == self._window_id
def poll_host_device(self):
if self._peers and self._peers[0] is not self:
return
pending = _virtual_pending.setdefault(id(self._host_device), [])
if not pending:
batch = self._host_device.poll()
if batch:
pending.extend(batch)
while pending:
event = pending.pop(0)
for peer in self._peers:
peer._route(event)
if event.type in (events.FINGERDOWN, events.FINGERUP, events.FINGERMOTION):
return
def _route(self, event):
if not self._accepts_window(event):
return
if event.type in (events.FINGERDOWN, events.FINGERMOTION):
pointer = self._vd_pointer
pointer._set_finger(event.finger_id, event.pos)
if pointer._fingers:
primary_id = min(pointer._fingers)
x, y = pointer._fingers[primary_id]
if event.finger_id == primary_id:
if event.type == events.FINGERDOWN:
pointer.add_event(
events.Button(
events.MOUSEBUTTONDOWN, (x, y), 1, True, event.window
)
)
else:
pointer.add_event(
events.Motion(
events.MOUSEMOTION,
(x, y),
(0, 0),
(1, 0, 0),
True,
event.window,
)
)
elif event.type == events.FINGERUP:
pointer = self._vd_pointer
was_primary = pointer._fingers and event.finger_id == min(pointer._fingers)
last = pointer._fingers.get(event.finger_id, event.pos)
pointer._set_finger(event.finger_id, None)
if was_primary:
pointer.add_event(
events.Button(events.MOUSEBUTTONUP, last, 1, True, event.window)
)
elif event.type in (events.MOUSEBUTTONDOWN, events.MOUSEBUTTONUP) or (
event.type == events.MOUSEMOTION and event.buttons[0]
):
if not (getattr(event, "touch", False) and self._vd_pointer._fingers):
self._vd_pointer.add_event(event)
elif event.type == events.MOUSEWHEEL:
self._vd_encoder.add_event(event)
elif event.type in (events.KEYDOWN, events.KEYUP):
self._vd_keypad.add_event(event)
app = appdev.App(board_config)
def _asyncio_loop_running():
if loop_running is None:
return False
return loop_running()
class event_loop:
"""LVGL task loop driven by ``App.every``.
One instance may be active at a time. Sync mode runs ``lv.task_handler``
from the shared timer; async mode signals an asyncio refresh task.
Prefer ``import display_driver`` (module ``main()``) over constructing this
by hand unless you need custom ``freq`` / ``asynchronous`` settings.
"""
_current_instance = None
def __init__(
self,
freq=None,
max_scheduled=2,
refresh_cb=None,
asynchronous=False,
exception_sink=None,
period_ms=None,
):
"""Create and register the LVGL event loop.
Args:
freq: Desired Hz when ``period_ms`` is omitted (period = ``1000 // freq``).
max_scheduled: Kept for lv_utils API parity (unused).
refresh_cb: Optional zero-arg callable after each successful
``lv.task_handler()``.
asynchronous: When True, drive LVGL via an asyncio refresh task.
exception_sink: Callable receiving exceptions from task handling;
defaults to :meth:`default_exception_sink`.
period_ms: Explicit tick period in milliseconds (overrides ``freq``).
Raises:
RuntimeError: Another loop is already running or async mode is
requested without asyncio.
"""
if self.is_running():
raise RuntimeError("Event loop is already running!")
if not lv.is_initialized():
lv.init()
event_loop._current_instance = self
if period_ms is not None:
self.delay = int(period_ms)
elif freq is not None:
self.delay = max(1, 1000 // int(freq))
else:
self.delay = LVGL_PERIOD_MS
self.refresh_cb = refresh_cb
self.exception_sink = exception_sink if exception_sink else self.default_exception_sink
# Start paused and do not arm machine.Timer until ``enable()``. On
# ESP32-P4, even a no-op timer callback interrupting SPIRAM
# ``draw_buf_create`` corrupts LVGL handlers (Illegal instruction,
# MTVAL often an ASCII fragment like ``star``).
self._pause = 1
self._in_task = False
self._next_ok_ms = None
self._last_tick_ms = None
self.asynchronous = asynchronous
self.refresh_task = None
self._timer_sub = None
self._async_armed = False
if self.asynchronous:
if not asyncio_available:
raise RuntimeError("Cannot run asynchronous event loop. asyncio is not available!")
self.refresh_event = asyncio.Event()
if _asyncio_loop_running():
self.arm()
# Sync: defer ``every`` until first ``enable()`` (see ``_arm_sync_timer``).
def _arm_sync_timer(self):
"""Subscribe the sync tick once; safe to call repeatedly."""
if self.asynchronous:
return
if self._timer_sub is not None:
if app._timer is not None:
return
self._timer_sub = None
self._timer_sub = app.every(self.delay, self.timer_cb)
def arm(self):
"""Create the async refresh task + shared timer once a loop is running.
No-op in sync mode or when already armed. Safe to call repeatedly.
"""
if not self.asynchronous or self._async_armed:
return
self._async_armed = True
self.refresh_task = asyncio.create_task(self.async_refresh())
self._timer_sub = app.every(self.delay, self.timer_cb)
def deinit(self):
"""Stop the tick subscription / async task and clear the singleton."""
if getattr(self, "_timer_sub", None) is not None:
self._timer_sub.cancel()
self._timer_sub = None
if self.asynchronous and self.refresh_task is not None:
self.refresh_task.cancel()
self.refresh_task = None
self._async_armed = False
event_loop._current_instance = None
def disable(self):
"""Pause LVGL task handling (re-entrant; pair with :meth:`enable`)."""
# Pause LVGL task handling (e.g. while building the UI). Re-entrant.
self._pause += 1
def enable(self):
"""Resume LVGL task handling after :meth:`disable`; arms the sync timer."""
if self._pause > 0:
self._pause -= 1
if self._pause == 0:
self._arm_sync_timer()
# Async path: arm refresh task + timer_cb if import-time construction
# could not (MicroPython lacks get_running_loop; UI builders that
# disable()/enable() around layout also land here).
if self.asynchronous and not self._async_armed and _asyncio_loop_running():
self.arm()
@staticmethod
def is_running():
"""True when an :class:`event_loop` instance is currently registered."""
return event_loop._current_instance is not None
@staticmethod
def current_instance():
"""Return the active :class:`event_loop`, or ``None``."""
return event_loop._current_instance
def task_handler(self, _=None):
"""Run ``lv.task_handler()`` once when not paused and not nested."""
if self._in_task or self._pause > 0:
return
self._in_task = True
try:
if lv._nesting.value == 0:
lv.task_handler()
if self.refresh_cb:
self.refresh_cb()
except Exception as e:
if self.exception_sink:
self.exception_sink(e)
finally:
self._in_task = False
def tick(self):
"""Manually invoke the timer callback once (same path as the shared timer)."""
self.timer_cb(None)
def run(self):
"""Blocking forever-tick loop (macOS only; prefer ``app.run()``)."""
if sys.platform == "darwin":
while True:
self.tick()
def _gate_allows(self):
if ticks_ms is None or self._next_ok_ms is None:
return True
# Positive diff means _next_ok_ms is still in the future.
return ticks_diff(self._next_ok_ms, ticks_ms()) <= 0
def _arm_gate(self):
if ticks_ms is None or ticks_add is None:
return
# Pace from completion so a slow flush cannot be immediately followed
# by another (RT-signal backlog under micropython -i).
self._next_ok_ms = ticks_add(ticks_ms(), self.delay)
def timer_cb(self, t):
"""Shared-timer callback: advance LVGL time and run/signal task handling.
Args:
t: Timer instance (ignored; may be ``None`` from :meth:`tick`).
"""
# Called from the app's shared timer (on the main thread).
# In async mode the AsyncTimer fires from inside the running asyncio
# loop, so we can safely arm (create the refresh task) on the first
# tick -- no need for an external coordinator.
if self.asynchronous and not self._async_armed:
self.arm()
# Advance LVGL time by real elapsed ms. The present-frame gate may
# skip task_handler when show()/flush is slow (mipidsi ~30ms); if we
# also skipped tick_inc there, timers ran at ~half wall-clock speed.
if ticks_ms is not None:
now = ticks_ms()
if self._last_tick_ms is None:
self._last_tick_ms = now
elapsed = ticks_diff(now, self._last_tick_ms)
if elapsed > 0:
lv.tick_inc(elapsed)
self._last_tick_ms = now
if not self._gate_allows():
return
if self._pause > 0:
self._arm_gate()
return
if self.asynchronous:
self.refresh_event.set()
self._arm_gate()
else:
self.task_handler()
self._arm_gate()
async def async_refresh(self):
"""Asyncio task body: wait for refresh signals and run ``lv.task_handler``."""
while True:
await self.refresh_event.wait()
if lv._nesting.value == 0:
self.refresh_event.clear()
try:
lv.task_handler()
except Exception as e:
if self.exception_sink:
self.exception_sink(e)
if self.refresh_cb:
self.refresh_cb()
self._arm_gate()
def default_exception_sink(self, e):
"""Print ``e`` with traceback to stderr (default :attr:`exception_sink`)."""
sys.print_exception(e)
def main():
"""Initialize LVGL, wire :class:`DisplayDriver`, and enable the event loop.
Called automatically on ``import display_driver`` when ``board_config``
provides ``display_drv`` and optional neutral input callables.
"""
global _driver_ref, _drivers, _host_pump_sub
gc.collect()
if not lv.is_initialized():
lv.init()
# Never arm a timer before SPIRAM draw buffers exist. A soft-timer callback
# during draw_buf_create can corrupt LVGL handlers on ESP32-P4.
app.stop_timer()
loop_inst = event_loop.current_instance()
if loop_inst is not None:
# Already-running loop: pause around driver (re)construction.
loop_inst.disable()
try:
if lv.group_get_default() is None:
lv.group_create().set_default()
devs = app.devices
_driver_ref = DisplayDriver(
display_drv,
devs,
)
_drivers = [_driver_ref]
# Start event_loop only after draw buffers exist (sync path defers
# every() until enable(); still construct after DisplayDriver so
# host_pump / service cannot arm the shared timer early).
if loop_inst is None:
# PARTIAL: present after every task_handler (blit already wrote the
# panel FB). Shared DIRECT: present only from flush_is_last.
loop_inst = event_loop(
period_ms=LVGL_PERIOD_MS,
asynchronous=app.timer_async,
refresh_cb=_present_lvgl_displays,
)
_ensure_host_pump()
finally:
if loop_inst is not None:
loop_inst.enable()
def _lvgl_shutdown_before_quit():
# Stop the bridge before releasing the display so no callback can touch
# LVGL state during interpreter finalization.
global _host_pump_sub
if _host_pump_sub is not None:
try:
_host_pump_sub.cancel()
except Exception:
pass
_host_pump_sub = None
inst = event_loop.current_instance()
if inst is not None:
inst.deinit()
try:
if lv.is_initialized():
lv.deinit()
except Exception:
pass
app.before_quit = _lvgl_shutdown_before_quit
def _ensure_host_pump():
"""Keep HOST/SDL draining on the 10 ms App tick for all drivers."""
global _host_pump_sub
if _host_pump_sub is not None and app._timer is not None:
return
if _host_pump_sub is not None:
try:
_host_pump_sub.cancel()
except Exception:
pass
_host_pump_sub = None
def _host_pump(_t):
for drv in _drivers:
for vd in getattr(drv, "virtual_devices", ()):
vd.poll_host_device()
_host_pump_sub = app.every(10, _host_pump)
def _present_lvgl_displays():
"""Present PARTIAL panels after ``lv.task_handler`` (DIRECT shows in flush).
Gated to :data:`LVGL_REFR_PERIOD_MS` so a faster ``task_handler`` loop does
not present every tick. DIRECT / shared-FB paths present from flush instead.
"""
global _present_next_ok_ms
if ticks_ms is not None and ticks_diff is not None and ticks_add is not None:
now = ticks_ms()
if _present_next_ok_ms is not None and ticks_diff(_present_next_ok_ms, now) > 0:
return
_present_next_ok_ms = ticks_add(now, LVGL_REFR_PERIOD_MS)
for drv in _drivers:
if getattr(drv, "_share_fb", False):
continue
panel = getattr(drv, "display_drv", None)
if panel is None or not callable(getattr(panel, "show", None)):
continue
try:
panel.show()
except Exception:
pass
def attach(display, devices=None, *, color_format=None, blocking=True):
"""Attach an additional displaydev panel as an LVGL display.
Call after ``import display_driver`` (primary already wired). The display
is also registered with this module's LVGL app.
Args:
display: Secondary displaydev driver.
devices: Optional LVGL input devices to bind as indevs on this display.
When omitted and ``app.host_dev`` exists, that host device is
reused (window-filtered) so the secondary panel receives pointer
input.
color_format: LVGL color format; default RGB565.
blocking: Passed to :class:`DisplayDriver`.
Returns:
DisplayDriver: The new bridge instance.
"""
global _drivers
if not lv.is_initialized():
raise RuntimeError("import display_driver before attach()")
if devices is None:
devices = []
if getattr(app, "host_dev", None) is not None:
devices = [app.host_dev]
app.add_display(display)
kwargs = {"devs": devices, "blocking": blocking}
if color_format is not None:
kwargs["color_format"] = color_format
drv = DisplayDriver(display, **kwargs)
_drivers.append(drv)
loop_inst = event_loop.current_instance()
if loop_inst is not None:
loop_inst.refresh_cb = _present_lvgl_displays
_ensure_host_pump()
return drv
def attach_devices(devs, lv_display=None):
"""Register LVGL input devices as LVGL indevs without creating a display.
Args:
devs: Iterable of LVGL input devices (encoder, keypad, pointer, …).
lv_display: Target ``lv.display``; default is the primary LVGL display.
Returns:
list: Virtual devices accumulated by :func:`create_devices`.
"""
if lv_display is None:
if not _drivers:
raise RuntimeError("no LVGL display; import display_driver first")
lv_display = _drivers[0].lv_display
return create_devices(devs, lv_display)
def _touch_state_for(device):
"""Per-pointer touch state (must not be module-global — multi-display)."""
st = getattr(device, "_lv_touch", None)
if st is None:
st = {"x": 0, "y": 0, "pressed": False}
device._lv_touch = st
return st
def _make_touch_cb(device):
"""Build a pointer event_cb that updates only ``device``'s touch state."""
def _touch_cb(event, indev, data):
st = _touch_state_for(device)
if event is not None:
if event.type == events.MOUSEBUTTONDOWN and event.button == 1:
st["x"], st["y"] = event.pos
st["pressed"] = True
elif event.type == events.MOUSEMOTION and event.buttons[0]:
st["x"], st["y"] = event.pos
elif event.type == events.MOUSEBUTTONUP and event.button == 1:
st["x"], st["y"] = event.pos
st["pressed"] = False
data.point = lv.point_t({"x": st["x"], "y": st["y"]})
data.state = lv.INDEV_STATE.PRESSED if st["pressed"] else lv.INDEV_STATE.RELEASED
return _touch_cb
# CPython: module-level lv.indev_gesture_recognizers_*; MP/CP: indev methods.
_GESTURE_UPDATE = hasattr(lv, "indev_touch_data_t")
# LVGL ``LV_GESTURE_MAX_POINTS`` is 2; finger id is stored as int8_t (-1 = free).
_MAX_GESTURE_TOUCHES = 2
# Windows/pygame often flickers or renumbers finger_id mid-pinch. Track by
# position → stable LVGL slots 0/1, and hold a slot briefly after the OS drops it
# so LVGL does not cancel ONGOING pinch (requires finger_cnt == 2).
_GESTURE_STICKY_MS = 250
_gesture_touches = None
# id(device) -> {slot: (x, y, last_ms)}
_gesture_slots = {}
def _gesture_tick_ms():
try:
return int(lv.tick_get())
except Exception:
return 0
def _gesture_dist2(a, b):
dx = a[0] - b[0]
dy = a[1] - b[1]
return dx * dx + dy * dy
def _gesture_track_slots(dev_key, points, now):
"""Map live contacts to stable slots 0..1 by nearest prior position.
Returns (pressed dict slot→(x,y), released slot list).
"""
live = [(int(pt[0]), int(pt[1])) for pt in points]
prev = _gesture_slots.get(dev_key) or {}
new_slots = {}
assigned_live = set()
# Match against last-known positions (ignore OS finger_id churn).
if live and prev:
slot_ids = list(prev.keys())
if len(live) == 2 and len(slot_ids) == 2:
s0, s1 = slot_ids[0], slot_ids[1]
d_same = _gesture_dist2(live[0], prev[s0][:2]) + _gesture_dist2(live[1], prev[s1][:2])
d_swap = _gesture_dist2(live[0], prev[s1][:2]) + _gesture_dist2(live[1], prev[s0][:2])
if d_same <= d_swap:
new_slots[s0] = (live[0][0], live[0][1], now)
new_slots[s1] = (live[1][0], live[1][1], now)
else:
new_slots[s1] = (live[0][0], live[0][1], now)
new_slots[s0] = (live[1][0], live[1][1], now)
assigned_live = {0, 1}
else:
pairs = []
for li, xy in enumerate(live):
for s, (sx, sy, _) in prev.items():
pairs.append((_gesture_dist2(xy, (sx, sy)), li, s))
pairs.sort()
used_s = set()
for _, li, s in pairs:
if li in assigned_live or s in used_s:
continue
assigned_live.add(li)
used_s.add(s)
x, y = live[li]
new_slots[s] = (x, y, now)
for li, xy in enumerate(live):
if li in assigned_live: