Repository navigation
Expand file tree
/
Copy pathdisplay.py
More file actions
806 lines (667 loc) · 35.2 KB
/
Copy pathdisplay.py
File metadata and controls
806 lines (667 loc) · 35.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
"""
display.py — управление OLED-дисплеем SSD1306 128×32.
CircuitPython 9+/10+: displayio.I2CDisplay переехал в i2cdisplaybus.I2CDisplayBus
Библиотеки (положить в lib/):
adafruit_displayio_ssd1306.mpy
adafruit_display_text/ (папка)
terminalio — встроен в CircuitPython 7+.
Компоновка экрана 128×32 (anchor_point = (0.5, 0.5) — центр по горизонтали и вертикали):
y= 4 — верхняя строка (статус / заголовок)
y=16 — центральная (имя текущего пункта меню)
y=24 — нижняя строка (следующее действие / подсказка)
"""
import board
import busio
import displayio
import terminalio
import time
from adafruit_display_text import label
import adafruit_displayio_ssd1306
import i2cdisplaybus # CircuitPython 9+/10+
import config as cfg
try:
import bitmaptools
except ImportError:
bitmaptools = None
_W = 128
_H = 32
_ADDR = 0x3C
# Geometric render constants
GEO_SLOTS = 6 # слотов на странице
GEO_SHAPES = ("square", "triangle", "circle", "diamond")
GEO_REST = 16 # размер невыбранной фигуры, px
GEO_SEL = 28 # размер выбранной фигуры, px
GEO_GAP = 3 # зазор, px
class DisplayManager:
def __init__(self):
hw = cfg.get_config().get("hardware", {})
sda_num = hw.get("display_sda", 4)
scl_num = hw.get("display_scl", 5)
sda = getattr(board, "GP" + str(sda_num))
scl = getattr(board, "GP" + str(scl_num))
displayio.release_displays()
i2c = None
try:
i2c = busio.I2C(scl=scl, sda=sda, frequency=400_000)
self.i2c = i2c
# ИСПРАВЛЕНО: i2cdisplaybus.I2CDisplayBus вместо displayio.I2CDisplay
bus = i2cdisplaybus.I2CDisplayBus(i2c, device_address=_ADDR)
self._disp = adafruit_displayio_ssd1306.SSD1306(bus, width=_W, height=_H)
_cx = _W // 2 # 64 — горизонтальный центр экрана
# ── Основная группа: 3 переиспользуемых лейбла ──────────────────
self._main_group = displayio.Group()
self._lbl_top = self._make_label(" ", _cx, 4)
self._lbl_center = self._make_label(" ", _cx, 16)
self._lbl_bottom = self._make_label(" ", _cx, 24)
self._main_group.append(self._lbl_top)
self._main_group.append(self._lbl_center)
self._main_group.append(self._lbl_bottom)
self._disp.root_group = self._main_group
# ── Группа анимации: два лейбла, пересоздаются не в цикле ───────
self._anim_group = displayio.Group()
self._lbl_anim_old = self._make_label(" ", _cx, 16)
self._lbl_anim_new = self._make_label(" ", _cx + _W, 16)
self._anim_group.append(self._lbl_anim_old)
self._anim_group.append(self._lbl_anim_new)
# ── Группа скринсейвера ─────────────────────────────────────────
self._screensaver_bitmap = displayio.Bitmap(_W, _H, 2)
self._screensaver_palette = displayio.Palette(2)
self._screensaver_palette[0] = 0x000000
self._screensaver_palette[1] = 0xFFFFFF
self._screensaver_tile_grid = displayio.TileGrid(
self._screensaver_bitmap,
pixel_shader=self._screensaver_palette
)
self._screensaver_group = displayio.Group()
self._screensaver_group.append(self._screensaver_tile_grid)
self._screensaver_manager = None
# ── Geometric render группа ─────────────────────────────────────
self._render_mode = "text"
self._geo_bitmap = displayio.Bitmap(_W, _H, 2)
self._geo_palette = displayio.Palette(2)
self._geo_palette[0] = 0x000000
self._geo_palette[1] = 0xFFFFFF
self._geo_group = displayio.Group()
self._geo_group.append(displayio.TileGrid(self._geo_bitmap, pixel_shader=self._geo_palette))
self._geo_cursor = 0 # последнее показанное положение курсора
self._geo_total = 0
self._geo_depth = 0
self._geo_target_cursor = 0
self._geo_target_total = 0
self._geo_target_depth = 0
self._geo_last_bump = 0.0
# ── Поддержка иконок ────────────────────────────────────────────
self._menu_items = []
self._icon_data = {} # key = id, value = список из 28 int-масок или None
self._icon_scaled = {} # key = (id, size), value = список из size int-масок
self._icon_invalid = set() # id пунктов с невалидными иконками (для лога)
print("[display] init OK SDA=GP", sda_num, " SCL=GP", scl_num)
except Exception:
if i2c is not None:
try:
i2c.deinit()
except Exception:
pass
self.i2c = None
raise
# ── Public: режим рендера и состояние меню ─────────────────────────────
def set_render_mode(self, mode):
"""Установить режим рендера: 'text' или 'geometric'."""
if mode not in ("text", "geometric"):
print(f"[display] WARNING: unknown render mode '{mode}', defaulting to 'text'")
mode = "text"
self._render_mode = mode
print(f"[display] render mode: {mode}")
def set_menu_state(self, cursor, total, depth):
"""Запомнить целевое состояние меню (вызывается перед draw_menu/animate_swipe)."""
self._geo_target_cursor = cursor
self._geo_target_total = total
self._geo_target_depth = depth
def set_menu_items(self, items):
"""Сохранить список пунктов меню для geometric-рендера с иконками."""
self._menu_items = items if items else []
def _geo_active(self):
"""Проверка активности геометрического режима."""
return (
self._render_mode == "geometric" and
self._geo_target_depth == 0 and
self._geo_target_total > 0
)
def is_geometric(self):
"""Публичная проверка геометрического режима."""
return self._render_mode == "geometric"
def _geo_fail(self, err):
"""Откат на текстовый режим при ошибке геометрического рендера."""
print("[display] geometric render failed, fallback to text:", err)
self._render_mode = "text"
try:
self._disp.auto_refresh = True
except Exception:
pass
# ── Geometric render: bitmap drawing ───────────────────────────────────
def _px(self, x, y):
"""Установить пиксель в bitmap с клиппингом."""
if 0 <= x < _W and 0 <= y < _H:
self._geo_bitmap[x, y] = 1
def _fill_shape(self, kind, cx, cy, size, color, dx=0):
"""Залить фигуру с центром (cx+dx, cy), размер size×size."""
half = size // 2
cx = cx + dx
if bitmaptools is not None:
# Быстрый путь через bitmaptools.fill_region
if kind == "square":
x1 = max(0, cx - half)
x2 = min(_W, cx + half + 1)
y1 = max(0, cy - half)
y2 = min(_H, cy + half + 1)
if x1 < x2 and y1 < y2:
bitmaptools.fill_region(self._geo_bitmap, x1, y1, x2, y2, color)
elif kind == "circle":
r = half
for dy in range(-half, half + 1):
y_abs = cy + dy
if not (0 <= y_abs < _H):
continue
dx_max = int((r * r - dy * dy) ** 0.5) if (r * r - dy * dy) >= 0 else 0
x1 = max(0, cx - dx_max)
x2 = min(_W, cx + dx_max + 1)
if x1 < x2:
bitmaptools.fill_region(self._geo_bitmap, x1, y_abs, x2, y_abs + 1, color)
elif kind == "triangle":
for dy in range(-half, half + 1):
y_abs = cy + dy
if not (0 <= y_abs < _H):
continue
ratio = (dy + half) / (size if size > 0 else 1)
dx_max = int(half * ratio)
x1 = max(0, cx - dx_max)
x2 = min(_W, cx + dx_max + 1)
if x1 < x2:
bitmaptools.fill_region(self._geo_bitmap, x1, y_abs, x2, y_abs + 1, color)
elif kind == "diamond":
for dy in range(-half, half + 1):
y_abs = cy + dy
if not (0 <= y_abs < _H):
continue
dx_max = int(half * (1 - abs(dy) / (half if half > 0 else 1)))
x1 = max(0, cx - dx_max)
x2 = min(_W, cx + dx_max + 1)
if x1 < x2:
bitmaptools.fill_region(self._geo_bitmap, x1, y_abs, x2, y_abs + 1, color)
else:
# Запасной пиксельный путь
if kind == "square":
for dy in range(-half, half + 1):
for dxx in range(-half, half + 1):
x, y = cx + dxx, cy + dy
if 0 <= x < _W and 0 <= y < _H:
self._geo_bitmap[x, y] = color
elif kind == "circle":
r = half
for dy in range(-half, half + 1):
dx_max = int((r * r - dy * dy) ** 0.5) if (r * r - dy * dy) >= 0 else 0
for dxx in range(-dx_max, dx_max + 1):
x, y = cx + dxx, cy + dy
if 0 <= x < _W and 0 <= y < _H:
self._geo_bitmap[x, y] = color
elif kind == "triangle":
for dy in range(-half, half + 1):
ratio = (dy + half) / (size if size > 0 else 1)
dx_max = int(half * ratio)
for dxx in range(-dx_max, dx_max + 1):
x, y = cx + dxx, cy + dy
if 0 <= x < _W and 0 <= y < _H:
self._geo_bitmap[x, y] = color
elif kind == "diamond":
for dy in range(-half, half + 1):
dx_max = int(half * (1 - abs(dy) / (half if half > 0 else 1)))
for dxx in range(-dx_max, dx_max + 1):
x, y = cx + dxx, cy + dy
if 0 <= x < _W and 0 <= y < _H:
self._geo_bitmap[x, y] = color
def _draw_shape(self, kind, cx, cy, size, filled, dx=0):
"""Нарисовать фигуру (заливка или контур)."""
if filled or size <= 6:
self._fill_shape(kind, cx, cy, size, 1, dx)
else:
# Контур: внешняя заливка белым, внутренняя черным
self._fill_shape(kind, cx, cy, size, 1, dx)
self._fill_shape(kind, cx, cy, size - 4, 0, dx)
def _draw_slot(self, idx, shape_kind, cx, cy, size, filled, dx):
"""Нарисовать слот: иконку (если есть) или фигуру.
idx: абсолютный индекс пункта меню
shape_kind: тип фигуры (для fallback)
cx, cy: центр слота
size: размер
filled: True для выбранного слота
dx: горизонтальный сдвиг для анимации
"""
item = None
if 0 <= idx < len(self._menu_items):
item = self._menu_items[idx]
# Попытка нарисовать иконку
if item and item.get("icon"):
try:
icon_drawn = self._draw_icon(item, cx, cy, size, filled, dx)
if icon_drawn:
return # иконка успешно отрисована
except Exception:
pass # fallback на фигуру, без _geo_fail()
# Fallback на фигуру
self._draw_shape(shape_kind, cx, cy, size, filled, dx)
# ── Icon support ───────────────────────────────────────────────────────
def _decode_icon(self, item_id, icon_data):
"""Декодировать иконку из config.json в список int-масок (28 строк).
Возвращает список из 28 int или None при ошибке.
"""
if not isinstance(icon_data, list):
if item_id not in self._icon_invalid:
print(f"[display] icon invalid for '{item_id}': not a list")
self._icon_invalid.add(item_id)
return None
if len(icon_data) != 28:
if item_id not in self._icon_invalid:
print(f"[display] icon invalid for '{item_id}': height {len(icon_data)} != 28")
self._icon_invalid.add(item_id)
return None
masks = []
for row_idx, row in enumerate(icon_data):
if not isinstance(row, list) or len(row) != 28:
if item_id not in self._icon_invalid:
print(f"[display] icon invalid for '{item_id}': row {row_idx} length != 28")
self._icon_invalid.add(item_id)
return None
mask = 0
for col_idx, pixel in enumerate(row):
if pixel not in (0, 1, "0", "1"):
if item_id not in self._icon_invalid:
print(f"[display] icon invalid for '{item_id}': row {row_idx} col {col_idx} not 0/1")
self._icon_invalid.add(item_id)
return None
if pixel == 1 or pixel == "1":
mask |= (1 << col_idx)
masks.append(mask)
return masks
def _scale_icon_nn(self, masks_28, target_size):
"""Масштабировать иконку 28×28 → target_size nearest-neighbor.
masks_28: список из 28 int-масок.
Возвращает список из target_size int-масок.
"""
if target_size == 28:
return masks_28
scaled = []
for y in range(target_size):
src_y = (y * 28) // target_size
src_mask = masks_28[src_y]
new_mask = 0
for x in range(target_size):
src_x = (x * 28) // target_size
if src_mask & (1 << src_x):
new_mask |= (1 << x)
scaled.append(new_mask)
return scaled
def _draw_icon(self, item, cx, cy, size, filled, dx):
"""Нарисовать иконку пункта меню в geometric-режиме.
item: dict пункта меню с полем "icon"
cx, cy: центр слота
size: текущий размер слота (GEO_REST..GEO_SEL или промежуточный)
filled: True — выбранный слот; если size>=12 рисуется рамка + уменьшенная
иконка внутри; если size<12 — иконка без рамки (как filled=False)
dx: горизонтальный сдвиг для анимации
"""
try:
item_id = item.get("id", "?")
icon_ref = item.get("icon")
if not icon_ref:
return False # нет иконки, fallback на фигуру
# Декодирование иконки (lazy, с кэшем)
if item_id not in self._icon_data:
self._icon_data[item_id] = self._decode_icon(item_id, icon_ref)
masks_28 = self._icon_data[item_id]
if masks_28 is None:
return False # невалидная иконка
# Рамку рисуем только при filled=True и достаточном size
draw_frame = filled and size >= 12
# scaled_size — фактический размер, в который масштабируем иконку
scaled_size = (size - 4) if draw_frame else size
# Масштабирование (с кэшем; ключ = (item_id, scaled_size))
cache_key = (item_id, scaled_size)
if cache_key not in self._icon_scaled:
self._icon_scaled[cache_key] = self._scale_icon_nn(masks_28, scaled_size)
masks = self._icon_scaled[cache_key]
half = size // 2
cx_shifted = cx + dx
# ── Рамка ───────────────────────────────────────────────────────
if draw_frame:
# Контур квадрата size×size с центром (cx_shifted, cy).
# Координаты крайних пикселей (включительно):
x0 = cx_shifted - half
x1 = cx_shifted - half + size - 1
y0 = cy - half
y1 = cy - half + size - 1
# Горизонтальные стороны (верх/низ), угловые пиксели пропускаем
for x in range(x0 + 1, x1):
if 0 <= x < _W:
if 0 <= y0 < _H:
self._geo_bitmap[x, y0] = 1
if 0 <= y1 < _H:
self._geo_bitmap[x, y1] = 1
# Вертикальные стороны (лево/право), угловые пиксели пропускаем
for y in range(y0 + 1, y1):
if 0 <= y < _H:
if 0 <= x0 < _W:
self._geo_bitmap[x0, y] = 1
if 0 <= x1 < _W:
self._geo_bitmap[x1, y] = 1
# ── Иконка ──────────────────────────────────────────────────────
# Центр иконки = центр слота; при рамке размер уменьшен на 4px,
# что даёт зазор 1px между рамкой и иконкой с каждой стороны
# (рамка 1px + gap 1px = 2px с каждой стороны → inner = size - 4).
inner_half = scaled_size // 2
for dy_i in range(scaled_size):
y_abs = cy - inner_half + dy_i
if not (0 <= y_abs < _H):
continue
mask = masks[dy_i]
for dxx in range(scaled_size):
if mask & (1 << dxx):
x_abs = cx_shifted - inner_half + dxx
if 0 <= x_abs < _W:
self._geo_bitmap[x_abs, y_abs] = 1
return True # иконка отрисована успешно
except Exception:
return False # fallback на фигуру
# ── Geometric render: row ──────────────────────────────────────────────
def _geo_row(self, page, sel_index, sel_size, other_size, dx):
"""Нарисовать ряд слотов для страницы."""
start_idx = page * GEO_SLOTS
end_idx = min(self._geo_target_total, (page + 1) * GEO_SLOTS)
count = end_idx - start_idx
if count <= 0:
return
# Вычисляем общую ширину ряда
total_width = 0
for i in range(start_idx, end_idx):
if i == sel_index:
total_width += sel_size
else:
total_width += other_size
total_width += GEO_GAP * (count - 1)
# Начальная позиция X (центрируем ряд)
x = (_W - total_width) // 2
y = 16
# Рисуем слоты
shape_kind = GEO_SHAPES[page % len(GEO_SHAPES)]
for i in range(start_idx, end_idx):
size = sel_size if i == sel_index else other_size
filled = (i == sel_index)
half = size // 2
# Единый helper для иконки или фигуры
self._draw_slot(i, shape_kind, x + half, y, size, filled, dx)
x += size + GEO_GAP
# ── Geometric render: static and animation ─────────────────────────────
def bump(self, direction):
"""Анимация упора в края меню (только для геометрического режима)."""
if self._render_mode != "geometric" or self._geo_total <= 0:
return
now = time.monotonic()
if now - self._geo_last_bump < 0.2:
return
self._geo_last_bump = now
try:
duration = 0.16
sgn = -1 if direction == "left" else 1
start_time = time.monotonic()
self._disp.auto_refresh = False
try:
while True:
elapsed = time.monotonic() - start_time
t = min(1.0, elapsed / duration)
# Треугольный профиль: вперёд до 0.5, назад после 0.5
p = t * 2 if t < 0.5 else (1 - t) * 2
dx = int(round(sgn * 6 * p))
self._geo_bitmap.fill(0)
# Рисуем ряд со сдвигом
page = self._geo_cursor // GEO_SLOTS
self._geo_row(page, self._geo_cursor, GEO_SEL, GEO_REST, dx)
# Рисуем стенку
if bitmaptools is not None:
if direction == "left":
bitmaptools.fill_region(self._geo_bitmap, 0, 0, 2, _H, 1)
else:
bitmaptools.fill_region(self._geo_bitmap, _W - 2, 0, _W, _H, 1)
else:
# Запасной путь через _px
if direction == "left":
for y in range(_H):
self._geo_bitmap[0, y] = 1
self._geo_bitmap[1, y] = 1
else:
for y in range(_H):
self._geo_bitmap[_W - 2, y] = 1
self._geo_bitmap[_W - 1, y] = 1
self._disp.root_group = self._geo_group
self._disp.refresh()
if t >= 1.0:
break
finally:
self._disp.auto_refresh = True
# Финальный статичный кадр
self._draw_geo_static(self._geo_cursor, self._geo_total)
except Exception as e:
self._geo_fail(e)
def _draw_geo_static(self, cursor, total):
"""Статичная отрисовка геометрического меню."""
self._disp.auto_refresh = False
try:
self._geo_bitmap.fill(0)
page = cursor // GEO_SLOTS
self._geo_row(page, cursor, GEO_SEL, GEO_REST, 0)
self._disp.root_group = self._geo_group
self._disp.refresh()
finally:
self._disp.auto_refresh = True
self._geo_cursor = cursor
self._geo_total = total
def _animate_geo(self, old_cursor, new_cursor, total, direction):
"""Анимация переходов в геометрическом режиме."""
old_page = old_cursor // GEO_SLOTS
new_page = new_cursor // GEO_SLOTS
self._disp.auto_refresh = False
try:
if old_page == new_page:
# Анимация роста внутри одной страницы
duration = 0.14
start_time = time.monotonic()
while True:
elapsed = time.monotonic() - start_time
t = min(1.0, elapsed / duration)
# Ease-out: p = 1 - (1 - t)^2
p = 1 - (1 - t) * (1 - t)
old_size = int(GEO_SEL - (GEO_SEL - GEO_REST) * p)
new_size = int(GEO_REST + (GEO_SEL - GEO_REST) * p)
self._geo_bitmap.fill(0)
# Рисуем старый выбранный (сжимается)
old_page_calc = old_cursor // GEO_SLOTS
start_idx = old_page_calc * GEO_SLOTS
end_idx = min(total, (old_page_calc + 1) * GEO_SLOTS)
count = end_idx - start_idx
# Пересчитываем ширину с текущими размерами
total_width = 0
for idx in range(start_idx, end_idx):
if idx == old_cursor:
total_width += old_size
elif idx == new_cursor:
total_width += new_size
else:
total_width += GEO_REST
total_width += GEO_GAP * (count - 1)
x = (_W - total_width) // 2
y = 16
shape_kind = GEO_SHAPES[old_page_calc % len(GEO_SHAPES)]
for idx in range(start_idx, end_idx):
if idx == old_cursor:
size = old_size
filled = True
elif idx == new_cursor:
size = new_size
filled = True
else:
size = GEO_REST
filled = False
half = size // 2
self._draw_slot(idx, shape_kind, x + half, y, size, filled, 0)
x += size + GEO_GAP
self._disp.root_group = self._geo_group
self._disp.refresh()
if t >= 1.0:
break
else:
# Анимация слайда между страницами
duration = 0.18
start_time = time.monotonic()
step_px = _W
dir_mult = 1 if direction == "right" else -1
while True:
elapsed = time.monotonic() - start_time
t = min(1.0, elapsed / duration)
# Ease-out: p = 1 - (1 - t)^2
p = 1 - (1 - t) * (1 - t)
self._geo_bitmap.fill(0)
offset = int(step_px * p)
# Старая страница уходит
old_dx = -dir_mult * offset
self._geo_row(old_page, old_cursor, GEO_REST, GEO_REST, old_dx)
# Новая страница входит
new_dx = dir_mult * (step_px - offset)
self._geo_row(new_page, new_cursor, GEO_SEL, GEO_REST, new_dx)
self._disp.root_group = self._geo_group
self._disp.refresh()
if t >= 1.0:
break
finally:
self._disp.auto_refresh = True
# Обновляем текущее состояние
self._geo_cursor = new_cursor
self._geo_total = total
# ── Public: основные экраны ────────────────────────────────────────────
def draw_menu(self, item_label, action_name=""):
if self._geo_active():
try:
self._draw_geo_static(self._geo_target_cursor, self._geo_target_total)
return
except Exception as e:
self._geo_fail(e)
_cx = _W // 2
self._lbl_top.anchored_position = (_cx, 4)
self._lbl_center.anchored_position = (_cx, 16)
self._lbl_bottom.anchored_position = (_cx, 27)
self._lbl_top.text = "< MENU >"
self._lbl_center.text = self._fit(item_label, 21)
self._lbl_bottom.text = ("-> " + action_name) if action_name else " "
self._disp.root_group = self._main_group
def show_executing(self, item_label, action_name=""):
_cx = _W // 2
self._lbl_top.anchored_position = (_cx, 4)
self._lbl_center.anchored_position = (_cx, 16)
self._lbl_bottom.anchored_position = (_cx, 27)
self._lbl_top.text = "Running..."
self._lbl_center.text = self._fit(item_label, 21)
self._lbl_bottom.text = self._fit(action_name, 21) if action_name else " "
self._disp.root_group = self._main_group
def show_status(self, line1="", line2="", line3=""):
_cx = _W // 2
self._lbl_top.anchored_position = (_cx, 4)
self._lbl_center.anchored_position = (_cx, 16)
self._lbl_bottom.anchored_position = (_cx, 27)
self._lbl_top.text = self._fit(line1, 21) if line1 else " "
self._lbl_center.text = self._fit(line2, 21) if line2 else " "
self._lbl_bottom.text = self._fit(line3, 21) if line3 else " "
self._disp.root_group = self._main_group
def show_encoder_control(self, mode_label, mode_type=""):
_cx = _W // 2
self._lbl_top.anchored_position = (_cx, 4)
self._lbl_center.anchored_position = (_cx, 16)
self._lbl_bottom.anchored_position = (_cx, 27)
self._lbl_top.text = "< CONTROL >"
self._lbl_center.text = self._fit(mode_label, 21)
self._lbl_bottom.text = self._fit(mode_type, 21) if mode_type else "Long: Exit"
self._disp.root_group = self._main_group
def show_boot(self):
self.show_status(line2="Booting...")
# ── Public: анимация перехода ──────────────────────────────────────────
def animate_swipe(self, old_label, new_label, direction="right"):
if self._geo_active():
try:
self._animate_geo(self._geo_cursor, self._geo_target_cursor, self._geo_target_total, direction)
return
except Exception as e:
self._geo_fail(e)
self._lbl_anim_old.text = self._fit(old_label, 21)
self._lbl_anim_new.text = self._fit(new_label, 21)
frames = 6
step_px = _W // frames # 21 px за кадр
cx = _W // 2 # 64
cy = 16
self._disp.root_group = self._anim_group
for i in range(frames + 1):
offset = i * step_px
if direction == "right":
self._lbl_anim_old.anchored_position = (cx - offset, cy)
self._lbl_anim_new.anchored_position = (cx + _W - offset, cy)
else:
self._lbl_anim_old.anchored_position = (cx + offset, cy)
self._lbl_anim_new.anchored_position = (cx - _W + offset, cy)
time.sleep(0.022)
self._disp.root_group = self._main_group
# ── Public: скринсейвер и сон ──────────────────────────────────────────
def start_screensaver(self, name):
import screensaver
self._screensaver_manager = screensaver.ScreensaverManager(self._screensaver_bitmap, name)
# Отключаем автоматическое обновление экрана, чтобы избежать мерцания в процессе отрисовки
try:
self._disp.auto_refresh = False
except AttributeError:
pass
self._disp.root_group = self._screensaver_group
def update_screensaver(self):
if self._screensaver_manager:
self._screensaver_manager.draw_frame()
# Принудительно обновляем экран только ПОСЛЕ полной отрисовки кадра
try:
self._disp.refresh()
except AttributeError:
pass
def stop_screensaver(self):
self._screensaver_manager = None
# Возвращаем автоматическое обновление для нормальной работы меню
try:
self._disp.auto_refresh = True
except AttributeError:
pass
self._disp.root_group = self._main_group
def sleep(self):
try:
self._disp.sleep()
except AttributeError:
self._disp.root_group = displayio.Group()
def wake(self):
try:
self._disp.wake()
except AttributeError:
pass
self._disp.root_group = self._main_group
# ── Internal ──────────────────────────────────────────────────────────
def _make_label(self, text, x, y):
return label.Label(
terminalio.FONT,
text=text,
color=0xFFFFFF,
anchor_point=(0.5, 0.5),
anchored_position=(x, y),
)
@staticmethod
def _fit(text, max_chars):
if len(text) <= max_chars:
return text
return text[:max_chars - 1] + "~"