diff --git a/internal/gui/app.go b/internal/gui/app.go index d8bfe957d..16c33e55e 100644 --- a/internal/gui/app.go +++ b/internal/gui/app.go @@ -573,6 +573,9 @@ func Run(version string, showMain bool, link string) error { } h.tray.SetMenu(menu) h.tray.AttachWindow(h.panel).WindowOffset(6) + // before Wails removes the item as the app quits, which would forget + // where the user put the icon (trayshown_darwin.go; nothing elsewhere) + h.app.OnShutdown(func() { keepTrayPlace() }) // a Mac that handed the gateway to the new version (handover.go) // leaves the menu bar to it while it finishes its requests: one bird if runtime.GOOS == "darwin" { diff --git a/internal/gui/trayplace_darwin_test.go b/internal/gui/trayplace_darwin_test.go new file mode 100644 index 000000000..cf06bb257 --- /dev/null +++ b/internal/gui/trayplace_darwin_test.go @@ -0,0 +1,91 @@ +//go:build darwin && cgo && !nogui + +package gui + +import ( + "fmt" + "net/http" + "os" + "strings" + "testing" + "time" + + "github.com/wailsapp/wails/v3/pkg/application" + "github.com/wailsapp/wails/v3/pkg/events" +) + +// nb5p on Discord (macOS 26): Ice put magpie's menu bar icon back in its +// hidden section after every update, and after a plain quit and reopen, +// however often it was moved out. AppKit keeps where the item sits by its +// autosave name ("NSStatusItem Preferred Position Item-0"), and Wails +// removes the item as the app quits, which forgets it: the next magpie's +// item started at the default spot. Renamed first, the removal forgets +// nothing kept. +func TestQuitKeepsTheMenuBarIconsPlace(t *testing.T) { + for _, c := range []struct{ keep, want string }{ + {"0", "tray place: forgotten"}, // the cause, without the fix + {"1", "tray place: kept"}, + } { + out, err := runAppKit(t, 30*time.Second, []string{"MAGPIE_TEST_TRAY_PLACE=" + c.keep}) + if err != nil || !strings.Contains(string(out), c.want) { + t.Fatalf("keep %s: want %q: %v\n%s", c.keep, c.want, err, out) + } + } +} + +func init() { + keep := os.Getenv("MAGPIE_TEST_TRAY_PLACE") + if keep == "" { + return + } + fail := func(format string, a ...any) { + fmt.Printf("tray place: "+format+"\n", a...) + os.Exit(1) + } + // where the user put it, the launch before + setTrayPlace("Item-0", 400) + app := application.New(application.Options{ + Name: "magpie tray place regression", + Mac: application.MacOptions{ActivationPolicy: application.ActivationPolicyAccessory}, + Assets: application.AssetOptions{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + fmt.Fprint(w, `
magpie
`) + })}, + }) + tray := app.SystemTray.New() + tray.SetTemplateIcon(trayIcon) + app.Event.OnApplicationEvent(events.Common.ApplicationStarted, func(*application.ApplicationEvent) { + go func() { + for deadline := time.Now().Add(5 * time.Second); trayItems() == 0; { + if time.Now().After(deadline) { + fail("no status item came up") + } + time.Sleep(50 * time.Millisecond) + } + // AppKit may move it to where the item really is; kept is + // what counts + if _, ok := trayPlace("Item-0"); !ok { + fail("the place set before the start is gone") + } + // what the app's shutdown does: magpie's task, then Wails' + // removal of every tray + if keep == "1" { + if n := keepTrayPlace(); n != 1 { + fail("kept the place of %d items, not 1", n) + } + } + tray.Destroy() + mainSettled() + if x, ok := trayPlace("Item-0"); ok { + fmt.Printf("tray place: kept (%v)\n", x) + } else { + fmt.Println("tray place: forgotten") + } + os.Exit(0) + }() + }) + if err := app.Run(); err != nil { + fail("run: %v", err) + } + os.Exit(1) +} diff --git a/internal/gui/trayshown_darwin.go b/internal/gui/trayshown_darwin.go index 5445f657e..b7210cfed 100644 --- a/internal/gui/trayshown_darwin.go +++ b/internal/gui/trayshown_darwin.go @@ -56,6 +56,60 @@ static void mpSetFlag(const char *k) { [d synchronize]; } +// AppKit keeps where a status item sits ("NSStatusItem Preferred Position +// Item-0", where the user or a menu bar manager like Ice put it) by its +// autosave name, and removeStatusItem: forgets it. Wails removes the item +// as the app quits, so every quit, and every restart to update, put the +// icon back at the default spot, left of the others: in Ice's hidden +// section (nb5p). Under a name of its own the removal forgets nothing that +// is kept. Every item of this app's, by its Wails controller (the button's +// target); how many there are, renamed if rename. +static int mpTrayItemsNow(int rename) { + int n = 0; + for (NSWindow *w in NSApp.windows) { + NSMutableArray *views = [NSMutableArray arrayWithObject:w.contentView ?: [NSNull null]]; + while (views.count) { + id v = views.lastObject; + [views removeLastObject]; + if (![v isKindOfClass:[NSView class]]) continue; + [views addObjectsFromArray:[v subviews]]; + if (![v isKindOfClass:[NSStatusBarButton class]]) continue; + id t = [(NSStatusBarButton *)v target]; + if (![t respondsToSelector:@selector(statusItem)]) continue; + id it = [t performSelector:@selector(statusItem)]; + if (![it isKindOfClass:[NSStatusItem class]]) continue; + if (rename) ((NSStatusItem *)it).autosaveName = [NSString stringWithFormat:@"magpie quitting %d", n]; + n++; + } + } + return n; +} + +static int mpTrayItems(int rename) { + if ([NSThread isMainThread]) return mpTrayItemsNow(rename); + __block int n = 0; + dispatch_sync(dispatch_get_main_queue(), ^{ n = mpTrayItemsNow(rename); }); + return n; +} + +static NSString *mpPlaceKey(const char *name) { + return [@"NSStatusItem Preferred Position " stringByAppendingString:[NSString stringWithUTF8String:name]]; +} + +// Where AppKit keeps the item named name, -1 for nowhere. +static double mpTrayPlace(const char *name) { + NSUserDefaults *d = [NSUserDefaults standardUserDefaults]; + [d synchronize]; + id v = [[d persistentDomainForName:[[NSBundle mainBundle] bundleIdentifier] ?: [[NSProcessInfo processInfo] processName]] objectForKey:mpPlaceKey(name)]; + return [v respondsToSelector:@selector(doubleValue)] ? [v doubleValue] : -1; +} + +static void mpSetTrayPlace(const char *name, double x) { + NSUserDefaults *d = [NSUserDefaults standardUserDefaults]; + [d setDouble:x forKey:mpPlaceKey(name)]; + [d synchronize]; +} + // Waits, off the main thread, for what is queued on it to have run. static void mpMainSettled(void) { dispatch_sync(dispatch_get_main_queue(), ^{}); @@ -76,6 +130,29 @@ func forgetTrayHidden() int { return int(C.mpForgetHidden()) } // what is queued on it, the tray's Hide among them. func forgetTrayHiddenLater() { C.mpForgetHiddenLater() } +// keepTrayPlace has the menu bar icon's place outlive this magpie: run as +// the app quits, before Wails removes the item, which would forget where +// the user put it (mpKeepTrayPlaceNow). How many items it kept the place of. +func keepTrayPlace() int { return int(C.mpTrayItems(1)) } + +// trayItems is how many status items this app has up. +func trayItems() int { return int(C.mpTrayItems(0)) } + +// trayPlace is where AppKit keeps the status item named name ("Item-0"), +// and whether it keeps one. +func trayPlace(name string) (float64, bool) { + k := C.CString(name) + defer C.free(unsafe.Pointer(k)) + x := float64(C.mpTrayPlace(k)) + return x, x >= 0 +} + +func setTrayPlace(name string, x float64) { + k := C.CString(name) + defer C.free(unsafe.Pointer(k)) + C.mpSetTrayPlace(k, C.double(x)) +} + // mainSettled waits for the main thread to run what is queued on it. Not // on the main thread. func mainSettled() { C.mpMainSettled() } diff --git a/internal/gui/trayshown_other.go b/internal/gui/trayshown_other.go index dba733ccb..81d0ff142 100644 --- a/internal/gui/trayshown_other.go +++ b/internal/gui/trayshown_other.go @@ -6,3 +6,4 @@ package gui func forgetTrayHidden() int { return 0 } func forgetTrayHiddenLater() {} func bringTrayBack() (stillHidden bool) { return false } +func keepTrayPlace() int { return 0 }