aboutsummaryrefslogtreecommitdiffstats
path: root/src/termios_wrapper.c
blob: 02f084bfc911df2f4f070a9d06088dfa822e4b1f (plain) (blame)
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
#include <stdlib.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>

/* very simplistic, ignores a lot of the settings that i don't understand,
 * patches welcome */

int cooked()
{
    struct termios t;

    if (tcgetattr(0, &t) == -1) {
        return errno;
    }

    t.c_lflag |= (ICANON | ISIG | IEXTEN);
    t.c_iflag |= (IXON | BRKINT);

    return tcsetattr(0, TCSANOW, &t) == 0 ? 0 : errno;
}

int cbreak()
{
    struct termios t;

    if (tcgetattr(0, &t) == -1) {
        return errno;
    }

    t.c_lflag |= ISIG;
    t.c_lflag &= ~(ICANON | IEXTEN);
    t.c_iflag |= (IXON | BRKINT);

    return tcsetattr(0, TCSANOW, &t) == 0 ? 0 : errno;
}

int raw()
{
    struct termios t;

    if (tcgetattr(0, &t) == -1) {
        return errno;
    }

    t.c_lflag &= ~(ICANON | ISIG | IEXTEN);
    t.c_iflag &= ~(IXON | BRKINT);

    return tcsetattr(0, TCSANOW, &t) == 0 ? 0 : errno;
}

int echo(int enabled)
{
    struct termios t;

    if (tcgetattr(0, &t) == -1) {
        return errno;
    }

    if (enabled) {
        t.c_lflag |= ECHO;
    }
    else {
        t.c_lflag &= ~ECHO;
    }

    return tcsetattr(0, TCSANOW, &t) == 0 ? 0 : errno;
}

struct termios *get()
{
    struct termios *t;

    t = malloc(sizeof(struct termios));
    if (tcgetattr(0, t) == -1) {
        return NULL;
    }

    return t;
}

void set(struct termios *t)
{
    if (t == NULL) {
        return;
    }

    tcsetattr(0, TCSANOW, t);
    free(t);
}

void size(unsigned int *cols, unsigned int *rows)
{
    struct winsize ws;
    ioctl(0, TIOCGWINSZ, &ws);
    *cols = ws.ws_col;
    *rows = ws.ws_row;
}