app.py 8.3 KB

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