/
main.go
103 lines (89 loc) · 2.24 KB
/
main.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package main
import (
"fmt"
"image"
"image/png"
"os"
"path/filepath"
"runtime"
"bitbucket.org/kardianos/osext"
"github.com/GeertJohan/go.rice"
"gopkg.in/qml.v1"
)
var imageEmpty = image.NewRGBA(image.Rect(0, 0, 16, 16))
var boxImages *rice.Box
var boxQml *rice.Box
func main() {
if err := qml.Run(run); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
}
func run() error {
boxImages = rice.MustFindBox("project/images")
boxQml = rice.MustFindBox("project/qml")
engine := qml.NewEngine()
engine.AddImageProvider("images", unboxImage)
engine.On("quit", func() {
fmt.Println("qml quit")
os.Exit(0)
})
component, err := componentFromFile("main.qml", engine)
if err != nil {
return err
}
win := component.CreateWindow(nil)
win.Show()
win.Wait()
return nil
}
// The unboxImage function is an image provider used within engine.AddImageProvider,
// loads image resources from the the specified rice box.
func unboxImage(name string, width, height int) image.Image {
file, err := boxImages.Open(name)
if err != nil {
fmt.Fprintf(os.Stderr, "resource: %v\n", err)
return imageEmpty
}
defer file.Close()
img, err := png.Decode(file)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
return imageEmpty
}
return img
}
// The componentFromFile function finds an existing path of qml file with given name
// and creates a component from it. This is supposed to be replaced with a rice box soon.
func componentFromFile(name string, engine *qml.Engine) (qml.Object, error) {
prefix, err := qmlPrefix()
if err != nil {
return nil, err
}
path := filepath.Join(prefix, name)
if _, err := os.Stat(path); os.IsNotExist(err) {
err0 := err
path = filepath.Join("project", "qml", name)
if _, err := os.Stat(path); os.IsNotExist(err) {
return nil, err0
}
}
component, err := engine.LoadFile(path)
if err != nil {
return nil, err
}
return component, nil
}
// The qmlPrefix function returns an executable-related path of dir with qml files.
func qmlPrefix() (path string, err error) {
path, err = osext.ExecutableFolder()
if err != nil {
return
}
switch runtime.GOOS {
case "darwin":
return filepath.Join(path, "..", "Resources", "qml"), nil
default:
return filepath.Join(path, "qml"), nil
}
}