menu.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #!./bin/python3
  2. import os
  3. import yaml
  4. import pygame # type: ignore
  5. from typing import Dict
  6. import random
  7. import tempfile
  8. import handler
  9. from handler import stream, m3u, dir
  10. class Menu:
  11. '''
  12. Control object which holds the menu state.
  13. '''
  14. def __init__(self, config, display):
  15. self._display = display # Display object
  16. self._current_item = None # Current item with display control
  17. # Register default handlers
  18. self.handler = {
  19. "stream" : stream.StreamHandler(config, display),
  20. "m3u" : m3u.M3UHandler(config, display),
  21. "dir" : dir.DirectoryHandler(config, display)
  22. }
  23. # Playlist data
  24. playlistsFile = config.get("playlists", "music.yml")
  25. self.playlists = yaml.safe_load(open(playlistsFile)).get("playlist", [])
  26. self.playlists_pointer = 0
  27. self.update()
  28. def update(self):
  29. # Delegate to the current item if there is one
  30. if self._current_item is not None:
  31. self._current_item.update()
  32. return
  33. # Show the slice of the main menu which is relevant
  34. playlist_display = []
  35. maxlines = self._display.drawlines
  36. for i, item in enumerate(self.playlists):
  37. if len(playlist_display) <= maxlines:
  38. if i >= self.playlists_pointer - maxlines and i <= self.playlists_pointer + maxlines:
  39. playlist_display.append(item.get("name", "<unknown>"))
  40. else:
  41. break
  42. playlist_pointer = self.playlists_pointer
  43. self._display.update(playlist_display, min(playlist_pointer, maxlines))
  44. def emitEvent(self, event):
  45. # Delegate to the current item if there is one
  46. if self._current_item is not None:
  47. try:
  48. self._current_item.emitEvent(event)
  49. except handler.HandlerExit as e:
  50. self._current_item = None
  51. self.update()
  52. return
  53. if event == handler.EVENT_RIGHT:
  54. self.selectPlaylistItem(self.playlists[self.playlists_pointer])
  55. if event == handler.EVENT_UP:
  56. self.playlists_pointer -=1
  57. if event == handler.EVENT_DOWN:
  58. self.playlists_pointer +=1
  59. if self.playlists_pointer >= len(self.playlists):
  60. self.playlists_pointer = 0
  61. if self.playlists_pointer < 0:
  62. self.playlists_pointer = len(self.playlists) - 1
  63. self.update()
  64. def selectPlaylistItem(self, item):
  65. handler = self.handler.get(item["type"])
  66. print("Selecting:", item)
  67. if handler is not None:
  68. handler.setPlaylistItem(item)
  69. self._current_item = handler