app.py 8.9 KB

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