1
0

playlist_model.py 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. from PySide6.QtCore import QAbstractListModel, Qt, Slot, Signal
  2. from PySide6.QtQml import QmlElement
  3. from pathlib import Path
  4. import json
  5. QML_IMPORT_NAME = "DuneWeaver"
  6. QML_IMPORT_MAJOR_VERSION = 1
  7. @QmlElement
  8. class PlaylistModel(QAbstractListModel):
  9. """Model for playlist list with direct JSON file access"""
  10. NameRole = Qt.UserRole + 1
  11. ItemCountRole = Qt.UserRole + 2
  12. def __init__(self):
  13. super().__init__()
  14. self._playlists = []
  15. # Look for playlists in the parent directory (main dune-weaver folder)
  16. self.playlists_file = Path("../playlists.json")
  17. self.refresh()
  18. def roleNames(self):
  19. return {
  20. self.NameRole: b"name",
  21. self.ItemCountRole: b"itemCount"
  22. }
  23. def rowCount(self, parent=None):
  24. return len(self._playlists)
  25. def data(self, index, role):
  26. if not index.isValid() or index.row() >= len(self._playlists):
  27. return None
  28. playlist = self._playlists[index.row()]
  29. if role == self.NameRole:
  30. return playlist["name"]
  31. elif role == self.ItemCountRole:
  32. return playlist["itemCount"]
  33. return None
  34. @Slot()
  35. def refresh(self):
  36. self.beginResetModel()
  37. playlists = []
  38. if self.playlists_file.exists():
  39. try:
  40. with open(self.playlists_file, 'r') as f:
  41. self._playlist_data = json.load(f)
  42. for name, playlist_patterns in self._playlist_data.items():
  43. # playlist_patterns is a list of pattern filenames
  44. playlists.append({
  45. "name": name,
  46. "itemCount": len(playlist_patterns) if isinstance(playlist_patterns, list) else 0
  47. })
  48. except (json.JSONDecodeError, KeyError, AttributeError):
  49. self._playlist_data = {}
  50. else:
  51. self._playlist_data = {}
  52. self._playlists = sorted(playlists, key=lambda x: x["name"])
  53. self.endResetModel()
  54. @Slot(str, result=list)
  55. def getPatternsForPlaylist(self, playlistName):
  56. """Get the list of patterns for a given playlist"""
  57. if hasattr(self, '_playlist_data') and playlistName in self._playlist_data:
  58. patterns = self._playlist_data[playlistName]
  59. if isinstance(patterns, list):
  60. # Clean up pattern names for display
  61. cleaned_patterns = []
  62. for pattern in patterns:
  63. # Remove path and .thr extension for display
  64. clean_name = pattern
  65. if '/' in clean_name:
  66. clean_name = clean_name.split('/')[-1]
  67. if clean_name.endswith('.thr'):
  68. clean_name = clean_name[:-4]
  69. cleaned_patterns.append(clean_name)
  70. return cleaned_patterns
  71. return []