tuikit/scrollbar.py
changeset 0 a35731b5e31a
child 3 33ec838dc021
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/tuikit/scrollbar.py	Wed Feb 16 23:51:30 2011 +0100
@@ -0,0 +1,107 @@
+# -*- coding: utf-8 -*-
+
+from .widget import Widget
+
+
+class VScrollbar(Widget):
+    def __init__(self, height=10):
+        Widget.__init__(self, 1, height)
+
+        self.max = height - 3
+        self.pos = 0
+        self.thumbpos = 0
+
+        self.interval = 0.1
+
+        self.dragging = False
+        self.move = None
+
+        self.connect('draw', self.on_draw)
+        self.connect('mousedown', self.on_mousedown)
+        self.connect('mouseup', self.on_mouseup)
+        self.connect('mousemove', self.on_mousemove)
+
+        self.newevent('change')
+
+
+    def setpos(self, pos):
+        self.pos = pos
+        self.thumbpos = int(round(self.pos / self.max * (self.height - 3)))
+
+
+    def on_draw(self, screen, x, y):
+        screen.putch(x, y, screen.UP_ARROW)
+        for i in range(y + 1, y + self.height - 1):
+            screen.putch(x, i, screen.LIGHT_SHADE)
+        screen.putch(x, y + 1 + self.thumbpos, screen.BLOCK)
+        screen.putch(x, y + self.height - 1, screen.DOWN_ARROW)
+
+
+    def on_mousedown(self, ev):
+        self.dragging = False
+        self.move = None
+        # arrow buttons
+        if ev.wy == 0 or ev.wy == self.height - 1:
+            if ev.wy == 0:
+                self.move_up()
+            else:
+                self.move_down()
+            self.top.add_timeout(self.interval * 2, self.on_timeout)
+            return
+        # thumb bar
+        if ev.wy == 1 + self.thumbpos:
+            self.dragging = True
+            return
+
+
+    def on_mouseup(self, ev):
+        if self.dragging:
+            self.drag(ev.wy)
+            self.dragging = False
+            return
+        if self.move:
+            self.top.remove_timeout(self.on_timeout)
+            self.move = None
+            return
+
+
+    def on_mousemove(self, ev):
+        if self.dragging:
+            self.drag(ev.wy)
+
+
+    def on_timeout(self):
+        if self.move == 'up':
+            self.move_up()
+        if self.move == 'down':
+            self.move_down()
+        self.top.add_timeout(self.interval, self.on_timeout)
+
+
+    def move_up(self):
+        if self.pos > 0:
+            self.setpos(self.pos - 1)
+        self.move = 'up'
+        self.redraw()
+        self.handle('change')
+
+
+    def move_down(self):
+        if self.pos < self.max:
+            self.setpos(self.pos + 1)
+        self.move = 'down'
+        self.redraw()
+        self.handle('change')
+
+
+    def drag(self, wy):
+        newpos = int(round((wy - 1) / (self.height - 3) * self.max))
+        if newpos < 0:
+            newpos = 0
+        if newpos > self.max:
+            newpos = self.max
+        if self.pos != newpos:
+            self.setpos(newpos)
+            self.redraw()
+            self.handle('change')
+