import sets class Slot: def __init__(self, height, width, offset, buffer=None): self.height = height self.width = width self.offset = offset self.buffer = buffer self.resize(height, width, offset) def is_empty(self): return self.buffer is None def resize(self, height, width, offset): self.height = height self.width = width self.offset = offset # possible callbacks def remove(self): # possible callbacks pass class BufferList: def __init__(self, height, width, buffers=()): self.slots = [] self.add_slot(height, width, 0) self.buffers = sets.Set() self.buffer_names = {} self.hidden_buffers = [] for b in buffers: self.add_buffer(b) # manipulate slots def add_slot(self, height, width, offset=0, buffer=None): self.slots.append(Slot(height, width, offset, buffer)) return len(self.slots) - 1 def empty_slot(self, i): assert i > -1 and i < len(self.slots), "slot %d does not exist" % i return self.slots[i].is_empty() def set_slot(self, i, b): assert i > -1 and i < len(self.slots), "slot %d does not exist" % i assert b in self.buffers, "buffer %s does not exist" % (b.name()) if b in self.hidden_buffers: self.hidden_buffers.remove(b) if not self.slots[i].is_empty(): b2 = self.slots[i].buffer self.hidden_buffers.insert(0, b2) self.slots[i].buffer = b def remove_slot(self, i): assert i > -1 and i < len(self.slots), "slot %d does not exist" % i if not self.slots[i].is_empty(): b = self.slots[i].buffer self.hidden_buffers.insert(0, b) self.slots[i].remove() del self.slots[i] # now fix the stored slot numbers for all the for b in self.buffers: for j in range(i, len(self.slots)): if b.has_window(j+1): w = b.get_window(j+1) del b.windows[j+1] w.slot = j b.windows[j] = w # add/remove buffers def add_buffer(self, b): assert b not in self.buffers, "buffer %s already exists" % (b.name()) self.buffers.add(b) self.buffer_names[b.name()] = b self.hidden_buffers.append(b) for i in range(0, len(self.slots)): if self.empty_slot(i): self.set_slot(i, b) def has_buffer(self, b): return b in self.buffers def has_buffer_name(self, name): return name in self.buffer_names def get_buffer_by_name(self, name): return self.buffer_names[name] def get_buffer_by_path(self, path): for b in self.buffers: if hasattr(b, 'path') and b.path == path: return b return None def remove_buffer(self, b): assert b in self.buffers, "buffer %s does not exist" % (b.name()) for slot in self.slots: if slot.buffer is b: slot.buffer = None self.buffers.remove(b) del self.buffer_names[b.name()] if b in self.hidden_buffers: self.hidden_buffers.remove(b) # query buffers def is_buffer_hidden(self, b): assert b in self.buffers, "buffer %s does not exist" % (b.name()) return b in self.hidden_buffers def is_buffer_visible(self, b): assert b in self.buffers, "buffer %s does not exist" % (b.name()) for slot in self.slots: if slot.buffer is b: return True return False