Skip to content

Commit

Permalink
Refactored Events (#3731)
Browse files Browse the repository at this point in the history
Experimental rename
  • Loading branch information
leaanthony committed Sep 7, 2024
1 parent 5004aac commit 5cde12b
Show file tree
Hide file tree
Showing 25 changed files with 175 additions and 118 deletions.
2 changes: 1 addition & 1 deletion v3/examples/build/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ func main() {
},
})

app.On(events.Mac.ApplicationDidFinishLaunching, func(*application.Event) {
app.OnApplicationEvent(events.Mac.ApplicationDidFinishLaunching, func(*application.ApplicationEvent) {
log.Println("ApplicationDidFinishLaunching")
})

Expand Down
4 changes: 2 additions & 2 deletions v3/examples/drag-n-drop/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,9 @@ func main() {
EnableDragAndDrop: true,
})

window.On(events.Common.WindowFilesDropped, func(event *application.WindowEvent) {
window.OnWindowEvent(events.Common.WindowFilesDropped, func(event *application.WindowEvent) {
files := event.Context().DroppedFiles()
app.Events.Emit(&application.WailsEvent{
app.customEventProcessor.Emit(&application.CustomEvent{
Name: "files",
Data: files,
})
Expand Down
4 changes: 4 additions & 0 deletions v3/examples/events/assets/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ <h1>Events Demo</h1>
let currentHTML = document.getElementById("results").innerHTML;
document.getElementById("results").innerHTML = currentHTML + "<br/>" + JSON.stringify(data);
})
wails.Events.On("windowevent", function(data) {
let currentHTML = document.getElementById("results").innerHTML;
document.getElementById("results").innerHTML = currentHTML + "<br/>" + JSON.stringify(data);
})
</script>

</html>
37 changes: 21 additions & 16 deletions v3/examples/events/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ var assets embed.FS
func main() {

app := application.New(application.Options{
Name: "Events Demo",
Description: "A demo of the Events API",
Name: "customEventProcessor Demo",
Description: "A demo of the customEventProcessor API",
Assets: application.AssetOptions{
Handler: application.BundledAssetFileServer(assets),
},
Expand All @@ -27,22 +27,21 @@ func main() {
})

// Custom event handling
app.Events.On("myevent", func(e *application.WailsEvent) {
app.Logger.Info("[Go] WailsEvent received", "name", e.Name, "data", e.Data, "sender", e.Sender, "cancelled", e.Cancelled)
app.OnEvent("myevent", func(e *application.CustomEvent) {
app.Logger.Info("[Go] CustomEvent received", "name", e.Name, "data", e.Data, "sender", e.Sender, "cancelled", e.Cancelled)
})

// OS specific application events
app.On(events.Common.ApplicationStarted, func(event *application.Event) {
app.OnApplicationEvent(events.Common.ApplicationStarted, func(event *application.ApplicationEvent) {
for {
app.Events.Emit(&application.WailsEvent{
Name: "myevent",
Data: "hello",
})
// This emits a custom event every 10 seconds
// As it's sent from the application, the sender will be blank
app.EmitEvent("myevent", "hello")
time.Sleep(10 * time.Second)
}
})

app.On(events.Common.ThemeChanged, func(event *application.Event) {
app.OnApplicationEvent(events.Common.ThemeChanged, func(event *application.ApplicationEvent) {
app.Logger.Info("System theme changed!")
if event.Context().IsDarkMode() {
app.Logger.Info("System is now using dark mode!")
Expand All @@ -52,12 +51,12 @@ func main() {
})

// Platform agnostic events
app.On(events.Common.ApplicationStarted, func(event *application.Event) {
app.OnApplicationEvent(events.Common.ApplicationStarted, func(event *application.ApplicationEvent) {
app.Logger.Info("events.Common.ApplicationStarted fired!")
})

win1 := app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{
Title: "Events Demo",
Title: "Window 1",
Name: "Window 1",
Mac: application.MacWindow{
Backdrop: application.MacBackdropTranslucent,
Expand All @@ -79,15 +78,21 @@ func main() {
})

win2 := app.NewWebviewWindowWithOptions(application.WebviewWindowOptions{
Title: "Events Demo",
Name: "Window 2",
Title: "Window 2",
Mac: application.MacWindow{
Backdrop: application.MacBackdropTranslucent,
TitleBar: application.MacTitleBarHiddenInsetUnified,
InvisibleTitleBarHeight: 50,
},
})

go func() {
for {
win2.EmitEvent("windowevent", "ooooh!")
time.Sleep(10 * time.Second)
}
}()

var cancel bool

win2.RegisterHook(events.Common.WindowFocus, func(e *application.WindowEvent) {
Expand All @@ -98,8 +103,8 @@ func main() {
}
})

win2.On(events.Common.WindowFocus, func(e *application.WindowEvent) {
app.Logger.Info("[Event] Window focus!")
win2.OnWindowEvent(events.Common.WindowFocus, func(e *application.WindowEvent) {
app.Logger.Info("[ApplicationEvent] Window focus!")
})

err := app.Run()
Expand Down
2 changes: 1 addition & 1 deletion v3/examples/hide-window/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func main() {
}

// Click Dock icon tigger application show
app.On(events.Mac.ApplicationShouldHandleReopen, func(event *application.Event) {
app.OnApplicationEvent(events.Mac.ApplicationShouldHandleReopen, func(event *application.ApplicationEvent) {
println("reopen")
window.Show()
})
Expand Down
2 changes: 1 addition & 1 deletion v3/examples/plain/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func main() {
JS: `window.iamhere = function() { console.log("Hello World!"); }`,
})

app.Events.On("clicked", func(_ *application.WailsEvent) {
app.customEventProcessor.On("clicked", func(_ *application.CustomEvent) {
println("clicked")
})

Expand Down
2 changes: 1 addition & 1 deletion v3/examples/video/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func main() {
WebviewBrowserPath: "",
},
})
app.On(events.Mac.ApplicationDidFinishLaunching, func(event *application.Event) {
app.OnApplicationEvent(events.Mac.ApplicationDidFinishLaunching, func(event *application.ApplicationEvent) {
log.Println("ApplicationDidFinishLaunching")
})

Expand Down
6 changes: 3 additions & 3 deletions v3/examples/window/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ func main() {
ApplicationShouldTerminateAfterLastWindowClosed: false,
},
})
app.On(events.Common.ApplicationStarted, func(event *application.Event) {
app.OnApplicationEvent(events.Common.ApplicationStarted, func(event *application.ApplicationEvent) {
log.Println("ApplicationDidFinishLaunching")
})

Expand Down Expand Up @@ -164,7 +164,7 @@ func main() {
SetRelativePosition(rand.Intn(1000), rand.Intn(800)).
SetURL("https://wails.io").
Show()
w.On(events.Common.WindowDidMove, func(event *application.WindowEvent) {
w.OnWindowEvent(events.Common.WindowDidMove, func(event *application.WindowEvent) {
x, y := w.Position()
fmt.Printf("WindowDidMove event triggered. New position: (%d, %d)\n", x, y)
})
Expand All @@ -181,7 +181,7 @@ func main() {
SetRelativePosition(rand.Intn(1000), rand.Intn(800)).
SetURL("https://wails.io").
Show()
w.On(events.Common.WindowDidResize, func(event *application.WindowEvent) {
w.OnWindowEvent(events.Common.WindowDidResize, func(event *application.WindowEvent) {
width, height := w.Size()

fmt.Printf("WindowDidResize event triggered. New size: (%d, %d)\n", width, height)
Expand Down
4 changes: 2 additions & 2 deletions v3/examples/wml/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,10 +35,10 @@ func main() {
},
})

app.Events.On("button-pressed", func(_ *application.WailsEvent) {
app.customEventProcessor.On("button-pressed", func(_ *application.CustomEvent) {
println("Button Pressed!")
})
app.Events.On("hover", func(_ *application.WailsEvent) {
app.customEventProcessor.On("hover", func(_ *application.CustomEvent) {
println("Hover time!")
})

Expand Down
2 changes: 1 addition & 1 deletion v3/internal/commands/appimage_testfiles/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ func main() {
ApplicationShouldTerminateAfterLastWindowClosed: false,
},
})
app.On(events.Mac.ApplicationDidFinishLaunching, func(event *application.Event) {
app.OnApplicationEvent(events.Mac.ApplicationDidFinishLaunching, func(event *application.ApplicationEvent) {
log.Println("ApplicationDidFinishLaunching")
})

Expand Down
76 changes: 55 additions & 21 deletions v3/pkg/application/application.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ func init() {
}

type EventListener struct {
callback func(app *Event)
callback func(app *ApplicationEvent)
}

func Get() *App {
Expand Down Expand Up @@ -80,7 +80,7 @@ func New(appOptions Options) *App {
result.logStartup()
result.logPlatformInfo()

result.Events = NewWailsEventProcessor(result.dispatchEventToListeners)
result.customEventProcessor = NewWailsEventProcessor(result.dispatchEventToListeners)

messageProc := NewMessageProcessor(result.Logger)
opts := &assetserver.Options{
Expand Down Expand Up @@ -264,7 +264,7 @@ func (r *webViewAssetRequest) Header() (http.Header, error) {
var webviewRequests = make(chan *webViewAssetRequest, 5)

type eventHook struct {
callback func(event *Event)
callback func(event *ApplicationEvent)
}

type App struct {
Expand Down Expand Up @@ -303,9 +303,9 @@ type App struct {
// The main application menu
ApplicationMenu *Menu

clipboard *Clipboard
Events *EventProcessor
Logger *slog.Logger
clipboard *Clipboard
customEventProcessor *EventProcessor
Logger *slog.Logger

contextMenus map[string]*Menu
contextMenusLock sync.Mutex
Expand Down Expand Up @@ -336,7 +336,7 @@ type App struct {
// signalHandler is used to handle signals
signalHandler *signal.SignalHandler

// Wails Event Listener related
// Wails ApplicationEvent Listener related
wailsEventListenerLock sync.Mutex
wailsEventListeners []WailsEventListener
}
Expand All @@ -349,6 +349,39 @@ func (a *App) handleError(err error) {
}
}

// EmitEvent will emit an event
func (a *App) EmitEvent(name string, data ...any) {
a.customEventProcessor.Emit(&CustomEvent{
Name: name,
Data: data,
})
}

// EmitEvent will emit an event
func (a *App) emitEvent(event *CustomEvent) {
a.customEventProcessor.Emit(event)
}

// OnEvent will listen for events
func (a *App) OnEvent(name string, callback func(event *CustomEvent)) func() {
return a.customEventProcessor.On(name, callback)
}

// OffEvent will remove an event listener
func (a *App) OffEvent(name string) {
a.customEventProcessor.Off(name)
}

// OnMultipleEvent will listen for events a set number of times before unsubscribing.
func (a *App) OnMultipleEvent(name string, callback func(event *CustomEvent), counter int) {
a.customEventProcessor.OnMultiple(name, callback, counter)
}

// ResetEvents will remove all event listeners and hooks
func (a *App) ResetEvents() {
a.customEventProcessor.OffAll()
}

func (a *App) handleFatalError(err error) {
var buffer strings.Builder
buffer.WriteString("*********************** FATAL ***********************")
Expand Down Expand Up @@ -398,7 +431,7 @@ func (a *App) Capabilities() capabilities.Capabilities {
return a.capabilities
}

func (a *App) On(eventType events.ApplicationEventType, callback func(event *Event)) func() {
func (a *App) OnApplicationEvent(eventType events.ApplicationEventType, callback func(event *ApplicationEvent)) func() {
eventID := uint(eventType)
a.applicationEventListenersLock.Lock()
defer a.applicationEventListenersLock.Unlock()
Expand All @@ -419,9 +452,10 @@ func (a *App) On(eventType events.ApplicationEventType, callback func(event *Eve
}
}

// RegisterHook registers a hook for the given event type. Hooks are called before the event listeners and can cancel the event.
// RegisterApplicationEventHook registers a hook for the given application event.
// Hooks are called before the event listeners and can cancel the event.
// The returned function can be called to remove the hook.
func (a *App) RegisterHook(eventType events.ApplicationEventType, callback func(event *Event)) func() {
func (a *App) RegisterApplicationEventHook(eventType events.ApplicationEventType, callback func(event *ApplicationEvent)) func() {
eventID := uint(eventType)
a.applicationEventHooksLock.Lock()
defer a.applicationEventHooksLock.Unlock()
Expand All @@ -437,15 +471,15 @@ 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) RegisterServiceHandler(prefix string, handler http.Handler) {
a.assets.AttachServiceHandler(prefix, handler)
}
//func (a *App) RegisterListener(listener WailsEventListener) {
// a.wailsEventListenerLock.Lock()
// a.wailsEventListeners = append(a.wailsEventListeners, listener)
// a.wailsEventListenerLock.Unlock()
//}
//
//func (a *App) RegisterServiceHandler(prefix string, handler http.Handler) {
// a.assets.AttachServiceHandler(prefix, handler)
//}

func (a *App) NewWebviewWindow() *WebviewWindow {
return a.NewWebviewWindowWithOptions(WebviewWindowOptions{})
Expand Down Expand Up @@ -602,7 +636,7 @@ func (a *App) Run() error {
return nil
}

func (a *App) handleApplicationEvent(event *Event) {
func (a *App) handleApplicationEvent(event *ApplicationEvent) {
a.applicationEventListenersLock.RLock()
listeners, ok := a.applicationEventListeners[event.Id]
a.applicationEventListenersLock.RUnlock()
Expand Down Expand Up @@ -822,7 +856,7 @@ func SaveFileDialogWithOptions(s *SaveFileDialogOptions) *SaveFileDialogStruct {
return result
}

func (a *App) dispatchEventToListeners(event *WailsEvent) {
func (a *App) dispatchEventToListeners(event *CustomEvent) {
listeners := a.wailsEventListeners

for _, window := range a.windows {
Expand Down
2 changes: 1 addition & 1 deletion v3/pkg/application/application_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ func (m *macosApp) setApplicationMenu(menu *Menu) {

func (m *macosApp) run() error {
// Add a hook to the ApplicationDidFinishLaunching event
m.parent.On(events.Mac.ApplicationDidFinishLaunching, func(*Event) {
m.parent.On(events.Mac.ApplicationDidFinishLaunching, func(*ApplicationEvent) {
C.setApplicationShouldTerminateAfterLastWindowClosed(C.bool(m.parent.options.Mac.ApplicationShouldTerminateAfterLastWindowClosed))
C.setActivationPolicy(C.int(m.parent.options.Mac.ActivationPolicy))
C.activateIgnoringOtherApps()
Expand Down
2 changes: 1 addition & 1 deletion v3/pkg/application/application_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func (a *linuxApp) setApplicationMenu(menu *Menu) {

func (a *linuxApp) run() error {

a.parent.On(events.Linux.ApplicationStartup, func(evt *Event) {
a.parent.On(events.Linux.ApplicationStartup, func(evt *ApplicationEvent) {
// TODO: What should happen here?
})
a.setupCommonEvents()
Expand Down
6 changes: 3 additions & 3 deletions v3/pkg/application/application_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -177,8 +177,8 @@ func (m *windowsApp) run() error {
for eventID := range m.parent.applicationEventListeners {
m.on(eventID)
}
// Emit application started event
applicationEvents <- &Event{
// EmitEvent application started event
applicationEvents <- &ApplicationEvent{
Id: uint(events.Windows.ApplicationStarted),
ctx: blankApplicationEventContext,
}
Expand Down Expand Up @@ -242,7 +242,7 @@ func (m *windowsApp) wndProc(hwnd w32.HWND, msg uint32, wParam, lParam uintptr)
if isDarkMode != m.isCurrentlyDarkMode {
eventContext := newApplicationEventContext()
eventContext.setIsDarkMode(isDarkMode)
applicationEvents <- &Event{
applicationEvents <- &ApplicationEvent{
Id: uint(events.Windows.SystemThemeChanged),
ctx: eventContext,
}
Expand Down
Loading

0 comments on commit 5cde12b

Please sign in to comment.