aboutsummaryrefslogtreecommitdiff
path: root/TUI/unix.jai
blob: 2c3412279634d5bdf3cff928ec338b4ea0d9d9cd (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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#scope_file

#import "Atomics";
#import "POSIX";
#import "System";

    // Required to do unlocking input.
    libc :: #system_library "libc";


    // int poll(struct pollfd *fds, nfds_t nfds, int timeout);
    pollfd :: struct  {
        fd      : s32;      // File descriptor.
        events  : s16;      // Requested events.
        revents : s16;      // Returned events.
    };
    
    poll :: (fds: *pollfd, nfds: u32, timeout: s32) -> s32 #foreign libc;

    // TODO Remote this.
    cfmakeraw :: (termios: *Terminal_IO_Mode) -> void #foreign libc;
    /* https://elixir.bootlin.com/glibc/glibc-2.28/source/termios/cfmakeraw.c#L22
        void
        cfmakeraw (struct termios *t)
        {
          t->c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
          t->c_oflag &= ~OPOST;
          t->c_lflag &= ~(ECHO|ECHONL|ICANON|ISIG|IEXTEN);
          t->c_cflag &= ~(CSIZE|PARENB);
          t->c_cflag |= CS8;
          t->c_cc[VMIN] = 1;		// read returns when one char is available.
          t->c_cc[VTIME] = 0;
        }
    */

    // https://codebrowser.dev/glibc/glibc/sysdeps/unix/sysv/linux/tcsetattr.c.html
    tcsetattr :: (fd: s32, optional_actions: s32, termios_p : *Terminal_IO_Mode) -> s32 #foreign libc;

    // https://codebrowser.dev/glibc/glibc/sysdeps/unix/sysv/linux/tcgetattr.c.html
    tcgetattr :: (fd: s32, termios_p: *Terminal_IO_Mode) -> s32 #foreign libc;

    // https://codebrowser.dev/glibc/glibc/sysdeps/unix/sysv/linux/tcflush.c.html
    tcflush :: (fd: s32, queue_selector: s32) -> s32 #foreign libc;

    // Information for the termios.h enums is platform dependent and  was retrieved from:
    // https://elixir.bootlin.com/glibc/latest/source/sysdeps/unix/sysv/linux/bits/termios.h

    // Set Attributes Actions.
    SetAttributesActions :: enum u32 {
        TCSANOW         :: 0;           // Change immediately.
        TCSADRAIN       :: 1;           // Change when pending output is written.
        TCSAFLUSH       :: 2;           // Flush pending input before changing.
    }
    
    // Input modes.
    Input_Modes :: enum_flags u32 {
        IGNBRK          :: 0000001;     // Ignore break condition.
        BRKINT          :: 0000002;     // Signal interrupt on break.
        IGNPAR          :: 0000004;     // Ignore characters with parity errors.
        PARMRK          :: 0000010;     // Mark parity and framing errors.
        INPCK           :: 0000020;     // Enable input parity check.
        ISTRIP          :: 0000040;     // Strip 8th bit off characters.
        INLCR           :: 0000100;     // Map NL to CR on input.
        IGNCR           :: 0000200;     // Ignore CR.
        ICRNL           :: 0000400;     // Map CR to NL on input.
        IUCLC           :: 0001000;     // Translate upper case input to lower case (not in POSIX).
        IXON            :: 0002000;     // Enable start/stop output control.
        IXANY           :: 0004000;     // Any character will restart after stop.
        IXOFF           :: 0010000;     // Enable start/stop input control.
        IMAXBEL         :: 0020000;     // Ring bell when input queue is full (not in POSIX).
        IUTF8           :: 0040000;     // Input is UTF8 (not in POSIX).
    }
    
    // Output modes.
    Output_Modes :: enum_flags u32 {
        OPOST           :: 0000001;     // Perform output processing.
        OLCUC           :: 0000002;     // Map lowercase characters to uppercase on output (not in POSIX).
        ONLCR           :: 0000004;     // Map NL to CR-NL on output.
        OCRNL           :: 0000010;     // Map CR to NL.
        ONOCR           :: 0000020;     // Discard CR's when on column 0.
        ONLRET          :: 0000040;     // Move to column 0 on NL.
        OFILL           :: 0000100;     // Send fill characters for delays.
        OFDEL           :: 0000200;     // Fill is DEL.
        VTDLY           :: 0040000;     // Select vertical-tab delays:
        VT0             :: 0000000;     //  Vertical-tab delay type 0.
        VT1             :: 0040000;     //  Vertical-tab delay type 1.
    }
    
    // Control modes.
    Control_Modes :: enum u32 {
        CS5             :: 0000000;     // 5 bits per byte.
        CS6             :: 0000020;     // 6 bits per byte.
        CS7             :: 0000040;     // 7 bits per byte.
        CS8             :: 0000060;     // 8 bits per byte.
        CSIZE           :: 0000060;     // Number of bits per byte (mask).
        CSTOPB          :: 0000100;     // Two stop bits instead of one.
        CREAD           :: 0000200;     // Enable receiver.
        PARENB          :: 0000400;     // Parity enable.
        PARODD          :: 0001000;     // Odd parity instead of even.
        HUPCL           :: 0002000;     // Hang up on last close.
        CLOCAL          :: 0004000;
    }
    
    // Local modes.
    Local_Modes :: enum_flags u32 {
        ISIG            :: 0000001;     // Enable signals.
        ICANON          :: 0000002;     // Do erase and kill processing.
        ECHO            :: 0000010;     // Enable echo.
        ECHOE           :: 0000020;     // Visual erase for ERASE.
        ECHOK           :: 0000040;     // Echo NL after KILL.
        ECHONL          :: 0000100;     // Echo NL even if ECHO is off.
        NOFLSH          :: 0000200;     // Disable flush after interrupt.
        TOSTOP          :: 0000400;     // Send SIGTTOU for background output.
        IEXTEN          :: 0100000;     // Enable DISCARD and LNEXT.
    }

    // Control Characters
    Control_Chars :: enum u8 {
        VINTR           :: 0;
        VQUIT           :: 1;
        VERASE          :: 2;
        VKILL           :: 3;
        VEOF            :: 4;
        VTIME           :: 5;           // Time-out value (tenths of a second) [!ICANON].
        VMIN            :: 6;           // Minimum number of bytes read at once [!ICANON].
        VSWTC           :: 7;
        VSTART          :: 8;
        VSTOP           :: 9;
        VSUSP           :: 10;
        VEOL            :: 11;
        VREPRINT        :: 12;
        VDISCARD        :: 13;
        VWERASE         :: 14;
        VLNEXT          :: 15;
        VEOL2           :: 16;
    }

    // The struct termios.
    Terminal_IO_Mode :: struct {
        c_iflag     : Input_Modes;      // Input mode flags.
        c_oflag     : Output_Modes;     // Output mode flags.
        c_cflag     : Control_Modes;    // Control modes flags.
        c_lflag     : Local_Modes;      // Local modes flags.
        c_line      : u8;               // Line discipline.
        c_cc        : [32]Control_Chars;// Control characters.
        c_ispeed    : u32;              // Input speed (baud rates).
        c_ospeed    : u32;              // Output speed (baud rates).
    }
    
    initial_tio_mode: Terminal_IO_Mode;
    raw_tio_mode: Terminal_IO_Mode;

////////////////////////////////////////////////////////////////////////////////
// Resize detection
was_resized     : bool;

resize_handler :: (signal_code : s32) #c_call {
    new_context : Context;
	push_context new_context {
	    print("SIGNAL:%", signal_code);
	    if signal_code != SIGWINCH  then return;
	    atomic_swap(*was_resized, true);
    }
}

