v2 / vlib / term / termios / termios_dragonfly.c.v
97 lines · 81 sloc · 2.31 KB · a87a4d73b9ab25cfff0822f4e94cf2a2d9e64323
Raw
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4//
5// Serves as more advanced input method
6// based on the work of https://github.com/AmokHuginnsson/replxx
7//
8module termios
9
10#include <termios.h>
11#include <sys/ioctl.h>
12
13// https://gitweb.dragonflybsd.org/dragonfly.git/blob_plain/HEAD:/sys/sys/_termios.h
14
15const cclen = 20
16
17type TcFlag = int
18type Speed = int
19type Cc = u8
20
21// Termios stores the terminal options
22pub struct C.termios {
23mut:
24 c_iflag TcFlag
25 c_oflag TcFlag
26 c_cflag TcFlag
27 c_lflag TcFlag
28 c_cc [cclen]Cc
29 c_ispeed Speed
30 c_ospeed Speed
31}
32
33fn C.tcgetattr(fd i32, termios_p &C.termios) i32
34
35fn C.tcsetattr(fd i32, optional_actions i32, const_termios_p &C.termios) i32
36
37fn C.ioctl(fd i32, request u64, args ...voidptr) i32
38
39// flag provides a termios flag of the correct size
40// for the underlying C.termios structure
41@[inline]
42pub fn flag(value int) TcFlag {
43 return int(value)
44}
45
46// invert is a platform dependant way to bitwise NOT (~) TcFlag
47// as its length varies across platforms
48@[inline]
49pub fn invert(value TcFlag) TcFlag {
50 return ~int(value)
51}
52
53pub struct Termios {
54pub mut:
55 c_iflag TcFlag
56 c_oflag TcFlag
57 c_cflag TcFlag
58 c_lflag TcFlag
59 c_cc [cclen]Cc
60 c_ispeed Speed
61 c_ospeed Speed
62}
63
64// tcgetattr is an unsafe wrapper around C.termios and keeps its semantic
65@[inline]
66pub fn tcgetattr(fd int, mut termios_p Termios) int {
67 unsafe {
68 return C.tcgetattr(fd, &C.termios(termios_p))
69 }
70}
71
72// tcsetattr is an unsafe wrapper around C.termios and keeps its semantic
73@[inline]
74pub fn tcsetattr(fd int, optional_actions int, mut termios_p Termios) int {
75 unsafe {
76 return C.tcsetattr(fd, optional_actions, &C.termios(termios_p))
77 }
78}
79
80// ioctl is an unsafe wrapper around C.ioctl and keeps its semantic.
81@[inline]
82pub fn ioctl(fd int, request u64, arg voidptr) int {
83 unsafe {
84 return C.ioctl(fd, request, arg)
85 }
86}
87
88// set_state applies the flags in the `new_state` to the descriptor `fd`.
89pub fn set_state(fd int, new_state Termios) int {
90 mut x := new_state
91 return tcsetattr(0, C.TCSANOW, mut x)
92}
93
94// disable_echo disables echoing characters as they are typed, when that Termios state is later set with termios.set_state(fd,t).
95pub fn (mut t Termios) disable_echo() {
96 t.c_lflag &= invert(C.ECHO)
97}
98