|
| 1 | +// +build linux,!windows,!darwin,!js |
| 2 | + |
| 3 | +package dlgs |
| 4 | + |
| 5 | +import ( |
| 6 | + "fmt" |
| 7 | + "image/color" |
| 8 | + "os/exec" |
| 9 | + "strconv" |
| 10 | + "strings" |
| 11 | + "syscall" |
| 12 | +) |
| 13 | + |
| 14 | +// Color displays a color selection dialog, returning the selected color and a bool for success. |
| 15 | +func Color(title, defaultColorHex string) (color.Color, bool, error) { |
| 16 | + cmd, err := cmdPath() |
| 17 | + if err != nil { |
| 18 | + return nil, false, err |
| 19 | + } |
| 20 | + |
| 21 | + o, err := exec.Command(cmd, "--color-selection", "--title", title, "--color", defaultColorHex).Output() |
| 22 | + if err != nil { |
| 23 | + if exitError, ok := err.(*exec.ExitError); ok { |
| 24 | + ws := exitError.Sys().(syscall.WaitStatus) |
| 25 | + return nil, ws.ExitStatus() == 0, nil |
| 26 | + } |
| 27 | + } |
| 28 | + |
| 29 | + ret := true |
| 30 | + out := strings.TrimSpace(string(o)) |
| 31 | + if out == "" { |
| 32 | + ret = false |
| 33 | + } |
| 34 | + |
| 35 | + return parseColor(out), ret, err |
| 36 | +} |
| 37 | + |
| 38 | +// parseColor returns color from output string. |
| 39 | +func parseColor(out string) color.Color { |
| 40 | + col := color.RGBA{} |
| 41 | + |
| 42 | + if strings.HasPrefix(out, "#") { |
| 43 | + var r, g, b uint8 |
| 44 | + fmt.Sscanf(out, "#%02x%02x%02x", &r, &g, &b) |
| 45 | + |
| 46 | + col.R = uint8(r) |
| 47 | + col.G = uint8(g) |
| 48 | + col.B = uint8(b) |
| 49 | + } else if strings.HasPrefix(out, "rgba(") { |
| 50 | + for _, s := range []string{"rgba", "(", ")"} { |
| 51 | + out = strings.Replace(out, s, "", -1) |
| 52 | + } |
| 53 | + t := strings.Split(out, ",") |
| 54 | + if len(t) == 4 { |
| 55 | + r, _ := strconv.ParseUint(t[0], 10, 8) |
| 56 | + g, _ := strconv.ParseUint(t[1], 10, 8) |
| 57 | + b, _ := strconv.ParseUint(t[2], 10, 8) |
| 58 | + a, _ := strconv.ParseUint(t[3], 10, 8) |
| 59 | + |
| 60 | + col.R = uint8(r) |
| 61 | + col.G = uint8(g) |
| 62 | + col.B = uint8(b) |
| 63 | + col.A = uint8(a) |
| 64 | + } |
| 65 | + } else if strings.HasPrefix(out, "rgb(") { |
| 66 | + for _, s := range []string{"rgb", "(", ")"} { |
| 67 | + out = strings.Replace(out, s, "", -1) |
| 68 | + } |
| 69 | + t := strings.Split(out, ",") |
| 70 | + if len(t) == 3 { |
| 71 | + r, _ := strconv.ParseUint(t[0], 10, 8) |
| 72 | + g, _ := strconv.ParseUint(t[1], 10, 8) |
| 73 | + b, _ := strconv.ParseUint(t[2], 10, 8) |
| 74 | + |
| 75 | + col.R = uint8(r) |
| 76 | + col.G = uint8(g) |
| 77 | + col.B = uint8(b) |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + return col |
| 82 | +} |
0 commit comments