summaryrefslogtreecommitdiff
path: root/src/write-tty
blob: fbe62ea75e1dc714aa7273609b0ed6219d6b42c3 (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
#!/bin/bash
BASH_ARGV0=write-tty
echo -n "$0" >/proc/$BASHPID/comm

output_filter()
{
        tokenize | colorize | soft_cursor
}

chr()
{
        declare -i n="$*"
        printf "\\$(printf %o "$n")"
}

colorize()
{
        BASH_ARGV0=colorize
        echo -n "$0" >/proc/$BASHPID/comm
        while read -r
        do
                case "$REPLY" in
                        \\[0-7][0-7][0-7] ) ;;
                        * )
                                printf '%s\n' "$REPLY"
                                continue
                                ;;
                esac
                declare -i c=8#"${REPLY#?}"
                if (( c > 128 + 127 ))
                then
                        :
                elif (( c > 128 + 32 ))
                then
                        printf -v REPLY "M-$(chr c - 128)"
                elif (( c > 127 ))
                then
                        printf -v REPLY "M-^$(chr c - 128 + 64)"
                elif (( c < 32 ))
                then
                        printf -v REPLY "^$(chr c + 64)"
                fi
                printf $'\e[106m%s\e[m\n' "$REPLY"
        done
}

tokenize()
{
        BASH_ARGV0=tokenize
        echo -n "$0" >/proc/$BASHPID/comm
        while read -r -N1
        do
                if [[ "$REPLY" =~ [[:print:]] ]]
                then
                        # Output one printable character per line. It may be a
                        # multibyte unicode character.
                        printf '%s\n' "$REPLY"
                        continue
                else
                        # If it is a non-printable, then we output a
                        # multi-character line. In this case we colorize it
                        # later so that it won't be confused with multiple
                        # printable characters in the .
                        printf '\\%.3o\n' "'$REPLY"
                        continue
                fi
        done
}

soft_cursor()
{
        BASH_ARGV0=soft_cursor
        echo -n "$0" >/proc/$BASHPID/comm
        FMT=$'%s \b\e[%sm \e[m\b'
        REPLY=
        color=101
        while printf "$FMT" "$REPLY" "$color"
        do
                read -r || break
                let '++color <= 105' || color=101
        done
}

if [ -t 1 ]
then
        output_filter
else
        exec -a write-tty-raw socat - -
fi