Explorar el Código

Add a playlist screen on the List key

The whole MPD queue, one song per line as "N. artist - title [m:ss]",
with artist and/or title truncated to fit. It opens with the current song
selected and centered; up/down move the selection, OK plays it, and
Menu, Esc, List or 30 s without a key close it. While it is open the
queue is refetched on MPD's playlist idle event.

The selection is a gray bar (level 1 background, level 2 edges) when the
panel has more than 1 bpp, inverted otherwise; the DRM frontend reads the
driver's bpp parameter. The simulator now shows 1 bpp black as black.
k4be hace 2 semanas
padre
commit
9e6b12a554
Se han modificado 10 ficheros con 457 adiciones y 21 borrados
  1. 7 0
      README.md
  2. 4 2
      radio/__main__.py
  3. 69 4
      radio/app.py
  4. 8 0
      radio/drm.py
  5. 63 8
      radio/mpd.py
  6. 121 1
      radio/render.py
  7. 9 5
      radio/sim.py
  8. 14 0
      radio/state.py
  9. 24 0
      tests/fake_mpd.py
  10. 138 1
      tests/test_ui.py

+ 7 - 0
README.md

@@ -61,6 +61,13 @@ or through the DRM driver:
     ./radio-ui i2c --bus N --host radio.lo
     ./radio-ui drm --host radio.lo
 
+On the main screen the keys are prev/play/pause/stop/next, up/down for the
+volume and Esc to refresh. List opens the playlist: the whole MPD queue, the
+current song centered and selected. Up/down move the selection, OK plays it,
+and Menu, Esc, List or 30 s without a key go back. With more than 1 bpp the
+selection is a gray bar, otherwise inverted. The transport keys keep working
+there.
+
 `--bus` must name a known adapter; motherboard and display buses are always
 refused. Only use the bus number of the adapter the panel is wired to.
 `./radio-ui FRONTEND --help` lists all options.

+ 4 - 2
radio/__main__.py

@@ -240,7 +240,8 @@ def run_i2c(args):
             print("backlight: %s" % e, file=sys.stderr)
 
     loop = GLib.MainLoop()
-    app = App(args.host, args.port, args.width, args.height, present, backlight, args.kmsg)
+    app = App(args.host, args.port, args.width, args.height, present, backlight, args.kmsg,
+              grayscale=args.bpp > 1)
     _start_keys(args, app, loop, None if args.no_i2c_keys else fd)
     platform.run(loop)
     app.close()
@@ -292,7 +293,8 @@ def run_drm(args):
 
     loop = GLib.MainLoop()
     app = App(args.host, args.port, dev.width, dev.height, present,
-              lambda on: platform.backlight_set(blpath, on), args.kmsg)
+              lambda on: platform.backlight_set(blpath, on), args.kmsg,
+              grayscale=dev.bpp() > 1)
     _start_keys(args, app, loop, keys_fd)
     platform.run(loop)
     app.close()

+ 69 - 4
radio/app.py

@@ -13,6 +13,7 @@ from . import mpd, render
 from . import state as st
 
 BACKLIGHT_TIMEOUT_S = 30
+LIST_TIMEOUT_S = 30         # the playlist closes after this long without a key
 KEY_LOCKOUT_MS = 300        # as the firmware: 300 ms after a press
 LOG_REDRAW_MS = 1000        # scrolling is the costliest redraw
 