prepare_resize_handler :: () {
	sa : sigaction_t;
	sa.sa_handler = resize_handler;
	sigemptyset(*(sa.sa_mask));
	sa.sa_flags = SA_RESTART;
	sigaction(SIGWINCH, *sa, null);
}

restore_resize_handler :: () {
	sa : sigaction_t;
	sa.sa_handler = SIG_DFL;
	sigaction(SIGWINCH, null, *sa);
}

////////////////////////////////////////////////////////////////////////////////

#scope_export

OS_flush_input :: inline () {
    TCIFLUSH    :: 0; // TODO Is this always zero in all systems?
    tcflush(STDIN_FILENO, TCIFLUSH);
}

OS_prepare_terminal :: () {
    tcgetattr(STDIN_FILENO, *initial_tio_mode); // TODO Log on error.
    raw_tio_mode = initial_tio_mode;
    raw_tio_mode.c_iflag &= ~(.IGNBRK | .BRKINT | .PARMRK | .ISTRIP | .INLCR | .IGNCR | .ICRNL | .IXON);
    raw_tio_mode.c_oflag &= ~(.OPOST);
    raw_tio_mode.c_lflag &= ~(.ECHO | .ECHONL | .ICANON | .ISIG | .IEXTEN);
    raw_tio_mode.c_cflag &= ~(.CSIZE | .PARENB);
    raw_tio_mode.c_cflag |= .CS8;
    raw_tio_mode.c_cc[Control_Chars.VMIN] = 1;
    raw_tio_mode.c_cc[Control_Chars.VTIME] = 0;
    tcsetattr(STDIN_FILENO, 0, *raw_tio_mode); // TODO Log on error.

    was_resized = false;
    prepare_resize_handler();
}

OS_reset_terminal :: () {
    restore_resize_handler();
    tcsetattr(STDIN_FILENO, 0, *initial_tio_mode); // TODO Log on error.
}

OS_read_input :: (buffer: *u8, bytes_to_read: s64) -> bytes_read: s64, error: bool = false, error_message: string = "" {
    bytes_read := read(STDIN_FILENO, buffer, xx bytes_to_read);
    if bytes_read < 0 {
        error_code, error_message := get_error_value_and_string();
        return -1, true, error_message;
    }
    return bytes_read;
}

OS_wait_for_input :: (timeout_milliseconds: s32) -> is_input_available: bool {
    fds     := pollfd.[ .{ fd = STDIN_FILENO, events = POLLIN, revents = 0 } ];
    nfds    := fds.count;
    poll_return := poll(fds.data, xx nfds, xx timeout_milliseconds); // TODO Wait for input using poll syscall. This breaks and throws '-1 | 4 | Interrupted system call' when we resize the window while polling.
    error_code, error_message := get_error_value_and_string(); // FIXME Not used.
    return ifx poll_return > 0 then true else false;
}

// TODO This procedure hides the behaviour of reseting on read.
// We should have the `was_resized` on module.jai so that we know it may be used in another thread.
OS_was_terminal_resized :: () -> bool {
    return atomic_swap(*was_resized, false); // TODO If the windows implementation is similar, we may push this into the main module file.
}