File: tty.go

package info (click to toggle)
termshark 2.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 1,800 kB
  • sloc: sh: 98; makefile: 9
file content (91 lines) | stat: -rw-r--r-- 1,676 bytes parent folder | download
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
// Copyright 2019-2021 Graham Clark. All rights reserved.  Use of this source
// code is governed by the MIT license that can be found in the LICENSE
// file.
//
// +build !windows

package tty

import (
	"os"

	"github.com/pkg/term/termios"
	"golang.org/x/sys/unix"
)

//======================================================================

type TerminalSignals struct {
	tiosp unix.Termios
	out   *os.File
	set   bool
}

func (t *TerminalSignals) IsSet() bool {
	return t.set
}

func (t *TerminalSignals) Restore() {
	if t.out != nil {
		fd := uintptr(t.out.Fd())
		termios.Tcsetattr(fd, termios.TCSANOW, &t.tiosp)

		t.out.Close()
		t.out = nil
	}
	t.set = false
}

func (t *TerminalSignals) Set() error {
	var e error
	var newtios unix.Termios
	var fd uintptr

	outtty := "/dev/tty"

	gwtty := os.Getenv("GOWID_TTY")
	if gwtty != "" {
		outtty = gwtty
	}

	if t.out, e = os.OpenFile(outtty, os.O_WRONLY, 0); e != nil {
		goto failed
	}

	fd = uintptr(t.out.Fd())

	if e = termios.Tcgetattr(fd, &t.tiosp); e != nil {
		goto failed
	}

	newtios = t.tiosp
	newtios.Lflag |= unix.ISIG

	// Enable ctrl-z for suspending the foreground process group via the
	// line discipline. Ctrl-c and Ctrl-\ are not handled, so the terminal
	// app will receive these keypresses.
	newtios.Cc[unix.VSUSP] = 032
	newtios.Cc[unix.VINTR] = 0
	newtios.Cc[unix.VQUIT] = 0

	if e = termios.Tcsetattr(fd, termios.TCSANOW, &newtios); e != nil {
		goto failed
	}

	t.set = true

	return nil

failed:
	if t.out != nil {
		t.out.Close()
		t.out = nil
	}
	return e
}

//======================================================================
// Local Variables:
// mode: Go
// fill-column: 78
// End: