Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1from . import OsError 

2 

3c"""source-before-namespace 

4#include <termios.h> 

5#include <unistd.h> 

6""" 

7 

8func set_to_raw_mode(fd: i64): 

9 """Set the mode of given file descriptor to raw. 

10 

11 """ 

12 

13 ok = False 

14 

15 c""" 

16 struct termios mode; 

17 

18 if (tcgetattr(fd, &mode) == 0) { 

19 mode.c_iflag &= ~(BRKINT | ICRNL | INPCK | ISTRIP | IXON); 

20 mode.c_oflag &= ~(OPOST); 

21 mode.c_cflag &= ~(CSIZE | PARENB); 

22 mode.c_cflag |= CS8; 

23 mode.c_lflag &= ~(ECHO | ICANON | IEXTEN | ISIG); 

24 mode.c_cc[VMIN] = 1; 

25 mode.c_cc[VTIME] = 0; 

26 

27 if (tcsetattr(fd, TCSAFLUSH, &mode) == 0) { 

28 ok = true; 

29 } 

30 } 

31 """ 

32 

33 if not ok: 

34 raise OsError(f"Failed to set fd {fd} to raw mode.") 

35 

36func set_to_cbreak_mode(fd: i64): 

37 """Set the mode of given file descriptor to cbreak. 

38 

39 """ 

40 

41 ok = False 

42 

43 c""" 

44 struct termios mode; 

45 

46 if (tcgetattr(fd, &mode) == 0) { 

47 mode.c_lflag &= ~(ECHO | ICANON); 

48 mode.c_cc[VMIN] = 1; 

49 mode.c_cc[VTIME] = 0; 

50 

51 if (tcsetattr(fd, TCSAFLUSH, &mode) == 0) { 

52 ok = true; 

53 } 

54 } 

55 """ 

56 

57 if not ok: 

58 raise OsError(f"Failed to set fd {fd} to cbreak mode.") 

59 

60func is_tty(fd: i64) -> bool: 

61 """Returns True if given file descriptor is a TTY, False otherwise. 

62 

63 """ 

64 

65 tty: bool = False 

66 

67 c""" 

68 tty = (isatty(fd) == 1); 

69 """ 

70 

71 return tty 

72 

73test set_to_raw_mode_bad_fd(): 

74 try: 

75 message = "" 

76 set_to_raw_mode(-1) 

77 except OsError as err: 

78 message = err.message 

79 

80 assert message == "Failed to set fd -1 to raw mode." 

81 

82test set_to_cbreak_mode_bad_fd(): 

83 try: 

84 message = "" 

85 set_to_cbreak_mode(-1) 

86 except OsError as err: 

87 message = err.message 

88 

89 assert message == "Failed to set fd -1 to cbreak mode." 

90 

91test is_tty(): 

92 assert not is_tty(-1)