forked from asticode/go-astilectron
-
Notifications
You must be signed in to change notification settings - Fork 0
/
window.go
478 lines (435 loc) · 18.7 KB
/
window.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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
package astilectron
import (
"net/url"
"sync"
"github.com/asticode/go-astilog"
"github.com/asticode/go-astitools/context"
"github.com/asticode/go-astitools/url"
"github.com/pkg/errors"
)
// Window event names
const (
EventNameWebContentsEventLogin = "web.contents.event.login"
EventNameWebContentsEventLoginCallback = "web.contents.event.login.callback"
EventNameWindowCmdBlur = "window.cmd.blur"
EventNameWindowCmdCenter = "window.cmd.center"
EventNameWindowCmdClose = "window.cmd.close"
EventNameWindowCmdCreate = "window.cmd.create"
EventNameWindowCmdDestroy = "window.cmd.destroy"
EventNameWindowCmdFocus = "window.cmd.focus"
EventNameWindowCmdHide = "window.cmd.hide"
EventNameWindowCmdLog = "window.cmd.log"
EventNameWindowCmdMaximize = "window.cmd.maximize"
eventNameWindowCmdMessage = "window.cmd.message"
eventNameWindowCmdMessageCallback = "window.cmd.message.callback"
EventNameWindowCmdMinimize = "window.cmd.minimize"
EventNameWindowCmdMove = "window.cmd.move"
EventNameWindowCmdResize = "window.cmd.resize"
EventNameWindowCmdRestore = "window.cmd.restore"
EventNameWindowCmdShow = "window.cmd.show"
EventNameWindowCmdUnmaximize = "window.cmd.unmaximize"
EventNameWindowCmdWebContentsCloseDevTools = "window.cmd.web.contents.close.dev.tools"
EventNameWindowCmdWebContentsOpenDevTools = "window.cmd.web.contents.open.dev.tools"
EventNameWindowEventBlur = "window.event.blur"
EventNameWindowEventClosed = "window.event.closed"
EventNameWindowEventDidFinishLoad = "window.event.did.finish.load"
EventNameWindowEventFocus = "window.event.focus"
EventNameWindowEventHide = "window.event.hide"
EventNameWindowEventMaximize = "window.event.maximize"
eventNameWindowEventMessage = "window.event.message"
eventNameWindowEventMessageCallback = "window.event.message.callback"
EventNameWindowEventMinimize = "window.event.minimize"
EventNameWindowEventMove = "window.event.move"
EventNameWindowEventReadyToShow = "window.event.ready.to.show"
EventNameWindowEventResize = "window.event.resize"
EventNameWindowEventRestore = "window.event.restore"
EventNameWindowEventShow = "window.event.show"
EventNameWindowEventUnmaximize = "window.event.unmaximize"
EventNameWindowEventUnresponsive = "window.event.unresponsive"
EventNameWindowEventDidGetRedirectRequest = "window.event.did.get.redirect.request"
EventNameWindowEventWillNavigate = "window.event.will.navigate"
)
// Title bar styles
var (
TitleBarStyleDefault = PtrStr("default")
TitleBarStyleHidden = PtrStr("hidden")
TitleBarStyleHiddenInset = PtrStr("hidden-inset")
)
// Window represents a window
// TODO Add missing window options
// TODO Add missing window methods
// TODO Add missing window events
type Window struct {
*object
callbackIdentifier *identifier
m sync.Mutex // Locks o
o *WindowOptions
onMessageOnce sync.Once
Session *Session
url *url.URL
}
// WindowOptions represents window options
// We must use pointers since GO doesn't handle optional fields whereas NodeJS does. Use PtrBool, PtrInt or PtrStr
// to fill the struct
// https://github.com/electron/electron/blob/v1.8.1/docs/api/browser-window.md
type WindowOptions struct {
AcceptFirstMouse *bool `json:"acceptFirstMouse,omitempty"`
AlwaysOnTop *bool `json:"alwaysOnTop,omitempty"`
AutoHideMenuBar *bool `json:"autoHideMenuBar,omitempty"`
BackgroundColor *string `json:"backgroundColor,omitempty"`
Center *bool `json:"center,omitempty"`
Closable *bool `json:"closable,omitempty"`
DisableAutoHideCursor *bool `json:"disableAutoHideCursor,omitempty"`
EnableLargerThanScreen *bool `json:"enableLargerThanScreen,omitempty"`
Focusable *bool `json:"focusable,omitempty"`
Frame *bool `json:"frame,omitempty"`
Fullscreen *bool `json:"fullscreen,omitempty"`
Fullscreenable *bool `json:"fullscreenable,omitempty"`
HasShadow *bool `json:"hasShadow,omitempty"`
Height *int `json:"height,omitempty"`
Icon *string `json:"icon,omitempty"`
Kiosk *bool `json:"kiosk,omitempty"`
MaxHeight *int `json:"maxHeight,omitempty"`
Maximizable *bool `json:"maximizable,omitempty"`
MaxWidth *int `json:"maxWidth,omitempty"`
MinHeight *int `json:"minHeight,omitempty"`
Minimizable *bool `json:"minimizable,omitempty"`
MinWidth *int `json:"minWidth,omitempty"`
Modal *bool `json:"modal,omitempty"`
Movable *bool `json:"movable,omitempty"`
Resizable *bool `json:"resizable,omitempty"`
Show *bool `json:"show,omitempty"`
SkipTaskbar *bool `json:"skipTaskbar,omitempty"`
Title *string `json:"title,omitempty"`
TitleBarStyle *string `json:"titleBarStyle,omitempty"`
Transparent *bool `json:"transparent,omitempty"`
UseContentSize *bool `json:"useContentSize,omitempty"`
WebPreferences *WebPreferences `json:"webPreferences,omitempty"`
Width *int `json:"width,omitempty"`
X *int `json:"x,omitempty"`
Y *int `json:"y,omitempty"`
// Additional options
Custom *WindowCustomOptions `json:"custom,omitempty"`
Load *WindowLoadOptions `json:"load,omitempty"`
Proxy *WindowProxyOptions `json:"proxy,omitempty"`
}
// WindowCustomOptions represents window custom options
type WindowCustomOptions struct {
HideOnClose *bool `json:"hideOnClose,omitempty"`
MessageBoxOnClose *MessageBoxOptions `json:"messageBoxOnClose,omitempty"`
MinimizeOnClose *bool `json:"minimizeOnClose,omitempty"`
Script string `json:"script,omitempty"`
}
// WindowLoadOptions represents window load options
// https://github.com/electron/electron/blob/v1.8.1/docs/api/browser-window.md#winloadurlurl-options
type WindowLoadOptions struct {
ExtraHeaders string `json:"extraHeaders,omitempty"`
HTTPReferer string `json:"httpReferrer,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
}
// WindowProxyOptions represents window proxy options
// https://github.com/electron/electron/blob/v1.8.1/docs/api/session.md#sessetproxyconfig-callback
type WindowProxyOptions struct {
BypassRules string `json:"proxyBypassRules,omitempty"`
PACScript string `json:"pacScript,omitempty"`
Rules string `json:"proxyRules,omitempty"`
}
// WebPreferences represents web preferences in window options.
// We must use pointers since GO doesn't handle optional fields whereas NodeJS does.
// Use PtrBool, PtrInt or PtrStr to fill the struct
type WebPreferences struct {
AllowRunningInsecureContent *bool `json:"allowRunningInsecureContent,omitempty"`
BackgroundThrottling *bool `json:"backgroundThrottling,omitempty"`
BlinkFeatures *string `json:"blinkFeatures,omitempty"`
ContextIsolation *bool `json:"contextIsolation,omitempty"`
DefaultEncoding *string `json:"defaultEncoding,omitempty"`
DefaultFontFamily map[string]interface{} `json:"defaultFontFamily,omitempty"`
DefaultFontSize *int `json:"defaultFontSize,omitempty"`
DefaultMonospaceFontSize *int `json:"defaultMonospaceFontSize,omitempty"`
DevTools *bool `json:"devTools,omitempty"`
DisableBlinkFeatures *string `json:"disableBlinkFeatures,omitempty"`
ExperimentalCanvasFeatures *bool `json:"experimentalCanvasFeatures,omitempty"`
ExperimentalFeatures *bool `json:"experimentalFeatures,omitempty"`
Images *bool `json:"images,omitempty"`
Javascript *bool `json:"javascript,omitempty"`
MinimumFontSize *int `json:"minimumFontSize,omitempty"`
NodeIntegration *bool `json:"nodeIntegration,omitempty"`
NodeIntegrationInWorker *bool `json:"nodeIntegrationInWorker,omitempty"`
Offscreen *bool `json:"offscreen,omitempty"`
Partition *string `json:"partition,omitempty"`
Plugins *bool `json:"plugins,omitempty"`
Preload *string `json:"preload,omitempty"`
Sandbox *bool `json:"sandbox,omitempty"`
ScrollBounce *bool `json:"scrollBounce,omitempty"`
Session map[string]interface{} `json:"session,omitempty"`
TextAreasAreResizable *bool `json:"textAreasAreResizable,omitempty"`
Webaudio *bool `json:"webaudio,omitempty"`
Webgl *bool `json:"webgl,omitempty"`
WebSecurity *bool `json:"webSecurity,omitempty"`
ZoomFactor *float64 `json:"zoomFactor,omitempty"`
}
// newWindow creates a new window
func newWindow(o Options, p Paths, url string, wo *WindowOptions, c *asticontext.Canceller, d *dispatcher, i *identifier, wrt *writer) (w *Window, err error) {
// Init
w = &Window{
callbackIdentifier: newIdentifier(),
o: wo,
object: newObject(nil, c, d, i, wrt, i.new()),
}
w.Session = newSession(w.ctx, c, d, i, wrt)
// Check app details
if wo.Icon == nil && p.AppIconDefaultSrc() != "" {
wo.Icon = PtrStr(p.AppIconDefaultSrc())
}
if wo.Title == nil && o.AppName != "" {
wo.Title = PtrStr(o.AppName)
}
// Make sure the window's context is cancelled once the closed event is received
w.On(EventNameWindowEventClosed, func(e Event) (deleteListener bool) {
w.cancel()
return true
})
// Show
w.On(EventNameWindowEventHide, func(e Event) (deleteListener bool) {
w.m.Lock()
defer w.m.Unlock()
w.o.Show = PtrBool(false)
return
})
w.On(EventNameWindowEventShow, func(e Event) (deleteListener bool) {
w.m.Lock()
defer w.m.Unlock()
w.o.Show = PtrBool(true)
return
})
// Parse url
if w.url, err = astiurl.Parse(url); err != nil {
err = errors.Wrapf(err, "parsing url %s failed", url)
return
}
return
}
// NewMenu creates a new window menu
func (w *Window) NewMenu(i []*MenuItemOptions) *Menu {
return newMenu(w.ctx, w.id, i, w.c, w.d, w.i, w.w)
}
// Blur blurs the window
func (w *Window) Blur() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdBlur, TargetID: w.id}, EventNameWindowEventBlur)
return
}
// Center centers the window
func (w *Window) Center() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdCenter, TargetID: w.id}, EventNameWindowEventMove)
return
}
// Close closes the window
func (w *Window) Close() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdClose, TargetID: w.id}, EventNameWindowEventClosed)
return
}
// CloseDevTools closes the dev tools
func (w *Window) CloseDevTools() (err error) {
if err = w.isActionable(); err != nil {
return
}
return w.w.write(Event{Name: EventNameWindowCmdWebContentsCloseDevTools, TargetID: w.id})
}
// Create creates the window
// We wait for EventNameWindowEventDidFinishLoad since we need the web content to be fully loaded before being able to
// send messages to it
func (w *Window) Create() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdCreate, SessionID: w.Session.id, TargetID: w.id, URL: w.url.String(), WindowOptions: w.o}, EventNameWindowEventDidFinishLoad)
return
}
// Destroy destroys the window
func (w *Window) Destroy() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdDestroy, TargetID: w.id}, EventNameWindowEventClosed)
return
}
// Focus focuses on the window
func (w *Window) Focus() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdFocus, TargetID: w.id}, EventNameWindowEventFocus)
return
}
// Hide hides the window
func (w *Window) Hide() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdHide, TargetID: w.id}, EventNameWindowEventHide)
return
}
// IsShown returns whether the window is shown
func (w *Window) IsShown() bool {
if err := w.isActionable(); err != nil {
return false
}
w.m.Lock()
defer w.m.Unlock()
return w.o.Show != nil && *w.o.Show
}
// Log logs a message in the JS console of the window
func (w *Window) Log(message string) (err error) {
if err = w.isActionable(); err != nil {
return
}
return w.w.write(Event{Message: newEventMessage(message), Name: EventNameWindowCmdLog, TargetID: w.id})
}
// Maximize maximizes the window
func (w *Window) Maximize() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdMaximize, TargetID: w.id}, EventNameWindowEventMaximize)
return
}
// Minimize minimizes the window
func (w *Window) Minimize() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdMinimize, TargetID: w.id}, EventNameWindowEventMinimize)
return
}
// Move moves the window
func (w *Window) Move(x, y int) (err error) {
if err = w.isActionable(); err != nil {
return
}
w.m.Lock()
w.o.X = PtrInt(x)
w.o.Y = PtrInt(y)
w.m.Unlock()
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdMove, TargetID: w.id, WindowOptions: &WindowOptions{X: PtrInt(x), Y: PtrInt(y)}}, EventNameWindowEventMove)
return
}
// MoveInDisplay moves the window in the proper display
func (w *Window) MoveInDisplay(d *Display, x, y int) error {
return w.Move(d.Bounds().X+x, d.Bounds().Y+y)
}
func (w *Window) OnLogin(fn func(i Event) (username, password string, err error)) {
w.On(EventNameWebContentsEventLogin, func(i Event) (deleteListener bool) {
// Get username and password
username, password, err := fn(i)
if err != nil {
astilog.Error(errors.Wrap(err, "getting username and password failed"))
return
}
// No auth
if len(username) == 0 && len(password) == 0 {
return
}
// Send message back
if err = w.w.write(Event{CallbackID: i.CallbackID, Name: EventNameWebContentsEventLoginCallback, Password: password, TargetID: w.id, Username: username}); err != nil {
astilog.Error(errors.Wrap(err, "writing login callback message failed"))
return
}
return
})
}
// ListenerMessage represents a message listener executed when receiving a message from the JS
type ListenerMessage func(m *EventMessage) (v interface{})
// OnMessage adds a specific listener executed when receiving a message from the JS
// This method can be called only once
func (w *Window) OnMessage(l ListenerMessage) {
w.onMessageOnce.Do(func() {
w.On(eventNameWindowEventMessage, func(i Event) (deleteListener bool) {
v := l(i.Message)
if len(i.CallbackID) > 0 {
o := Event{CallbackID: i.CallbackID, Name: eventNameWindowCmdMessageCallback, TargetID: w.id}
if v != nil {
o.Message = newEventMessage(v)
}
if err := w.w.write(o); err != nil {
astilog.Error(errors.Wrap(err, "writing callback message failed"))
}
}
return
})
})
}
// OpenDevTools opens the dev tools
func (w *Window) OpenDevTools() (err error) {
if err = w.isActionable(); err != nil {
return
}
return w.w.write(Event{Name: EventNameWindowCmdWebContentsOpenDevTools, TargetID: w.id})
}
// Resize resizes the window
func (w *Window) Resize(width, height int) (err error) {
if err = w.isActionable(); err != nil {
return
}
w.m.Lock()
w.o.Height = PtrInt(height)
w.o.Width = PtrInt(width)
w.m.Unlock()
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdResize, TargetID: w.id, WindowOptions: &WindowOptions{Height: PtrInt(height), Width: PtrInt(width)}}, EventNameWindowEventResize)
return
}
// Restore restores the window
func (w *Window) Restore() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdRestore, TargetID: w.id}, EventNameWindowEventRestore)
return
}
// CallbackMessage represents a message callback
type CallbackMessage func(m *EventMessage)
// SendMessage sends a message to the JS window and execute optional callbacks upon receiving a response from the JS
// Use astilectron.onMessage method to capture those messages in JS
func (w *Window) SendMessage(message interface{}, callbacks ...CallbackMessage) (err error) {
if err = w.isActionable(); err != nil {
return
}
var e = Event{Message: newEventMessage(message), Name: eventNameWindowCmdMessage, TargetID: w.id}
if len(callbacks) > 0 {
e.CallbackID = w.callbackIdentifier.new()
w.On(eventNameWindowEventMessageCallback, func(i Event) (deleteListener bool) {
if i.CallbackID == e.CallbackID {
for _, c := range callbacks {
c(i.Message)
}
deleteListener = true
}
return
})
}
return w.w.write(e)
}
// Show shows the window
func (w *Window) Show() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdShow, TargetID: w.id}, EventNameWindowEventShow)
return
}
// Unmaximize unmaximize the window
func (w *Window) Unmaximize() (err error) {
if err = w.isActionable(); err != nil {
return
}
_, err = synchronousEvent(w.c, w, w.w, Event{Name: EventNameWindowCmdUnmaximize, TargetID: w.id}, EventNameWindowEventUnmaximize)
return
}