codekingpro/portable-devtools
114k
1"""Terminal utilities."""2 3# Author: Steen Lumholt.4 5from termios import *6 7__all__ = ["cfmakeraw", "cfmakecbreak", "setraw", "setcbreak"]8 9# Indices for termios list.10IFLAG = 011OFLAG = 112CFLAG = 213LFLAG = 314ISPEED = 415OSPEED = 516CC = 617 18def cfmakeraw(mode):19 """Make termios mode raw."""20 # Clear all POSIX.1-2017 input mode flags.21 # See chapter 11 "General Terminal Interface"22 # of POSIX.1-2017 Base Definitions.23 mode[IFLAG] &= ~(IGNBRK | BRKINT | IGNPAR | PARMRK | INPCK | ISTRIP |24 INLCR | IGNCR | ICRNL | IXON | IXANY | IXOFF)25 26 # Do not post-process output.27 mode[OFLAG] &= ~OPOST28 29 # Disable parity generation and detection; clear character size mask;30 # let character size be 8 bits.31 mode[CFLAG] &= ~(PARENB | CSIZE)32 mode[CFLAG] |= CS833 34 # Clear all POSIX.1-2017 local mode flags.35 mode[LFLAG] &= ~(ECHO | ECHOE | ECHOK | ECHONL | ICANON |36 IEXTEN | ISIG | NOFLSH | TOSTOP)37 38 # POSIX.1-2017, 11.1.7 Non-Canonical Mode Input Processing,39 # Case B: MIN>0, TIME=040 # A pending read shall block until MIN (here 1) bytes are received,41 # or a signal is received.42 mode[CC] = list(mode[CC])43 mode[CC][VMIN] = 144 mode[CC][VTIME] = 045 46def cfmakecbreak(mode):47 """Make termios mode cbreak."""48 # Do not echo characters; disable canonical input.49 mode[LFLAG] &= ~(ECHO | ICANON)50 51 # POSIX.1-2017, 11.1.7 Non-Canonical Mode Input Processing,52 # Case B: MIN>0, TIME=053 # A pending read shall block until MIN (here 1) bytes are received,54 # or a signal is received.55 mode[CC] = list(mode[CC])56 mode[CC][VMIN] = 157 mode[CC][VTIME] = 058 59def setraw(fd, when=TCSAFLUSH):60 """Put terminal into raw mode."""61 mode = tcgetattr(fd)62 new = list(mode)63 cfmakeraw(new)64 tcsetattr(fd, when, new)65 return mode66 67def setcbreak(fd, when=TCSAFLUSH):68 """Put terminal into cbreak mode."""69 mode = tcgetattr(fd)70 new = list(mode)71 cfmakecbreak(new)72 tcsetattr(fd, when, new)73 return mode74 