/
calc.go
88 lines (67 loc) · 1.73 KB
/
calc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package launcher
import (
"regexp"
"strconv"
"fyne.io/fyne/v2"
"fyshos.com/fynedesk"
wmTheme "fyshos.com/fynedesk/theme"
"github.com/Knetic/govaluate"
)
var (
exprRegex = regexp.MustCompile(`^[0-9.+\-*/()]+$`)
numRegex = regexp.MustCompile(`^[0-9.]+$`)
)
var calcMeta = fynedesk.ModuleMetadata{
Name: "Launcher: Calculate",
NewInstance: newCalcSuggest,
}
type calc struct{}
func (c *calc) Destroy() {
}
func (c *calc) LaunchSuggestions(input string) []fynedesk.LaunchSuggestion {
if !c.isExpression(input) {
return nil
}
result, err := c.eval(input)
if err != nil {
return nil
}
return []fynedesk.LaunchSuggestion{&calcItem{sum: input, result: result}}
}
func (c *calc) eval(sum string) (string, error) {
expression, err := govaluate.NewEvaluableExpression(sum)
if err != nil {
return "", err
}
res, err := expression.Evaluate(nil)
if err != nil {
return "", err
}
if f, ok := res.(float64); ok {
return strconv.FormatFloat(f, 'f', -1, 64), nil
}
return "", nil
}
func (c *calc) Metadata() fynedesk.ModuleMetadata {
return calcMeta
}
// isExpression will return true if input is a mathematical expression unless it just contains a number
func (c *calc) isExpression(input string) bool {
return exprRegex.MatchString(input) && !numRegex.MatchString(input)
}
// newCalcSuggest creates a new module that will show calculations in the launcher suggestions
func newCalcSuggest() fynedesk.Module {
return &calc{}
}
type calcItem struct {
sum, result string
}
func (i *calcItem) Icon() fyne.Resource {
return wmTheme.CalculateIcon
}
func (i *calcItem) Title() string {
return i.sum + " = " + i.result
}
func (i *calcItem) Launch() {
fyne.CurrentApp().Driver().AllWindows()[0].Clipboard().SetContent(i.result)
}