Files

79 lines
2.3 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 console
/*
#include <sys/ioctl.h>
#include <errno.h>
#include <termios.h>
static int paste_byte(int fd, unsigned char value) {
return ioctl(fd, TIOCSTI, &value) < 0 ? -errno : 0;
}
*/
import "C"
import (
"context"
"fmt"
"os"
"path/filepath"
"syscall"
)
// Paste runs on the clipboard worker and targets a captured VT. Recheck text
// mode and the active VT before each byte; never follow a VT switch mid-paste.
// Kernels that deny TIOCSTI return their error without reporting success.
func (s *Source) Paste(ctx context.Context, text string, terminal int) error {
if err := ctx.Err(); err != nil {
return err
}
// Check before opening the target: otherwise our own descriptor would
// make an unused console pass the occupancy check below.
number, textMode, _, _, err := s.active()
if err != nil {
return err
}
if number != terminal || !textMode {
return fmt.Errorf("clipboard paste stopped: active VT changed")
}
path := filepath.Join(s.root, "dev", fmt.Sprintf("tty%d", terminal))
file, err := os.OpenFile(path, os.O_WRONLY|syscall.O_NOCTTY|syscall.O_NONBLOCK, 0)
if err != nil {
return err
}
defer file.Close()
for _, value := range []byte(text) {
if err := ctx.Err(); err != nil {
return err
}
number, textMode, _, _, err := s.active()
if err != nil {
return err
}
if number != terminal || !textMode {
return fmt.Errorf("clipboard paste stopped: active VT changed")
}
if code := C.paste_byte(C.int(file.Fd()), C.uchar(value)); code < 0 {
return fmt.Errorf("console clipboard paste: %w", syscall.Errno(-code))
}
}
return nil
}