master
 1package utils
 2
 3import (
 4	"fmt"
 5	"os"
 6
 7	"github.com/atotto/clipboard"
 8	clipboardImage "github.com/skanehira/clipboard-image/v2"
 9)
10
11func WriteToClipboard(text string) error {
12	if err := clipboard.WriteAll(text); err != nil {
13		return fmt.Errorf("failed to write to clipboard: %w", err)
14	}
15	return nil
16}
17
18func WriteToClipboardImage(bytes []byte) error {
19	tempFilename := "/tmp/qr-image.png"
20	if err := os.WriteFile(tempFilename, bytes, 0644); err != nil {
21		return fmt.Errorf("failed to write temp image for clipboard: %w", err)
22	}
23
24	f, err := os.Open(tempFilename)
25	if err != nil {
26		return fmt.Errorf("failed to open temp image for clipboard: %w", err)
27	}
28	defer func(f *os.File) {
29		if err := f.Close(); err != nil {
30			// Log this error but don't override the main return error
31			fmt.Fprintf(os.Stderr, "warning: error closing temp image file: %v\n", err)
32		}
33	}(f)
34
35	if err = clipboardImage.Write(f); err != nil {
36		return fmt.Errorf("failed to copy to clipboard: %w", err)
37	}
38	return nil
39}
40
41func ReadFromClipboard() (string, error) {
42	text, err := clipboard.ReadAll()
43	if err != nil {
44		return "", fmt.Errorf("failed to read from clipboard: %w", err)
45	}
46	return text, nil
47}