commit 3775386aa28a537b6d9ec81117ad03b4bdffa2b5 Author: relikd Date: Tue Oct 12 01:35:25 2021 +0200 Initial diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..53eea1f --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.DS_Store +/*.app +/*.tar.gz diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..724c90c --- /dev/null +++ b/LICENSE @@ -0,0 +1,7 @@ +Copyright 2021 Oleg Geier + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Makefile b/Makefile new file mode 100755 index 0000000..9ea327e --- /dev/null +++ b/Makefile @@ -0,0 +1,26 @@ +# usage: make [CONFIG=debug|release] + +ifeq ($(CONFIG), debug) + CFLAGS=-Onone -g +else + CFLAGS=-O +endif + +APP_DIR = Memmon.app/Contents + +Memmon.app: SDK_PATH = $(shell xcrun --show-sdk-path --sdk macosx) +Memmon.app: src/* + mkdir -p Memmon.app/Contents/MacOS/ + swiftc $(CFLAGS) src/main.swift \ + -target arm64-apple-macos10.10 -target x86_64-apple-macos10.10 \ + -emit-executable -sdk $(SDK_PATH) -o Memmon.app/Contents/MacOS/Memmon + mkdir -p Memmon.app/Contents/Resources/ + cp src/AppIcon.icns Memmon.app/Contents/Resources/AppIcon.icns + cp src/Info.plist Memmon.app/Contents/Info.plist + echo 'APPL????' > Memmon.app/Contents/PkgInfo + @touch Memmon.app + +.PHONY: release +release: VERSION=$(shell grep -A1 CFBundleShortVersionString src/Info.plist | tail -1 | tr -d '[a-z \t]') +release: Memmon.app + tar -czf "Memmon_v$(VERSION).tar.gz" Memmon.app diff --git a/README.md b/README.md new file mode 100644 index 0000000..9135597 --- /dev/null +++ b/README.md @@ -0,0 +1,49 @@ +[![macOS 10.10+](https://img.shields.io/badge/macOS-10.10+-888)](#install) +[![Current release](https://img.shields.io/github/release/relikd/Memmon)](https://github.com/relikd/Memmon/releases) + + + +# Memmon + +Memmon remembers what your Mac forgets – A simple deamon that restores your window positions on external monitors. + +## FAQ + +### Why‽ + +I am frustrated! Why does my Mac forget all window positions which I moved to a second screen? Every time I unplug the monitor. Every time I close my Macbook lid. Every time I lock my Mac. + +Is it macOS 11? Is it the USB-C-to-HDMI converter dongle (notably one made by Apple)? Why do I have to fix things that Apple should have fixed long ago? … + + +### Aren't there other solutions? + +Yes, for example [Mjolnir](https://github.com/mjolnirapp/mjolnir) or [Hammerspoon](https://github.com/Hammerspoon/hammerspoon) (and some comercial ones). But I do not need a full-fledged window manager. Nor the dependencies they rely on. I just need to fix this damn bug. + + +### What is it good for? + +First off, Memmon is just 130 lines of code – no dependencies. You can audit it in 5 minutes. Or just build it from scratch if you like (just run `make`). + +Secondly, it does one thing and one thing only: Save and restore window positions whenever your monitor setup changes. + + +## Install + +1. You will need macOS 10.10 or newer. +2. Grant Memmon the Accessibility privilege. Go to "System Preference" > "Security & Privacy" > "Accessibility" and add Memmon to that list. Otherwise, you can't move other application windows around and the app has no purpose. +3. Thats it. The app runs in your status bar. + + +### Hide Status Icon + +You can hide the status icon either via the same-titled menu entry. If you do so, the only way to quit the app is by killing the process (with Activity.app or `killall Memmon`). + +If you like to hide the icon directly on launch, use this app-setting: + +```sh +# disable status icon completely +defaults write de.relikd.Memmon invisible -bool True +# re-enable status icon +defaults delete de.relikd.Memmon invisible +``` diff --git a/img/icon-small.svg b/img/icon-small.svg new file mode 100644 index 0000000..9574673 --- /dev/null +++ b/img/icon-small.svg @@ -0,0 +1,9 @@ + + + + + + + + + diff --git a/img/icon.svg b/img/icon.svg new file mode 100644 index 0000000..f81a634 --- /dev/null +++ b/img/icon.svg @@ -0,0 +1,12 @@ + + + + + + + + + + + + diff --git a/src/AppIcon.icns b/src/AppIcon.icns new file mode 100644 index 0000000..aeffca9 Binary files /dev/null and b/src/AppIcon.icns differ diff --git a/src/Info.plist b/src/Info.plist new file mode 100644 index 0000000..9e08c90 --- /dev/null +++ b/src/Info.plist @@ -0,0 +1,36 @@ + + + + + CFBundleIdentifier + de.relikd.Memmon + CFBundleExecutable + Memmon + CFBundleName + Memmon + CFBundleIconFile + AppIcon + CFBundleInfoDictionaryVersion + 6.0 + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 42 + LSMinimumSystemVersion + 10.10 + LSBackgroundOnly + + LSUIElement + + NSHighResolutionCapable + + NSSupportsSuddenTermination + + NSPrincipalClass + NSApplication + NSHumanReadableCopyright + Copyright © 2021 relikd. + + diff --git a/src/main.swift b/src/main.swift new file mode 100755 index 0000000..7aba48d --- /dev/null +++ b/src/main.swift @@ -0,0 +1,126 @@ +#!/usr/bin/env swift +import Cocoa +import AppKit + +class AppDelegate: NSObject, NSApplicationDelegate { + private var statusItem: NSStatusItem! + private var numScreens: Int = NSScreen.screens.count + private var state: [Int: [Int32: [CGRect]]] = [:] // [screencount: [pid: [windows]]] + + func applicationDidFinishLaunching(_ aNotification: Notification) { + if UserDefaults.standard.bool(forKey: "invisible") == true { + return + } + self.statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength) + if let button = self.statusItem.button { + button.image = self.statusMenuIcon() + } + self.statusItem.menu = NSMenu(title: "") + self.statusItem.menu!.addItem(withTitle: "Hide Status Icon", action: #selector(self.enableInvisbleMode), keyEquivalent: "") + self.statusItem.menu!.addItem(withTitle: "Quit", action: #selector(NSApp.terminate), keyEquivalent: "q") + } + + func statusMenuIcon() -> NSImage { + let img = NSImage.init(size: .init(width: 21, height: 14), flipped: true) { + let ctx = NSGraphicsContext.current!.cgContext + let w = $0.width + let h = $0.height + let ssw = 0.025 * w // small stroke width + let lsw = 0.05 * w // large stroke width + // main screen + ctx.stroke(CGRect(x: 0.1 * w, y: 0.0 * h, width: 0.8 * w, height: 0.8 * h).insetBy(dx: lsw / 2, dy: lsw / 2), width: lsw) + ctx.clear(CGRect(x: 0.0 * w, y: 0.2 * h, width: 1.0 * w, height: 0.4 * h)) + ctx.fill(CGRect(x: 0.41 * w, y: 0.8 * h, width: 0.18 * w, height: 0.12 * h)) + ctx.fill(CGRect(x: 0.27 * w, y: 0.92 * h, width: 0.46 * w, height: 0.08 * h)) + // three windows + ctx.stroke(CGRect(x: 0.0 * w, y: 0.28 * h, width: 0.27 * w, height: 0.24 * h).insetBy(dx: ssw / 2, dy: ssw / 2), width: ssw) + ctx.stroke(CGRect(x: 0.34 * w, y: 0.2 * h, width: 0.32 * w, height: 0.4 * h).insetBy(dx: ssw / 2, dy: ssw / 2), width: ssw) + ctx.stroke(CGRect(x: 0.73 * w, y: 0.28 * h, width: 0.27 * w, height: 0.24 * h).insetBy(dx: ssw / 2, dy: ssw / 2), width: ssw) + return true + } + img.isTemplate = true + return img + } + + @objc func enableInvisbleMode() { + self.statusItem = nil + } + + func applicationDidChangeScreenParameters(_ notification: Notification) { + if numScreens != NSScreen.screens.count { + // save state + self.state[numScreens] = self.getState() + numScreens = NSScreen.screens.count + // restore state + if let previous = self.state[numScreens] { + self.restoreState(previous) + } + } + } + + private func getState() -> [Int32: [CGRect]] { + var state: [Int32: [CGRect]] = [:] + let windowList = CGWindowListCopyWindowInfo(.optionOnScreenOnly, kCGNullWindowID) as NSArray? as? [[String: AnyObject]] + for entry in windowList! { + let pid = entry[kCGWindowOwnerPID as String] as! Int32 + let layer = entry[kCGWindowLayer as String] as! Int32 + // let owner = entry[kCGWindowOwnerName as String] as! String + if layer != 0 { + continue + } + let b = entry[kCGWindowBounds as String] as! [String: Int] + let bounds = CGRect(x: b["X"]!, y: b["Y"]!, width: b["Width"]!, height: b["Height"]!) + if (state[pid] == nil) { + state[pid] = [bounds] + } else { + state[pid]!.append(bounds) + } + } + return state + } + + private func restoreState(_ state: [Int32: [CGRect]]) { + for (pid, bounds) in state { + self.setWindowSizes(pid, bounds) + } + } + + private func setWindowSizes(_ pid: Int32, _ sizes: [CGRect]) { + let win = self.axWinList(pid) + guard win.count > 0, win.count == sizes.count else { + print(pid, win.count, sizes.count) + return + } + for i in 0 ..< win.count { + var newPoint = sizes[i].origin + var newSize = sizes[i].size + AXUIElementSetAttributeValue(win[i], kAXPositionAttribute as CFString, + AXValueCreate(AXValueType(rawValue: kAXValueCGPointType)!, &newPoint)!); + AXUIElementSetAttributeValue(win[i], kAXSizeAttribute as CFString, + AXValueCreate(AXValueType(rawValue: kAXValueCGSizeType)!, &newSize)!); + } + } + + private func axWinList(_ pid: Int32) -> [AXUIElement] { + let appRef = AXUIElementCreateApplication(pid) + var value: AnyObject? + AXUIElementCopyAttributeValue(appRef, kAXWindowsAttribute as CFString, &value) + if let windowList = value as? [AXUIElement] { + var tmp: [AXUIElement] = [] + for win in windowList { + var role: CFTypeRef? + AXUIElementCopyAttributeValue(win, kAXRoleAttribute as CFString, &role) + if role as? String == kAXWindowRole { + tmp.append(win) // filter e.g. Finder's AXScrollArea + } + } + return tmp + } + return [] + } +} + +let delegate = AppDelegate() +NSApplication.shared.delegate = delegate +NSApplication.shared.run() +// _ = NSApplicationMain(CommandLine.argc, CommandLine.unsafeArgv)