zenity/internal/zenutil/run_unix.go

106 lines
1.9 KiB
Go
Raw Normal View History

2021-04-11 22:59:08 -04:00
// +build !windows,!darwin,!js
2020-01-09 06:17:39 -05:00
2020-01-19 06:57:05 -05:00
package zenutil
2020-01-09 06:17:39 -05:00
import (
2020-01-28 07:46:43 -05:00
"context"
2020-01-09 06:17:39 -05:00
"os"
"os/exec"
2020-01-28 07:46:43 -05:00
"strconv"
2020-01-09 06:17:39 -05:00
"syscall"
)
var tool, path string
func init() {
2020-01-09 21:14:50 -05:00
for _, tool = range [3]string{"qarma", "zenity", "matedialog"} {
2020-01-09 06:17:39 -05:00
path, _ = exec.LookPath(tool)
if path != "" {
return
}
}
tool = "zenity"
}
2020-01-29 11:45:40 -05:00
// Run is internal.
2020-01-28 07:46:43 -05:00
func Run(ctx context.Context, args []string) ([]byte, error) {
2020-01-19 06:57:05 -05:00
if Command && path != "" {
2020-01-28 07:46:43 -05:00
if Timeout > 0 {
args = append(args, "--timeout", strconv.Itoa(Timeout))
}
2020-01-09 06:17:39 -05:00
syscall.Exec(path, append([]string{tool}, args...), os.Environ())
}
2020-01-28 07:46:43 -05:00
if ctx != nil {
2020-01-29 06:09:06 -05:00
out, err := exec.CommandContext(ctx, tool, args...).Output()
if ctx.Err() != nil {
err = ctx.Err()
}
return out, err
2020-01-28 07:46:43 -05:00
}
2020-01-09 06:17:39 -05:00
return exec.Command(tool, args...).Output()
}
2021-04-25 19:36:15 -04:00
// RunProgress is internal.
func RunProgress(ctx context.Context, max int, args []string) (m *progressDialog, err error) {
if Command && path != "" {
if Timeout > 0 {
args = append(args, "--timeout", strconv.Itoa(Timeout))
}
syscall.Exec(path, append([]string{tool}, args...), os.Environ())
}
cmd := exec.Command(tool, args...)
pipe, err := cmd.StdinPipe()
if err != nil {
return nil, err
}
if err = cmd.Start(); err != nil {
return nil, err
}
if ctx == nil {
ctx = context.Background()
}
m = &progressDialog{
done: make(chan struct{}),
lines: make(chan string),
percent: true,
max: max,
}
go func() {
err := cmd.Wait()
select {
case _, ok := <-m.lines:
if !ok {
err = nil
}
default:
}
if cerr := ctx.Err(); cerr != nil {
err = cerr
}
m.err = err
close(m.done)
}()
go func() {
defer cmd.Process.Signal(syscall.SIGTERM)
for {
var line string
select {
case s, ok := <-m.lines:
if !ok {
return
}
line = s
case <-ctx.Done():
return
}
if _, err := pipe.Write([]byte(line + "\n")); err != nil {
return
}
}
}()
return
}