app.py 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. """Radio UI core: everything that is the same in the window and on the panel.
  2. A frontend supplies present(data, stride, x, y, w, h), which gets the whole
  3. XRGB8888 frame and the rectangle that changed, and optionally backlight(on).
  4. """
  5. import errno
  6. import os
  7. import cairo
  8. from gi.repository import GLib
  9. from . import mpd, render
  10. from . import state as st
  11. BACKLIGHT_TIMEOUT_S = 30
  12. LIST_TIMEOUT_S = 30 # the playlist closes after this long without a key
  13. KEY_LOCKOUT_MS = 300 # as the firmware: 300 ms after a press
  14. LOG_REDRAW_MS = 1000 # scrolling is the costliest redraw
  15. _KEY_COMMANDS = {
  16. "prev": mpd.PREV,
  17. "play": mpd.PLAY,
  18. "pause": mpd.TOGGLE,
  19. "stop": mpd.STOP,
  20. "next": mpd.NEXT,
  21. "esc": mpd.REFRESH,
  22. "up": mpd.VOLUME_UP,
  23. "down": mpd.VOLUME_DOWN,
  24. # menu, list, ok, left, right: not assigned yet
  25. }
  26. class App(object):
  27. def __init__(self, host, port, width, height, present, backlight=None, kmsg=False,
  28. grayscale=True):
  29. """grayscale: the panel shows more than black and white (bpp > 1)"""
  30. self.width, self.height = width, height
  31. self.grayscale = grayscale
  32. self.present = present
  33. self.backlight = backlight
  34. self.state = st.RadioState(host)
  35. self.surface = cairo.ImageSurface(cairo.FORMAT_RGB24, width, height)
  36. self.stride = self.surface.get_stride()
  37. self.prev = None
  38. self.render_id = 0
  39. self.log_timer_id = 0
  40. self.backlight_id = 0
  41. self.list_timer_id = 0
  42. self.key_time_ms = {}
  43. self.mpd = mpd.MpdClient(host, port, self.state, self._schedule_render, self.log)
  44. self.kmsg = KmsgFollower(self.log) if kmsg else None
  45. self.tick_id = GLib.timeout_add_seconds(1, self._tick)
  46. self._backlight_wake()
  47. self._schedule_render()
  48. def close(self):
  49. for attr in ("render_id", "log_timer_id", "backlight_id", "tick_id",
  50. "list_timer_id"):
  51. if getattr(self, attr):
  52. GLib.source_remove(getattr(self, attr))
  53. setattr(self, attr, 0)
  54. if self.kmsg:
  55. self.kmsg.close()
  56. self.mpd.close()
  57. # ---- rendering ------------------------------------------------------------
  58. def _render_now(self):
  59. self.render_id = 0
  60. self._settle_selection()
  61. cr = cairo.Context(self.surface)
  62. render.render(cr, self.state, self.width, self.height, self.grayscale)
  63. del cr
  64. self.surface.flush()
  65. data = self.surface.get_data()
  66. frame = bytes(data)
  67. stride, y0, y1 = self.stride, None, 0
  68. for y in range(self.height):
  69. a = y * stride
  70. if self.prev is not None and frame[a:a + stride] == self.prev[a:a + stride]:
  71. continue
  72. if y0 is None:
  73. y0 = y
  74. y1 = y + 1
  75. self.prev = frame
  76. # whole rows: the panel core finds the changed bytes itself
  77. if y0 is not None:
  78. self.present(data, stride, 0, y0, self.width, y1 - y0)
  79. return False
  80. def _schedule_render(self):
  81. if not self.render_id:
  82. self.render_id = GLib.idle_add(self._render_now)
  83. def _tick(self):
  84. if self.state.state == st.PLAY_PLAYING and not self.state.list_open:
  85. self._schedule_render()
  86. return True
  87. # ---- log ------------------------------------------------------------------
  88. def log(self, text):
  89. self.state.log_append(text)
  90. if not self.log_timer_id:
  91. self.log_timer_id = GLib.timeout_add(LOG_REDRAW_MS, self._log_timer)
  92. def _log_timer(self):
  93. self.log_timer_id = 0
  94. self._schedule_render()
  95. return False
  96. # ---- keys and backlight -----------------------------------------------------
  97. def _backlight_expired(self):
  98. self.backlight_id = 0
  99. if self.backlight:
  100. self.backlight(False)
  101. return False
  102. def _backlight_wake(self):
  103. if self.backlight:
  104. self.backlight(True)
  105. if self.backlight_id:
  106. GLib.source_remove(self.backlight_id)
  107. self.backlight_id = GLib.timeout_add_seconds(BACKLIGHT_TIMEOUT_S,
  108. self._backlight_expired)
  109. def key(self, name):
  110. if name not in st.KEYS:
  111. return
  112. now = st.monotonic_ms()
  113. last = self.key_time_ms.get(name)
  114. if last is not None and now - last < KEY_LOCKOUT_MS:
  115. return
  116. self.key_time_ms[name] = now
  117. self._backlight_wake()
  118. if self.state.list_open:
  119. if self._list_key(name):
  120. return
  121. elif name == "list":
  122. self._list_show(True)
  123. return
  124. cmd = _KEY_COMMANDS.get(name)
  125. if cmd is not None:
  126. self.mpd.command(cmd)
  127. # ---- playlist screen --------------------------------------------------------
  128. def _list_show(self, on):
  129. s = self.state
  130. s.list_open = on
  131. s.list_sel = -1
  132. self.mpd.follow_playlist(on)
  133. if self.list_timer_id:
  134. GLib.source_remove(self.list_timer_id)
  135. self.list_timer_id = 0
  136. if on:
  137. self.list_timer_id = GLib.timeout_add_seconds(LIST_TIMEOUT_S,
  138. self._list_expired)
  139. self._schedule_render()
  140. def _list_expired(self):
  141. self.list_timer_id = 0
  142. self._list_show(False)
  143. return False
  144. def _list_key(self, name):
  145. """A key on the playlist screen; False passes it on to the player"""
  146. s = self.state
  147. if name in ("menu", "esc", "list"):
  148. self._list_show(False)
  149. return True
  150. if self.list_timer_id:
  151. GLib.source_remove(self.list_timer_id)
  152. self.list_timer_id = GLib.timeout_add_seconds(LIST_TIMEOUT_S, self._list_expired)
  153. if name in ("up", "down"):
  154. if s.playlist and s.list_sel >= 0:
  155. step = -1 if name == "up" else 1
  156. s.list_sel = min(max(s.list_sel + step, 0), len(s.playlist) - 1)
  157. self._schedule_render()
  158. return True
  159. if name == "ok":
  160. if s.playlist and s.list_sel >= 0:
  161. pos = s.list_sel
  162. self._list_show(False)
  163. self.mpd.command(mpd.PLAY_POS, pos)
  164. return True
  165. return False
  166. def _settle_selection(self):
  167. """Selection starts on the current song once the list is in"""
  168. s = self.state
  169. if not s.list_open or not s.playlist:
  170. return
  171. if s.list_sel < 0:
  172. s.list_sel = s.song_pos if 0 <= s.song_pos < len(s.playlist) else 0
  173. s.list_sel = min(s.list_sel, len(s.playlist) - 1)
  174. class KmsgFollower(object):
  175. """Kernel log pane source: follows /dev/kmsg from the moment it is opened"""
  176. def __init__(self, log):
  177. self.log = log
  178. self.watch_id = 0
  179. try:
  180. self.fd = os.open("/dev/kmsg", os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
  181. except OSError:
  182. self.fd = -1
  183. log("Nie można otworzyć /dev/kmsg")
  184. return
  185. os.lseek(self.fd, 0, os.SEEK_END)
  186. self.watch_id = GLib.io_add_watch(self.fd, GLib.PRIORITY_DEFAULT,
  187. GLib.IO_IN, self._on_readable)
  188. def _on_readable(self, fd, cond):
  189. while True:
  190. try:
  191. rec = os.read(self.fd, 4096)
  192. except OSError as e:
  193. if e.errno == errno.EPIPE:
  194. continue # records were overwritten; carry on
  195. if e.errno == errno.EAGAIN:
  196. return True
  197. break
  198. if not rec:
  199. break
  200. # "prio,seq,usec,flags;message\n" then optional " KEY=value" lines
  201. head, sep, text = rec.decode("utf-8", "replace").partition(";")
  202. if sep:
  203. self.log(text.split("\n", 1)[0])
  204. self.watch_id = 0
  205. return False
  206. def close(self):
  207. if self.watch_id:
  208. GLib.source_remove(self.watch_id)
  209. if self.fd >= 0:
  210. os.close(self.fd)