vvin/cmd_wait.go

84 lines
1.4 KiB
Go
Raw Normal View History

2023-10-17 00:00:50 -04:00
//go:build windows
// +build windows
2023-10-16 09:51:11 -04:00
package vvin
2019-11-18 00:48:49 -05:00
import (
2019-11-18 02:08:13 -05:00
"context"
2019-11-18 00:48:49 -05:00
"errors"
2019-11-18 02:08:13 -05:00
"fmt"
"os"
2019-11-18 02:09:56 -05:00
"os/signal"
2019-11-18 00:48:49 -05:00
"strings"
2019-11-18 02:09:56 -05:00
"syscall"
2019-11-18 00:48:49 -05:00
"time"
)
type waitCmd struct {
2019-11-18 00:55:17 -05:00
_ struct{} `help:"[--close] {Title}"`
2019-11-18 00:48:49 -05:00
Closed bool `help:"wait until the window is closed"`
Interval time.Duration `cli:"interval,i=DURATION" default:"1s"`
Timeout time.Duration `cli:"timeout=DURATION" default:"0s" help:"zero value means ininite"`
2019-11-18 00:48:49 -05:00
}
func (c waitCmd) Run(args []string) error {
if len(args) != 1 {
return errors.New("not one target")
}
an := ancestors()
t := strings.ToLower(args[0])
2019-11-18 02:08:13 -05:00
var ctx context.Context
var cancel func()
2019-11-18 02:08:13 -05:00
if c.Timeout == 0 {
ctx = context.Background()
cancel = func() {}
2019-11-18 02:08:13 -05:00
} else {
ctx, cancel = context.WithTimeout(context.Background(), c.Timeout)
2019-11-18 02:08:13 -05:00
}
2019-11-18 02:09:56 -05:00
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT, os.Interrupt)
fmt.Println("Press Ctrl+C to cancel.")
2019-11-18 02:08:13 -05:00
waitLoop:
2019-11-18 00:48:49 -05:00
for {
wins, err := listAllWindows()
if err != nil {
cancel()
2019-11-18 00:48:49 -05:00
return err
}
win := findFirstTarget(t, wins, an)
if c.Closed {
if win == nil {
break
}
} else {
if win != nil {
break
}
}
2019-11-18 02:08:13 -05:00
select {
2019-11-18 02:09:56 -05:00
case <-signalChan:
fmt.Fprintln(os.Stderr, "cancelled")
break waitLoop
2019-11-18 02:08:13 -05:00
case <-ctx.Done():
fmt.Fprintln(os.Stderr, "cancelled (timeout)")
2019-11-18 02:08:13 -05:00
break waitLoop
default:
//nop
}
time.Sleep(c.Interval)
2019-11-18 00:48:49 -05:00
}
cancel()
2019-11-18 00:48:49 -05:00
return nil
}