allow for non-Window WailsEvent listeners (#3406)

* allow for non-Window WailsEvent listeners

- adds a RegisterListener function on the App struct such
  that code can listen for WailsEvent(s) even if it isn't a Window
- rename dispatchEventToWindows -> dispatchEventToListeners
- add all windows and WailsEventListeners to slice before emitting

* Update v3/pkg/application/application.go

---------

Co-authored-by: Lea Anthony <lea.anthony@gmail.com>
This commit is contained in:
Travis McLane 2024-04-19 18:39:57 -05:00 committed by GitHub
commit 021efab84d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 25 additions and 2 deletions

View file

@ -76,7 +76,7 @@ func New(appOptions Options) *App {
result.logStartup()
result.logPlatformInfo()
result.Events = NewWailsEventProcessor(result.dispatchEventToWindows)
result.Events = NewWailsEventProcessor(result.dispatchEventToListeners)
messageProc := NewMessageProcessor(result.Logger)
opts := &assetserver.Options{
@ -326,6 +326,10 @@ type App struct {
// signalHandler is used to handle signals
signalHandler *signal.SignalHandler
// Wails Event Listener related
wailsEventListenerLock sync.Mutex
wailsEventListeners []WailsEventListener
}
func (a *App) init() {
@ -336,6 +340,7 @@ func (a *App) init() {
a.keyBindings = make(map[string]func(window *WebviewWindow))
a.Logger = a.options.Logger
a.pid = os.Getpid()
a.wailsEventListeners = make([]WailsEventListener, 0)
}
func (a *App) getSystemTrayID() uint {
@ -400,6 +405,12 @@ func (a *App) RegisterHook(eventType events.ApplicationEventType, callback func(
}
}
func (a *App) RegisterListener(listener WailsEventListener) {
a.wailsEventListenerLock.Lock()
a.wailsEventListeners = append(a.wailsEventListeners, listener)
a.wailsEventListenerLock.Unlock()
}
func (a *App) NewWebviewWindow() *WebviewWindow {
return a.NewWebviewWindowWithOptions(WebviewWindowOptions{})
}
@ -774,10 +785,16 @@ func SaveFileDialogWithOptions(s *SaveFileDialogOptions) *SaveFileDialogStruct {
return result
}
func (a *App) dispatchEventToWindows(event *WailsEvent) {
func (a *App) dispatchEventToListeners(event *WailsEvent) {
listeners := a.wailsEventListeners
for _, window := range a.windows {
window.DispatchWailsEvent(event)
}
for _, listener := range listeners {
listener.DispatchWailsEvent(event)
}
}
func (a *App) IsDarkMode() bool {

View file

@ -60,6 +60,12 @@ func (e WailsEvent) ToJSON() string {
return string(marshal)
}
// WailsEventListener is an interface that can be implemented to listen for Wails events
// It is used by the RegisterListener method of the Application.
type WailsEventListener interface {
DispatchWailsEvent(event *WailsEvent)
}
type hook struct {
callback func(*WailsEvent)
}