diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 25e7aa565..f84b3e5af 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -377,6 +377,8 @@ jobs: # on Windows. - name: directory picker initial location run: go test ./internal/platform/windows ./app -run '^Test(FileDialogInitialDirectory|DriverInterceptsOpenDirectory)$' -count=1 -v + - name: Native directory watches + run: go test ./internal/filewatch -count=1 -timeout=1m - name: Material contracts and controls (WARP) run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview|QueuedMenuKeysLeaveTerminalCompositionWithItsOwner|MenuKeysPreserveSystemChordsAndShift|TerminalMenuStopsCapturingWhenWindowLosesFocus|DisabledIMEOffersMenuShortcutDuringComposition)' -count=1 -v - name: Offscreen incremental frame pixels diff --git a/app/app.go b/app/app.go index ccced95e7..7022a8f5d 100644 --- a/app/app.go +++ b/app/app.go @@ -149,6 +149,9 @@ type Config struct { // at window creation, even if it initially returns BackdropNone, allowing // later material changes without rebuilding the application. WindowBackdrop func() BackdropStyle + // Watermark is an input-transparent native overlay above all content, including + // web views. Unsupported native platforms ignore it; see CapabilityWindowWatermark. + Watermark Watermark // OnBackdropChange reports API activation initially and when it changes. // Windows may still substitute a solid color. Other platforms do not call // it. Update paint state without blocking; a change schedules a repaint. @@ -333,6 +336,11 @@ type StateSlot struct { } func (config Config) normalize() (Config, error) { + watermark, err := config.Watermark.normalized() + if err != nil { + return Config{}, err + } + config.Watermark = watermark if config.Title == "" { config.Title = defaultTitle } diff --git a/app/application.go b/app/application.go index e06cf227b..0c4af0d9f 100644 --- a/app/application.go +++ b/app/application.go @@ -23,6 +23,7 @@ var ErrNoWindows = errors.New("app: application opened no windows") // before resize/frame callbacks and repaints afterward. // An always-on-top host additionally implements SetAlwaysOnTop(bool) error. // A size-capable host additionally implements SetSize(int, int) error. +// A watermark-capable host additionally implements SetWatermark(Watermark) error. // A decoration-capable host additionally implements SetDecorated(bool, func(error)) error. type WindowControl interface { Close() @@ -36,6 +37,8 @@ type WindowControl interface { // Host is the event loop an Application runs on. The native backends provide // one over their platform adapters; a development runner such as package // headless provides one to drive an application without a window. +// A host may additionally implement ShowNotification(Notification, +// NotificationEvents) (NotificationControl, error) for interactive notifications. type Host interface { // OpenWindow creates and presents a window. closed must be called exactly // once, after the window has released its resources. @@ -248,8 +251,10 @@ type Application struct { // active is the window that last became the one the user works in, which is // where the application menu bar's commands take effect, as a native menu's // key equivalents do. - active *Window - openedAny bool + active *Window + openedAny bool + notifications map[*NotificationHandle]struct{} + notificationsClosed bool } // OpenWindow creates and presents one independent retained window. @@ -434,6 +439,7 @@ func (application *Application) SetProgress(fraction float32) { // goroutine. func (application *Application) Quit() { if application != nil && application.host != nil { + application.closeNotifications() application.host.Quit() } } diff --git a/app/application_native.go b/app/application_native.go index 0ec3ae514..134d48198 100644 --- a/app/application_native.go +++ b/app/application_native.go @@ -18,9 +18,16 @@ import ( // start the native application from main to satisfy AppKit's main-thread requirement. func RunApplication(start func(*Application) error) error { attendFaults() + var owned *Application + defer func() { + if owned != nil { + owned.closeNotifications() + } + }() if applicationRunner != nil { return applicationRunner(func(host Host) error { application := &Application{host: host} + owned = application if err := start(application); err != nil { return err } @@ -35,6 +42,7 @@ func RunApplication(start func(*Application) error) error { defer runtime.UnlockOSThread() return runNativeApplication(func(native platform.Application) error { application := &Application{host: nativeHost{native}} + owned = application if err := start(application); err != nil { return err } @@ -48,6 +56,8 @@ func RunApplication(start func(*Application) error) error { // nativeHost is the Host over a platform adapter. type nativeHost struct{ native platform.Application } +var _ notificationHost = nativeHost{} + func (host nativeHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func()) (WindowControl, error) { windowConfig, painter, cleanup, err := prepareNativeWindow(config, canvas) if err != nil { @@ -66,6 +76,11 @@ func (host nativeHost) OpenWindow(config Config, canvas *gfx.Canvas, closed func cleanup() return nil, err } + if config.Watermark.Text != "" { + if _, ok := window.(nativeWatermarkControl); !ok { + reportUnsupportedWatermark() + } + } // A command the runtime did not receive through an event handler, such as a // menu action, hands its result here: the painter carries it out and the // window's waker asks for the frame that shows it. @@ -89,6 +104,7 @@ var _ fullscreenControl = resultWindow{} var _ alwaysOnTopControl = resultWindow{} var _ shortcutCapturer = resultWindow{} var _ titleControl = resultWindow{} +var _ watermarkControl = resultWindow{} var _ windowIconControl = resultWindow{} var _ platform.WindowMover = resultWindow{} @@ -266,6 +282,14 @@ func (host nativeHost) Quit() { host.native.Quit() } func (host nativeHost) Post(fn func()) { host.native.Post(fn) } +func (window resultWindow) SetWatermark(value Watermark) error { + control, ok := window.WindowControl.(nativeWatermarkControl) + if !ok { + return fmt.Errorf("%w: window watermarks", ErrUnsupported) + } + return control.SetWatermark(value.platform()) +} + type nativeStatusItem struct{ item platform.StatusItem } func (item nativeStatusItem) SetIcon(icon StatusIcon) error { @@ -282,3 +306,11 @@ func (item nativeStatusItem) SetStatusHover(handler func(StatusAnchor, bool)) bo }) } func (item nativeStatusItem) RefreshMenu() { item.item.RefreshMenu() } + +func (host nativeHost) ShowNotification(value Notification, events NotificationEvents) (NotificationControl, error) { + cancel, err := nativeShowNotification(value, events) + if err != nil { + return nil, err + } + return &nativeNotificationControl{cancel: cancel}, nil +} diff --git a/app/capabilities.go b/app/capabilities.go index 4b072b23e..cae63c14e 100644 --- a/app/capabilities.go +++ b/app/capabilities.go @@ -63,6 +63,12 @@ const ( // them. Only Windows takes them; macOS and Linux file managers read files // by path and cannot ask for a paste's content later. CapabilityClipboardFilePromise + // CapabilityNotificationActivation means an application can own cancellable + // system notifications and receive activation while its loop is running. + CapabilityNotificationActivation + // CapabilityWindowWatermark means native text patterns can cover canvas and + // embedded native views without receiving input. + CapabilityWindowWatermark ) // Capabilities is a set of platform integrations. diff --git a/app/capabilities_native.go b/app/capabilities_native.go index 988d13dd1..9e88abdd5 100644 --- a/app/capabilities_native.go +++ b/app/capabilities_native.go @@ -42,6 +42,6 @@ func nativeCapabilities() Capabilities { } else { capabilities |= CapabilityWindowMaximize } - capabilities |= capabilityTransparentWindow + capabilities |= capabilityTransparentWindow | capabilityNotificationActivation | capabilityWindowWatermark return Capabilities(capabilities) } diff --git a/app/capability_notification_native.go b/app/capability_notification_native.go new file mode 100644 index 000000000..2c91627ad --- /dev/null +++ b/app/capability_notification_native.go @@ -0,0 +1,5 @@ +//go:build (darwin && !ios) || windows + +package app + +const capabilityNotificationActivation = CapabilityNotificationActivation diff --git a/app/capability_notification_other.go b/app/capability_notification_other.go new file mode 100644 index 000000000..2bf6cb7a3 --- /dev/null +++ b/app/capability_notification_other.go @@ -0,0 +1,5 @@ +//go:build (!darwin && !windows) || ios + +package app + +const capabilityNotificationActivation Capability = 0 diff --git a/app/capability_watermark_native.go b/app/capability_watermark_native.go new file mode 100644 index 000000000..6afcaa64a --- /dev/null +++ b/app/capability_watermark_native.go @@ -0,0 +1,5 @@ +//go:build (darwin && !ios) || windows + +package app + +const capabilityWindowWatermark = CapabilityWindowWatermark diff --git a/app/capability_watermark_other.go b/app/capability_watermark_other.go new file mode 100644 index 000000000..9c463da78 --- /dev/null +++ b/app/capability_watermark_other.go @@ -0,0 +1,5 @@ +//go:build (!darwin && !windows) || ios + +package app + +const capabilityWindowWatermark Capability = 0 diff --git a/app/content_window.go b/app/content_window.go index 740a43678..2993b6a40 100644 --- a/app/content_window.go +++ b/app/content_window.go @@ -126,3 +126,11 @@ func (content *ContentWindow) RequestClose() { content.Close() } } + +// SetWatermark updates the content window's native overlay, as Window.SetWatermark. +func (content *ContentWindow) SetWatermark(value Watermark) error { + if content == nil || content.window == nil { + return fmt.Errorf("app: content window is closed") + } + return content.window.SetWatermark(value) +} diff --git a/app/directory_watch.go b/app/directory_watch.go index 291ea70ed..0142033a4 100644 --- a/app/directory_watch.go +++ b/app/directory_watch.go @@ -25,9 +25,10 @@ type DirectoryChanges struct { // DirectoryWatch reports changes to the entries of one directory from the // operating system's own notification (inotify, FSEvents, ReadDirectoryChangesW). // -// It does not poll and keeps no timer. An open watch holds one system -// registration and one goroutine blocked on it; closing it releases both, and an -// application that opens none pays nothing. A change wakes the window thread +// It does not poll and keeps no timer. An open watch holds system registrations +// and one goroutine blocked on them. On Windows the watch also follows changes +// to the directory's name when the system lets it watch the parent directory. +// Closing the watch releases these resources. A change wakes the window thread // through the function given at the start, which only hands the news on (for // example Invalidator.Invalidate, whose Config.OnWake then reads it with // Changes). diff --git a/app/driver.go b/app/driver.go index b0aabe2da..db7e68d46 100644 --- a/app/driver.go +++ b/app/driver.go @@ -534,7 +534,7 @@ func (driver *Driver) Scroll(event gfx.ScrollEvent) error { } _, err := driver.painter.scroll(platform.ScrollEvent{ Modifiers: event.Modifiers | driver.heldModifiers(), X: event.X, Y: event.Y, - DeltaX: event.DeltaX, DeltaY: event.DeltaY, Precise: event.Precise, + DeltaX: event.DeltaX, DeltaY: event.DeltaY, Pages: event.Pages, Precise: event.Precise, }) return err } @@ -1123,6 +1123,8 @@ type Primitive struct { Layer uint16 // EdgeMask selects the boundary edges feathered for TrianglePrimitive. EdgeMask uint8 + // Coverage carries the original silhouette for a clipped stroke quad. + Coverage *gfx.StrokeCoverage // Shaded gives a TrianglePrimitive the colors Shade[0] and Shade[1] at // Points[1] and Points[2], Color being that of Points[0]; the color varies // linearly between them. @@ -1318,6 +1320,13 @@ func (driver *Driver) Snapshot() Snapshot { if rectangle.Kind == scene.KindTriangle { primitive.Kind = TrianglePrimitive primitive.EdgeMask = rectangle.EdgeMask + if source, ok := rectangle.StrokeCoverage(); ok { + coverage := &gfx.StrokeCoverage{EdgeMask: source.EdgeMask} + for index, point := range source.Points { + coverage.Points[index] = gfx.Point(point) + } + primitive.Coverage = coverage + } if rectangle.Shade.On { primitive.Shaded = true for index, color := range rectangle.Shade.Colors { diff --git a/app/notification.go b/app/notification.go new file mode 100644 index 000000000..58cb51f92 --- /dev/null +++ b/app/notification.go @@ -0,0 +1,213 @@ +package app + +import ( + "fmt" + "strings" + "sync" + "unicode/utf8" + + "github.com/vivaui/viva/internal/diag" +) + +// NotificationControl is the cancellable notification an optional Host supplies. +// Close requests native withdrawal and invalidates callbacks. It is idempotent +// and safe from any goroutine. A host returns a non-nil control on success. +type NotificationControl interface{ Close() } + +// Application delivers NotificationEvents on its event-loop thread. Hosts may +// signal their supplied callbacks from any thread; Application queues them. +// Both callbacks are optional. OnError reports asynchronous authorization or +// delivery failure; errors without a handler go to the diagnostic sink. +// Activation or failure consumes the handle, so only one terminal event runs. +type NotificationEvents struct { + OnActivate func() + OnError func(error) +} + +type notificationHost interface { + ShowNotification(Notification, NotificationEvents) (NotificationControl, error) +} + +// NotificationHandle owns one notification. Close requests withdrawal and discards +// queued callbacks. A callback already running may finish. It is nil-safe, +// idempotent and safe from any goroutine. Applications close handles whose +// targets become stale; Quit and the end of RunApplication close all remaining +// handles automatically. A native dismissal does not promise a terminal event. +type NotificationHandle struct { + mu sync.Mutex + closed bool + queued bool + control NotificationControl + application *Application + callback func() +} + +func (handle *NotificationHandle) Close() { handle.finish(false) } + +// finish claims a terminal event before releasing native ownership. No user or +// host code runs under either mutex, so Close and callbacks may be reentrant. +func (handle *NotificationHandle) finish(deliver bool) func() { + if handle == nil { + return nil + } + handle.mu.Lock() + if handle.closed { + handle.mu.Unlock() + return nil + } + handle.closed = true + control := handle.control + owner := handle.application + callback := handle.callback + handle.callback = nil + if !deliver { + callback = nil + } + handle.control = nil + handle.application = nil + handle.mu.Unlock() + if owner != nil { + owner.mu.Lock() + delete(owner.notifications, handle) + owner.mu.Unlock() + } + if control != nil { + control.Close() + } + return callback +} + +func (handle *NotificationHandle) attach(control NotificationControl) { + handle.mu.Lock() + closed := handle.closed + if !closed { + handle.control = control + } + handle.mu.Unlock() + if closed { + control.Close() + } +} + +// post bounds each handle to one queued terminal callback, even for a custom +// host that races activation against failure. Close can still cancel that post. +func (handle *NotificationHandle) post(callback func()) { + handle.mu.Lock() + if handle.closed || handle.queued { + handle.mu.Unlock() + return + } + handle.queued = true + handle.callback = callback + owner := handle.application + handle.mu.Unlock() + // The queue retains only this handle. Close clears callback and owner even + // if a custom host stops its loop before processing the queued method. + owner.Post(handle.deliver) +} + +func (handle *NotificationHandle) deliver() { + if callback := handle.finish(true); callback != nil { + callback() + } +} + +// ShowNotification requests an interactive system notification. Call it from +// startup or a window callback, like AddStatusItem. The request does not wait +// for authorization UI or user interaction. Success accepts a request, rather than +// promising the OS will display it; system policy may suppress it. +// +// Content must be nonblank valid UTF-8 without NUL. Native limits may truncate +// title/body. The returned handle is application-owned until activation, error +// or Close. Callbacks run on the event loop and may open or restore windows. +// CapabilityNotificationActivation reports native support. Custom/headless +// hosts opt in with ShowNotification(Notification, NotificationEvents) +// (NotificationControl,error); unsupported hosts return ErrUnsupported. +// +// macOS requires an application bundle identifier and system permission. Windows +// uses notification-area balloons, not a persistent toast-activation service. +// Activation works only while this process and its application loop are alive. +// SendNotification remains the compatible title/body-only API. +func (application *Application) ShowNotification(value Notification, events NotificationEvents) (*NotificationHandle, error) { + if application == nil || application.host == nil { + return nil, fmt.Errorf("app: application is not running") + } + if !utf8.ValidString(value.Title) || !utf8.ValidString(value.Body) || strings.ContainsRune(value.Title, 0) || strings.ContainsRune(value.Body, 0) { + return nil, fmt.Errorf("app: notification text must be valid UTF-8 without NUL") + } + if strings.TrimSpace(value.Title) == "" && strings.TrimSpace(value.Body) == "" { + return nil, fmt.Errorf("app: notification requires title or body") + } + host, ok := application.host.(notificationHost) + if !ok { + return nil, fmt.Errorf("%w: notification activation", ErrUnsupported) + } + handle := &NotificationHandle{application: application} + application.mu.Lock() + if application.notificationsClosed { + application.mu.Unlock() + return nil, fmt.Errorf("app: application notifications are closed") + } + if application.notifications == nil { + application.notifications = make(map[*NotificationHandle]struct{}) + } + application.notifications[handle] = struct{}{} + application.mu.Unlock() + control, err := host.ShowNotification(value, NotificationEvents{ + OnActivate: func() { handle.post(events.OnActivate) }, + OnError: func(err error) { + if err == nil { + err = fmt.Errorf("app: notification host reported an unspecified failure") + } + handle.post(func() { + if events.OnError != nil { + events.OnError(err) + } else { + reportNotificationError(err) + } + }) + }, + }) + if err != nil { + handle.Close() + return nil, err + } + if control == nil { + handle.Close() + return nil, fmt.Errorf("app: notification host returned no control") + } + handle.attach(control) + return handle, nil +} + +func (application *Application) closeNotifications() { + application.mu.Lock() + application.notificationsClosed = true + handles := application.notifications + application.notifications = nil + application.mu.Unlock() + for handle := range handles { + handle.Close() + } +} + +// nativeNotificationControl adapts a platform cancellation without leaking an +// internal type through the optional public Host contract. +type nativeNotificationControl struct { + once sync.Once + cancel func() +} + +func (control *nativeNotificationControl) Close() { + control.once.Do(func() { + if control.cancel != nil { + control.cancel() + } + }) +} + +func reportNotificationError(err error) { + if err != nil { + diag.Report(diag.Error, "notification", "delivery-failed", err.Error()) + } +} diff --git a/app/notification_darwin.go b/app/notification_darwin.go new file mode 100644 index 000000000..f9d3ec173 --- /dev/null +++ b/app/notification_darwin.go @@ -0,0 +1,21 @@ +//go:build darwin && !ios + +package app + +import ( + "github.com/vivaui/viva/internal/platform" + darwinplatform "github.com/vivaui/viva/internal/platform/darwin" +) + +func nativeShowNotification(notification Notification, events NotificationEvents) (func(), error) { + failed := func(err error) { + err = darwinNotificationError(err) + if events.OnError != nil { + events.OnError(err) + } else { + reportNotificationError(err) + } + } + cancel, err := darwinplatform.ShowNotification(notification.Title, notification.Body, platform.NotificationEvents{Activated: events.OnActivate, Failed: failed}) + return cancel, darwinNotificationError(err) +} diff --git a/app/notification_test.go b/app/notification_test.go new file mode 100644 index 000000000..4d2af2fc7 --- /dev/null +++ b/app/notification_test.go @@ -0,0 +1,249 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "sync" + "sync/atomic" + "testing" + + "github.com/vivaui/viva/gfx" +) + +type notificationTestControl struct{ closed atomic.Int32 } + +func (control *notificationTestControl) Close() { control.closed.Add(1) } + +type notificationTestHost struct { + fakeHost + mu sync.Mutex + posts []func() + events []NotificationEvents + controls []*notificationTestControl + show func(NotificationEvents) + err error +} + +func (host *notificationTestHost) Post(fn func()) { + host.mu.Lock() + host.posts = append(host.posts, fn) + host.mu.Unlock() +} +func (host *notificationTestHost) drain() { + for { + host.mu.Lock() + if len(host.posts) == 0 { + host.mu.Unlock() + return + } + fn := host.posts[0] + host.posts = host.posts[1:] + host.mu.Unlock() + fn() + } +} +func (host *notificationTestHost) ShowNotification(_ Notification, events NotificationEvents) (NotificationControl, error) { + host.events = append(host.events, events) + if host.err != nil { + return nil, host.err + } + control := ¬ificationTestControl{} + host.controls = append(host.controls, control) + if host.show != nil { + host.show(events) + } + return control, nil +} + +func TestNotificationDispatchesOnLoopAndConsumesOnlyOneEvent(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + calls := 0 + handle, err := application.ShowNotification(Notification{Title: "测试通知"}, NotificationEvents{OnActivate: func() { calls++; application.Post(func() { calls++ }) }}) + if err != nil { + t.Fatal(err) + } + host.events[0].OnActivate() + host.events[0].OnActivate() + host.events[0].OnError(errors.New("late failure")) + if calls != 0 { + t.Fatal("native callback changed UI state before the event loop") + } + host.drain() + if calls != 2 || host.controls[0].closed.Load() != 1 || len(application.notifications) != 0 { + t.Fatal("terminal event did not consume ownership exactly once", calls) + } + handle.Close() + if host.controls[0].closed.Load() != 1 || handle.application != nil || handle.callback != nil { + t.Fatal("consumed control retained its owner or closed twice") + } +} + +func TestNotificationCloseCancelsQueuedActivationConcurrently(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + calls := 0 + handle, err := application.ShowNotification(Notification{Body: "body"}, NotificationEvents{OnActivate: func() { calls++ }}) + if err != nil { + t.Fatal(err) + } + host.events[0].OnActivate() + var jobs sync.WaitGroup + for range 32 { + jobs.Add(1) + go func() { defer jobs.Done(); handle.Close() }() + } + jobs.Wait() + host.drain() + if calls != 0 || host.controls[0].closed.Load() != 1 { + t.Fatal("Close did not discard queued callbacks") + } + var empty *NotificationHandle + empty.Close() + (&NotificationHandle{}).Close() +} + +func TestNotificationErrorsValidationAndOptionalCallbacks(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + for _, value := range []Notification{{}, {Title: "\x00"}, {Body: string([]byte{0xff})}} { + if _, err := application.ShowNotification(value, NotificationEvents{}); err == nil { + t.Fatal("invalid content reached host") + } + } + if len(host.events) != 0 { + t.Fatal("invalid request reached host") + } + failure := errors.New("authorization denied") + got := error(nil) + handle, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{OnError: func(err error) { got = err }}) + if err != nil { + t.Fatal(err) + } + host.events[0].OnError(failure) + host.drain() + handle.Close() + if got != failure || len(application.notifications) != 0 { + t.Fatal("asynchronous error lost ownership or identity", got) + } + host.err = failure + if _, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{}); err != failure || len(application.notifications) != 0 { + t.Fatal("immediate failure retained a handle", err) + } + host.err = nil + handle, err = application.ShowNotification(Notification{Body: "callbacks optional"}, NotificationEvents{}) + if err != nil { + t.Fatal(err) + } + handle.Close() + unsupported := &Application{host: &fakeHost{}} + if _, err := unsupported.ShowNotification(Notification{Title: "test"}, NotificationEvents{}); !errors.Is(err, ErrUnsupported) { + t.Fatal("host support was inferred from the OS", err) + } +} + +func TestNotificationSynchronousHostEventAndCloseBeforeAttach(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + calls := 0 + host.show = func(events NotificationEvents) { events.OnActivate(); application.Quit() } + _, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{OnActivate: func() { calls++ }}) + if err != nil { + t.Fatal(err) + } + host.drain() + if calls != 0 || host.controls[0].closed.Load() != 1 || len(application.notifications) != 0 { + t.Fatal("late control escaped application shutdown") + } + if _, err := application.ShowNotification(Notification{Title: "after quit"}, NotificationEvents{}); err == nil { + t.Fatal("quit application accepted notification") + } +} + +func TestNotificationRunApplicationCleanup(t *testing.T) { + host := ¬ificationTestHost{} + previous := applicationRunner + defer func() { applicationRunner = previous }() + applicationRunner = func(start func(Host) error) error { return start(host) } + calls := 0 + err := RunApplication(func(application *Application) error { + if _, err := application.OpenWindow(Config{Title: "test"}, &gfx.Canvas{}); err != nil { + return err + } + _, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{OnActivate: func() { calls++ }}) + return err + }) + defer func() { + for _, window := range host.windows { + window.Close() + } + }() + if err != nil { + t.Fatal(err) + } + host.events[0].OnActivate() + host.drain() + if calls != 0 || host.controls[0].closed.Load() != 1 { + t.Fatal("notification survived the application runner") + } +} + +func TestNotificationConcurrentCallbacksAndCancellation(t *testing.T) { + host := ¬ificationTestHost{} + application := &Application{host: host} + calls := atomic.Int32{} + handle, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{OnActivate: func() { calls.Add(1) }, OnError: func(error) { calls.Add(1) }}) + if err != nil { + t.Fatal(err) + } + events := host.events[0] + var jobs sync.WaitGroup + for index := range 48 { + jobs.Add(1) + go func() { + defer jobs.Done() + switch index % 3 { + case 0: + handle.Close() + case 1: + events.OnActivate() + case 2: + events.OnError(errors.New("failed")) + } + }() + } + jobs.Wait() + host.drain() + if calls.Load() != 0 || host.controls[0].closed.Load() != 1 { + t.Fatal("cancellation lost the callback race") + } +} + +func TestNotificationStartupFailureCleansUp(t *testing.T) { + for _, failStartup := range []bool{true, false} { + t.Run(map[bool]string{true: "start error", false: "no window"}[failStartup], func(t *testing.T) { + host := ¬ificationTestHost{} + previous := applicationRunner + defer func() { applicationRunner = previous }() + applicationRunner = func(start func(Host) error) error { return start(host) } + sentinel := errors.New("startup failed") + err := RunApplication(func(application *Application) error { + if _, err := application.ShowNotification(Notification{Title: "test"}, NotificationEvents{}); err != nil { + return err + } + if failStartup { + return sentinel + } + return nil + }) + want := sentinel + if !failStartup { + want = ErrNoWindows + } + if err != want || host.controls[0].closed.Load() != 1 { + t.Fatal("startup failure leaked notification", err) + } + }) + } +} diff --git a/app/notification_unsupported.go b/app/notification_unsupported.go new file mode 100644 index 000000000..2a05f8ad5 --- /dev/null +++ b/app/notification_unsupported.go @@ -0,0 +1,7 @@ +//go:build (!darwin && !windows) || ios + +package app + +func nativeShowNotification(Notification, NotificationEvents) (func(), error) { + return nil, ErrUnsupported +} diff --git a/app/notification_windows.go b/app/notification_windows.go new file mode 100644 index 000000000..f2e36d390 --- /dev/null +++ b/app/notification_windows.go @@ -0,0 +1,16 @@ +package app + +import ( + "github.com/vivaui/viva/internal/platform" + windowsplatform "github.com/vivaui/viva/internal/platform/windows" +) + +func nativeShowNotification(notification Notification, events NotificationEvents) (func(), error) { + return windowsplatform.ShowNotification(notification.Title, notification.Body, platform.NotificationEvents{Activated: events.OnActivate, Failed: func(err error) { + if events.OnError != nil { + events.OnError(err) + } else { + reportNotificationError(err) + } + }}) +} diff --git a/app/painter.go b/app/painter.go index d312cf628..42ade8fed 100644 --- a/app/painter.go +++ b/app/painter.go @@ -127,8 +127,16 @@ type painter struct { // coordinates: a hit's position-dependent picture is asked for at this // place, so it follows the pointer without a repaint. pointerAt gfx.Point - scrollX float32 - scrollY float32 + // pointerPresent distinguishes a pointer in the window from the initial + // state and the coordinates carried by an exit. + pointerPresent bool + // hoverFromLayout distinguishes an updated highlight from a pointer entry. + hoverFromLayout bool + // pointerNeedsHit marks a viewport resize, which can move the window edge + // across the pointer even if the page declares the same regions. + pointerNeedsHit bool + scrollX float32 + scrollY float32 // scheduleFrame asks the runtime for one more frame, after at least the // delay, while a transition is in flight or the application asked for one. scheduleFrame func(delay time.Duration) @@ -225,6 +233,7 @@ func (painter *painter) resize(size platform.Size) (platform.Frame, error) { next := gfx.Size{Width: size.Width, Height: size.Height} changed := next != painter.size painter.size, painter.scale = next, size.Scale + painter.pointerNeedsHit = painter.pointerNeedsHit || changed if changed && painter.onResize != nil { painter.onResize(next) } @@ -285,8 +294,8 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo painter.pointer.Exit() event.Kind = platform.PointerExit } - if event.Kind == platform.PointerMove && painter.pointerOutside && - event.X >= 0 && event.Y >= 0 && event.X < painter.size.Width && event.Y < painter.size.Height { + painter.pointerPresent = event.Kind != platform.PointerExit + if event.Kind == platform.PointerMove && painter.pointerOutside && painter.pointerAtInside() { painter.pointerOutside = false } if event.Kind == platform.PointerExit && !painter.pointer.PressTarget().IsZero() { @@ -295,16 +304,16 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo // exactly where the user needs it: past the edge of the terminal, the // list or the window. The exit is delivered when the button is released. painter.pointerOutside = true - painter.onSurface = false - if painter.pointer.Hovered().IsZero() { + painter.trackEdge(false) + if !painter.updateHover(false, false) { return platform.Frame{}, nil } - painter.pointer.SetHovered(gfx.ID{}) - painter.pointer.SetHoveredRole(gfx.Role(0)) return painter.repaintAfterInput() } beforeHovered, beforePressed := painter.pointer.Hovered(), painter.pointer.Pressed() - beforeSurface := painter.onSurface + beforeRole, beforeSurface := painter.pointer.HoveredRole(), painter.onSurface + beforeHoverFromLayout := painter.hoverFromLayout && !beforeHovered.IsZero() + painter.hoverFromLayout = false beforeFocus, beforeKeyboard := painter.focus.Focused(), painter.focus.KeyboardFocus() passes := event.Kind == platform.PointerDown && (event.Button == gfx.PointerButtonSecondary && painter.focus.Router().PassesSecondary(event.X, event.Y) || @@ -352,7 +361,8 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo } if painter.pointer.Hovered() == beforeHovered && painter.pointer.Pressed() == beforePressed && - painter.onSurface == beforeSurface && + painter.pointer.HoveredRole() == beforeRole && painter.onSurface == beforeSurface && + !beforeHoverFromLayout && painter.focus.Focused() == beforeFocus && painter.focus.KeyboardFocus() == beforeKeyboard && !focusChanged && !result.Repaint { if edgeChanged { @@ -373,18 +383,10 @@ func (painter *painter) pointerInputOf(event platform.PointerEvent, handled *boo // state, the application and the controls' event pass. It returns what the // application answered and whether focus and the pointer's edge state changed. func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.EventResult, focusChanged, edgeChanged bool) { - painter.pointer.SetHovered(gfx.ID{}) - painter.pointer.SetHoveredRole(gfx.Role(0)) - painter.onSurface = false - if event.Kind != platform.PointerExit { - secondaryPress := event.Kind == platform.PointerDown && event.Button == gfx.PointerButtonSecondary - if target, ok, onSurface := painter.focus.Router().PointerAt(event.X, event.Y, secondaryPress); ok || onSurface { - painter.pointer.SetHovered(target.Target) - painter.pointer.SetHoveredRole(target.Role) - painter.onSurface = onSurface - } - } - edgeChanged = painter.trackEdge(event) + secondaryPress := event.Kind == platform.PointerDown && event.Button == gfx.PointerButtonSecondary + inside := painter.pointerPresent && !painter.pointerOutside && painter.pointerAtInside() + painter.updateHover(inside, secondaryPress) + edgeChanged = painter.trackEdge(inside) if event.Kind == platform.PointerDown { painter.pointer.Down(event.Button) @@ -419,6 +421,26 @@ func (painter *painter) pointerStep(event platform.PointerEvent) (result gfx.Eve return result, focusChanged, edgeChanged } +func (painter *painter) pointerAtInside() bool { + return painter.pointerAt.X >= 0 && painter.pointerAt.Y >= 0 && + painter.pointerAt.X < painter.size.Width && painter.pointerAt.Y < painter.size.Height +} + +// updateHover resolves the pointer against the current routing regions. Press +// capture and application pointer events are independent of this lookup. +func (painter *painter) updateHover(inside, secondaryPress bool) bool { + var hit input.Region + var onSurface bool + if inside { + hit, _, onSurface = painter.focus.Router().PointerAt(painter.pointerAt.X, painter.pointerAt.Y, secondaryPress) + } + changed := painter.pointer.Hovered() != hit.Target || painter.pointer.HoveredRole() != hit.Role || painter.onSurface != onSurface + painter.pointer.SetHovered(hit.Target) + painter.pointer.SetHoveredRole(hit.Role) + painter.onSurface = onSurface + return changed +} + // placeCaret puts the caret of the focused text field where a press, or the drag // of one, lands, when the field lays its rows out itself (gfx.TextPlacement): the // platform editor knows one line only and leaves such a field to this. A press @@ -720,7 +742,7 @@ func (painter *painter) key(event platform.KeyEvent) (platform.Frame, error) { activated = true } painter.focus.Refresh() - if event.Key == input.KeyTab { + if !response.Handled && event.Key == input.KeyTab { painter.focus.SetKeyboardFocus(!painter.focus.Focused().IsZero()) } focusChanged := painter.applyEventResult(response) @@ -942,7 +964,7 @@ func (painter *painter) applyScroll(event platform.ScrollEvent) bool { if painter.onScroll != nil { response = painter.onScroll(gfx.ScrollEvent{ Phase: event.Phase, Modifiers: gfx.Modifiers(event.Modifiers), X: event.X, Y: event.Y, - DeltaX: event.DeltaX, DeltaY: event.DeltaY, Viewport: painter.size, Target: target, Precise: event.Precise, + DeltaX: event.DeltaX, DeltaY: event.DeltaY, Pages: event.Pages, Viewport: painter.size, Target: target, Precise: event.Precise, }) } focusChanged := painter.applyEventResult(response) @@ -1050,7 +1072,7 @@ func (painter *painter) repaint() (platform.Frame, error) { painter.noteFrameStart() } painter.paintCanvas() - painter.settleFocus() + painter.settleInteraction() frame, err := painter.publish() if err != nil { return platform.Frame{}, err @@ -1094,27 +1116,40 @@ const ( focusReused ) -// maxFocusPasses bounds the paints settleFocus adds to one frame: a page whose -// every paint moves the focus somewhere new shows the last move. -const maxFocusPasses = 2 +// maxInteractionRepaints bounds the work for a page where paint keeps moving +// the focused or hovered target. +const maxInteractionRepaints = 2 -// settleFocus applies the focus changes the paint itself made, by an Autofocus -// hit that appeared, a focus request or release, a returning scope that closed, -// a modal that opened or closed, or a request carried from the event, and paints -// again when the focus moved, so the frame shows the focus it routes keys to. -func (painter *painter) settleFocus() { +// settleInteraction syncs focus and the pointer with the regions just painted. +// A scroll or layout change can move hits under a stationary pointer. Paint +// again if these regions change the state that the frame should show. +func (painter *painter) settleInteraction() { if painter.paint == nil { return } - for range maxFocusPasses { - if !painter.regionsNeedSync() { + needsPointerHit := painter.pointerNeedsHit + painter.pointerNeedsHit = false + synced := false + for pass := 0; ; pass++ { + before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus() + // After an intermediate paint, the router may differ from the last + // published regions even if the new paint restored those regions. + if synced || painter.regionsNeedSync() { + painter.focus.Sync(painter.canvas) + painter.focusSettled = focusSynced + synced = true + } else { painter.focusSettled = focusReused - return } - before, beforeVisible := painter.focus.Focused(), painter.focus.KeyboardFocus() - painter.focus.Sync(painter.canvas) - painter.focusSettled = focusSynced - if painter.focus.Focused() == before && painter.focus.KeyboardFocus() == beforeVisible { + hoverChanged := false + if painter.pointerPresent && (synced || needsPointerHit) { + inside := !painter.pointerOutside && painter.pointerAtInside() + hoverChanged = painter.updateHover(inside, false) + painter.hoverFromLayout = painter.hoverFromLayout || hoverChanged + painter.trackEdge(inside) + } + if pass == maxInteractionRepaints || + (!hoverChanged && painter.focus.Focused() == before && painter.focus.KeyboardFocus() == beforeVisible) { return } painter.paintCanvas() @@ -1144,6 +1179,7 @@ func (painter *painter) paintCanvas() { } focused, visible := painter.focus.PaintTarget() painter.canvas.SetInteraction(painter.pointer.Hovered(), painter.pointer.Pressed(), focused, visible) + painter.canvas.SetHoverFromLayout(painter.hoverFromLayout) painter.canvas.SetHoveredRole(painter.pointer.HoveredRole()) painter.canvas.SetPointerOnSurface(painter.onSurface) painter.canvas.SetTitlebarInsets(painter.titlebarInsets()) diff --git a/app/painter_test.go b/app/painter_test.go index cbe959775..75b64ad7a 100644 --- a/app/painter_test.go +++ b/app/painter_test.go @@ -767,6 +767,85 @@ func TestPointerHoverEntersAndExitsOnce(t *testing.T) { } } +func TestStationaryPointerFollowsNewHitGeometry(t *testing.T) { + var canvas gfx.Canvas + var events, paints int + var covered bool + config := Config{Title: "stationary pointer", Width: 100, Height: 100} + config.OnPointer = func(gfx.PointerEvent) gfx.EventResult { + events++ + return gfx.EventResult{} + } + config.Paint = func(canvas *gfx.Canvas, _ gfx.Size) { + paints++ + canvas.HitWithOptions(gfx.Item(7), gfx.Rect{Y: -canvas.ScrollY(), Width: 40, Height: 20}, "First", gfx.HitOptions{Cursor: gfx.PointerCursorHand}) + canvas.HitWithOptions(gfx.Item(8), gfx.Rect{Y: 20 - canvas.ScrollY(), Width: 40, Height: 20}, "Second", gfx.HitOptions{Role: gfx.RoleTextField, Cursor: gfx.PointerCursorText}) + if covered { + canvas.BlockSurface(gfx.Rect{Width: 40, Height: 20}) + } + } + painter := newTestPainter(t, &canvas, config) + check := func(target gfx.ID, role gfx.Role, cursor Cursor, onSurface bool) { + t.Helper() + if canvas.Hovered() != target || canvas.HoveredRole() != role || painter.cursor != cursor || canvas.PointerOnSurface() != onSurface { + t.Fatalf("painted hover = %v, role = %v, cursor = %v, surface = %v, want %v, %v, %v, %v", + canvas.Hovered(), canvas.HoveredRole(), painter.cursor, canvas.PointerOnSurface(), target, role, cursor, onSurface) + } + } + check(gfx.ID{}, 0, CursorArrow, false) + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerMove, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + check(gfx.Item(7), gfx.RoleButton, CursorHand, false) + + if _, err := painter.scroll(platform.ScrollEvent{X: 10, Y: 10, DeltaY: 20}); err != nil { + t.Fatal(err) + } + check(gfx.Item(8), gfx.RoleTextField, CursorText, false) + if canvas.HoverCrossed() || !canvas.HoverFromLayout() { + t.Fatal("scrolling under the pointer should update hover without a pointer entry") + } + + covered = true + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + check(gfx.ID{}, 0, CursorArrow, true) + if events != 1 { + t.Fatalf("scroll and repaints sent pointer events, got %d events", events) + } + before := paints + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + if paints != before+1 { + t.Fatalf("stable geometry required %d paints, want one", paints-before) + } + + covered = false + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + check(gfx.Item(8), gfx.RoleTextField, CursorText, false) + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerMove, X: 11, Y: 10}); err != nil { + t.Fatal(err) + } + if !canvas.HoverCrossed() || canvas.HoverFromLayout() { + t.Fatal("moving over a laid-out hover should register its first pointer entry") + } + + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerExit}); err != nil { + t.Fatal(err) + } + covered = false + // An exit carries no useful coordinates. A later paint must not treat + // its zero position as a pointer that moved onto the exposed item. + if _, err := painter.repaint(); err != nil { + t.Fatal(err) + } + check(gfx.ID{}, 0, CursorArrow, false) +} + // A drag off a surface and out of the window ends the surface state even when no // hit is hovered: the early return must not leave the host's copy of the flag set // for the next paint. @@ -1091,6 +1170,40 @@ func TestKeyTabTraversesFocusAndEnterActivates(t *testing.T) { } } +func TestHandledKeyTabDoesNotRevealKeyboardFocus(t *testing.T) { + var canvas gfx.Canvas + config := Config{ + Title: "test", Width: 100, Height: 100, + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(7), gfx.Rect{X: 0, Y: 0, Width: 50, Height: 20}, "Terminal", gfx.HitOptions{Role: gfx.RoleTerminal}) + canvas.HitWithLabel(gfx.Item(8), gfx.Rect{X: 0, Y: 40, Width: 50, Height: 20}, "Cancel") + }, + OnKey: func(event gfx.KeyEvent) gfx.EventResult { + if event.Key == gfx.KeyTab && event.Target == gfx.Item(7) { + return gfx.EventResult{Handled: true} + } + return gfx.EventResult{} + }, + } + painter := newTestPainter(t, &canvas, config) + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerDown, Button: gfx.PointerButtonPrimary, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + if _, err := painter.pointerEvent(platform.PointerEvent{Kind: platform.PointerUp, Button: gfx.PointerButtonPrimary, X: 10, Y: 10}); err != nil { + t.Fatal(err) + } + if painter.focus.Focused() != gfx.Item(7) || painter.focus.KeyboardFocus() { + t.Fatalf("after click: focused=%v keyboard=%v", painter.focus.Focused(), painter.focus.KeyboardFocus()) + } + + if _, err := painter.key(platform.KeyEvent{Key: input.KeyTab}); err != nil { + t.Fatal(err) + } + if painter.focus.Focused() != gfx.Item(7) || painter.focus.KeyboardFocus() || !canvas.FocusVisible().IsZero() { + t.Fatalf("handled Tab changed focus state: focused=%v keyboard=%v visible=%v", painter.focus.Focused(), painter.focus.KeyboardFocus(), canvas.FocusVisible()) + } +} + func TestAccessibilityNodesFollowHitsAndFocus(t *testing.T) { var canvas gfx.Canvas canvas.HitWithLabel(gfx.Item(7), gfx.Rect{X: 0, Y: 0, Width: 50, Height: 20}, "Save") diff --git a/app/run.go b/app/run.go index 783f4cd8a..9c74ba81b 100644 --- a/app/run.go +++ b/app/run.go @@ -19,10 +19,14 @@ func Run(config Config) error { return err } + if normalized.Watermark.Text != "" && !Supports(CapabilityWindowWatermark) { + reportUnsupportedWatermark() + } runtime.LockOSThread() defer runtime.UnlockOSThread() return runNative(platform.Config{ + Watermark: normalized.Watermark.platform(), Title: normalized.Title, Class: normalized.Class, Icon: normalized.Icon.platform(), diff --git a/app/run_canvas.go b/app/run_canvas.go index 6beb89fac..db3443e18 100644 --- a/app/run_canvas.go +++ b/app/run_canvas.go @@ -27,6 +27,9 @@ func RunCanvas(config Config, canvas *gfx.Canvas) error { if err != nil { return err } + if normalized.Watermark.Text != "" && !Supports(CapabilityWindowWatermark) { + reportUnsupportedWatermark() + } if normalized.TextInput != nil && !nativeTextInputSupported { return fmt.Errorf("%w: native text input", ErrUnsupported) } @@ -173,6 +176,7 @@ func nativeWindowConfig(normalized *Config, painter *painter) (platform.Config, closeHandler = platform.CloseRequestHandler(normalized.OnCloseRequest) } config := platform.Config{ + Watermark: normalized.Watermark.platform(), Actions: painter.windowActions(), TextInput: painter.initialTextInput(), TakeTextMenu: painter.textMenuTaker(), diff --git a/app/watermark.go b/app/watermark.go new file mode 100644 index 000000000..67c95cd92 --- /dev/null +++ b/app/watermark.go @@ -0,0 +1,78 @@ +package app + +import ( + "fmt" + "sync" + + "github.com/vivaui/viva/gfx" + + "github.com/vivaui/viva/internal/diag" + "github.com/vivaui/viva/internal/platform" +) + +// Watermark is a retained, input-transparent single-line text pattern above canvas and native +// views. Text is centered in each tile using font metrics, then the pattern is +// rotated by Angle degrees in the content's top-left, Y-down coordinate system. +// Zero sizes use 12pt text and a 240 by 180 logical-pixel tile. A zero Color uses +// neutral gray at 12% opacity; other colors are linear RGBA, as Config.ClearColor. +// FontWeight uses gfx.WeightLight through gfx.WeightBold. FontFamily optionally +// names an installed family, with native fallback; empty uses the system font. +// Typography is explicit and independent of the canvas's interface font setting. +// Text is limited to 16 KiB, font size to 4096 logical pixels and tile sides to +// 8192 logical pixels; native backing tiles are additionally limited to 16 Mpixels. +// Empty Text disables the overlay. Use Supports(CapabilityWindowWatermark) to +// check native support; headless hosts may record the configuration for tests. +type Watermark struct { + Text, FontFamily string + Color Color + FontSize, FontWeight, Angle float32 + TileWidth, TileHeight float32 + Insets gfx.Insets +} + +func (w Watermark) platform() platform.Watermark { + return platform.Watermark{Text: w.Text, FontFamily: w.FontFamily, Color: platform.Color(w.Color), FontSize: w.FontSize, FontWeight: w.FontWeight, Angle: w.Angle, TileWidth: w.TileWidth, TileHeight: w.TileHeight, Insets: w.Insets} +} + +func (w Watermark) normalized() (Watermark, error) { + value, err := platform.NormalizeWatermark(w.platform()) + if err != nil { + return Watermark{}, err + } + return Watermark{Text: value.Text, FontFamily: value.FontFamily, Color: Color(value.Color), FontSize: value.FontSize, FontWeight: value.FontWeight, Angle: value.Angle, TileWidth: value.TileWidth, TileHeight: value.TileHeight, Insets: value.Insets}, nil +} + +// Hosts implement this optional capability using the public value; application +// hosts outside Viva cannot import internal/platform. +type watermarkControl interface{ SetWatermark(Watermark) error } +type nativeWatermarkControl interface { + SetWatermark(platform.Watermark) error +} + +// SetWatermark replaces the retained overlay. Calls are safe from any goroutine; +// native changes run on the window thread, and Windows queues the latest request. +// A successful return accepts the request, not completion of native rendering. +// Invalid requests change nothing; asynchronous native failures use the diagnostic +// sink. Unsupported hosts return an error wrapping ErrUnsupported. +func (window *Window) SetWatermark(value Watermark) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("app: window is closed") + } + value, err := value.normalized() + if err != nil { + return err + } + control, ok := window.control.(watermarkControl) + if !ok { + return fmt.Errorf("%w: window watermarks", ErrUnsupported) + } + return control.SetWatermark(value) +} + +var unsupportedWatermarkNotice sync.Once + +func reportUnsupportedWatermark() { + unsupportedWatermarkNotice.Do(func() { + diag.Report(diag.Debug, "window", "watermark-unsupported", "native window watermarks are unsupported by this host") + }) +} diff --git a/app/watermark_test.go b/app/watermark_test.go new file mode 100644 index 000000000..36fbc78df --- /dev/null +++ b/app/watermark_test.go @@ -0,0 +1,93 @@ +//go:build darwin || windows || linux + +package app + +import ( + "errors" + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +type watermarkTestControl struct { + fakeWindow + values []platform.Watermark +} + +func (control *watermarkTestControl) SetWatermark(value platform.Watermark) error { + control.values = append(control.values, value) + return nil +} + +func TestWatermarkDelegatesThroughResultWindowAndRejectsInvalidChanges(t *testing.T) { + control := &watermarkTestControl{} + window := &Window{control: resultWindow{WindowControl: control}} + value := Watermark{Text: "测试用户 10086", Color: Color{Alpha: 0.1}, FontWeight: -0.4} + if err := window.SetWatermark(value); err != nil { + t.Fatal(err) + } + if len(control.values) != 1 || control.values[0].Text != value.Text || control.values[0].FontSize != 12 { + t.Fatal("optional capability lost in native wrapper", control.values) + } + value.Insets.Left = -1 + if err := window.SetWatermark(value); err == nil || len(control.values) != 1 { + t.Fatal("invalid change reached host") + } + window.closed.Store(true) + if err := window.SetWatermark(Watermark{}); err == nil { + t.Fatal("closed window accepted change") + } + unsupported := &Window{control: resultWindow{WindowControl: &fakeWindow{}}} + if err := unsupported.SetWatermark(Watermark{}); !errors.Is(err, ErrUnsupported) { + t.Fatal("unsupported host lost sentinel", err) + } +} + +func TestWatermarkInitialConfigNormalization(t *testing.T) { + value, err := (Config{Watermark: Watermark{Text: "测试用户 10086", Color: Color{Alpha: 0.1}}}).normalize() + if err != nil || value.Watermark.FontSize != 12 { + t.Fatal("initial watermark not normalized", err, value.Watermark) + } + _, err = (Config{Watermark: Watermark{Text: "bad\x00value"}}).normalize() + if err == nil { + t.Fatal("invalid initial text accepted") + } +} + +func TestWatermarkReachesNativeWindowConfig(t *testing.T) { + value := Watermark{Text: "测试用户 10086", Color: Color{Alpha: 0.1}, Insets: gfx.Insets{Top: 42, Left: 120}} + normalized, err := (Config{Watermark: value}).normalize() + if err != nil { + t.Fatal(err) + } + painter, err := newPainter(&gfx.Canvas{}, &normalized) + if err != nil { + t.Fatal(err) + } + config, frames := nativeWindowConfig(&normalized, painter) + if frames != nil { + defer frames.stop() + } + if config.Watermark.Text != value.Text || config.Watermark.Insets != value.Insets || config.Watermark.TileWidth != 240 { + t.Fatal("native initial configuration lost watermark", config.Watermark) + } +} + +func TestWatermarkTextOnlyDefaultsAndContentWindowForwarding(t *testing.T) { + control := &watermarkTestControl{} + content := &ContentWindow{window: &Window{control: resultWindow{WindowControl: control}}} + if err := content.SetWatermark(Watermark{Text: "DRAFT"}); err != nil { + t.Fatal(err) + } + if len(control.values) != 1 || control.values[0].Color.Alpha <= 0 { + t.Fatal("text-only watermark is invisible", control.values) + } + if err := content.SetWatermark(Watermark{}); err != nil || control.values[1] != (platform.Watermark{}) { + t.Fatal("empty text did not disable watermark", err) + } + var closed *ContentWindow + if err := closed.SetWatermark(Watermark{}); err == nil { + t.Fatal("nil content window accepted watermark") + } +} diff --git a/app/window_edge.go b/app/window_edge.go index 20ace7d7f..9b46f2b50 100644 --- a/app/window_edge.go +++ b/app/window_edge.go @@ -5,10 +5,10 @@ import "github.com/vivaui/viva/internal/platform" // trackEdge follows which resize edge of a window with Viva-drawn controls the // pointer is over, and reports whether that changed. The top edge yields to a // control under the pointer, as it does when pressed. -func (painter *painter) trackEdge(event platform.PointerEvent) bool { +func (painter *painter) trackEdge(inside bool) bool { next := platform.EdgeNone - if painter.controls != nil && event.Kind != platform.PointerExit && !painter.controls.maximized() { - next = platform.EdgeAt(event.X, event.Y, painter.size.Width, painter.size.Height, !painter.pointer.Hovered().IsZero()) + if painter.controls != nil && inside && !painter.controls.maximized() { + next = platform.EdgeAt(painter.pointerAt.X, painter.pointerAt.Y, painter.size.Width, painter.size.Height, !painter.pointer.Hovered().IsZero()) } changed := next != painter.edge painter.edge = next diff --git a/audio/audio.go b/audio/audio.go index 7d4b12280..438a73d89 100644 --- a/audio/audio.go +++ b/audio/audio.go @@ -24,6 +24,9 @@ var ( // output that can play the stream: the package is not implemented for the // platform, the system library is missing, or no default device exists. ErrUnsupported = errors.New("audio: no output device is available") + // ErrInputUnsupported reports that this build target, or the system, has no + // input device that can capture audio. + ErrInputUnsupported = errors.New("audio: no input device is available") // ErrClosed reports a Write after Close. ErrClosed = errors.New("audio: output is closed") // ErrFrame reports data that does not hold whole frames. diff --git a/audio/device_test.go b/audio/device_test.go index 74e092957..e45b5f5a2 100644 --- a/audio/device_test.go +++ b/audio/device_test.go @@ -1,6 +1,7 @@ package audio import ( + "io" "os" "testing" "time" @@ -32,3 +33,29 @@ func TestOutputDevice(t *testing.T) { } } } + +// TestInputDevice captures a short sample from the machine's default input. +// Like TestOutputDevice, it is opt-in under VIVA_AUDIO_TEST=1. +func TestInputDevice(t *testing.T) { + if os.Getenv("VIVA_AUDIO_TEST") == "" { + t.Skip("set VIVA_AUDIO_TEST=1 to open the default input device") + } + for _, format := range []Format{ + {SampleRate: 48000, Channels: 1}, + {SampleRate: 44100, Channels: 2}, + {SampleRate: 16000, Channels: 1}, + } { + in, err := OpenInput(format) + if err != nil { + t.Fatalf("OpenInput(%+v): %v", format, err) + } + buf := make([]byte, format.SampleRate/20*format.Channels*2) + if _, err := io.ReadFull(in, buf); err != nil { + _ = in.Close() + t.Fatalf("ReadFull(%+v): %v", format, err) + } + if err := in.Close(); err != nil { + t.Fatalf("Close(%+v): %v", format, err) + } + } +} diff --git a/audio/input.go b/audio/input.go new file mode 100644 index 000000000..a00af7bcf --- /dev/null +++ b/audio/input.go @@ -0,0 +1,206 @@ +package audio + +import ( + "fmt" + "io" + "runtime" + "sync" +) + +// Input is a stream capturing PCM from the system's default input device. It +// implements io.ReadCloser; each Read returns interleaved 16-bit signed +// little-endian frames in the format given to OpenInput. +// +// While an Input is open it holds one goroutine, a fixed ring buffer, and the +// capture device. If the caller stops reading temporarily, oldest frames are +// discarded so the capture thread never stalls. +type Input struct { + format Format + align int + + mu sync.Mutex + cond *sync.Cond + ring []byte + head int // read offset in ring + used int // unread bytes in ring + closed bool + failed error + dev inputDevice + openErr error + done chan struct{} + ready chan struct{} +} + +// OpenInput opens the default input device for format. It returns +// ErrInputUnsupported when the platform, the system library, or the system's +// default input device cannot capture. +// +// Denied microphone access is not an error: macOS and Windows deliver silence. +// docs/audio.md lists what a macOS bundle must declare. +func OpenInput(format Format) (*Input, error) { + if err := format.valid(); err != nil { + return nil, err + } + align := format.Channels * 2 + // Keep up to a quarter second of captured audio in the ring. + ringBytes := max(format.SampleRate/4*align, 4096) + ringBytes -= ringBytes % align + if ringBytes < align { + ringBytes = align + } + in := &Input{ + format: format, + align: align, + ring: make([]byte, ringBytes), + done: make(chan struct{}), + ready: make(chan struct{}), + } + in.cond = sync.NewCond(&in.mu) + go in.run() + <-in.ready + if in.openErr != nil { + <-in.done + return nil, in.openErr + } + return in, nil +} + +// Format returns the format given to OpenInput. +func (in *Input) Format() Format { return in.format } + +func (in *Input) run() { + runtime.LockOSThread() + defer close(in.done) + + dev, err := loadInputDevice(in.format) + in.mu.Lock() + in.openErr = err + if err != nil { + in.failed = err + } else { + in.dev = dev + } + in.mu.Unlock() + close(in.ready) + if err != nil { + return + } + + scratch := make([]byte, max(in.format.SampleRate/4, 4096)*in.align) + for { + n, err := dev.read(scratch) + if n > 0 { + in.push(scratch[:n]) + } + if err != nil { + in.mu.Lock() + if !in.closed { + in.failed = err + } + in.cond.Broadcast() + in.mu.Unlock() + break + } + in.mu.Lock() + closed := in.closed + in.mu.Unlock() + if closed { + break + } + } + dev.close() +} + +func (in *Input) push(pcm []byte) { + in.mu.Lock() + defer in.mu.Unlock() + if in.closed { + return + } + capRing := len(in.ring) + if len(pcm) >= capRing { + pcm = pcm[len(pcm)-capRing:] + in.head = 0 + in.used = 0 + } else if overflow := in.used + len(pcm) - capRing; overflow > 0 { + in.head = (in.head + overflow) % capRing + in.used -= overflow + } + write := (in.head + in.used) % capRing + first := min(len(pcm), capRing-write) + copy(in.ring[write:], pcm[:first]) + if first < len(pcm) { + copy(in.ring, pcm[first:]) + } + in.used += len(pcm) + in.cond.Broadcast() +} + +// Read copies captured PCM frames into pcm, blocking until at least one byte +// is available or the stream ends. Returns io.EOF after Close. +func (in *Input) Read(pcm []byte) (int, error) { + if len(pcm) == 0 { + return 0, nil + } + in.mu.Lock() + defer in.mu.Unlock() + for in.used == 0 && !in.closed && in.failed == nil { + in.cond.Wait() + } + if in.closed { + return 0, io.EOF + } + if in.used == 0 && in.failed != nil { + return 0, in.failed + } + take := min(len(pcm), in.used) + if len(pcm) >= in.align && take >= in.align { + take -= take % in.align + } + capRing := len(in.ring) + first := min(take, capRing-in.head) + copy(pcm[:first], in.ring[in.head:in.head+first]) + if first < take { + copy(pcm[first:take], in.ring[:take-first]) + } + in.head = (in.head + take) % capRing + in.used -= take + return take, nil +} + +// Close stops capturing and releases the input device. It is safe to call more +// than once, and unblocks any waiting Read with io.EOF. +func (in *Input) Close() error { + in.mu.Lock() + already := in.closed + in.closed = true + dev := in.dev + in.cond.Broadcast() + in.mu.Unlock() + if !already && dev != nil { + dev.stop() + } + <-in.done + return nil +} + +func loadInputDevice(format Format) (dev inputDevice, err error) { + defer func() { + if recovered := recover(); recovered != nil { + dev, err = nil, fmt.Errorf("audio: %v", recovered) + } + }() + return openInputDevice(format) +} + +// inputDevice is one platform's capture stream. read and close run on the +// capture goroutine locked to an OS thread; stop may be called from any +// goroutine to unblock read. +type inputDevice interface { + read(pcm []byte) (int, error) + stop() + close() +} + +// openInputDevice is the platform's implementation. Tests replace it. +var openInputDevice = platformInputDevice diff --git a/audio/input_darwin.c b/audio/input_darwin.c new file mode 100644 index 000000000..25a1f4d3b --- /dev/null +++ b/audio/input_darwin.c @@ -0,0 +1,383 @@ +//go:build darwin && !ios + +#include +#include +#include +#include +#include +#include + +typedef struct viva_audio_input viva_audio_input; + +// viva_audio_input captures from the default input HAL AudioUnit into a ring +// buffer. CoreAudio's input callback runs on its own real-time thread and only +// copies bytes under the mutex; Go reads from the ring without touching CoreAudio. +struct viva_audio_input { + pthread_mutex_t mutex; + pthread_cond_t cond; + uint8_t *data; + size_t capacity; + size_t frame; + size_t read; + size_t used; + AudioUnit unit; + AudioConverterRef converter; + AudioStreamBasicDescription client_fmt; + AudioStreamBasicDescription target_fmt; + uint8_t *capture_buf; + size_t capture_cap; + uint8_t *convert_buf; + size_t convert_cap; + const uint8_t *conv_ptr; + UInt32 conv_bytes; + int started; + int closed; +}; + +static size_t viva_in_min(size_t a, size_t b) { return a < b ? a : b; } + +static void viva_in_ring_push(struct viva_audio_input *a, const uint8_t *src, size_t len) { + if (len == 0) { + return; + } + pthread_mutex_lock(&a->mutex); + if (a->closed) { + pthread_mutex_unlock(&a->mutex); + return; + } + if (len >= a->capacity) { + src += len - a->capacity; + len = a->capacity; + a->read = 0; + a->used = 0; + } else if (a->used + len > a->capacity) { + size_t drop = a->used + len - a->capacity; + a->read = (a->read + drop) % a->capacity; + a->used -= drop; + } + size_t write = (a->read + a->used) % a->capacity; + size_t first = viva_in_min(len, a->capacity - write); + memcpy(a->data + write, src, first); + if (len > first) { + memcpy(a->data, src + first, len - first); + } + a->used += len; + pthread_cond_signal(&a->cond); + pthread_mutex_unlock(&a->mutex); +} + +static OSStatus viva_in_conv_supply(AudioConverterRef converter, UInt32 *packets, + AudioBufferList *data, + AudioStreamPacketDescription **desc, + void *ref) { + (void)converter; + (void)desc; + struct viva_audio_input *a = ref; + if (a->conv_bytes == 0) { + *packets = 0; + data->mBuffers[0].mDataByteSize = 0; + data->mBuffers[0].mData = NULL; + return noErr; + } + UInt32 avail = a->conv_bytes / a->client_fmt.mBytesPerPacket; + UInt32 take = *packets < avail ? *packets : avail; + UInt32 take_bytes = take * a->client_fmt.mBytesPerPacket; + data->mNumberBuffers = 1; + data->mBuffers[0].mNumberChannels = a->client_fmt.mChannelsPerFrame; + data->mBuffers[0].mData = (void *)a->conv_ptr; + data->mBuffers[0].mDataByteSize = take_bytes; + a->conv_ptr += take_bytes; + a->conv_bytes -= take_bytes; + *packets = take; + return noErr; +} + +static OSStatus viva_in_callback(void *ref, AudioUnitRenderActionFlags *flags, + const AudioTimeStamp *timestamp, UInt32 bus, + UInt32 frames, AudioBufferList *io_data) { + (void)io_data; + struct viva_audio_input *a = ref; + size_t need = (size_t)frames * a->client_fmt.mBytesPerFrame; + if (need == 0 || need > a->capture_cap) { + return noErr; + } + + AudioBufferList abl; + abl.mNumberBuffers = 1; + abl.mBuffers[0].mNumberChannels = a->client_fmt.mChannelsPerFrame; + abl.mBuffers[0].mDataByteSize = (UInt32)need; + abl.mBuffers[0].mData = a->capture_buf; + + OSStatus err = AudioUnitRender(a->unit, flags, timestamp, bus, frames, &abl); + if (err != noErr) { + return err; + } + + if (a->converter == NULL) { + viva_in_ring_push(a, a->capture_buf, abl.mBuffers[0].mDataByteSize); + return noErr; + } + + a->conv_ptr = a->capture_buf; + a->conv_bytes = abl.mBuffers[0].mDataByteSize; + while (a->conv_bytes > 0) { + UInt32 out_packets = (UInt32)(a->convert_cap / a->target_fmt.mBytesPerPacket); + AudioBufferList out_abl; + out_abl.mNumberBuffers = 1; + out_abl.mBuffers[0].mNumberChannels = a->target_fmt.mChannelsPerFrame; + out_abl.mBuffers[0].mDataByteSize = out_packets * a->target_fmt.mBytesPerPacket; + out_abl.mBuffers[0].mData = a->convert_buf; + + err = AudioConverterFillComplexBuffer(a->converter, viva_in_conv_supply, a, + &out_packets, &out_abl, NULL); + if (out_packets > 0 && out_abl.mBuffers[0].mDataByteSize > 0) { + viva_in_ring_push(a, a->convert_buf, out_abl.mBuffers[0].mDataByteSize); + } + if (err != noErr || out_packets == 0) { + break; + } + } + return noErr; +} + +viva_audio_input *viva_audio_input_open(double rate, uint32_t channels, int32_t *status) { + *status = 0; + if (rate < 8000 || rate > 192000 || channels < 1 || channels > 2) { + *status = kAudioUnitErr_InvalidParameter; + return NULL; + } + + AudioObjectPropertyAddress dev_addr = { + .mSelector = kAudioHardwarePropertyDefaultInputDevice, + .mScope = kAudioObjectPropertyScopeGlobal, + .mElement = kAudioObjectPropertyElementMain, + }; + AudioDeviceID dev_id = kAudioObjectUnknown; + UInt32 dev_size = sizeof(dev_id); + OSStatus err = AudioObjectGetPropertyData(kAudioObjectSystemObject, &dev_addr, 0, NULL, &dev_size, &dev_id); + if (err != noErr || dev_id == kAudioObjectUnknown) { + *status = -1; + return NULL; + } + + AudioComponentDescription description = { + .componentType = kAudioUnitType_Output, + .componentSubType = kAudioUnitSubType_HALOutput, + .componentManufacturer = kAudioUnitManufacturer_Apple, + }; + AudioComponent component = AudioComponentFindNext(NULL, &description); + if (component == NULL) { + *status = -1; + return NULL; + } + + struct viva_audio_input *a = calloc(1, sizeof(*a)); + if (a == NULL) { + *status = kAudioUnitErr_NoConnection; + return NULL; + } + a->frame = (size_t)channels * 2; + a->capacity = (size_t)(rate / 4.0) * a->frame; + if (a->capacity < 4096) { + a->capacity = 4096; + } + a->capacity -= a->capacity % a->frame; + a->data = malloc(a->capacity); + a->capture_cap = 65536; + a->capture_buf = malloc(a->capture_cap); + a->convert_cap = 65536; + a->convert_buf = malloc(a->convert_cap); + if (a->data == NULL || a->capture_buf == NULL || a->convert_buf == NULL) { + free(a->data); + free(a->capture_buf); + free(a->convert_buf); + free(a); + *status = kAudioUnitErr_NoConnection; + return NULL; + } + if (pthread_mutex_init(&a->mutex, NULL) != 0 || + pthread_cond_init(&a->cond, NULL) != 0) { + free(a->data); + free(a->capture_buf); + free(a->convert_buf); + free(a); + *status = kAudioUnitErr_NoConnection; + return NULL; + } + + err = AudioComponentInstanceNew(component, &a->unit); + if (err != noErr) { + goto fail; + } + + UInt32 enable_in = 1; + err = AudioUnitSetProperty(a->unit, kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Input, 1, &enable_in, sizeof(enable_in)); + if (err != noErr) { + goto fail; + } + + UInt32 disable_out = 0; + err = AudioUnitSetProperty(a->unit, kAudioOutputUnitProperty_EnableIO, + kAudioUnitScope_Output, 0, &disable_out, sizeof(disable_out)); + if (err != noErr) { + goto fail; + } + + err = AudioUnitSetProperty(a->unit, kAudioOutputUnitProperty_CurrentDevice, + kAudioUnitScope_Global, 0, &dev_id, sizeof(dev_id)); + if (err != noErr) { + goto fail; + } + + AudioStreamBasicDescription hw_fmt; + UInt32 hw_size = sizeof(hw_fmt); + err = AudioUnitGetProperty(a->unit, kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Input, 1, &hw_fmt, &hw_size); + if (err != noErr) { + goto fail; + } + + UInt32 hw_channels = hw_fmt.mChannelsPerFrame; + if (hw_channels == 0) { + hw_channels = channels; + } + if (hw_channels > 2) { + hw_channels = 2; + } + double hw_rate = hw_fmt.mSampleRate > 0 ? hw_fmt.mSampleRate : rate; + + a->client_fmt = (AudioStreamBasicDescription){ + .mSampleRate = hw_rate, + .mFormatID = kAudioFormatLinearPCM, + .mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked, + .mBytesPerPacket = hw_channels * 2, + .mFramesPerPacket = 1, + .mBytesPerFrame = hw_channels * 2, + .mChannelsPerFrame = hw_channels, + .mBitsPerChannel = 16, + }; + a->target_fmt = (AudioStreamBasicDescription){ + .mSampleRate = rate, + .mFormatID = kAudioFormatLinearPCM, + .mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked, + .mBytesPerPacket = (UInt32)a->frame, + .mFramesPerPacket = 1, + .mBytesPerFrame = (UInt32)a->frame, + .mChannelsPerFrame = channels, + .mBitsPerChannel = 16, + }; + + err = AudioUnitSetProperty(a->unit, kAudioUnitProperty_StreamFormat, + kAudioUnitScope_Output, 1, &a->client_fmt, sizeof(a->client_fmt)); + if (err != noErr) { + goto fail; + } + + if (a->client_fmt.mSampleRate != a->target_fmt.mSampleRate || + a->client_fmt.mChannelsPerFrame != a->target_fmt.mChannelsPerFrame) { + err = AudioConverterNew(&a->client_fmt, &a->target_fmt, &a->converter); + if (err != noErr) { + goto fail; + } + } + + AURenderCallbackStruct callback = { + .inputProc = viva_in_callback, + .inputProcRefCon = a, + }; + err = AudioUnitSetProperty(a->unit, kAudioOutputUnitProperty_SetInputCallback, + kAudioUnitScope_Global, 0, &callback, sizeof(callback)); + if (err != noErr) { + goto fail; + } + + err = AudioUnitInitialize(a->unit); + if (err != noErr) { + goto fail; + } + err = AudioOutputUnitStart(a->unit); + if (err != noErr) { + AudioUnitUninitialize(a->unit); + goto fail; + } + a->started = 1; + return a; + +fail: + *status = err; + if (a->converter != NULL) { + AudioConverterDispose(a->converter); + } + if (a->unit != NULL) { + AudioComponentInstanceDispose(a->unit); + } + pthread_mutex_destroy(&a->mutex); + pthread_cond_destroy(&a->cond); + free(a->data); + free(a->capture_buf); + free(a->convert_buf); + free(a); + return NULL; +} + +int64_t viva_audio_input_read(viva_audio_input *a, void *pcm, uintptr_t len) { + if (a == NULL || len == 0) { + return 0; + } + pthread_mutex_lock(&a->mutex); + while (a->used == 0 && !a->closed) { + pthread_cond_wait(&a->cond, &a->mutex); + } + if (a->closed) { + pthread_mutex_unlock(&a->mutex); + return 0; + } + size_t take = viva_in_min((size_t)len, a->used); + take -= take % a->frame; + if (take == 0 && a->used > 0) { + take = viva_in_min((size_t)len, a->used); + } + uint8_t *dst = pcm; + size_t first = viva_in_min(take, a->capacity - a->read); + memcpy(dst, a->data + a->read, first); + if (take > first) { + memcpy(dst + first, a->data, take - first); + } + a->read = (a->read + take) % a->capacity; + a->used -= take; + pthread_mutex_unlock(&a->mutex); + return (int64_t)take; +} + +void viva_audio_input_stop(viva_audio_input *a) { + if (a == NULL) { + return; + } + pthread_mutex_lock(&a->mutex); + a->closed = 1; + pthread_cond_broadcast(&a->cond); + pthread_mutex_unlock(&a->mutex); +} + +void viva_audio_input_close(viva_audio_input *a) { + if (a == NULL) { + return; + } + viva_audio_input_stop(a); + if (a->started) { + AudioOutputUnitStop(a->unit); + a->started = 0; + } + AudioUnitUninitialize(a->unit); + AudioComponentInstanceDispose(a->unit); + if (a->converter != NULL) { + AudioConverterDispose(a->converter); + } + pthread_mutex_destroy(&a->mutex); + pthread_cond_destroy(&a->cond); + free(a->data); + free(a->capture_buf); + free(a->convert_buf); + free(a); +} diff --git a/audio/input_darwin.go b/audio/input_darwin.go new file mode 100644 index 000000000..87a3e3e8c --- /dev/null +++ b/audio/input_darwin.go @@ -0,0 +1,69 @@ +//go:build darwin && !ios + +package audio + +/* +#cgo darwin LDFLAGS: -framework AudioToolbox -framework CoreAudio +#include + +typedef struct viva_audio_input viva_audio_input; + +viva_audio_input *viva_audio_input_open(double rate, uint32_t channels, int32_t *status); +int64_t viva_audio_input_read(viva_audio_input *a, void *pcm, uintptr_t len); +void viva_audio_input_stop(viva_audio_input *a); +void viva_audio_input_close(viva_audio_input *a); +*/ +import "C" + +import ( + "errors" + "fmt" + "runtime" + "unsafe" +) + +var errInputStopped = errors.New("audio: input stopped") + +type darwinInputDevice struct { + handle *C.viva_audio_input +} + +func platformInputDevice(format Format) (inputDevice, error) { + var status C.int32_t + handle := C.viva_audio_input_open(C.double(format.SampleRate), C.uint32_t(format.Channels), &status) + if handle == nil { + if status == -1 { + return nil, fmt.Errorf("audio: the default input device is missing: %w", ErrInputUnsupported) + } + return nil, fmt.Errorf("audio: open the default input unit: OSStatus %d", int32(status)) + } + return &darwinInputDevice{handle: handle}, nil +} + +func (d *darwinInputDevice) read(pcm []byte) (int, error) { + if len(pcm) == 0 { + return 0, nil + } + n := C.viva_audio_input_read(d.handle, unsafe.Pointer(&pcm[0]), C.uintptr_t(len(pcm))) + runtime.KeepAlive(pcm) + if n == 0 { + return 0, errInputStopped + } + if n < 0 { + return 0, fmt.Errorf("audio: capture on the input unit: OSStatus %d", int64(n)) + } + return int(n), nil +} + +func (d *darwinInputDevice) stop() { + if d.handle != nil { + C.viva_audio_input_stop(d.handle) + } +} + +func (d *darwinInputDevice) close() { + if d.handle != nil { + C.viva_audio_input_close(d.handle) + d.handle = nil + } +} diff --git a/audio/input_linux.go b/audio/input_linux.go new file mode 100644 index 000000000..1e8e02867 --- /dev/null +++ b/audio/input_linux.go @@ -0,0 +1,119 @@ +//go:build linux && (amd64 || arm64) + +package audio + +import ( + "errors" + "fmt" + "sync/atomic" + "time" + "unsafe" + + "github.com/ebitengine/purego" +) + +var errInputStopped = errors.New("audio: input stopped") + +type alsaInputDevice struct { + library uintptr + pcm uintptr + frame int + chunkFrames int + api *alsaAPI + stopped atomic.Bool +} + +func platformInputDevice(format Format) (inputDevice, error) { + api, library, err := openALSA() + if err != nil { + return nil, fmt.Errorf("%w: %v", ErrInputUnsupported, err) + } + name := []byte("default\x00") + var pcm uintptr + if status := api.open(&pcm, &name[0], alsaCapture, 0); status < 0 { + message := alsaError(api, status) + purego.Dlclose(library) + return nil, fmt.Errorf("audio: open the ALSA default capture device: %s: %w", message, ErrInputUnsupported) + } + if err := configureALSA(api, pcm, format); err != nil { + api.close(pcm) + purego.Dlclose(library) + return nil, err + } + return &alsaInputDevice{ + library: library, + pcm: pcm, + frame: format.Channels * 2, + chunkFrames: max(format.SampleRate/100, 1), + api: api, + }, nil +} + +func (d *alsaInputDevice) read(pcm []byte) (int, error) { + wantFrames := min(len(pcm)/d.frame, d.chunkFrames) + if wantFrames < 1 { + wantFrames = 1 + } + for { + if d.stopped.Load() { + return 0, errInputStopped + } + ready := d.api.wait(d.pcm, 50) + if d.stopped.Load() { + return 0, errInputStopped + } + if ready == 0 { + continue + } + if ready < 0 { + if status := d.api.recover(d.pcm, ready, 1); status < 0 { + return 0, fmt.Errorf("audio: wait on the ALSA capture device: %s", alsaError(d.api, status)) + } + continue + } + got := d.api.readi(d.pcm, unsafe.Pointer(&pcm[0]), uintptr(wantFrames)) + if got > 0 { + return int(got) * d.frame, nil + } + if got == 0 { + time.Sleep(time.Millisecond) + continue + } + recovered := false + for range alsaRecoverRetries { + if d.stopped.Load() { + return 0, errInputStopped + } + if status := d.api.recover(d.pcm, int32(got), 1); status < 0 { + return 0, fmt.Errorf("audio: capture on the ALSA device: %s", alsaError(d.api, status)) + } + got = d.api.readi(d.pcm, unsafe.Pointer(&pcm[0]), uintptr(wantFrames)) + if got > 0 { + return int(got) * d.frame, nil + } + if got == 0 { + recovered = true + break + } + } + if !recovered { + return 0, fmt.Errorf("audio: the ALSA capture device stopped: %s", alsaError(d.api, int32(got))) + } + } +} + +func (d *alsaInputDevice) stop() { + d.stopped.Store(true) +} + +func (d *alsaInputDevice) close() { + if d.pcm != 0 { + d.api.drop(d.pcm) + d.api.close(d.pcm) + d.pcm = 0 + } + if d.library != 0 { + purego.Dlclose(d.library) + d.library = 0 + } +} diff --git a/audio/input_linux_other.go b/audio/input_linux_other.go new file mode 100644 index 000000000..29837afa7 --- /dev/null +++ b/audio/input_linux_other.go @@ -0,0 +1,5 @@ +//go:build linux && !amd64 && !arm64 && !android + +package audio + +func platformInputDevice(Format) (inputDevice, error) { return nil, ErrInputUnsupported } diff --git a/audio/input_other.go b/audio/input_other.go new file mode 100644 index 000000000..b029b55e5 --- /dev/null +++ b/audio/input_other.go @@ -0,0 +1,5 @@ +//go:build (!darwin || ios) && !windows && !linux + +package audio + +func platformInputDevice(Format) (inputDevice, error) { return nil, ErrInputUnsupported } diff --git a/audio/input_test.go b/audio/input_test.go new file mode 100644 index 000000000..518700a96 --- /dev/null +++ b/audio/input_test.go @@ -0,0 +1,164 @@ +package audio + +import ( + "bytes" + "errors" + "io" + "sync" + "testing" + "time" +) + +type fakeInputDevice struct { + mu sync.Mutex + chunks chan []byte + closed bool + fail error +} + +func newFakeInputDevice() *fakeInputDevice { + return &fakeInputDevice{chunks: make(chan []byte, 16)} +} + +func (d *fakeInputDevice) push(pcm []byte) { + d.chunks <- append([]byte(nil), pcm...) +} + +func (d *fakeInputDevice) read(dst []byte) (int, error) { + chunk, ok := <-d.chunks + if !ok { + if d.fail != nil { + return 0, d.fail + } + return 0, io.EOF + } + return copy(dst, chunk), nil +} + +func (d *fakeInputDevice) stop() { + d.mu.Lock() + if !d.closed { + d.closed = true + close(d.chunks) + } + d.mu.Unlock() +} + +func (d *fakeInputDevice) close() { + d.stop() +} + +func withInputDevice(t testing.TB, dev inputDevice, err error) { + t.Helper() + previous := openInputDevice + openInputDevice = func(Format) (inputDevice, error) { return dev, err } + t.Cleanup(func() { openInputDevice = previous }) +} + +func TestOpenInputRejectsBadFormats(t *testing.T) { + for _, format := range []Format{ + {SampleRate: 0, Channels: 2}, + {SampleRate: 7999, Channels: 2}, + {SampleRate: 192001, Channels: 1}, + {SampleRate: 8000, Channels: 0}, + {SampleRate: 8000, Channels: 3}, + } { + if _, err := OpenInput(format); !errors.Is(err, ErrFormat) { + t.Errorf("OpenInput(%+v) error = %v, want ErrFormat", format, err) + } + } +} + +func TestOpenInputReportsPlatformError(t *testing.T) { + withInputDevice(t, nil, ErrInputUnsupported) + if _, err := OpenInput(testFormat()); !errors.Is(err, ErrInputUnsupported) { + t.Fatalf("OpenInput error = %v, want ErrInputUnsupported", err) + } +} + +func TestInputStreamsInOrderAndCloseUnblocksRead(t *testing.T) { + dev := newFakeInputDevice() + withInputDevice(t, dev, nil) + + in, err := OpenInput(Format{SampleRate: 16000, Channels: 1}) + if err != nil { + t.Fatal(err) + } + if in.Format() != (Format{SampleRate: 16000, Channels: 1}) { + t.Fatalf("Format() = %+v", in.Format()) + } + + want := []byte{1, 2, 3, 4, 5, 6, 7, 8} + dev.push(want[:4]) + dev.push(want[4:]) + + got := make([]byte, len(want)) + if _, err := io.ReadFull(in, got); err != nil { + t.Fatalf("ReadFull: %v", err) + } + if !bytes.Equal(got, want) { + t.Fatalf("read %v, want %v", got, want) + } + + readErr := make(chan error, 1) + go func() { + var buf [16]byte + _, err := in.Read(buf[:]) + readErr <- err + }() + time.Sleep(20 * time.Millisecond) + if err := in.Close(); err != nil { + t.Fatalf("Close: %v", err) + } + select { + case err := <-readErr: + if !errors.Is(err, io.EOF) { + t.Fatalf("Read after Close = %v, want io.EOF", err) + } + case <-time.After(time.Second): + t.Fatal("Read did not unblock after Close") + } + if err := in.Close(); err != nil { + t.Fatalf("second Close: %v", err) + } +} + +func TestInputRingDropsOldestFramesWhenOverflowed(t *testing.T) { + dev := newFakeInputDevice() + withInputDevice(t, dev, nil) + + in, err := OpenInput(Format{SampleRate: 8000, Channels: 2}) + if err != nil { + t.Fatal(err) + } + defer in.Close() + + // Ring size for 8000 Hz stereo is 8000 bytes; push 10000 bytes so the first + // 2000 bytes are dropped in favor of newer frames. + chunk := make([]byte, 4000) + for i := range chunk { + chunk[i] = 1 + } + dev.push(chunk) + chunk2 := make([]byte, 4000) + for i := range chunk2 { + chunk2[i] = 2 + } + dev.push(chunk2) + chunk3 := make([]byte, 2000) + for i := range chunk3 { + chunk3[i] = 3 + } + dev.push(chunk3) + + // Wait briefly for the capture goroutine to drain all 3 chunks into the ring. + time.Sleep(30 * time.Millisecond) + + buf := make([]byte, 8000) + if _, err := io.ReadFull(in, buf); err != nil { + t.Fatalf("ReadFull: %v", err) + } + if buf[0] != 1 || buf[2000] != 2 || buf[6000] != 3 { + t.Fatalf("ring overwrite unexpected: first=%d mid=%d tail=%d", buf[0], buf[2000], buf[6000]) + } +} diff --git a/audio/input_windows.go b/audio/input_windows.go new file mode 100644 index 000000000..a8863067b --- /dev/null +++ b/audio/input_windows.go @@ -0,0 +1,206 @@ +//go:build windows + +package audio + +import ( + "errors" + "fmt" + "runtime" + "sync" + "unsafe" + + "golang.org/x/sys/windows" +) + +const ( + wasapiCapture = 1 // eCapture + wasapiBufferFlagSilent = 0x2 +) + +var ( + iidAudioCaptureClient = guid{0xC8ADBD64, 0xE71E, 0x48A0, [8]byte{0xA4, 0xDE, 0x18, 0x5C, 0x39, 0x5C, 0xD3, 0x17}} + errInputStopped = errors.New("audio: input stopped") +) + +type wasapiInputDevice struct { + enumerator uintptr + endpoint uintptr + client uintptr + capture uintptr + audioEvent windows.Handle + stopMu sync.Mutex + stopEvent windows.Handle + started bool + frameBytes int +} + +func platformInputDevice(format Format) (inputDevice, error) { + result, _, _ := coInitializeEx.Call(0, coinitMultithreaded) + switch uint32(result) { + case 0, coinitSFalse: + case hresultChangedMode: + return nil, fmt.Errorf("audio: the audio thread is already in a COM apartment of another mode: %w", ErrInputUnsupported) + default: + return nil, hresult("initialize COM", result) + } + d := &wasapiInputDevice{frameBytes: format.Channels * 2} + if err := d.open(format); err != nil { + d.close() + return nil, err + } + return d, nil +} + +func (d *wasapiInputDevice) open(format Format) error { + r, _, _ := coCreateInstance.Call( + uintptr(unsafe.Pointer(&clsidMMDeviceEnumerator)), + 0, + clsctxAll, + uintptr(unsafe.Pointer(&iidMMDeviceEnumerator)), + uintptr(unsafe.Pointer(&d.enumerator)), + ) + runtime.KeepAlive(&clsidMMDeviceEnumerator) + runtime.KeepAlive(&iidMMDeviceEnumerator) + if err := hresult("create the audio endpoint enumerator", r); err != nil { + return fmt.Errorf("%w: %v", ErrInputUnsupported, err) + } + // IMMDeviceEnumerator::GetDefaultAudioEndpoint(eCapture, eConsole, ...). + if r := comCall(d.enumerator, 4, wasapiCapture, wasapiConsole, uintptr(unsafe.Pointer(&d.endpoint))); int32(uint32(r)) < 0 { + return fmt.Errorf("audio: no default input device: %w", ErrInputUnsupported) + } + // IMMDevice::Activate(IID_IAudioClient, ...). + if r := comCall(d.endpoint, 3, uintptr(unsafe.Pointer(&iidAudioClient)), clsctxAll, 0, uintptr(unsafe.Pointer(&d.client))); int32(uint32(r)) < 0 { + return hresult("activate the audio capture client", r) + } + + wfx := waveFormatEx{ + FormatTag: waveFormatPCM, + Channels: uint16(format.Channels), + SamplesPerSec: uint32(format.SampleRate), + BlockAlign: uint16(format.Channels * 2), + BitsPerSample: 16, + } + wfx.AvgBytesPerSec = wfx.SamplesPerSec * uint32(wfx.BlockAlign) + const flags = wasapiEventCallback | wasapiAutoConvertPCM | wasapiSRCDefaultQuality + if r := comCall(d.client, 3, + wasapiShareModeShared, + flags, + wasapiBufferDuration100ns, + 0, + uintptr(unsafe.Pointer(&wfx)), + 0, + ); int32(uint32(r)) < 0 { + return hresult("initialize the audio capture client", r) + } + runtime.KeepAlive(&wfx) + + var frames uint32 + if r := comCall(d.client, 4, uintptr(unsafe.Pointer(&frames))); int32(uint32(r)) < 0 { + return hresult("read the capture buffer size", r) + } + if frames == 0 { + return fmt.Errorf("audio: the audio capture client reported an empty buffer") + } + // IAudioClient::GetService(IID_IAudioCaptureClient). + if r := comCall(d.client, 14, uintptr(unsafe.Pointer(&iidAudioCaptureClient)), uintptr(unsafe.Pointer(&d.capture))); int32(uint32(r)) < 0 { + return hresult("get the audio capture client", r) + } + audioEvent, err := windows.CreateEvent(nil, 0, 0, nil) + if err != nil { + return fmt.Errorf("audio: create the capture event: %w", err) + } + d.audioEvent = audioEvent + stopEvent, err := windows.CreateEvent(nil, 1, 0, nil) + if err != nil { + return fmt.Errorf("audio: create the capture stop event: %w", err) + } + d.stopEvent = stopEvent + // IAudioClient::SetEventHandle. + if r := comCall(d.client, 13, uintptr(d.audioEvent)); int32(uint32(r)) < 0 { + return hresult("set the capture event", r) + } + // IAudioClient::Start. + if r := comCall(d.client, 10); int32(uint32(r)) < 0 { + return hresult("start the audio capture client", r) + } + d.started = true + return nil +} + +func (d *wasapiInputDevice) read(pcm []byte) (int, error) { + written := 0 + for written == 0 { + var packetFrames uint32 + if r := comCall(d.capture, 5, uintptr(unsafe.Pointer(&packetFrames))); int32(uint32(r)) < 0 { + return 0, hresult("read the next capture packet size", r) + } + if packetFrames == 0 { + handles := [2]windows.Handle{d.audioEvent, d.stopEvent} + ev, err := windows.WaitForMultipleObjects(handles[:], false, 200) + if err != nil { + return 0, fmt.Errorf("audio: wait for capture event: %w", err) + } + if ev == windows.WAIT_OBJECT_0+1 { + return 0, errInputStopped + } + continue + } + for packetFrames > 0 { + var data unsafe.Pointer + var numFrames uint32 + var flags uint32 + if r := comCall(d.capture, 3, uintptr(unsafe.Pointer(&data)), uintptr(unsafe.Pointer(&numFrames)), uintptr(unsafe.Pointer(&flags)), 0, 0); int32(uint32(r)) < 0 { + return written, hresult("get a capture buffer", r) + } + nBytes := int(numFrames) * d.frameBytes + if nBytes > 0 && written+nBytes <= len(pcm) { + if flags&wasapiBufferFlagSilent != 0 || data == nil { + clear(pcm[written : written+nBytes]) + } else { + copy(pcm[written:written+nBytes], unsafe.Slice((*byte)(data), nBytes)) + } + written += nBytes + } + if r := comCall(d.capture, 4, uintptr(numFrames)); int32(uint32(r)) < 0 { + return written, hresult("release a capture buffer", r) + } + if written >= len(pcm) { + break + } + if r := comCall(d.capture, 5, uintptr(unsafe.Pointer(&packetFrames))); int32(uint32(r)) < 0 { + return written, hresult("read the next capture packet size", r) + } + } + } + return written, nil +} + +func (d *wasapiInputDevice) stop() { + d.stopMu.Lock() + if d.stopEvent != 0 { + _ = windows.SetEvent(d.stopEvent) + } + d.stopMu.Unlock() +} + +func (d *wasapiInputDevice) close() { + if d.client != 0 && d.started { + comCall(d.client, 11) // Stop + d.started = false + } + release(&d.capture) + release(&d.client) + release(&d.endpoint) + release(&d.enumerator) + if d.audioEvent != 0 { + _ = windows.CloseHandle(d.audioEvent) + d.audioEvent = 0 + } + d.stopMu.Lock() + if d.stopEvent != 0 { + _ = windows.CloseHandle(d.stopEvent) + d.stopEvent = 0 + } + d.stopMu.Unlock() + coUninitialize.Call() +} diff --git a/audio/output_linux.go b/audio/output_linux.go index fee369b1c..95df636ab 100644 --- a/audio/output_linux.go +++ b/audio/output_linux.go @@ -13,6 +13,7 @@ import ( // ALSA constants (alsa/pcm.h). const ( alsaPlayback = 0 + alsaCapture = 1 alsaNoWait = 1 // SND_PCM_NONBLOCK, deliberately not used alsaAccessRWInter = 3 // SND_PCM_ACCESS_RW_INTERLEAVED alsaFormatS16LE = 2 // SND_PCM_FORMAT_S16_LE @@ -35,7 +36,9 @@ type alsaAPI struct { drop func(pcm uintptr) int32 prepare func(pcm uintptr) int32 recover func(pcm uintptr, err int32, silent int32) int32 + wait func(pcm uintptr, timeout int32) int32 writei func(pcm uintptr, buf unsafe.Pointer, frames uintptr) int64 + readi func(pcm uintptr, buf unsafe.Pointer, frames uintptr) int64 strerror func(err int32) *byte paramsMalloc func(params *uintptr) int32 paramsFree func(params uintptr) @@ -67,7 +70,9 @@ func openALSA() (*alsaAPI, uintptr, error) { purego.RegisterLibFunc(&api.drop, library, "snd_pcm_drop") purego.RegisterLibFunc(&api.prepare, library, "snd_pcm_prepare") purego.RegisterLibFunc(&api.recover, library, "snd_pcm_recover") + purego.RegisterLibFunc(&api.wait, library, "snd_pcm_wait") purego.RegisterLibFunc(&api.writei, library, "snd_pcm_writei") + purego.RegisterLibFunc(&api.readi, library, "snd_pcm_readi") purego.RegisterLibFunc(&api.strerror, library, "snd_strerror") purego.RegisterLibFunc(&api.paramsMalloc, library, "snd_pcm_hw_params_malloc") purego.RegisterLibFunc(&api.paramsFree, library, "snd_pcm_hw_params_free") diff --git a/base/button_node_test.go b/base/button_node_test.go index fca19723f..da6a10dfe 100644 --- a/base/button_node_test.go +++ b/base/button_node_test.go @@ -273,3 +273,17 @@ func TestButtonIsOneRectangleWhateverItIsGiven(t *testing.T) { } } } + +// A ghost button holds the keyboard too: its focus ring is a halo around it, and its +// middle still shows the page rather than the ring's disc. +func TestFocusedGhostButtonKeepsItsMiddleClear(t *testing.T) { + focused := func(c *gfx.Canvas) { c.SetInteraction(gfx.ID{}, gfx.ID{}, save, true) } + p := probeButton(t, focused, func(f *Frame) Box { return f.Button(save, "Save").Ghost() }) + center := gfx.Point{X: p.box.X + p.box.Width/2, Y: p.box.Y + p.box.Height/2} + for _, rectangle := range p.canvas.Rectangles() { + box := rectangle.Bounds + if center.X > box.X && center.X < box.X+box.Width && center.Y > box.Y && center.Y < box.Y+box.Height { + t.Fatalf("the focus ring fills the ghost button's middle: %+v", rectangle) + } + } +} diff --git a/base/list.go b/base/list.go index 10cff5e65..6c40cde31 100644 --- a/base/list.go +++ b/base/list.go @@ -1255,7 +1255,9 @@ func (p *Page) ListKey(event gfx.KeyEvent) (gfx.EventResult, bool) { func (p *Page) ListWheelX(event gfx.ScrollEvent) (moved, only bool) { dx, only := event.DeltaX, event.DeltaY == 0 if dx == 0 && event.Modifiers&gfx.ModifierShift != 0 { - dx, only = event.DeltaY, true + // The vertical wheel turned sideways: its page is sideways too. + event.DeltaX, event.DeltaY = event.DeltaY, 0 + dx, only = event.DeltaX, true } if dx == 0 { return false, false @@ -1264,7 +1266,7 @@ func (p *Page) ListWheelX(event gfx.ScrollEvent) (moved, only bool) { if f := p.View.Frame; f != nil { panel = f.wheelPanel(event.X, event.Y) } - dx = wheelStep(dx, event.Precise) // a notch moves at least a line, as down the list + step := wheelStep(dx, event.Precise) // a notch moves at least a line, as down the list for _, s := range p.listStates { in := &s.list if s.RowWidth <= 0 || in.f == nil || !in.f.ContainsPoint(int(in.area), event.X, event.Y) || !in.f.within(in.area, panel) { @@ -1274,6 +1276,11 @@ func (p *Page) ListWheelX(event gfx.ScrollEvent) (moved, only bool) { if room <= 0 { continue } + // A screen per notch is a screen of this list's width. + dx := step + if event.Pages != 0 { + dx = event.StepXIn(1, in.View.Width) + } before := s.ScrollX() in.scrollX = min(max(before+dx, 0), room) return in.scrollX != before, only diff --git a/base/menu_state.go b/base/menu_state.go index f0453e254..12c15c419 100644 --- a/base/menu_state.go +++ b/base/menu_state.go @@ -85,6 +85,9 @@ func (scroll *MenuScroll) Max() float32 { return scroll.MaxValue } // A notch of a wheel (a gesture that is not Precise) moves at least 24 pixels. func (scroll *MenuScroll) Wheel(event gfx.ScrollEvent) bool { step := event.DeltaY + if event.Pages != 0 { + step = event.StepYIn(1, scroll.View) + } if !event.Precise { if step > 0 && step < 24 { step = 24 diff --git a/base/scroll.go b/base/scroll.go index ffe72e475..a164d3a7d 100644 --- a/base/scroll.go +++ b/base/scroll.go @@ -210,6 +210,14 @@ func (s *ScrollState) canScroll(dx, dy float32) bool { // wheelSteps is how far a scroll event moves the area, right and down. A Sideways area // takes the wheel with Shift held, and no horizontal delta, as a horizontal wheel. func (s *ScrollState) wheelSteps(event gfx.ScrollEvent) (dx, dy float32) { + if event.Pages != 0 { + // The system asks for whole screens: the area moves one of its own, not + // one of the window's, which the event's delta is measured in. + if s.sideways && event.DeltaX == 0 && event.Modifiers&gfx.ModifierShift != 0 { + return event.StepYIn(1, s.ViewportWidth), 0 + } + return event.StepXIn(1, s.ViewportWidth), event.StepYIn(1, s.Viewport) + } dx, dy = event.DeltaX, event.DeltaY if s.sideways && dx == 0 && event.Modifiers&gfx.ModifierShift != 0 { dx, dy = dy, 0 diff --git a/base/scroll_test.go b/base/scroll_test.go index 945fbff5d..f183d14a6 100644 --- a/base/scroll_test.go +++ b/base/scroll_test.go @@ -362,3 +362,26 @@ func TestScrollStateFollowingAndPrepend(t *testing.T) { t.Fatal("ScrollToEnd did not reattach the follow") } } + +func TestAWheelPageMovesTheAreasOwnPage(t *testing.T) { + var view View + logPage(&view, false, 20) // 600 of rows in a 100-tall area + state := view.ScrollState(listID) + window := gfx.Size{Width: 800, Height: 1000} + // The system asks for a screen per notch: the event's delta is a screen of + // the window, and the area moves a screen of its own instead. + if result := state.Wheel(gfx.ScrollEvent{DeltaY: 1000, Pages: 1, Viewport: window}); !result.Handled { + t.Fatal("a page notch was not handled") + } + if state.Offset != 100 { + t.Fatalf("one page notch moved the area to %v, want its own page 100, not the window's", state.Offset) + } + state.Wheel(gfx.ScrollEvent{DeltaY: 1000, Pages: 1, Viewport: window}) + if state.Offset != 200 { + t.Fatalf("the second page notch left the area at %v, want 200", state.Offset) + } + state.Wheel(gfx.ScrollEvent{DeltaY: -1000, Pages: -1, Viewport: window}) + if state.Offset != 100 { + t.Fatalf("a page notch up left the area at %v, want 100", state.Offset) + } +} diff --git a/base/select.go b/base/select.go index 3ca6873ab..ca9f743fb 100644 --- a/base/select.go +++ b/base/select.go @@ -103,7 +103,7 @@ func (s *SelectState) Wheel(event gfx.ScrollEvent) gfx.EventResult { return gfx.EventResult{} } last := len(s.labels) - s.Visible - step := event.DeltaY / selectItem + step := event.StepYIn(selectItem, float32(s.Visible)*selectItem) / selectItem if !event.Precise { switch { case event.DeltaY > 0: diff --git a/base/style.go b/base/style.go index e3bfdfa67..cabbf459f 100644 --- a/base/style.go +++ b/base/style.go @@ -355,9 +355,10 @@ type resolved struct { // and then the line over it even where one shape could paint both. borderWidth float32 splitBorder bool - // ringFilled paints the ring as a disc under the element rather than a line around - // it, and a nonzero ringLine is the width the line is drawn at: how a control's - // recipe draws its focus ring over an opaque page and over a translucent one. + // ringFilled paints the ring as a disc under an element whose opaque background + // covers its middle rather than as a line around it, and a nonzero ringLine is the + // width the line is drawn at: how a control's recipe draws its focus ring over an + // opaque page and over a translucent one. ringFilled bool ringLine float32 } @@ -464,11 +465,14 @@ func (f *Frame) paintRing(r Rect, Radius float32, s *resolved) { Radius += w } switch { - case s.ringFilled: + case s.ringFilled && s.Background.Alpha*f.Opacity >= 1: + // The surface covers the middle of the disc, leaving the halo outside it. f.Surface.Rounded(outer, Radius, color) case s.ringLine > 0: f.Surface.RoundedOutline(outer, Radius, s.ringLine, color) default: + // Nothing over the middle (a ghost or link button's transparent surface, or a + // disabled one) would cover a disc: the halo is only its line. f.Surface.RoundedOutline(outer, Radius, w, color) } } diff --git a/base/textarea.go b/base/textarea.go index 2aa8bfaab..b8d02edde 100644 --- a/base/textarea.go +++ b/base/textarea.go @@ -307,6 +307,9 @@ func (layout *TextareaLayout) Wheel(event gfx.ScrollEvent) bool { return false } dy := event.DeltaY + if event.Pages != 0 { + dy = event.StepYIn(1, content.Height) + } if !event.Precise && dy > 0 && dy < 24 { dy = 24 } else if !event.Precise && dy < 0 && dy > -24 { diff --git a/base/tree.go b/base/tree.go index 35b02093c..82566e115 100644 --- a/base/tree.go +++ b/base/tree.go @@ -46,6 +46,11 @@ type TreeState struct { // SelectedColor paints the selected row's background instead of the theme's // Accent. Zero keeps the theme's. SelectedColor gfx.Color + // RowBackground optionally supplies a full-width wash painted behind row i + // (underneath indentation, disclosure arrow, hover and selection highlight) + // so consecutive rows with the same tint form a continuous band. Zero paints + // nothing. + RowBackground func(i int) gfx.Color // DisplayDepth maps a row's Depth to the level the tree indents it by, when // the application compresses deep rows to keep their names in view. Depth // stays the tree's structure, which keyboard movement, typeahead and drops diff --git a/cmd/viva/templates/button.go.txt b/cmd/viva/templates/button.go.txt index 967446a24..828f26b75 100644 --- a/cmd/viva/templates/button.go.txt +++ b/cmd/viva/templates/button.go.txt @@ -377,26 +377,7 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { Invalid: button.state.Invalid, Disabled: button.disabled, }) } - radius := look.Radius - if look.Shadow != gfx.ShadowNone { - button.canvas.Elevate(button.bounds, radius, look.Shadow) // shadow-xs - } - if look.RingWidth > 0 { - if look.RingOutline { - button.canvas.RoundedOutline(expand(button.bounds, look.RingWidth), look.RingRadius, 2, look.Ring) - } else { - button.canvas.Rounded(expand(button.bounds, look.RingWidth), look.RingRadius, look.Ring) - } - } - style := buttonStyle{ - background: look.Background, foreground: look.Foreground, border: look.Border, - filled: look.Filled, bordered: look.Bordered, underlined: look.Underlined, - } - if style.bordered && style.filled { - paintBordered(button.canvas, button.theme, button.bounds, radius, style.border, style.background) - } else if style.filled { - button.canvas.Rounded(button.bounds, radius, style.background) - } + PaintButtonSurface(button.canvas, button.theme, button.bounds, look) area := button.bounds _, padding, _, _ := button.geometry() if !iconOnly && padding > 0 { @@ -415,8 +396,8 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { } hint := PaintButtonContent(button.canvas, area, ButtonContent{ Label: label, Icon: button.icon, IconTransform: button.iconTransform, - FontSize: fontSize, Weight: gfx.WeightMedium, Color: style.foreground, - Gap: buttonIconGap, Height: height, IconOnly: iconOnly, Underlined: style.underlined, + FontSize: fontSize, Weight: gfx.WeightMedium, Color: look.Foreground, + Gap: buttonIconGap, Height: height, IconOnly: iconOnly, Underlined: look.Underlined, }) if !button.id.IsZero() { button.canvas.HitWithOptions(button.id, button.bounds, label, gfx.HitOptions{ @@ -646,6 +627,45 @@ type ButtonContent struct { // function, not a closure made in each paint, which would allocate. type ButtonLoadingPainter func(canvas *gfx.Canvas, theme *gfx.Theme, bounds gfx.Rect, color gfx.Color, phase uint8) +// PaintButtonSurface paints a button's surface in bounds: its shadow, its focus +// ring, its fill and its border, for a look the caller resolved itself with +// ButtonRecipe or with a recipe of its own. It is the surface half of the paint +// BeginButton does, so a control that draws content of its own on a button's +// surface paints the same surface as a declared button; PaintButtonContent is +// the content half. +// +// The focus ring is a halo that reaches RingWidth beyond bounds. Under an opaque +// fill only the part outside the bounds can be seen, so the whole halo is painted +// with the fill over it; a button that paints no opaque fill (ghost or link, or +// one that is disabled) gets the halo as a line, since nothing would cover the +// middle of the disc. +func PaintButtonSurface(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, look ButtonLook) { + if canvas == nil || bounds.Width <= 0 || bounds.Height <= 0 { + return + } + radius := look.Radius + if look.Shadow != gfx.ShadowNone { + canvas.Elevate(bounds, radius, look.Shadow) // shadow-xs + } + if look.RingWidth > 0 { + halo := expand(bounds, look.RingWidth) + switch { + case look.RingOutline: + canvas.RoundedOutline(halo, look.RingRadius, 2, look.Ring) + case look.Filled && look.Background.Alpha >= 1: + canvas.Rounded(halo, look.RingRadius, look.Ring) + default: + canvas.RoundedOutline(halo, look.RingRadius, look.RingWidth, look.Ring) + } + } + switch { + case look.Bordered && look.Filled: + paintBordered(canvas, theme, bounds, radius, look.Border, look.Background) + case look.Filled: + canvas.Rounded(bounds, radius, look.Background) + } +} + // PaintButtonContent paints a button's icon and label centered in area and returns the // hint an icon-only button gives assistive technology, which is its label. It is the // content half of the paint the Button does: the same placement, the same shrinking of diff --git a/cmd/viva/templates/button_group.go.txt b/cmd/viva/templates/button_group.go.txt index d71bbdb5c..f948a11a4 100644 --- a/cmd/viva/templates/button_group.go.txt +++ b/cmd/viva/templates/button_group.go.txt @@ -95,7 +95,16 @@ func (group ButtonGroup) Paint() ButtonGroupResult { framed = framed || option.Variant == ButtonOutline || option.Variant == ButtonDestructiveOutline if !group.disabled && !option.Disabled && !option.ID.IsZero() && group.canvas.FocusVisible() == option.ID { ring, _ := buttonRing(&group.theme, option.Variant, false) - group.canvas.Rounded(expand(group.optionBounds(index, float32(count)), 3), radius+3, ring) + halo := expand(group.optionBounds(index, float32(count)), 3) + // The halo is a disc under an action that paints an opaque fill; an action + // with no fill of its own gets it as a line, or the disc would fill the + // action's whole surface. + style := buttonStyleFor(&group.theme, option.Variant, group.canvas.Hovered() == option.ID, group.canvas.Pressed() == option.ID) + if style.filled && style.background.Alpha >= 1 { + group.canvas.Rounded(halo, radius+3, ring) + } else { + group.canvas.RoundedOutline(halo, radius+3, 3, ring) + } } } // The outline goes down first and the actions are painted inside it. diff --git a/cmd/viva/templates/code_diff.go.txt b/cmd/viva/templates/code_diff.go.txt index d2f5708db..243d3d1d2 100644 --- a/cmd/viva/templates/code_diff.go.txt +++ b/cmd/viva/templates/code_diff.go.txt @@ -866,12 +866,16 @@ func (diff *CodeDiff) linesForValue(value string) ([]string, []int) { // Scroll applies a wheel or touchpad scroll to both panes. Horizontal deltas use // horizontal movement; Shift turns vertical delta into horizontal movement. func (diff *CodeDiff) Scroll(event gfx.ScrollEvent) gfx.EventResult { - diff.scrollX += event.DeltaX + dy := event.DeltaY + if event.Pages != 0 { + dy = event.StepYIn(1, float32(diff.visibleRows)*diff.rowHeight) + } + dx := event.DeltaX if event.Modifiers&gfx.ModifierShift != 0 { - diff.scrollX += event.DeltaY - } else { - diff.scrollY += event.DeltaY + dx, dy = dx+dy, 0 // Shift turns the vertical travel sideways } + diff.scrollX += dx + diff.scrollY += dy diff.clampScroll() return gfx.EventResult{Handled: true, Repaint: true} } diff --git a/cmd/viva/templates/code_editor_layout.go.txt b/cmd/viva/templates/code_editor_layout.go.txt index 7f7ab7342..386fc257a 100644 --- a/cmd/viva/templates/code_editor_layout.go.txt +++ b/cmd/viva/templates/code_editor_layout.go.txt @@ -705,7 +705,7 @@ func (editor *CodeEditor) Scroll(event gfx.ScrollEvent) gfx.EventResult { if !editor.painted { return gfx.EventResult{} } - dx, dy := event.StepX(editor.cellWidth), event.StepY(editor.lineHeight) + dx, dy := event.StepXIn(editor.cellWidth, editor.content.Width), event.StepYIn(editor.lineHeight, editor.content.Height) if event.Modifiers&gfx.ModifierShift != 0 && dx == 0 { dx, dy = dy, 0 } diff --git a/cmd/viva/templates/hierarchy_menu.go.txt b/cmd/viva/templates/hierarchy_menu.go.txt index 9461d87ff..41673af9e 100644 --- a/cmd/viva/templates/hierarchy_menu.go.txt +++ b/cmd/viva/templates/hierarchy_menu.go.txt @@ -104,6 +104,9 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } // Move the cursor before any row is painted, as the flat list does. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } level, row, onRow := 0, 0, false if index, ok := hovered.In(o.OptionIDs); ok && index&0xFFFF != hierarchyBarRow { level, row, onRow = index>>16, index&0xFFFF, true diff --git a/cmd/viva/templates/multi_select.go.txt b/cmd/viva/templates/multi_select.go.txt index c4b6648aa..2b1ab9668 100644 --- a/cmd/viva/templates/multi_select.go.txt +++ b/cmd/viva/templates/multi_select.go.txt @@ -155,6 +155,9 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M // Move the cursor before any row is painted: syncing it while the rows are // drawn would tint the previous row and the new one in the same frame. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } if s.AdoptHover(hovered) && !hovered.IsZero() { for i := range choices { if o.OptionIDs.At(i) == hovered && !choices[i].Disabled { diff --git a/cmd/viva/templates/single_select.go.txt b/cmd/viva/templates/single_select.go.txt index 80df14c81..376f20032 100644 --- a/cmd/viva/templates/single_select.go.txt +++ b/cmd/viva/templates/single_select.go.txt @@ -192,6 +192,9 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * // Move the cursor before any row is painted: syncing it while the rows are // drawn would tint the previous row and the new one in the same frame. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } if s.Hover.Entered(hovered) && !hovered.IsZero() { for i := range choices { if o.OptionIDs.At(i) == hovered && !choices[i].Disabled { diff --git a/cmd/viva/templates/tooltip.go.txt b/cmd/viva/templates/tooltip.go.txt index 125bb2926..e84631bc3 100644 --- a/cmd/viva/templates/tooltip.go.txt +++ b/cmd/viva/templates/tooltip.go.txt @@ -352,24 +352,20 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g id, immediate = hovered, false } } - if hover.focus && hover.held.IsZero() { - if focused := canvas.FocusVisible(); !focused.IsZero() { - id, immediate = focused, true - } - } - if id.IsZero() { - hover.target, hover.shown = gfx.ID{}, gfx.ID{} - return false - } hits := canvas.Hits() var hit gfx.Hit found := false - for index := len(hits) - 1; index >= 0; index-- { - if hits[index].ID == id && !hits[index].Block { - hit, found = hits[index], hits[index].Hint != "" - break + if hover.focus && hover.held.IsZero() { + if focused := canvas.FocusVisible(); !focused.IsZero() { + if focusHit, ok := hoverHintHit(hits, focused); ok { + id, immediate = focused, true + hit, found = focusHit, true + } } } + if !found { + hit, found = hoverHintHit(hits, id) + } if !found { hover.target, hover.shown = gfx.ID{}, gfx.ID{} return false @@ -396,6 +392,20 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g return true } +// hoverHintHit returns the front-most non-blocking hit for id that declares a +// non-empty Hint. +func hoverHintHit(hits []gfx.Hit, id gfx.ID) (gfx.Hit, bool) { + if id.IsZero() { + return gfx.Hit{}, false + } + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].ID == id && !hits[index].Block { + return hits[index], hits[index].Hint != "" + } + } + return gfx.Hit{}, false +} + // holdByFinger opens the tooltip of a control a finger held long enough to press it as a // right click, when nothing took that press (a control with a context menu takes it, as // on Android a long-click listener keeps the tooltip from showing). diff --git a/components/button.go b/components/button.go index 2c8c1809a..b2920c14c 100644 --- a/components/button.go +++ b/components/button.go @@ -377,26 +377,7 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { Invalid: button.state.Invalid, Disabled: button.disabled, }) } - radius := look.Radius - if look.Shadow != gfx.ShadowNone { - button.canvas.Elevate(button.bounds, radius, look.Shadow) // shadow-xs - } - if look.RingWidth > 0 { - if look.RingOutline { - button.canvas.RoundedOutline(expand(button.bounds, look.RingWidth), look.RingRadius, 2, look.Ring) - } else { - button.canvas.Rounded(expand(button.bounds, look.RingWidth), look.RingRadius, look.Ring) - } - } - style := buttonStyle{ - background: look.Background, foreground: look.Foreground, border: look.Border, - filled: look.Filled, bordered: look.Bordered, underlined: look.Underlined, - } - if style.bordered && style.filled { - paintBordered(button.canvas, button.theme, button.bounds, radius, style.border, style.background) - } else if style.filled { - button.canvas.Rounded(button.bounds, radius, style.background) - } + PaintButtonSurface(button.canvas, button.theme, button.bounds, look) area := button.bounds _, padding, _, _ := button.geometry() if !iconOnly && padding > 0 { @@ -415,8 +396,8 @@ func (button Button) paint(label string, variant ButtonVariant) ButtonResult { } hint := PaintButtonContent(button.canvas, area, ButtonContent{ Label: label, Icon: button.icon, IconTransform: button.iconTransform, - FontSize: fontSize, Weight: gfx.WeightMedium, Color: style.foreground, - Gap: buttonIconGap, Height: height, IconOnly: iconOnly, Underlined: style.underlined, + FontSize: fontSize, Weight: gfx.WeightMedium, Color: look.Foreground, + Gap: buttonIconGap, Height: height, IconOnly: iconOnly, Underlined: look.Underlined, }) if !button.id.IsZero() { button.canvas.HitWithOptions(button.id, button.bounds, label, gfx.HitOptions{ @@ -646,6 +627,45 @@ type ButtonContent struct { // function, not a closure made in each paint, which would allocate. type ButtonLoadingPainter func(canvas *gfx.Canvas, theme *gfx.Theme, bounds gfx.Rect, color gfx.Color, phase uint8) +// PaintButtonSurface paints a button's surface in bounds: its shadow, its focus +// ring, its fill and its border, for a look the caller resolved itself with +// ButtonRecipe or with a recipe of its own. It is the surface half of the paint +// BeginButton does, so a control that draws content of its own on a button's +// surface paints the same surface as a declared button; PaintButtonContent is +// the content half. +// +// The focus ring is a halo that reaches RingWidth beyond bounds. Under an opaque +// fill only the part outside the bounds can be seen, so the whole halo is painted +// with the fill over it; a button that paints no opaque fill (ghost or link, or +// one that is disabled) gets the halo as a line, since nothing would cover the +// middle of the disc. +func PaintButtonSurface(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, look ButtonLook) { + if canvas == nil || bounds.Width <= 0 || bounds.Height <= 0 { + return + } + radius := look.Radius + if look.Shadow != gfx.ShadowNone { + canvas.Elevate(bounds, radius, look.Shadow) // shadow-xs + } + if look.RingWidth > 0 { + halo := expand(bounds, look.RingWidth) + switch { + case look.RingOutline: + canvas.RoundedOutline(halo, look.RingRadius, 2, look.Ring) + case look.Filled && look.Background.Alpha >= 1: + canvas.Rounded(halo, look.RingRadius, look.Ring) + default: + canvas.RoundedOutline(halo, look.RingRadius, look.RingWidth, look.Ring) + } + } + switch { + case look.Bordered && look.Filled: + paintBordered(canvas, theme, bounds, radius, look.Border, look.Background) + case look.Filled: + canvas.Rounded(bounds, radius, look.Background) + } +} + // PaintButtonContent paints a button's icon and label centered in area and returns the // hint an icon-only button gives assistive technology, which is its label. It is the // content half of the paint the Button does: the same placement, the same shrinking of diff --git a/components/button_group.go b/components/button_group.go index d5977ddf1..c3a62bfb4 100644 --- a/components/button_group.go +++ b/components/button_group.go @@ -95,7 +95,16 @@ func (group ButtonGroup) Paint() ButtonGroupResult { framed = framed || option.Variant == ButtonOutline || option.Variant == ButtonDestructiveOutline if !group.disabled && !option.Disabled && !option.ID.IsZero() && group.canvas.FocusVisible() == option.ID { ring, _ := buttonRing(&group.theme, option.Variant, false) - group.canvas.Rounded(expand(group.optionBounds(index, float32(count)), 3), radius+3, ring) + halo := expand(group.optionBounds(index, float32(count)), 3) + // The halo is a disc under an action that paints an opaque fill; an action + // with no fill of its own gets it as a line, or the disc would fill the + // action's whole surface. + style := buttonStyleFor(&group.theme, option.Variant, group.canvas.Hovered() == option.ID, group.canvas.Pressed() == option.ID) + if style.filled && style.background.Alpha >= 1 { + group.canvas.Rounded(halo, radius+3, ring) + } else { + group.canvas.RoundedOutline(halo, radius+3, 3, ring) + } } } // The outline goes down first and the actions are painted inside it. diff --git a/components/button_group_test.go b/components/button_group_test.go index 2d092b853..c9562b7bc 100644 --- a/components/button_group_test.go +++ b/components/button_group_test.go @@ -121,3 +121,30 @@ func hasRectangleColor(canvas *gfx.Canvas, color gfx.Color) bool { } return false } + +// A ghost action in a group holds the keyboard like any other: its focus ring is a halo +// around it, and the disc a filled action hides under itself would fill the ghost's +// whole surface. +func TestFocusedGhostGroupActionKeepsItsMiddleClear(t *testing.T) { + options := [...]ButtonGroupOption{ + {ID: gfx.Item(61), Label: "Save", Variant: ButtonDefault}, + {ID: gfx.Item(62), Label: "More", Variant: ButtonGhost}, + } + var canvas gfx.Canvas + canvas.SetInteraction(gfx.ID{}, gfx.ID{}, gfx.Item(62), true) + BeginButtonGroup(&canvas, gfx.LightTheme(), gfx.Rect{Width: 240}, options[:]).Paint() + if len(canvas.Hits()) != len(options) { + t.Fatalf("hits = %+v", canvas.Hits()) + } + ghost := canvas.Hits()[1].Bounds + center := gfx.Point{X: ghost.X + ghost.Width/2, Y: ghost.Y + ghost.Height/2} + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color.Alpha <= 0 { + continue + } + box := rectangle.Bounds + if center.X > box.X && center.X < box.X+box.Width && center.Y > box.Y && center.Y < box.Y+box.Height { + t.Fatalf("the focus ring fills the ghost action's middle: %+v", rectangle) + } + } +} diff --git a/components/button_test.go b/components/button_test.go index 10549ab82..b95e84ac2 100644 --- a/components/button_test.go +++ b/components/button_test.go @@ -160,11 +160,17 @@ func TestButtonFocusAndInvalidRingsUseOfficialTokensInDark(t *testing.T) { if focusRing.Color != wantFocus || focusRing.Bounds != (gfx.Rect{X: 1, Y: 1, Width: 106, Height: 38}) { t.Fatalf("focus ring = %+v, want Ring/50 expanded 3px", focusRing) } - invalidRing := invalid.Rectangles()[0] + // The dark outline's surface is a translucent input tint, so nothing covers the + // middle of a ring disc: the invalid ring is the danger token drawn as a line, and + // the border keeps its own token. + ring := invalid.Triangles() wantInvalid := withAlpha(theme.Danger, 0.40) wantBorder := invalidBorder(&theme).Over(theme.Background) - if invalidRing.Color != wantInvalid || invalid.Rectangles()[1].Color != wantBorder { - t.Fatalf("invalid ring/border = %+v / %+v", invalidRing, invalid.Rectangles()[1]) + if len(ring) == 0 || ring[0].Color != wantInvalid { + t.Fatalf("invalid ring = %+v, want the danger/40 line", ring) + } + if invalid.Rectangles()[0].Color != wantBorder { + t.Fatalf("invalid border = %+v, want %+v", invalid.Rectangles()[0], wantBorder) } } @@ -315,3 +321,27 @@ func TestButtonFontSizeChangesOnlyTheLabel(t *testing.T) { t.Errorf("a bigger label fit in %v, no wider than %v", large, small) } } + +// A focused button that paints no fill keeps its middle: the focus ring is a halo +// around the button, and a disc under it would show through the surface. +func TestFocusedButtonRingDoesNotFillAnUnpaintedSurface(t *testing.T) { + theme := gfx.LightTheme() + bounds := gfx.Rect{X: 20, Y: 20, Width: 40, Height: 32} + center := gfx.Point{X: bounds.X + bounds.Width/2, Y: bounds.Y + bounds.Height/2} + for _, variant := range []ButtonVariant{ButtonGhost, ButtonLink} { + var canvas gfx.Canvas + BeginButton(&canvas, theme, gfx.Item(1), bounds).WithState(ButtonState{Focused: true}).paint("Open", variant) + if len(canvas.Triangles()) == 0 { + t.Fatalf("%v: a focused button drew no ring", variant) + } + for _, rectangle := range canvas.Rectangles() { + if rectangle.Color.Alpha <= 0 { + continue + } + box := rectangle.Bounds + if center.X > box.X && center.X < box.X+box.Width && center.Y > box.Y && center.Y < box.Y+box.Height { + t.Fatalf("%v: the ring fills the button's middle: %+v", variant, rectangle) + } + } + } +} diff --git a/components/code_diff.go b/components/code_diff.go index e1934a12b..512ccffc9 100644 --- a/components/code_diff.go +++ b/components/code_diff.go @@ -866,12 +866,16 @@ func (diff *CodeDiff) linesForValue(value string) ([]string, []int) { // Scroll applies a wheel or touchpad scroll to both panes. Horizontal deltas use // horizontal movement; Shift turns vertical delta into horizontal movement. func (diff *CodeDiff) Scroll(event gfx.ScrollEvent) gfx.EventResult { - diff.scrollX += event.DeltaX + dy := event.DeltaY + if event.Pages != 0 { + dy = event.StepYIn(1, float32(diff.visibleRows)*diff.rowHeight) + } + dx := event.DeltaX if event.Modifiers&gfx.ModifierShift != 0 { - diff.scrollX += event.DeltaY - } else { - diff.scrollY += event.DeltaY + dx, dy = dx+dy, 0 // Shift turns the vertical travel sideways } + diff.scrollX += dx + diff.scrollY += dy diff.clampScroll() return gfx.EventResult{Handled: true, Repaint: true} } diff --git a/components/code_editor_layout.go b/components/code_editor_layout.go index ea9a9696c..15a10ce61 100644 --- a/components/code_editor_layout.go +++ b/components/code_editor_layout.go @@ -705,7 +705,7 @@ func (editor *CodeEditor) Scroll(event gfx.ScrollEvent) gfx.EventResult { if !editor.painted { return gfx.EventResult{} } - dx, dy := event.StepX(editor.cellWidth), event.StepY(editor.lineHeight) + dx, dy := event.StepXIn(editor.cellWidth, editor.content.Width), event.StepYIn(editor.lineHeight, editor.content.Height) if event.Modifiers&gfx.ModifierShift != 0 && dx == 0 { dx, dy = dy, 0 } diff --git a/components/doc.go b/components/doc.go index 3abe264ff..f17601d23 100644 --- a/components/doc.go +++ b/components/doc.go @@ -74,9 +74,10 @@ // - Button: `BeginButton` paints a labeled control with Default, Secondary, // Outline, and Ghost variants; hover, press, and focus states, metrics- // scaled geometry, and the hit declaration are built in. -// `ButtonRecipe` is the look of a variant in a state as plain values, and +// `ButtonRecipe` is the look of a variant in a state as plain values; +// `PaintButtonSurface` paints that look's surface alone, and // `PaintButtonContent` paints a button's icon and label alone, centered in -// the area a surface the caller painted leaves for them. +// the area the surface leaves for them. // - Icon hover: `IconHover` plays one short gesture after an icon-only // control's pointer rests, and `Button.IconTransform` paints the resulting // transform inside the button's hit region. diff --git a/components/hierarchy_menu.go b/components/hierarchy_menu.go index 55ed916c4..70b47ac66 100644 --- a/components/hierarchy_menu.go +++ b/components/hierarchy_menu.go @@ -104,6 +104,9 @@ func PaintHierarchyMenu(canvas *gfx.Canvas, theme gfx.Theme, anchor gfx.Rect, m } // Move the cursor before any row is painted, as the flat list does. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } level, row, onRow := 0, 0, false if index, ok := hovered.In(o.OptionIDs); ok && index&0xFFFF != hierarchyBarRow { level, row, onRow = index>>16, index&0xFFFF, true diff --git a/components/multi_select.go b/components/multi_select.go index c822c07c1..b911ca927 100644 --- a/components/multi_select.go +++ b/components/multi_select.go @@ -155,6 +155,9 @@ func PaintMultiSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s *M // Move the cursor before any row is painted: syncing it while the rows are // drawn would tint the previous row and the new one in the same frame. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } if s.AdoptHover(hovered) && !hovered.IsZero() { for i := range choices { if o.OptionIDs.At(i) == hovered && !choices[i].Disabled { diff --git a/components/recipes_test.go b/components/recipes_test.go index b8d2e4894..3b5be6c2a 100644 --- a/components/recipes_test.go +++ b/components/recipes_test.go @@ -185,21 +185,7 @@ func TestButtonRecipePaintsTheSurfaceAsTheComponentDoes(t *testing.T) { var got gfx.Canvas look := ButtonRecipe(theme, variant, state) - if look.Shadow != gfx.ShadowNone { - got.Elevate(bounds, look.Radius, look.Shadow) - } - if look.RingWidth > 0 { - if look.RingOutline { - got.RoundedOutline(expand(bounds, look.RingWidth), look.RingRadius, 2, look.Ring) - } else { - got.Rounded(expand(bounds, look.RingWidth), look.RingRadius, look.Ring) - } - } - if look.Bordered && look.Filled { - paintBordered(&got, theme, bounds, look.Radius, look.Border, look.Background) - } else if look.Filled { - got.Rounded(bounds, look.Radius, look.Background) - } + PaintButtonSurface(&got, theme, bounds, look) // The underline of a hovered link belongs to the label, which this test has none of. var surface []gfx.Rectangle for _, r := range want.Rectangles() { diff --git a/components/single_select.go b/components/single_select.go index 6e007a313..fad55afe7 100644 --- a/components/single_select.go +++ b/components/single_select.go @@ -192,6 +192,9 @@ func PaintSingleSelect(canvas *gfx.Canvas, theme gfx.Theme, bounds gfx.Rect, s * // Move the cursor before any row is painted: syncing it while the rows are // drawn would tint the previous row and the new one in the same frame. hovered := canvas.Hovered() + if canvas.HoverFromLayout() { + hovered = gfx.ID{} + } if s.Hover.Entered(hovered) && !hovered.IsZero() { for i := range choices { if o.OptionIDs.At(i) == hovered && !choices[i].Disabled { diff --git a/components/tooltip.go b/components/tooltip.go index 7d9d52b14..5e1f6ffb2 100644 --- a/components/tooltip.go +++ b/components/tooltip.go @@ -352,24 +352,20 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g id, immediate = hovered, false } } - if hover.focus && hover.held.IsZero() { - if focused := canvas.FocusVisible(); !focused.IsZero() { - id, immediate = focused, true - } - } - if id.IsZero() { - hover.target, hover.shown = gfx.ID{}, gfx.ID{} - return false - } hits := canvas.Hits() var hit gfx.Hit found := false - for index := len(hits) - 1; index >= 0; index-- { - if hits[index].ID == id && !hits[index].Block { - hit, found = hits[index], hits[index].Hint != "" - break + if hover.focus && hover.held.IsZero() { + if focused := canvas.FocusVisible(); !focused.IsZero() { + if focusHit, ok := hoverHintHit(hits, focused); ok { + id, immediate = focused, true + hit, found = focusHit, true + } } } + if !found { + hit, found = hoverHintHit(hits, id) + } if !found { hover.target, hover.shown = gfx.ID{}, gfx.ID{} return false @@ -396,6 +392,20 @@ func (hover *HoverTooltip) Paint(canvas *gfx.Canvas, theme gfx.Theme, viewport g return true } +// hoverHintHit returns the front-most non-blocking hit for id that declares a +// non-empty Hint. +func hoverHintHit(hits []gfx.Hit, id gfx.ID) (gfx.Hit, bool) { + if id.IsZero() { + return gfx.Hit{}, false + } + for index := len(hits) - 1; index >= 0; index-- { + if hits[index].ID == id && !hits[index].Block { + return hits[index], hits[index].Hint != "" + } + } + return gfx.Hit{}, false +} + // holdByFinger opens the tooltip of a control a finger held long enough to press it as a // right click, when nothing took that press (a control with a context menu takes it, as // on Android a long-click listener keeps the tooltip from showing). diff --git a/components/tooltip_hover_test.go b/components/tooltip_hover_test.go index 2fe3a4496..ccc9064bc 100644 --- a/components/tooltip_hover_test.go +++ b/components/tooltip_hover_test.go @@ -117,6 +117,37 @@ func TestHoverTooltipShowsOnKeyboardFocusWhenAsked(t *testing.T) { } } +// When ShowOnFocus is enabled and the keyboard-focused control has no Hint +// (such as a terminal or text field), hovering another control with a Hint must +// still show that hovered control's tooltip. +func TestHoverTooltipFallsBackToHoverWhenFocusedControlHasNoHint(t *testing.T) { + var hover HoverTooltip + hover.ShowOnFocus() + viewport := gfx.Rect{Width: 300, Height: 200} + paint := func(now time.Duration) (*gfx.Canvas, bool) { + var canvas gfx.Canvas + canvas.SetClock(func() time.Duration { return now }) + canvas.BeginFrame() + canvas.HitWithOptions(gfx.Item(9), gfx.Rect{X: 0, Y: 0, Width: 200, Height: 120}, "Terminal", gfx.HitOptions{Role: gfx.RoleTerminal}) + canvas.HitWithOptions(gfx.Item(7), gfx.Rect{X: 220, Y: 10, Width: 28, Height: 28}, "Refresh", gfx.HitOptions{Role: gfx.RoleButton, Hint: "Refresh the list"}) + canvas.SetInteraction(gfx.Item(7), gfx.ID{}, gfx.Item(9), true) + painted := hover.Paint(&canvas, gfx.DarkTheme(), viewport, TooltipOptions{}, testTooltipDelay) + canvas.EndFrame() + return &canvas, painted + } + + if _, painted := paint(0); painted { + t.Fatal("hovered tooltip painted before its delay while focus had no hint") + } + canvas, painted := paint(testTooltipDelay) + if !painted || hover.Showing() != gfx.Item(7) { + t.Fatalf("painted=%v showing=%v, want hovered item 7", painted, hover.Showing()) + } + if _, ok := tooltipText(canvas, "Refresh the list"); !ok { + t.Fatalf("missing hovered tooltip text: %+v", canvas.Texts()) + } +} + // Escape (Dismiss) and a press anywhere hide the shown tooltip until the pointer // leaves the control, as Base UI's tooltip dismiss does. func TestHoverTooltipDismissesOnEscapeAndPress(t *testing.T) { diff --git a/components/tree.go b/components/tree.go index 8a3e644fe..7977d0f91 100644 --- a/components/tree.go +++ b/components/tree.go @@ -77,6 +77,9 @@ func (tree *Tree) Item(item TreeItem) TreeRow { hovered := enabled && tree.canvas.Hovered() == item.ID focused := enabled && !item.Dragging && tree.canvas.FocusVisible() == item.ID radius := tree.theme.Metrics.RadiusControl + if item.Background.Alpha > 0 { + tree.canvas.Fill(row, item.Background) + } if item.Selected || hovered { background := tree.theme.Muted if item.Selected { diff --git a/components/tree_test.go b/components/tree_test.go index 0856845cf..993b5f515 100644 --- a/components/tree_test.go +++ b/components/tree_test.go @@ -143,3 +143,44 @@ func TestTreeSelectedRowColourIsTheTrees(t *testing.T) { t.Fatal("a zero SelectedColor did not keep the theme's Accent") } } + +// Background paints a full-width, square-cornered wash behind the entire row +// before any selection highlight so consecutive tinted rows form one continuous band. +func TestTreeItemBackgroundPaintsFullWidthUnderSelection(t *testing.T) { + theme := gfx.LightTheme() + wash := gfx.RGBA(245, 200, 90, 0.25) + var canvas gfx.Canvas + tree := BeginTree(&canvas, theme, gfx.Rect{X: 0, Y: 0, Width: 240, Height: 64}).RowHeight(24) + row1 := tree.Item(TreeItem{ID: gfx.Item(1), Label: "rust", Depth: 1, Branch: true, Expanded: true, Selected: true, Background: wash}) + row2 := tree.Item(TreeItem{ID: gfx.Item(2), Label: "crates", Depth: 2, Branch: true, Background: wash}) + + rects := canvas.Rectangles() + washIdx, selIdx := -1, -1 + washCount := 0 + for i, r := range rects { + if r.Color == wash { + washCount++ + if washIdx < 0 { + washIdx = i + } + if r.Bounds.X != 0 || r.Bounds.Width != 240 || r.Bounds.Height != 24 { + t.Fatalf("wash rect did not span full row: got %+v", r.Bounds) + } + if r.Radius != 0 { + t.Fatalf("wash rect must be square-cornered for seamless bands, got radius %v", r.Radius) + } + } + if r.Color == theme.Accent && selIdx < 0 { + selIdx = i + } + } + if washCount != 2 { + t.Fatalf("expected 2 full-width wash rects, got %d", washCount) + } + if washIdx < 0 || selIdx < 0 || washIdx >= selIdx { + t.Fatalf("expected row background (%d) to paint underneath selection highlight (%d)", washIdx, selIdx) + } + if row1.Bounds.Y+row1.Bounds.Height != row2.Bounds.Y { + t.Fatalf("expected adjacent rows to touch seamlessly: row1=%+v row2=%+v", row1.Bounds, row2.Bounds) + } +} diff --git a/docs/audio.md b/docs/audio.md index 0123be2d1..7d8704810 100644 --- a/docs/audio.md +++ b/docs/audio.md @@ -1,4 +1,4 @@ -# Audio output +# Audio `audio` plays PCM on the system's default output device. It exists for a stream an application receives from elsewhere — a remote desktop's sound, a @@ -28,10 +28,35 @@ discarded. It is safe to call more than once. - It has no volume control. The stream follows the system's output volume and mute, which is what a remote desktop wants: the machine's own controls stay authoritative. -- It does not capture the microphone. Audio input is a separate capability and - is not implemented. - It does not exist on WebAssembly. `Open` returns `ErrUnsupported`. +## Microphone capture + +`audio.OpenInput` captures the system's default input device as the same +16-bit little-endian PCM. `Input` implements `io.ReadCloser`; nothing is opened +until it is called, and `Close` joins the capture goroutine and releases the +device. If the reader stalls, the oldest quarter-second is dropped rather than +blocking the device. Targets without a backend return `ErrInputUnsupported`. + +Opening the microphone is a privacy decision the operating system gates, so an +application declares it: + +- **macOS** asks the user once per application. The bundle must carry + `NSMicrophoneUsageDescription`, and a hardened-runtime build must be signed + with `com.apple.security.device.audio-input`. Both are project settings, not + code: put the usage string under `[mac.info]` and the entitlement in the + property list that `[mac] entitlements` points to. Without them macOS can + terminate the process or deliver silence, and `OpenInput` reports success + either way, so a capture of all zeros means the permission is missing, not + that the microphone is quiet. +- **Windows** gates desktop applications with Settings > Privacy > Microphone; + when access is off the device delivers silence. +- **Linux** has no per-application prompt; a sandbox such as Flatpak grants + access through its portal. + +An application should say why it listens before it calls `OpenInput`, and +should not open the device before the user asks for sound. + ## Backends | Target | Backend | Format handling | diff --git a/docs/notification-activation.md b/docs/notification-activation.md new file mode 100644 index 000000000..d06196094 --- /dev/null +++ b/docs/notification-activation.md @@ -0,0 +1,101 @@ +# Interactive system notifications + +Use `Application.ShowNotification` when a notification needs activation or +withdrawal. The existing comparable `app.Notification{Title, Body}` value and +`app.SendNotification` title/body-only function remain compatible. + +```go +handle, err := application.ShowNotification( + app.Notification{Title: "Download complete", Body: "Click to open the window."}, + app.NotificationEvents{ + OnActivate: func() { window.Show() }, + OnError: func(err error) { log.Printf("notification: %v", err) }, + }, +) +if err != nil { + // The request was rejected before native delivery could be accepted. + log.Printf("request notification: %v", err) +} +// Later, when this notification is no longer relevant: +handle.Close() +``` + +Call from startup or an event callback, like `AddStatusItem`. Both event handlers +are optional, and `Close` is nil-safe and safe from any goroutine. The application +marshals native signals onto its existing event loop: callbacks can restore or +open windows without a separate dispatch queue. At most one terminal event is +queued for a handle, and activation or error consumes its ownership. `Close` +invalidates queued events; a callback already running may finish. + +The application owns active handles and closes them on `Quit`, startup failure +or the end of `RunApplication`. Applications should also close stale handles +while running. A system dismissal does not promise a terminal event, so retaining +an arbitrary number of handles until process exit is not a resource policy. No +application-specific timeout, deduplication or navigation payload lives in Viva. + +## Support and host boundary + +`app.Supports(app.CapabilityNotificationActivation)` reports native build-target +support on desktop macOS and Windows. Other native platforms return +`app.ErrUnsupported`. Capabilities describe the build target, not what a custom +runtime host implements. + +A custom `app.Host` opts in with the public method: + +```go +ShowNotification(app.Notification, app.NotificationEvents) (app.NotificationControl, error) +``` + +The host returns a non-nil control promptly, reports asynchronous failures through +`OnError`, and may signal callbacks from native threads. Its control requests +withdrawal and invalidates native callbacks with an idempotent, any-goroutine +`Close`. No `internal/platform` import is required. A host without this optional +method returns `ErrUnsupported` instead of accidentally accessing the real OS; +headless applications can supply a synthetic host for notification tests. + +## Platform semantics + +- macOS uses `UNUserNotificationCenter`, requiring an application bundle + identifier and permission. The first request can ask for authorization + asynchronously. Denial is `app.ErrPermissionDenied`, delivered immediately or + through `OnError` according to when it is discovered. Closing while permission + is pending prevents late authorization from reinstating the request. A loose + command-line binary cannot stand in for packaged-app permission testing. +- Windows uses Shell notification-area balloons through the application's + message-only event-loop window, so closing an ordinary window does not retire + a notification. Each carrier has an independent full-width identifier; + callbacks are not routed through the last message sent. The legacy callback + layout preserves all 32 identifier bits instead of version 4's 16-bit field. + A title-only request is represented as body text because an empty Shell body + is a withdrawal request. Closing the loop removes remaining carriers. This is not a persistent toast + activation service and does not add activation after process exit. + +A successful request does not prove that the OS displayed it: notification policy, +quiet modes and Shell state can suppress delivery. Native field limits may +truncate text; UTF-16 truncation preserves surrogate pairs. The title and body +must contain valid UTF-8 without NUL and cannot both be blank. Closing requests +native withdrawal; the OS controls already-presented UI. Unhandled asynchronous +failures enter the structured `notification/delivery-failed` diagnostic stream, +not the recovered-panic fault stream. + +## Lifecycle and verification + +The framework starts no timer, polling loop or Go worker for interactive +notifications. Application tracking and native callback maps allocate lazily; +active requests retain text, callbacks and native resources until activation, +failure or explicit close. Programs that do not request notifications still carry +some linked code and additional application metadata; binary-size comparisons +should quantify that cost rather than claim it is zero. + +`examples/guides/notifications` provides show, withdraw and window-restore actions. +On macOS, package it with the normal Viva application-bundle tooling before +checking permission, notification-center delivery and activation. On Windows, +verify multiple notifications, ordinary-window closure, cancellation and loop +shutdown. Real OS delivery/permission verification is separate from unit tests. + +The automated contracts use a synthetic public host to test loop dispatch, +concurrent cancellation, one terminal event, errors, callbacks before host return, +late controls, startup failures and runner cleanup. Native Darwin tests exercise +actual bridge registry consumption and permission-error mapping without requesting +permission or presenting UI. Windows tests exercise callback identities, +wrong-host rejection, duplicate events, carrier cleanup and UTF-16 truncation. diff --git a/docs/releases/0.6.10.md b/docs/releases/0.6.10.md new file mode 100644 index 000000000..9f0a35a1a --- /dev/null +++ b/docs/releases/0.6.10.md @@ -0,0 +1,55 @@ +v0.6.10 是 v0.6.9 之后的版本:加入原生窗口水印、由应用事件循环接管的系统通知激活、跨平台麦克风采集,以及窗口装饰的即时切换;输入、剪贴板与绘制方面修复了 Caps Lock、被平台夺走的按下、Windows 与 GTK 的文件拖放回调、细描边亮度不均、静止指针下的悬停刷新等问题。macOS 是参考平台。 + +v0.6.10 comes after v0.6.9: native window watermarks, system notification activation owned by the application event loop, cross-platform microphone capture and live window decoration changes arrive, and input, clipboard and painting gain fixes for Caps Lock, a press the platform takes away, file-drop callbacks on Windows and GTK, uneven thin-stroke brightness and hover under a stationary pointer. macOS is the reference platform. + +## 拿到它 · Getting it + +`go get github.com/vivaui/viva@v0.6.10`,需要 Go 1.26 或更新;系统依赖与 v0.6.9 相同。每个 Release 附带 `viva` 命令的预编译压缩包、`SHA256SUMS`,以及 Homebrew 与 Scoop 清单(`brew install vivaui/tap/viva`,或 `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` 后 `scoop install viva`)。 + +`go get github.com/vivaui/viva@v0.6.10` needs Go 1.26 or newer; the system requirements are those of v0.6.9. Every Release carries prebuilt archives of the `viva` command, `SHA256SUMS`, and Homebrew and Scoop manifests (`brew install vivaui/tap/viva`, or `scoop bucket add vivaui https://github.com/vivaui/homebrew-tap` then `scoop install viva`). + +## 有什么 · What is in it + +- `Config.Watermark`、`Window.SetWatermark` 与 `CapabilityWindowWatermark` 在画布和内嵌原生视图(例如 web view)上方叠一层不接收输入的文字水印:macOS 用原生视图叠加,Windows 用点击穿透的分层弹窗,Linux 忽略,headless 只记录状态;自定义 host 可实现可选的 `SetWatermark(app.Watermark)`;`gfx.WeightLight` 补上细字重 (contributed by @darrenjindai) (PR [#462](https://github.com/vivaui/viva/pull/462))。 +- `Application.ShowNotification` 返回可在任意 goroutine 关闭的句柄,`OnActivate` 与 `OnError` 回调排到应用事件循环上执行,点击通知即可恢复或打开窗口,`Close` 撤回通知,权限被拒时报告 `ErrPermissionDenied`;macOS 用 UNUserNotificationCenter,Windows 用唤醒窗口上的托盘气泡,其他平台返回 `ErrUnsupported`,`CapabilityNotificationActivation` 报告平台是否支持 (contributed by @darrenjindai) (PR [#475](https://github.com/vivaui/viva/pull/475))。 +- `audio.OpenInput` 从默认输入设备采集 16 位小端 PCM,`Input` 实现 `io.ReadCloser`;macOS 用 CoreAudio,Windows 用 WASAPI,Linux 用 ALSA,其他平台返回 `ErrInputUnsupported`;macOS 的麦克风授权与 bundle 键见 `docs/audio.md` (contributed by @DeanCen) (PR [#483](https://github.com/vivaui/viva/pull/483))。 +- `Window.SetDecorated` 在已显示的窗口上切换原生装饰,并在确认后通过 `done` 报告一次结果。 +- 窗口可以让控件声明自己的指针光标,指针悬停时跟随命中项的光标图片,状态项在原生悬停时可预览;菜单项可以加字母助记键;`TextArea` 在 `Secure` 时把内容显示为圆点;剪贴板可以放入承诺文件;被省略的标签悬停时显示全文,只读文本可在 `TextSelectionArea` 中选择并复制。 +- 新增 `ui/overflowlist`(折进「更多」菜单的工具栏行)、统计、输入标签、自动补全与指示器控件;`CodeEditor` 增加跟随编辑的折叠状态、可点击的折叠省略徽标、行号栏与字节装饰。 +- `gfx` 可以在设备像素上绘制调用方的位图,`HitOptions` 有了 `IsZero`;颜色选择器的无效 HEX 提示已本地化;headless 脚本可以把复制的文件放上剪贴板。 +- 细描边在三角形与裁剪之间保持均匀覆盖:竖直细线与被裁剪的图标描边不再沿长度方向忽明忽暗 (contributed by @mirakyux) (PR [#488](https://github.com/vivaui/viva/pull/488))。 +- 布局变化后,静止的指针下的控件在同一帧得到悬停与光标,菜单不会因此丢掉键盘的当前行 (contributed by @mirakyux) (PR [#487](https://github.com/vivaui/viva/pull/487))。 +- 工具提示在获得焦点的控件没有 `Hint` 时回退到悬停;被应用处理的 Tab 不再显现键盘焦点 (contributed by @DeanCen) (PR [#481](https://github.com/vivaui/viva/pull/481))。 +- 无填充按钮的焦点环画成光晕而不是盖满表面,`viva add button` 与 `button-group` 装出的代码与参考组件一致 (contributed by @caichangqing1120) (PR [#484](https://github.com/vivaui/viva/pull/484))。 +- Caps Lock 作为按键交给应用;被平台夺走的按下会正常结束;页面按一格滚动时使用区域自己的屏幕。 +- Windows 监听的目录被移走并在原路径重建时,现在会报告 Resync (contributed by @1lck) (PR [#485](https://github.com/vivaui/viva/pull/485));Windows 在首帧前应用显示器的 DPI,`WindowNotification` 的原点以物理像素报告 (contributed by @Ezreal-byte) (PR [#479](https://github.com/vivaui/viva/pull/479)),并在 Windows 与 GTK 上保护文件拖放回调 (contributed by @Ezreal-byte) (PR [#480](https://github.com/vivaui/viva/pull/480))。 +- Windows 在注册字体里绘制回退字形,且剪贴板事务固定在同一个系统线程上;Linux 读取放下选择时带上 `XdndDrop` 时间戳,字体列表包含双宽与未标记的等宽字体,门户的初始目录得到转发。 +- Web 与 dev 构建恢复了光标图片回调 (contributed by @caichangqing1120) (PR [#477](https://github.com/vivaui/viva/pull/477));增量渲染的混合删除与插入不再重建整页,批处理的临时空间在页面缩小后释放,每次绘制只对已发布的命中区域比较一次。 +- `viva init` 与 `viva add` 的组件模板已按源码重新生成。 + +- `Config.Watermark`, `Window.SetWatermark` and `CapabilityWindowWatermark` lay a text watermark over the canvas and over embedded native views such as a web view, without taking input: macOS uses a native overlay view, Windows a click-through layered popup, Linux ignores it, and headless only records the state; a custom host may implement the optional `SetWatermark(app.Watermark)`, and `gfx.WeightLight` adds a light weight (contributed by @darrenjindai) (PR [#462](https://github.com/vivaui/viva/pull/462)). +- `Application.ShowNotification` returns a handle closable from any goroutine; its `OnActivate` and `OnError` callbacks run on the application event loop, so a click can restore or open a window, `Close` withdraws the notification, and a refused permission is reported as `ErrPermissionDenied`; macOS uses UNUserNotificationCenter, Windows a tray balloon on the wake window, other targets return `ErrUnsupported`, and `CapabilityNotificationActivation` reports whether the platform has it (contributed by @darrenjindai) (PR [#475](https://github.com/vivaui/viva/pull/475)). +- `audio.OpenInput` captures 16-bit little-endian PCM from the default input device, and `Input` implements `io.ReadCloser`; macOS uses CoreAudio, Windows WASAPI and Linux ALSA, and other targets return `ErrInputUnsupported`; the macOS microphone permission and bundle keys are in `docs/audio.md` (contributed by @DeanCen) (PR [#483](https://github.com/vivaui/viva/pull/483)). +- `Window.SetDecorated` toggles native decorations on a shown window and reports the confirmed result once through `done`. +- A control can declare its own pointer cursor, the pointer follows a hit's cursor picture, a status item can be previewed on native hover, menu items take letter mnemonics, a `TextArea` shows its value as bullets when `Secure`, promised files can be put on the clipboard, an ellipsized label shows its full text on hover, and read-only text can be selected and copied in a `TextSelectionArea`. +- New are `ui/overflowlist` (a toolbar row that folds into a More menu) and statistic, input tag, autocomplete and indicator controls; `CodeEditor` gains edit-following fold state, a clickable ellipsis badge on folded lines, a gutter and byte decorations. +- `gfx` draws a caller's bitmap on device pixels and `HitOptions` has an `IsZero`; the color picker's invalid HEX message is localized; and a headless script can put copied files on the clipboard. +- A thin stroke keeps uniform coverage across triangles and clips: a thin vertical line or a clipped icon stroke no longer brightens and dims along its length (contributed by @mirakyux) (PR [#488](https://github.com/vivaui/viva/pull/488)). +- After a layout change the control under a stationary pointer takes hover and cursor in the same frame, and menus keep the keyboard's current row (contributed by @mirakyux) (PR [#487](https://github.com/vivaui/viva/pull/487)). +- A tooltip falls back to hover when the focused control has no `Hint`, and a Tab the application handled no longer shows keyboard focus (contributed by @DeanCen) (PR [#481](https://github.com/vivaui/viva/pull/481)). +- An unfilled button's focus ring is drawn as a halo rather than covering its surface, and `viva add button` and `button-group` install what the reference components draw (contributed by @caichangqing1120) (PR [#484](https://github.com/vivaui/viva/pull/484)). +- Caps Lock reaches the application as a key, a press the platform takes away ends cleanly, and a page notch scrolls by the region's own screen. +- A watched directory on Windows that is moved away and recreated at the same path now reports a Resync (contributed by @1lck) (PR [#485](https://github.com/vivaui/viva/pull/485)); Windows applies the monitor's DPI before the first frame and reports the `WindowNotification` origin in physical pixels (contributed by @Ezreal-byte) (PR [#479](https://github.com/vivaui/viva/pull/479)), and file-drop callbacks are guarded on Windows and GTK (contributed by @Ezreal-byte) (PR [#480](https://github.com/vivaui/viva/pull/480)). +- Windows draws fallback glyphs from registered fonts and keeps clipboard transactions on one OS thread; Linux passes the `XdndDrop` timestamp when it reads the drop selection, lists dual-width and unflagged monospace fonts, and forwards the initial directory to the portal. +- The Web and dev builds have their cursor image callbacks back (contributed by @caichangqing1120) (PR [#477](https://github.com/vivaui/viva/pull/477)); incremental rendering applies mixed deletes and inserts without a rebuild, batch scratch is released once the page shrinks, and each paint diffs its hits against the published ones once. +- The component templates `viva init` and `viva add` install are regenerated from the sources. + +## 注意 · Caveats + +- 没有不兼容的 API 变更。 +- 在 macOS 上使用 `audio.OpenInput` 的应用必须在 bundle 中声明 `NSMicrophoneUsageDescription`(`[mac.info]`),启用 hardened runtime 时还要在 `[mac] entitlements` 指向的文件中加入 `com.apple.security.device.audio-input`;缺少时系统可能终止进程或交付静音,而 `OpenInput` 仍报告成功。 +- 水印与通知激活没有在 Linux 上实现;Windows 的水印叠加层 z 序与真机验收尚未验证。 + +- There are no incompatible API changes. +- An application that calls `audio.OpenInput` on macOS must declare `NSMicrophoneUsageDescription` in its bundle (`[mac.info]`) and, under the hardened runtime, `com.apple.security.device.audio-input` in the file `[mac] entitlements` names; without them the system may terminate the process or deliver silence while `OpenInput` still reports success. +- Watermarks and notification activation are not implemented on Linux; the Windows watermark overlay's z-order and real-device behaviour are not yet verified. diff --git a/docs/window-watermark.md b/docs/window-watermark.md new file mode 100644 index 000000000..3d61c46f5 --- /dev/null +++ b/docs/window-watermark.md @@ -0,0 +1,92 @@ +# Native window watermarks + +A native watermark is an input-transparent tiled text overlay above both canvas +content and embedded native views. It belongs to a window, including an +`OpenContentWindow` document or tool window. Text, identity and coverage policy +belong to the application. + +```go +config := app.Config{ + Title: "Document", + Width: 800, Height: 500, + Watermark: app.Watermark{Text: "DRAFT"}, +} +``` + +Text alone is visible: the zero color selects neutral linear gray at 12% opacity, +zero font size selects 12 logical pixels, and the tile defaults to 240 by 180 +logical pixels. Text is centered horizontally and vertically using font metrics. +There is no SVG baseline parameter. Empty text, including `app.Watermark{}`, +removes the overlay. A nonzero color is used exactly, including its alpha. + +For explicit styling, use existing framework types: + +```go +config.Watermark = app.Watermark{ + Text: "CONFIDENTIAL", + FontWeight: gfx.WeightLight, + FontFamily: "Arial", // optional; empty uses the native system font + Angle: -25, + Insets: gfx.All(24), +} +``` + +The watermark's typography is explicit and independent of interface-font state. +Applications that want the same family pass their selected family when updating +the watermark. This avoids making window composition depend on the canvas text +engine or on process-global font changes. Native fallback handles missing faces +and glyphs. Weight uses the same scale and constants as `gfx.TextStyle.Weight`. + +`app.Supports(app.CapabilityWindowWatermark)` reports native support on macOS and +Windows. Capabilities are static for a build target, rather than a runtime-host +promise. Other native platforms ignore initial configuration and return +`app.ErrUnsupported` for updates. The headless application host records normalized +state and accepts updates for lifecycle tests; it does not draw a native overlay. + +`window.SetWatermark(value)` and `contentWindow.SetWatermark(value)` are safe from +any goroutine. Validation completes before a request reaches the host. Windows +coalesces pending requests and applies the latest one on its window thread; +macOS applies on the main thread. Success means the request was accepted, not that +a frame is already presented. Later native failures use the diagnostic sink. +Custom `app.Host` controls implement the optional public method +`SetWatermark(app.Watermark) error`; no internal package import is required. + +Text must be valid UTF-8 without NUL or line breaks, at most 16 KiB. Color channels +must be finite and in [0,1], dimensions and insets finite and nonnegative, and +weight between `gfx.WeightLight` and `gfx.WeightBold`. Font size is at most 4096, +tile sides at most 8192 logical pixels; a native tile is additionally limited to +8192 pixels per side and 16 Mpixels at the actual backing scale. Invalid public +requests leave existing state intact. Windows restores prior configuration if +native application of an accepted request fails. + +## Lifecycle and cost + +No watermark view or popup is created for an empty watermark. Enabled macOS +windows retain a small backing-scale text tile and clipping/composition layers. +The inverse-rotated clip rectangle bounds the pattern plane and keeps its origin +stable during resize. An unattached view waits for the real window's backing +scale before generating a tile. + +Enabled Windows windows retain a 4-byte-per-pixel client DIB, a small tile and +Direct2D resources. The client DIB is released while hidden or minimized. +Translation reuses retained pixels; rotation and insets do not rasterize text +again. Resize follows the window's existing resize scheduler. The owned overlay +tracks its owner's topmost promotion and demotion. + +## Reproduce and verify + +Run `go run ./examples/guides/watermark` on macOS or Windows. Verify button input, +resize, mixed-DPI moves, hide/show, and removal through `SetWatermark` with empty +text. To exercise native-view stacking, configure a web view in the same window +and verify that the watermark covers it while text selection and scrolling still +reach the page. + +Automated contracts cover normalization, visible zero-value styling, bounds, +public-host forwarding, content-window forwarding and headless retention/close. +The native macOS fixture creates real CoreText lines and CGPatterns, tests +centering, backing-scale orientation, inverse-rotation coverage, view stacking, +clipping and input transparency, without drawing text or taking screenshots. +Windows native tests additionally exercise topmost transitions and retained +translation/resize behavior; cross-compilation alone does not verify those tests +on a Windows desktop. Real-device visual acceptance is separate from these +contracts. diff --git a/examples/guides/notifications/main.go b/examples/guides/notifications/main.go new file mode 100644 index 000000000..f9f84b86c --- /dev/null +++ b/examples/guides/notifications/main.go @@ -0,0 +1,43 @@ +package main + +import ( + "log" + + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/ui" +) + +func main() { + err := app.RunApplication(func(application *app.Application) error { + var window *app.Window + var latest *app.NotificationHandle + var err error + window, err = ui.OpenWindow(application, app.Config{Title: "System notifications", Width: 600, Height: 300}, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Gap(12).Children(func() { + if !app.Supports(app.CapabilityNotificationActivation) { + ui.Text(c, "Interactive notifications are not supported on this target.") + return + } + ui.Text(c, "On macOS, run the packaged application and allow system notifications.") + if ui.Button(c, "Show notification").Clicked() { + latest.Close() + latest, err = application.ShowNotification(app.Notification{Title: "Viva", Body: "Click to restore the application window."}, app.NotificationEvents{ + OnActivate: func() { window.Show() }, + OnError: func(err error) { log.Printf("notification delivery: %v", err) }, + }) + if err != nil { + log.Printf("request notification: %v", err) + } + } + if ui.Button(c, "Withdraw notification").Clicked() { + latest.Close() + latest = nil + } + }) + }}) + return err + }) + if err != nil { + log.Fatal(err) + } +} diff --git a/examples/guides/watermark/main.go b/examples/guides/watermark/main.go new file mode 100644 index 000000000..1d633af98 --- /dev/null +++ b/examples/guides/watermark/main.go @@ -0,0 +1,21 @@ +// A native watermark stays above embedded views without receiving input. +package main + +import ( + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/ui" + "log" +) + +func main() { + config := app.Config{Title: "Native watermark", Width: 800, Height: 500} + if app.Supports(app.CapabilityWindowWatermark) { + config.Watermark = app.Watermark{Text: "DRAFT", Angle: -25, FontWeight: gfx.WeightLight, Insets: gfx.All(24)} + } + if err := ui.Run(config, ui.PageConfig{View: func(c ui.C) { + ui.Column(c).Fill().Pad(24).Children(func() { ui.Button(c, "The watermark does not intercept input") }) + }}); err != nil { + log.Fatal(err) + } +} diff --git a/gfx/canvas.go b/gfx/canvas.go index 8bfd38730..6a7600376 100644 --- a/gfx/canvas.go +++ b/gfx/canvas.go @@ -124,6 +124,13 @@ var shadowLayers = [...][2]struct { ShadowLG: {{ShadowStyle{OffsetY: 10, Blur: 15, Spread: -3}, 0.10}, {ShadowStyle{OffsetY: 4, Blur: 6, Spread: -4}, 0.10}}, } +// StrokeCoverage describes the uncut triangle of a stroke quad. All pieces +// cut from the same triangle use these coordinates for edge feathering. +type StrokeCoverage struct { + Points [3]Point + EdgeMask uint8 +} + // Triangle is one solid vector-mesh primitive. Paths are tessellated into // triangles so native backends need no SVG parser or general geometry engine. type Triangle struct { @@ -141,7 +148,14 @@ type Triangle struct { // boundary. Bit 0 is Points[0]→Points[1], bit 1 is Points[1]→Points[2], // and bit 2 is Points[2]→Points[0]. Renderers feather only these edges; // shared tessellation edges stay fully covered. + // Bit 3 marks one half of a stroke quad: the long edge is 0→1 when bit 0 + // is set, otherwise 2→0. Its opposite boundary is parallel through the + // remaining point. Both boundaries constrain coverage, whichever half the + // quad's internal diagonal assigns a pixel to. EdgeMask uint8 + // Coverage, when present, gives a flat clipped stroke its original + // silhouette. Points and EdgeMask still control which pixels it owns. + Coverage *StrokeCoverage ClipOf Rect HasClip bool // Order is where the triangle was painted among every primitive of the @@ -818,13 +832,14 @@ type Canvas struct { touched bool // prevHovered is the hit the pointer was on at the end of the previous // paint, which is what HoverCrossed compares against. - prevHovered ID - pressed ID - focused ID - scrollX float32 - scrollY float32 - trappedScope ID - escapeTarget ID + prevHovered ID + hoverFromLayout, prevHoverFromLayout bool + pressed ID + focused ID + scrollX float32 + scrollY float32 + trappedScope ID + escapeTarget ID // The focus-scope depth each overlay claim was made at. A claim from a // deeper scope (a popup inside a dialog) wins over an outer one however // late the outer overlay finishes painting; equal depths let the later @@ -1103,6 +1118,7 @@ func (canvas *Canvas) Reset() { canvas.focusReturns = canvas.focusReturns[:0] canvas.trapDepth, canvas.escapeDepth, canvas.initialDepth = -1, -1, -1 canvas.prevHovered = canvas.hovered + canvas.prevHoverFromLayout = canvas.hoverFromLayout canvas.listensForClicks = false canvas.listensForPointer = false } @@ -2183,6 +2199,7 @@ func (canvas *Canvas) Clips() []Clip { // runtime-facing; application paint code should only read it. func (canvas *Canvas) SetInteraction(hovered, pressed, focused ID, focusVisible bool) { canvas.hovered = hovered + canvas.hoverFromLayout = false canvas.hoveredRole = 0 canvas.onSurface = false canvas.pressed = pressed @@ -2195,6 +2212,19 @@ func (canvas *Canvas) Hovered() ID { return canvas.hovered } +// HoverFromLayout reports that the current hover was found after layout moved +// hits under a stationary pointer. It can update the highlight without +// moving a menu's keyboard cursor. +func (canvas *Canvas) HoverFromLayout() bool { + return canvas.hoverFromLayout +} + +// SetHoverFromLayout records the source of the hover for this paint. It is +// runtime-facing; application paint code should only read it. +func (canvas *Canvas) SetHoverFromLayout(fromLayout bool) { + canvas.hoverFromLayout = fromLayout +} + // HoveredRole returns the role of the hovered hit, or the zero role when the // runtime did not record one. func (canvas *Canvas) HoveredRole() Role { @@ -2234,12 +2264,13 @@ func (canvas *Canvas) SetTitlebarInsets(leading, trailing float32) { canvas.titlebarLeading, canvas.titlebarTrailing = leading, trailing } -// HoverCrossed reports whether the pointer reached a different hit since the -// previous paint. Lists use it to move their current row onto the row the -// pointer entered, without letting a pointer that rests in place take the row -// back from the keyboard. +// HoverCrossed reports whether pointer input reached a different hit since the +// previous paint or moved within a hit that layout moved under the pointer. +// Lists use it to move their current row without taking it back from the +// keyboard while the pointer rests in place. func (canvas *Canvas) HoverCrossed() bool { - return canvas.hovered != canvas.prevHovered + return !canvas.hoverFromLayout && (canvas.hovered != canvas.prevHovered || + canvas.prevHoverFromLayout && !canvas.hovered.IsZero()) } // Pressed returns the hit ID currently held down, or the zero ID. diff --git a/gfx/embed.go b/gfx/embed.go index a3483198c..1b0d88bc5 100644 --- a/gfx/embed.go +++ b/gfx/embed.go @@ -31,6 +31,7 @@ func (canvas *Canvas) BeginEmbedded(parent *Canvas, mount Scope) { canvas.iconCache = parent.icons() tree := canvas.tree canvas.hovered, _ = tree.Local(mount, parent.hovered) + canvas.hoverFromLayout = parent.hoverFromLayout canvas.pressed, _ = tree.Local(mount, parent.pressed) canvas.focused, _ = tree.Local(mount, parent.focused) canvas.focusVisible = parent.focusVisible && !canvas.focused.IsZero() @@ -86,6 +87,11 @@ func (canvas *Canvas) Embed(child *Canvas, origin Point, mount Scope) { triangle.Points[index].X += origin.X triangle.Points[index].Y += origin.Y } + if triangle.Coverage != nil { + coverage := *triangle.Coverage + coverage.Points = translatePoints(coverage.Points, origin) + triangle.Coverage = &coverage + } triangle.Layer += layer triangle.Order += orderBase triangle.ClipOf, triangle.HasClip = embedClip(triangle.ClipOf, triangle.HasClip, origin, outer, hasOuter) diff --git a/gfx/icon_cache.go b/gfx/icon_cache.go index 92bf58aa6..ada4f42ad 100644 --- a/gfx/icon_cache.go +++ b/gfx/icon_cache.go @@ -251,6 +251,7 @@ func (canvas *Canvas) drawIconTrianglesPlaced(triangles []iconTriangle, icon Ico place.apply(cached.points[1]), place.apply(cached.points[2]), } + var coverage *StrokeCoverage emit := func(points [3]Point, edges uint8, weights [3][3]float32) { triangle := Triangle{ Points: points, Color: tint, Layer: state.layer, EdgeMask: edges, @@ -259,6 +260,12 @@ func (canvas *Canvas) drawIconTrianglesPlaced(triangles []iconTriangle, icon Ico if cached.layer >= 0 && !shadeIconTriangleAt(icon, tint, cached, weights, &triangle) { return } + if cached.edges&triangleStrokeQuad != 0 && edges&triangleStrokeQuad == 0 { + if coverage == nil { + coverage = &StrokeCoverage{Points: source, EdgeMask: cached.edges} + } + triangle.Coverage = coverage + } triangle.Order = canvas.nextOrder() canvas.triangles = append(canvas.triangles, triangle) } diff --git a/gfx/icon_clip.go b/gfx/icon_clip.go index eb3d43e8a..34ced99fa 100644 --- a/gfx/icon_clip.go +++ b/gfx/icon_clip.go @@ -123,6 +123,7 @@ func (shape iconClipShape) eachTriangle( // fixed vertex array, once per edge and per triangle. var polygons [2]iconClipPolygon current := 0 + unchanged := true for index := range points { var weights [3]float32 weights[index] = 1 @@ -139,6 +140,7 @@ func (shape iconClipShape) eachTriangle( to := cur.vertices[(vertex+1)%cur.count] fromInside := insideIconClip(a, b, from.point, sign) toInside := insideIconClip(a, b, to.point, sign) + unchanged = unchanged && fromInside if fromInside { next.add(from.point, from.boundary, from.weights) if !toInside { @@ -152,7 +154,13 @@ func (shape iconClipShape) eachTriangle( } current = 1 - current } - emitIconClipTriangles(&polygons[current], emit) + var sourceFlags uint8 + if unchanged { + // The stroke quad flag describes the original corners. A cut cannot + // reconstruct the opposite edge from its new corners. + sourceFlags = edges &^ triangleAllEdges + } + emitIconClipTriangles(&polygons[current], sourceFlags, emit) } // iconClipWeights interpolates barycentric weights along from→to. @@ -192,7 +200,7 @@ func iconClipIntersection(a, b Point, from, to iconClipVertex) (Point, float64) // pointer because the fan compacts the shared corner list in place, and a copy // of the fixed vertex array per clipped triangle is the cost that made a rounded // clip an order of magnitude slower than the other transforms. -func emitIconClipTriangles(polygon *iconClipPolygon, emit func([3]Point, uint8, [3][3]float32)) { +func emitIconClipTriangles(polygon *iconClipPolygon, sourceFlags uint8, emit func([3]Point, uint8, [3][3]float32)) { count := 0 for index := 0; index < polygon.count; index++ { next := polygon.vertices[(index+1)%polygon.count] @@ -211,7 +219,7 @@ func emitIconClipTriangles(polygon *iconClipPolygon, emit func([3]Point, uint8, if !clipFiniteArea(a.point, b.point, c.point) || cross > -1e-5 && cross < 1e-5 { continue } - var edges uint8 + edges := sourceFlags if index == 1 && a.boundary { edges |= 1 } diff --git a/gfx/icon_clip_raster_test.go b/gfx/icon_clip_raster_test.go new file mode 100644 index 000000000..c693c62f8 --- /dev/null +++ b/gfx/icon_clip_raster_test.go @@ -0,0 +1,59 @@ +package gfx_test + +import ( + "testing" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/framebuild" + "github.com/vivaui/viva/internal/raster" + "github.com/vivaui/viva/internal/render" +) + +func TestIconClipPreservesThinStrokeCoverage(t *testing.T) { + icon := gfx.Icon{ + ViewBox: 32, Stroke: 1, Cap: gfx.CapButt, + Commands: []gfx.PathCommand{gfx.MoveTo(12.25, 4), gfx.LineTo(12.25, 28)}, + } + bounds := gfx.Rect{Width: 32, Height: 32} + for _, test := range []struct { + name string + clip *gfx.IconClip + from int + to int + }{ + {name: "unclipped", from: 5, to: 27}, + {name: "contained", clip: &gfx.IconClip{Bounds: bounds}, from: 5, to: 27}, + {name: "cut", clip: &gfx.IconClip{Bounds: gfx.Rect{Y: 6, Width: 32, Height: 20}}, from: 6, to: 26}, + {name: "cut-rounded", clip: &gfx.IconClip{Bounds: gfx.Rect{Y: 6, Width: 24, Height: 20}, Radius: 10}, from: 6, to: 26}, + {name: "cut-across-width", clip: &gfx.IconClip{Bounds: gfx.Rect{X: 12, Y: 6, Width: 2, Height: 20}}, from: 6, to: 26}, + {name: "cut-away-both-edges", clip: &gfx.IconClip{Bounds: gfx.Rect{X: 12.375, Y: 6, Width: 0.25, Height: 20}}, from: 6, to: 26}, + } { + t.Run(test.name, func(t *testing.T) { + var canvas gfx.Canvas + canvas.DrawIconTransformed(icon, bounds, gfx.Color{Red: 1, Alpha: 1}, gfx.IconTransform{Clip: test.clip}) + instances := make([]render.Rectangle, 0, len(canvas.Triangles())) + for _, triangle := range canvas.Triangles() { + instances = append(instances, framebuild.SceneTriangle(triangle)) + } + pixels := raster.NewCanvas(32, 32) + var renderer raster.Rasterizer + renderer.Draw(pixels, raster.Params{Scale: 1}, instances, nil) + for y := test.from; y < test.to; y++ { + // The center at x=12.5 is a quarter pixel from the right + // stroke edge, giving 75% coverage regardless of the cut. + if got := pixels.Pix[y*pixels.Stride+12*4+3]; got < 190 || got > 192 { + t.Fatalf("alpha at (12, %d) = %d, want 191", y, got) + } + } + if test.from == 6 { + for _, y := range []int{5, 26} { + for x := 11; x <= 12; x++ { + if got := pixels.Pix[y*pixels.Stride+x*4+3]; got != 0 { + t.Fatalf("alpha outside clip at (%d, %d) = %d, want 0", x, y, got) + } + } + } + } + }) + } +} diff --git a/gfx/input.go b/gfx/input.go index 558e0a813..4bdc1eeed 100644 --- a/gfx/input.go +++ b/gfx/input.go @@ -252,9 +252,16 @@ type ScrollEvent struct { Y float32 DeltaX float32 DeltaY float32 - Viewport Size - Target ID - Precise bool + // Pages is how many screens the gesture is when the system's wheel setting + // asks for whole screens per notch, zero otherwise, and in the same + // direction as the delta of its axis. DeltaX and DeltaY are that many + // screens of the window, which is right only for what the window scrolls: + // a scroll region moves Pages of its own page instead, as StepYIn and + // StepXIn give it. + Pages float32 + Viewport Size + Target ID + Precise bool } // ScrollPhase is what a scroll event comes from. A wheel or a touchpad is the zero value @@ -281,15 +288,57 @@ const ( // which the pixel scale turns into a distance far below one row, so without the // floor several notches would pass before anything moves. A precise delta is // the distance the finger moved and is returned as it is. +// +// It is the whole window's step. A scroll region smaller than the window takes +// StepYIn instead, so a page notch is one of its pages and not one of the +// window's. func (e ScrollEvent) StepY(unit float32) float32 { return wheelStep(e.DeltaY, unit, e.Precise) } +// StepYIn is StepY for content of unit-sized rows inside a scroll region whose +// visible height is viewport. When the system asks for whole screens, the notch +// moves as many of the region's pages as Pages says, rounded down to whole rows, +// rather than the window-sized distance DeltaY carries; that is one screen of +// the region, which is a screen of the rows a user sees in it. +func (e ScrollEvent) StepYIn(unit, viewport float32) float32 { + if e.Pages == 0 || unit <= 0 || e.DeltaY == 0 { + return e.StepY(unit) + } + return pageStep(e.DeltaY, e.Pages, unit, viewport) +} + // StepX is StepY for DeltaX. func (e ScrollEvent) StepX(unit float32) float32 { return wheelStep(e.DeltaX, unit, e.Precise) } +// StepXIn is StepX for a sideways region whose visible width is viewport, as +// StepYIn is for a tall one. +func (e ScrollEvent) StepXIn(unit, viewport float32) float32 { + if e.Pages == 0 || unit <= 0 || e.DeltaX == 0 { + return e.StepX(unit) + } + return pageStep(e.DeltaX, e.Pages, unit, viewport) +} + +// pageStep is how far pages of a region of viewport units-by-unit move it in the +// direction of delta. +func pageStep(delta, pages, unit, viewport float32) float32 { + if pages < 0 { + pages = -pages + } + units := float32(int(pages * viewport / unit)) + if units < 1 { + units = 1 + } + step := units * unit + if delta < 0 { + return -step + } + return step +} + func wheelStep(delta, unit float32, precise bool) float32 { switch { case precise || delta == 0 || unit <= 0: diff --git a/gfx/path.go b/gfx/path.go index 655d56728..e138999e6 100644 --- a/gfx/path.go +++ b/gfx/path.go @@ -366,7 +366,10 @@ func (canvas *Canvas) dashStrokeContours(opaque bool, half float32, cap StrokeCa } } -const triangleAllEdges = uint8(1<<3 - 1) +const ( + triangleAllEdges = uint8(1<<3 - 1) + triangleStrokeQuad = uint8(1 << 3) +) func canonicalEdge(a, b Point) [4]uint32 { ax, ay := pointBits(a) @@ -529,6 +532,8 @@ func mergeCollinear(destination []Point, points []Point, closed bool, epsilon fl // appendStrokeQuad adds one offset rectangle for the segment from→to. The long // sides are always visible union boundaries. A cross edge is a boundary only // at an open butt cap; joins and explicit cap geometry cover every other one. +// Both triangles retain the stroke-quad flag so each fragment can account for +// the opposite long edge, including where the internal diagonal owns its fringe. func (canvas *Canvas) appendStrokeQuad(from, to Point, half float32, color Color, startCap, endCap bool) { dir := direction(from, to) normal := Point{X: -dir.Y * half, Y: dir.X * half} @@ -536,8 +541,8 @@ func (canvas *Canvas) appendStrokeQuad(from, to Point, half float32, color Color b := Point{X: to.X + normal.X, Y: to.Y + normal.Y} c := Point{X: to.X - normal.X, Y: to.Y - normal.Y} d := Point{X: from.X - normal.X, Y: from.Y - normal.Y} - firstMask := uint8(1 << 0) - secondMask := uint8(1 << 2) + firstMask := triangleStrokeQuad | 1<<0 + secondMask := triangleStrokeQuad | 1<<2 if startCap { firstMask |= 1 << 2 } diff --git a/gfx/path_test.go b/gfx/path_test.go index 9a50138a0..3526d4ea3 100644 --- a/gfx/path_test.go +++ b/gfx/path_test.go @@ -166,8 +166,8 @@ func TestDrawPathOpaqueStrokeDoesNotFeatherItsTriangleDiagonal(t *testing.T) { if len(triangles) != 2 { t.Fatalf("stroke triangles = %d, want 2", len(triangles)) } - if triangles[0].EdgeMask != 1<<0|1<<2 || triangles[1].EdgeMask != 1<<1|1<<2 { - t.Fatalf("stroke edge masks = %03b, %03b; shared diagonal must stay opaque", triangles[0].EdgeMask, triangles[1].EdgeMask) + if triangles[0].EdgeMask != triangleStrokeQuad|1<<0|1<<2 || triangles[1].EdgeMask != triangleStrokeQuad|1<<1|1<<2 { + t.Fatalf("stroke edge masks = %04b, %04b; both halves must retain the quad while the shared diagonal stays opaque", triangles[0].EdgeMask, triangles[1].EdgeMask) } } diff --git a/gfx/presence.go b/gfx/presence.go index 47114972e..50d0f0ead 100644 --- a/gfx/presence.go +++ b/gfx/presence.go @@ -648,6 +648,13 @@ func (transform presenceTransform) apply(canvas *Canvas, open presenceOpen, fade for corner := range triangle.Points { triangle.Points[corner] = transform.point(triangle.Points[corner]) } + if triangle.Coverage != nil { + coverage := *triangle.Coverage + for corner := range coverage.Points { + coverage.Points[corner] = transform.point(coverage.Points[corner]) + } + triangle.Coverage = &coverage + } if fade { triangle.Color = transform.color(triangle.Color) triangle.Shade[0] = transform.color(triangle.Shade[0]) diff --git a/gfx/replay.go b/gfx/replay.go index a17c7a677..12e741aff 100644 --- a/gfx/replay.go +++ b/gfx/replay.go @@ -374,9 +374,18 @@ func (canvas *Canvas) SameAsPrevious(span, prev Span, dx, dy float32) bool { // part painted ignores it: the copy's place among the other primitives is // checked by the span it lands in, not by the numbers. func sameRectangle(a, b Rectangle) bool { a.Order, b.Order = 0, 0; return a == b } -func sameTriangle(a, b Triangle) bool { a.Order, b.Order = 0, 0; return a == b } -func sameShadow(a, b Shadow) bool { a.Order, b.Order = 0, 0; return a == b } -func sameText(a, b Text) bool { a.Order, b.Order = 0, 0; return a == b } +func sameTriangle(a, b Triangle) bool { + if a.Coverage != b.Coverage { + if a.Coverage == nil || b.Coverage == nil || *a.Coverage != *b.Coverage { + return false + } + a.Coverage = b.Coverage + } + a.Order, b.Order = 0, 0 + return a == b +} +func sameShadow(a, b Shadow) bool { a.Order, b.Order = 0, 0; return a == b } +func sameText(a, b Text) bool { a.Order, b.Order = 0, 0; return a == b } func sameImage(a, b Image) bool { return a.Source == b.Source && a.Bounds == b.Bounds && a.Layer == b.Layer && a.ClipOf == b.ClipOf && a.HasClip == b.HasClip && diff --git a/gfx/scroll_test.go b/gfx/scroll_test.go index 7308be5e9..cd05518fb 100644 --- a/gfx/scroll_test.go +++ b/gfx/scroll_test.go @@ -23,3 +23,36 @@ func TestScrollStepRaisesClassicWheelToOneUnit(t *testing.T) { t.Errorf("StepX = %v, want -8", got) } } + +func TestPageStepMovesOnePageOfTheRegion(t *testing.T) { + // A page notch reports the window as pixels and the region's own page is + // what moves: whole rows that fit in the region, not the window's. + cases := []struct { + name string + event ScrollEvent + unit float32 + view float32 + want float32 + }{ + {"a page down in a short list", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 300, 300}, + {"a page up in a short list", ScrollEvent{DeltaY: -900, Pages: -1}, 30, 300, -300}, + {"rows that do not fit whole are left out", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 305, 300}, + {"two pages", ScrollEvent{DeltaY: 1800, Pages: 2}, 24, 200, 384}, + {"half a page of a trackpad setting", ScrollEvent{DeltaY: 450, Pages: 0.5}, 24, 200, 96}, + {"a region shorter than one row still moves a row", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 10, 30}, + {"a line notch is not a page", ScrollEvent{DeltaY: 48}, 30, 300, 48}, + {"a zero viewport keeps a row", ScrollEvent{DeltaY: 900, Pages: 1}, 30, 0, 30}, + } + for _, c := range cases { + if got := c.event.StepYIn(c.unit, c.view); got != c.want { + t.Errorf("%s: StepYIn(%v, %v) = %v, want %v", c.name, c.unit, c.view, got, c.want) + } + } + if got := (ScrollEvent{DeltaX: 900, Pages: 1}).StepXIn(10, 50); got != 50 { + t.Errorf("StepXIn = %v, want 50", got) + } + // A page setting does not turn a horizontal delta into a vertical page. + if got := (ScrollEvent{DeltaY: 900, Pages: 1}).StepXIn(10, 50); got != 0 { + t.Errorf("StepXIn on a vertical page = %v, want 0", got) + } +} diff --git a/gfx/theme.go b/gfx/theme.go index 09079f605..f6d1af0b3 100644 --- a/gfx/theme.go +++ b/gfx/theme.go @@ -6,6 +6,7 @@ import ( ) const ( + WeightLight float32 = -0.4 WeightRegular float32 = 0 WeightMedium float32 = 0.15 WeightSemibold float32 = 0.23 diff --git a/headless/application.go b/headless/application.go index aa9e89f9d..fc6744eaf 100644 --- a/headless/application.go +++ b/headless/application.go @@ -15,6 +15,7 @@ import ( "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" ) type applicationWindow struct { @@ -26,6 +27,7 @@ type applicationWindow struct { id uint64 title string icon app.WindowIcon + watermark platform.Watermark panel bool notification bool hidden bool @@ -87,7 +89,11 @@ func (application *applicationSession) Post(fn func()) { // OpenWindow implements app.Host. func (application *applicationSession) OpenWindow(config app.Config, canvas *gfx.Canvas, closed func()) (app.WindowControl, error) { - entry := &applicationWindow{icon: config.Icon} + watermark, err := headlessWatermark(config.Watermark) + if err != nil { + return nil, err + } + entry := &applicationWindow{icon: config.Icon, watermark: watermark} if config.Invalidator == nil { config.Invalidator = &app.Invalidator{} } @@ -745,3 +751,24 @@ func (application *applicationSession) afterCommand(reply string) (string, bool) } return strings.TrimSuffix(reply, "\n") + " windows=0\n", true } + +// SetWatermark records normalized state without claiming native composition support. +// The application lock provides the same any-goroutine contract as native controls. +func (window *headlessWindow) SetWatermark(request app.Watermark) error { + value, err := headlessWatermark(request) + if err != nil { + return err + } + window.application.mu.Lock() + defer window.application.mu.Unlock() + entry := window.application.windows[window.id] + if entry == nil { + return fmt.Errorf("headless: window is closed") + } + entry.watermark = value + return nil +} + +func headlessWatermark(value app.Watermark) (platform.Watermark, error) { + return platform.NormalizeWatermark(platform.Watermark{Text: value.Text, FontFamily: value.FontFamily, Color: platform.Color(value.Color), FontSize: value.FontSize, FontWeight: value.FontWeight, Angle: value.Angle, TileWidth: value.TileWidth, TileHeight: value.TileHeight, Insets: value.Insets}) +} diff --git a/headless/application_test.go b/headless/application_test.go index 1c7b83f30..2eddb9924 100644 --- a/headless/application_test.go +++ b/headless/application_test.go @@ -186,3 +186,38 @@ func TestProgressCommandReportsWhatTheIconWasAskedToShow(t *testing.T) { t.Fatalf("cleared: %q", text) } } + +func TestHeadlessWatermarkRecordsStateAndRejectsClosedUpdates(t *testing.T) { + application := newApplicationSession(Options{Scale: 1}) + defer application.closeAll() + control, err := application.OpenWindow(app.Config{Title: "watermark", Width: 200, Height: 100, Watermark: app.Watermark{Text: "DRAFT"}}, nil, func() {}) + if err != nil { + t.Fatal(err) + } + window := control.(*headlessWindow) + application.mu.Lock() + initial := application.windows[window.id].watermark + application.mu.Unlock() + if initial.Text != "DRAFT" || initial.Color.Alpha <= 0 { + t.Fatal("initial state was lost", initial) + } + value := app.Watermark{Text: "CONFIDENTIAL"} + if err := window.SetWatermark(value); err != nil { + t.Fatal(err) + } + invalid := value + invalid.Insets.Left = -1 + if err := window.SetWatermark(invalid); err == nil { + t.Fatal("invalid update accepted") + } + application.mu.Lock() + current := application.windows[window.id].watermark + application.mu.Unlock() + if current.Text != value.Text { + t.Fatal("invalid update changed retained state") + } + window.Close() + if err := window.SetWatermark(value); err == nil { + t.Fatal("closed host accepted update") + } +} diff --git a/headless/convert.go b/headless/convert.go index e2ff33f48..8bfb2fb2c 100644 --- a/headless/convert.go +++ b/headless/convert.go @@ -34,6 +34,13 @@ func scenery(snapshot app.Snapshot) ([]render.Rectangle, []platform.TextLabel, * if primitive.Shaded { rectangle.Shade = scene.Shade{On: true, Colors: [2]scene.Color{scene.Color(primitive.Shade[0]), scene.Color(primitive.Shade[1])}} } + if source := primitive.Coverage; source != nil { + coverage := scene.StrokeCoverage{EdgeMask: source.EdgeMask} + for point, position := range source.Points { + coverage.Points[point] = scene.Point(position) + } + rectangle.SetStrokeCoverage(coverage) + } for point := range rectangle.Points { rectangle.Points[point] = scene.Point{X: primitive.Points[point].X, Y: primitive.Points[point].Y} } diff --git a/headless/vector_aa_test.go b/headless/vector_aa_test.go index 8819b6fa5..02616b5dd 100644 --- a/headless/vector_aa_test.go +++ b/headless/vector_aa_test.go @@ -104,3 +104,116 @@ func TestVectorCoverageAtDeviceScales(t *testing.T) { }) } } + +// A stroke's internal diagonal must not change the coverage of either long edge, +// even near the ends where the triangle owning a pixel carries the opposite edge. +func TestVectorStrokeQuadCoverageIsUniform(t *testing.T) { + if !rendererAvailable { + t.Skip("native screenshots need the platform headless renderer") + } + r := newRenderer() + defer r.close() + for _, scale := range []float64{1, 1.25, 1.5, 2} { + for _, width := range []float64{1, 1.25, 2, 3} { + for _, reverse := range []bool{false, true} { + for _, cap := range []gfx.StrokeCap{gfx.CapButt, gfx.CapRound} { + t.Run(fmt.Sprintf("%gx/%gpx/reverse=%t/cap=%d", scale, width, reverse, cap), func(t *testing.T) { + const center = 12.25 + from, to := float32(4/scale), float32(28/scale) + if reverse { + from, to = to, from + } + var canvas gfx.Canvas + canvas.SetPixelScale(float32(scale)) + driver, err := app.NewDriver(app.Config{ + Title: "stroke coverage", Width: 32, Height: 32, ClearColor: app.Color{Alpha: 1}, + Paint: func(canvas *gfx.Canvas, size gfx.Size) { + path := canvas.PathBuilder() + path.MoveTo(float32(center/scale), from) + path.LineTo(float32(center/scale), to) + canvas.DrawPath(path.Path(size.Width, size.Height), gfx.Rect{Width: size.Width, Height: size.Height}, gfx.PathStyle{ + Stroke: gfx.Color{Red: 1, Green: 1, Blue: 1, Alpha: 1}, StrokeWidth: float32(width / scale), Cap: cap, + }) + }, + }, &canvas) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + pixels, err := r.render(driver.Snapshot(), scale) + if err != nil { + t.Fatal(err) + } + for x := 9; x <= 15; x++ { + // Coverage is the width of the intersection of this pixel and the stroke. + coverage := min(float64(x+1), center+width/2) - max(float64(x), center-width/2) + want := math.Round(255 * max(0, coverage)) + // Both cap styles end at least two device pixels outside this band. + for y := 6; y < 26; y++ { + if got := pixels.RGBAAt(x, y).R; math.Abs(float64(got)-want) > 2 { + t.Fatalf("stroke coverage at (%d,%d) = %d, want %g", x, y, got, want) + } + } + } + }) + } + } + } + } +} + +func TestVectorClippedStrokeCoverage(t *testing.T) { + if !rendererAvailable { + t.Skip("native screenshots need the platform headless renderer") + } + renderer := newRenderer() + defer renderer.close() + icon := gfx.Icon{ + ViewBox: 32, Stroke: 1, Cap: gfx.CapButt, + Commands: []gfx.PathCommand{gfx.MoveTo(12.25, 4), gfx.LineTo(12.25, 28)}, + } + bounds := gfx.Rect{Width: 32, Height: 32} + for _, tc := range []struct { + name string + clip gfx.IconClip + leftCoverage float64 + }{ + {name: "ends", clip: gfx.IconClip{Bounds: gfx.Rect{Y: 6, Width: 32, Height: 20}}, leftCoverage: 64}, + {name: "ends and side", clip: gfx.IconClip{Bounds: gfx.Rect{X: 12, Y: 6, Width: 2, Height: 20}}}, + {name: "rounded", clip: gfx.IconClip{Bounds: gfx.Rect{Y: 6, Width: 24, Height: 20}, Radius: 10}, leftCoverage: 64}, + } { + t.Run(tc.name, func(t *testing.T) { + driver, err := app.NewDriver(app.Config{ + Title: "clipped stroke coverage", Width: 32, Height: 32, ClearColor: app.Color{Alpha: 1}, + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.DrawIconTransformed(icon, bounds, gfx.Color{Red: 1, Alpha: 1}, gfx.IconTransform{Clip: &tc.clip}) + }, + }, nil) + if err != nil { + t.Fatal(err) + } + defer driver.Close() + pixels, err := renderer.render(driver.Snapshot(), 1) + if err != nil { + t.Fatal(err) + } + near := func(x, y int, want float64) { + t.Helper() + if got := pixels.RGBAAt(x, y).R; math.Abs(float64(got)-want) > 2 { + t.Fatalf("stroke coverage at (%d,%d) = %d, want %g", x, y, got, want) + } + } + // The 1px stroke spans x=11.75 to 12.75. The clipping side + // at x=12 removes the quarter pixel on the left. + for y := 6; y < 26; y++ { + near(11, y, tc.leftCoverage) + near(12, y, 191) + near(13, y, 0) + } + for _, y := range []int{5, 26} { + near(11, y, 0) + near(12, y, 0) + } + }) + } +} diff --git a/internal/filewatch/watch.go b/internal/filewatch/watch.go index 9a11be6c4..64c2d10b3 100644 --- a/internal/filewatch/watch.go +++ b/internal/filewatch/watch.go @@ -2,12 +2,12 @@ // directory tree, changed, using the // platform's own change notification (inotify, FSEvents, ReadDirectoryChangesW). // -// It does not poll. A Watch owns one operating-system registration and, while it -// is open, one goroutine blocked on the system's wait; closing it releases both, -// and an application that opens no Watch pays nothing. Events carry only the name -// of the entry that changed: editors replace files by writing a temporary one and -// renaming it, so the kinds the platforms report differ and none of them can be -// trusted over looking at the entry afterwards. +// It does not poll. A Watch owns its operating-system registrations and, while +// it is open, one goroutine blocked on the system's wait. Closing it releases +// them, and an application that opens no Watch pays nothing. Events carry only +// the name of the entry that changed: editors replace files by writing a +// temporary one and renaming it, so the kinds the platforms report differ and +// none of them can be trusted over looking at the entry afterwards. package filewatch import ( diff --git a/internal/filewatch/watch_windows.go b/internal/filewatch/watch_windows.go index 255c1c04e..ce0281122 100644 --- a/internal/filewatch/watch_windows.go +++ b/internal/filewatch/watch_windows.go @@ -21,12 +21,16 @@ var ( procCreateEvent = kernel32.NewProc("CreateEventW") procSetEvent = kernel32.NewProc("SetEvent") procWaitMultiple = kernel32.NewProc("WaitForMultipleObjects") + procFindFirstChange = kernel32.NewProc("FindFirstChangeNotificationW") + procFindNextChange = kernel32.NewProc("FindNextChangeNotification") + procFindCloseChange = kernel32.NewProc("FindCloseChangeNotification") ) const ( fileListDirectory = 0x0001 fileFlagOverlapped = 0x40000000 - filterChange = 0x1 | 0x2 | 0x8 | 0x10 | 0x40 // file/dir name, attributes, size, last write, creation + filterChange = 0x1 | syscall.FILE_NOTIFY_CHANGE_DIR_NAME | 0x8 | 0x10 | 0x40 // file/dir name, attributes, size, last write, creation + shareDirectory = syscall.FILE_SHARE_READ | syscall.FILE_SHARE_WRITE | syscall.FILE_SHARE_DELETE actionAdded = 1 actionRemoved = 2 actionModified = 3 @@ -48,6 +52,7 @@ type directoryBackend struct { handle syscall.Handle ioDone syscall.Handle stop syscall.Handle + root rootGuard done chan struct{} once sync.Once // overlapped and the read buffer are written by the system after the call @@ -57,12 +62,15 @@ type directoryBackend struct { } func openBackend(dir string, w *Watch) (backend, error) { - path, err := syscall.UTF16PtrFromString(filepath.Clean(dir)) + absolute, err := filepath.Abs(dir) if err != nil { return nil, err } - handle, err := syscall.CreateFile(path, fileListDirectory, - syscall.FILE_SHARE_READ|syscall.FILE_SHARE_WRITE|syscall.FILE_SHARE_DELETE, nil, + path, err := syscall.UTF16PtrFromString(absolute) + if err != nil { + return nil, err + } + handle, err := syscall.CreateFile(path, fileListDirectory, shareDirectory, nil, syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS|fileFlagOverlapped, 0) if err != nil { return nil, &os.PathError{Op: "CreateFile", Path: dir, Err: err} @@ -85,6 +93,7 @@ func openBackend(dir string, w *Watch) (backend, error) { syscall.CloseHandle(handle) return nil, &os.PathError{Op: "ReadDirectoryChangesW", Path: dir, Err: err} } + b.root = watchRootName(absolute, path, handle) go b.run(w) return b, nil } @@ -107,6 +116,51 @@ func (b *directoryBackend) close() { }) } +// ReadDirectoryChangesW follows the opened directory and never reports changes +// to that directory's own name. Watch direct directory names in its parent +// as well. This notification is only a signal: compare file IDs to distinguish +// a sibling change from a move or a different directory at the same path. +type rootGuard struct { + event syscall.Handle + path *uint16 + info syscall.ByHandleFileInformation +} + +func watchRootName(dir string, path *uint16, handle syscall.Handle) rootGuard { + parent := filepath.Dir(dir) + if parent == dir { + return rootGuard{} // volume root + } + var info syscall.ByHandleFileInformation + if syscall.GetFileInformationByHandle(handle, &info) != nil { + return rootGuard{} + } + parentPath, err := syscall.UTF16PtrFromString(parent) + if err != nil { + return rootGuard{} + } + event, _, _ := procFindFirstChange.Call(uintptr(unsafe.Pointer(parentPath)), 0, syscall.FILE_NOTIFY_CHANGE_DIR_NAME) + if syscall.Handle(event) == syscall.InvalidHandle { + // A caller can have access to the directory without being able to + // list its parent. Keep delivering the directory's own changes. + return rootGuard{} + } + return rootGuard{event: syscall.Handle(event), path: path, info: info} +} + +func (g *rootGuard) sameDirectory() bool { + h, err := syscall.CreateFile(g.path, 0, shareDirectory, nil, + syscall.OPEN_EXISTING, syscall.FILE_FLAG_BACKUP_SEMANTICS, 0) + if err != nil { + return false + } + defer syscall.CloseHandle(h) + var current syscall.ByHandleFileInformation + return syscall.GetFileInformationByHandle(h, ¤t) == nil && + current.VolumeSerialNumber == g.info.VolumeSerialNumber && + current.FileIndexHigh == g.info.FileIndexHigh && current.FileIndexLow == g.info.FileIndexLow +} + // issue starts the next overlapped read. The first one is made before Open // returns, because changes are only buffered by the system once a read has been // issued; later ones follow a completion, and the system keeps what happened in @@ -127,20 +181,50 @@ func (b *directoryBackend) issue() error { func (b *directoryBackend) run(w *Watch) { defer close(b.done) - for { - handles := [2]syscall.Handle{b.ioDone, b.stop} - which, _, _ := procWaitMultiple.Call(2, uintptr(unsafe.Pointer(&handles[0])), 0, infinite) - var n uint32 - if which != waitObject0 { - // Stopped (or the wait failed): abandon the read and wait for the system - // to stop writing into the buffer before it is released. + pending := true + defer func() { + if pending { + // Wait for the system to stop writing into the buffer before it + // is released. procCancelIoEx.Call(uintptr(b.handle), uintptr(unsafe.Pointer(&b.overlapped))) + var n uint32 procGetOverlappedResult.Call(uintptr(b.handle), uintptr(unsafe.Pointer(&b.overlapped)), uintptr(unsafe.Pointer(&n)), 1) - if which != waitObject0+1 { + } + }() + // Stop takes priority over further changes, and root changes take + // priority over events that may have come from the old directory. + handles := []syscall.Handle{b.stop, b.ioDone} + if b.root.event != 0 { + defer procFindCloseChange.Call(uintptr(b.root.event)) + handles = []syscall.Handle{b.stop, b.root.event, b.ioDone} + // The path may have changed before the parent notification was armed. + if !b.root.sameDirectory() { + w.postResync() + return + } + } + readReady := waitObject0 + uintptr(len(handles)-1) + for { + which, _, _ := procWaitMultiple.Call(uintptr(len(handles)), uintptr(unsafe.Pointer(&handles[0])), 0, infinite) + switch { + case which == waitObject0: + return + case which == readReady: + pending = false + case b.root.event != 0 && which == waitObject0+1: + // Rearm before looking up the path, so a change during the lookup + // either shows up in the lookup or signals the next wait. + ok, _, _ := procFindNextChange.Call(uintptr(b.root.event)) + if ok == 0 || !b.root.sameDirectory() { w.postResync() + return } + continue + default: + w.postResync() return } + var n uint32 r, _, err := procGetOverlappedResult.Call(uintptr(b.handle), uintptr(unsafe.Pointer(&b.overlapped)), uintptr(unsafe.Pointer(&n)), 0) if r == 0 { if errno, ok := err.(syscall.Errno); !ok || errno != errorOperationAbort { @@ -157,6 +241,7 @@ func (b *directoryBackend) run(w *Watch) { w.postResync() return } + pending = true } } diff --git a/internal/filewatch/watch_windows_test.go b/internal/filewatch/watch_windows_test.go new file mode 100644 index 000000000..f380d167d --- /dev/null +++ b/internal/filewatch/watch_windows_test.go @@ -0,0 +1,64 @@ +package filewatch + +import ( + "os" + "path/filepath" + "testing" + "time" +) + +func TestWindowsReplacingWatchedDirectoryAsksForResync(t *testing.T) { + for _, tree := range []bool{false, true} { + name := "directory" + if tree { + name = "tree" + } + t.Run(name, func(t *testing.T) { + parent := t.TempDir() + root := filepath.Join(parent, "workspace") + moved := filepath.Join(t.TempDir(), "moved") + if err := os.Mkdir(root, 0o700); err != nil { + t.Fatal(err) + } + woken := make(chan struct{}, 1) + watch, err := openWatch(root, tree, nil, func() { + select { + case woken <- struct{}{}: + default: + } + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(watch.Close) + + if err := os.Rename(root, moved); err != nil { + t.Fatalf("move watched root: %v", err) + } + if err := os.Mkdir(root, 0o700); err != nil { + t.Fatalf("recreate watched root: %v", err) + } + select { + case <-woken: + if p := watch.Drain(nil); !p.Resync || len(p.Names) != 0 { + t.Fatalf("root replacement reported %+v, want only Resync", p) + } + case <-time.After(4 * time.Second): + t.Fatal("root replacement did not wake the watch") + } + watch.Close() + if err := os.Remove(moved); err != nil { + t.Fatalf("remove the old root after Close: %v", err) + } + if err := os.Mkdir(moved, 0o700); err != nil { + t.Fatalf("reuse the old root path after Close: %v", err) + } + if err := os.RemoveAll(parent); err != nil { + t.Fatalf("remove the watched parent after Close: %v", err) + } + if err := os.Mkdir(parent, 0o700); err != nil { + t.Fatalf("reuse the watched parent path after Close: %v", err) + } + }) + } +} diff --git a/internal/framebuild/framebuild.go b/internal/framebuild/framebuild.go index 1e34fee67..269a0fd85 100644 --- a/internal/framebuild/framebuild.go +++ b/internal/framebuild/framebuild.go @@ -572,8 +572,11 @@ func min32(a, b float32) float32 { func (builder *Builder) drawnBy(stored *render.Rectangle, ref shapeRef) bool { if ref.triangle { triangle := &builder.clippedPaths[ref.index] + coverage, hasCoverage := stored.StrokeCoverage() return stored.Kind == scene.KindTriangle && stored.Color == scene.Color(triangle.Color) && - stored.EdgeMask == triangle.EdgeMask && stored.Shade == sceneShade(*triangle) && + stored.EdgeMask == triangle.EdgeMask && stored.Shade.On == triangle.Shaded && + (!triangle.Shaded || stored.Shade == sceneShade(*triangle)) && + strokeCoverageMatches(coverage, hasCoverage, triangle.Coverage) && stored.Points[0] == scene.Point(triangle.Points[0]) && stored.Points[1] == scene.Point(triangle.Points[1]) && stored.Points[2] == scene.Point(triangle.Points[2]) @@ -652,8 +655,9 @@ func (builder *Builder) syncShapes() { // setShape makes an existing node draw a shape, whatever it drew before. func (builder *Builder) setShape(id scene.ID, ref shapeRef) { if ref.triangle { - value := SceneTriangle(builder.clippedPaths[ref.index]) - builder.graph.SetTriangle(id, value.Points, value.Color, value.EdgeMask, value.Shade) + triangle := builder.clippedPaths[ref.index] + value := sceneTriangleGeometry(triangle) + builder.graph.SetTriangle(id, value.Points, value.Color, value.EdgeMask, value.Shade, sceneStrokeCoverage(triangle.Coverage)) return } if ref.shadow { @@ -667,8 +671,9 @@ func (builder *Builder) setShape(id scene.ID, ref shapeRef) { // insertShape adds a node drawing a shape right after previous. func (builder *Builder) insertShape(root, previous scene.ID, ref shapeRef) scene.ID { if ref.triangle { - value := SceneTriangle(builder.clippedPaths[ref.index]) - id, _ := builder.graph.InsertTriangle(root, previous, value.Points, value.Color, value.EdgeMask, value.Shade) + triangle := builder.clippedPaths[ref.index] + value := sceneTriangleGeometry(triangle) + id, _ := builder.graph.InsertTriangle(root, previous, value.Points, value.Color, value.EdgeMask, value.Shade, sceneStrokeCoverage(triangle.Coverage)) return id } if ref.shadow { @@ -947,6 +952,14 @@ func SceneRectangle(rectangle gfx.Rectangle) render.Rectangle { // SceneTriangle converts a canvas triangle to its render instance shape. func SceneTriangle(triangle gfx.Triangle) render.Rectangle { + rectangle := sceneTriangleGeometry(triangle) + if source := triangle.Coverage; source != nil { + rectangle.SetStrokeCoverage(*sceneStrokeCoverage(source)) + } + return rectangle +} + +func sceneTriangleGeometry(triangle gfx.Triangle) render.Rectangle { return render.Rectangle{ Kind: scene.KindTriangle, Points: [3]scene.Point{ @@ -964,6 +977,27 @@ func SceneTriangle(triangle gfx.Triangle) render.Rectangle { } } +func sceneStrokeCoverage(source *gfx.StrokeCoverage) *scene.StrokeCoverage { + if source == nil { + return nil + } + coverage := &scene.StrokeCoverage{EdgeMask: source.EdgeMask} + for index, point := range source.Points { + coverage.Points[index] = scene.Point(point) + } + return coverage +} + +func strokeCoverageMatches(stored scene.StrokeCoverage, hasCoverage bool, canvas *gfx.StrokeCoverage) bool { + if !hasCoverage || canvas == nil { + return !hasCoverage && canvas == nil + } + return stored.EdgeMask == canvas.EdgeMask && + stored.Points[0] == scene.Point(canvas.Points[0]) && + stored.Points[1] == scene.Point(canvas.Points[1]) && + stored.Points[2] == scene.Point(canvas.Points[2]) +} + // sceneShade is the vertex colors of a shaded triangle, and the zero Shade for a // flat one, whatever stale colors its Shade array holds. func sceneShade(triangle gfx.Triangle) scene.Shade { diff --git a/internal/platform/contract.go b/internal/platform/contract.go index 6004a6987..07806937f 100644 --- a/internal/platform/contract.go +++ b/internal/platform/contract.go @@ -23,7 +23,8 @@ type Color struct { // Config contains the data needed to create a native window. type Config struct { - Title string + Watermark Watermark + Title string // Class names the application to the desktop environment where it keeps // windows of one application together under a launcher entry (the X11 // WM_CLASS). Empty means the executable's file name. @@ -746,7 +747,12 @@ type ScrollEvent struct { Y float32 DeltaX float32 DeltaY float32 - Precise bool + // Pages is how many screens the gesture is, when the user's wheel setting + // is whole screens per notch; zero otherwise. DeltaX and DeltaY carry the + // same distance against the window, which is the page only for the window's + // own scrolling: a scroll region moves Pages of its own page instead. + Pages float32 + Precise bool } // ScrollHandler applies one scroll gesture and returns an optional repaint. diff --git a/internal/platform/darwin/callback.go b/internal/platform/darwin/callback.go index e948c923b..7f5ea9b28 100644 --- a/internal/platform/darwin/callback.go +++ b/internal/platform/darwin/callback.go @@ -1233,15 +1233,13 @@ func updateLabels(view unsafe.Pointer, labels []TextLabel) error { // layout: float4 bounds, float4 color, float4 style, float4 shade1, float4 // shade2. A shadow keeps its blur in the third style value and its offset and // spread in shade1 (see the Metal vertex shader). Triangles reuse the slot as bounds=(p0, p1), style=(p2.x, layer, p2.y, -// edgeMask+1), color, shade1 and shade2 being the colors of p0, p1 and p2. Zero -// continues to identify rectangles while values 1..8 identify triangles and -// their three independently feathered boundary edges. +// edgeFlags+1). PackTriangleCoverage defines the shade slots and edge flags. func makeNativeRectangle(rectangle render.Rectangle) C.viva_rectangle { if rectangle.Kind == scene.KindTriangle { - colors := rectangle.VertexColors() + marker, shade1, shade2 := platform.PackTriangleCoverage(rectangle) return C.viva_rectangle{ - shade1_red: C.float(colors[1].Red), shade1_green: C.float(colors[1].Green), shade1_blue: C.float(colors[1].Blue), shade1_alpha: C.float(colors[1].Alpha), - shade2_red: C.float(colors[2].Red), shade2_green: C.float(colors[2].Green), shade2_blue: C.float(colors[2].Blue), shade2_alpha: C.float(colors[2].Alpha), + shade1_red: C.float(shade1[0]), shade1_green: C.float(shade1[1]), shade1_blue: C.float(shade1[2]), shade1_alpha: C.float(shade1[3]), + shade2_red: C.float(shade2[0]), shade2_green: C.float(shade2[1]), shade2_blue: C.float(shade2[2]), shade2_alpha: C.float(shade2[3]), x: C.float(rectangle.Points[0].X), y: C.float(rectangle.Points[0].Y), width: C.float(rectangle.Points[1].X), @@ -1253,7 +1251,7 @@ func makeNativeRectangle(rectangle render.Rectangle) C.viva_rectangle { corner_radius: C.float(rectangle.Points[2].X), reserved0: C.float(rectangle.Layer), reserved1: C.float(rectangle.Points[2].Y), - reserved2: C.float(rectangle.EdgeMask + 1), + reserved2: C.float(marker), } } native := C.viva_rectangle{ diff --git a/internal/platform/darwin/native.h b/internal/platform/darwin/native.h index 9e3e6fdaa..36863dc09 100644 --- a/internal/platform/darwin/native.h +++ b/internal/platform/darwin/native.h @@ -1,3 +1,4 @@ +#include "watermark_darwin.h" #ifndef VIVA_INTERNAL_PLATFORM_DARWIN_NATIVE_H #define VIVA_INTERNAL_PLATFORM_DARWIN_NATIVE_H @@ -304,6 +305,7 @@ enum { typedef struct { const char *title; + viva_watermark watermark; int width; int height; int min_width; diff --git a/internal/platform/darwin/native.m b/internal/platform/darwin/native.m index 50af4326f..e9d9988bd 100644 --- a/internal/platform/darwin/native.m +++ b/internal/platform/darwin/native.m @@ -3582,6 +3582,9 @@ - (BOOL)canBecomeMainWindow { @end @interface VivaAppDelegate : NSObject { + viva_watermark _initialWatermark; + NSString *_initialWatermarkText; + NSString *_initialWatermarkFamily; NSRect _anchor; BOOL _hasAnchor; BOOL _hasOrigin; @@ -3703,6 +3706,11 @@ - (instancetype)initWithConfig:(viva_window_config)config self = [super init]; if (self != nil) { _title = [[NSString alloc] initWithUTF8String:config.title]; + _initialWatermark = config.watermark; + _initialWatermarkText = [[NSString alloc] initWithUTF8String:config.watermark.text ?: ""]; + _initialWatermark.text = NULL; + _initialWatermarkFamily = [[NSString alloc] initWithUTF8String:config.watermark.font_family ?: ""]; + _initialWatermark.font_family = NULL; _width = config.width; _height = config.height; _minWidth = config.min_width; @@ -3766,6 +3774,8 @@ - (void)dealloc { } [_titlebarWatched release]; [_window release]; + [_initialWatermarkText release]; + [_initialWatermarkFamily release]; [_title release]; [_rectangleBuffer release]; [_rectanglePipeline release]; @@ -3882,6 +3892,12 @@ - (void)applicationDidFinishLaunching:(NSNotification *)notification { return; } _window.contentView = view; + // UTF-8 pointers are borrowed only for this synchronous consumption. + _initialWatermark.text = _initialWatermarkText.UTF8String; + _initialWatermark.font_family = _initialWatermarkFamily.UTF8String; + viva_watermark_apply(view, _initialWatermark); + _initialWatermark.text = NULL; + _initialWatermark.font_family = NULL; if (_fileDropEnabled) { [view enableFileDrops]; } @@ -5880,3 +5896,20 @@ void viva_override_default_integer(const char *key, int value, int remove) { } #endif /* VIVA_OFFSCREEN */ + +int viva_application_set_watermark(void *window, viva_watermark config) { + __block int found = 0; + void (^work)(void) = ^{ + NSView *host = viva_application_window_view(window); + if (host != nil) { + viva_watermark_apply(host, config); + found = 1; + } + }; + if ([NSThread isMainThread]) { + work(); + } else { + dispatch_sync(dispatch_get_main_queue(), work); + } + return found; +} diff --git a/internal/platform/darwin/notification_darwin.go b/internal/platform/darwin/notification_darwin.go new file mode 100644 index 000000000..18437ba17 --- /dev/null +++ b/internal/platform/darwin/notification_darwin.go @@ -0,0 +1,91 @@ +//go:build darwin && !ios + +package darwin + +/* +#include +#include "system_darwin.h" +*/ +import "C" + +import ( + "fmt" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +var notificationCallbacks platform.NotificationRegistry + +func ShowNotification(title, body string, events platform.NotificationEvents) (func(), error) { + id := notificationCallbacks.Add(events) + titleText, err := systemCString("notification title", title) + if err != nil { + notificationCallbacks.Remove(id) + return nil, err + } + bodyText, err := systemCString("notification body", body) + if err != nil { + notificationCallbacks.Remove(id) + C.free(unsafe.Pointer(titleText)) + return nil, err + } + identifier := C.CString(id) + defer C.free(unsafe.Pointer(identifier)) + defer C.free(unsafe.Pointer(titleText)) + defer C.free(unsafe.Pointer(bodyText)) + var message *C.char + status := C.viva_system_show_interactive_notification(identifier, titleText, bodyText, &message) + if status != 0 { + notificationCallbacks.Remove(id) + if status == -2 { + if message != nil { + C.viva_system_free(unsafe.Pointer(message)) + } + return nil, ErrPermissionDenied + } + return nil, systemError("send interactive notification", message) + } + return func() { + notificationCallbacks.Remove(id) + identifier := C.CString(id) + defer C.free(unsafe.Pointer(identifier)) + C.viva_system_remove_notification(identifier) + }, nil +} + +//export vivaSystemNotificationActivated +func vivaSystemNotificationActivated(identifier *C.char) { + activateNotification(C.GoString(identifier)) +} + +//export vivaSystemNotificationIsActive +func vivaSystemNotificationIsActive(identifier *C.char) C.int { + if notificationCallbacks.Has(C.GoString(identifier)) { + return 1 + } + return 0 +} + +//export vivaSystemNotificationFailed +func vivaSystemNotificationFailed(identifier, message *C.char, denied C.int) { + failNotification(C.GoString(identifier), C.GoString(message), denied != 0) +} + +func failNotification(identifier, message string, denied bool) { + events := notificationCallbacks.Take(identifier) + if events.Failed == nil { + return + } + var err error = fmt.Errorf("darwin: notification delivery failed: %s", message) + if denied { + err = ErrPermissionDenied + } + events.Failed(err) +} + +func activateNotification(identifier string) { + if activate := notificationCallbacks.Take(identifier).Activated; activate != nil { + activate() + } +} diff --git a/internal/platform/darwin/notification_darwin_test.go b/internal/platform/darwin/notification_darwin_test.go new file mode 100644 index 000000000..7dd37da0b --- /dev/null +++ b/internal/platform/darwin/notification_darwin_test.go @@ -0,0 +1,47 @@ +//go:build darwin && !ios + +package darwin + +import ( + "errors" + "github.com/vivaui/viva/internal/platform" + "testing" +) + +func TestNotificationNativeActivationConsumesCallback(t *testing.T) { + calls := 0 + id := notificationCallbacks.Add(platform.NotificationEvents{Activated: func() { calls++ }}) + activateNotification(id) + activateNotification(id) + if calls != 1 || notificationCallbacks.Has(id) { + t.Fatal("native activation was not consumed exactly once") + } + id = notificationCallbacks.Add(platform.NotificationEvents{Activated: func() { calls++ }}) + notificationCallbacks.Remove(id) + activateNotification(id) + if calls != 1 { + t.Fatal("cancelled native identity was reactivated") + } +} +func TestNotificationNativeRejectsNULBeforeDelivery(t *testing.T) { + if close, err := ShowNotification("bad\x00title", "body", platform.NotificationEvents{}); err == nil || close != nil { + t.Fatal("invalid native string reached notification center") + } + if close, err := ShowNotification("title", "bad\x00body", platform.NotificationEvents{}); err == nil || close != nil { + t.Fatal("invalid native body reached notification center") + } +} + +func TestNotificationNativeFailureAndLateCancellation(t *testing.T) { + calls := 0 + var got error + id := notificationCallbacks.Add(platform.NotificationEvents{Failed: func(err error) { calls++; got = err }}) + failNotification(id, "denied", true) + failNotification(id, "duplicate", false) + if calls != 1 || !errors.Is(got, ErrPermissionDenied) || notificationCallbacks.Has(id) { + t.Fatal("permission failure did not consume native callback", calls, got) + } + id = notificationCallbacks.Add(platform.NotificationEvents{Failed: func(error) { t.Error("cancelled failure delivered") }}) + notificationCallbacks.Remove(id) + failNotification(id, "late failure", false) +} diff --git a/internal/platform/darwin/platform.go b/internal/platform/darwin/platform.go index 964d7397a..6f86c0107 100644 --- a/internal/platform/darwin/platform.go +++ b/internal/platform/darwin/platform.go @@ -344,6 +344,15 @@ func onlyMoved(previous, next TextInput) bool { func (application *nativeApplication) SupportsDragPreview() {} func (application *nativeApplication) OpenWindow(config Config) (platform.Window, error) { + watermark, err := platform.NormalizeWatermark(config.Watermark) + if err != nil { + return nil, err + } + config.Watermark = watermark + watermarkText := C.CString(config.Watermark.Text) + defer C.free(unsafe.Pointer(watermarkText)) + watermarkFamily := C.CString(config.Watermark.FontFamily) + defer C.free(unsafe.Pointer(watermarkFamily)) title := C.CString(config.Title) defer C.free(unsafe.Pointer(title)) @@ -441,6 +450,7 @@ func (application *nativeApplication) OpenWindow(config Config) (platform.Window } token := C.viva_application_open_window(C.viva_window_config{ title: title, + watermark: nativeWatermark(config.Watermark, watermarkText, watermarkFamily), width: C.int(config.Width), height: C.int(config.Height), min_width: C.int(config.MinWidth), diff --git a/internal/platform/darwin/shaders/scene.metal b/internal/platform/darwin/shaders/scene.metal index 2926a0140..21ccf7af8 100644 --- a/internal/platform/darwin/shaders/scene.metal +++ b/internal/platform/darwin/shaders/scene.metal @@ -20,12 +20,15 @@ struct VertexOutput { float2 triA [[flat]]; float2 triB [[flat]]; float2 triC [[flat]]; + float2 coverageC [[flat]]; float pixelSize [[flat]]; uint triangleMask [[flat]]; }; // Low bits retain edgeMask+1; this bit is local to the rasterizer varyings. constant uint boundedTriangleFlag = 1u << 8; +constant uint strokeQuadEdgeMask = 1u << 3; +constant uint coverageSourceFlag = 1u << 4; static float cross2(float2 a, float2 b) { return a.x*b.y - a.y*b.x; } static float segmentDistance(float2 p, float2 a, float2 b) { @@ -68,6 +71,7 @@ vertex VertexOutput viva_rectangle_vertex( float2 triA = 0.0; float2 triB = 0.0; float2 triC = 0.0; + float2 coverageC = 0.0; uint triangleMask = 0; float4 color = instance.color; if (isTriangle) { @@ -81,7 +85,9 @@ vertex VertexOutput viva_rectangle_vertex( instance.bounds.zw, instance.style.xz, }; - uint edgeMask = (uint(instance.style.w + 0.5) - 1u) & 7u; + uint edgeFlags = uint(instance.style.w + 0.5) - 1u; + uint edgeMask = edgeFlags & 7u; + bool hasCoverageSource = (edgeFlags & coverageSourceFlag) != 0u; float2 ab = points[1] - points[0], ac = points[2] - points[0]; float2 bc = points[2] - points[1]; float area = cross2(ab, ac); @@ -94,7 +100,7 @@ vertex VertexOutput viva_rectangle_vertex( // scales because hardware snaps geometry to its own subpixel grid. // Above this aspect ratio the miter displacement is at most eight // device pixels. Below it the quad avoids both overflow and overdraw. - bool bounded = valid && (edgeMask != 7u || abs(area) < longest2 * 0.125); + bool bounded = valid && (hasCoverageSource || edgeMask != 7u || abs(area) < longest2 * 0.125); uint index = vertexID < 3 ? vertexID : 0u; uint previous = (index + 2u) % 3u; if (!valid) { @@ -107,18 +113,20 @@ vertex VertexOutput viva_rectangle_vertex( pixel = fringeVertex(points[previous], points[index], points[(index + 1u) % 3u], 1u << previous, 1u << index, edgeMask, viewportSize.z); } // Extrapolate corner colors so interpolation stays on the original mesh. - if (valid) { + if (valid && !hasCoverageSource) { float2 delta = pixel - points[0]; color = instance.color + cross2(delta, ac) / area * (instance.shade1 - instance.color) + cross2(ab, delta) / area * (instance.shade2 - instance.color); } - localPixel = 0.0; - size = 0.0; - radius = 0.0; + // A clipped flat stroke sends its antialiasing face in the shade slots. + localPixel = hasCoverageSource ? instance.shade1.xy : float2(0.0); + size = hasCoverageSource ? instance.shade1.zw : float2(0.0); + coverageC = hasCoverageSource ? instance.shade2.xy : float2(0.0); + radius = hasCoverageSource ? instance.shade2.z : 0.0; triA = points[0]; triB = points[1]; triC = points[2]; - triangleMask = (edgeMask + 1u) | (bounded ? boundedTriangleFlag : 0u); + triangleMask = (edgeFlags + 1u) | (bounded ? boundedTriangleFlag : 0u); } else if (instance.style.z > 0.0) { // Shadow slots: bounds and style.x are the rounded rectangle that casts // the shadow, style.z its blur, shade1 = (offset.x, offset.y, spread). The @@ -150,6 +158,7 @@ vertex VertexOutput viva_rectangle_vertex( output.triA = triA; output.triB = triB; output.triC = triC; + output.coverageC = coverageC; output.pixelSize = viewportSize.z; output.triangleMask = triangleMask; return output; @@ -207,7 +216,8 @@ fragment float4 viva_rectangle_fragment(VertexOutput input [[stage_in]]) { float area2 = (input.triB.x - input.triA.x) * (input.triC.y - input.triA.y) - (input.triB.y - input.triA.y) * (input.triC.x - input.triA.x); float sign = area2 > 0.0 ? 1.0 : -1.0; - uint edgeMask = (input.triangleMask & ~boundedTriangleFlag) - 1u; + uint edgeFlags = (input.triangleMask & ~boundedTriangleFlag) - 1u; + uint edgeMask = edgeFlags & 7u; // Use the actual sample position, not interpolation over an acute face. float2 p = input.position.xy * input.pixelSize; float pixel = input.pixelSize; @@ -244,18 +254,47 @@ fragment float4 viva_rectangle_fragment(VertexOutput input [[stage_in]]) { } } } - float d0 = (edgeMask & 1u) != 0u ? sign * edgeDistance(p, input.triA, input.triB) : 1e6; - float d1 = (edgeMask & 2u) != 0u ? sign * edgeDistance(p, input.triB, input.triC) : 1e6; - float d2 = (edgeMask & 4u) != 0u ? sign * edgeDistance(p, input.triC, input.triA) : 1e6; + // The clipped face owns the sample. Its original outline determines + // the feathering, even when clipping removed every silhouette edge. + float2 coverageA = input.triA, coverageB = input.triB, coverageC = input.triC; + uint coverageFlags = edgeFlags; + float coverageSign = sign; + if ((edgeFlags & coverageSourceFlag) != 0u) { + coverageA = input.localPosition; + coverageB = input.size; + coverageC = input.coverageC; + coverageFlags = uint(input.radius + 0.5); + coverageSign = cross2(coverageB - coverageA, coverageC - coverageA) > 0.0 ? 1.0 : -1.0; + } + uint coverageMask = coverageFlags & 7u; + float d0 = (coverageMask & 1u) != 0u ? coverageSign * edgeDistance(p, coverageA, coverageB) : 1e6; + float d1 = (coverageMask & 2u) != 0u ? coverageSign * edgeDistance(p, coverageB, coverageC) : 1e6; + float d2 = (coverageMask & 4u) != 0u ? coverageSign * edgeDistance(p, coverageC, coverageA) : 1e6; float inside = min(d0, min(d1, d2)); + bool strokeQuad = (coverageFlags & strokeQuadEdgeMask) != 0u; + float2 oppositeStart, oppositeEnd; + if (strokeQuad) { + // The shared diagonal decides ownership, but coverage depends on both long edges. + bool firstHalf = (coverageMask & 1u) != 0u; + float2 from = firstHalf ? coverageA : coverageC; + float2 to = firstHalf ? coverageB : coverageA; + oppositeStart = firstHalf ? coverageC : coverageB; + oppositeEnd = oppositeStart + (to - from); + float primary = firstHalf ? d0 : d2; + inside = min(inside, coverageSign * edgeDistance(oppositeStart, from, to) - primary); + } if (inside < 0.0) { - // Acute offset-line miters must not paint beyond the actual ends. - float s0 = (edgeMask & 1u) != 0u ? segmentDistance(p, input.triA, input.triB) : 1e6; - float s1 = (edgeMask & 2u) != 0u ? segmentDistance(p, input.triB, input.triC) : 1e6; - float s2 = (edgeMask & 4u) != 0u ? segmentDistance(p, input.triC, input.triA) : 1e6; - inside = -min(s0, min(s1, s2)); + // Use the visible edge segments for the outward fringe. A clipped + // stroke's original edges may extend beyond the cut. + bool clippedStroke = (edgeFlags & coverageSourceFlag) != 0u; + uint fringeMask = clippedStroke ? edgeMask : coverageMask; + float s0 = (fringeMask & 1u) != 0u ? segmentDistance(p, input.triA, input.triB) : 1e6; + float s1 = (fringeMask & 2u) != 0u ? segmentDistance(p, input.triB, input.triC) : 1e6; + float s2 = (fringeMask & 4u) != 0u ? segmentDistance(p, input.triC, input.triA) : 1e6; + float opposite = strokeQuad && !clippedStroke ? segmentDistance(p, oppositeStart, oppositeEnd) : 1e6; + inside = -min(min(s0, s1), min(s2, opposite)); } - float coverage = edgeMask == 0 ? 1.0 : saturate(0.5 + inside / pixel); + float coverage = coverageMask == 0 ? 1.0 : saturate(0.5 + inside / pixel); float4 shade = saturate(input.color); return float4(shade.rgb, shade.a * coverage); } diff --git a/internal/platform/darwin/shaders/scene.metallib b/internal/platform/darwin/shaders/scene.metallib index 17f2c0d83..3ebf7620b 100644 Binary files a/internal/platform/darwin/shaders/scene.metallib and b/internal/platform/darwin/shaders/scene.metallib differ diff --git a/internal/platform/darwin/system_darwin.h b/internal/platform/darwin/system_darwin.h index e6f0ce324..ad52cb83c 100644 --- a/internal/platform/darwin/system_darwin.h +++ b/internal/platform/darwin/system_darwin.h @@ -99,6 +99,9 @@ int viva_system_send_notification( char **error_message ); +int viva_system_show_interactive_notification(const char *identifier, const char *title, const char *body, char **error_message); +void viva_system_remove_notification(const char *identifier); + void viva_system_free(void *memory); void viva_system_free_string_array(viva_system_string_array values); diff --git a/internal/platform/darwin/system_darwin.m b/internal/platform/darwin/system_darwin.m index 21a3a800f..e585927c2 100644 --- a/internal/platform/darwin/system_darwin.m +++ b/internal/platform/darwin/system_darwin.m @@ -1252,6 +1252,11 @@ int viva_system_play_sound(uint8_t sound, char **error_message) { return status; } +// Standalone native fixtures do not link the Go callback bridge. +extern void vivaSystemNotificationActivated(char *) __attribute__((weak_import)); +extern int vivaSystemNotificationIsActive(char *) __attribute__((weak_import)); +extern void vivaSystemNotificationFailed(char *, char *, int) __attribute__((weak_import)); + @interface VivaNotificationDelegate : NSObject @end @@ -1271,6 +1276,16 @@ - (void)userNotificationCenter:(UNUserNotificationCenter *)center #pragma clang diagnostic pop } } +- (void)userNotificationCenter:(UNUserNotificationCenter *)center + didReceiveNotificationResponse:(UNNotificationResponse *)response + withCompletionHandler:(void (^)(void))completionHandler { + if ([response.actionIdentifier isEqualToString:UNNotificationDefaultActionIdentifier] && + vivaSystemNotificationActivated != NULL) { + vivaSystemNotificationActivated((char *)response.notification.request.identifier.UTF8String); + } + completionHandler(); +} + @end static VivaNotificationDelegate *viva_notification_delegate(void) { @@ -1408,6 +1423,84 @@ int viva_system_send_notification( } } +static BOOL viva_interactive_notification_active(NSString *identifier) { + return vivaSystemNotificationIsActive != NULL && vivaSystemNotificationIsActive((char *)identifier.UTF8String) != 0; +} + +void viva_system_remove_notification(const char *identifier) { + @autoreleasepool { + if (NSBundle.mainBundle.bundleIdentifier.length == 0 || identifier == NULL) return; + NSString *value = viva_string(identifier); + if (value == nil) return; + UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter; + [center removePendingNotificationRequestsWithIdentifiers:@[value]]; + [center removeDeliveredNotificationsWithIdentifiers:@[value]]; + } +} + +static void viva_interactive_notification_failed(NSString *identifier, NSString *message, BOOL denied) { + if (vivaSystemNotificationFailed != NULL) { + vivaSystemNotificationFailed((char *)identifier.UTF8String, (char *)message.UTF8String, denied ? 1 : 0); + } +} + +static void viva_interactive_notification_schedule(UNUserNotificationCenter *center, NSString *identifier, NSString *title, NSString *body) { + if (!viva_interactive_notification_active(identifier)) return; + UNMutableNotificationContent *content = [[[UNMutableNotificationContent alloc] init] autorelease]; + content.title = title; + content.body = body; + content.sound = UNNotificationSound.defaultSound; + UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:nil]; + [center addNotificationRequest:request withCompletionHandler:^(NSError *error) { + if (error != nil) { + viva_interactive_notification_failed(identifier, error.localizedDescription, NO); + } + // Cancellation can race scheduling. Remove the request again after the + // native completion so late authorization never reinstates a retired request. + if (!viva_interactive_notification_active(identifier)) { + viva_system_remove_notification(identifier.UTF8String); + } + }]; +} + +int viva_system_show_interactive_notification(const char *identifier, const char *title, const char *body, char **error_message) { + @autoreleasepool { + if (NSBundle.mainBundle.bundleIdentifier.length == 0) { + viva_set_error(error_message, @"notifications require an application bundle identifier"); + return -1; + } + NSString *key = viva_string(identifier), *notificationTitle = viva_string(title), *notificationBody = viva_string(body); + if (key == nil || notificationTitle == nil || notificationBody == nil) { + viva_set_error(error_message, @"notification text is not valid UTF-8"); + return -1; + } + UNUserNotificationCenter *center = UNUserNotificationCenter.currentNotificationCenter; + center.delegate = viva_notification_delegate(); + [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings *settings) { + if (!viva_interactive_notification_active(key)) return; + if (settings.authorizationStatus == UNAuthorizationStatusNotDetermined) { + [center requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound) + completionHandler:^(BOOL allowed, NSError *error) { + if (!viva_interactive_notification_active(key)) return; + if (!allowed || error != nil) { + viva_interactive_notification_failed(key, error.localizedDescription ?: @"notification permission was denied", !allowed); + return; + } + viva_interactive_notification_schedule(center, key, notificationTitle, notificationBody); + }]; + } else if (settings.authorizationStatus == UNAuthorizationStatusDenied) { + viva_interactive_notification_failed(key, @"notification permission is denied in System Settings", YES); + } else if (settings.authorizationStatus == UNAuthorizationStatusAuthorized || + settings.authorizationStatus == UNAuthorizationStatusProvisional) { + viva_interactive_notification_schedule(center, key, notificationTitle, notificationBody); + } else { + viva_interactive_notification_failed(key, @"notification authorization status is unsupported", NO); + } + }]; + return 0; + } +} + void viva_system_free(void *memory) { free(memory); } diff --git a/internal/platform/darwin/testdata/dock_reopen.m b/internal/platform/darwin/testdata/dock_reopen.m index 09dab38ce..5c74148b4 100644 --- a/internal/platform/darwin/testdata/dock_reopen.m +++ b/internal/platform/darwin/testdata/dock_reopen.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/file_drop.m b/internal/platform/darwin/testdata/file_drop.m index e71475272..9b224b1a3 100644 --- a/internal/platform/darwin/testdata/file_drop.m +++ b/internal/platform/darwin/testdata/file_drop.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/live_resize.m b/internal/platform/darwin/testdata/live_resize.m index ed90feede..de5abc9db 100644 --- a/internal/platform/darwin/testdata/live_resize.m +++ b/internal/platform/darwin/testdata/live_resize.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/modifier_taps.m b/internal/platform/darwin/testdata/modifier_taps.m index 5ab013d00..7ad2a8380 100644 --- a/internal/platform/darwin/testdata/modifier_taps.m +++ b/internal/platform/darwin/testdata/modifier_taps.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/text_selection.m b/internal/platform/darwin/testdata/text_selection.m index 93b0a77d6..72b34cfa8 100644 --- a/internal/platform/darwin/testdata/text_selection.m +++ b/internal/platform/darwin/testdata/text_selection.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/traffic_lights.m b/internal/platform/darwin/testdata/traffic_lights.m index 3f333e0c9..5789e46f0 100644 --- a/internal/platform/darwin/testdata/traffic_lights.m +++ b/internal/platform/darwin/testdata/traffic_lights.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/watermark.m b/internal/platform/darwin/testdata/watermark.m new file mode 100644 index 000000000..ceb04fafd --- /dev/null +++ b/internal/platform/darwin/testdata/watermark.m @@ -0,0 +1,79 @@ +#import +#include "../watermark_darwin.m" +#include "../cursor_owner_darwin.h" + +// Exercise only the native view tree: no window, GPU, tile rasterization, or screenshot. +@interface WatermarkProbe : VivaWatermarkView +@end +@implementation WatermarkProbe +- (void)updatePattern {} +@end +@interface WatermarkTestHost : NSView +@end +@implementation WatermarkTestHost +- (BOOL)isFlipped {return YES;} +@end +int main(void) { + @autoreleasepool { + // Allocate only: no text rasterization, window, GPU, or screenshot. + // The previous extended-linear/8-bit combination returned NULL on macOS. + for (size_t scale=1; scale<=2; scale++) { + CGContextRef context=watermarkCreateTileContext(240*scale,180*scale); + if(context==NULL) return 8; + if(CGBitmapContextGetBitsPerComponent(context)!=8 || CGBitmapContextGetWidth(context)!=240*scale || CGBitmapContextGetHeight(context)!=180*scale) return 9; + CGContextRelease(context); + } + // Exercise real CoreText metrics and real CGPattern ownership without drawing + // text, allocating a window, or reading pixels/screenshots. + CGColorSpaceRef space=CGColorSpaceCreateWithName(kCGColorSpaceLinearSRGB); + CGFloat channels[]={0.5,0.5,0.5,0.12}; + CGColorRef color=CGColorCreate(space,channels); + for (NSString *text in @[@"DRAFT",@"测试用户 10086"]) { + CTLineRef line=watermarkCreateLine(text,@"",12,-0.4,color); + CGFloat ascent=0,descent=0; + double advance=CTLineGetTypographicBounds(line,&ascent,&descent,NULL); + CGPoint origin=watermarkTextOrigin(line,240,180); + if(advance<=0 || fabs(origin.x+advance/2-120)>0.001 || fabs(origin.y+(ascent-descent)/2-90)>0.001) return 7; + CFRelease(line); + } + CGColorRelease(color);CGColorSpaceRelease(space); + for (size_t scale=1;scale<=2;scale++) { + CGAffineTransform matrix=watermarkPatternMatrix(scale); + CGSize right=CGSizeApplyAffineTransform(CGSizeMake(scale,0),matrix); + CGSize up=CGSizeApplyAffineTransform(CGSizeMake(0,scale),matrix); + if(right.width!=1 || right.height!=0 || up.width!=0 || up.height!=1) return 10; + CGContextRef context=watermarkCreateTileContext(240*scale,180*scale); + CGImageRef image=CGBitmapContextCreateImage(context);CGContextRelease(context); + CGPatternRef pattern=watermarkCreatePattern(image,scale); + if(pattern==NULL) {CGImageRelease(image);return 11;} + CGPatternRelease(pattern); + } + for (int angle=-90;angle<=90;angle+=15) { + CGAffineTransform rotation=CGAffineTransformMakeRotation(angle*M_PI/180); + CGRect bounds=watermarkPatternBounds(3840,2160,rotation); + CGRect required=CGRectApplyAffineTransform(CGRectMake(0,0,3840,2160),CGAffineTransformInvert(rotation)); + if(!CGRectContainsRect(bounds,required)) return 12; + // Coverage uses the inverse-rotated rectangle, not a huge square plane. + if(bounds.size.width>hypot(3840,2160)+2 || bounds.size.height>hypot(3840,2160)+2) return 13; + } + NSView *host=[[WatermarkTestHost alloc] initWithFrame:NSMakeRect(0,0,800,600)]; + NSView *page=[[NSView alloc] initWithFrame:host.bounds]; + WatermarkProbe *overlay=[[WatermarkProbe alloc] initWithFrame:host.bounds]; + [overlay configure:(viva_watermark){.text="测试用户 10086",.alpha=.1,.font_size=12,.tile_width=240,.tile_height=180,.angle=-25,.top=42,.left=120}]; + [host addSubview:overlay]; + [host addSubview:page positioned:NSWindowAbove relativeTo:nil]; + viva_raise_watermark(host); + if(host.subviews.lastObject!=overlay) return 1; + if([overlay hitTest:NSMakePoint(200,200)]!=nil || overlay.acceptsFirstResponder) return 2; + if([host hitTest:NSMakePoint(200,200)]!=page) return 3; + [overlay layout]; + CALayer *clip=overlay.layer.sublayers.firstObject; + if(!clip.masksToBounds || clip.frame.origin.x!=120 || clip.frame.origin.y!=42 || clip.frame.size.width!=680 || clip.frame.size.height!=558) return 4; + [overlay setFrameSize:NSMakeSize(1000,700)];[overlay layout]; + if(clip.frame.size.width!=880 || clip.frame.size.height!=658) return 5; + viva_watermark_apply(host,(viva_watermark){0}); + if([host.subviews containsObject:overlay]) return 6; + [overlay release];[page release];[host release]; + } + return 0; +} diff --git a/internal/platform/darwin/testdata/window_close.m b/internal/platform/darwin/testdata/window_close.m index 3cb10a1fb..5ea1e3503 100644 --- a/internal/platform/darwin/testdata/window_close.m +++ b/internal/platform/darwin/testdata/window_close.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/window_decoration.m b/internal/platform/darwin/testdata/window_decoration.m index d942aff61..a5806202e 100644 --- a/internal/platform/darwin/testdata/window_decoration.m +++ b/internal/platform/darwin/testdata/window_decoration.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/testdata/window_notification.m b/internal/platform/darwin/testdata/window_notification.m index ee49a879d..02f6ff06e 100644 --- a/internal/platform/darwin/testdata/window_notification.m +++ b/internal/platform/darwin/testdata/window_notification.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include "window_test_callbacks.h" diff --git a/internal/platform/darwin/testdata/window_size.m b/internal/platform/darwin/testdata/window_size.m index 7fab1de82..bbb866887 100644 --- a/internal/platform/darwin/testdata/window_size.m +++ b/internal/platform/darwin/testdata/window_size.m @@ -1,5 +1,6 @@ #include "../core_text.m" #include "../core_render.m" +#include "../watermark_darwin.m" #include "../native.m" #include "../main_menu_darwin.m" #include diff --git a/internal/platform/darwin/watermark_config_darwin.go b/internal/platform/darwin/watermark_config_darwin.go new file mode 100644 index 000000000..7f2acde4a --- /dev/null +++ b/internal/platform/darwin/watermark_config_darwin.go @@ -0,0 +1,13 @@ +//go:build darwin + +package darwin + +/* +#include "watermark_darwin.h" +*/ +import "C" +import "github.com/vivaui/viva/internal/platform" + +func nativeWatermark(value platform.Watermark, text, family *C.char) C.viva_watermark { + return C.viva_watermark{text: text, font_family: family, red: C.double(value.Color.Red), green: C.double(value.Color.Green), blue: C.double(value.Color.Blue), alpha: C.double(value.Color.Alpha), font_size: C.float(value.FontSize), font_weight: C.float(value.FontWeight), angle: C.float(value.Angle), tile_width: C.float(value.TileWidth), tile_height: C.float(value.TileHeight), top: C.float(value.Insets.Top), right: C.float(value.Insets.Right), bottom: C.float(value.Insets.Bottom), left: C.float(value.Insets.Left)} +} diff --git a/internal/platform/darwin/watermark_darwin.go b/internal/platform/darwin/watermark_darwin.go new file mode 100644 index 000000000..28157b84e --- /dev/null +++ b/internal/platform/darwin/watermark_darwin.go @@ -0,0 +1,33 @@ +//go:build darwin && !ios + +package darwin + +/* +#include +#include "watermark_darwin.h" +*/ +import "C" +import ( + "fmt" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +func (window *nativeWindow) SetWatermark(value platform.Watermark) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("darwin: window is closed") + } + value, err := platform.NormalizeWatermark(value) + if err != nil { + return err + } + text := C.CString(value.Text) + defer C.free(unsafe.Pointer(text)) + family := C.CString(value.FontFamily) + defer C.free(unsafe.Pointer(family)) + if C.viva_application_set_watermark(window.token, nativeWatermark(value, text, family)) == 0 { + return fmt.Errorf("darwin: window is unavailable") + } + return nil +} diff --git a/internal/platform/darwin/watermark_darwin.h b/internal/platform/darwin/watermark_darwin.h new file mode 100644 index 000000000..aaac3fcd7 --- /dev/null +++ b/internal/platform/darwin/watermark_darwin.h @@ -0,0 +1,13 @@ +#ifndef VIVA_WATERMARK_H +#define VIVA_WATERMARK_H + +typedef struct { + const char *text, *font_family; + double red, green, blue, alpha; + float font_size, font_weight, angle, tile_width, tile_height; + float top, right, bottom, left; +} viva_watermark; +void viva_watermark_apply(void *host, viva_watermark config); +void viva_raise_watermark(void *host); +int viva_application_set_watermark(void *window, viva_watermark config); +#endif diff --git a/internal/platform/darwin/watermark_darwin.m b/internal/platform/darwin/watermark_darwin.m new file mode 100644 index 000000000..7ba828dad --- /dev/null +++ b/internal/platform/darwin/watermark_darwin.m @@ -0,0 +1,254 @@ +//go:build !ios + +#import +#import +#import +#include "watermark_darwin.h" + +static const size_t watermarkMaxTileSize = 8192; +static const size_t watermarkMaxTilePixels = 16u << 20; + +@interface VivaWatermarkView : NSView { + viva_watermark _config; + NSString *_text, *_family; + CALayer *_clipLayer; + CALayer *_patternLayer; + CGFloat _tileScale; +} +- (void)configure:(viva_watermark)config; +@end + +static void watermarkDrawTile(void *info, CGContextRef context) { + CGImageRef image = info; + // Pattern coordinates are device pixels; the pattern matrix restores logical units. + CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image), CGImageGetHeight(image)), image); +} + +// Core Animation presents the bitmap contents upright in the flipped host. +// Only convert device pixels to logical units here; reflecting Y again would +// mirror the glyphs as well as the baseline. +static CGAffineTransform watermarkPatternMatrix(CGFloat scale) { + return CGAffineTransformMakeScale(1 / scale, 1 / scale); +} + +static void watermarkReleaseTile(void *info) { + CGImageRelease(info); +} + +// Extended linear RGB requires floating-point components. The retained tile uses +// 8-bit components, so use bounded linear sRGB to match the canvas color values. +static CGContextRef watermarkCreateTileContext(size_t width, size_t height) { + CGColorSpaceRef space = CGColorSpaceCreateWithName(kCGColorSpaceLinearSRGB); + CGContextRef context = CGBitmapContextCreate(NULL, width, height, 8, 0, space, (CGBitmapInfo)kCGImageAlphaPremultipliedLast); + CGColorSpaceRelease(space); + return context; +} + +// These helpers share production font metrics, pattern ownership and coverage +// geometry with the native contract test, which does not rasterize text. +static CTLineRef watermarkCreateLine(NSString *text, NSString *family, CGFloat size, CGFloat weight, CGColorRef color) { + NSFont *font = [NSFont systemFontOfSize:size weight:weight]; + if (family.length > 0) { + NSFontDescriptor *descriptor = [NSFontDescriptor fontDescriptorWithFontAttributes:@{ + NSFontFamilyAttribute: family, + NSFontTraitsAttribute: @{NSFontWeightTrait: @(weight)}, + }]; + font = [NSFont fontWithDescriptor:descriptor size:size] ?: font; + } + NSAttributedString *string = [[NSAttributedString alloc] initWithString:text attributes:@{ + (id)kCTFontAttributeName: font, + (id)kCTForegroundColorAttributeName: (id)color, + }]; + CTLineRef line = CTLineCreateWithAttributedString((CFAttributedStringRef)string); + [string release]; + return line; +} + +static CGPoint watermarkTextOrigin(CTLineRef line, CGFloat width, CGFloat height) { + CGFloat ascent = 0, descent = 0; + double advance = CTLineGetTypographicBounds(line, &ascent, &descent, NULL); + return CGPointMake((width - advance) / 2, (height - ascent - descent) / 2 + descent); +} + +static CGPatternRef watermarkCreatePattern(CGImageRef image, CGFloat scale) { + CGPatternCallbacks callbacks = {0, watermarkDrawTile, watermarkReleaseTile}; + size_t width = CGImageGetWidth(image), height = CGImageGetHeight(image); + return CGPatternCreate(image, CGRectMake(0, 0, width, height), watermarkPatternMatrix(scale), width, height, + kCGPatternTilingConstantSpacing, true, &callbacks); +} + +static CGRect watermarkPatternBounds(CGFloat width, CGFloat height, CGAffineTransform rotation) { + if (width <= 0 || height <= 0) { + return CGRectZero; + } + return CGRectIntegral(CGRectApplyAffineTransform(CGRectMake(0, 0, width, height), CGAffineTransformInvert(rotation))); +} + +@implementation VivaWatermarkView +- (instancetype)initWithFrame:(NSRect)frame { + self = [super initWithFrame:frame]; + if (self != nil) { + self.autoresizingMask = NSViewWidthSizable | NSViewHeightSizable; + self.wantsLayer = YES; + self.layer.geometryFlipped = YES; + _clipLayer = [CALayer layer]; + _clipLayer.masksToBounds = YES; + _patternLayer = [CALayer layer]; + [_clipLayer addSublayer:_patternLayer]; + [self.layer addSublayer:_clipLayer]; + } + return self; +} + +- (BOOL)isFlipped { return YES; } +- (NSView *)hitTest:(NSPoint)point { return nil; } +- (BOOL)acceptsFirstResponder { return NO; } + +- (void)dealloc { + [_text release]; + [_family release]; + [super dealloc]; +} + +- (void)configure:(viva_watermark)config { + NSString *text = [NSString stringWithUTF8String:config.text != NULL ? config.text : ""]; + NSString *family = [NSString stringWithUTF8String:config.font_family ?: ""]; + BOOL rebuild = ![_text isEqualToString:text] || ![_family isEqualToString:family] || + _config.red != config.red || _config.green != config.green || + _config.blue != config.blue || _config.alpha != config.alpha || + _config.font_size != config.font_size || _config.font_weight != config.font_weight || + _config.tile_width != config.tile_width || _config.tile_height != config.tile_height; + [_text release]; + _text = [text copy]; + _config = config; + _config.text = NULL; + _config.font_family = NULL; + [_family release]; + _family = [family copy]; + if (rebuild) { + _tileScale = 0; + } + [self updatePattern]; + [self setNeedsLayout:YES]; + [self layoutSubtreeIfNeeded]; +} + +- (void)viewDidMoveToWindow { + [super viewDidMoveToWindow]; + [self updatePattern]; +} + +- (void)viewDidChangeBackingProperties { + [super viewDidChangeBackingProperties]; + [self updatePattern]; +} + +- (void)updatePattern { + // Wait for the actual backing scale before rasterizing. + if (self.window == nil) { + return; + } + CGFloat scale = self.window.backingScaleFactor; + if (scale <= 0) { + scale = 1; + } + if (_tileScale == scale || _text.length == 0) { + return; + } + size_t width = ceil(_config.tile_width * scale); + size_t height = ceil(_config.tile_height * scale); + if (width == 0 || height == 0 || width > watermarkMaxTileSize || height > watermarkMaxTileSize || width * height > watermarkMaxTilePixels) { + return; + } + CGContextRef context = watermarkCreateTileContext(width, height); + if (context == NULL) { + return; + } + CGColorSpaceRef space = CGBitmapContextGetColorSpace(context); + CGContextScaleCTM(context, scale, scale); + CGFloat channels[] = {_config.red, _config.green, _config.blue, _config.alpha}; + CGColorRef color = CGColorCreate(space, channels); + CTLineRef line = watermarkCreateLine(_text, _family, _config.font_size, _config.font_weight, color); + CGPoint origin = watermarkTextOrigin(line, _config.tile_width, _config.tile_height); + CGContextSetTextPosition(context, origin.x, origin.y); + CTLineDraw(line, context); + CFRelease(line); + CGColorRelease(color); + CGImageRef image = CGBitmapContextCreateImage(context); + CGContextRelease(context); + if (image == NULL) { + return; + } + CGPatternRef pattern = watermarkCreatePattern(image, scale); + if (pattern == NULL) { + CGImageRelease(image); + return; + } + CGColorSpaceRef patternSpace = CGColorSpaceCreatePattern(NULL); + CGFloat alpha = 1; + CGColorRef patternColor = CGColorCreateWithPattern(patternSpace, pattern, &alpha); + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + _patternLayer.backgroundColor = patternColor; + [CATransaction commit]; + CGColorRelease(patternColor); + CGColorSpaceRelease(patternSpace); + CGPatternRelease(pattern); + _tileScale = scale; +} + +- (void)layout { + [super layout]; + CGFloat width = MAX(0, self.bounds.size.width - _config.left - _config.right); + CGFloat height = MAX(0, self.bounds.size.height - _config.top - _config.bottom); + CGAffineTransform rotation = CGAffineTransformMakeRotation(_config.angle * M_PI / 180); + CGRect bounds = watermarkPatternBounds(width, height, rotation); + [CATransaction begin]; + [CATransaction setDisableActions:YES]; + _clipLayer.frame = CGRectMake(_config.left, _config.top, width, height); + // Anchor pattern coordinate (0,0) at the clip origin. Changing size changes + // only the inverse-rotated coverage rectangle, never the pattern phase. + _patternLayer.bounds = bounds; + _patternLayer.anchorPoint = CGPointMake(bounds.size.width > 0 ? -bounds.origin.x / bounds.size.width : 0, + bounds.size.height > 0 ? -bounds.origin.y / bounds.size.height : 0); + _patternLayer.position = CGPointZero; + _patternLayer.affineTransform = rotation; + [CATransaction commit]; +} +@end + +static VivaWatermarkView *watermarkIn(NSView *host) { + for (NSView *view in host.subviews) { + if ([view isKindOfClass:[VivaWatermarkView class]]) { + return (VivaWatermarkView *)view; + } + } + return nil; +} + +// Native view creators call this after changing the host's view tree. +void viva_raise_watermark(void *value) { + NSView *host = value; + VivaWatermarkView *view = watermarkIn(host); + if (view != nil) { + [host addSubview:view positioned:NSWindowAbove relativeTo:nil]; + } +} + +void viva_watermark_apply(void *value, viva_watermark config) { + NSView *host = value; + if (host == nil) { + return; + } + VivaWatermarkView *view = watermarkIn(host); + if (config.text == NULL || config.text[0] == 0 || config.alpha <= 0) { + [view removeFromSuperview]; + return; + } + if (view == nil) { + view = [[[VivaWatermarkView alloc] initWithFrame:host.bounds] autorelease]; + [host addSubview:view positioned:NSWindowAbove relativeTo:nil]; + } + [view configure:config]; + viva_raise_watermark(host); +} diff --git a/internal/platform/darwin/watermark_darwin_test.go b/internal/platform/darwin/watermark_darwin_test.go new file mode 100644 index 000000000..83a722a0c --- /dev/null +++ b/internal/platform/darwin/watermark_darwin_test.go @@ -0,0 +1,20 @@ +//go:build darwin && !ios + +package darwin + +import ( + "os/exec" + "path/filepath" + "testing" +) + +func TestWatermarkNativeStackingClippingAndInputTransparency(t *testing.T) { + binary := filepath.Join(t.TempDir(), "watermark-views") + command := exec.Command("xcrun", "clang", "-fno-objc-arc", "-Werror", "-framework", "Cocoa", "-framework", "QuartzCore", "-framework", "CoreText", "testdata/watermark.m", "-o", binary) + if output, err := command.CombinedOutput(); err != nil { + t.Fatalf("compile native watermark view test: %v\n%s", err, output) + } + if output, err := exec.Command(binary).CombinedOutput(); err != nil { + t.Fatalf("native watermark view test: %v\n%s", err, output) + } +} diff --git a/internal/platform/darwin/web_darwin.m b/internal/platform/darwin/web_darwin.m index 504666b12..2d83e850d 100644 --- a/internal/platform/darwin/web_darwin.m +++ b/internal/platform/darwin/web_darwin.m @@ -1,5 +1,6 @@ //go:build !ios +#include "watermark_darwin.h" #import #import #import @@ -687,6 +688,7 @@ static int viva_web_named_store(WKWebViewConfiguration *configuration, const cha web.autoresizingMask = NSViewMinYMargin; web.hidden = YES; [host addSubview:web positioned:NSWindowAbove relativeTo:nil]; + viva_raise_watermark(host); [web release]; // the view hierarchy owns it } else { [controller removeScriptMessageHandlerForName:@"viva"]; diff --git a/internal/platform/notification_callbacks.go b/internal/platform/notification_callbacks.go new file mode 100644 index 000000000..8669affa7 --- /dev/null +++ b/internal/platform/notification_callbacks.go @@ -0,0 +1,43 @@ +package platform + +import ( + "crypto/rand" + "sync" +) + +type NotificationEvents struct { + Activated func() + Failed func(error) +} + +// NotificationRegistry owns active-process callbacks keyed by opaque identities. +// Cancellation removes the callback before a late native response can use it. +type NotificationRegistry struct { + mu sync.Mutex + values map[string]NotificationEvents +} + +func (callbacks *NotificationRegistry) Add(events NotificationEvents) string { + id := rand.Text() + callbacks.mu.Lock() + defer callbacks.mu.Unlock() + if callbacks.values == nil { + callbacks.values = make(map[string]NotificationEvents) + } + callbacks.values[id] = events + return id +} +func (callbacks *NotificationRegistry) Has(id string) bool { + callbacks.mu.Lock() + defer callbacks.mu.Unlock() + _, exists := callbacks.values[id] + return exists +} +func (callbacks *NotificationRegistry) Take(id string) NotificationEvents { + callbacks.mu.Lock() + defer callbacks.mu.Unlock() + events := callbacks.values[id] + delete(callbacks.values, id) + return events +} +func (callbacks *NotificationRegistry) Remove(id string) { callbacks.Take(id) } diff --git a/internal/platform/notification_callbacks_test.go b/internal/platform/notification_callbacks_test.go new file mode 100644 index 000000000..61726652f --- /dev/null +++ b/internal/platform/notification_callbacks_test.go @@ -0,0 +1,32 @@ +package platform + +import ( + "sync" + "sync/atomic" + "testing" +) + +func TestNotificationRegistryActivationOnceAndCancellation(t *testing.T) { + var callbacks NotificationRegistry + var calls atomic.Int32 + id := callbacks.Add(NotificationEvents{Activated: func() { calls.Add(1); callbacks.Remove("other") }}) + var jobs sync.WaitGroup + for range 32 { + jobs.Add(1) + go func() { + defer jobs.Done() + if activate := callbacks.Take(id).Activated; activate != nil { + activate() + } + }() + } + jobs.Wait() + if calls.Load() != 1 || callbacks.Has(id) { + t.Fatal("activation was not consumed exactly once") + } + id = callbacks.Add(NotificationEvents{Activated: func() { t.Error("cancelled activation") }}) + callbacks.Remove(id) + if callbacks.Has(id) || callbacks.Take(id).Activated != nil { + t.Fatal("cancelled callback retained") + } +} diff --git a/internal/platform/triangle.go b/internal/platform/triangle.go new file mode 100644 index 000000000..d449bcaef --- /dev/null +++ b/internal/platform/triangle.go @@ -0,0 +1,20 @@ +package platform + +import "github.com/vivaui/viva/internal/render" + +// PackTriangleCoverage returns the triangle marker and the two shade slots in +// the instance format shared by the GPU renderers. A clipped flat stroke uses +// the shade slots to carry its original coverage edges. +func PackTriangleCoverage(rectangle render.Rectangle) (marker float32, shade1, shade2 [4]float32) { + const coverageSourceFlag = 1 << 4 + if coverage, ok := rectangle.StrokeCoverage(); ok { + a, b, c := coverage.Points[0], coverage.Points[1], coverage.Points[2] + return float32((rectangle.EdgeMask | coverageSourceFlag) + 1), + [4]float32{a.X, a.Y, b.X, b.Y}, + [4]float32{c.X, c.Y, float32(coverage.EdgeMask), 0} + } + colors := rectangle.VertexColors() + return float32(rectangle.EdgeMask + 1), + [4]float32{colors[1].Red, colors[1].Green, colors[1].Blue, colors[1].Alpha}, + [4]float32{colors[2].Red, colors[2].Green, colors[2].Blue, colors[2].Alpha} +} diff --git a/internal/platform/vulkan/shaders/scene.frag b/internal/platform/vulkan/shaders/scene.frag index a495c9989..e85f88842 100644 --- a/internal/platform/vulkan/shaders/scene.frag +++ b/internal/platform/vulkan/shaders/scene.frag @@ -4,7 +4,7 @@ layout(location = 0) in vec4 inColor; layout(location = 1) in vec2 inLocal; layout(location = 2) in vec2 inSize; layout(location = 3) in float inRadius; -layout(location = 4) in vec2 inFragment; +layout(location = 4) flat in vec2 inCoverageC; layout(location = 5) in vec2 inTriangleA; layout(location = 6) in vec2 inTriangleB; layout(location = 7) in vec2 inTriangleC; @@ -22,6 +22,8 @@ layout(location = 0) out vec4 outColor; // Low bits keep edgeMask+1; this bit is local to the rasterizer. #define boundedTriangleFlag (1u << 8) +#define strokeQuadEdgeMask (1u << 3) +#define coverageSourceFlag (1u << 4) float edgeDistance(vec2 point, vec2 from, vec2 to) { vec2 edge = to - from; @@ -80,7 +82,8 @@ void main() { float area = (inTriangleB.x - inTriangleA.x) * (inTriangleC.y - inTriangleA.y) - (inTriangleB.y - inTriangleA.y) * (inTriangleC.x - inTriangleA.x); float orientation = area > 0.0 ? 1.0 : -1.0; - uint edgeMask = (inTriangleMask & ~boundedTriangleFlag) - 1u; + uint edgeFlags = (inTriangleMask & ~boundedTriangleFlag) - 1u; + uint edgeMask = edgeFlags & 7u; // The actual sample in the content's device pixels, as D3D and Metal // take it: the interpolated face would put a sample that lies exactly on // a shared edge on either side by rounding. @@ -125,18 +128,47 @@ void main() { } } } - float distance0 = (edgeMask & 1u) != 0u ? orientation * edgeDistance(p, inTriangleA, inTriangleB) : 1e6; - float distance1 = (edgeMask & 2u) != 0u ? orientation * edgeDistance(p, inTriangleB, inTriangleC) : 1e6; - float distance2 = (edgeMask & 4u) != 0u ? orientation * edgeDistance(p, inTriangleC, inTriangleA) : 1e6; + // The clipped face owns the sample. Its original outline determines + // the feathering, even when clipping removed every silhouette edge. + vec2 coverageA = inTriangleA, coverageB = inTriangleB, coverageC = inTriangleC; + uint coverageFlags = edgeFlags; + float coverageSign = orientation; + if ((edgeFlags & coverageSourceFlag) != 0u) { + coverageA = inLocal; + coverageB = inSize; + coverageC = inCoverageC; + coverageFlags = uint(inRadius + 0.5); + coverageSign = cross2(coverageB - coverageA, coverageC - coverageA) > 0.0 ? 1.0 : -1.0; + } + uint coverageMask = coverageFlags & 7u; + float distance0 = (coverageMask & 1u) != 0u ? coverageSign * edgeDistance(p, coverageA, coverageB) : 1e6; + float distance1 = (coverageMask & 2u) != 0u ? coverageSign * edgeDistance(p, coverageB, coverageC) : 1e6; + float distance2 = (coverageMask & 4u) != 0u ? coverageSign * edgeDistance(p, coverageC, coverageA) : 1e6; float inside = min(distance0, min(distance1, distance2)); + bool strokeQuad = (coverageFlags & strokeQuadEdgeMask) != 0u; + vec2 oppositeStart, oppositeEnd; + if (strokeQuad) { + // The shared diagonal decides ownership, but coverage depends on both long edges. + bool firstHalf = (coverageMask & 1u) != 0u; + vec2 from = firstHalf ? coverageA : coverageC; + vec2 to = firstHalf ? coverageB : coverageA; + oppositeStart = firstHalf ? coverageC : coverageB; + oppositeEnd = oppositeStart + (to - from); + float primary = firstHalf ? distance0 : distance2; + inside = min(inside, coverageSign * edgeDistance(oppositeStart, from, to) - primary); + } if (inside < 0.0) { - // Acute offset-line miters must not paint beyond the actual ends. - float s0 = (edgeMask & 1u) != 0u ? segmentDistance(p, inTriangleA, inTriangleB) : 1e6; - float s1 = (edgeMask & 2u) != 0u ? segmentDistance(p, inTriangleB, inTriangleC) : 1e6; - float s2 = (edgeMask & 4u) != 0u ? segmentDistance(p, inTriangleC, inTriangleA) : 1e6; - inside = -min(s0, min(s1, s2)); + // Use the visible edge segments for the outward fringe. A clipped + // stroke's original edges may extend beyond the cut. + bool clippedStroke = (edgeFlags & coverageSourceFlag) != 0u; + uint fringeMask = clippedStroke ? edgeMask : coverageMask; + float s0 = (fringeMask & 1u) != 0u ? segmentDistance(p, inTriangleA, inTriangleB) : 1e6; + float s1 = (fringeMask & 2u) != 0u ? segmentDistance(p, inTriangleB, inTriangleC) : 1e6; + float s2 = (fringeMask & 4u) != 0u ? segmentDistance(p, inTriangleC, inTriangleA) : 1e6; + float opposite = strokeQuad && !clippedStroke ? segmentDistance(p, oppositeStart, oppositeEnd) : 1e6; + inside = -min(min(s0, s1), min(s2, opposite)); } - float coverage = edgeMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); + float coverage = coverageMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); vec4 shade = clamp(inColor, 0.0, 1.0); float alpha = shade.a * coverage; outColor = vec4(shade.rgb * alpha, alpha); diff --git a/internal/platform/vulkan/shaders/scene.frag.spv b/internal/platform/vulkan/shaders/scene.frag.spv index cdc526655..1bfadc985 100644 Binary files a/internal/platform/vulkan/shaders/scene.frag.spv and b/internal/platform/vulkan/shaders/scene.frag.spv differ diff --git a/internal/platform/vulkan/shaders/scene.vert b/internal/platform/vulkan/shaders/scene.vert index 21f858f63..4dbcd15f6 100644 --- a/internal/platform/vulkan/shaders/scene.vert +++ b/internal/platform/vulkan/shaders/scene.vert @@ -11,6 +11,7 @@ layout(location = 4) in vec4 inShade2; // Low bits keep edgeMask+1; this bit is local to the rasterizer. #define boundedTriangleFlag (1u << 8) +#define coverageSourceFlag (1u << 4) layout(push_constant) uniform Frame { vec2 viewport; @@ -24,7 +25,7 @@ layout(location = 0) out vec4 outColor; layout(location = 1) out vec2 outLocal; layout(location = 2) out vec2 outSize; layout(location = 3) out float outRadius; -layout(location = 4) out vec2 outFragment; +layout(location = 4) flat out vec2 outCoverageC; layout(location = 5) out vec2 outTriangleA; layout(location = 6) out vec2 outTriangleB; layout(location = 7) out vec2 outTriangleC; @@ -59,6 +60,7 @@ void main() { vec2 localPixel; vec2 size = inBounds.zw; float radius = inStyle.x; + vec2 coverageC = vec2(0.0); vec2 triangleA = vec2(0.0); vec2 triangleB = vec2(0.0); vec2 triangleC = vec2(0.0); @@ -67,7 +69,9 @@ void main() { if (inStyle.w > 0.5) { vec2 points[3] = vec2[](inBounds.xy, inBounds.zw, inStyle.xz); uint index = gl_VertexIndex < 3 ? uint(gl_VertexIndex) : 0u; - uint edgeMask = uint(inStyle.w + 0.5) - 1u; + uint edgeFlags = uint(inStyle.w + 0.5) - 1u; + uint edgeMask = edgeFlags & 7u; + bool hasCoverageSource = (edgeFlags & coverageSourceFlag) != 0u; uint previous = (index + 2u) % 3u; vec2 ab = points[1] - points[0], ac = points[2] - points[0]; vec2 bc = points[2] - points[1]; @@ -81,7 +85,7 @@ void main() { // scales because hardware snaps geometry to its own subpixel grid. // Above this aspect ratio the miter displacement is at most eight // device pixels; below it the quad avoids both overflow and overdraw. - bool bounded = valid && (edgeMask != 7u || abs(area) < longest2 * 0.125); + bool bounded = valid && (hasCoverageSource || edgeMask != 7u || abs(area) < longest2 * 0.125); if (!valid) { pixel = vec2(0.0); } else if (bounded) { @@ -92,18 +96,20 @@ void main() { pixel = fringeVertex(points[previous], points[index], points[(index + 1u) % 3u], 1u << previous, 1u << index, edgeMask); } // Extrapolate corner colors so interpolation stays on the original mesh. - if (valid) { + if (valid && !hasCoverageSource) { vec2 delta = pixel - points[0]; color = inColor + cross2(delta, ac) / area * (inShade1 - inColor) + cross2(ab, delta) / area * (inShade2 - inColor); } - localPixel = vec2(0.0); - size = vec2(0.0); - radius = 0.0; + // A clipped flat stroke sends its antialiasing face in the shade slots. + localPixel = hasCoverageSource ? inShade1.xy : vec2(0.0); + size = hasCoverageSource ? inShade1.zw : vec2(0.0); + coverageC = hasCoverageSource ? inShade2.xy : vec2(0.0); + radius = hasCoverageSource ? inShade2.z : 0.0; triangleA = points[0]; triangleB = points[1]; triangleC = points[2]; - triangleMask = edgeMask + 1u + (bounded ? boundedTriangleFlag : 0u); + triangleMask = edgeFlags + 1u + (bounded ? boundedTriangleFlag : 0u); } else if (inStyle.z > 0.0) { // A soft shadow: inBounds and inStyle.x are the rounded rectangle that // casts it, inStyle.z its blur, inShade1 = (offset.x, offset.y, spread). The @@ -127,7 +133,7 @@ void main() { outLocal = localPixel; outSize = size; outRadius = radius; - outFragment = pixel; + outCoverageC = coverageC; outTriangleA = triangleA; outTriangleB = triangleB; outTriangleC = triangleC; diff --git a/internal/platform/vulkan/shaders/scene.vert.spv b/internal/platform/vulkan/shaders/scene.vert.spv index 763411859..cb996ef35 100644 Binary files a/internal/platform/vulkan/shaders/scene.vert.spv and b/internal/platform/vulkan/shaders/scene.vert.spv differ diff --git a/internal/platform/vulkan/vulkan_scene_linux.go b/internal/platform/vulkan/vulkan_scene_linux.go index 59f0937f1..bfd629bcc 100644 --- a/internal/platform/vulkan/vulkan_scene_linux.go +++ b/internal/platform/vulkan/vulkan_scene_linux.go @@ -6,6 +6,7 @@ import ( "unsafe" "github.com/ebitengine/purego" + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" ) @@ -273,10 +274,9 @@ func makeVulkanRectangleInstance(rectangle render.Rectangle) vulkanRectangleInst } if rectangle.Kind == scene.KindTriangle { instance.Bounds = [4]float32{rectangle.Points[0].X, rectangle.Points[0].Y, rectangle.Points[1].X, rectangle.Points[1].Y} - instance.Style = [4]float32{rectangle.Points[2].X, float32(rectangle.Layer), rectangle.Points[2].Y, float32(rectangle.EdgeMask + 1)} - colors := rectangle.VertexColors() - instance.Shade1 = [4]float32{colors[1].Red, colors[1].Green, colors[1].Blue, colors[1].Alpha} - instance.Shade2 = [4]float32{colors[2].Red, colors[2].Green, colors[2].Blue, colors[2].Alpha} + marker, shade1, shade2 := platform.PackTriangleCoverage(rectangle) + instance.Style = [4]float32{rectangle.Points[2].X, float32(rectangle.Layer), rectangle.Points[2].Y, marker} + instance.Shade1, instance.Shade2 = shade1, shade2 } if rectangle.Kind == scene.KindShadow && rectangle.Shadow.Blur > 0 { // The casting rectangle keeps the slot's bounds and radius; the blur is the diff --git a/internal/platform/watermark.go b/internal/platform/watermark.go new file mode 100644 index 000000000..40090d0de --- /dev/null +++ b/internal/platform/watermark.go @@ -0,0 +1,93 @@ +package platform + +import ( + "fmt" + "math" + "strings" + "unicode/utf8" + + "github.com/vivaui/viva/gfx" +) + +const ( + watermarkMaxFontSize = 4096 + watermarkMaxTileSize = 8192 + watermarkMaxTilePixels = 16 << 20 + watermarkMaxTextBytes = 16 << 10 +) + +// Watermark is an input-transparent, native text pattern above all content. +type Watermark struct { + Text, FontFamily string + Color Color + FontSize, FontWeight, Angle float32 + TileWidth, TileHeight float32 + Insets gfx.Insets +} + +// NormalizeWatermark validates the complete request before changing native state. +func NormalizeWatermark(w Watermark) (Watermark, error) { + if len(w.Text) > watermarkMaxTextBytes || len(w.FontFamily) > 1024 || strings.ContainsAny(w.Text, "\r\n") { + return Watermark{}, fmt.Errorf("watermark: text must be a bounded single line and family name at most 1024 bytes") + } + if !utf8.ValidString(w.Text) || strings.IndexByte(w.Text, 0) >= 0 || !utf8.ValidString(w.FontFamily) || strings.IndexByte(w.FontFamily, 0) >= 0 { + return Watermark{}, fmt.Errorf("watermark: text must be valid UTF-8 without NUL") + } + values := []float32{w.FontSize, w.TileWidth, w.TileHeight, w.Insets.Top, w.Insets.Right, w.Insets.Bottom, w.Insets.Left} + for _, v := range values { + if math.IsNaN(float64(v)) || math.IsInf(float64(v), 0) || v < 0 { + return Watermark{}, fmt.Errorf("watermark: dimensions must be finite and nonnegative") + } + } + for _, v := range []float64{float64(w.Angle), float64(w.FontWeight), w.Color.Red, w.Color.Green, w.Color.Blue, w.Color.Alpha} { + if math.IsNaN(v) || math.IsInf(v, 0) { + return Watermark{}, fmt.Errorf("watermark: parameters must be finite") + } + } + if w.Color.Red < 0 || w.Color.Red > 1 || w.Color.Green < 0 || w.Color.Green > 1 || w.Color.Blue < 0 || w.Color.Blue > 1 || w.Color.Alpha < 0 || w.Color.Alpha > 1 { + return Watermark{}, fmt.Errorf("watermark: color components must be between 0 and 1") + } + if w.FontWeight < gfx.WeightLight || w.FontWeight > gfx.WeightBold { + return Watermark{}, fmt.Errorf("watermark: font weight must be between gfx.WeightLight and gfx.WeightBold") + } + if w.Text == "" { + return Watermark{}, nil + } + if w.Color == (Color{}) { + w.Color = Color{Red: 0.5, Green: 0.5, Blue: 0.5, Alpha: 0.12} + } + if w.FontSize == 0 { + w.FontSize = 12 + } + if w.TileWidth == 0 { + w.TileWidth = 240 + } + if w.TileHeight == 0 { + w.TileHeight = 180 + } + // Bound native allocations at every backing scale; the pixel-size helper also + // caps the total area before a platform allocates its retained tile. + if w.FontSize > watermarkMaxFontSize || w.TileWidth > watermarkMaxTileSize || w.TileHeight > watermarkMaxTileSize { + return Watermark{}, fmt.Errorf("watermark: text or tile dimensions exceed limits") + } + return w, nil +} + +// WatermarkTileSize converts logical periods to physical pixels without a 1x intermediate. +func WatermarkTileSize(w Watermark, scale float32) (int, int) { + if scale <= 0 || math.IsNaN(float64(scale)) || math.IsInf(float64(scale), 0) { + return 0, 0 + } + width, height := math.Ceil(float64(w.TileWidth)*float64(scale)), math.Ceil(float64(w.TileHeight)*float64(scale)) + if width <= 0 || height <= 0 || width > watermarkMaxTileSize || height > watermarkMaxTileSize || width*height > watermarkMaxTilePixels { + return 0, 0 + } + return int(width), int(height) +} + +// WatermarkContentRect clips the overlay to client pixels. Insets are logical. +func WatermarkContentRect(size gfx.Size, insets gfx.Insets, scale float32) gfx.Rect { + x, y := float32(math.Ceil(float64(insets.Left*scale))), float32(math.Ceil(float64(insets.Top*scale))) + right, bottom := float32(math.Floor(float64(size.Width-insets.Right*scale))), float32(math.Floor(float64(size.Height-insets.Bottom*scale))) + return gfx.Rect{X: x, Y: y, Width: max(right-x, 0), Height: max(bottom-y, 0)} +} diff --git a/internal/platform/watermark_test.go b/internal/platform/watermark_test.go new file mode 100644 index 000000000..b7b781dde --- /dev/null +++ b/internal/platform/watermark_test.go @@ -0,0 +1,71 @@ +package platform + +import ( + "math" + "testing" + + "github.com/vivaui/viva/gfx" +) + +func TestWatermarkValidationAndDefaults(t *testing.T) { + base := Watermark{Text: "测试用户 10086", Color: Color{Alpha: 0.1}, FontWeight: -0.4} + got, err := NormalizeWatermark(base) + if err != nil || got.FontSize != 12 || got.TileWidth != 240 || got.TileHeight != 180 || got.FontWeight != -0.4 { + t.Fatalf("defaults: %+v, %v", got, err) + } + for name, change := range map[string]func(*Watermark){ + "invalid UTF-8": func(w *Watermark) { w.Text = "\xff" }, + "NUL": func(w *Watermark) { w.Text = "a\x00b" }, + "negative tile": func(w *Watermark) { w.TileWidth = -1 }, + "multiline": func(w *Watermark) { w.Text = "a\nb" }, + "negative weight": func(w *Watermark) { w.FontWeight = -1 }, + "large weight": func(w *Watermark) { w.FontWeight = 1 }, + "large tile": func(w *Watermark) { w.TileWidth = 1 << 25 }, + "invalid family": func(w *Watermark) { w.FontFamily = "bad\x00family" }, + "negative alpha": func(w *Watermark) { w.Color.Alpha = -1 }, + "negative inset": func(w *Watermark) { w.Insets.Top = -1 }, + "NaN": func(w *Watermark) { w.Angle = float32(math.NaN()) }, + "infinite color": func(w *Watermark) { w.Color.Red = math.Inf(1) }, + } { + t.Run(name, func(t *testing.T) { + value := base + change(&value) + if _, err := NormalizeWatermark(value); err == nil { + t.Fatal("invalid request accepted") + } + }) + } + for _, value := range []Watermark{{}} { + normalized, err := NormalizeWatermark(value) + if err != nil || normalized != (Watermark{}) { + t.Fatalf("disabled: %+v, %v", normalized, err) + } + } +} + +func TestWatermarkPixelGeometry(t *testing.T) { + for _, scale := range []float32{1, 1.25, 1.5, 2} { + width, height := WatermarkTileSize(Watermark{TileWidth: 240, TileHeight: 180}, scale) + if width != int(240*scale) || height != int(180*scale) { + t.Fatal("tile was not rasterized at backing scale", scale, width, height) + } + area := WatermarkContentRect(gfx.Size{Width: 1600 * scale, Height: 960 * scale}, gfx.Insets{Top: 42, Left: 120}, scale) + if area.X != 120*scale || area.Width != (1600-120)*scale || area.Y < float32(42)*scale || area.Height <= 0 { + t.Fatal("incorrect content clipping", scale, area) + } + } + area := WatermarkContentRect(gfx.Size{Width: 10, Height: 10}, gfx.Insets{Left: 120, Top: 42}, 2) + if area.Width != 0 || area.Height != 0 { + t.Fatal("insets outside client must hide the overlay", area) + } +} + +func TestWatermarkTextOnlyIsVisibleAndTileAllocationIsBounded(t *testing.T) { + value, err := NormalizeWatermark(Watermark{Text: "DRAFT"}) + if err != nil || value.Color.Alpha <= 0 || value.FontSize <= 0 { + t.Fatal("text-only watermark is invisible", value, err) + } + if width, height := WatermarkTileSize(Watermark{TileWidth: 8192, TileHeight: 8192}, 4); width != 0 || height != 0 { + t.Fatal("oversized backing allocation accepted") + } +} diff --git a/internal/platform/web/glpack.go b/internal/platform/web/glpack.go index ef8138072..ec1cfa721 100644 --- a/internal/platform/web/glpack.go +++ b/internal/platform/web/glpack.go @@ -1,6 +1,7 @@ package web import ( + "github.com/vivaui/viva/internal/platform" "github.com/vivaui/viva/internal/render" "github.com/vivaui/viva/internal/scene" ) @@ -35,18 +36,18 @@ func packInstance(dst []float32, instance render.Rectangle) { for index := 0; index < 20; index++ { dst[index] = 0 } - colors := instance.VertexColors() setColor := func(at int, color scene.Color) { dst[at], dst[at+1], dst[at+2], dst[at+3] = color.Red, color.Green, color.Blue, color.Alpha } switch instance.Kind { case scene.KindTriangle: points := instance.Points + marker, shade1, shade2 := platform.PackTriangleCoverage(instance) dst[0], dst[1], dst[2], dst[3] = points[0].X, points[0].Y, points[1].X, points[1].Y - dst[8], dst[9], dst[10], dst[11] = points[2].X, float32(instance.Layer), points[2].Y, float32(instance.EdgeMask)+1 - setColor(4, colors[0]) - setColor(12, colors[1]) - setColor(16, colors[2]) + dst[8], dst[9], dst[10], dst[11] = points[2].X, float32(instance.Layer), points[2].Y, marker + setColor(4, instance.Color) + copy(dst[12:16], shade1[:]) + copy(dst[16:20], shade2[:]) case scene.KindShadow: dst[0], dst[1], dst[2], dst[3] = instance.Bounds.X, instance.Bounds.Y, instance.Bounds.Width, instance.Bounds.Height dst[8], dst[9], dst[10], dst[11] = instance.Radius, 0, instance.Shadow.Blur, 0 diff --git a/internal/platform/web/painter.go b/internal/platform/web/painter.go index f1b44ea8d..f316c6df2 100644 --- a/internal/platform/web/painter.go +++ b/internal/platform/web/painter.go @@ -153,7 +153,7 @@ func (p *painter) keyDownCode(event gfx.KeyEvent, code uint32) bool { activated = true } p.focus.Refresh() - if event.Key == gfx.KeyTab { + if !response.Handled && event.Key == gfx.KeyTab { p.focus.SetKeyboardFocus(!p.focus.Focused().IsZero()) } focusChanged := p.applyEventResult(response) diff --git a/internal/platform/web/painter_test.go b/internal/platform/web/painter_test.go index 285903d5c..ca8e78cb7 100644 --- a/internal/platform/web/painter_test.go +++ b/internal/platform/web/painter_test.go @@ -93,6 +93,34 @@ func TestPointerFocusMatchesNativeWithoutRing(t *testing.T) { } } +func TestHandledKeyTabDoesNotRevealKeyboardFocus(t *testing.T) { + var canvas gfx.Canvas + config := Config{ + Paint: func(canvas *gfx.Canvas, _ gfx.Size) { + canvas.HitWithOptions(gfx.Item(1), gfx.Rect{X: 0, Y: 0, Width: 80, Height: 40}, "Terminal", gfx.HitOptions{Role: gfx.RoleTerminal}) + canvas.HitWithLabel(gfx.Item(2), gfx.Rect{X: 100, Y: 0, Width: 80, Height: 40}, "Cancel") + }, + OnKey: func(event gfx.KeyEvent) gfx.EventResult { + if event.Key == gfx.KeyTab && event.Target == gfx.Item(1) { + return gfx.EventResult{Handled: true} + } + return gfx.EventResult{} + }, + } + painter := newPainter(&canvas, &config) + painter.width, painter.height = 200, 100 + painter.repaint() + painter.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerDown, Button: gfx.PointerButtonPrimary, X: 20, Y: 20}) + painter.pointerEvent(gfx.PointerEvent{Kind: gfx.PointerUp, Button: gfx.PointerButtonPrimary, X: 20, Y: 20}) + if painter.focus.Focused() != gfx.Item(1) || painter.focus.KeyboardFocus() { + t.Fatalf("after click: focused=%v keyboard=%v", painter.focus.Focused(), painter.focus.KeyboardFocus()) + } + painter.keyDown(gfx.KeyEvent{Key: gfx.KeyTab}) + if painter.focus.Focused() != gfx.Item(1) || painter.focus.KeyboardFocus() || !canvas.FocusVisible().IsZero() { + t.Fatalf("handled Tab changed focus state: focused=%v keyboard=%v visible=%v", painter.focus.Focused(), painter.focus.KeyboardFocus(), canvas.FocusVisible()) + } +} + func TestPointerEventsCaptureTargetAndHandledSuppressesClick(t *testing.T) { var canvas gfx.Canvas var events [3]gfx.PointerEvent diff --git a/internal/platform/web/shaders/scene.frag.glsl b/internal/platform/web/shaders/scene.frag.glsl index 3d1ae728b..095797d49 100644 --- a/internal/platform/web/shaders/scene.frag.glsl +++ b/internal/platform/web/shaders/scene.frag.glsl @@ -6,7 +6,7 @@ in vec4 vColor; in vec2 vLocal; in vec2 vSize; in float vRadius; -in vec2 vFragment; +flat in vec2 vCoverageC; in vec2 vTriangleA; in vec2 vTriangleB; in vec2 vTriangleC; @@ -19,6 +19,8 @@ uniform float uPixelSize; out vec4 outColor; #define boundedTriangleFlag (1u << 8) +#define strokeQuadEdgeMask (1u << 3) +#define coverageSourceFlag (1u << 4) float edgeDistance(vec2 point, vec2 from, vec2 to) { vec2 edge = to - from; @@ -82,7 +84,8 @@ void main() { float area = (vTriangleB.x - vTriangleA.x) * (vTriangleC.y - vTriangleA.y) - (vTriangleB.y - vTriangleA.y) * (vTriangleC.x - vTriangleA.x); float orientation = area > 0.0 ? 1.0 : -1.0; - uint edgeMask = (vTriangleMask & ~boundedTriangleFlag) - 1u; + uint edgeFlags = (vTriangleMask & ~boundedTriangleFlag) - 1u; + uint edgeMask = edgeFlags & 7u; // Marked edges are supporting lines: only their half-pixel neighborhood // of the triangle itself is coverage. Without this cut a sliver paints // its lines across the window. @@ -121,18 +124,47 @@ void main() { } } } - float distance0 = (edgeMask & 1u) != 0u ? orientation * edgeDistance(p, vTriangleA, vTriangleB) : 1e6; - float distance1 = (edgeMask & 2u) != 0u ? orientation * edgeDistance(p, vTriangleB, vTriangleC) : 1e6; - float distance2 = (edgeMask & 4u) != 0u ? orientation * edgeDistance(p, vTriangleC, vTriangleA) : 1e6; + // The clipped face owns the sample. Its original outline determines + // the feathering, even when clipping removed every silhouette edge. + vec2 coverageA = vTriangleA, coverageB = vTriangleB, coverageC = vTriangleC; + uint coverageFlags = edgeFlags; + float coverageSign = orientation; + if ((edgeFlags & coverageSourceFlag) != 0u) { + coverageA = vLocal; + coverageB = vSize; + coverageC = vCoverageC; + coverageFlags = uint(vRadius + 0.5); + coverageSign = cross2(coverageB - coverageA, coverageC - coverageA) > 0.0 ? 1.0 : -1.0; + } + uint coverageMask = coverageFlags & 7u; + float distance0 = (coverageMask & 1u) != 0u ? coverageSign * edgeDistance(p, coverageA, coverageB) : 1e6; + float distance1 = (coverageMask & 2u) != 0u ? coverageSign * edgeDistance(p, coverageB, coverageC) : 1e6; + float distance2 = (coverageMask & 4u) != 0u ? coverageSign * edgeDistance(p, coverageC, coverageA) : 1e6; float inside = min(distance0, min(distance1, distance2)); + bool strokeQuad = (coverageFlags & strokeQuadEdgeMask) != 0u; + vec2 oppositeStart, oppositeEnd; + if (strokeQuad) { + // The shared diagonal decides ownership, but coverage depends on both long edges. + bool firstHalf = (coverageMask & 1u) != 0u; + vec2 from = firstHalf ? coverageA : coverageC; + vec2 to = firstHalf ? coverageB : coverageA; + oppositeStart = firstHalf ? coverageC : coverageB; + oppositeEnd = oppositeStart + (to - from); + float primary = firstHalf ? distance0 : distance2; + inside = min(inside, coverageSign * edgeDistance(oppositeStart, from, to) - primary); + } if (inside < 0.0) { - // Acute offset-line miters must not paint beyond the actual ends. - float s0 = (edgeMask & 1u) != 0u ? segmentDistance(p, vTriangleA, vTriangleB) : 1e6; - float s1 = (edgeMask & 2u) != 0u ? segmentDistance(p, vTriangleB, vTriangleC) : 1e6; - float s2 = (edgeMask & 4u) != 0u ? segmentDistance(p, vTriangleC, vTriangleA) : 1e6; - inside = -min(s0, min(s1, s2)); + // Use the visible edge segments for the outward fringe. A clipped + // stroke's original edges may extend beyond the cut. + bool clippedStroke = (edgeFlags & coverageSourceFlag) != 0u; + uint fringeMask = clippedStroke ? edgeMask : coverageMask; + float s0 = (fringeMask & 1u) != 0u ? segmentDistance(p, vTriangleA, vTriangleB) : 1e6; + float s1 = (fringeMask & 2u) != 0u ? segmentDistance(p, vTriangleB, vTriangleC) : 1e6; + float s2 = (fringeMask & 4u) != 0u ? segmentDistance(p, vTriangleC, vTriangleA) : 1e6; + float opposite = strokeQuad && !clippedStroke ? segmentDistance(p, oppositeStart, oppositeEnd) : 1e6; + inside = -min(min(s0, s1), min(s2, opposite)); } - float coverage = edgeMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); + float coverage = coverageMask == 0u ? 1.0 : clamp(0.5 + inside / pixel, 0.0, 1.0); vec4 shade = clamp(vColor, 0.0, 1.0); float alpha = shade.a * coverage; outColor = vec4(shade.rgb * alpha, alpha); diff --git a/internal/platform/web/shaders/scene.vert.glsl b/internal/platform/web/shaders/scene.vert.glsl index 0f919b76b..cb0ff5994 100644 --- a/internal/platform/web/shaders/scene.vert.glsl +++ b/internal/platform/web/shaders/scene.vert.glsl @@ -13,12 +13,13 @@ uniform float uPixelSize; // Low bits keep edgeMask+1; this bit is local to the rasterizer. #define boundedTriangleFlag (1u << 8) +#define coverageSourceFlag (1u << 4) out vec4 vColor; out vec2 vLocal; out vec2 vSize; out float vRadius; -out vec2 vFragment; +flat out vec2 vCoverageC; out vec2 vTriangleA; out vec2 vTriangleB; out vec2 vTriangleC; @@ -54,6 +55,7 @@ void main() { vec2 localPixel; vec2 size = inBounds.zw; float radius = inStyle.x; + vec2 coverageC = vec2(0.0); vec2 triangleA = vec2(0.0); vec2 triangleB = vec2(0.0); vec2 triangleC = vec2(0.0); @@ -62,7 +64,9 @@ void main() { if (inStyle.w > 0.5) { vec2 points[3] = vec2[](inBounds.xy, inBounds.zw, inStyle.xz); uint index = gl_VertexID < 3 ? uint(gl_VertexID) : 0u; - uint edgeMask = uint(inStyle.w + 0.5) - 1u; + uint edgeFlags = uint(inStyle.w + 0.5) - 1u; + uint edgeMask = edgeFlags & 7u; + bool hasCoverageSource = (edgeFlags & coverageSourceFlag) != 0u; uint previous = (index + 2u) % 3u; vec2 ab = points[1] - points[0], ac = points[2] - points[0]; vec2 bc = points[2] - points[1]; @@ -74,7 +78,7 @@ void main() { // its finite support instead. Every face with a shared edge uses this // path: mixing hardware and analytic edge ownership cracks at fractional // scales because hardware snaps geometry to its own subpixel grid. - bool bounded = valid && (edgeMask != 7u || abs(area) < longest2 * 0.125); + bool bounded = valid && (hasCoverageSource || edgeMask != 7u || abs(area) < longest2 * 0.125); if (!valid) { pixel = vec2(0.0); } else if (bounded) { @@ -85,18 +89,20 @@ void main() { pixel = fringeVertex(points[previous], points[index], points[(index + 1u) % 3u], 1u << previous, 1u << index, edgeMask); } // Extrapolate corner colors so interpolation stays on the original mesh. - if (valid) { + if (valid && !hasCoverageSource) { vec2 delta = pixel - points[0]; color = inColor + cross2(delta, ac) / area * (inShade1 - inColor) + cross2(ab, delta) / area * (inShade2 - inColor); } - localPixel = vec2(0.0); - size = vec2(0.0); - radius = 0.0; + // A clipped flat stroke sends its antialiasing face in the shade slots. + localPixel = hasCoverageSource ? inShade1.xy : vec2(0.0); + size = hasCoverageSource ? inShade1.zw : vec2(0.0); + coverageC = hasCoverageSource ? inShade2.xy : vec2(0.0); + radius = hasCoverageSource ? inShade2.z : 0.0; triangleA = points[0]; triangleB = points[1]; triangleC = points[2]; - triangleMask = edgeMask + 1u + (bounded ? boundedTriangleFlag : 0u); + triangleMask = edgeFlags + 1u + (bounded ? boundedTriangleFlag : 0u); } else if (inStyle.z > 0.0) { // A soft shadow: inBounds and inStyle.x are the rounded rectangle that // casts it, inStyle.z its blur, inShade1 = (offset.x, offset.y, spread). @@ -118,7 +124,7 @@ void main() { vLocal = localPixel; vSize = size; vRadius = radius; - vFragment = pixel; + vCoverageC = coverageC; vTriangleA = triangleA; vTriangleB = triangleB; vTriangleC = triangleC; diff --git a/internal/platform/windows/always_on_top_windows.go b/internal/platform/windows/always_on_top_windows.go index 9e0273d2f..75e4d616f 100644 --- a/internal/platform/windows/always_on_top_windows.go +++ b/internal/platform/windows/always_on_top_windows.go @@ -32,5 +32,8 @@ func (state *windowState) setAlwaysOnTop(enabled bool) bool { level = ^uintptr(0) // HWND_TOPMOST } applied, _, _ := setWindowPosition.Call(state.window, level, 0, 0, 0, 0, 0x13) + if applied != 0 { + state.raiseWatermark() + } return applied != 0 } diff --git a/internal/platform/windows/notification_windows.go b/internal/platform/windows/notification_windows.go new file mode 100644 index 000000000..94aed6d3c --- /dev/null +++ b/internal/platform/windows/notification_windows.go @@ -0,0 +1,170 @@ +package windows + +import ( + "fmt" + "sync" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +const ( + wmNotificationActivation = 0x8014 + notificationBalloonClick = 0x0405 // NIN_BALLOONUSERCLICK + notificationIDNamespace uint32 = 1 << 31 +) + +type interactiveNotification struct { + host uintptr + activate func() +} + +var interactiveNotifications = struct { + sync.Mutex + next uint32 + entries map[uint32]interactiveNotification +}{} + +// ShowNotification serializes Shell and window access on the owning event loop. +// Closing invalidates callbacks immediately, even before queued native work runs. +func ShowNotification(title, body string, events platform.NotificationEvents) (func(), error) { + application := wakeOwner.Load() + if application == nil { + return nil, fmt.Errorf("windows: notification requires a running application") + } + var mu sync.Mutex + closed := false + var nativeCancel func() + activate := func() { + mu.Lock() + active := !closed + closed = true + mu.Unlock() + if active && events.Activated != nil { + events.Activated() + } + } + application.Post(func() { + mu.Lock() + stopped := closed + mu.Unlock() + if stopped { + return + } + cancel, err := showNotification(application, title, body, activate) + mu.Lock() + stopped = closed + if !stopped { + nativeCancel = cancel + } + mu.Unlock() + if stopped && cancel != nil { + cancel() + } + if err != nil { + mu.Lock() + active := !closed + closed = true + mu.Unlock() + if active && events.Failed != nil { + events.Failed(err) + } + } + }) + return func() { + mu.Lock() + closed = true + cancel := nativeCancel + nativeCancel = nil + mu.Unlock() + if cancel != nil { + application.Post(cancel) + } + }, nil +} + +func showNotification(application *windowsApplication, title, body string, activate func()) (func(), error) { + // The event-loop carrier outlives ordinary windows. Closing the window that + // happened to be active must not retire an application-owned notification. + host := application.wakeWindow.Load() + if host == 0 { + return nil, fmt.Errorf("windows: notification requires a running application") + } + icon := notificationIcon(notificationHost()) + if icon == 0 { + var err error + icon, _, err = loadIcon.Call(0, 32512) + if icon == 0 { + return nil, windowsCallError("load notification icon", err) + } + } + interactiveNotifications.Lock() + if interactiveNotifications.next >= notificationIDNamespace-1 { + interactiveNotifications.Unlock() + return nil, fmt.Errorf("windows: notification identifiers exhausted") + } + interactiveNotifications.next++ + id := notificationIDNamespace | interactiveNotifications.next + if interactiveNotifications.entries == nil { + interactiveNotifications.entries = make(map[uint32]interactiveNotification) + } + interactiveNotifications.entries[id] = interactiveNotification{host: host, activate: activate} + interactiveNotifications.Unlock() + // NIF_INFO with an empty body withdraws a balloon. Preserve title-only + // requests as body text rather than accidentally asking the Shell to remove it. + if body == "" { + body = title + title = "" + } + data := notificationIconData(host, icon, title, body) + data.ID = id + data.Flags |= notifyMessage + data.CallbackMessage = wmNotificationActivation + // Retain the legacy callback layout deliberately: wParam contains the full + // 32-bit uID. Version 4 truncates it to 16 bits and can alias stale callbacks. + if ok, _, err := callNotifyIcon(notifyAdd, &data); ok == 0 { + forgetInteractiveNotification(host, id) + return nil, windowsCallError("send interactive notification", err) + } + return func() { forgetInteractiveNotification(host, id) }, nil +} + +func forgetInteractiveNotification(host uintptr, id uint32) func() { + interactiveNotifications.Lock() + entry, ok := interactiveNotifications.entries[id] + if ok && entry.host == host { + delete(interactiveNotifications.entries, id) + } else { + ok = false + } + interactiveNotifications.Unlock() + if !ok { + return nil + } + data := notifyIconData{Size: uint32(unsafe.Sizeof(notifyIconData{})), Window: host, ID: id} + callNotifyIcon(notifyDelete, &data) + return entry.activate +} + +func activateSystemNotification(host uintptr, id, event uint32) { + if event != notificationBalloonClick { + return + } + if activate := forgetInteractiveNotification(host, id); activate != nil { + activate() + } +} + +func removeInteractiveNotifications(host uintptr) { + interactiveNotifications.Lock() + var ids []uint32 + for id, entry := range interactiveNotifications.entries { + if entry.host == host { + ids = append(ids, id) + } + } + interactiveNotifications.Unlock() + for _, id := range ids { + forgetInteractiveNotification(host, id) + } +} diff --git a/internal/platform/windows/notification_windows_test.go b/internal/platform/windows/notification_windows_test.go new file mode 100644 index 000000000..44086a728 --- /dev/null +++ b/internal/platform/windows/notification_windows_test.go @@ -0,0 +1,156 @@ +package windows + +import ( + "github.com/vivaui/viva/internal/platform" + "runtime" + "syscall" + "testing" +) + +func TestNotificationActivationIdentityAndCancellation(t *testing.T) { + previous := callNotifyIcon + callNotifyIcon = func(uintptr, *notifyIconData) (uintptr, uintptr, error) { return 1, 0, nil } + defer func() { callNotifyIcon = previous }() + const host = uintptr(0x1234) + id := notificationIDNamespace | 123 + calls := 0 + interactiveNotifications.Lock() + if interactiveNotifications.entries == nil { + interactiveNotifications.entries = make(map[uint32]interactiveNotification) + } + interactiveNotifications.entries[id] = interactiveNotification{host: host, activate: func() { calls++ }} + interactiveNotifications.Unlock() + activateSystemNotification(host+1, id, notificationBalloonClick) + activateSystemNotification(host, id, 0) + if calls != 0 { + t.Fatal("wrong host or event activated a notification") + } + wakeProc(host, wmNotificationActivation, uintptr(id), notificationBalloonClick) + wakeProc(host, wmNotificationActivation, uintptr(id), notificationBalloonClick) + if calls != 1 { + t.Fatalf("activation calls = %d", calls) + } + interactiveNotifications.Lock() + interactiveNotifications.entries[id+1] = interactiveNotification{host: host, activate: func() { calls++ }} + interactiveNotifications.Unlock() + removeInteractiveNotifications(host) + activateSystemNotification(host, id+1, notificationBalloonClick) + if calls != 1 { + t.Fatal("closed host retained activation") + } +} + +func TestNotificationTruncationPreservesUTF16(t *testing.T) { + var short [3]uint16 + copyUTF16(short[:], "a😀b") + if short[0] != 'a' || short[1] != 0 { + t.Fatal("truncated title retained half a surrogate pair", short) + } + var fitting [4]uint16 + copyUTF16(fitting[:], "a😀b") + if fitting[0] != 'a' || fitting[1] != 0xd83d || fitting[2] != 0xde00 || fitting[3] != 0 { + t.Fatal("title lost a complete surrogate pair", fitting) + } + copyUTF16(nil, "ignored") +} + +// The Shell call is mocked, so this exercises the real message-only carrier and +// queued lifecycle without displaying a notification or opening a visual window. +func TestNotificationCarrierAndQueuedCancellation(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + application := &windowsApplication{} + if err := application.openWakeWindow(); err != nil { + t.Fatal(err) + } + previous := callNotifyIcon + defer func() { application.closeWakeWindow(); callNotifyIcon = previous }() + var data notifyIconData + adds, calls := 0, 0 + callNotifyIcon = func(operation uintptr, value *notifyIconData) (uintptr, uintptr, error) { + if operation == notifyAdd { + data = *value + adds++ + } + return 1, 0, nil + } + events := platform.NotificationEvents{Activated: func() { calls++ }, Failed: func(err error) { t.Error(err) }} + cancel, err := ShowNotification("Title only", "", events) + if err != nil { + t.Fatal(err) + } + application.drainPosts() + if adds != 1 || data.Window != application.wakeWindow.Load() || syscall.UTF16ToString(data.Info[:]) != "Title only" || data.State¬ifyHidden == 0 || data.StateMask¬ifyHidden == 0 || data.Flags¬ifyState == 0 { + t.Fatal("request lost its application carrier, title-only content or hidden state") + } + oldID := data.ID + cancel() + wakeProc(data.Window, wmNotificationActivation, uintptr(oldID), notificationBalloonClick) + application.drainPosts() + if calls != 0 { + t.Fatal("late click escaped queued cancellation") + } + cancel, err = ShowNotification("Second", "body", events) + if err != nil { + t.Fatal(err) + } + application.drainPosts() + if data.ID == oldID { + t.Fatal("notification identity was reused") + } + wakeProc(data.Window, wmNotificationActivation, uintptr(oldID), notificationBalloonClick) + wakeProc(data.Window, wmNotificationActivation, uintptr(data.ID), notificationBalloonClick) + wakeProc(data.Window, wmNotificationActivation, uintptr(data.ID), notificationBalloonClick) + if calls != 1 { + t.Fatal("click identity did not select one live notification", calls) + } + cancel() + application.drainPosts() + cancel, err = ShowNotification("Cancelled before posting", "body", events) + if err != nil { + t.Fatal(err) + } + cancel() + application.drainPosts() + if adds != 2 { + t.Fatal("cancelled queued request reached the Shell") + } +} + +func TestNotificationShellFailureReleasesIdentity(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + application := &windowsApplication{} + if err := application.openWakeWindow(); err != nil { + t.Fatal(err) + } + previous := callNotifyIcon + defer func() { application.closeWakeWindow(); callNotifyIcon = previous }() + var id uint32 + callNotifyIcon = func(operation uintptr, data *notifyIconData) (uintptr, uintptr, error) { + id = data.ID + if operation == notifyAdd { + return 0, 0, syscall.EINVAL + } + return 1, 0, nil + } + errors := 0 + cancel, err := ShowNotification("title", "body", platform.NotificationEvents{Failed: func(err error) { + if err == nil { + t.Error("nil native failure") + } + errors++ + }}) + if err != nil { + t.Fatal(err) + } + application.drainPosts() + cancel() + application.drainPosts() + interactiveNotifications.Lock() + _, retained := interactiveNotifications.entries[id] + interactiveNotifications.Unlock() + if errors != 1 || retained { + t.Fatal("Shell failure retained a callback", errors, retained) + } +} diff --git a/internal/platform/windows/post_windows.go b/internal/platform/windows/post_windows.go index f677ae0b4..22313122f 100644 --- a/internal/platform/windows/post_windows.go +++ b/internal/platform/windows/post_windows.go @@ -41,6 +41,10 @@ var ( // wakeProc runs posted work for the wake window. A modal loop dispatches the // wake here just as the application's own loop does. func wakeProc(window, kind, first, second uintptr) (result uintptr) { + if kind == wmNotificationActivation { + activateSystemNotification(window, uint32(first), uint32(second)) + return 0 + } if kind == wmPost { if application := wakeOwner.Load(); application != nil { application.drainPosts() @@ -89,6 +93,7 @@ func (application *windowsApplication) openWakeWindow() error { // closeWakeWindow drops the wake window; no posted work runs after it. func (application *windowsApplication) closeWakeWindow() { if window := application.wakeWindow.Swap(0); window != 0 { + removeInteractiveNotifications(window) destroyWindow.Call(window) } wakeOwner.CompareAndSwap(application, nil) diff --git a/internal/platform/windows/renderer_windows.go b/internal/platform/windows/renderer_windows.go index 28d4d47b1..770453f5c 100644 --- a/internal/platform/windows/renderer_windows.go +++ b/internal/platform/windows/renderer_windows.go @@ -540,10 +540,9 @@ func makeRectangleInstance(rectangle render.Rectangle) rectangleInstance { // Same triangle slot convention as the Metal backend: // bounds=(p0, p1), style=(p2.x, layer, p2.y, edgeMask+1). instance.Bounds = [4]float32{rectangle.Points[0].X, rectangle.Points[0].Y, rectangle.Points[1].X, rectangle.Points[1].Y} - instance.Style = [4]float32{rectangle.Points[2].X, float32(rectangle.Layer), rectangle.Points[2].Y, float32(rectangle.EdgeMask + 1)} - colors := rectangle.VertexColors() - instance.Shade1 = [4]float32{colors[1].Red, colors[1].Green, colors[1].Blue, colors[1].Alpha} - instance.Shade2 = [4]float32{colors[2].Red, colors[2].Green, colors[2].Blue, colors[2].Alpha} + marker, shade1, shade2 := platform.PackTriangleCoverage(rectangle) + instance.Style = [4]float32{rectangle.Points[2].X, float32(rectangle.Layer), rectangle.Points[2].Y, marker} + instance.Shade1, instance.Shade2 = shade1, shade2 } if rectangle.Kind == scene.KindShadow && rectangle.Shadow.Blur > 0 { // The casting rectangle keeps the slot's bounds and radius; the blur is the diff --git a/internal/platform/windows/shaders/manifest.json b/internal/platform/windows/shaders/manifest.json index 462c7f3ac..01bfa63c6 100644 --- a/internal/platform/windows/shaders/manifest.json +++ b/internal/platform/windows/shaders/manifest.json @@ -1,30 +1,30 @@ { - "source_sha256": "5083c9723999eac26132facf2b8ce704824dfc4719b56fe9b8974de7d91b2524", + "source_sha256": "0a87c0024b7eaed6bfd77f1c47843e77dff754954839ed9156a029358f8ed548", "compiler": "d3dcompiler_47.dll", "flags": 34816, "entries": [ { "name": "rectangleVertex", "profile": "vs_5_0", - "sha256": "edf06eb99b4bbbc8f0386f1ddc0fbce58e20e61721c2c810073b7ab040873a03", - "bytes": 6612 + "sha256": "cf2f256447720e809e81cdc38b6f015b8ac72cee432324dba946f781558e8129", + "bytes": 6808 }, { "name": "rectangleFragment", "profile": "ps_5_0", - "sha256": "820e508861cefb20e957f6cd042110ab33f63220ee6a134c59b8c84f1ed60db1", - "bytes": 9660 + "sha256": "568dc12dba9084a4e72eff46fd01022b8fe4fb9397cfa258e84f134bdb46709e", + "bytes": 11308 }, { "name": "textVertex", "profile": "vs_5_0", - "sha256": "701be5fdd0a737b4f23d8807f92451955d587b0e91b4c6e8423b70236a3195c7", - "bytes": 2152 + "sha256": "9aae8cd4ab52b16ee24a465887e7c92d178dd950068b6f1db6d564f1b7fb4178", + "bytes": 2164 }, { "name": "textFragment", "profile": "ps_5_0", - "sha256": "43278ce7f746c6d9b366868be6388938e5dec229a01d4c4e78be043236954542", + "sha256": "2d79ce8be175bfdae8f807268157325e7122e72d57185b202dff778293d25007", "bytes": 2576 } ] diff --git a/internal/platform/windows/shaders/rectangleFragment.dxbc b/internal/platform/windows/shaders/rectangleFragment.dxbc index 261e021d9..c1683f999 100644 Binary files a/internal/platform/windows/shaders/rectangleFragment.dxbc and b/internal/platform/windows/shaders/rectangleFragment.dxbc differ diff --git a/internal/platform/windows/shaders/rectangleVertex.dxbc b/internal/platform/windows/shaders/rectangleVertex.dxbc index f8f28333c..1af12b462 100644 Binary files a/internal/platform/windows/shaders/rectangleVertex.dxbc and b/internal/platform/windows/shaders/rectangleVertex.dxbc differ diff --git a/internal/platform/windows/shaders/scene.hlsl b/internal/platform/windows/shaders/scene.hlsl index 8387c9b9c..635d1c6fd 100644 --- a/internal/platform/windows/shaders/scene.hlsl +++ b/internal/platform/windows/shaders/scene.hlsl @@ -8,9 +8,11 @@ struct Rectangle { float4 bounds; float4 color; float4 style; float4 shade1; flo StructuredBuffer rectangles : register(t0); Texture2D labelTexture : register(t1); SamplerState labelSampler : register(s0); -struct Vertex { float4 position : SV_Position; float4 color : COLOR; float2 local : LOCAL; float2 size : SIZE; float radius : RADIUS; float2 uv : TEXCOORD; float2 frag : FRAG; float2 triA : TRIA; float2 triB : TRIB; float2 triC : TRIC; nointerpolation uint triangleMask : TRIMASK; }; +struct Vertex { float4 position : SV_Position; float4 color : COLOR; float2 local : LOCAL; float2 size : SIZE; float radius : RADIUS; float2 uv : TEXCOORD; nointerpolation float2 coverageC : COVERC; float2 triA : TRIA; float2 triB : TRIB; float2 triC : TRIC; nointerpolation uint triangleMask : TRIMASK; }; // Low bits keep edgeMask+1; this bit is local to the rasterizer. #define boundedTriangleFlag (1u << 8) +#define strokeQuadFlag (1u << 3) +#define coverageSourceFlag (1u << 4) float2 corner(uint vertex) { const float2 corners[6] = {float2(0,0),float2(1,0),float2(0,1),float2(0,1),float2(1,0),float2(1,1)}; return corners[vertex]; @@ -46,6 +48,7 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) float2 local; float2 size = rectangle.bounds.zw; float radius = rectangle.style.x; + float2 coverageC = 0; float2 triA = 0, triB = 0, triC = 0; uint triangleMask = 0; float4 color = rectangle.color; @@ -60,7 +63,9 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) rectangle.style.xz, }; uint index = vertex < 3 ? vertex : 0; - uint edgeMask = (uint)(rectangle.style.w + 0.5) - 1; + uint edgeFlags = (uint)(rectangle.style.w + 0.5) - 1; + uint edgeMask = edgeFlags & 7u; + bool hasCoverageSource = (edgeFlags & coverageSourceFlag) != 0; uint previous = (index + 2) % 3; float2 ab = points[1] - points[0], ac = points[2] - points[0]; float2 bc = points[2] - points[1]; @@ -74,7 +79,7 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) // scales because hardware snaps geometry to its own subpixel grid. // Above this aspect ratio the miter displacement is at most eight // device pixels; below it the quad avoids both overflow and overdraw. - bool bounded = valid && (edgeMask != 7 || abs(area) < longest2 * 0.125); + bool bounded = valid && (hasCoverageSource || edgeMask != 7 || abs(area) < longest2 * 0.125); if (!valid) { pixel = 0; } else if (bounded) { @@ -85,18 +90,20 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) pixel = fringeVertex(points[previous], points[index], points[(index + 1) % 3], 1u << previous, 1u << index, edgeMask); } // Extrapolate corner colors so interpolation stays on the original mesh. - if (valid) { + if (valid && !hasCoverageSource) { float2 delta = pixel - points[0]; color = rectangle.color + cross2(delta, ac) / area * (rectangle.shade1 - rectangle.color) + cross2(ab, delta) / area * (rectangle.shade2 - rectangle.color); } - local = 0; - size = 0; - radius = 0; + // A clipped flat stroke sends its antialiasing face in the shade slots. + local = hasCoverageSource ? rectangle.shade1.xy : 0; + size = hasCoverageSource ? rectangle.shade1.zw : 0; + coverageC = hasCoverageSource ? rectangle.shade2.xy : 0; + radius = hasCoverageSource ? rectangle.shade2.z : 0; triA = points[0]; triB = points[1]; triC = points[2]; - triangleMask = edgeMask + 1 + (bounded ? boundedTriangleFlag : 0); + triangleMask = edgeFlags + 1 + (bounded ? boundedTriangleFlag : 0); } else if (rectangle.style.z > 0) { // A soft shadow: bounds and style.x are the rounded rectangle that casts it, // style.z its blur, shade1 = (offset.x, offset.y, spread). The quad grows by @@ -119,7 +126,7 @@ Vertex rectangleVertex(uint vertex : SV_VertexID, uint instance : SV_InstanceID) output.size = size; output.radius = radius; output.uv = corner(vertex); - output.frag = pixel; + output.coverageC = coverageC; output.triA = triA; output.triB = triB; output.triC = triC; @@ -169,7 +176,8 @@ float4 rectangleFragment(Vertex input) : SV_Target { float area2 = (input.triB.x-input.triA.x)*(input.triC.y-input.triA.y) - (input.triB.y-input.triA.y)*(input.triC.x-input.triA.x); float sign = area2 > 0 ? 1 : -1; - uint edgeMask = (input.triangleMask & ~boundedTriangleFlag) - 1; + uint edgeFlags = (input.triangleMask & ~boundedTriangleFlag) - 1; + uint edgeMask = edgeFlags & 7u; // The actual sample, not the interpolated face: over a sliver's long // support the interpolant cannot say which pixel it is. float2 p = input.position.xy * pixelSize; @@ -211,18 +219,48 @@ float4 rectangleFragment(Vertex input) : SV_Target { } } } - float d0 = (edgeMask & 1u) != 0 ? sign * edgeDistance(p, input.triA, input.triB) : 1e6; - float d1 = (edgeMask & 2u) != 0 ? sign * edgeDistance(p, input.triB, input.triC) : 1e6; - float d2 = (edgeMask & 4u) != 0 ? sign * edgeDistance(p, input.triC, input.triA) : 1e6; + // The clipped face owns the sample. Its original outline determines + // the feathering, even when clipping removed every silhouette edge. + float2 coverageA = input.triA, coverageB = input.triB, coverageC = input.triC; + uint coverageFlags = edgeFlags; + float coverageSign = sign; + if ((edgeFlags & coverageSourceFlag) != 0u) { + coverageA = input.local; + coverageB = input.size; + coverageC = input.coverageC; + coverageFlags = uint(input.radius + 0.5); + coverageSign = cross2(coverageB - coverageA, coverageC - coverageA) > 0.0 ? 1.0 : -1.0; + } + uint coverageMask = coverageFlags & 7u; + float d0 = (coverageMask & 1u) != 0 ? coverageSign * edgeDistance(p, coverageA, coverageB) : 1e6; + float d1 = (coverageMask & 2u) != 0 ? coverageSign * edgeDistance(p, coverageB, coverageC) : 1e6; + float d2 = (coverageMask & 4u) != 0 ? coverageSign * edgeDistance(p, coverageC, coverageA) : 1e6; float inside = min(d0, min(d1, d2)); + float2 oppositeStart = 0, oppositeEnd = 0; + bool strokeQuad = (coverageFlags & strokeQuadFlag) != 0; + if (strokeQuad) { + // The diagonal assigns this sample to one triangle, but coverage is + // measured against both long edges of the original stroke quad. + bool firstHalf = (coverageMask & 1u) != 0; + float2 start = firstHalf ? coverageA : coverageC; + float2 end = firstHalf ? coverageB : coverageA; + oppositeStart = firstHalf ? coverageC : coverageB; + oppositeEnd = oppositeStart + (end - start); + float opposite = -coverageSign * edgeDistance(p, oppositeStart, oppositeEnd); + inside = min(inside, opposite); + } if (inside < 0) { - // Acute offset-line miters must not paint beyond the actual ends. - float s0 = (edgeMask & 1u) != 0 ? segmentDistance(p, input.triA, input.triB) : 1e6; - float s1 = (edgeMask & 2u) != 0 ? segmentDistance(p, input.triB, input.triC) : 1e6; - float s2 = (edgeMask & 4u) != 0 ? segmentDistance(p, input.triC, input.triA) : 1e6; - inside = -min(s0, min(s1, s2)); + // Use the visible edge segments for the outward fringe. A clipped + // stroke's original edges may extend beyond the cut. + bool clippedStroke = (edgeFlags & coverageSourceFlag) != 0u; + uint fringeMask = clippedStroke ? edgeMask : coverageMask; + float s0 = (fringeMask & 1u) != 0 ? segmentDistance(p, input.triA, input.triB) : 1e6; + float s1 = (fringeMask & 2u) != 0 ? segmentDistance(p, input.triB, input.triC) : 1e6; + float s2 = (fringeMask & 4u) != 0 ? segmentDistance(p, input.triC, input.triA) : 1e6; + float opposite = strokeQuad && !clippedStroke ? segmentDistance(p, oppositeStart, oppositeEnd) : 1e6; + inside = -min(opposite, min(s0, min(s1, s2))); } - float coverage = edgeMask == 0 ? 1 : saturate(0.5 + inside / pixel); + float coverage = coverageMask == 0 ? 1 : saturate(0.5 + inside / pixel); float4 shade = saturate(input.color); return float4(shade.rgb*coverage*shade.a, shade.a*coverage); } diff --git a/internal/platform/windows/shaders/textFragment.dxbc b/internal/platform/windows/shaders/textFragment.dxbc index d11331f54..eabaace9a 100644 Binary files a/internal/platform/windows/shaders/textFragment.dxbc and b/internal/platform/windows/shaders/textFragment.dxbc differ diff --git a/internal/platform/windows/shaders/textVertex.dxbc b/internal/platform/windows/shaders/textVertex.dxbc index 6e01f9282..9fad70a40 100644 Binary files a/internal/platform/windows/shaders/textVertex.dxbc and b/internal/platform/windows/shaders/textVertex.dxbc differ diff --git a/internal/platform/windows/system_windows.go b/internal/platform/windows/system_windows.go index 7458f5eba..707fec3f5 100644 --- a/internal/platform/windows/system_windows.go +++ b/internal/platform/windows/system_windows.go @@ -1010,12 +1010,17 @@ func dialogOwner() uintptr { } func copyUTF16(destination []uint16, value string) { + if len(destination) == 0 { + return + } encoded := syscall.StringToUTF16(value) - if len(encoded) > len(destination) { - encoded = encoded[:len(destination)] - encoded[len(encoded)-1] = 0 + count := min(len(encoded)-1, len(destination)-1) + // Reserve NUL and never truncate between the two halves of a surrogate pair. + if count > 0 && count < len(encoded)-1 && encoded[count-1] >= 0xd800 && encoded[count-1] <= 0xdbff { + count-- } - copy(destination, encoded) + copy(destination, encoded[:count]) + destination[count] = 0 } func windowsCallError(action string, callErr error) error { diff --git a/internal/platform/windows/text_windows.go b/internal/platform/windows/text_windows.go index 2ea2b96a8..6181a2ac3 100644 --- a/internal/platform/windows/text_windows.go +++ b/internal/platform/windows/text_windows.go @@ -174,7 +174,7 @@ func (services *textServices) chosenWeight(weight float32, main, bold uint32) ui return native } -// nativeFontWeight is the DirectWrite weight of a Viva weight: regular, medium, semibold and +// nativeFontWeight is the DirectWrite weight of a Viva weight: light, regular, medium, semibold and // bold are the faces Segoe UI has. A font without one of them, such as Consolas, which has // regular and bold only, is drawn with the face DirectWrite finds nearest. func nativeFontWeight(weight float32) uint32 { @@ -185,6 +185,8 @@ func nativeFontWeight(weight float32) uint32 { return 600 case weight >= 0.10: return 500 + case weight <= -0.2: + return 300 default: return 400 } diff --git a/internal/platform/windows/text_windows_test.go b/internal/platform/windows/text_windows_test.go index f560ecdcb..5b9911aac 100644 --- a/internal/platform/windows/text_windows_test.go +++ b/internal/platform/windows/text_windows_test.go @@ -5,6 +5,7 @@ import ( "runtime" "testing" + "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/internal/platform" ) @@ -177,3 +178,9 @@ func TestSemiboldIsTheRealSemiboldFace(t *testing.T) { t.Errorf("semibold line is %.3f times as wide as regular, want a real semibold's 1.02 to 1.08", ratio) } } + +func TestLightFontWeight(t *testing.T) { + if got := nativeFontWeight(gfx.WeightLight); got != 300 { + t.Fatalf("light weight = %d, want 300", got) + } +} diff --git a/internal/platform/windows/watermark_windows.go b/internal/platform/windows/watermark_windows.go new file mode 100644 index 000000000..d8cf74232 --- /dev/null +++ b/internal/platform/windows/watermark_windows.go @@ -0,0 +1,342 @@ +package windows + +import ( + "fmt" + "math" + "sync" + "syscall" + "unicode/utf16" + "unsafe" + + "github.com/vivaui/viva/gfx" + "github.com/vivaui/viva/internal/platform" +) + +const ( + wmSetWatermark = 0x8057 // follows wmChangeDecoration + d2dCreateBitmap = 4 + d2dCreateBitmapBrush = 7 + d2dFillRectangle = 17 + watermarkClassName = "VivaWatermark" +) + +var ( + watermarkClass sync.Once + watermarkClassError error + updateWatermarkLayer = user.NewProc("UpdateLayeredWindow") +) + +type watermarkRequest struct { + mu sync.Mutex + handle uintptr + value platform.Watermark + pending bool +} + +func (window *nativeWindow) SetWatermark(value platform.Watermark) error { + if window == nil || window.closed.Load() { + return fmt.Errorf("windows: window is closed") + } + value, err := platform.NormalizeWatermark(value) + if err != nil { + return err + } + request := &window.state.pendingWatermark + request.mu.Lock() + defer request.mu.Unlock() + if request.handle == 0 { + return fmt.Errorf("windows: window is closed") + } + request.value, request.pending = value, true + // PostMessage never waits for the window thread. Teardown retires this handle + // under the same lock, so background setters never read mutable window state. + if ok, _, err := postMessage.Call(request.handle, wmSetWatermark, 0, 0); ok == 0 { + return fmt.Errorf("windows: post watermark: %w", err) + } + return nil +} + +func (state *windowState) applyWatermark() { + request := &state.pendingWatermark + request.mu.Lock() + value, pending := request.value, request.pending + request.pending = false + request.mu.Unlock() + if !pending { + return + } + previous := state.config.Watermark + state.config.Watermark = value + if err := state.syncWatermark(); err != nil { + state.config.Watermark = previous + if restoreErr := state.syncWatermark(); restoreErr != nil { + platform.ReportFault("restore window watermark", restoreErr) + } + platform.ReportFault("window watermark", err) + } +} + +// watermarkOverlay retains the small text tile independently of the client-sized DIB. +// Moving and ordinary frames never rasterize text or refill the DIB. +type watermarkOverlay struct { + window uintptr + rasterizer *directRasterizer + target *directTarget + bitmap, brush uintptr + config platform.Watermark + scale float32 + width, height int + tileWidth, tileHeight int +} + +func watermarkProc(window, kind, first, second uintptr) uintptr { + switch kind { + case wmNCHitTest: + return ^uintptr(0) // HTTRANSPARENT + case 0x0021: + return 3 // WM_MOUSEACTIVATE -> MA_NOACTIVATE + case wmErase: + return 1 + } + result, _, _ := defaultWindowProc.Call(window, kind, first, second) + return result +} + +func (state *windowState) newWatermark() (*watermarkOverlay, error) { + watermarkClass.Do(func() { + class := windowClass{Size: uint32(unsafe.Sizeof(windowClass{})), Procedure: syscall.NewCallback(watermarkProc), Instance: state.application.instance, Name: wide(watermarkClassName)} + if ok, _, err := registerClass.Call(uintptr(unsafe.Pointer(&class))); ok == 0 { + watermarkClassError = fmt.Errorf("windows: register watermark: %w", err) + } + }) + if watermarkClassError != nil { + return nil, watermarkClassError + } + handle, _, err := createWindow.Call(wsExLayered|wsExTransparent|wsExNoActivate|wsExToolWindow, uintptr(unsafe.Pointer(wide(watermarkClassName))), 0, wsPopup, 0, 0, 1, 1, state.window, 0, state.application.instance, 0) + if handle == 0 { + return nil, fmt.Errorf("windows: create watermark: %w", err) + } + return &watermarkOverlay{window: handle}, nil +} + +func (overlay *watermarkOverlay) suspend() { + showWindow.Call(overlay.window, 0) + release(&overlay.brush) + release(&overlay.bitmap) + if overlay.target != nil { + overlay.target.close() + overlay.target = nil + } + overlay.width, overlay.height = 0, 0 +} +func (overlay *watermarkOverlay) close() { + overlay.suspend() + if overlay.rasterizer != nil { + overlay.rasterizer.close() + overlay.rasterizer = nil + } + if overlay.window != 0 { + destroyWindow.Call(overlay.window) + overlay.window = 0 + } +} + +// raiseWatermark is the only stacking entry point. New native child/owned windows +// must call it after changing the native view tree. +func (state *windowState) raiseWatermark() { + if state.watermark != nil && state.watermark.window != 0 { + level := ^uintptr(1) // HWND_NOTOPMOST: match the owner, including demotion. + if style, err := readDecorationStyle(state.window, ^uintptr(19)); err == nil && style&wsExTopmost != 0 { + level = ^uintptr(0) + } + setWindowPosition.Call(state.watermark.window, level, 0, 0, 0, 0, 0x13) // HWND_TOP, NOMOVE|NOSIZE|NOACTIVATE + } +} + +func (state *windowState) syncWatermark() error { + value := state.config.Watermark + if value.Text == "" || value.Color.Alpha <= 0 { + if state.watermark != nil { + state.watermark.close() + state.watermark = nil + } + return nil + } + if !state.ready || state.window == 0 { + return nil + } + if state.watermark == nil { + overlay, err := state.newWatermark() + if err != nil { + return err + } + state.watermark = overlay + } + overlay := state.watermark + if state.minimized || state.hiddenByShow { + overlay.suspend() + return nil + } + var client rect + if ok, _, err := getClientRect.Call(state.window, uintptr(unsafe.Pointer(&client))); ok == 0 { + return err + } + area := platform.WatermarkContentRect(gfx.Size{Width: float32(client.Right), Height: float32(client.Bottom)}, value.Insets, state.scale) + if area.Width <= 0 || area.Height <= 0 { + overlay.suspend() + return nil + } + origin := point{X: int32(area.X), Y: int32(area.Y)} + if ok, _, err := clientToScreen.Call(state.window, uintptr(unsafe.Pointer(&origin))); ok == 0 { + return err + } + width, height := int(area.Width), int(area.Height) + rebuild := watermarkTileChanged(overlay.config, value) || overlay.scale != state.scale || overlay.rasterizer == nil + if overlay.config != value || overlay.scale != state.scale || overlay.width != width || overlay.height != height || overlay.target == nil { + if err := overlay.render(value, state.scale, width, height, rebuild); err != nil { + overlay.suspend() + return err + } + size := point{X: int32(width), Y: int32(height)} + source := point{} + blend := struct{ Operation, Flags, Alpha, Format byte }{Alpha: 255, Format: 1} + if ok, _, err := updateWatermarkLayer.Call(overlay.window, 0, uintptr(unsafe.Pointer(&origin)), uintptr(unsafe.Pointer(&size)), overlay.target.scratch.dc, uintptr(unsafe.Pointer(&source)), 0, uintptr(unsafe.Pointer(&blend)), 2); ok == 0 { + return fmt.Errorf("windows: present watermark: %w", err) + } + overlay.width, overlay.height = width, height + } else { + // Translation only: keep the retained surface and its z-order. + setWindowPosition.Call(overlay.window, 0, uintptr(origin.X), uintptr(origin.Y), 0, 0, 0x15) + } + showWindow.Call(overlay.window, swShowNoActivate) + state.raiseWatermark() + return nil +} + +// Rotation and clipping change composition, not the retained text tile. +func watermarkTileChanged(previous, next platform.Watermark) bool { + return previous.Text != next.Text || previous.FontFamily != next.FontFamily || previous.Color != next.Color || + previous.FontSize != next.FontSize || previous.FontWeight != next.FontWeight || previous.TileWidth != next.TileWidth || previous.TileHeight != next.TileHeight +} + +func watermarkSRGB(value float64) float32 { + if value <= 0.0031308 { + return float32(12.92 * value) + } + return float32(1.055*math.Pow(value, 1/2.4) - 0.055) +} + +func (overlay *watermarkOverlay) render(value platform.Watermark, scale float32, width, height int, rebuild bool) error { + if overlay.rasterizer == nil { + rasterizer, err := newDirectRasterizer() + if err != nil { + return err + } + overlay.rasterizer = rasterizer + } + if rebuild { + if err := overlay.renderTile(value, scale); err != nil { + return err + } + release(&overlay.brush) + release(&overlay.bitmap) + } + if overlay.target == nil { + target, err := newDirectTarget(overlay.rasterizer.factory, d2dAlphaPremultiplied) + if err != nil { + return err + } + overlay.target = target + } + target := overlay.target + surface, err := target.bind(width, height) + if err != nil { + return err + } + clear(surface.Pixels) + if overlay.brush == 0 { + tile := overlay.rasterizer.translucent.scratch + properties := struct { + Format, AlphaMode uint32 + DPIX, DPIY float32 + }{87, d2dAlphaPremultiplied, 96, 96} + packedSize := uintptr(uint32(overlay.tileWidth)) | uintptr(uint32(overlay.tileHeight))<<32 + if err := hresult(comCall5(target.target, d2dCreateBitmap, packedSize, uintptr(unsafe.Pointer(&tile.Pixels[0])), uintptr(tile.Width*4), uintptr(unsafe.Pointer(&properties)), uintptr(unsafe.Pointer(&overlay.bitmap)))); err != nil { + return fmt.Errorf("windows: create watermark tile: %w", err) + } + brushProperties := struct{ X, Y, Interpolation uint32 }{1, 1, 1} // WRAP, WRAP, LINEAR + if err := hresult(comCall4(target.target, d2dCreateBitmapBrush, overlay.bitmap, uintptr(unsafe.Pointer(&brushProperties)), 0, uintptr(unsafe.Pointer(&overlay.brush)))); err != nil { + return err + } + } + angle := float64(value.Angle) * math.Pi / 180 + matrix := d2dMatrix{M11: float32(math.Cos(angle)), M12: float32(math.Sin(angle)), M21: -float32(math.Sin(angle)), M22: float32(math.Cos(angle))} + comCall1(overlay.brush, 5, uintptr(unsafe.Pointer(&matrix))) // ID2D1Brush.SetTransform + bounds := struct{ Left, Top, Right, Bottom float32 }{Right: float32(width), Bottom: float32(height)} + target.begin(d2dColor{}, d2dAntialiasGrayscale) + comCall2(target.target, d2dFillRectangle, uintptr(unsafe.Pointer(&bounds)), overlay.brush) + if err := target.end(); err != nil { + return err + } + overlay.config, overlay.scale = value, scale + return nil +} + +func (overlay *watermarkOverlay) renderTile(value platform.Watermark, scale float32) error { + width, height := platform.WatermarkTileSize(value, scale) + if width <= 0 || height <= 0 { + return fmt.Errorf("windows: invalid watermark tile") + } + rasterizer := overlay.rasterizer + target := rasterizer.translucent + surface, err := target.bind(width, height) + if err != nil { + return err + } + clear(surface.Pixels) + weight := nativeFontWeight(value.FontWeight) + family := value.FontFamily + if family == "" { + family = "Segoe UI" + } + format, err := rasterizer.services.formatWeight(family, value.FontSize*scale, weight, false) + if err != nil { + return err + } + defer release(&format) + units := utf16.Encode([]rune(value.Text)) + if len(units) == 0 { + return fmt.Errorf("windows: watermark text is empty") + } + var layout uintptr + if err := hresult(rasterizer.services.createLayout(rasterizer.services.write, &units[0], uint32(len(units)), format, 1<<20, 1<<20, &layout)); err != nil { + return err + } + defer release(&layout) + var metrics textMetrics + if err := hresult(comCall1(layout, writeGetMetrics, uintptr(unsafe.Pointer(&metrics)))); err != nil { + return err + } + target.begin(d2dColor{R: watermarkSRGB(value.Color.Red), G: watermarkSRGB(value.Color.Green), B: watermarkSRGB(value.Color.Blue), A: float32(value.Color.Alpha)}, d2dAntialiasGrayscale) + target.pushClip(0, width, height) + target.draw((float32(width)-metrics.WidthTrailing)/2-metrics.Left, (float32(height)-metrics.Height)/2-metrics.Top, layout, 0) + target.popClip() + if err := target.end(); err != nil { + return err + } + overlay.tileWidth, overlay.tileHeight = width, height + return nil +} + +// moveWatermark only translates the retained surface. Resize messages are paced +// separately by serviceResize, including left/top-edge resize drags. +func (state *windowState) moveWatermark() { + if state.watermark == nil || state.minimized || state.hiddenByShow { + return + } + insets := state.config.Watermark.Insets + origin := point{X: int32(math.Ceil(float64(insets.Left * state.scale))), Y: int32(math.Ceil(float64(insets.Top * state.scale)))} + if ok, _, _ := clientToScreen.Call(state.window, uintptr(unsafe.Pointer(&origin))); ok != 0 { + setWindowPosition.Call(state.watermark.window, 0, uintptr(origin.X), uintptr(origin.Y), 0, 0, 0x15) + } +} diff --git a/internal/platform/windows/watermark_windows_test.go b/internal/platform/windows/watermark_windows_test.go new file mode 100644 index 000000000..5a4ff67bf --- /dev/null +++ b/internal/platform/windows/watermark_windows_test.go @@ -0,0 +1,124 @@ +package windows + +import ( + "runtime" + "sync" + "testing" + "time" + "unsafe" + + "github.com/vivaui/viva/internal/platform" +) + +// This test needs a Windows desktop. It also reports the bounded resize work +// requested by the native-overlay design; it is not a steady-frame benchmark. +func TestWatermarkWindowTransparencyStackingAndResizeTiming(t *testing.T) { + runtime.LockOSThread() + defer runtime.UnlockOSThread() + err := RunApplication(func(application platform.Application) error { + opened, err := application.OpenWindow(platform.Config{Title: "Watermark native test", Width: 640, Height: 400, ClearColor: platform.Color{Alpha: 1}, Watermark: platform.Watermark{Text: "测试用户 10086", Color: platform.Color{Alpha: .1}, FontWeight: -.4, Angle: -25}}) + if err != nil { + return err + } + defer opened.Close() + state := opened.(*nativeWindow).state + overlay := state.watermark + if overlay == nil || overlay.target == nil { + t.Fatal("initial watermark missing") + } + if watermarkProc(overlay.window, wmNCHitTest, 0, 0) != ^uintptr(0) || watermarkProc(overlay.window, 0x21, 0, 0) != 3 { + t.Fatal("watermark intercepts pointer or activation") + } + // A newly created owned popup may reorder the overlay; restore the invariant. + host := &webHost{state: state} + cover := host.newCover() + if cover == 0 { + t.Fatal("create owned popup") + } + defer destroyWindow.Call(cover) + showWindow.Call(cover, swShowNoActivate) + state.raiseWatermark() + previous, _, _ := user.NewProc("GetWindow").Call(overlay.window, 3) // GW_HWNDPREV + if previous == cover { + t.Fatal("owned popup is above watermark") + } + for _, enabled := range []bool{true, false, true, false} { + if !state.setAlwaysOnTop(enabled) { + t.Fatal("owner topmost change failed") + } + style, err := readDecorationStyle(overlay.window, ^uintptr(19)) + if err != nil || (style&wsExTopmost != 0) != enabled { + t.Fatal("overlay did not follow owner topmost level", enabled, style, err) + } + } + // Concurrent callers only enqueue requests; the window thread applies the latest one. + var jobs sync.WaitGroup + failures := make(chan error, 8) + for range 8 { + jobs.Add(1) + go func() { + defer jobs.Done() + if err := opened.(*nativeWindow).SetWatermark(state.config.Watermark); err != nil { + failures <- err + } + }() + } + jobs.Wait() + close(failures) + for err := range failures { + t.Fatal(err) + } + state.applyWatermark() + retained := overlay.target.scratch + state.moveWatermark() + if overlay.target.scratch != retained { + t.Fatal("translation reallocated surface") + } + if err := overlay.render(state.config.Watermark, 1.5, 320, 200, true); err != nil { + return err + } + for _, size := range []struct{ width, height int }{{1600, 960}, {2560, 1440}} { + start := time.Now() + if err := overlay.render(state.config.Watermark, 1.5, size.width*3/2, size.height*3/2, false); err != nil { + return err + } + destination := point{} + source := point{} + dimensions := point{X: int32(size.width * 3 / 2), Y: int32(size.height * 3 / 2)} + blend := struct{ Operation, Flags, Alpha, Format byte }{Alpha: 255, Format: 1} + if ok, _, err := updateWatermarkLayer.Call(overlay.window, 0, uintptr(unsafe.Pointer(&destination)), uintptr(unsafe.Pointer(&dimensions)), overlay.target.scratch.dc, uintptr(unsafe.Pointer(&source)), 0, uintptr(unsafe.Pointer(&blend)), 2); ok == 0 { + return err + } + t.Logf("resize %dx%d @150%% fill + submit: %v; retained DIB: %d bytes", size.width, size.height, time.Since(start), len(overlay.target.scratch.Pixels)) + } + overlay.suspend() + if overlay.target != nil || overlay.brush != 0 || overlay.bitmap != 0 { + t.Fatal("hidden overlay retained client-sized resources") + } + return nil + }) + if err != nil { + t.Fatal(err) + } +} + +func TestWatermarkSetterRejectsRetiredHandle(t *testing.T) { + window := &nativeWindow{state: &windowState{}} + if err := window.SetWatermark(platform.Watermark{}); err == nil { + t.Fatal("retired native handle accepted an update") + } +} + +func TestWatermarkCompositionDoesNotRebuildTextTile(t *testing.T) { + original := platform.Watermark{Text: "DRAFT", FontSize: 12, TileWidth: 240, TileHeight: 180} + changed := original + changed.Angle = -25 + changed.Insets.Left = 40 + if watermarkTileChanged(original, changed) { + t.Fatal("composition-only update rebuilt text") + } + changed.FontFamily = "Arial" + if !watermarkTileChanged(original, changed) { + t.Fatal("font family update reused stale text") + } +} diff --git a/internal/platform/windows/web_windows.go b/internal/platform/windows/web_windows.go index 41b4202f2..58a755cc5 100644 --- a/internal/platform/windows/web_windows.go +++ b/internal/platform/windows/web_windows.go @@ -930,6 +930,7 @@ func (w *webHost) layoutCovers(page *windowsWeb, view platform.NativeView) { if sameRects(page.coverSet, w.cuts) { return } + defer w.state.raiseWatermark() page.coverSet = append(page.coverSet[:0], w.cuts...) origin := point{} clientToScreen.Call(w.state.window, uintptr(unsafe.Pointer(&origin))) @@ -969,6 +970,7 @@ func (w *webHost) newCover() uintptr { 0, 0, 1, 1, state.window, 0, state.application.instance, 0) if window != 0 { setLayered.Call(window, 0, 1, 2) + state.raiseWatermark() } return window } diff --git a/internal/platform/windows/wheel_windows.go b/internal/platform/windows/wheel_windows.go index c84a720f6..148b61dc3 100644 --- a/internal/platform/windows/wheel_windows.go +++ b/internal/platform/windows/wheel_windows.go @@ -43,7 +43,8 @@ func (state *windowState) wheelEvent(horizontal bool, first, second uintptr) pla if horizontal { units, extent = state.wheel.chars, state.pageExtent(true) } - pixels, precise := platform.WheelPixels(int(int16(first>>16)), units, extent) + wheelDelta := int16(first >> 16) + pixels, precise := platform.WheelPixels(int(wheelDelta), units, extent) event := platform.ScrollEvent{ Modifiers: modifiers(), X: float32(position.X) / state.scale, Y: float32(position.Y) / state.scale, Precise: precise, @@ -53,6 +54,16 @@ func (state *windowState) wheelEvent(horizontal bool, first, second uintptr) pla } else { event.DeltaY = -pixels } + if units == platform.WheelPageScroll { + // The system asks for whole screens, and extent is only the window's: the + // region the pointer is over moves Pages of its own page. A notch away + // from the user is up, as a negative DeltaY. + pages := float32(wheelDelta) / platform.WheelNotch + if !horizontal { + pages = -pages + } + event.Pages = pages + } return event } diff --git a/internal/platform/windows/window_windows.go b/internal/platform/windows/window_windows.go index 90b56b0ee..721e30f12 100644 --- a/internal/platform/windows/window_windows.go +++ b/internal/platform/windows/window_windows.go @@ -79,6 +79,8 @@ const ( type windowState struct { // pendingTitle is the title SetTitle asked for, applied on the window thread. pendingTitle titleRequest + pendingWatermark watermarkRequest + watermark *watermarkOverlay pendingIcon iconRequest decoration windowDecoration fullscreen atomic.Bool @@ -321,6 +323,11 @@ func RunApplication(start platform.ApplicationStart) error { } func (application *windowsApplication) OpenWindow(config platform.Config) (platform.Window, error) { + watermark, err := platform.NormalizeWatermark(config.Watermark) + if err != nil { + return nil, err + } + config.Watermark = watermark if err := validateTextInput(config.TextInput); err != nil { return nil, err } @@ -474,6 +481,11 @@ func (application *windowsApplication) OpenWindow(config platform.Config) (platf postMessage.Call(state.window, wmWebReady, 0, 0) } } + state.pendingWatermark.handle = state.window + if err := state.syncWatermark(); err != nil { + destroyWindow.Call(state.window) + return nil, err + } state.testEvents() return &nativeWindow{state: state}, nil } @@ -530,6 +542,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { case wmFullscreen: state.setFullscreen(first != 0) return 0 + case wmSetWatermark: + state.applyWatermark() + return 0 case wmChangeDecoration: state.applyDecoration() return 0 @@ -819,6 +834,7 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { } return 0 case wmMove: + state.moveWatermark() state.refreshResizeTimer() state.reportFrame() if state.web != nil { @@ -831,12 +847,18 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { // own state, which wmSize follows. if second == 0 { state.hiddenByShow = first == 0 + if err := state.syncWatermark(); err != nil { + platform.ReportFault("window watermark", err) + } state.reportVisibility() } case wmSize: if first == 1 { // SIZE_MINIMIZED if !state.minimized { state.minimized = true + if state.watermark != nil { + state.watermark.suspend() + } if state.ready && state.config.OnMinimize != nil { state.config.OnMinimize(true) } @@ -912,6 +934,9 @@ func windowProc(window, kind, first, second uintptr) (result uintptr) { frame, err := state.config.OnResize(state.logicalSize(int(client.Right), int(client.Bottom))) state.frame(frame, err) } + if err := state.syncWatermark(); err != nil { + platform.ReportFault("window watermark", err) + } invalidateRect.Call(window, 0, 0) return 0 case wmLeftDown, wmLeftUp, wmRightDown, wmRightUp, wmMiddleDown, wmMiddleUp, wmXButtonDown, wmXButtonUp, wmMouseMove: @@ -1287,6 +1312,11 @@ func (state *windowState) presentClientSize(width, height int) { } func (state *windowState) layoutClientSize(width, height int) bool { + defer func() { + if err := state.syncWatermark(); err != nil { + platform.ReportFault("window watermark", err) + } + }() if state.config.OnResize != nil { state.resizeEvents++ frame, err := state.config.OnResize(state.logicalSize(width, height)) @@ -1383,6 +1413,14 @@ func (state *windowState) frameWithTextAndCancel(frame platform.Frame, err error // message loop running with no window to show, and the single-instance claim held // by a process nobody can see. func (state *windowState) destroyed(window uintptr) { + request := &state.pendingWatermark + request.mu.Lock() + request.handle, request.pending = 0, false + request.mu.Unlock() + if state.watermark != nil { + state.watermark.close() + state.watermark = nil + } // Native teardown can reenter the dispatcher; retire text callbacks first. state.ready = false if request := state.decoration.close(); request != nil { diff --git a/internal/raster/raster_test.go b/internal/raster/raster_test.go index b1eb3e952..26b3468ce 100644 --- a/internal/raster/raster_test.go +++ b/internal/raster/raster_test.go @@ -169,6 +169,37 @@ func TestTrianglesSharingAnEdgeMeetWithoutGapOrOverlap(t *testing.T) { } } +func TestThinStrokeHasConstantCoverageAcrossItsTriangleDiagonal(t *testing.T) { + const scale = 1.25 + leftTop := scene.Point{X: 2.25, Y: 4.25} + rightTop := scene.Point{X: 15.5, Y: 4.25} + rightBottom := scene.Point{X: 15.5, Y: 5} + leftBottom := scene.Point{X: 2.25, Y: 5} + for _, reverse := range []bool{false, true} { + a, b, c, d := leftTop, rightTop, rightBottom, leftBottom + if reverse { + a, b, c, d = c, d, a, b + } + canvas := NewCanvas(24, 12) + var r Rasterizer + r.Draw(canvas, Params{Scale: scale}, []render.Rectangle{ + {Kind: scene.KindTriangle, Points: [3]scene.Point{a, b, d}, Color: white, EdgeMask: scene.StrokeQuadEdgeMask | 0b101}, + {Kind: scene.KindTriangle, Points: [3]scene.Point{d, b, c}, Color: white, EdgeMask: scene.StrokeQuadEdgeMask | 0b110}, + }, nil) + // The stroke covers device rows 5 and 6 at 68.75% and 25%, respectively. + // The stroke has constant device width even where its internal diagonal + // changes which triangle owns a pixel. + for x := 4; x <= 17; x++ { + if got := at(canvas, x, 5)[3]; got != 175 { + t.Fatalf("reversed=%t: pixel (%d,5) alpha=%d, want 175", reverse, x, got) + } + if got := at(canvas, x, 6)[3]; got != 64 { + t.Fatalf("reversed=%t: pixel (%d,6) alpha=%d, want 64", reverse, x, got) + } + } + } +} + func TestShadowIsDarkestNearItsEdgeAndHasTheCasterCutOut(t *testing.T) { c := NewCanvas(80, 60) var r Rasterizer diff --git a/internal/raster/shapes.go b/internal/raster/shapes.go index 56c8eb6a6..4c35ffd7e 100644 --- a/internal/raster/shapes.go +++ b/internal/raster/shapes.go @@ -198,7 +198,7 @@ func drawTriangle(c *Canvas, area render.Scissor, rc *render.Rectangle, scale fl if !(finite(ax) && finite(ay) && finite(bx) && finite(by) && finite(cx) && finite(cy) && finite(area2) && finite(longest2)) || abs32(area2) < 1e-8 { return } - edgeMask := uint32(rc.EdgeMask) + edgeMask := uint32(rc.EdgeMask & 7) bounded := edgeMask != 7 || abs32(area2) < longest2*0.125 ps := 1 / scale lowX := min(ax, min(bx, cx)) - 0.5*ps @@ -214,6 +214,34 @@ func drawTriangle(c *Canvas, area render.Scissor, rc *render.Rectangle, scale fl if cross2(bx-ax, by-ay, cx-ax, cy-ay) > 0 { orientation = 1 } + coveragePoints, coverageFlags := pts, rc.EdgeMask + coverageOrientation := orientation + source, hasSource := rc.StrokeCoverage() + if hasSource { + coveragePoints, coverageFlags = source.Points, source.EdgeMask + a, b, c := coveragePoints[0], coveragePoints[1], coveragePoints[2] + if cross2(b.X-a.X, b.Y-a.Y, c.X-a.X, c.Y-a.Y) > 0 { + coverageOrientation = 1 + } else { + coverageOrientation = -1 + } + } + strokeQuad := coverageFlags&scene.StrokeQuadEdgeMask != 0 + coverageEdges := coverageFlags & 7 + fa, fb, fc := coveragePoints[0], coveragePoints[1], coveragePoints[2] + var strokeWidth, oppositeX, oppositeY, oppositeEndX, oppositeEndY float32 + firstHalf := coverageEdges&1 != 0 + if strokeQuad { + if firstHalf { + strokeWidth = coverageOrientation * edgeDistance(fc.X, fc.Y, fa.X, fa.Y, fb.X, fb.Y) + oppositeX, oppositeY = fc.X, fc.Y + oppositeEndX, oppositeEndY = fc.X+(fb.X-fa.X), fc.Y+(fb.Y-fa.Y) + } else { + strokeWidth = coverageOrientation * edgeDistance(fb.X, fb.Y, fc.X, fc.Y, fa.X, fa.Y) + oppositeX, oppositeY = fb.X, fb.Y + oppositeEndX, oppositeEndY = fb.X+(fa.X-fc.X), fb.Y+(fa.Y-fc.Y) + } + } px := [3][2]float32{{ax, ay}, {bx, by}, {cx, cy}} for y := box.Top; y < box.Bottom; y++ { dy := float32(y) + 0.5 @@ -249,18 +277,29 @@ func drawTriangle(c *Canvas, area render.Scissor, rc *render.Rectangle, scale fl } const far = 1e6 d0, d1, d2 := float32(far), float32(far), float32(far) - if edgeMask&1 != 0 { - d0 = orientation * edgeDistance(ppx, py, ax, ay, bx, by) + if coverageEdges&1 != 0 { + d0 = coverageOrientation * edgeDistance(ppx, py, fa.X, fa.Y, fb.X, fb.Y) } - if edgeMask&2 != 0 { - d1 = orientation * edgeDistance(ppx, py, bx, by, cx, cy) + if coverageEdges&2 != 0 { + d1 = coverageOrientation * edgeDistance(ppx, py, fb.X, fb.Y, fc.X, fc.Y) } - if edgeMask&4 != 0 { - d2 = orientation * edgeDistance(ppx, py, cx, cy, ax, ay) + if coverageEdges&4 != 0 { + d2 = coverageOrientation * edgeDistance(ppx, py, fc.X, fc.Y, fa.X, fa.Y) } inside := min(d0, min(d1, d2)) + if strokeQuad { + // The internal diagonal determines ownership only. The opposite + // side can be closer to a pixel center even in this half. + longEdge := d2 + if firstHalf { + longEdge = d0 + } + inside = min(inside, strokeWidth-longEdge) + } if inside < 0 { - // An acute offset line must not paint past the actual ends. + // The clipped mesh still supplies the visible line segments + // for outward feathering. The source's longer segments could + // extend a fringe past the end of the cut. s0, s1, s2 := float32(far), float32(far), float32(far) if edgeMask&1 != 0 { s0 = segmentDistance(ppx, py, ax, ay, bx, by) @@ -271,10 +310,14 @@ func drawTriangle(c *Canvas, area render.Scissor, rc *render.Rectangle, scale fl if edgeMask&4 != 0 { s2 = segmentDistance(ppx, py, cx, cy, ax, ay) } - inside = -min(s0, min(s1, s2)) + outside := min(s0, min(s1, s2)) + if strokeQuad && !hasSource { + outside = min(outside, segmentDistance(ppx, py, oppositeX, oppositeY, oppositeEndX, oppositeEndY)) + } + inside = -outside } coverage := float32(1) - if edgeMask != 0 { + if coverageEdges != 0 { coverage = clamp01(0.5 + inside/ps) } // The color at this point of a shaded face (flat when the three are equal). diff --git a/internal/reloadwire/codec.go b/internal/reloadwire/codec.go index cc6dc4bb8..ad42907a4 100644 --- a/internal/reloadwire/codec.go +++ b/internal/reloadwire/codec.go @@ -9,7 +9,7 @@ import ( ) const ( - ProtocolVersion = 30 + ProtocolVersion = 31 MaxFrameBytes = 32 << 20 MaxStateBytes = 8 << 20 maxItems = 200_000 @@ -403,6 +403,7 @@ func encodeScrollEvent(value gfx.ScrollEvent) []byte { result.f32(value.Y) result.f32(value.DeltaX) result.f32(value.DeltaY) + result.f32(value.Pages) result.f32(value.Viewport.Width) result.f32(value.Viewport.Height) result.id(value.Target) @@ -414,7 +415,7 @@ func decodeScrollEvent(data []byte) (gfx.ScrollEvent, error) { value := decoder{data: data} result := gfx.ScrollEvent{ Modifiers: gfx.Modifiers(value.u8()), X: value.f32(), Y: value.f32(), - DeltaX: value.f32(), DeltaY: value.f32(), Viewport: gfx.Size{Width: value.f32(), Height: value.f32()}, Target: value.id(), Precise: value.bool(), + DeltaX: value.f32(), DeltaY: value.f32(), Pages: value.f32(), Viewport: gfx.Size{Width: value.f32(), Height: value.f32()}, Target: value.id(), Precise: value.bool(), } if err := value.finish(); err != nil { return gfx.ScrollEvent{}, err @@ -495,6 +496,14 @@ func encodeCanvas(value CanvasSnapshot) ([]byte, error) { result.bool(triangle.Shaded) result.u16(triangle.Layer) result.u8(triangle.EdgeMask) + result.bool(triangle.Coverage != nil) + if coverage := triangle.Coverage; coverage != nil { + for _, point := range coverage.Points { + result.f32(point.X) + result.f32(point.Y) + } + result.u8(coverage.EdgeMask) + } encodeRect(&result, triangle.ClipOf) result.bool(triangle.HasClip) result.u32(triangle.Order) @@ -634,6 +643,14 @@ func decodeCanvas(data []byte) (CanvasSnapshot, error) { triangle.Shaded = value.bool() triangle.Layer = value.u16() triangle.EdgeMask = value.u8() + if value.bool() { + coverage := new(gfx.StrokeCoverage) + for point := range coverage.Points { + coverage.Points[point] = gfx.Point{X: value.f32(), Y: value.f32()} + } + coverage.EdgeMask = value.u8() + triangle.Coverage = coverage + } triangle.ClipOf, triangle.HasClip = decodeRect(&value), value.bool() triangle.Order = value.u32() result.Triangles[index] = triangle diff --git a/internal/reloadwire/reloadwire_test.go b/internal/reloadwire/reloadwire_test.go index cf7f26bc3..d54a86108 100644 --- a/internal/reloadwire/reloadwire_test.go +++ b/internal/reloadwire/reloadwire_test.go @@ -21,6 +21,12 @@ func TestCanvasCodecPreservesRetainedOutput(t *testing.T) { Points: [3]gfx.Point{{X: 0, Y: 0}, {X: 12, Y: 0}, {X: 0, Y: 9}}, Color: gfx.Color{Red: 1, Alpha: 0.5}, EdgeMask: 1, }) + canvas.DrawIconTransformed(gfx.Icon{ + ViewBox: 24, Stroke: 1, Cap: gfx.CapButt, + Commands: []gfx.PathCommand{gfx.MoveTo(12.25, 2), gfx.LineTo(12.25, 22)}, + }, gfx.Rect{Width: 24, Height: 24}, gfx.Color{Red: 1, Alpha: 1}, gfx.IconTransform{ + Clip: &gfx.IconClip{Bounds: gfx.Rect{Y: 4, Width: 24, Height: 16}}, + }) canvas.Elevate(gfx.Rect{X: 1, Y: 2, Width: 80, Height: 30}, 6, gfx.ShadowMD) canvas.Rounded(gfx.Rect{X: 1, Y: 2, Width: 80, Height: 30}, 6, gfx.Color{Red: 0.2, Green: 0.3, Blue: 0.4, Alpha: 1}) canvas.AppendTriangle(gfx.Triangle{ diff --git a/internal/render/store.go b/internal/render/store.go index b9cfa11ae..c850d78c9 100644 --- a/internal/render/store.go +++ b/internal/render/store.go @@ -17,9 +17,12 @@ type Rectangle struct { Points [3]scene.Point Layer uint16 // EdgeMask selects the triangle edges that receive boundary feathering. - EdgeMask uint8 + // scene.StrokeQuadEdgeMask also enables coverage from the opposite edge. + EdgeMask uint8 + hasStrokeCoverage bool // Shade, when On, gives the triangle the colors of its second and third - // corner; Color is the first's. + // corner; Color is the first's. Flat clipped strokes reuse the same + // slots for coverage coordinates, keeping the instance pointer-free. Shade scene.Shade // Shadow places and blurs a KindShadow instance: Bounds and Radius are the // rectangle that casts it. @@ -32,6 +35,28 @@ type Rectangle struct { Clip scene.Rect } +// SetStrokeCoverage stores a flat clipped stroke's original feathering edges. +func (rectangle *Rectangle) SetStrokeCoverage(coverage scene.StrokeCoverage) { + a, b, c := coverage.Points[0], coverage.Points[1], coverage.Points[2] + rectangle.hasStrokeCoverage = true + rectangle.Shade.Colors = [2]scene.Color{ + {Red: a.X, Green: a.Y, Blue: b.X, Alpha: b.Y}, + {Red: c.X, Green: c.Y, Blue: float32(coverage.EdgeMask)}, + } +} + +// StrokeCoverage returns the original feathering edges of a flat clipped stroke. +func (rectangle Rectangle) StrokeCoverage() (scene.StrokeCoverage, bool) { + if !rectangle.hasStrokeCoverage { + return scene.StrokeCoverage{}, false + } + ab, c := rectangle.Shade.Colors[0], rectangle.Shade.Colors[1] + return scene.StrokeCoverage{ + Points: [3]scene.Point{{X: ab.Red, Y: ab.Green}, {X: ab.Blue, Y: ab.Alpha}, {X: c.Red, Y: c.Green}}, + EdgeMask: uint8(c.Blue), + }, true +} + // VertexColors is the color at each corner of a triangle: all Color for a flat // one, so a renderer that interpolates colors across the face needs no special // case for either. @@ -421,7 +446,7 @@ func rectangleOf(change scene.Change) Rectangle { if change.Shape != nil { shape = *change.Shape } - return Rectangle{ + rectangle := Rectangle{ ID: change.ID, Kind: change.Kind, Bounds: change.Bounds, @@ -432,6 +457,10 @@ func rectangleOf(change scene.Change) Rectangle { Shade: shape.Shade, Shadow: shape.Shadow, } + if shape.Coverage != nil { + rectangle.SetStrokeCoverage(*shape.Coverage) + } + return rectangle } // reindexFrom repoints every slot whose instance is at or after index, @@ -495,10 +524,14 @@ func (store *Store) upsert(change scene.Change) (bool, int, error) { rectangle.Bounds = change.Bounds rectangle.Color = change.Color rectangle.Radius = change.Radius + rectangle.hasStrokeCoverage = false if change.Shape != nil { rectangle.Points = change.Shape.Points rectangle.Shade = change.Shape.Shade rectangle.Shadow = change.Shape.Shadow + if change.Shape.Coverage != nil { + rectangle.SetStrokeCoverage(*change.Shape.Coverage) + } } rectangle.EdgeMask = change.EdgeMask } diff --git a/internal/render/store_test.go b/internal/render/store_test.go index efeec5411..d012e4a6d 100644 --- a/internal/render/store_test.go +++ b/internal/render/store_test.go @@ -214,7 +214,7 @@ func TestStoreInsertsInTheMiddleAlongsideAChangeToItsSuccessor(t *testing.T) { } graph.SetRectangle(second, scene.Rect{X: 20}, scene.Color{Red: 1}) // queued before the insert - inserted, _ := graph.InsertTriangle(graph.Root(), first, [3]scene.Point{{X: 1}, {X: 2}, {X: 3}}, scene.Color{Green: 1}, 5, scene.Shade{}) + inserted, _ := graph.InsertTriangle(graph.Root(), first, [3]scene.Point{{X: 1}, {X: 2}, {X: 3}}, scene.Color{Green: 1}, 5, scene.Shade{}, nil) update, err := store.Apply(graph.DrainChanges(nil)) if err != nil { t.Fatal(err) @@ -248,7 +248,13 @@ func TestStoreKeepsPlaceWhenAShapeChangesKind(t *testing.T) { var store Store store.Apply(graph.DrainChanges(nil)) - graph.SetTriangle(flip, [3]scene.Point{{X: 5}, {X: 6}, {X: 7}}, scene.Color{Blue: 1}, 3, scene.Shade{}) + points := [3]scene.Point{{X: 5}, {X: 6}, {X: 7}} + color := scene.Color{Blue: 1} + coverage := scene.StrokeCoverage{ + Points: [3]scene.Point{{X: 5}, {X: 5, Y: 10}, {X: 7}}, + EdgeMask: scene.StrokeQuadEdgeMask | 1, + } + graph.SetTriangle(flip, points, color, 3, scene.Shade{}, &coverage) update, err := store.Apply(graph.DrainChanges(nil)) if err != nil { t.Fatal(err) @@ -256,14 +262,30 @@ func TestStoreKeepsPlaceWhenAShapeChangesKind(t *testing.T) { if update != (Update{First: 1, Count: 1}) { t.Fatalf("kind change update = %+v", update) } - if got := store.Rectangles()[1]; got.ID != flip || got.Kind != scene.KindTriangle || got.Points[1].X != 6 || got.Bounds != (scene.Rect{}) || got.EdgeMask != 3 { + if got := store.Rectangles()[1]; got.ID != flip || got.Kind != scene.KindTriangle || got.Points != points || got.Bounds != (scene.Rect{}) || + got.EdgeMask != 3 { t.Fatalf("flipped shape = %+v", got) } + if got, ok := store.Rectangles()[1].StrokeCoverage(); !ok || got != coverage { + t.Fatalf("retained coverage = %v, want %+v", got, coverage) + } + updatedCoverage := coverage + if graph.SetTriangle(flip, points, color, 3, scene.Shade{}, &updatedCoverage) { + t.Fatal("identical coverage queued an update") + } + updatedCoverage.Points[1].Y++ + graph.SetTriangle(flip, points, color, 3, scene.Shade{}, &updatedCoverage) + if update, err := store.Apply(graph.DrainChanges(nil)); err != nil || update != (Update{First: 1, Count: 1}) { + t.Fatalf("coverage update = %+v, error = %v", update, err) + } + if got, ok := store.Rectangles()[1].StrokeCoverage(); !ok || got != updatedCoverage { + t.Fatalf("retained coverage = %v, want %+v", got, updatedCoverage) + } graph.SetRoundedRectangle(flip, scene.Rect{X: 8}, scene.Color{}, 3) if _, err := store.Apply(graph.DrainChanges(nil)); err != nil { t.Fatal(err) } - if got := store.Rectangles()[1]; got.Kind != scene.KindRectangle || got.Bounds.X != 8 || got.Radius != 3 { + if got := store.Rectangles()[1]; got.Kind != scene.KindRectangle || got.Bounds.X != 8 || got.Radius != 3 || got.hasStrokeCoverage { t.Fatalf("flipped back = %+v", got) } } diff --git a/internal/render/validate.go b/internal/render/validate.go index 008df193b..b1bc0dc82 100644 --- a/internal/render/validate.go +++ b/internal/render/validate.go @@ -33,14 +33,40 @@ func ValidateRectangles(rectangles []Rectangle) error { return fmt.Errorf("render: triangle %d point %d is non-finite", index, pointIndex) } } - if rectangle.EdgeMask > 7 { + if !validTriangleEdgeMask(rectangle.EdgeMask) { return fmt.Errorf("render: triangle %d has invalid edge mask %d", index, rectangle.EdgeMask) } + if source, ok := rectangle.StrokeCoverage(); ok { + if rectangle.Shade.On || rectangle.EdgeMask > 7 || + source.EdgeMask&scene.StrokeQuadEdgeMask == 0 || !validTriangleEdgeMask(source.EdgeMask) { + return fmt.Errorf("render: triangle %d has invalid stroke coverage", index) + } + for pointIndex, point := range source.Points { + if !finiteFloat(point.X) || !finiteFloat(point.Y) { + return fmt.Errorf("render: triangle %d stroke coverage point %d is non-finite", index, pointIndex) + } + } + } } } return nil } +func validTriangleEdgeMask(mask uint8) bool { + if mask <= 7 { + return true + } + // The first half has long edge 0→1 and an optional start cap 2→0. + // The second has long edge 2→0 and an optional end cap 1→2. + switch mask { + case scene.StrokeQuadEdgeMask | 0b001, scene.StrokeQuadEdgeMask | 0b101, + scene.StrokeQuadEdgeMask | 0b100, scene.StrokeQuadEdgeMask | 0b110: + return true + default: + return false + } +} + func finiteFloat(value float32) bool { return !math.IsNaN(float64(value)) && !math.IsInf(float64(value), 0) } diff --git a/internal/scene/scene.go b/internal/scene/scene.go index 5d7e451ea..324100a4d 100644 --- a/internal/scene/scene.go +++ b/internal/scene/scene.go @@ -46,6 +46,19 @@ type Point struct { Y float32 } +// StrokeQuadEdgeMask marks a triangle as one half of a parallelogram stroke. +// Its long edge is 0→1 when bit 0 is set, or 2→0 otherwise. The opposite edge +// is parallel and passes through the remaining point. Both contribute to +// coverage even though the diagonal gives each pixel to just one triangle. +const StrokeQuadEdgeMask uint8 = 1 << 3 + +// StrokeCoverage is the original half of a stroke quad after clipping has +// divided it into triangles with their own geometry and edge masks. +type StrokeCoverage struct { + Points [3]Point + EdgeMask uint8 +} + // Shade makes a triangle vary from its Color at Points[0] to Colors[0] at // Points[1] and Colors[1] at Points[2], linearly across its face. The zero Shade // leaves the triangle one flat color. @@ -81,9 +94,10 @@ func abs32(value float32) float32 { // Shape is the geometry only a triangle or a shadow carries. Rectangle // changes leave Change.Shape nil, so the common change is small. type Shape struct { - Points [3]Point - Shade Shade - Shadow Shadow + Points [3]Point + Shade Shade + Shadow Shadow + Coverage *StrokeCoverage } // Change is one renderer-facing incremental scene update. @@ -116,6 +130,7 @@ type node struct { edgeMask uint8 shade Shade shadow Shadow + coverage *StrokeCoverage generation uint32 kind Kind alive bool @@ -165,7 +180,7 @@ func (scene *Scene) Root() ID { // AddGroup creates a retained group below parent. func (scene *Scene) AddGroup(parent ID) (ID, bool) { - return scene.add(parent, KindGroup, Rect{}, Color{}, 0, [3]Point{}, 0, Shade{}, Shadow{}) + return scene.add(parent, KindGroup, Rect{}, Color{}, 0, [3]Point{}, 0, Shade{}, Shadow{}, nil) } // AddRectangle creates a retained rectangle below parent. @@ -175,44 +190,44 @@ func (scene *Scene) AddRectangle(parent ID, bounds Rect, color Color) (ID, bool) // AddRoundedRectangle creates a retained rounded rectangle below parent. func (scene *Scene) AddRoundedRectangle(parent ID, bounds Rect, color Color, radius float32) (ID, bool) { - return scene.add(parent, KindRectangle, bounds, color, radius, [3]Point{}, 0, Shade{}, Shadow{}) + return scene.add(parent, KindRectangle, bounds, color, radius, [3]Point{}, 0, Shade{}, Shadow{}, nil) } // AddTriangle creates one retained vector-mesh triangle below parent. -func (scene *Scene) AddTriangle(parent ID, points [3]Point, color Color, edgeMask uint8, shade Shade) (ID, bool) { - return scene.add(parent, KindTriangle, Rect{}, color, 0, points, edgeMask, shade, Shadow{}) +func (scene *Scene) AddTriangle(parent ID, points [3]Point, color Color, edgeMask uint8, shade Shade, coverage *StrokeCoverage) (ID, bool) { + return scene.add(parent, KindTriangle, Rect{}, color, 0, points, edgeMask, shade, Shadow{}, coverage) } -func (scene *Scene) add(parent ID, kind Kind, bounds Rect, color Color, radius float32, points [3]Point, edgeMask uint8, shade Shade, shadow Shadow) (ID, bool) { +func (scene *Scene) add(parent ID, kind Kind, bounds Rect, color Color, radius float32, points [3]Point, edgeMask uint8, shade Shade, shadow Shadow, coverage *StrokeCoverage) (ID, bool) { parentNode, ok := scene.liveNode(parent) if !ok { return 0, false } - return scene.insert(parent, parentNode.lastChild, kind, bounds, color, radius, points, edgeMask, shade, shadow) + return scene.insert(parent, parentNode.lastChild, kind, bounds, color, radius, points, edgeMask, shade, shadow, coverage) } // InsertRoundedRectangle creates a rounded rectangle below parent, right after // the child previous (the first child when previous is zero), so a shape can // appear in the middle of the paint order without disturbing its neighbours. func (scene *Scene) InsertRoundedRectangle(parent, previous ID, bounds Rect, color Color, radius float32) (ID, bool) { - return scene.insert(parent, previous, KindRectangle, bounds, color, radius, [3]Point{}, 0, Shade{}, Shadow{}) + return scene.insert(parent, previous, KindRectangle, bounds, color, radius, [3]Point{}, 0, Shade{}, Shadow{}, nil) } // InsertShadow creates the soft shadow of a rounded rectangle below parent, right // after the child previous (the first child when previous is zero). func (scene *Scene) InsertShadow(parent, previous ID, bounds Rect, color Color, radius float32, shadow Shadow) (ID, bool) { - return scene.insert(parent, previous, KindShadow, bounds, color, radius, [3]Point{}, 0, Shade{}, shadow) + return scene.insert(parent, previous, KindShadow, bounds, color, radius, [3]Point{}, 0, Shade{}, shadow, nil) } // InsertTriangle creates a triangle below parent, right after the child // previous (the first child when previous is zero). -func (scene *Scene) InsertTriangle(parent, previous ID, points [3]Point, color Color, edgeMask uint8, shade Shade) (ID, bool) { - return scene.insert(parent, previous, KindTriangle, Rect{}, color, 0, points, edgeMask, shade, Shadow{}) +func (scene *Scene) InsertTriangle(parent, previous ID, points [3]Point, color Color, edgeMask uint8, shade Shade, coverage *StrokeCoverage) (ID, bool) { + return scene.insert(parent, previous, KindTriangle, Rect{}, color, 0, points, edgeMask, shade, Shadow{}, coverage) } // insert links a new child of parent after previous. A previous that is not a // child of parent is rejected. -func (scene *Scene) insert(parent, previous ID, kind Kind, bounds Rect, color Color, radius float32, points [3]Point, edgeMask uint8, shade Shade, shadow Shadow) (ID, bool) { +func (scene *Scene) insert(parent, previous ID, kind Kind, bounds Rect, color Color, radius float32, points [3]Point, edgeMask uint8, shade Shade, shadow Shadow, coverage *StrokeCoverage) (ID, bool) { parentNode, ok := scene.liveNode(parent) if !ok || parentNode.kind != KindGroup { return 0, false @@ -237,6 +252,7 @@ func (scene *Scene) insert(parent, previous ID, kind Kind, bounds Rect, color Co child.edgeMask = edgeMask child.shade = shade child.shadow = shadow + child.coverage = coverage id := makeID(index, child.generation) child.previous = previous @@ -282,6 +298,7 @@ func (scene *Scene) SetRoundedRectangle(id ID, bounds Rect, color Color, radius current.edgeMask = 0 current.shade = Shade{} current.shadow = Shadow{} + current.coverage = nil scene.markDirty(id, current) return true } @@ -304,18 +321,20 @@ func (scene *Scene) SetShadow(id ID, bounds Rect, color Color, radius float32, s current.edgeMask = 0 current.shade = Shade{} current.shadow = shadow + current.coverage = nil scene.markDirty(id, current) return true } // SetTriangle updates one retained vector-mesh triangle. A rectangle becomes a // triangle in place and keeps its position in paint order. -func (scene *Scene) SetTriangle(id ID, points [3]Point, color Color, edgeMask uint8, shade Shade) bool { +func (scene *Scene) SetTriangle(id ID, points [3]Point, color Color, edgeMask uint8, shade Shade, coverage *StrokeCoverage) bool { current, ok := scene.liveNode(id) if !ok || current.kind == KindGroup { return false } - if current.kind == KindTriangle && current.points == points && current.color == color && current.edgeMask == edgeMask && current.shade == shade { + if current.kind == KindTriangle && current.points == points && current.color == color && current.edgeMask == edgeMask && + current.shade == shade && (current.coverage == coverage || current.coverage != nil && coverage != nil && *current.coverage == *coverage) { return false } current.kind = KindTriangle @@ -323,6 +342,7 @@ func (scene *Scene) SetTriangle(id ID, points [3]Point, color Color, edgeMask ui current.color = color current.edgeMask = edgeMask current.shade = shade + current.coverage = coverage current.bounds = Rect{} current.radius = 0 current.shadow = Shadow{} @@ -420,7 +440,7 @@ func (scene *Scene) DrainChanges(destination []Change) []Change { var shape *Shape if current.kind == KindTriangle || current.kind == KindShadow { scene.shapeScratch = append(scene.shapeScratch, Shape{ - Points: current.points, Shade: current.shade, Shadow: current.shadow, + Points: current.points, Shade: current.shade, Shadow: current.shadow, Coverage: current.coverage, }) shape = &scene.shapeScratch[len(scene.shapeScratch)-1] } diff --git a/internal/scene/scene_test.go b/internal/scene/scene_test.go index 3b171d8e7..9706ac29d 100644 --- a/internal/scene/scene_test.go +++ b/internal/scene/scene_test.go @@ -186,7 +186,7 @@ func TestSceneInsertsAShapeInTheMiddleOfPaintOrder(t *testing.T) { if !ok { t.Fatal("insert after a child failed") } - head, ok := graph.InsertTriangle(graph.Root(), 0, [3]Point{{X: 1}}, Color{}, 5, Shade{}) + head, ok := graph.InsertTriangle(graph.Root(), 0, [3]Point{{X: 1}}, Color{}, 5, Shade{}, nil) if !ok { t.Fatal("insert as the first child failed") } @@ -225,14 +225,14 @@ func TestSceneLeafChangesKindInPlace(t *testing.T) { id, _ := graph.AddRectangle(graph.Root(), Rect{X: 1, Width: 5}, Color{Alpha: 1}) graph.DrainChanges(nil) - if !graph.SetTriangle(id, [3]Point{{X: 1}, {X: 2}, {X: 3}}, Color{Alpha: 1}, 5, Shade{}) { + if !graph.SetTriangle(id, [3]Point{{X: 1}, {X: 2}, {X: 3}}, Color{Alpha: 1}, 5, Shade{}, nil) { t.Fatal("a rectangle did not become a triangle") } changes := graph.DrainChanges(nil) if len(changes) != 1 || changes[0].Kind != KindTriangle || changes[0].Bounds != (Rect{}) || changes[0].Shape == nil || changes[0].Shape.Points[2].X != 3 || changes[0].EdgeMask != 5 { t.Fatalf("rectangle to triangle = %+v", changes) } - if graph.SetTriangle(id, [3]Point{{X: 1}, {X: 2}, {X: 3}}, Color{Alpha: 1}, 5, Shade{}) { + if graph.SetTriangle(id, [3]Point{{X: 1}, {X: 2}, {X: 3}}, Color{Alpha: 1}, 5, Shade{}, nil) { t.Fatal("setting the same triangle again reported a change") } if !graph.SetRoundedRectangle(id, Rect{X: 9}, Color{Alpha: 1}, 2) { @@ -242,7 +242,7 @@ func TestSceneLeafChangesKindInPlace(t *testing.T) { if len(changes) != 1 || changes[0].Kind != KindRectangle || changes[0].Shape != nil || changes[0].Radius != 2 { t.Fatalf("triangle to rectangle = %+v", changes) } - if graph.SetTriangle(graph.Root(), [3]Point{}, Color{}, 0, Shade{}) || graph.SetRectangle(graph.Root(), Rect{}, Color{}) { + if graph.SetTriangle(graph.Root(), [3]Point{}, Color{}, 0, Shade{}, nil) || graph.SetRectangle(graph.Root(), Rect{}, Color{}) { t.Fatal("a group became a shape") } } @@ -251,18 +251,18 @@ func TestTriangleShadeIsPublishedChangeCheckedAndClearedByARectangle(t *testing. graph := New() points := [3]Point{{X: 1}, {X: 2}, {X: 3}} shade := Shade{On: true, Colors: [2]Color{{Red: 1, Alpha: 1}, {Blue: 1, Alpha: 1}}} - id, _ := graph.AddTriangle(graph.Root(), points, Color{Green: 1, Alpha: 1}, 0, shade) + id, _ := graph.AddTriangle(graph.Root(), points, Color{Green: 1, Alpha: 1}, 0, shade, nil) changes := graph.DrainChanges(nil) if changes[len(changes)-1].Shape == nil || changes[len(changes)-1].Shape.Shade != shade { t.Fatalf("published shape = %+v", changes[len(changes)-1].Shape) } - if graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, shade) { + if graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, shade, nil) { t.Fatal("setting the same shaded triangle reported a change") } - if !graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, Shade{}) { + if !graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, Shade{}, nil) { t.Fatal("dropping the shade reported no change") } - graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, shade) + graph.SetTriangle(id, points, Color{Green: 1, Alpha: 1}, 0, shade, nil) graph.SetRectangle(id, Rect{Width: 4}, Color{Alpha: 1}) changes = graph.DrainChanges(changes[:0]) if len(changes) != 1 || changes[0].Shape != nil { diff --git a/style/look.go b/style/look.go index 9052e6127..9d4a30269 100644 --- a/style/look.go +++ b/style/look.go @@ -17,8 +17,8 @@ type ButtonLook struct { // Shadow is the elevation under the surface; only the outline variant has one. Shadow gfx.ShadowLevel // Ring is the halo of a focused or invalid button, transparent with a zero RingWidth - // when there is none. RingOutline says it is drawn as a line over a translucent theme - // rather than a disc under the surface. + // when there is none. RingOutline says it is drawn as a line over a translucent theme. + // A surface with no opaque fill is not covered by a disc either, so its halo is a line. Ring gfx.Color RingWidth, RingRadius float32 RingOutline bool diff --git a/style/tree.go b/style/tree.go index eb9a1db0d..b73e9f075 100644 --- a/style/tree.go +++ b/style/tree.go @@ -21,4 +21,8 @@ type TreeItem struct { // being fetched. Phase is the spinner's frame, 0 to 7. Loading bool Phase uint8 + // Background paints a full-width, square-cornered wash behind the row + // (underneath indentation, disclosure arrow, hover and selection highlight) + // so consecutive tinted rows form one continuous band. Zero paints nothing. + Background gfx.Color } diff --git a/ui/editabletabs/editabletabs.go b/ui/editabletabs/editabletabs.go index c30d4f002..10e9c4a67 100644 --- a/ui/editabletabs/editabletabs.go +++ b/ui/editabletabs/editabletabs.go @@ -200,6 +200,12 @@ func (t *EditableTabs) scroll(event gfx.ScrollEvent) gfx.EventResult { if math.Abs(float64(event.DeltaY)) > math.Abs(float64(event.DeltaX)) { delta = event.DeltaY } + if event.Pages != 0 { + delta = event.StepXIn(1, t.width) + if math.Abs(float64(event.DeltaY)) > math.Abs(float64(event.DeltaX)) { + delta = event.StepYIn(1, t.width) + } + } if delta == 0 { return gfx.EventResult{} } diff --git a/ui/timepicker/timepicker.go b/ui/timepicker/timepicker.go index ceb02264e..ea1862d1c 100644 --- a/ui/timepicker/timepicker.go +++ b/ui/timepicker/timepicker.go @@ -237,7 +237,11 @@ func (t *TimePicker) scroll(event gfx.ScrollEvent) gfx.EventResult { } rows, _ := t.size(column) limit := max(float32(rows*rowHeight)-visibleRows*rowHeight, 0) - t.offsets[column] = min(max(t.offsets[column]-event.DeltaY, 0), limit) + step := event.DeltaY + if event.Pages != 0 { + step = event.StepYIn(rowHeight, visibleRows*rowHeight) + } + t.offsets[column] = min(max(t.offsets[column]-step, 0), limit) return gfx.EventResult{Handled: true, Repaint: true} } diff --git a/ui/tree_paint.go b/ui/tree_paint.go index 4c6a865bc..973434673 100644 --- a/ui/tree_paint.go +++ b/ui/tree_paint.go @@ -24,6 +24,9 @@ func treeStateRow(s *TreeState, i int, rowBox Box) { if node.Branch { item.DisclosureID = s.GetChevrons().At(key) } + if s.RowBackground != nil { + item.Background = s.RowBackground(i) + } if canvas := f.Surface; canvas != nil && !node.Disabled { if canvas.Clicked(item.ID) { s.SetChosenIndex(i)