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
7 changes: 5 additions & 2 deletions QuickMD/QuickMD/QuickMDApp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
30 changes: 28 additions & 2 deletions QuickMD/QuickMD/Views/SettingsView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Bool> {
Binding(
get: { separateWindows },
set: { newValue in
separateWindows = newValue
WindowTabbing.applyWindowPreference()
}
)
}

var body: some View {
VStack(alignment: .leading, spacing: 0) {
Expand All @@ -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 })) {
Expand Down
93 changes: 89 additions & 4 deletions QuickMD/QuickMD/WindowTabbing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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
Expand All @@ -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
}
Expand Down
107 changes: 107 additions & 0 deletions QuickMD/QuickMDTests/WindowTabbingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,20 +37,26 @@ 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()
let defaults = UserDefaults.standard
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() {
let defaults = UserDefaults.standard
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()
}

Expand Down Expand Up @@ -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)
}
}