tty_windows.go

 1//go:build windows
 2// +build windows
 3
 4package tea
 5
 6import (
 7	"fmt"
 8	"os"
 9
10	"github.com/charmbracelet/x/term"
11	"golang.org/x/sys/windows"
12)
13
14func (p *Program) initInput() (err error) {
15	// Save stdin state and enable VT input
16	// We also need to enable VT
17	// input here.
18	if f, ok := p.input.(term.File); ok && term.IsTerminal(f.Fd()) {
19		p.ttyInput = f
20		p.previousTtyInputState, err = term.MakeRaw(p.ttyInput.Fd())
21		if err != nil {
22			return fmt.Errorf("error making terminal raw: %w", err)
23		}
24
25		// Enable VT input
26		var mode uint32
27		if err := windows.GetConsoleMode(windows.Handle(p.ttyInput.Fd()), &mode); err != nil {
28			return fmt.Errorf("error getting console mode: %w", err)
29		}
30
31		if err := windows.SetConsoleMode(windows.Handle(p.ttyInput.Fd()), mode|windows.ENABLE_VIRTUAL_TERMINAL_INPUT); err != nil {
32			return fmt.Errorf("error setting console mode: %w", err)
33		}
34	}
35
36	// Save output screen buffer state and enable VT processing.
37	if f, ok := p.output.(term.File); ok && term.IsTerminal(f.Fd()) {
38		p.ttyOutput = f
39		p.previousOutputState, err = term.GetState(f.Fd())
40		if err != nil {
41			return fmt.Errorf("error getting terminal state: %w", err)
42		}
43
44		var mode uint32
45		if err := windows.GetConsoleMode(windows.Handle(p.ttyOutput.Fd()), &mode); err != nil {
46			return fmt.Errorf("error getting console mode: %w", err)
47		}
48
49		if err := windows.SetConsoleMode(windows.Handle(p.ttyOutput.Fd()),
50			mode|windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING|
51				windows.DISABLE_NEWLINE_AUTO_RETURN); err != nil {
52			return fmt.Errorf("error setting console mode: %w", err)
53		}
54
55		//nolint:godox
56		// TODO: check if we can optimize cursor movements on Windows.
57		p.checkOptimizedMovements(p.previousOutputState)
58	}
59
60	return //nolint:nakedret
61}
62
63// Open the Windows equivalent of a TTY.
64func openInputTTY() (*os.File, error) {
65	f, err := os.OpenFile("CONIN$", os.O_RDWR, 0o644) //nolint:mnd,gosec
66	if err != nil {
67		return nil, fmt.Errorf("error opening CONIN$: %w", err)
68	}
69	return f, nil
70}
71
72const suspendSupported = false
73
74func suspendProcess() {}