def __init__(self, filename): self.filename = filename self.treedict = TreeDict() try: self.treedict.load(filename) except IOError: self.treedict.cues = [] self.cues = self.treedict.cues self.current_cue_index = -1 self.next_pointer = 0 self.prev_pointer = None import atexit atexit.register(self.save)
class CueList: """Persistent list of Cues""" def __init__(self, filename): self.filename = filename self.treedict = TreeDict() try: self.treedict.load(filename) except IOError: self.treedict.cues = [] self.cues = self.treedict.cues self.current_cue_index = -1 self.next_pointer = 0 self.prev_pointer = None import atexit atexit.register(self.save) def add_cue(self, cue, index=None): """Adds a Cue object to the list. If no index is specified, the cue will be added to the end.""" index = index or len(self.cues) self.cues.insert(index, cue) def shift(self, diff): """Shift through cue history""" old_index = self.current_cue_index self.current_cue_index = None if diff < 0: # if going backwards if self.prev_pointer: # use a prev pointer if we have one self.current_cue_index = self.prev_pointer self.next_pointer = old_index self.prev_pointer = None else: if self.next_pointer: # use a next pointer if we have one self.current_cue_index = self.next_pointer self.next_pointer = None self.prev_pointer = old_index if not self.current_cue_index: self.current_cue_index = old_index + diff def set_next(self, index): self.next_pointer = index def set_prev(self, index): self.prev_pointer = index def bound_index(self, index): if not self.cues or index < 0: return None else: return min(index, len(self.cues) - 1) def get_current_cue_indices(self): """Returns a list of the indices of three cues: the previous cue, the current cue, and the next cue.""" cur = self.current_cue_index return [self.bound_index(index) for index in (self.prev_pointer or cur - 1, cur, self.next_pointer or cur + 1)] def get_current_cues(self): """Returns a list of three cues: the previous cue, the current cue, and the next cue.""" return [self.get_cue_by_index(index) for index in self.get_current_cue_indices()] def get_cue_by_index(self, index): try: return self.cues[self.bound_index(index)] except TypeError: return empty_cue def __del__(self): self.save() def save(self, backup=0): if backup: backupfilename = "%s-backup" % self.filename print time.asctime(), "Saving backup version of cues to", \ backupfilename self.treedict.save(backupfilename) else: print time.asctime(), "Saving cues to", self.filename self.treedict.save(self.filename) def reload(self): # TODO: we probably will need to make sure that indices still make # sense, etc. self.treedict.load(self.filename)