summaryrefslogtreecommitdiff
path: root/twopane.bash
blob: f3aff570fee49a090e545cdb6d3766d4f9b65d81 (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
#!/bin/bash
set -e
set -f
set -o pipefail
shopt -s lastpipe
PROGNAME=${0##*/}

BOT_SIZE=8
BOT_TITLE=input
BOT_CMD=start
TOP_CMD='PS1="$TOP_TITLE\$ " bash --noprofile --norc -i'
TOP_TITLE=output

TWOPANE=$(mktemp -d)
export TWOPANE TOP_CMD BOT_CMD TOP_TITLE BOT_TITLE BOT_SIZE
trap 'rm -r "$TWOPANE"' EXIT
STY=twopane.${TWOPANE##*/}

save_file()
{
        cat > "$TWOPANE"/"${1:?$PROGNAME: Error: filename cannot be empty string}"
}
save_screenrc()
{
        save_file screenrc"${1:+.$1}"
}

save_screenrc <<'.'
unbindall
escape \0\0
caption string '%t'
layout new
split
focus bottom
resize $BOT_SIZE
screen -ln -t "$BOT_TITLE" 0 bash --noprofile --rcfile "$TWOPANE"/bashrc -i

source "$TWOPANE"/screenrc.startpane
.

save_screenrc 'startpane' <<'.'
focus top
screen -ln -t "$TOP_TITLE" 1 sh -c "$TOP_CMD"
exec :!. socat -u UNIX-RECV:"$TWOPANE"/socket STDOUT
title 'output'
focus bottom
layout save 0
.

save_screenrc 'restart' <<.
layout new
split
focus bottom
resize $BOT_SIZE
select 0
title 'input'

source "$TWOPANE"/screenrc.startpane
.

TWOPANE_FUNCTION_EXPORTS='restart sendp sendc send start'
restart()
{
        screen -X source "$TWOPANE"/screenrc.restart
}
sendp()
{
        socat -u STDIN UNIX-SENDTO:"$TWOPANE"/socket
}
sendc()
{
        [ "${COPROC[1]}" ] || coproc sendp
        printf '%s' "$*" >&${COPROC[1]}
}
send()
{
        [ "${COPROC[1]}" ] || coproc sendp
        printf '%s' "$*"$'\n' >&${COPROC[1]}
}
start()
{
        [ "${COPROC[1]}" ] || coproc sendp
        while read -r -N1 </dev/tty
        do
                [ "${COPROC[1]}" ] || break
                printf '%s' "$REPLY"
        done >&${COPROC[1]}
}

save_file bashrc <<.
set -f
set -o pipefail
shopt -s lastpipe
trap 'COPROC=()' SIGPIPE
trap "screen -X quit" EXIT
$(declare -f $TWOPANE_FUNCTION_EXPORTS | sed 's/ COPROC / /')
export PS1="$BOT_TITLE\$ "
\$BOT_CMD
.

main()
{
        screen -c "$TWOPANE"/screenrc -m -S "$STY" -ln
}

main "$@"