72 lines
1.5 KiB
Go
72 lines
1.5 KiB
Go
package inject
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"strings"
|
|
)
|
|
|
|
type Backend interface {
|
|
Inject(ctx context.Context, text string) error
|
|
}
|
|
|
|
type ClipboardWriter interface {
|
|
WriteClipboard(ctx context.Context, text string) error
|
|
}
|
|
|
|
type ClipboardWriterFunc func(ctx context.Context, text string) error
|
|
|
|
func (f ClipboardWriterFunc) WriteClipboard(ctx context.Context, text string) error {
|
|
return f(ctx, text)
|
|
}
|
|
|
|
type Paster interface {
|
|
Paste(ctx context.Context) error
|
|
}
|
|
|
|
type Typer interface {
|
|
TypeText(ctx context.Context, text string) error
|
|
}
|
|
|
|
type Deps struct {
|
|
Clipboard ClipboardWriter
|
|
Paster Paster
|
|
Typer Typer
|
|
}
|
|
|
|
type ClipboardBackend struct {
|
|
Writer ClipboardWriter
|
|
Paster Paster
|
|
}
|
|
|
|
func (b ClipboardBackend) Inject(ctx context.Context, text string) error {
|
|
if b.Writer == nil || b.Paster == nil {
|
|
return errors.New("clipboard backend missing dependencies")
|
|
}
|
|
if err := b.Writer.WriteClipboard(ctx, text); err != nil {
|
|
return err
|
|
}
|
|
return b.Paster.Paste(ctx)
|
|
}
|
|
|
|
type InjectionBackend struct {
|
|
Typer Typer
|
|
}
|
|
|
|
func (b InjectionBackend) Inject(ctx context.Context, text string) error {
|
|
if b.Typer == nil {
|
|
return errors.New("injection backend missing dependencies")
|
|
}
|
|
return b.Typer.TypeText(ctx, text)
|
|
}
|
|
|
|
func NewBackend(name string, deps Deps) (Backend, error) {
|
|
switch strings.ToLower(strings.TrimSpace(name)) {
|
|
case "", "clipboard":
|
|
return ClipboardBackend{Writer: deps.Clipboard, Paster: deps.Paster}, nil
|
|
case "injection":
|
|
return InjectionBackend{Typer: deps.Typer}, nil
|
|
default:
|
|
return nil, errors.New("unknown injection backend")
|
|
}
|
|
}
|