Add Buffer class with basic drawing methods.
authorRadek Brich <radek.brich@devl.cz>
Wed, 12 Mar 2014 23:21:20 +0100
changeset 78 6031e99c8ad3
parent 77 fc1989059e19
child 79 dbdc38f9981a
Add Buffer class with basic drawing methods.
.hgignore
demos/demo_buffer.py
tuikit/core/__init__.py
tuikit/core/buffer.py
--- a/.hgignore	Sun Feb 03 16:38:41 2013 +0100
+++ b/.hgignore	Wed Mar 12 23:21:20 2014 +0100
@@ -10,5 +10,6 @@
 ^(.*/)?\.c?project$
 ^(.*/)?\.pydevproject$
 ^\.settings
+^\.idea/
 .*\.appstats
 __pycache__
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/demos/demo_buffer.py	Wed Mar 12 23:21:20 2014 +0100
@@ -0,0 +1,19 @@
+#!/usr/bin/env python3
+
+import sys
+sys.path.append('..')
+
+from tuikit.core.buffer import Buffer
+
+
+buf = Buffer(16, 8)
+buf.fill(c='#')
+buf.hline(1, 1, 14, c='-')
+buf.hline(1, 6, 14, c='-')
+buf.vline(7, 2, 4, c='|')
+buf.puts(8, 4, 'Hello!')
+
+for y in range(buf.size.h):
+    for x in range(buf.size.w):
+        print(buf.getch(x, y), end='')
+    print()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tuikit/core/buffer.py	Wed Mar 12 23:21:20 2014 +0100
@@ -0,0 +1,62 @@
+from tuikit.common import Size
+
+
+class Buffer:
+
+    """Rectangular character buffer.
+
+    Retains characters and colors drawn into it
+    until resized. Contents are reset when resized.
+
+    """
+
+    def __init__(self, w=0, h=0):
+        self._size = Size(w, h)
+        self._data = None
+        self.clear()
+        self._size.add_handler('change', self._on_resize)
+
+    @property
+    def size(self):
+        return self._size
+
+    def resize(self, w, h):
+        """Resize buffer."""
+        self._size.update(w, h)
+
+    def _on_resize(self):
+        """Reset contents of buffer when resized."""
+        self.clear()
+
+    def clear(self):
+        """Reset buffer data."""
+        self._data = [None] * self._size.w * self._size.h
+
+    def getch(self, x, y):
+        return self._data[y * self._size.w + x]
+
+    def putch(self, x, y, c):
+        """Set character on xy coords to c."""
+        self._data[y * self._size.w + x] = c
+
+    def puts(self, x, y, s):
+        """Output string of characters."""
+        for c in s:
+            self.putch(x, y, c)
+            x += 1
+
+    def hline(self, x, y, w, c=' '):
+        """Draw horizontal line."""
+        self.puts(x, y, [c] * w)
+
+    def vline(self, x, y, h, c=' '):
+        """Draw vertical line."""
+        for i in range(h):
+            self.putch(x, y + i, c)
+
+    def fill(self, x=0, y=0, w=0, h=0, c=' '):
+        """Fill rectangular area."""
+        w = self._size.w if not w else w
+        h = self._size.h if not h else h
+        for i in range(h):
+            self.hline(x, y + i, w, c)