Files

77 lines
2.5 KiB
Go

// Fenrir console screen reader.
// Copyright (c) 2026 Storm Dragon
// SPDX-License-Identifier: GPL-3.0-or-later
//
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the Free
// Software Foundation, either version 3 of the License, or (at your option)
// any later version.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
// more details.
//
// You should have received a copy of the GNU General Public License along with
// this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.html>.
//go:build linux && cgo
package terminal
/*
#include "native.h"
*/
import "C"
import (
"fmt"
"unsafe"
"git.stormux.org/storm/fenrir/internal/screen"
)
type Emulator struct {
native *C.VTerm
rows, cols int
}
func new_emulator(rows, cols int) (*Emulator, error) {
if !valid_size(rows, cols) {
return nil, fmt.Errorf("unsupported terminal geometry %dx%d", cols, rows)
}
vt := C.terminal_vterm(C.int(rows), C.int(cols))
if vt == nil {
return nil, fmt.Errorf("allocate terminal emulator")
}
return &Emulator{native: vt, rows: rows, cols: cols}, nil
}
func (e *Emulator) close() { C.terminal_vterm_free(e.native) }
func (e *Emulator) feed(bytes []byte) {
if len(bytes) == 0 {
return
}
C.vterm_input_write(e.native, (*C.char)(unsafe.Pointer(&bytes[0])), C.size_t(len(bytes)))
// The outer terminal answers queries. Discard duplicate emulator replies.
var discard [4096]byte
for C.vterm_output_read(e.native, (*C.char)(unsafe.Pointer(&discard[0])), C.size_t(len(discard))) > 0 {
}
}
func (e *Emulator) resize(rows, cols int) {
C.vterm_set_size(e.native, C.int(rows), C.int(cols))
e.rows, e.cols = rows, cols
}
func (e *Emulator) snapshot(active, lock bool) screen.Snapshot {
snapshot := screen.Snapshot{Terminal: 1, Active: active, NumLock: lock, Rows: e.rows, Cols: e.cols, Cells: make([]rune, e.rows*e.cols)}
snapshot.Generation = uint64(C.terminal_generation(e.native))
snapshot.Attributes = make([]screen.Attribute, len(snapshot.Cells))
var x, y C.int
C.terminal_cells(e.native, (*C.uint32_t)(unsafe.Pointer(&snapshot.Cells[0])), (*C.TerminalAttribute)(unsafe.Pointer(&snapshot.Attributes[0])), C.int(len(snapshot.Cells)), &x, &y)
snapshot.X, snapshot.Y = min(int(x), e.cols-1), min(int(y), e.rows-1)
return snapshot
}