state.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. """What the screen shows, shared by the MPD client, the log and the renderer."""
  2. import time
  3. LOG_ROWS = 7
  4. LOG_COLS = 44
  5. PLAY_UNKNOWN, PLAY_PLAYING, PLAY_PAUSED, PLAY_STOPPED = range(4)
  6. # Key identifiers, as the C version's enum radio_key; the names are what
  7. # --press and the help text use.
  8. KEYS = ("esc", "next", "stop", "menu", "list", "up", "prev",
  9. "right", "down", "pause", "ok", "left", "play")
  10. def monotonic_ms():
  11. return int(time.monotonic() * 1000)
  12. class RadioState(object):
  13. def __init__(self, server=""):
  14. self.connected = False
  15. self.server = server
  16. self.state = PLAY_UNKNOWN
  17. self.title = ""
  18. self.song_pos = -1 # -1: none
  19. self.queue_len = 0
  20. self.elapsed_ms = 0
  21. self.elapsed_stamp_ms = 0 # monotonic time elapsed_ms was read
  22. self.total_ms = 0 # 0: unknown, e.g. a stream
  23. self.volume = -1 # -1: unknown
  24. self.repeat = False
  25. self.random = False
  26. self.log = [""] * LOG_ROWS # wrapped rows, oldest first
  27. def current_elapsed_ms(self):
  28. """Position, advanced locally between MPD updates while playing"""
  29. ms = self.elapsed_ms
  30. # with the link down the player's position is unknown, so hold it
  31. if not self.connected or self.state != PLAY_PLAYING or not self.elapsed_stamp_ms:
  32. return ms
  33. ms += monotonic_ms() - self.elapsed_stamp_ms
  34. return min(ms, self.total_ms) if self.total_ms else ms
  35. def log_append(self, text):
  36. """Wrap text into rows of LOG_COLS characters and scroll them in"""
  37. text = text.replace("\n", " ").replace("\t", " ")
  38. while True:
  39. row, text = text[:LOG_COLS], text[LOG_COLS:]
  40. self.log = self.log[1:] + [row]
  41. if not text:
  42. break