filelist.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. #!./bin/python3
  2. import threading
  3. import time
  4. from handler import EVENT_LEFT
  5. from handler.listhandler import BaseListHandler
  6. from handler.lib.pymplb import MPlayer
  7. class FileListHandler(BaseListHandler):
  8. def __init__(self, config, display):
  9. super().__init__(config, display)
  10. self._mplayer = None
  11. self._mplayer_watcher = None
  12. self.is_playing = False
  13. self._last_event = time.time()
  14. def setPlaylistItem(self, item):
  15. '''
  16. Called with the selected item.
  17. '''
  18. super().setPlaylistItem(item)
  19. if self._mplayer is None:
  20. self._mplayer = MPlayer()
  21. self.setItems(self.getPlaylistItems(item))
  22. self._mplayer_watcher = threading.Thread(target=self._watch_mplayer, daemon=True)
  23. self._mplayer_watcher.start()
  24. self.is_playing = False
  25. def getPlaylistItems(self, item):
  26. raise NotImplementedError()
  27. def update(self, text=None, highlight=-1, title=None, img=None):
  28. '''
  29. Called when the handler should update the display.
  30. '''
  31. super().update(title=[
  32. "",
  33. "Playlist:",
  34. self.item["name"],
  35. "[play]" if self.is_playing else "[stop]"
  36. ], img=self.item.get("img"))
  37. def itemSelected(self, item):
  38. self._mplayer.loadfile(item["path"])
  39. self.is_playing = True
  40. def stop(self):
  41. '''
  42. Called when the handler should stop.
  43. '''
  44. if self._mplayer is not None:
  45. self._mplayer.quit()
  46. self._mplayer = None
  47. self._mplayer_watcher = None
  48. def emitEvent(self, event):
  49. '''
  50. Called when an event has happened.
  51. '''
  52. # Clock the time so the thread can hold off if there
  53. # was a recent user event
  54. self._last_event = time.time()
  55. if event == EVENT_LEFT and self.is_playing:
  56. self._mplayer.stop()
  57. self.is_playing = False
  58. return
  59. super().emitEvent(event)
  60. def _watch_mplayer(self):
  61. '''
  62. Thread to watch mplayer and advance the playlist.
  63. '''
  64. while self._mplayer_watcher is not None:
  65. try:
  66. time.sleep(0.5)
  67. if self._mplayer:
  68. playing_path = self._mplayer.p_path
  69. # Only do something in the thread if the last user
  70. # input is at least 3 seconds ago
  71. if time.time() - self._last_event > 3:
  72. # Advance to the next item if we are playing music
  73. if self.is_playing and playing_path == "(null)":
  74. self.nextItem()
  75. except Exception as e:
  76. print("Error watching player:", e)