Last active
April 24, 2026 19:49
-
-
Save hymkor/de87849cbd3cd2fbb804cec28f409c4d to your computer and use it in GitHub Desktop.
キーボード入力の汎用 channel 化を試みたが、どうしても1回分のブロックは解消できないので、ボツ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //go:build run | |
| package main | |
| import ( | |
| "fmt" | |
| "os" | |
| "time" | |
| "github.com/hymkor/jegan/internal/ttychan" | |
| "github.com/nyaosorg/go-ttyadapter/tty8pe" | |
| ) | |
| func mains() error { | |
| tty := ttychan.New(&tty8pe.Tty{}) | |
| if err := tty.Open(nil); err != nil { | |
| return err | |
| } | |
| defer tty.Close() | |
| for { | |
| select { | |
| case <-time.After(time.Second): | |
| fmt.Print(".") | |
| case k := <-tty.GetKey(): | |
| fmt.Printf("%q\n", k.Key) | |
| if k.Err != nil { | |
| return k.Err | |
| } | |
| if k.Key == "\a" { | |
| return nil | |
| } | |
| } | |
| } | |
| } | |
| func main() { | |
| if err := mains(); err != nil { | |
| fmt.Fprintln(os.Stderr, err.Error()) | |
| os.Exit(1) | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package ttychan | |
| import ( | |
| "context" | |
| "github.com/nyaosorg/go-ttyadapter" | |
| ) | |
| type Keys struct { | |
| Key string | |
| Err error | |
| } | |
| type TtyChan struct { | |
| ttyadapter.Tty | |
| request chan struct{} | |
| response chan Keys | |
| cancel context.CancelFunc | |
| } | |
| func New(t ttyadapter.Tty) *TtyChan { | |
| return &TtyChan{ | |
| Tty: t, | |
| } | |
| } | |
| func (t *TtyChan) Open(onResize func(int, int)) error { | |
| if err := t.Tty.Open(onResize); err != nil { | |
| return err | |
| } | |
| var ctx context.Context | |
| ctx, t.cancel = context.WithCancel(context.Background()) | |
| t.request = make(chan struct{}) | |
| t.response = make(chan Keys) | |
| go func() { | |
| defer close(t.response) | |
| for { | |
| select { | |
| case <-ctx.Done(): | |
| return | |
| case <-t.request: | |
| key, err := t.Tty.GetKey() | |
| select { | |
| case <-ctx.Done(): | |
| case t.response <- Keys{Key: key, Err: err}: | |
| } | |
| } | |
| } | |
| }() | |
| return nil | |
| } | |
| func (t *TtyChan) Close() error { | |
| t.cancel() | |
| close(t.request) | |
| return t.Tty.Close() | |
| } | |
| func (t *TtyChan) GetKey() chan Keys { | |
| select { | |
| case t.request <- struct{}{}: | |
| default: | |
| } | |
| return t.response | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment