wails/v3/examples/print/main.go
Lea Anthony 2c9d23b040
fix(macos): fix print dialog not opening and add Window.Print() to runtime (#4789)
fix(macos): fix print dialog not opening and add Window.Print() to runtime (#4290)

The print dialog was not opening on macOS because the CGO windowPrint function was passing the wrong pointer type to NSPrintOperation's runOperationModalForWindow method. It was passing the raw void* window instead of the properly cast WebviewWindow* nsWindow.

This also adds a Window.Print() method to the JavaScript runtime, allowing frontend code to trigger the print dialog directly without needing a Go binding.

Changes:
- Fix webview_window_darwin.go to use nsWindow instead of window
- Add WindowPrint constant (51) and handler to messageprocessor_window.go
- Add Print() method to window.ts in the runtime
- Rebuild bundled runtime (runtime.js and runtime.debug.js)
- Add print example in v3/examples/print to demonstrate both Go API and JS runtime methods
- Update API documentation for Window.Print() in both Go and JavaScript references

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude <noreply@anthropic.com>
2025-12-14 15:04:54 +11:00

90 lines
1.8 KiB
Go

//go:build darwin
package main
import (
"embed"
"log"
"runtime"
"github.com/wailsapp/wails/v3/pkg/application"
)
//go:embed assets/*
var assets embed.FS
// PrintService provides print functionality to the frontend
type PrintService struct {
app *application.App
}
func (p *PrintService) Print() error {
if w := p.app.Window.Current(); w != nil {
log.Println("PrintService.Print() called")
return w.Print()
}
return nil
}
func main() {
// Only run on macOS
if runtime.GOOS != "darwin" {
log.Fatal("This test is only for macOS")
}
printService := &PrintService{}
app := application.New(application.Options{
Name: "Print Dialog Test",
Description: "Test for macOS print dialog (Issue #4290)",
Assets: application.AssetOptions{
Handler: application.BundledAssetFileServer(assets),
},
Services: []application.Service{
application.NewService(printService),
},
})
printService.app = app
// Create application menu
menu := app.NewMenu()
// File menu
fileMenu := menu.AddSubmenu("File")
fileMenu.Add("Print...").
SetAccelerator("CmdOrCtrl+P").
OnClick(func(ctx *application.Context) {
if w := app.Window.Current(); w != nil {
log.Println("Attempting to print...")
if err := w.Print(); err != nil {
log.Printf("Print error: %v", err)
} else {
log.Println("Print completed (or dialog dismissed)")
}
}
})
fileMenu.AddSeparator()
fileMenu.Add("Quit").
SetAccelerator("CmdOrCtrl+Q").
OnClick(func(ctx *application.Context) {
app.Quit()
})
app.Menu.Set(menu)
// Create main window
app.Window.NewWithOptions(application.WebviewWindowOptions{
Title: "Print Dialog Test - Issue #4290",
Width: 800,
Height: 600,
URL: "/index.html",
})
log.Println("Starting application. Use File > Print or Cmd+P to test print dialog.")
err := app.Run()
if err != nil {
log.Fatal(err)
}
}