from collections import namedtuple _AB = namedtuple("_AB", ["a", "b"]) class ABController: def __init__(self, enabled=True, callback=None): self._setPositionCallback = callback self._limits = dict() # dictionary of all songs self._songLimits = None # list of limits for selected song self._currentLimits = _AB(0.0, 0.0) # a/b positions of active limit self._loadedIndex = None self._enabled = enabled def _ensureSongExists(self, path): if path not in self._limits: self._limits[path] = list() def setCurrentSong(self, path): self._ensureSongExists(path) self._songLimits = self._limits[path] def storeLimits(self, aLimit, bLimit, song=None): if song is not None: self._ensureSongExists(song) songLimits = self._limits[song] else: songLimits = self._songLimits if songLimits is None: return ab = _AB(aLimit, bLimit) songLimits.append(ab) def loadLimits(self, index): if not self._songLimits: return if index >= 0 and index < len(self._songLimits): self._currentLimits = self._songLimits[index] self._loadedIndex = index def nextStoredAbLimits(self): if self._loadedIndex is None: nextIndex = 0 else: nextIndex = self._loadedIndex + 1 self.loadLimits(nextIndex) def previousStoredAbLimits(self): if self._loadedIndex is None: previousIndex = 0 else: previousIndex = self._loadedIndex - 1 self.loadLimits(previousIndex) def setLimits(self, aLimit, bLimit): self._currentLimits = _AB(aLimit, bLimit) self._loadedIndex = None def positionChanged(self, position): if position > self._currentLimits.b and self._setPositionCallback and self._enabled: self._setPositionCallback(self._currentLimits.a) def setEnable(self, enable): self._enabled = enable def getStoredLimits(self, song): return self._limits.get(song) def getCurrentLimits(self): return self._currentLimits def getLoadedIndex(self): return self._loadedIndex def clear(self): self.__init__(enabled=self._enabled, callback=self._setPositionCallback)