summaryrefslogtreecommitdiff
path: root/keyboardpython/__init__.py
blob: 7034b14685815e697c321ddc8d0151ee1fff47fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
from key import *

def set_to_read_key(fd='default'):
    ''' Set tty so that os.read gets one keypress at a time '''
    import sys,termios
    # VMIN min bytes read before returning from os.read()
    VMIN = 0
    # VTIME tenths of a second elapses between bytes read
    VTIME = 1
    if fd == 'default': fd = sys.stdin.fileno()
    global before_t
    before_t = termios.tcgetattr(fd)
    t = termios.tcgetattr(fd)
    # turn echo and needing to press enter off
    t[3] = t[3] & ~termios.ICANON & ~termios.ECHO
    cc = t[-1]
    cc[termios.VMIN] = VMIN
    cc[termios.VTIME] = VTIME
    termios.tcsetattr(fd, termios.TCSANOW, t)

def reset_tty(fd='default'):
    ''' set tty to how it was before set_to_read_key '''
    import sys,termios
    if fd == 'default': fd = sys.stdin.fileno()
    termios.tcsetattr(fd, termios.TCSANOW, before_t)

def getkey(fd='default',timeout=40,buffersize=6):
    ''' Read keypress and return Key object.

        - fd='default' will try and get this stdin.
        - timeout in miliseconds
        - buffersize is passed to os.read, 6 is 
        enough for alt+F12 for example.
    '''
    import os,sys,time
    if fd == 'default': fd = sys.stdin.fileno()
    to_return = str()
    timeout = float(timeout) / 1000
    c = os.read(fd,buffersize)
    endtime = time.time() + timeout
    while c and time.time() < endtime:
        to_return += c
        c = os.read(fd,buffersize)
    if to_return:
        return key.parse_code(to_return)
    else: return None

def queue_keypresses(q,signal,fd='default',buffersize=6):
    ''' Read keypress and put in Queue q while signal
        is True, deals with setup and teardown.

        - fd='default' will try and get this stdin.
        - buffersize is passed to os.read, 6 is 
        enough for alt+F12 for example.
    '''
    import Queue
    assert isinstance(q,Queue.Queue), "expected a Queue"
    if signal: set_to_read_key(fd)
    while signal:
        if not q.full(): q.put(getkey(fd,buffersize))
    reset_tty(fd)