forked from richardwilkes/unison
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
311 lines (279 loc) · 8.94 KB
/
app.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
// Copyright ©2021-2022 by Richard A. Wilkes. All rights reserved.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, version 2.0. If a copy of the MPL was not distributed with
// this file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
// This Source Code Form is "Incompatible With Secondary Licenses", as
// defined by the Mozilla Public License, version 2.0.
package unison
import (
"os"
"path/filepath"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/go-gl/glfw/v3.3/glfw"
"github.com/richardwilkes/toolbox"
"github.com/richardwilkes/toolbox/atexit"
"github.com/richardwilkes/toolbox/errs"
"github.com/richardwilkes/toolbox/fatal"
"github.com/richardwilkes/unison/enums/thememode"
"github.com/richardwilkes/unison/internal/skia"
)
var (
redrawSet = make(map[*Window]struct{})
startupFinishedCallback func()
openFilesCallback func([]string) //nolint:unused // Not all platforms use this
themeChangedCallback func()
recoveryCallback errs.RecoveryHandler
quitAfterLastWindowClosedCallback func() bool
allowQuitCallback func() bool
quittingCallback func()
glfwInited atomic.Bool
noGlobalMenuBar bool
quitLock sync.RWMutex
calledAtExit bool
currentThemeMode = thememode.Auto
needPlatformDarkModeUpdate = true
platformDarkModeEnabled bool
)
type startupOption struct { // This exists just to prevent arbitrary functions from being passed to application startup.
}
// StartupOption holds an option for application startup.
type StartupOption func(startupOption) error
func init() {
// All init functions are run on the startup thread. Calling LockOSThread from an init function will cause the main
// function to be invoked on that thread.
runtime.LockOSThread()
}
// StartupFinishedCallback will cause f to be called once application startup has completed and it is about to start
// servicing the event loop. You should create your app's windows at this point.
func StartupFinishedCallback(f func()) StartupOption {
return func(_ startupOption) error {
startupFinishedCallback = f
return nil
}
}
// OpenFilesCallback will cause f to be called when the application is asked to open one or more files by the OS or an
// external application. By default, nothing is done with the request.
func OpenFilesCallback(f func(urls []string)) StartupOption {
return func(_ startupOption) error {
openFilesCallback = f
return nil
}
}
// ThemeChangedCallback will cause f to be called when the theme is changed. This occurs after the colors have been
// updated, but before any windows have been redraw.
func ThemeChangedCallback(f func()) StartupOption {
return func(_ startupOption) error {
themeChangedCallback = f
return nil
}
}
// RecoveryCallback will cause f to be called should a task invoked via task.InvokeTask() or task.InvokeTaskAfter()
// panic. If no recovery callback is set, the panic will be logged via errs.Log(err).
func RecoveryCallback(f errs.RecoveryHandler) StartupOption {
return func(_ startupOption) error {
recoveryCallback = f
return nil
}
}
// QuitAfterLastWindowClosedCallback will cause f to be called when the last window is closed to determine if the
// application should quit as a result. By default, the app will terminate when the last window is closed.
func QuitAfterLastWindowClosedCallback(f func() bool) StartupOption {
return func(_ startupOption) error {
quitAfterLastWindowClosedCallback = f
return nil
}
}
// AllowQuitCallback will cause f to be called when app termination has been requested. Return true to permit the
// request. By default, app termination requests are permitted.
func AllowQuitCallback(f func() bool) StartupOption {
return func(_ startupOption) error {
allowQuitCallback = f
return nil
}
}
// QuittingCallback will cause f to be called just before the app terminates.
func QuittingCallback(f func()) StartupOption {
return func(_ startupOption) error {
quittingCallback = f
return nil
}
}
// NoGlobalMenuBar will disable the global menu bar on platforms that normally use it, instead using the in-window menu
// bar.
func NoGlobalMenuBar() StartupOption {
return func(_ startupOption) error {
noGlobalMenuBar = true
return nil
}
}
// Start the application. This function does NOT return. While some calls may be safe to make, it should be assumed no
// calls into unison can be made prior to Start() being called unless explicitly stated otherwise.
func Start(options ...StartupOption) {
pwd, err := filepath.Abs(".")
if err != nil {
errs.Log(err)
}
for _, option := range options {
fatal.IfErr(option(startupOption{}))
}
glfw.InitHint(glfw.CocoaMenubar, glfw.False)
fatal.IfErr(glfw.Init())
// Restore the original working directory, as glfw changes it on some platforms
if err = os.Chdir(pwd); err != nil {
errs.Log(err)
}
atexit.Register(quitting)
atexit.Register(func() {
quitLock.Lock()
calledAtExit = true
quitLock.Unlock()
})
glfw.WindowHint(glfw.ContextVersionMajor, 3)
glfw.WindowHint(glfw.ContextVersionMinor, 2)
platformEarlyInit()
glfwInited.Store(true)
InvokeTask(finishStartup)
for {
processEvents()
}
}
func processEvents() {
glfw.WaitEvents()
processNextTask(uiTaskRecovery)
if len(redrawSet) > 0 {
set := redrawSet
redrawSet = make(map[*Window]struct{})
for wnd := range set {
if wnd.IsVisible() {
wnd.draw()
} else {
redrawSet[wnd] = struct{}{}
}
}
}
}
func finishStartup() {
skiaColorspace = skia.ColorSpaceNewSRGB()
RebuildDynamicColors()
platformLateInit()
if startupFinishedCallback != nil {
toolbox.Call(startupFinishedCallback)
}
platformFinishedStartup()
}
// ThemeChanged marks dynamic colors for rebuilding, calls any installed theme change callback, and then redraws all
// windows. This is normally called automatically for you, however, it has been made public to allow you to trigger it
// on demand.
func ThemeChanged() {
MarkDynamicColorsForRebuild()
if themeChangedCallback != nil {
toolbox.Call(themeChangedCallback)
}
for _, wnd := range Windows() {
wnd.MarkForRedraw()
}
}
func uiTaskRecovery(err error) {
if recoveryCallback != nil {
toolbox.Call(func() { recoveryCallback(err) })
} else {
errs.Log(err)
}
}
func quitAfterLastWindowClosed() bool {
if quitAfterLastWindowClosedCallback != nil {
quit := true
toolbox.Call(func() { quit = quitAfterLastWindowClosedCallback() })
return quit
}
return true
}
func allowQuit() bool {
if allowQuitCallback != nil {
allow := true
toolbox.Call(func() { allow = allowQuitCallback() })
return allow
}
return true
}
func quitting() {
quitLock.Lock()
callback := quittingCallback
quittingCallback = nil
quitLock.Unlock()
if callback != nil {
toolbox.Call(callback)
}
// atexit.Exit() is called here once to ensure registered atexit hooks are actually called, as OS's may directly
// terminate the app after returning from this function.
quitLock.Lock()
calledExit := calledAtExit
calledAtExit = true
quitLock.Unlock()
if !calledExit {
atexit.Exit(0)
}
glfw.Terminate()
}
// AttemptQuit initiates the termination sequence.
func AttemptQuit() {
if allowQuit() {
quitting()
}
}
// Beep plays the system beep sound.
func Beep() {
platformBeep()
}
// IsColorModeTrackingPossible returns true if the underlying platform can provide the current dark mode state. On those
// platforms that return false from this function, thememode.Auto is the same as thememode.Light.
func IsColorModeTrackingPossible() bool {
return platformIsDarkModeTrackingPossible()
}
// CurrentThemeMode returns the current theme mode state.
func CurrentThemeMode() thememode.Enum {
return currentThemeMode
}
// SetThemeMode sets the current theme mode state.
func SetThemeMode(mode thememode.Enum) {
if currentThemeMode != mode {
currentThemeMode = mode
needPlatformDarkModeUpdate = true
InvokeTask(ThemeChanged)
}
}
// IsDarkModeEnabled returns true if the OS is currently using a "dark mode".
func IsDarkModeEnabled() bool {
switch currentThemeMode {
case thememode.Light:
return false
case thememode.Dark:
return true
default:
if needPlatformDarkModeUpdate {
needPlatformDarkModeUpdate = false
platformDarkModeEnabled = platformIsDarkModeEnabled()
}
return platformDarkModeEnabled
}
}
// DoubleClickParameters returns the maximum delay between clicks and the maximum pixel drift allowed to register as a
// double-click.
func DoubleClickParameters() (maxDelay time.Duration, maxMouseDrift float32) {
return platformDoubleClickInterval(), 5
}
// DragGestureParameters returns the minimum delay before mouse movement should be recognized as a drag as well as the
// minimum pixel drift required to trigger a drag.
func DragGestureParameters() (minDelay time.Duration, minMouseDrift float32) {
return 250 * time.Millisecond, 5
}
func postEmptyEvent() {
if glfwInited.Load() {
glfw.PostEmptyEvent()
}
}