Add attribute storage to Buffer.
authorRadek Brich <radek.brich@devl.cz>
Fri, 14 Mar 2014 08:44:15 +0100
changeset 79 dbdc38f9981a
parent 78 6031e99c8ad3
child 80 573a9e76719d
Add attribute storage to Buffer.
demos/demo_buffer.py
tuikit/core/buffer.py
--- a/demos/demo_buffer.py	Wed Mar 12 23:21:20 2014 +0100
+++ b/demos/demo_buffer.py	Fri Mar 14 08:44:15 2014 +0100
@@ -15,5 +15,5 @@
 
 for y in range(buf.size.h):
     for x in range(buf.size.w):
-        print(buf.getch(x, y), end='')
+        print(buf.get(x, y)[0], end='')
     print()
--- a/tuikit/core/buffer.py	Wed Mar 12 23:21:20 2014 +0100
+++ b/tuikit/core/buffer.py	Fri Mar 14 08:44:15 2014 +0100
@@ -1,6 +1,25 @@
 from tuikit.common import Size
 
 
+class Cell:
+
+    """Character buffer cell.
+
+    Cell contains one character and its attribute.
+
+    """
+
+    __slots__ = ('char', 'attr')
+
+    def __init__(self, char=' ', attr=0):
+        self.char = char
+        self.attr = attr
+
+    def set(self, char, attr):
+        self.char = char
+        self.attr = attr
+
+
 class Buffer:
 
     """Rectangular character buffer.
@@ -13,6 +32,9 @@
     def __init__(self, w=0, h=0):
         self._size = Size(w, h)
         self._data = None
+        self._attr_descs = ['default']
+        self._attr_map = {'default': 0}
+        self._current_attr = 0
         self.clear()
         self._size.add_handler('change', self._on_resize)
 
@@ -30,14 +52,20 @@
 
     def clear(self):
         """Reset buffer data."""
-        self._data = [None] * self._size.w * self._size.h
+        self._data = [Cell() for _i in range(self._size.w * self._size.h)]
+
+    def get(self, x, y):
+        """Get cell data at `x`, `y` coords.
+
+        Returns tuple (char, attr_desc).
 
-    def getch(self, x, y):
-        return self._data[y * self._size.w + x]
+        """
+        cell = self._data[y * self._size.w + x]
+        return cell.char, self._attr_descs[cell.attr]
 
-    def putch(self, x, y, c):
+    def putch(self, x, y, ch):
         """Set character on xy coords to c."""
-        self._data[y * self._size.w + x] = c
+        self._data[y * self._size.w + x].set(ch, self._current_attr)
 
     def puts(self, x, y, s):
         """Output string of characters."""
@@ -60,3 +88,14 @@
         h = self._size.h if not h else h
         for i in range(h):
             self.hline(x, y + i, w, c)
+
+    def setattr(self, attr_desc):
+        """Set attribute to be used for subsequent draw operations."""
+        if attr_desc in self._attr_map:
+            attr = self._attr_map[attr_desc]
+        else:
+            attr = len(self._attr_descs)
+            self._attr_descs.append(attr_desc)
+            self._attr_map[attr_desc] = attr
+        self._current_attr = attr
+