@@ -30,8 +31,11 @@ _KEY_COMMANDS = {
 
 
 class App(object):
-    def __init__(self, host, port, width, height, present, backlight=None, kmsg=False):
+    def __init__(self, host, port, width, height, present, backlight=None, kmsg=False,
+                 grayscale=True):
+        """grayscale: the panel shows more than black and white (bpp > 1)"""
         self.width, self.height = width, height
+        self.grayscale = grayscale
         self.present = present
         self.backlight = backlight
         self.state = st.RadioState(host)
@@ -43,6 +47,7 @@ class App(object):
         self.render_id = 0
         self.log_timer_id = 0
         self.backlight_id = 0
+        self.list_timer_id = 0
         self.key_time_ms = {}
 
         self.mpd = mpd.MpdClient(host, port, self.state, self._schedule_render, self.log)
@@ -52,7 +57,8 @@ class App(object):
         self._schedule_render()
 
     def close(self):
-        for attr in ("render_id", "log_timer_id", "backlight_id", "tick_id"):
+        for attr in ("render_id", "log_timer_id", "backlight_id", "tick_id",
+                     "list_timer_id"):
             if getattr(self, attr):
                 GLib.source_remove(getattr(self, attr))
                 setattr(self, attr, 0)
@@ -64,8 +70,9 @@ class App(object):
 
     def _render_now(self):
         self.render_id = 0
+        self._settle_selection()
         cr = cairo.Context(self.surface)
-        render.render(cr, self.state, self.width, self.height)
+        render.render(cr, self.state, self.width, self.height, self.grayscale)
         del cr
         self.surface.flush()
 
@@ -90,7 +97,7 @@ class App(object):
             self.render_id = GLib.idle_add(self._render_now)
 
     def _tick(self):
-        if self.state.state == st.PLAY_PLAYING:
+        if self.state.state == st.PLAY_PLAYING and not self.state.list_open:
             self._schedule_render()
         return True
 
@@ -131,10 +138,68 @@ class App(object):
             return
         self.key_time_ms[name] = now
         self._backlight_wake()
+        if self.state.list_open:
+            if self._list_key(name):
+                return
+        elif name == "list":
+            self._list_show(True)
+            return
         cmd = _KEY_COMMANDS.get(name)
         if cmd is not None:
             self.mpd.command(cmd)
 
+    # ---- playlist screen --------------------------------------------------------
+
+    def _list_show(self, on):
+        s = self.state
+        s.list_open = on
+        s.list_sel = -1
+        self.mpd.follow_playlist(on)
+        if self.list_timer_id:
+            GLib.source_remove(self.list_timer_id)
+            self.list_timer_id = 0
+        if on:
+            self.list_timer_id = GLib.timeout_add_seconds(LIST_TIMEOUT_S,
+                                                          self._list_expired)
+        self._schedule_render()
+
+    def _list_expired(self):
+        self.list_timer_id = 0
+        self._list_show(False)
+        return False
+
+    def _list_key(self, name):
+        """A key on the playlist screen; False passes it on to the player"""
+        s = self.state
+        if name in ("menu", "esc", "list"):
+            self._list_show(False)
+            return True
+        if self.list_timer_id:
+            GLib.source_remove(self.list_timer_id)
+        self.list_timer_id = GLib.timeout_add_seconds(LIST_TIMEOUT_S, self._list_expired)
+        if name in ("up", "down"):
+            if s.playlist and s.list_sel >= 0:
+                step = -1 if name == "up" else 1
+                s.list_sel = min(max(s.list_sel + step, 0), len(s.playlist) - 1)
+                self._schedule_render()
+            return True
+        if name == "ok":
+            if s.playlist and s.list_sel >= 0:
+                pos = s.list_sel
+                self._list_show(False)
+                self.mpd.command(mpd.PLAY_POS, pos)
+            return True
+        return False
+
+    def _settle_selection(self):
+        """Selection starts on the current song once the list is in"""
+        s = self.state
+        if not s.list_open or not s.playlist:
+            return
+        if s.list_sel < 0:
+            s.list_sel = s.song_pos if 0 <= s.song_pos < len(s.playlist) else 0
+        s.list_sel = min(s.list_sel, len(s.playlist) - 1)
+
 
 class KmsgFollower(object):
     """Kernel log pane source: follows /dev/kmsg from the moment it is opened"""

+ 8 - 0
radio/drm.py

@@ -185,6 +185,14 @@ class DrmPanel(object):
         except (OSError, ValueError):
             return None
 
+    def bpp(self):
+        """The driver's bits per pixel (its module parameter); 2 if unreadable"""
+        try:
+            with open("/sys/module/%s/parameters/bpp" % DRIVER_NAME.replace("-", "_")) as f:
+                return int(f.read())
+        except (OSError, ValueError):
+            return 2
+
     def present(self, data, stride, x, y, w, h):
         for row in range(y, y + h):
             src = row * stride + x * 4

+ 63 - 8
radio/mpd.py

@@ -20,7 +20,7 @@ RESPONSE_TIMEOUT_S = 30
 RECONNECT_S = 3
 IDLE_SUBSYSTEMS = "playlist player mixer options"
 
-PLAY, TOGGLE, STOP, NEXT, PREV, VOLUME_UP, VOLUME_DOWN, REFRESH = range(8)
+PLAY, TOGGLE, STOP, NEXT, PREV, VOLUME_UP, VOLUME_DOWN, REFRESH, PLAY_POS, PLAYLIST = range(10)
 
 _COMMANDS = {
     PLAY: "play",
@@ -47,6 +47,38 @@ def _ack_message(line):
     return line[brace + 2:] if brace >= 0 else line
 
 
+def _first_tags(pairs):
+    song = {}
+    for key, value in pairs:
+        song.setdefault(key.lower(), value)     # first value of each tag
+    return song
+
+
+def queue_entry(song):
+    duration = _float(song.get("duration"), -1.0)
+    if duration < 0:
+        duration = _float(song.get("time"), -1.0)
+    artist, title = song.get("artist"), song.get("title")
+    if not (artist and title):
+        artist = title = None
+    return st.QueueEntry(artist, title, format_title(song), int(duration))
+
+
+def parse_playlistinfo(pairs):
+    """Songs as QueueEntry; each starts at its "file" line"""
+    songs, cur = [], None
+    for key, value in pairs:
+        if key == "file":
+            if cur is not None:
+                songs.append(queue_entry(_first_tags(cur)))
+            cur = []
+        if cur is not None:
+            cur.append((key, value))
+    if cur is not None:
+        songs.append(queue_entry(_first_tags(cur)))
+    return songs
+
+
 def format_title(song):
     artist, title, name = song.get("artist"), song.get("title"), song.get("name")
     uri = song.get("file", "")
@@ -146,6 +178,7 @@ class MpdClient(object):
         self.pending = collections.deque()
         self.pairs = []
         self.idling = False     # "idle" sent and no "noidle" after it yet
+        self.want_playlist = False  # keep state.playlist current
         # not directly: the owner must finish construction first
         self.retry_id = GLib.idle_add(self._try_connect)
 
@@ -194,6 +227,8 @@ class MpdClient(object):
             self.conn.fileno(), GLib.PRIORITY_DEFAULT,
             GLib.IO_IN | GLib.IO_HUP | GLib.IO_ERR, self._on_readable)
         try:
+            if self.want_playlist:
+                self._send("playlistinfo", self._on_playlist)
             self._queue_refresh()
         except ConnectionLost as e:
             self._drop(str(e))
@@ -278,8 +313,19 @@ class MpdClient(object):
         self.idling = False
         # left for a command: the refresh queued after it covers any change
         if not self.pending:
+            changed = () if isinstance(result, ServerError) else [v for k, v in result]
+            if self.want_playlist and "playlist" in changed:
+                self._send("playlistinfo", self._on_playlist)
             self._queue_refresh()
 
+    def _on_playlist(self, result):
+        if isinstance(result, ServerError):
+            self.log("MPD: %s" % result)
+            return
+        if self.want_playlist:
+            self.state.playlist = parse_playlistinfo(result)
+            self.changed()
+
     def _on_status(self, result):
         if isinstance(result, ServerError):
             self.log("MPD: %s" % result)
@@ -312,26 +358,35 @@ class MpdClient(object):
         s.title = ""
         # as the firmware: a stopped player shows no title
         if not isinstance(result, ServerError) and s.state != st.PLAY_STOPPED:
-            song = {}
-            for key, value in result:
-                song.setdefault(key.lower(), value)     # first value of each tag
+            song = _first_tags(result)
             if song:
                 s.title = format_title(song)
         self.changed()
 
-    def command(self, cmd):
+    def command(self, cmd, arg=None):
+        """arg: the queue position for PLAY_POS"""
         if not self.conn:
             self.log("Brak połączenia z MPD")
             return
         try:
             self._leave_idle()
-            line = _COMMANDS.get(cmd)
-            if line:
-                self._send(line, self._on_command)
+            if cmd == PLAYLIST:
+                self._send("playlistinfo", self._on_playlist)
+            else:
+                line = "play %d" % arg if cmd == PLAY_POS else _COMMANDS.get(cmd)
+                if line:
+                    self._send(line, self._on_command)
             self._queue_refresh()
         except ConnectionLost as e:
             self._drop(str(e))
 
+    def follow_playlist(self, on):
+        """While on, state.playlist is fetched now and kept current"""
+        self.want_playlist = on
+        self.state.playlist = None
+        if on and self.conn:
+            self.command(PLAYLIST)
+
 
 def _int(text, default):
     try:

+ 121 - 1
radio/render.py

@@ -31,6 +31,19 @@ LOG_LINE_H = 10     # 9 px text: room for Polish accents
 
 TEXT_ANTIALIAS = cairo.ANTIALIAS_NONE
 
+# playlist screen: a row is the text plus a line above and below for the
+# selection marker
+FONT_LIST = FONT_SMALL
+LIST_ROW_H = 12
+LIST_TEXT_DY = 1
+LIST_SEP = " - "
+
+
+def gray(level):
+    """Source color for panel level 0 (background) .. 3 (black), at 2 bpp"""
+    v = 1 - level / 3.0
+    return v, v, v
+
 _fonts = {}
 
 
@@ -155,11 +168,118 @@ def _log(cr, s, w, h):
             _text(cr, FONT_LOG, 1, y - 1, w - 1, Pango.Alignment.LEFT, row)
 
 
-def render(cr, s, width, height):
+def list_rows(height):
+    return height // LIST_ROW_H
+
+
+def list_first(sel, count, rows):
+    """First row shown: the selection centered, without empty rows at the end"""
+    return max(0, min(sel - rows // 2, count - rows))
+
+
+def _measure(cr, text):
+    layout = _layout(cr, FONT_LIST)
+    layout.set_text(text, -1)
+    return layout.get_pixel_size()[0]
+
+
+def _fit(cr, text, w):
+    """text, or its longest prefix plus an ellipsis that fits in w pixels.
+    Not Pango's ellipsizing: that pads the line out to the full width, which
+    would leave a gap before whatever follows."""
+    if _measure(cr, text) <= w:
+        return text
+    lo, hi = 0, len(text)       # text[:lo] + "…" fits; text[:hi] + "…" does not
+    while hi - lo > 1:
+        mid = (lo + hi) // 2
+        if _measure(cr, text[:mid].rstrip() + "…") <= w:
+            lo = mid
+        else:
+            hi = mid
+    return text[:lo].rstrip() + "…"
+
+
+def _piece(cr, x, y, text):
+    """Draws text; returns its width"""
+    layout = _layout(cr, FONT_LIST)
+    layout.set_text(text, -1)
+    cr.move_to(x, y)
+    PangoCairo.show_layout(cr, layout)
+    return layout.get_pixel_size()[0]
+
+
+def split_width(avail, artist_w, title_w):
+    """Widths for artist and title sharing avail: the shorter one whole if it
+    fits in half, the other truncated; otherwise half each"""
+    if artist_w + title_w <= avail:
+        return artist_w, title_w
+    half = avail // 2
+    if artist_w <= half:
+        return artist_w, avail - artist_w
+    if title_w <= half:
+        return avail - title_w, title_w
+    return half, avail - half
+
+
+def _list_line(cr, pos, e, y, w):
+    """N. artist - title [m:ss], artist and/or title truncated to fit"""
+    x = 1
+    right = w - 1
+    prefix = "%d. " % (pos + 1)
+    suffix = " [%s]" % format_time(e.duration_s * 1000) if e.duration_s >= 0 else ""
+    avail = right - x - _measure(cr, prefix) - _measure(cr, suffix)
+    if e.artist is None:
+        text = _fit(cr, e.fallback, avail)
+    else:
+        sep_w = _measure(cr, LIST_SEP)
+        aw, tw = split_width(avail - sep_w, _measure(cr, e.artist), _measure(cr, e.title))
+        text = _fit(cr, e.artist, aw) + LIST_SEP + _fit(cr, e.title, tw)
+    _piece(cr, x, y, prefix + text + suffix)
+
+
+def _playlist(cr, s, w, h, grayscale):
+    if s.playlist is None or not s.playlist:
+        if not s.connected:
+            text = "Brak połączenia z %s" % s.server
+        elif s.playlist is None:
+            text = "Wczytywanie listy…"
+        else:
+            text = "Lista odtwarzania jest pusta"
+        _text(cr, FONT_LIST, 1, (h - LIST_ROW_H) // 2, w - 2, Pango.Alignment.CENTER, text)
+        return
+    rows = list_rows(h)
+    count = len(s.playlist)
+    sel = min(max(s.list_sel, 0), count - 1)
+    first = list_first(sel, count, rows)
+    top = (h - rows * LIST_ROW_H) // 2
+    for i in range(first, min(first + rows, count)):
+        y = top + (i - first) * LIST_ROW_H
+        if i == sel:
+            if grayscale:
+                cr.set_source_rgb(*gray(1))
+                cr.rectangle(0, y, w, LIST_ROW_H)
+                cr.fill()
+                cr.set_source_rgb(*gray(2))
+                cr.rectangle(0, y, w, 1)
+                cr.rectangle(0, y + LIST_ROW_H - 1, w, 1)
+                cr.fill()
+                cr.set_source_rgb(*gray(3))
+            else:
+                cr.rectangle(0, y, w, LIST_ROW_H)
+                cr.fill()
+                cr.set_source_rgb(1, 1, 1)
+        _list_line(cr, i, s.playlist[i], y + LIST_TEXT_DY, w)
+        cr.set_source_rgb(0, 0, 0)
+
+
+def render(cr, s, width, height, grayscale=True):
     cr.set_antialias(cairo.ANTIALIAS_NONE)
     cr.set_source_rgb(1, 1, 1)
     cr.paint()
     cr.set_source_rgb(0, 0, 0)
+    if s.list_open:
+        _playlist(cr, s, width, height, grayscale)
+        return
     if s.title:
         _title(cr, width - 2, s.title)
     _status(cr, s, width)

+ 9 - 5
radio/sim.py

@@ -17,9 +17,12 @@ LIT = ((0xc4, 0xd8, 0x90), (0x8c, 0xa0, 0x60), (0x50, 0x64, 0x38), (0x14, 0x20,
 DARK = ((0x4a, 0x52, 0x38), (0x36, 0x3e, 0x2a), (0x24, 0x2a, 0x1e), (0x10, 0x14, 0x10))
 
 
-def _channel_tables(palette):
-    """bytes.translate tables giving B, G, R of a level (only 2 bits are used)"""
-    return [bytes(palette[i & 3][c] for i in range(256)) for c in (2, 1, 0)]
+def _channel_tables(palette, bpp):
+    """bytes.translate tables giving B, G, R of a level, scaled from bpp to the
+    palette's four shades"""
+    top = (1 << bpp) - 1
+    return [bytes(palette[min(i, top) * 3 // top][c] for i in range(256))
+            for c in (2, 1, 0)]
 
 
 class SimWindow(object):
@@ -31,7 +34,8 @@ class SimWindow(object):
         self.lit = True
         self.total_bytes = 0
         self.frames = 0
-        self.tables = {True: _channel_tables(LIT), False: _channel_tables(DARK)}
+        self.tables = {True: _channel_tables(LIT, args.bpp),
+                       False: _channel_tables(DARK, args.bpp)}
         self.image = cairo.ImageSurface(cairo.FORMAT_RGB24, self.w, self.h)
         self.snapshot = args.snapshot
 
@@ -39,7 +43,7 @@ class SimWindow(object):
         self._update_image()
         self.window.show_all()
         self.app = App(args.host, args.port, self.w, self.h, self._present,
-                       self._backlight, args.kmsg)
+                       self._backlight, args.kmsg, grayscale=args.bpp > 1)
 
         if args.press:
             self.press = [k for k in args.press.split(",") if k]

+ 14 - 0
radio/state.py

@@ -16,6 +16,17 @@ def monotonic_ms():
     return int(time.monotonic() * 1000)
 
 
+class QueueEntry(object):
+    """One song of the MPD queue, as the playlist screen shows it"""
+    __slots__ = ("artist", "title", "fallback", "duration_s")
+
+    def __init__(self, artist, title, fallback, duration_s):
+        self.artist = artist        # both set, or the line shows the fallback
+        self.title = title
+        self.fallback = fallback    # the main screen's title text
+        self.duration_s = duration_s    # -1: unknown, e.g. a stream
+
+
 class RadioState(object):
     def __init__(self, server=""):
         self.connected = False
@@ -31,6 +42,9 @@ class RadioState(object):
         self.repeat = False
         self.random = False
         self.log = [""] * LOG_ROWS  # wrapped rows, oldest first
+        self.playlist = None        # list of QueueEntry; None: not fetched
+        self.list_open = False      # the playlist screen is shown
+        self.list_sel = -1          # selected queue position; -1: not yet set
 
     def current_elapsed_ms(self):
         """Position, advanced locally between MPD updates while playing"""

+ 24 - 0
tests/fake_mpd.py

@@ -21,6 +21,26 @@ class Player:
 
 player = Player()
 
+# the queue: playlistlength in status matches it
+QUEUE = [
+    ("Artysta %d" % i, "Utwór numer %d" % i, 180 + i * 7) for i in range(10)
+]
+QUEUE[3] = ("Bardzo, bardzo długa nazwa wykonawcy", "Również bardzo długi tytuł utworu", 193)
+QUEUE[4] = ("Krótki", "Tytuł tak długi, że sam zajmie całą linię wyświetlacza", 402)
+QUEUE[5] = (None, None, None)   # a stream
+
+
+def playlistinfo():
+    out = ""
+    for i, (artist, title, duration) in enumerate(QUEUE):
+        if artist is None:
+            out += "file: http://radio.example/stream\nName: Radio Testowe\n"
+        else:
+            out += "file: muzyka/%d.flac\nArtist: %s\nTitle: %s\n" % (i, artist, title)
+            out += "Time: %d\nduration: %d.000\n" % (duration, duration)
+        out += "Pos: %d\nId: %d\n" % (i, i + 1)
+    return out + "OK\n"
+
 
 def record(line):
     with open(log_path, "a") as f:
@@ -87,8 +107,12 @@ class Handler(socketserver.StreamRequestHandler):
             elif cmd == "stop":
                 player.state = "stop"
                 self.send("OK\n")
+            elif cmd == "playlistinfo":
+                self.send(playlistinfo())
             elif cmd == "play":
                 player.state = "play"
+                if " " in line:
+                    player.song = int(line.split(" ")[1].strip('"'))
                 self.send("OK\n")
             elif cmd == "pause":
                 player.state = "pause" if player.state == "play" else "play"

+ 138 - 1
tests/test_ui.py

@@ -17,7 +17,7 @@ sys.path.insert(0, os.path.join(HERE, ".."))
 
 from gi.repository import GLib  # noqa: E402
 
-from radio import keypad, mpd, platform  # noqa: E402
+from radio import keypad, mpd, platform, render  # noqa: E402
 from radio import state as st  # noqa: E402
 from radio.__main__ import make_pattern, parse_args  # noqa: E402
 from radio.app import App  # noqa: E402
@@ -300,6 +300,143 @@ class TestPlatform(unittest.TestCase):
         self.assertTrue(parse_args(["keytest", "--bus", "1", "--init-only"]).init_only)
 
 
+class TestPlaylist(unittest.TestCase):
+    def test_parse_playlistinfo(self):
+        pairs = [("file", "a.flac"), ("Artist", "A"), ("Artist", "B"), ("Title", "T"),
+                 ("Time", "214"), ("duration", "213.627"), ("Pos", "0"),
+                 ("file", "http://x/stream"), ("Name", "Radio"), ("Pos", "1"),
+                 ("file", "dir/c.mp3"), ("Title", "Only title"), ("Pos", "2")]
+        a, b, c = mpd.parse_playlistinfo(pairs)
+        self.assertEqual((a.artist, a.title, a.duration_s), ("A", "T", 213))
+        self.assertEqual((b.artist, b.fallback, b.duration_s), (None, "Radio", -1))
+        self.assertEqual((c.artist, c.fallback), (None, "Only title"))
+        self.assertEqual(mpd.parse_playlistinfo([]), [])
+
+    def test_split_width(self):
+        self.assertEqual(render.split_width(100, 30, 40), (30, 40))     # fits
+        self.assertEqual(render.split_width(100, 30, 90), (30, 70))     # title cut
+        self.assertEqual(render.split_width(100, 90, 30), (70, 30))     # artist cut
+        self.assertEqual(render.split_width(100, 80, 90), (50, 50))     # both
+
+    def test_fit(self):
+        cr = render.cairo.Context(render.cairo.ImageSurface(render.cairo.FORMAT_RGB24, 1, 1))
+        self.assertEqual(render._fit(cr, "Krótki", 200), "Krótki")
+        text = render._fit(cr, "Bardzo, bardzo długa nazwa wykonawcy", 80)
+        self.assertTrue(text.endswith("…") and not text.endswith(" …"))
+        self.assertLessEqual(render._measure(cr, text), 80)
+        self.assertGreater(render._measure(cr, text), 70)
+        self.assertEqual(render._fit(cr, "Długie", 1), "…")
+
+    def test_selection_centered(self):
+        self.assertEqual(render.list_first(0, 100, 13), 0)
+        self.assertEqual(render.list_first(50, 100, 13), 44)
+        self.assertEqual(render.list_first(99, 100, 13), 87)
+        self.assertEqual(render.list_first(3, 5, 13), 0)
+
+
+class TestPlaylistScreen(unittest.TestCase):
+    def setUp(self):
+        self.server = FakeMpd()
+        self.frames = 0
+
+        def present(*a):
+            self.frames += 1
+        self.app = App("127.0.0.1", self.server.port, 240, 160, present)
+        self.state = self.app.state
+        self.assertTrue(run_loop_until(lambda: self.state.connected and self.app.mpd.idling))
+
+    def tearDown(self):
+        self.app.close()
+        self.server.stop()
+
+    def press(self, name):
+        self.app.key_time_ms.clear()    # no lockout between test presses
+        self.app.key(name)
+
+    def rendered(self):
+        n = self.frames
+        return run_loop_until(lambda: self.frames > n and not self.app.render_id, 1)
+
+    def test_open_select_play(self):
+        self.press("list")
+        self.assertTrue(run_loop_until(lambda: self.state.playlist is not None))
+        self.assertEqual(len(self.state.playlist), 10)
+        self.rendered()
+        self.assertTrue(self.state.list_open)
+        self.assertEqual(self.state.list_sel, 2)        # the current song
+        self.press("down")
+        self.press("down")
+        self.press("up")
+        self.assertEqual(self.state.list_sel, 3)
+        self.press("ok")
+        self.assertFalse(self.state.list_open)
+        self.assertTrue(run_loop_until(lambda: "play 3" in self.server.commands()))
+        self.assertTrue(run_loop_until(lambda: self.state.song_pos == 3))
+        self.assertNotIn("volume +1", self.server.commands())
+
+    def test_closing(self):
+        for key in ("menu", "esc", "list"):
+            self.press("list")
+            self.assertTrue(self.state.list_open)
+            self.press(key)
+            self.assertFalse(self.state.list_open)
+            self.assertIsNone(self.state.playlist)
+        self.press("list")
+        self.app._list_expired()
+        self.assertFalse(self.state.list_open)
+        self.assertFalse(self.app.list_timer_id)
+        self.assertNotIn("refresh", self.server.commands())
+
+    def test_selection_clamped(self):
+        self.press("list")
+        self.assertTrue(run_loop_until(lambda: self.state.playlist is not None))
+        self.rendered()
+        for _ in range(12):
+            self.press("down")
+        self.assertEqual(self.state.list_sel, 9)
+        for _ in range(12):
+            self.press("up")
+        self.assertEqual(self.state.list_sel, 0)
+
+
+@unittest.skipUnless(have_panel_lib(), "needs `make lib`")
+class TestPlaylistRender(unittest.TestCase):
+    def levels(self, bpp, grayscale):
+        s = st.RadioState("x")
+        s.connected = True
+        s.list_open = True
+        s.playlist = mpd.parse_playlistinfo(
+            [("file", "f%d" % i) for i in range(30)])
+        s.list_sel = 20
+        panel = Panel(bpp=bpp)
+        panel.init()
+        surface = render.cairo.ImageSurface(render.cairo.FORMAT_RGB24, 240, 160)
+        render.render(render.cairo.Context(surface), s, 240, 160, grayscale)
+        surface.flush()
+        panel.update(surface.get_data(), surface.get_stride(), 0, 0, 240, 160)
+        self.assertEqual(panel.sim_faults(), 0)
+        return panel.sim_render()[1]
+
+    def test_gray_marker(self):
+        levels = self.levels(2, True)
+        rows = render.list_rows(160)
+        top = (160 - rows * render.LIST_ROW_H) // 2
+        y = top + (rows // 2) * render.LIST_ROW_H      # 20 is centered
+        self.assertEqual(levels[y * 240 + 239], 2)
+        self.assertEqual(levels[(y + render.LIST_ROW_H - 1) * 240 + 239], 2)
+        self.assertEqual(levels[(y + 1) * 240 + 239], 1)
+        self.assertEqual(levels[(y - 1) * 240 + 239], 0)
+        self.assertIn(3, levels[(y + 1) * 240:(y + render.LIST_ROW_H - 1) * 240])
+
+    def test_inverted_without_gray(self):
+        levels = self.levels(1, False)
+        self.assertTrue(set(levels) <= {0, 1})
+        rows = render.list_rows(160)
+        top = (160 - rows * render.LIST_ROW_H) // 2
+        y = top + (rows // 2) * render.LIST_ROW_H
+        self.assertEqual(levels[(y + 1) * 240 + 239], 1)
+
+
 def _raw(*keys):
     """Input port reading with these keys held: every other pin reads low"""
     raw = 0