Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions changelog.d/macos-env-refresh.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
### Fixed

- Stop macOS apps re-rendering on every frame of a display brightness ramp and asking AVFoundation for the camera on every environment refresh: the camera is probed once and followed through device connect and disconnect notifications, display and backing-scale notifications arriving in one run loop turn refresh once, and a change of `HDRHeadroom` alone updates the environment at most four times a second, ending with the settled value (#2813 by @houko).
2 changes: 1 addition & 1 deletion docs/public/en/services.md
Original file line number Diff line number Diff line change
Expand Up @@ -596,7 +596,7 @@ Use `audio.SetSoundLimits(cx, audio.SoundLimits{MaxSounds: 200, MaxDuration: 20

## Displays

`cx.Env().Display()` returns the window's current `core.DisplayInfo` and updates bindings when the window moves to another display or display settings change. `cx.Env().Displays()` lists the displays the platform reports. `RefreshRate` and `MaxRefreshRate` are in Hz, with zero for an unavailable rate. `HDR` and `HDRSupported` report active and capable HDR output, with `HDRHeadroom` (peak relative to SDR white), `SDRWhiteLevel` (nits) and `MaxLuminance` (nits) where available on macOS, iOS, Windows and Wayland Linux. iOS reports the panel's maximum. HarmonyOS reports the window's display, its current rate and its highest supported rate. The web reports the current screen and marks its frame callback measurement with `RefreshRateEstimated`. In tests, set `Displays` and `DisplayID` through `nsgotest.Environment`.
`cx.Env().Display()` returns the window's current `core.DisplayInfo` and updates bindings when the window moves to another display or display settings change. `cx.Env().Displays()` lists the displays the platform reports. `RefreshRate` and `MaxRefreshRate` are in Hz, with zero for an unavailable rate. `HDR` and `HDRSupported` report active and capable HDR output, with `HDRHeadroom` (peak relative to SDR white), `SDRWhiteLevel` (nits) and `MaxLuminance` (nits) where available on macOS, iOS, Windows and Wayland Linux. iOS reports the panel's maximum. On macOS, a change of `HDRHeadroom` alone, as during a brightness ramp, updates the environment at most four times a second and ends with the value the display settles at. HarmonyOS reports the window's display, its current rate and its highest supported rate. The web reports the current screen and marks its frame callback measurement with `RefreshRateEstimated`. In tests, set `Displays` and `DisplayID` through `nsgotest.Environment`.

## Speaking text

Expand Down
88 changes: 88 additions & 0 deletions internal/platform/macos/camera.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
//go:build darwin && !ios

package macos

import (
"sync"

"github.com/ebitengine/purego/objc"

"github.com/nsgo-dev/nsgo/internal/platform/apple"
)

// cameraProbe asks AVFoundation for the default video device, which runs its device discovery.
var cameraProbe = func() bool { return apple.ScanCamera() != 0 }

// camera is Environment.Camera and ScanCode, which every environment refresh reads.
var camera = &cameraWatch{}

// cameraWatch keeps whether the Mac has a camera: probed once, on first use, and again only when AVFoundation reports a device connected or disconnected, as device discovery is slow and logs on every call, and a refresh can run every frame (#2813).
type cameraWatch struct {
mu sync.Mutex
started bool
available bool
changed []func()
// probe and observe are cameraProbe and observeCameraDevices unless a test sets them; observe calls its function on the main thread whenever a device comes or goes.
probe func() bool
observe func(func())
}

// Available reports whether a camera is available.
func (c *cameraWatch) Available() bool {
c.mu.Lock()
if c.started {
defer c.mu.Unlock()
return c.available
}
c.started = true
observe := c.observe
if observe == nil {
observe = observeCameraDevices
}
c.mu.Unlock()
// Observed before the probe, so a device that comes in between is not missed.
observe(c.update)
available := c.probeNow()
c.mu.Lock()
defer c.mu.Unlock()
c.available = available
return available
}

// OnChange calls fn on the main thread whenever the camera's availability changes.
func (c *cameraWatch) OnChange(fn func()) {
c.mu.Lock()
defer c.mu.Unlock()
c.changed = append(c.changed, fn)
}

// update probes again after a device came or went, and tells the listeners when availability changed.
func (c *cameraWatch) update() {
available := c.probeNow()
c.mu.Lock()
changed := available != c.available
c.available = available
listeners := c.changed
c.mu.Unlock()
if changed {
for _, fn := range listeners {
fn()
}
}
}

func (c *cameraWatch) probeNow() bool {
if c.probe != nil {
return c.probe()
}
return cameraProbe()
}

// observeCameraDevices calls fn on the main thread when AVFoundation reports a capture device connected or disconnected, for the app's life.
func observeCameraDevices(fn func()) {
const avFoundation = "/System/Library/Frameworks/AVFoundation.framework/AVFoundation"
center := objc.ID(apple.Class("NSNotificationCenter")).Send(sel("defaultCenter"))
for _, name := range []string{"AVCaptureDeviceWasConnectedNotification", "AVCaptureDeviceWasDisconnectedNotification"} {
apple.Observe(center, apple.Global(avFoundation, name), func(objc.ID) { fn() })
}
}
69 changes: 69 additions & 0 deletions internal/platform/macos/camera_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
//go:build darwin && !ios

package macos

import (
"testing"

"github.com/ebitengine/purego/objc"

"github.com/nsgo-dev/nsgo/internal/platform/apple"
)

// TestEnvironmentDoesNotProbeTheCameraPerCall checks that environment reads the camera's availability from what was probed once, not from AVFoundation's device discovery on every refresh (#2813).
func TestEnvironmentDoesNotProbeTheCameraPerCall(t *testing.T) {
probes := 0
savedProbe, savedWatch := cameraProbe, camera
cameraProbe = func() bool { probes++; return true }
camera = &cameraWatch{observe: func(func()) {}}
defer func() { cameraProbe, camera = savedProbe, savedWatch }()
onMain(func() {
loadAppKit()
pool := objc.ID(apple.Class("NSAutoreleasePool")).Send(selNew)
defer pool.Send(sel("drain"))
s := newSurface(Options{Width: 160, Height: 100}, false)
defer func() {
delete(surfaces, s)
delete(views, s.native)
s.native.Send(selRelease)
}()
for range 10 {
s.environment()
}
})
if probes != 1 {
t.Errorf("10 environments probed the camera %d times, want once", probes)
}
}

// TestCameraWatchProbesOnceAndFollowsDevices checks that the camera's availability is probed on first use and again only when AVFoundation reports a device connected or disconnected, and that only a change tells the listeners.
func TestCameraWatchProbesOnceAndFollowsDevices(t *testing.T) {
probes, connected, observed := 0, true, 0
var update func()
c := &cameraWatch{
probe: func() bool { probes++; return connected },
observe: func(fn func()) { observed++; update = fn },
}
changes := 0
c.OnChange(func() { changes++ })
for range 5 {
if !c.Available() {
t.Fatal("camera unavailable, want available")
}
}
if probes != 1 || observed != 1 {
t.Fatalf("5 reads probed %d times and observed %d times, want once each", probes, observed)
}
update() // a device connected; the default one is unchanged
if changes != 0 || probes != 2 {
t.Fatalf("unchanged device: %d changes, %d probes, want 0 and 2", changes, probes)
}
connected = false
update()
if c.Available() || changes != 1 {
t.Fatalf("disconnected: available %v after %d changes, want false after 1", c.Available(), changes)
}
if probes != 3 {
t.Fatalf("probed %d times, want 3", probes)
}
}
51 changes: 46 additions & 5 deletions internal/platform/macos/macos.go
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,9 @@ type surface struct {
// stops end the surface's observations as it closes.
stops []func()
closed bool
// refreshes coalesces the refreshes notifications request; headroom rate-limits the environments that change only displays' HDR headroom (refresh.go).
refreshes coalescer
headroom headroomGate
// pointer is where the window takes the pointer (windowpointer.go).
pointer windowPointer
// appearance is the one the app forces, host the one an embedding
Expand Down Expand Up @@ -555,12 +558,19 @@ func loadAppKit() {
v.surface.refresh()
}
}
// A display's brightness ramp or scale change can call it on every frame.
requestRefresh := func(self objc.ID, cmd objc.SEL) {
apple.Super(self, cmd)
if v := views[self]; v != nil {
v.surface.requestRefresh()
}
}
classSurface = register("NsgoSurface", nsView, nil, append(common,
objc.MethodDef{Cmd: sel("setFrameSize:"), Fn: surfaceSetFrameSize},
objc.MethodDef{Cmd: sel("viewDidMoveToWindow"), Fn: surfaceMoved},
objc.MethodDef{Cmd: selApply, Fn: surfaceApply},
objc.MethodDef{Cmd: sel("viewDidChangeEffectiveAppearance"), Fn: refresh},
objc.MethodDef{Cmd: sel("viewDidChangeBackingProperties"), Fn: refresh},
objc.MethodDef{Cmd: sel("viewDidChangeBackingProperties"), Fn: requestRefresh},
objc.MethodDef{Cmd: sel("acceptsFirstResponder"), Fn: func(objc.ID, objc.SEL) bool { return true }},
// It holds selections, but Tab passes it by.
objc.MethodDef{Cmd: sel("canBecomeKeyView"), Fn: func(objc.ID, objc.SEL) bool { return false }},
Expand Down Expand Up @@ -1250,6 +1260,7 @@ func (s *surface) environment() driver.Environment {
thermal, lowPower := apple.ProcessPower()
appearance := apple.GoString(s.native.Send(sel("effectiveAppearance")).Send(sel("name")))
displays, displayID := displaySnapshot(s.window.Send(sel("screen")))
hasCamera := camera.Available()
return driver.Environment{
DeviceName: deviceName,
DeviceModel: deviceModel,
Expand All @@ -1261,8 +1272,8 @@ func (s *surface) environment() driver.Environment {
ScreenColor: true,

DiscoverServices: true,
ScanCode: apple.ScanCamera() != 0,
Camera: apple.ScanCamera() != 0,
ScanCode: hasCamera,
Camera: hasCamera,
Speech: apple.SpeechAvailable(),
Speak: apple.SpeakAvailable(),
Audio: apple.AudioAvailable(),
Expand Down Expand Up @@ -1383,13 +1394,23 @@ func (s *surface) refresh() {
if s == nil || s.engine == nil || s.settingPanelFrame {
return
}
s.refreshes.done()
if lockedPointer.owner == s && !s.canHoldPointer() {
s.releasePointer(true)
}
s.layoutTrafficLights()
env := s.environment()
s.reportFrameWindow(env)
if !env.Equal(s.env) {
if wait, schedule := s.headroom.hold(s.env, env, time.Now()); wait > 0 {
if schedule {
s.later(wait, func() {
s.headroom.fired()
s.refresh()
})
}
return
}
rescale := env.PixelRatio != s.env.PixelRatio
redock := s.dock.Edge != driver.WindowPlaceDefault && !slices.Equal(env.Displays, s.env.Displays)
s.env = env
Expand All @@ -1403,6 +1424,15 @@ func (s *surface) refresh() {
}
}

// requestRefresh refreshes the surface on the main queue's next turn, once however many requests arrive before then. Notifications that can come in storms request it rather than refresh at once: a display's change of parameters, profile or backing scale, and a camera coming or going.
func (s *surface) requestRefresh() {
s.refreshes.request(apple.OnMain, func() {
if !s.closed {
s.refresh()
}
})
}

func (s *surface) reportFrameWindow(env driver.Environment) {
s.devFrame.record(env)
visible := s.window != 0 && s.kind != driver.SurfaceTrayIcon && env.Lifecycle != driver.LifecycleBackground
Expand Down Expand Up @@ -1449,7 +1479,11 @@ func (s *surface) observe() {
case "NSWindowDidEnterFullScreenNotification", "NSWindowDidExitFullScreenNotification":
s.fullScreenEntering = false
}
s.refresh()
if name == "NSWindowDidChangeScreenNotification" || name == "NSWindowDidChangeScreenProfileNotification" {
s.requestRefresh()
} else {
s.refresh()
}
if name == "NSWindowDidEnterFullScreenNotification" || name == "NSWindowDidExitFullScreenNotification" {
// AppKit lays the bar out again as it leaves full screen, after the notification. A surface closed by then may have let its window go.
apple.OnMain(func() {
Expand Down Expand Up @@ -1524,9 +1558,16 @@ func observeApp() {
})
for _, name := range []string{"NSApplicationDidBecomeActiveNotification", "NSApplicationDidResignActiveNotification",
"NSApplicationDidHideNotification", "NSApplicationDidUnhideNotification",
"NSApplicationDidChangeOcclusionStateNotification", "NSApplicationDidChangeScreenParametersNotification"} {
"NSApplicationDidChangeOcclusionStateNotification"} {
apple.Observe(center, apple.Global(appKitPath, name), refresh)
}
requestRefresh := func() {
for s := range surfaces {
s.requestRefresh()
}
}
apple.Observe(center, apple.Global(appKitPath, "NSApplicationDidChangeScreenParametersNotification"), func(objc.ID) { requestRefresh() })
camera.OnChange(requestRefresh)
appObserver = objc.ID(classObserver).Send(selNew)
ws.Send(sel("addObserver:forKeyPath:options:context:"), appObserver, apple.NSString("voiceOverEnabled"), uint(0), uintptr(0))
}
Expand Down
71 changes: 71 additions & 0 deletions internal/platform/macos/refresh.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
//go:build darwin && !ios

package macos

import (
"slices"
"time"

"github.com/nsgo-dev/nsgo/internal/driver"
)

// coalescer runs a refresh once per turn of the main queue however many notifications request it in that turn, as a display change can post several of them for each window at once (#2813).
type coalescer struct {
pending bool
}

// request has post run run on the main queue's next turn, unless a request is already waiting or a direct refresh satisfies it first (done).
func (c *coalescer) request(post func(func()), run func()) {
if c.pending {
return
}
c.pending = true
post(func() {
if c.pending {
c.pending = false
run()
}
})
}

// done tells the coalescer that a refresh ran, which satisfies a request still waiting.
func (c *coalescer) done() { c.pending = false }

// headroomInterval is the least time between two environments that change only displays' HDR headroom.
const headroomInterval = 250 * time.Millisecond

// headroomGate rate-limits environments that change only displays' HDR headroom. The headroom follows the panel's brightness and steps on every frame of a brightness ramp, and each new environment updates every view that reads the environment (#2813). A held change is published by a refresh scheduled for when the interval ends, so the value the display settles at is always published.
type headroomGate struct {
last time.Time // when the last headroom change was published
pending bool // a refresh is scheduled for when the interval ends
}

// hold reports how long refresh should keep next from the engine, which already has prev: zero unless next changes only displays' headroom within headroomInterval of the last such change. schedule is whether the caller must refresh again after wait, false while a refresh is already scheduled.
func (g *headroomGate) hold(prev, next driver.Environment, now time.Time) (wait time.Duration, schedule bool) {
if !headroomOnly(prev, next) {
return 0, false
}
if wait = g.last.Add(headroomInterval).Sub(now); wait <= 0 {
g.last = now
return 0, false
}
schedule = !g.pending
g.pending = true
return wait, schedule
}

// fired tells the gate that the refresh it had scheduled runs.
func (g *headroomGate) fired() { g.pending = false }

// headroomOnly reports whether next differs from prev in displays' HDR headroom and nothing else, the same displays staying in HDR or out of it.
func headroomOnly(prev, next driver.Environment) bool {
if len(prev.Displays) != len(next.Displays) || prev.Equal(next) {
return false
}
same := next
same.Displays = slices.Clone(next.Displays)
for i := range same.Displays {
same.Displays[i].HDRHeadroom = prev.Displays[i].HDRHeadroom
}
return same.Equal(prev)
}
Loading
Loading