From 8c6a95e7980c40880a1a74d4be77a446e3b2be60 Mon Sep 17 00:00:00 2001 From: Alejandro Torres Date: Wed, 11 Nov 2026 09:12:24 -0300 Subject: [PATCH] feat(windows): option to open each document in its own window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QuickMD forces every document into the frontmost window as a tab (WindowTabbing.preferTabsAlways + a manual merge), so two documents can never be read side by side. Settings ▸ General ▸ Windows ▸ "Open each document in its own window" turns that off: each document then gets its own window. How it works: - At launch, the tabbing preference is written to the argument domain as "manual" instead of "always", and NSWindow.allowsAutomaticWindowTabbing is set to false. The preference is what AppKit reads when it shows a window, and AppKit caches it for the whole process, so it can only be chosen at launch. - While the app runs, the two levers that do work at runtime are used: NSWindow.allowsAutomaticWindowTabbing (global) and NSWindow.tabbingMode (per window). The manual merge that joins a new window to an existing tab group is skipped in separate-windows mode. Documents already open keep the tab group they are in — AppKit gives an app no way to take a tab group apart — but every document opened from then on honours the new mode. --- QuickMD/QuickMD/QuickMDApp.swift | 7 +- QuickMD/QuickMD/Views/SettingsView.swift | 30 ++++- QuickMD/QuickMD/WindowTabbing.swift | 93 ++++++++++++++- QuickMD/QuickMDTests/WindowTabbingTests.swift | 107 ++++++++++++++++++ 4 files changed, 229 insertions(+), 8 deletions(-) diff --git a/QuickMD/QuickMD/QuickMDApp.swift b/QuickMD/QuickMD/QuickMDApp.swift index 34d50fb..7135237 100644 --- a/QuickMD/QuickMD/QuickMDApp.swift +++ b/QuickMD/QuickMD/QuickMDApp.swift @@ -21,8 +21,11 @@ struct QuickMDApp: App { // Split View. Overrides the system-wide "Prefer tabs when opening // documents" preference for our app only; AppKit does the tabbing as // each window is ordered in. Must run before the first window exists. - NSWindow.allowsAutomaticWindowTabbing = true - WindowTabbing.preferTabsAlways() + // + // Settings ▸ General ▸ "Open each document in its own window" flips + // this (each document then gets its own window); the same helper + // re-applies it live when the setting is toggled. + WindowTabbing.applyWindowPreferenceAtLaunch() } var body: some Scene { diff --git a/QuickMD/QuickMD/Views/SettingsView.swift b/QuickMD/QuickMD/Views/SettingsView.swift index c745d03..1a4f29a 100644 --- a/QuickMD/QuickMD/Views/SettingsView.swift +++ b/QuickMD/QuickMD/Views/SettingsView.swift @@ -28,12 +28,26 @@ struct SettingsView: View { // MARK: - General /// Settings → General: behaviour that is not about how the document looks — -/// the opt-in auto-copy of selections (v1.11 S-D10) and the Contents sidebar's -/// depth (#42, also in the sidebar's context menu); same grouped Form and +/// the opt-in auto-copy of selections (v1.11 S-D10), the Contents sidebar's +/// depth (#42, also in the sidebar's context menu) and how documents are +/// windowed (tabs in one window, or one window each); same grouped Form and /// window size as the other tabs, so switching tabs does not resize the window. struct GeneralSettingsView: View { @AppStorage(SelectionAutoCopy.defaultsKey) private var autoCopySelection: Bool = false @AppStorage(ToCDepth.defaultsKey) private var tocMaxLevel: Int = ToCDepth.all + @AppStorage(WindowTabbing.separateWindowsKey) private var separateWindows: Bool = false + + /// Writes the setting and re-applies it right away, so the next document + /// opens in its own window without restarting the app. + private var separateWindowsBinding: Binding { + Binding( + get: { separateWindows }, + set: { newValue in + separateWindows = newValue + WindowTabbing.applyWindowPreference() + } + ) + } var body: some View { VStack(alignment: .leading, spacing: 0) { @@ -50,6 +64,18 @@ struct GeneralSettingsView: View { .foregroundColor(.secondary) } + Section { + Toggle("Open each document in its own window", isOn: separateWindowsBinding) + } header: { + Text("Windows") + .font(.system(size: 11, weight: .semibold)) + .foregroundColor(.secondary) + } footer: { + Text("Off: every document opens as a tab of the same window. On: each document gets its own window, so you can read several at once side by side.") + .font(.system(size: 11)) + .foregroundColor(.secondary) + } + Section { Picker("Show", selection: Binding(get: { ToCDepth.normalized(tocMaxLevel) }, set: { tocMaxLevel = $0 })) { diff --git a/QuickMD/QuickMD/WindowTabbing.swift b/QuickMD/QuickMD/WindowTabbing.swift index 5f2e2f6..c32548d 100644 --- a/QuickMD/QuickMD/WindowTabbing.swift +++ b/QuickMD/QuickMD/WindowTabbing.swift @@ -17,6 +17,12 @@ struct WindowConfigurator: NSViewRepresentable { func makeNSView(context: Context) -> NSView { let view = TabAwareView() view.onWindowAttached = { window in + // "Open each document in its own window": the window itself + // refuses to join a tab group. AppKit decides when a window is + // shown, and by then this can already be too late — the global + // switch in WindowTabbing is what decides in practice — but it + // keeps a window that is shown later on the right track. + window.tabbingMode = WindowTabbing.documentTabbingMode configure(window) WindowTabbing.registerDocumentWindow(window) let merged = WindowTabbing.joinExistingTabs(window, among: WindowTabbing.documentWindows) @@ -49,16 +55,91 @@ enum WindowTabbing { /// Settings ▸ Desktop & Dock ▸ "Prefer tabs when opening documents"). static let preferenceKey = "AppleWindowTabbingMode" + /// Settings ▸ General ▸ Windows ▸ "Open each document in its own window". + /// Off by default (every document shares one window, as a tab); when on, + /// each document gets its own window and nothing is ever merged into + /// another window's tab group. + static let separateWindowsKey = "separateDocumentWindows" + + /// Whether each document should open in its own window. + static func separateWindowsEnabled(in defaults: UserDefaults = .standard) -> Bool { + defaults.bool(forKey: separateWindowsKey) + } + /// Every QuickMD document opens as a tab, whatever the system-wide setting /// (default "In Full Screen" only). Set in the argument domain: it outranks /// the global domain, is never written to disk, and leaves the user's /// setting for other apps alone. Call before the first window exists. static func preferTabsAlways(in defaults: UserDefaults = .standard) { + setTabbingMode("always", in: defaults) + } + + /// The opposite of `preferTabsAlways()`: documents never join a tab group, + /// whatever the system-wide "Prefer tabs when opening documents" setting + /// says. Set in the argument domain too, for the same reasons. + /// + /// "manual" is the value AppKit reads as "never tab" — "never" is an old + /// alias for "inFullScreen". + static func preferTabsNever(in defaults: UserDefaults = .standard) { + setTabbingMode("manual", in: defaults) + } + + /// Writes the tabbing mode into the argument domain, keeping any other + /// argument-domain value the app (or a test) put there. + private static func setTabbingMode(_ mode: String, in defaults: UserDefaults) { var arguments = defaults.volatileDomain(forName: UserDefaults.argumentDomain) - arguments[preferenceKey] = "always" + arguments[preferenceKey] = mode defaults.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain) } + /// The tabbing mode a document window must use. + /// + /// `.disallowed` is the per-window lever: it needs no global state and + /// can be changed while the app runs. The alternative, + /// `NSWindow.userTabbingPreference`, cannot be: AppKit reads it once per + /// process and caches it, so changing the defaults domain after the first + /// window exists has no effect. + static var documentTabbingMode: NSWindow.TabbingMode { + separateWindowsEnabled() ? .disallowed : .automatic + } + + /// Applies the "separate windows" setting at launch, before the first + /// window exists: the global tabbing switch, the preference AppKit reads + /// for every window it shows, and the mode of the windows already open. + static func applyWindowPreferenceAtLaunch(in defaults: UserDefaults = .standard) { + let separate = separateWindowsEnabled(in: defaults) + NSWindow.allowsAutomaticWindowTabbing = !separate + if separate { + preferTabsNever(in: defaults) + } else { + preferTabsAlways(in: defaults) + } + applyTabbingModeToOpenWindows() + } + + /// Applies the "separate windows" setting while the app is running. + /// + /// The tabbing *preference* is not touched: AppKit reads + /// `NSWindow.userTabbingPreference` once per process and caches it, so + /// rewriting the defaults domain now would have no effect. The two levers + /// that do work at runtime are `NSWindow.allowsAutomaticWindowTabbing` + /// (global) and `NSWindow.tabbingMode` (per window, read when the window + /// is shown). + static func applyWindowPreference() { + NSWindow.allowsAutomaticWindowTabbing = !separateWindowsEnabled() + applyTabbingModeToOpenWindows() + } + + /// Gives every open document window the tabbing mode the setting asks + /// for. Windows that are already on screen keep the tab group they are in + /// — a tab group is not something AppKit lets an app take apart — but a + /// document opened from now on honours the new mode. + private static func applyTabbingModeToOpenWindows() { + for window in documentWindows { + window.tabbingMode = documentTabbingMode + } + } + /// Every document window, registered as it attaches (WindowConfigurator /// lives in MarkdownView only). The manual merge picks its host from these, /// not by `tabbingIdentifier`: SwiftUI chooses that value, and the Settings @@ -80,10 +161,14 @@ enum WindowTabbing { /// half-empty black full-screen Space without a menu bar. @discardableResult static func joinExistingTabs(_ newWindow: NSWindow, among documentWindows: [NSWindow]) -> Bool { + // "Open each document in its own window": never merge. The check comes + // before the tabbed-windows test on purpose — a window that AppKit + // already grouped must still count as standalone, so it also gets the + // remembered size (see WindowConfigurator). + guard !separateWindowsEnabled() else { return false } if (newWindow.tabbedWindows?.count ?? 0) > 1 { return true } - guard let host = documentWindows.first(where: { other in - other !== newWindow && other.isVisible - }) else { return false } + let candidates = documentWindows.filter { $0 !== newWindow && $0.isVisible } + guard let host = candidates.first else { return false } if host.styleMask.contains(.fullScreen) || newWindow.styleMask.contains(.fullScreen) { return false } diff --git a/QuickMD/QuickMDTests/WindowTabbingTests.swift b/QuickMD/QuickMDTests/WindowTabbingTests.swift index 7ca697a..f95df63 100644 --- a/QuickMD/QuickMDTests/WindowTabbingTests.swift +++ b/QuickMD/QuickMDTests/WindowTabbingTests.swift @@ -37,6 +37,8 @@ final class WindowTabbingTests: XCTestCase { private var savedArguments: [String: Any] = [:] private var savedSize: (Any?, Any?) + private var savedSeparateWindows: Bool = false + private var savedAllowsAutomaticTabbing: Bool = true override func setUp() { super.setUp() @@ -44,6 +46,8 @@ final class WindowTabbingTests: XCTestCase { savedArguments = defaults.volatileDomain(forName: UserDefaults.argumentDomain) savedSize = (defaults.object(forKey: "lastWindowFrameWidth"), defaults.object(forKey: "lastWindowFrameHeight")) + savedSeparateWindows = defaults.bool(forKey: WindowTabbing.separateWindowsKey) + savedAllowsAutomaticTabbing = NSWindow.allowsAutomaticWindowTabbing } override func tearDown() { @@ -51,6 +55,8 @@ final class WindowTabbingTests: XCTestCase { defaults.setVolatileDomain(savedArguments, forName: UserDefaults.argumentDomain) defaults.set(savedSize.0, forKey: "lastWindowFrameWidth") defaults.set(savedSize.1, forKey: "lastWindowFrameHeight") + defaults.set(savedSeparateWindows, forKey: WindowTabbing.separateWindowsKey) + NSWindow.allowsAutomaticWindowTabbing = savedAllowsAutomaticTabbing super.tearDown() } @@ -188,4 +194,105 @@ final class WindowTabbingTests: XCTestCase { XCTAssertEqual(UserDefaults.standard.double(forKey: "lastWindowFrameWidth"), window.frame.width) XCTAssertEqual(UserDefaults.standard.double(forKey: "lastWindowFrameHeight"), window.frame.height) } + + // MARK: - Separate windows (one window per document) + + /// AppKit reads `NSWindow.userTabbingPreference` ONCE per process and + /// caches it — proven by this file's very first test, which is the one + /// that sees "always"; every later read in the same process still sees + /// "always" no matter what the defaults domain says. So the preference is + /// only a launch-time lever, and the runtime levers are + /// `allowsAutomaticWindowTabbing` and the per-window `tabbingMode`. + func testPreferTabsNeverWritesTheValueAppKitReadsAsManual() { + WindowTabbing.preferTabsNever() + let after = UserDefaults.standard.volatileDomain(forName: UserDefaults.argumentDomain) + XCTAssertEqual(after[WindowTabbing.preferenceKey] as? String, "manual") + } + + func testSeparateWindowsTurnsAutomaticTabbingOff() { + UserDefaults.standard.set(true, forKey: WindowTabbing.separateWindowsKey) + WindowTabbing.applyWindowPreference() + XCTAssertFalse(NSWindow.allowsAutomaticWindowTabbing) + } + + func testDefaultKeepsTabsAndAutomaticTabbingOn() { + UserDefaults.standard.set(false, forKey: WindowTabbing.separateWindowsKey) + WindowTabbing.applyWindowPreference() + XCTAssertTrue(NSWindow.allowsAutomaticWindowTabbing) + } + + /// At launch the preference AppKit will read is written to match the + /// setting: "manual" (never tab) with separate windows on. + func testLaunchWritesThePreferenceAppKitWillRead() { + UserDefaults.standard.set(true, forKey: WindowTabbing.separateWindowsKey) + WindowTabbing.applyWindowPreferenceAtLaunch() + let after = UserDefaults.standard.volatileDomain(forName: UserDefaults.argumentDomain) + XCTAssertEqual(after[WindowTabbing.preferenceKey] as? String, "manual") + XCTAssertFalse(NSWindow.allowsAutomaticWindowTabbing) + } + + func testLaunchKeepsTheAlwaysPreferenceByDefault() { + UserDefaults.standard.set(false, forKey: WindowTabbing.separateWindowsKey) + WindowTabbing.applyWindowPreferenceAtLaunch() + let after = UserDefaults.standard.volatileDomain(forName: UserDefaults.argumentDomain) + XCTAssertEqual(after[WindowTabbing.preferenceKey] as? String, "always") + XCTAssertTrue(NSWindow.allowsAutomaticWindowTabbing) + } + + /// The manual merge is what actually forces a second document into the + /// first window's tab group — with separate windows on, it must not run. + func testSeparateWindowsNeverMergesIntoAnExistingWindow() { + UserDefaults.standard.set(true, forKey: WindowTabbing.separateWindowsKey) + let host = FakeWindow() + host.fakeVisible = true + let new = FakeWindow() + XCTAssertFalse(WindowTabbing.joinExistingTabs(new, among: [host, new])) + XCTAssertTrue(host.addedTabs.isEmpty) + } + + /// Even a window AppKit already tabbed must count as standalone, so it + /// gets the remembered size instead of inheriting the tab group's frame. + func testSeparateWindowsTreatsAnAppKitTabGroupAsStandalone() { + UserDefaults.standard.set(true, forKey: WindowTabbing.separateWindowsKey) + let host = FakeWindow() + let new = FakeWindow() + new.fakeTabs = [host, new] + XCTAssertFalse(WindowTabbing.joinExistingTabs(new, among: [host, new])) + } + + func testSeparateWindowsKeepsOtherLaunchArguments() { + let defaults = UserDefaults.standard + var arguments = savedArguments + arguments["QuickMDTestArgument"] = "kept" + defaults.setVolatileDomain(arguments, forName: UserDefaults.argumentDomain) + + UserDefaults.standard.set(true, forKey: WindowTabbing.separateWindowsKey) + WindowTabbing.applyWindowPreferenceAtLaunch() + + let after = defaults.volatileDomain(forName: UserDefaults.argumentDomain) + XCTAssertEqual(after["QuickMDTestArgument"] as? String, "kept") + XCTAssertEqual(after[WindowTabbing.preferenceKey] as? String, "manual") + } + + /// The per-window mode is the lever that survives a running app: AppKit + /// caches `userTabbingPreference` for the whole process, so the window's + /// own mode is what really decides whether it joins a tab group. + func testSeparateWindowsDisallowsTabbingForTheWindow() { + UserDefaults.standard.set(true, forKey: WindowTabbing.separateWindowsKey) + XCTAssertEqual(WindowTabbing.documentTabbingMode, .disallowed) + } + + func testDefaultLeavesTheWindowTabbingModeAutomatic() { + UserDefaults.standard.set(false, forKey: WindowTabbing.separateWindowsKey) + XCTAssertEqual(WindowTabbing.documentTabbingMode, .automatic) + } + + /// Toggling the setting off again must restore the tabbing behaviour. + func testTurningSeparateWindowsOffRestoresTabs() { + UserDefaults.standard.set(true, forKey: WindowTabbing.separateWindowsKey) + WindowTabbing.applyWindowPreference() + UserDefaults.standard.set(false, forKey: WindowTabbing.separateWindowsKey) + WindowTabbing.applyWindowPreference() + XCTAssertTrue(NSWindow.allowsAutomaticWindowTabbing) + } }