ui.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. """ui.py -- fullscreen touchscreen UI for the Steam Deck forwarder.
  2. Big tappable tiles, one per bonded puck. A tile is tappable when its puck is LIVE (the RF link is up).
  3. Tapping a live tile detaches the Deck controls and forwards to that puck (a single tap -- connecting is
  4. cheap and reversible). The two DESTRUCTIVE actions -- stopping/disconnecting a forward, and removing a
  5. bond (unpair) -- instead require a 5-SECOND HOLD: an errant screen tap mid-game used to drop the forward
  6. (which on the puck side tears down a USB device and could reboot the MCU), so a brief touch must no longer
  7. trigger it. A progress fill shows the hold; lifting before it completes cancels. Sized for the Deck's
  8. 1280x800 touchscreen but scales.
  9. """
  10. import time
  11. import pygame
  12. # Destructive actions (stop forwarding, remove bond) require holding this long; a tap no longer triggers them.
  13. HOLD_SECS = 5.0
  14. BG = (16, 18, 24)
  15. FG = (230, 232, 238)
  16. DIM = (120, 126, 140)
  17. ACCENT = (90, 170, 255)
  18. LIVE = (70, 200, 120)
  19. WARN = (235, 180, 70)
  20. STOP = (235, 90, 90)
  21. TILE = (32, 36, 46)
  22. TILE_LIVE = (28, 54, 40)
  23. TILE_SEL = (40, 70, 110)
  24. def _font(sz, bold=False):
  25. f = pygame.font.SysFont("noto sans,dejavusans,sans", sz, bold=bold)
  26. return f
  27. def run(app):
  28. pygame.init()
  29. pygame.display.set_caption("ReversePuck · Steam Deck")
  30. screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
  31. W, H = screen.get_size()
  32. clock = pygame.time.Clock()
  33. f_title = _font(int(H * 0.05), bold=True)
  34. f_big = _font(int(H * 0.045), bold=True)
  35. f_med = _font(int(H * 0.03))
  36. f_small = _font(int(H * 0.022))
  37. tile_rects = [] # (rect, slot, tappable)
  38. del_rects = [] # (rect, slot) -- the per-tile "remove bond" ✕ target
  39. # Active hold-to-confirm gesture, or None. dict(kind="stop"|"unpair", slot, start). Read by draw() for
  40. # the progress fill; set in handle_down()/cleared in handle_up() and on completion.
  41. hold = None
  42. def hold_progress():
  43. """0.0..1.0 of the current hold, or None if no hold is active."""
  44. if hold is None:
  45. return None
  46. return max(0.0, min(1.0, (time.monotonic() - hold["start"]) / HOLD_SECS))
  47. def draw():
  48. nonlocal tile_rects, del_rects
  49. screen.fill(BG)
  50. s = app.status
  51. connected = app.dongle_connected
  52. # compact status line (no big title banner): dongle presence first, then RF link
  53. if not connected:
  54. badge, col = "⨯ no dongle", WARN
  55. elif s["link_up"]:
  56. badge, col = "● linked ch%d" % s["sess_ch"], LIVE
  57. else:
  58. badge, col = "○ searching…", DIM
  59. t = f_med.render(badge, True, col)
  60. screen.blit(t, (W - t.get_width() - 40, 24))
  61. # tiles -- live pucks float to the top, then by slot index
  62. tile_rects = []
  63. del_rects = []
  64. bonds = sorted(s["bonds"], key=lambda b: (not b["alive"], b["slot"]))
  65. top = int(H * 0.16)
  66. gap = int(H * 0.025)
  67. th = int((H * 0.42 - gap * max(0, len(bonds) - 1)) / max(1, len(bonds)))
  68. th = min(th, int(H * 0.20))
  69. if not connected:
  70. msg = f_big.render("Plug in the ReversePuck dongle", True, WARN)
  71. screen.blit(msg, (W // 2 - msg.get_width() // 2, H // 2 - 40))
  72. sub = f_small.render("Waiting for the nRF (Valve 28DE:1302) on USB… it'll appear here automatically.",
  73. True, DIM)
  74. screen.blit(sub, (W // 2 - sub.get_width() // 2, H // 2 + 20))
  75. elif not bonds:
  76. msg = f_big.render("No paired pucks", True, DIM)
  77. screen.blit(msg, (W // 2 - msg.get_width() // 2, H // 2 - 40))
  78. sub = f_small.render("Pair on a computer with Steam or PairTUI (scpair.py), then plug the puck into your host.",
  79. True, DIM)
  80. screen.blit(sub, (W // 2 - sub.get_width() // 2, H // 2 + 20))
  81. for n, b in enumerate(bonds):
  82. slot = b["slot"]
  83. y = top + n * (th + gap)
  84. rect = pygame.Rect(40, y, W - 80, th)
  85. sel = app.forwarding and app.fwd_slot == slot
  86. tappable = b["alive"] and not app.forwarding
  87. color = TILE_SEL if sel else (TILE_LIVE if b["alive"] else TILE)
  88. pygame.draw.rect(screen, color, rect, border_radius=18)
  89. pygame.draw.rect(screen, (ACCENT if (tappable or sel) else DIM), rect, width=2, border_radius=18)
  90. # glyph + serial
  91. glyph = "●" if b["alive"] else "○"
  92. gcol = LIVE if b["alive"] else DIM
  93. screen.blit(f_big.render(glyph, True, gcol), (rect.x + 30, rect.y + th // 2 - 22))
  94. screen.blit(f_big.render(b["serial"] or "puck %d" % slot, True, FG),
  95. (rect.x + 90, rect.y + 20))
  96. state = ("FORWARDING — hold anywhere to stop" if sel
  97. else "available — tap to forward" if tappable
  98. else "live (forwarding elsewhere)" if b["alive"]
  99. else "paired · offline")
  100. screen.blit(f_small.render("slot %d · %s" % (slot, state), True, DIM),
  101. (rect.x + 90, rect.y + th - 38))
  102. tile_rects.append((rect, slot, tappable or sel))
  103. # remove-bond ✕ on the far right (only when idle -- can't un-bond while forwarding)
  104. if not app.forwarding:
  105. dsz = min(th - 24, 64)
  106. drect = pygame.Rect(rect.right - dsz - 18, rect.y + (th - dsz) // 2, dsz, dsz)
  107. pygame.draw.rect(screen, TILE, drect, border_radius=12)
  108. # while this ✕ is being held, fill it from the bottom up as a hold-to-unpair progress meter
  109. hp = hold_progress()
  110. if hold is not None and hold["kind"] == "unpair" and hold["slot"] == slot and hp:
  111. fh = int(dsz * hp)
  112. fill = pygame.Rect(drect.x, drect.bottom - fh, dsz, fh)
  113. pygame.draw.rect(screen, STOP, fill, border_radius=12)
  114. pygame.draw.rect(screen, STOP, drect, width=2, border_radius=12)
  115. x = f_big.render("✕", True, FG if (hold is not None and hold["kind"] == "unpair"
  116. and hold["slot"] == slot) else STOP)
  117. screen.blit(x, (drect.centerx - x.get_width() // 2,
  118. drect.centery - x.get_height() // 2))
  119. screen.blit(f_small.render("hold to remove", True, DIM),
  120. (drect.x - 6, drect.bottom + 2))
  121. del_rects.append((drect, slot))
  122. # firmware log panel (the in-app serial monitor) — fills the area below the tiles
  123. log_top = int(H * 0.60)
  124. log_bot = H - int(H * (0.12 if app.forwarding else 0.02))
  125. lh = f_small.get_height() + 2
  126. nlines = max(1, (log_bot - log_top - 24) // lh)
  127. screen.blit(f_small.render("firmware log", True, DIM), (40, log_top))
  128. lines = app.log[-nlines:]
  129. for i, ln in enumerate(lines):
  130. # colorize the lines that matter for connecting
  131. c = DIM
  132. if "SESSION live" in ln or "CONNECTED" in ln:
  133. c = LIVE
  134. elif "adopted" in ln or "E1 heard" in ln:
  135. c = ACCENT
  136. elif "lost" in ln or "no bond" in ln or "fail" in ln:
  137. c = WARN
  138. screen.blit(f_small.render(ln[:120], True, c), (40, log_top + 24 + i * lh))
  139. # forwarding banner (drawn last so it sits on top)
  140. if app.forwarding:
  141. bar = pygame.Rect(0, H - int(H * 0.1), W, int(H * 0.1))
  142. pygame.draw.rect(screen, STOP, bar)
  143. hp = hold_progress()
  144. if hold is not None and hold["kind"] == "stop" and hp:
  145. # fill the banner left->right as the stop hold progresses; lighten so the fill reads as a meter
  146. pygame.draw.rect(screen, (255, 150, 150),
  147. pygame.Rect(bar.x, bar.y, int(bar.width * hp), bar.height))
  148. left = max(0.0, HOLD_SECS * (1.0 - hp))
  149. msg = f_big.render("KEEP HOLDING TO STOP — %.0fs" % (left + 0.99),
  150. True, (255, 255, 255))
  151. else:
  152. msg = f_big.render("FORWARDING — Deck controls detached · hold anywhere 5s to stop",
  153. True, (255, 255, 255))
  154. screen.blit(msg, (W // 2 - msg.get_width() // 2, bar.y + bar.height // 2 - 22))
  155. pygame.display.flip()
  156. def handle_down(pos):
  157. # Press handler. CONNECT (toggle a live tile) fires immediately -- it's cheap and reversible. The
  158. # destructive actions (STOP a forward, REMOVE a bond) instead ARM a hold; they only fire from
  159. # check_hold() once HOLD_SECS elapses, so an errant tap can't trigger them. Actions still only
  160. # ENQUEUE intents so they never race the IO thread's serial/libusb access.
  161. nonlocal hold
  162. if hold is not None:
  163. return # a hold is already in progress; ignore re-entrant/duplicate down events
  164. if app.forwarding:
  165. # hold anywhere on the screen to stop forwarding
  166. hold = {"kind": "stop", "slot": None, "start": time.monotonic()}
  167. return
  168. # the remove-bond ✕ takes priority over the tile body it sits on -- hold it to unpair
  169. for drect, slot in del_rects:
  170. if drect.collidepoint(pos):
  171. hold = {"kind": "unpair", "slot": slot, "start": time.monotonic()}
  172. return
  173. # live tile: connecting/forwarding stays a single tap
  174. for rect, slot, tappable in tile_rects:
  175. if rect.collidepoint(pos) and tappable:
  176. app.request_toggle(slot)
  177. return
  178. def handle_up():
  179. # Lifting (or a stray up) before HOLD_SECS cancels the pending destructive action.
  180. nonlocal hold
  181. hold = None
  182. def check_hold():
  183. # Fire the held action once it has been sustained long enough, then disarm. Also cancel a hold whose
  184. # target went away (the forward auto-released, or forwarding started so a bond can't be removed).
  185. nonlocal hold
  186. if hold is None:
  187. return
  188. if hold["kind"] == "stop" and not app.forwarding:
  189. hold = None
  190. return
  191. if hold["kind"] == "unpair" and app.forwarding:
  192. hold = None
  193. return
  194. if time.monotonic() - hold["start"] >= HOLD_SECS:
  195. if hold["kind"] == "stop":
  196. app.request_stop()
  197. elif hold["kind"] == "unpair":
  198. app.request_remove(hold["slot"])
  199. hold = None
  200. running = True
  201. while running:
  202. for ev in pygame.event.get():
  203. if ev.type == pygame.QUIT:
  204. running = False
  205. elif ev.type == pygame.KEYDOWN and ev.key in (pygame.K_ESCAPE, pygame.K_q):
  206. running = False
  207. elif ev.type == pygame.MOUSEBUTTONDOWN:
  208. handle_down(ev.pos)
  209. elif ev.type == pygame.FINGERDOWN:
  210. handle_down((int(ev.x * W), int(ev.y * H)))
  211. elif ev.type in (pygame.MOUSEBUTTONUP, pygame.FINGERUP):
  212. handle_up()
  213. check_hold() # promote a sustained hold into the actual stop/unpair intent
  214. # Render only -- serial I/O + input forwarding run on app._io_loop (a separate thread) so the
  215. # vsync'd flip() below can't throttle forwarding to 60Hz. A bad draw must never kill the app.
  216. try:
  217. draw()
  218. except Exception as ex:
  219. app._flog("UI draw error: %r" % ex)
  220. app.note = "recovered from error: %s" % ex
  221. clock.tick(60) # UI render rate; forwarding is decoupled on the IO thread now
  222. pygame.quit()