Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407public enum LayoutVariant: String, Sendable, Equatable, Codable { case standard, portrait, ultrawide}
public struct LayoutCapabilities: Sendable, Equatable, Codable { public let variant: LayoutVariant public let maximumWindowCount: Int
public func effectiveWindowCap(for requested: Int) -> Int { precondition(requested >= 0) guard requested != 0, requested != Int.max else { return Int.max } return min(requested, maximumWindowCount) }}
extension Layout { public func capabilities(in screen: Rect) -> LayoutCapabilities { let size = screen.size let portrait = size.height > size.width let wide = size.height > 0 && size.width / size.height >= 2 let compact = min(size.width, size.height) < 1000 let maximum: Int switch self { case .grid: maximum = 4 case .columns: maximum = portrait || compact ? 3 : 4 case .rows: maximum = portrait || !compact ? 3 : 2 case .side: maximum = portrait || wide ? 5 : (compact ? 3 : 4) case .tree, .bsp, .accordion: maximum = Int.max } return LayoutCapabilities( variant: preservesTree ? .standard : (portrait ? .portrait : (self == .side && wide ? .ultrawide : .standard)), maximumWindowCount: maximum) }}
extension TileTree { func transposingAxes() -> TileTree { fold( { .tile($0) }, { node, first, second in switch node { case .tile: preconditionFailure("A folded branch must be a split or partition") case .split(let axis, let fraction, _, _): return .split( axis: axis == .horizontal ? .vertical : .horizontal, fraction: fraction, first: first, second: second) case .partition(let axis, let fraction, _, _): return .partition( axis: axis == .horizontal ? .vertical : .horizontal, fraction: fraction, first: first, second: second) } }) }
func updatingSurvivingFractions(from current: TileTree, since projection: TileTree) -> TileTree { fold( { .tile($0) }, { node, first, second in switch node { case .tile: preconditionFailure("A folded branch must be a split or partition") case .split(let axis, let fraction, let oldFirst, let oldSecond): return .split( axis: axis, fraction: current.changedFraction( between: oldFirst.windows, and: oldSecond.windows, axis: axis, since: projection) ?? fraction, first: first, second: second) case .partition(let axis, let fraction, let oldFirst, let oldSecond): return .partition( axis: axis, fraction: current.changedFraction( between: oldFirst.windows, and: oldSecond.windows, axis: axis, since: projection) ?? fraction, first: first, second: second) } }) }
private func changedFraction( between left: [WindowID], and right: [WindowID], axis: Axis, since projection: TileTree ) -> Double? { guard let current = fraction(between: left, and: right, axis: axis), let previous = projection.fraction(between: left, and: right, axis: axis), current != previous else { return nil } return current }
private func fraction(between left: [WindowID], and right: [WindowID], axis: Axis) -> Double? { var pending = [self] while let node = pending.popLast() { switch node { case .tile: continue case .split(let currentAxis, let fraction, let first, let second), .partition(let currentAxis, let fraction, let first, let second): if currentAxis == axis && first.windows == left && second.windows == right { return fraction } pending.append(second) pending.append(first) } } return nil }
func restoringStacks(_ stacks: [WindowStack]) -> TileTree? { guard self.stacks.map(\.windows) == stacks.map(\.windows) else { return nil } var iterator = stacks.makeIterator() return mappingStacks { _ in guard let stack = iterator.next() else { preconditionFailure("Matching trees need matching stacks") } return stack } }}
public struct LayoutDefaults: Sendable, Equatable, Codable { public var landscape: Layout public var portrait: Layout
public init(landscape: Layout = .grid, portrait: Layout = .rows) { self.landscape = landscape self.portrait = portrait }
public func layout(in size: Size?) -> Layout { size.map { $0.height > $0.width } == true ? portrait : landscape }}
struct AdaptiveTileMemory: Sendable, Equatable, Codable { var original: TileTree var projection: TileTree}
extension State { func newWorkspace(_ key: WorkspaceKey) -> Workspace { let defaults = displayLayoutDefaults?[key.display] ?? layoutDefaults ?? LayoutDefaults() var workspace = Workspace(key: key, layout: defaults.landscape) workspace.layoutDefaults = defaults if let display = displays[key.display], display.hasUsableGeometry { workspace.adapt(to: display.frame, fullFrame: display.fullFrame) } return workspace }
mutating func adaptWorkspaces(effects: inout [Effect]) { for key in workspaceKeys { guard let display = displays[key.display], display.hasUsableGeometry, var workspace = workspaces[key], workspace.needsAdaptation(to: display.frame, fullFrame: display.fullFrame) else { continue } let previous = workspace workspace.adapt(to: display.frame, fullFrame: display.fullFrame) setWorkspace(workspace) if previous.layout != workspace.layout { effects.append(.announce(.layoutChanged(workspace.layout))) } workspace.announceMergedTiles(since: previous, effects: &effects) } }}
extension Workspace { public var effectiveWindowCap: Int { guard let size = capabilitySize ?? displaySize else { return windowCap } return layout.capabilities(in: Rect(origin: Point(), size: size)).effectiveWindowCap(for: windowCap) }
var transposesLayout: Bool { layoutVariant == .portrait && (layout == .grid || layout == .columns || layout == .side) }
var mainRatioPath: [TileEdge.Child] { if primaryExpandsTile { return layoutVariant == .ultrawide && (tree?.tileCount ?? 0) >= 3 ? [primaryOnRight ? .second : .first] : [] } var path: [TileEdge.Child] = [] var node = tree while let current = node { switch current { case .tile: return path case .split(_, _, let first, _), .partition(_, _, let first, _): if case .tile = first { return path } path.append(.first) node = first } } return path }
public var mainSizeRatio: Double { guard layout != .accordion, let node = tree?.node(at: mainRatioPath[...]) else { return ratio.value } switch node { case .tile: return ratio.value case .split(_, let fraction, _, _), .partition(_, let fraction, _, _): return primaryExpandsTile && primaryOnRight ? 1 - fraction : fraction } }
func needsAdaptation(to screen: Rect, fullFrame: Rect) -> Bool { displaySize != screen.size || capabilitySize != fullFrame.size || layoutDefaults.map { $0.layout(in: fullFrame.size) != layout } == true || layoutVariant != layout.capabilities(in: fullFrame).variant || (tree?.tileCount ?? 0) > effectiveWindowCap || adaptiveTileMemory.map { $0.original.tileCount <= effectiveWindowCap } == true }
public mutating func adapt(to screen: Rect, fullFrame: Rect? = nil) { let fullFrame = fullFrame ?? screen guard Display(id: key.display, frame: screen, fullFrame: fullFrame).hasUsableGeometry, needsAdaptation(to: screen, fullFrame: fullFrame) else { return } restoreAdaptiveTiles() displaySize = screen.size capabilitySize = fullFrame.size if let defaults = layoutDefaults { let requested = defaults.layout(in: fullFrame.size) if layout != requested { changeLayout(requested) layoutDefaults = defaults } } let variant = layout.capabilities(in: fullFrame).variant if variant != layoutVariant { if transposesLayout { tree = tree?.transposingAxes() } let wasWide = layoutVariant == .ultrawide layoutVariant = variant if layout == .side && wasWide != (variant == .ultrawide) { let previous = tree let stacks = tree?.stacks ?? [] tree = alternateSideTree?.restoringStacks(stacks) ?? balancedWorkspaceTree(stacks) alternateSideTree = previous } if transposesLayout { tree = tree?.transposingAxes() } } constrainTileCount() }
mutating func restoreAdaptiveTiles() { guard let memory = adaptiveTileMemory else { return } adaptiveTileMemory = nil // An explicit rearrangement replaces the remembered grouping, never resurrects it. guard let tree, tree.hasSameTopology(as: memory.projection) else { return } self.tree = memory.original.updatingSurvivingFractions(from: tree, since: memory.projection) for stack in tree.stacks { self.tree = self.tree?.mappingStacks { original in var selected = original selected.select(stack.visible) return selected } } }
public func announceMergedTiles(since previous: Workspace, effects: inout [Effect]) { let merged = (previous.tree?.tileCount ?? 0) - (tree?.tileCount ?? 0) if merged > 0 { effects.append(.announce(.tilesMerged(count: merged, limit: effectiveWindowCap))) } }
mutating func constrainTileCount() { restoreAdaptiveTiles() guard let existing = tree, existing.tileCount > effectiveWindowCap else { return } var stacks = existing.stacks if primaryExpandsTile, let primaryWindow, let index = stacks.firstIndex(where: { $0.windows.contains(primaryWindow) }) { // Spatial traversal puts a right-side primary last; capacity must retain its tile. stacks.insert(stacks.remove(at: index), at: 0) } let kept = Array(stacks.prefix(effectiveWindowCap)) let overflow = stacks.dropFirst(effectiveWindowCap).flatMap(\.windows) guard let last = kept.last else { return } var updated: TileTree? = existing for window in overflow { updated = updated?.removing(window) } tree = updated?.mappingStacks { stack in guard stack.windows == last.windows else { return stack } var merged = stack for window in overflow { merged.append(window) } return merged } if layout == .side && layoutVariant == .ultrawide && effectiveWindowCap < 3 { tree = balancedWorkspaceTree(tree?.stacks ?? []) } if let focus { select(focus) } if let tree { adaptiveTileMemory = AdaptiveTileMemory(original: existing, projection: tree) } }
mutating func preserveWideSideSplits(from previous: TileTree) { if primaryOnRight { tree = tree?.mirrored(along: .horizontal) preserveWideSideSplits(from: previous.mirrored(along: .horizontal)) tree = tree?.mirrored(along: .horizontal) return } guard previous.tileCount >= 3, (tree?.tileCount ?? 0) >= 3, case .partition(.horizontal, let fraction, _, let oldSide) = previous, case .partition(.horizontal, _, let main, let newSide)? = tree else { return } let kept = Set(newSide.windows) var sidebar: TileTree? = oldSide for window in oldSide.windows where !kept.contains(window) { sidebar = sidebar?.removing(window) } tree = .partition( axis: .horizontal, fraction: fraction, first: main, second: sidebar?.restoringStacks(newSide.stacks) ?? newSide) }
func resetFraction(at path: [TileEdge.Child], node: TileTree) -> Double { if primaryExpandsTile { if path == mainRatioPath { return primaryOnRight ? 1 - configuredRatio.value : configuredRatio.value } if layoutVariant == .ultrawide && path.isEmpty { return primaryOnRight ? 0.25 : 0.75 } } return LayoutEngine.balancedFraction(node) }}
extension Workspace { /// Primary belongs to the retained tile, independently of spatial traversal order. public var primaryWindow: WindowID? { guard let tree, let member = order.first(where: { tree.contains($0) }) else { return nil } return tree.stack(containing: member)?.visible }
public var primaryExpandsTile: Bool { layout == .side || (usesAdaptiveThreeTiles && tree?.tileCount == 3) }
var usesAdaptiveThreeTiles: Bool { layoutDefaults != nil && layout == .grid && layoutVariant != .portrait }
var primaryOnRight: Bool { guard let primaryWindow, let tree else { return false } switch tree { case .split(.horizontal, _, let first, let second), .partition(.horizontal, _, let first, let second): return second.contains(primaryWindow) && !first.contains(primaryWindow) default: return false } }
func sourceOnRight(_ window: WindowID, frames: [WindowID: Rect], screen: Rect) -> Bool { let area = screen.inset(by: reservedEdges).inset(by: gaps.outer) guard let frame = frames[window] else { return primaryOnRight } let delta = frame.center.xCoordinate - area.center.xCoordinate return abs(delta) < 0.5 ? primaryOnRight : delta > 0 }
mutating func designatePrimary(_ stack: WindowStack) { let members = Set(stack.windows) let tiled = Set(tree?.windows ?? []) let sequence = stack.windows + order.filter { tiled.contains($0) && !members.contains($0) } var iterator = sequence.makeIterator() order = order.map { member in guard tiled.contains(member) else { return member } guard let next = iterator.next() else { preconditionFailure("Primary must retain all tiled members") } return next } }
func balancedWorkspaceTree(_ stacks: [WindowStack]) -> TileTree? { guard layout == .side || (usesAdaptiveThreeTiles && stacks.count == 3) else { return TileTree.balanced(stacks, layout: layout, ratio: ratio, variant: layoutVariant) } var ordered = stacks let members = Set(stacks.flatMap(\.windows)) if let primary = order.first(where: members.contains), let index = ordered.firstIndex(where: { $0.windows.contains(primary) }) { ordered.insert(ordered.remove(at: index), at: 0) } let result = TileTree.balanced( ordered, layout: .side, ratio: ratio, variant: usesAdaptiveThreeTiles ? .standard : layoutVariant) return primaryOnRight ? result?.mirrored(along: .horizontal) : result }
mutating func promotePrimary(_ window: WindowID, onRight: Bool, frames: [WindowID: Rect]) { guard let tree, let source = tree.stack(containing: window) else { return } if primaryExpandsTile { // Work in the unmirrored orientation so divider fractions retain their meaning. let canonical = primaryOnRight ? tree.mirrored(along: .horizontal) : tree var neighbors = tree.stacks.filter { $0.windows != source.windows } neighbors = neighbors.enumerated().sorted { lhs, rhs in let left = frames[lhs.element.visible]?.center.yCoordinate ?? 0 let right = frames[rhs.element.visible]?.center.yCoordinate ?? 0 return left == right ? lhs.offset < rhs.offset : left < right }.map(\.element) let stacks = [source] + neighbors var template: TileTree? if layout == .side { template = canonical } else if case .split(.horizontal, _, .tile, _) = canonical { template = canonical } else { template = TileTree.balanced(stacks, layout: .side, ratio: ratio) } var iterator = stacks.makeIterator() let promoted = template?.mappingStacks { _ in guard let stack = iterator.next() else { preconditionFailure("Primary must retain all tiles") } return stack } self.tree = onRight ? promoted?.mirrored(along: .horizontal) : promoted adaptiveTileMemory = nil alternateSideTree = nil } designatePrimary(source) }}