summaryrefslogtreecommitdiff
path: root/keyboardpython/__init__.py
blob: 50410b143056e238ba90048e5ca252e2c01b16c1 (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
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
    if fd == 'default': fd = sys.stdin.fileno()
    global before_tty
    before_tty = termios.tcgetattr(fd)
    tty = termios.tcgetattr(fd)
    tty[3] = tty[3] & ~termios.ICANON & ~termios.ECHO
    tty[6][termios.VMIN] = 1
    tty[6][termios.VTIME] = 0
    termios.tcsetattr(fd, termios.TCSANOW, tty)

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_tty)

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

        - fd='default' will try and get this stdin.
        - buffersize is passed to os.read, 6 is 
        enough for alt+F12 for example.
    '''
    import os,sys
    if fd == 'default': fd = sys.stdin.fileno()
    c = os.read(fd,buffersize)
    return key.parse_code(c)

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)