// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

//go:build darwin || dragonfly || freebsd || (linux && !appengine) || netbsd || openbsd
// +build darwin dragonfly freebsd linux,!appengine netbsd openbsd

package term

import (
	
)

// State contains the state of a terminal.
type State struct {
	termios unix.Termios
}

// IsTerminal returns true if the given file descriptor is a terminal.
func ( int) bool {
	,  := unix.IoctlGetTermios(, ioctlReadTermios)

	return  == nil
}

// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func ( int) (*State, error) {
	,  := unix.IoctlGetTermios(, ioctlReadTermios)
	if  != nil {
		return nil, 
	}

	 := State{termios: *}

	// This attempts to replicate the behaviour documented for cfmakeraw in
	// the termios(3) manpage.
	.Iflag &^= unix.IGNBRK | unix.BRKINT | unix.PARMRK | unix.ISTRIP | unix.INLCR | unix.IGNCR | unix.ICRNL | unix.IXON

	.Lflag &^= unix.ECHO | unix.ECHONL | unix.ICANON | unix.ISIG | unix.IEXTEN
	.Cflag &^= unix.CSIZE | unix.PARENB
	.Cflag |= unix.CS8
	.Cc[unix.VMIN] = 1
	.Cc[unix.VTIME] = 0

	if  := unix.IoctlSetTermios(, ioctlWriteTermios, );  != nil {
		return nil, 
	}

	return &, nil
}

// GetState returns the current state of a terminal which may be useful to
// restore the terminal after a signal.
func ( int) (*State, error) {
	,  := unix.IoctlGetTermios(, ioctlReadTermios)
	if  != nil {
		return nil, 
	}

	return &State{termios: *}, nil
}

// Restore restores the terminal connected to the given file descriptor to a
// previous state.
func ( int,  *State) error {
	return unix.IoctlSetTermios(, ioctlWriteTermios, &.termios)
}

// GetSize returns the dimensions of the given terminal.
func ( int) (,  int,  error) {
	,  := unix.IoctlGetWinsize(, unix.TIOCGWINSZ)
	if  != nil {
		return -1, -1, 
	}

	return int(.Col), int(.Row), nil
}