Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593public indirect enum TileTree: Sendable, Equatable, Codable { case tile(WindowStack) case split(axis: Axis, fraction: Double, first: TileTree, second: TileTree) case partition(axis: Axis, fraction: Double, first: TileTree, second: TileTree)
public var stacks: [WindowStack] { var result: [WindowStack] = [] result.reserveCapacity(tileCount) visitStacks { result.append($0) } return result }
public var windows: [WindowID] { var count = 0 visitStacks { count += $0.windows.count } var result: [WindowID] = [] result.reserveCapacity(count) visitStacks { result.append(contentsOf: $0.windows) } return result }
public var tileCount: Int { var count = 0 visitStacks { _ in count += 1 } return count }
public var visibleWindows: [WindowID] { visibleWindows(reservingCapacity: 0) }
func visibleWindows(reservingCapacity capacity: Int) -> [WindowID] { var result: [WindowID] = [] result.reserveCapacity(capacity) appendVisibleWindows(to: &result) return result }
func appendVisibleWindows(to result: inout [WindowID]) { visitStacks { result.append($0.visible) } }
var firstStack: WindowStack { var node = self while true { switch node { case .tile(let stack): return stack case .split(_, _, let first, _), .partition(_, _, let first, _): node = first } } }
var lastStack: WindowStack { var node = self while true { switch node { case .tile(let stack): return stack case .split(_, _, _, let second), .partition(_, _, _, let second): node = second } } }
func stack(containing window: WindowID) -> WindowStack? { var pending = [self] while let node = pending.popLast() { switch node { case .tile(let stack): if stack.windows.contains(window) { return stack } case .split(_, _, let first, let second), .partition(_, _, let first, let second): pending.append(second) pending.append(first) } } return nil }
func contains(_ window: WindowID) -> Bool { stack(containing: window) != nil }
private func visitStacks(_ visit: (WindowStack) -> Void) { var pending: [TileTree] = [] var node = self while true { switch node { case .tile(let stack): visit(stack) guard let next = pending.popLast() else { return } node = next case .split(_, _, let first, let second), .partition(_, _, let first, let second): pending.append(second) node = first } } }
func fold<Result>( _ tile: (WindowStack) -> Result, _ branch: (TileTree, Result, Result) -> Result, reservingCapacity capacity: Int = 0 ) -> Result { var pending: [(tree: TileTree, expanded: Bool)] = [] var values: [Result] = [] if capacity > 0 { pending.reserveCapacity(capacity + 1) values.reserveCapacity(capacity) } pending.append((self, false)) while let (node, expanded) = pending.popLast() { switch node { case .tile(let stack): values.append(tile(stack)) case .split(_, _, let first, let second), .partition(_, _, let first, let second): if expanded { let right = values.removeLast() let left = values.removeLast() values.append(branch(node, left, right)) } else { pending.append((node, true)) pending.append((second, false)) pending.append((first, false)) } } } precondition(values.count == 1, "A tree fold must produce one root value") return values.removeLast() }
public static func balanced( _ stacks: [WindowStack], layout: Layout, ratio: MainRatio = .half, variant: LayoutVariant = .standard ) -> TileTree? { guard let first = stacks.first else { return nil } guard stacks.count > 1 else { return .tile(first) } if variant == .portrait && (layout == .grid || layout == .columns || layout == .side) { return balanced(stacks, layout: layout, ratio: ratio)?.transposingAxes() } if layout == .side && variant == .ultrawide && stacks.count >= 3 { return .partition( axis: .horizontal, fraction: 0.75, first: .partition( axis: .horizontal, fraction: ratio.value, first: .tile(first), second: .tile(stacks[1])), second: line(Array(stacks.dropFirst(2)), axis: .vertical)) } switch layout { case .columns, .accordion: return line(stacks, axis: .horizontal) case .rows: return line(stacks, axis: .vertical) case .side: return .split( axis: .horizontal, fraction: ratio.value, first: .tile(first), second: line(Array(stacks.dropFirst()), axis: .vertical) ) case .grid, .tree, .bsp: let columns = Int(Double(stacks.count).squareRoot().rounded(.up)) let rows = stride(from: 0, to: stacks.count, by: columns).map { start in line(Array(stacks[start..<min(start + columns, stacks.count)]), axis: .horizontal) } return lineTrees(rows, axis: .vertical) } }
private static func line(_ stacks: [WindowStack], axis: Axis) -> TileTree { lineTrees(stacks.map { .tile($0) }, axis: axis) }
private static func lineTrees(_ trees: [TileTree], axis: Axis) -> TileTree { guard let last = trees.last else { preconditionFailure("A line must contain at least one tree") } var result = last for index in trees.indices.dropLast().reversed() { result = .split( axis: axis, fraction: 1 / Double(trees.count - index), first: trees[index], second: result) } return result }
func mappingStacks(_ transform: (WindowStack) -> WindowStack) -> TileTree { fold( { .tile(transform($0)) }, { node, first, second in node.replacingChildren(first: first, second: second) }) }
func removing(_ window: WindowID) -> TileTree? { fold( { stack -> TileTree? in stack.removing(window).map { .tile($0) } }, { node, first, second in if let first, let second { return node.replacingChildren(first: first, second: second) } return first ?? second }) }
func inserting(_ window: WindowID, beside target: WindowID, axis: Axis, before: Bool) -> TileTree { inserting(.tile(WindowStack(window)), beside: target, axis: axis, before: before) }
func inserting(_ tile: TileTree, beside target: WindowID, axis: Axis, before: Bool) -> TileTree { fold( { stack in let current = TileTree.tile(stack) guard stack.windows.contains(target) else { return current } return .partition( axis: axis, fraction: 0.5, first: before ? tile : current, second: before ? current : tile) }, { node, first, second in node.replacingChildren(first: first, second: second) }) }
private func replacingChildren(first: TileTree, second: TileTree, fraction: Double? = nil) -> TileTree { switch self { case .tile: return self case .split(let axis, let existing, _, _): return .split(axis: axis, fraction: fraction ?? existing, first: first, second: second) case .partition(let axis, let existing, _, _): return .partition(axis: axis, fraction: fraction ?? existing, first: first, second: second) } }
func node(at path: ArraySlice<TileEdge.Child>) -> TileTree? { var node = self for child in path { switch node { case .tile: return nil case .split(_, _, let first, let second), .partition(_, _, let first, let second): node = child == .first ? first : second } } return node }
func replacingFraction(at path: ArraySlice<TileEdge.Child>, with fraction: Double) -> TileTree? { var node = self var ancestors: [(tree: TileTree, child: TileEdge.Child)] = [] ancestors.reserveCapacity(path.count) for child in path { switch node { case .tile: return nil case .split(_, _, let first, let second), .partition(_, _, let first, let second): ancestors.append((node, child)) node = child == .first ? first : second } } var updated: TileTree switch node { case .tile: return nil case .split(_, _, let first, let second), .partition(_, _, let first, let second): updated = node.replacingChildren(first: first, second: second, fraction: fraction) } while let (ancestor, child) = ancestors.popLast() { switch ancestor { case .tile: preconditionFailure("A path ancestor must have children") case .split(_, _, let first, let second), .partition(_, _, let first, let second): updated = ancestor.replacingChildren( first: child == .first ? updated : first, second: child == .second ? updated : second) } } return updated }
public static func == (left: TileTree, right: TileTree) -> Bool { left.matches(right, includingPlacement: true) }
func hasSameTopology(as other: TileTree) -> Bool { matches(other, includingPlacement: false) }
private func matches(_ other: TileTree, includingPlacement: Bool) -> Bool { var pending = [(self, other)] while let (left, right) = pending.popLast() { switch (left, right) { case (.tile(let first), .tile(let second)): guard includingPlacement ? first == second : first.windows == second.windows else { return false } case ( .split(let leftAxis, let leftFraction, let leftFirst, let leftSecond), .split(let rightAxis, let rightFraction, let rightFirst, let rightSecond) ), ( .partition(let leftAxis, let leftFraction, let leftFirst, let leftSecond), .partition(let rightAxis, let rightFraction, let rightFirst, let rightSecond) ): guard leftAxis == rightAxis, !includingPlacement || leftFraction == rightFraction else { return false } pending.append((leftSecond, rightSecond)) pending.append((leftFirst, rightFirst)) default: return false } } return true }
}
public enum WhenFull: String, Sendable, Equatable, Codable, CaseIterable { case stack, float}
public struct Workspace: Sendable, Equatable, Codable { public static let windowCapBounds = 0...100
public let key: WorkspaceKey public var layout: Layout public var ratio: MainRatio public var configuredRatio: MainRatio public var gaps: Gaps public var reservedEdges: Insets public var whenFull: WhenFull public private(set) var windowCap: Int public internal(set) var order: [WindowID] public internal(set) var openingOrder: [WindowID] public internal(set) var focus: WindowID? public internal(set) var tree: TileTree? public internal(set) var pendingSplitAxis: Axis? public internal(set) var layoutVariant: LayoutVariant = .standard public internal(set) var displaySize: Size? public internal(set) var capabilitySize: Size? public var layoutDefaults: LayoutDefaults? var alternateSideTree: TileTree? var adaptiveTileMemory: AdaptiveTileMemory?
public init( key: WorkspaceKey, layout: Layout = .grid, ratio: MainRatio = .half, gaps: Gaps = Gaps(), reservedEdges: Insets = Insets(), windowCap: Int = 3, order: [WindowID] = [], focus: WindowID? = nil, whenFull: WhenFull = .stack ) { self.key = key self.layout = layout self.ratio = ratio configuredRatio = ratio self.gaps = gaps self.reservedEdges = reservedEdges self.whenFull = whenFull self.windowCap = max(1, windowCap) var seen: Set<WindowID> = [] self.order = order.filter { seen.insert($0).inserted } openingOrder = self.order self.focus = focus.flatMap { self.order.contains($0) ? $0 : nil } tree = nil pendingSplitAxis = nil rebuild(stacks: self.order.map { WindowStack($0) }) if adaptiveTileMemory != nil { tree = TileTree.balanced(tree?.stacks ?? [], layout: layout, ratio: ratio) adaptiveTileMemory = nil } }
public var visibleWindows: [WindowID] { tree?.visibleWindows(reservingCapacity: order.count) ?? [] }
public mutating func setWindowCap(_ cap: Int) { let cap = max(1, cap) if windowCap != cap { windowCap = cap constrainTileCount() } restoreAutomaticTiles() }
@discardableResult public mutating func setWindowCap( _ cap: Int, in frame: Rect, windows: [WindowID: ManagedWindow] ) -> Bool { var expanded = self expanded.setWindowCap(cap) let targetCount = expanded.tree?.tileCount ?? 0 if LayoutEngine.arrange(expanded, in: frame, windows: windows).cannotFit.isEmpty { self = expanded return true } windowCap = max(1, cap) adaptiveTileMemory = nil constrainTileCount() guard var stacks = tree?.stacks else { return targetCount == 0 } // Keep constrained members together when a flexible member can occupy the new tile. while stacks.count < targetCount { var replacement: [WindowStack]? for index in stacks.indices where !stacks[index].isUserMade && stacks[index].windows.count > 1 { let source = stacks[index] for member in source.recency { guard let retained = source.removing(member) else { continue } var proposed = stacks proposed[index] = retained proposed.append(WindowStack(member)) var candidate = self candidate.tree = balancedWorkspaceTree(proposed) guard LayoutEngine.arrange(candidate, in: frame, windows: windows).cannotFit.isEmpty else { continue } replacement = proposed break } if replacement != nil { break } } guard let replacement else { break } stacks = replacement tree = balancedWorkspaceTree(stacks) adaptiveTileMemory = nil alternateSideTree = nil } if let focus { select(focus) } return stacks.count == targetCount && LayoutEngine.arrange(self, in: frame, windows: windows).cannotFit.isEmpty }
mutating func rebuild(stacks: [WindowStack]) { let preservesMembership = tree?.stacks == stacks restoreAdaptiveTiles() let currentStacks = tree?.stacks let stacks = preservesMembership ? (currentStacks ?? stacks) : stacks if usesAdaptiveThreeTiles && currentStacks == stacks && tree != TileTree.balanced(stacks, layout: layout, ratio: ratio, variant: layoutVariant) { // Retile must not discard a spatial promotion or user-adjusted divider. } else if !layout.preservesTree || currentStacks != stacks { tree = balancedWorkspaceTree(stacks) } constrainTileCount() if let focus { select(focus) } }
mutating func synchronizeTreeOrder() { guard let tree else { return } let windows = tree.windows let members = Set(windows) precondition(members.count == windows.count && members.isSubset(of: Set(order))) var tiled = windows.makeIterator() order = order.map { window in guard members.contains(window) else { return window } guard let next = tiled.next() else { preconditionFailure("Tile order must cover workspace membership") } return next } precondition(tiled.next() == nil, "Every tiled window must belong to the workspace") }
mutating func select(_ window: WindowID) { guard order.contains(window) else { return } focus = window tree = tree?.mappingStacks { stack in var selected = stack selected.select(window) return selected } }
mutating func remove(_ window: WindowID, restoringAutomaticTiles: Bool = true) { removeTile(window) order.removeAll { $0 == window } openingOrder.removeAll { $0 == window } if focus == window { focus = tree?.lastStack.visible ?? order.last } if restoringAutomaticTiles { restoreAutomaticTiles() } }
mutating func removeTile(_ window: WindowID) { if let memory = adaptiveTileMemory, let original = memory.original.removing(window), let projection = memory.projection.removing(window) { adaptiveTileMemory = AdaptiveTileMemory(original: original, projection: projection) } else { adaptiveTileMemory = nil } let promotesMain = layout == .side && primaryWindow == window && tree?.stack(containing: window)?.windows == [window] let promotesWide = layout == .side && layoutVariant == .ultrawide && tree?.stacks.prefix(2).contains(where: { $0.windows == [window] }) == true let previous = tree tree = tree?.removing(window) if promotesMain || promotesWide { rebuild(stacks: tree?.stacks ?? []) if promotesWide, let previous { preserveWideSideSplits(from: previous) } } }
mutating func insert( _ window: WindowID, floating: Bool, in frame: Rect?, windows: [WindowID: ManagedWindow], position: Int? = nil ) { let previousFocus = focus if !order.contains(window) { order.insert(window, at: min(max(position ?? order.count, 0), order.count)) openingOrder.append(window) focus = window } guard !floating, tree?.contains(window) != true else { return } let requestedAxis = layout == .tree ? pendingSplitAxis : nil guard let current = tree else { tree = .tile(WindowStack(window)) return } let stacks = current.stacks guard let last = stacks.last else { preconditionFailure("A tile tree must contain a stack") } let members = Set(stacks.flatMap(\.windows)) let next = order.drop { $0 != window }.dropFirst().first { members.contains($0) } let fallback = layout == .side && primaryOnRight ? (stacks.last(where: { !$0.windows.contains(primaryWindow ?? window) }) ?? last) : last let orderedTarget = stacks.first { stack in next.map(stack.windows.contains) == true } ?? fallback let focusedTarget = previousFocus.flatMap { focused in stacks.first { $0.windows.contains(focused) } } let tileCount = stacks.count let target = tileCount >= effectiveWindowCap || layout == .tree || layout == .bsp ? (focusedTarget ?? orderedTarget) : orderedTarget if tileCount >= effectiveWindowCap { tree = current.mappingStacks { stack in guard stack.windows == target.windows else { return stack } var updated = stack updated.insert(window, before: next) return updated } if var memory = adaptiveTileMemory, let tree { memory.original = memory.original.mappingStacks { stack in guard stack.windows.contains(target.visible) else { return stack } var updated = stack updated.append(window) return updated } memory.projection = tree adaptiveTileMemory = memory } return } if layout == .side && layoutVariant == .ultrawide && tileCount == 2 { var stacks = stacks let index = next.flatMap { next in stacks.firstIndex { $0.windows.contains(next) } } ?? stacks.count stacks.insert(WindowStack(window), at: index) tree = balancedWorkspaceTree(stacks) restoreAutomaticTiles() return } let neutralPair: Bool switch current { case .split(.horizontal, 0.5, .tile, .tile), .partition(.horizontal, 0.5, .tile, .tile): neutralPair = true default: neutralPair = false } if usesAdaptiveThreeTiles, tileCount == 2, neutralPair { var candidate = self candidate.tree = balancedWorkspaceTree(stacks + [WindowStack(window)]) if let screen = frame, LayoutEngine.arrange(candidate, in: screen, windows: windows).cannotFit.isEmpty { tree = candidate.tree return } } let axis: Axis switch layout { case .columns: axis = layoutVariant == .portrait ? .vertical : .horizontal case .accordion: axis = .horizontal case .rows: axis = .vertical case .side: let mainAxis: Axis = layoutVariant == .portrait ? .vertical : .horizontal axis = tileCount == 1 ? mainAxis : (mainAxis == .horizontal ? .vertical : .horizontal) case .grid, .tree, .bsp: if let screen = frame ?? displaySize.map({ Rect(origin: Point(), size: $0) }) { var beforeInsertion = self beforeInsertion.focus = previousFocus let frames = layout == .grid ? LayoutEngine.arrangeUnrounded(beforeInsertion, in: screen, windows: windows).frames : LayoutEngine.arrange(beforeInsertion, in: screen, windows: windows).frames let area = frames[target.visible] ?? screen axis = requestedAxis ?? (area.size.width >= area.size.height ? .horizontal : .vertical) } else { axis = requestedAxis ?? .horizontal } } let before = layout == .tree || layout == .bsp ? false : next != nil tree = current.inserting(window, beside: target.visible, axis: axis, before: before) if layout == .tree { pendingSplitAxis = nil } if layout == .tree || layout == .bsp { synchronizeTreeOrder() } if layout != .accordion && tileCount == 1 { changeRatio(ratio) } restoreAutomaticTiles() }
mutating func restoreAutomaticTiles() { guard whenFull == .stack, let current = tree, current.tileCount < min(effectiveWindowCap, current.windows.count) else { return } restoreAdaptiveTiles() constrainTileCount() guard let current = tree else { return } var stacks = current.stacks var changed = false while stacks.count < effectiveWindowCap, let index = stacks.firstIndex(where: { !$0.isUserMade && $0.windows.count > 1 }) { let source = stacks[index] guard let leastRecent = source.recency.first, let retained = source.removing(leastRecent) else { preconditionFailure("A stacked tile must have a removable least-recent member") } stacks[index] = retained stacks.append(WindowStack(leastRecent)) changed = true } guard changed else { return } tree = balancedWorkspaceTree(stacks) adaptiveTileMemory = nil alternateSideTree = nil if let focus { select(focus) } }}