diff --git a/.gitignore b/.gitignore index 140e9b7..59b55fc 100644 --- a/.gitignore +++ b/.gitignore @@ -29,6 +29,7 @@ Package.resolved # hence it is not needed unless you have added a package configuration file to your project .swiftpm .build/ +.build* # CocoaPods # diff --git a/Package.swift b/Package.swift index 12907a8..1208668 100644 --- a/Package.swift +++ b/Package.swift @@ -22,6 +22,9 @@ import PackageDescription /// system font, and QuickDraw's text. /// - `GraphiteSound`: sampled sounds from 'snd ' resources and AIFF files, /// the codecs that decode them, and the channels and mixer that play them. +/// - `GraphiteWindows`: the Window Manager: windows of every class, the +/// window list, FindWindow, zooming and collapsing, the visible and +/// update regions, and the content's buffer the host flushes. /// - `Graphite`: re-exports the modules above. /// /// Everything here depends only on the Swift standard library, the C @@ -70,6 +73,10 @@ let package = Package( .library( name: "GraphiteSound", targets: ["GraphiteSound"] + ), + .library( + name: "GraphiteWindows", + targets: ["GraphiteWindows"] ) ], // FreeType reads outline fonts; builds without it keep the bitmap font. @@ -125,9 +132,13 @@ let package = Package( name: "GraphiteSound", dependencies: ["GraphiteBase"] ), + .target( + name: "GraphiteWindows", + dependencies: ["GraphiteBase", "GraphiteQuickDraw"] + ), .target( name: "Graphite", - dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound"] + dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound", "GraphiteWindows"] ), .testTarget( name: "GraphiteBaseTests", @@ -160,6 +171,10 @@ let package = Package( .testTarget( name: "GraphiteSoundTests", dependencies: ["GraphiteSound"] + ), + .testTarget( + name: "GraphiteWindowsTests", + dependencies: ["GraphiteWindows", "GraphiteQuickDraw"] ) ] ) diff --git a/README.md b/README.md index 4d1cab4..14f85dc 100644 --- a/README.md +++ b/README.md @@ -27,9 +27,9 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). > **Status:** early development. `GraphiteBase`, `GraphiteTasks`, > `GraphiteFiles`, `GraphiteResources`, `GraphiteAppleEvents`, -> `GraphiteQuickDraw`, `GraphiteText` and `GraphiteSound` are in place, apart -> from the MACE codecs and double-buffered sound. The Toolbox's windows, menus, -> controls and dialogs come next. +> `GraphiteQuickDraw`, `GraphiteText`, `GraphiteSound` and `GraphiteWindows` +> are in place, apart from the MACE codecs and double-buffered sound. The +> Toolbox's menus, controls and dialogs come next. ## Modules @@ -43,6 +43,7 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). | `GraphiteQuickDraw` | QuickDraw's pixels (1 to 8 bits indexed, 16 and 32 bits direct, big-endian on every CPU, in memory of its own or a program's), colors and the system's color tables, regions as real regions with QuickDraw's region records, patterns, transfer modes, ports, devices and offscreen worlds; drawing rectangles, ovals, round rectangles, arcs, polygons, regions and lines with the pen, and CopyBits, CopyMask and ScrollRect between any depths; PICT pictures, version 1 and 2, with PackBits and QuickTime-compressed images through a decoder the host gives. | | `GraphiteText` | Fonts: faces and their metrics, the Font Manager's family numbers and names with the classic fonts' and their substitutes, a built-in bitmap system font (from Pomme), and QuickDraw's text in a port's font, face, size and mode, with the styles a face hasn't drawn from its plain glyphs; ATSUI-style layouts with styled runs, line breaking, measuring, hit testing and drawing, and the text in PICT pictures; and, with the `FreeType` trait (on by default), faces from TrueType, OpenType and other outline fonts, found by family name in the system's font folders. | | `GraphiteSound` | The Sound Manager: sampled sounds from `'snd '` resources (formats 1 and 2, with the standard, compressed and extended headers) and AIFF and AIFF-C files, read to 16-bit PCM; the µ-law, A-law and IMA4 codecs (MACE is recognized but not decoded yet); sound channels with queued commands (`SndDoCommand`) including `callBackCmd`, `waitCmd` and `syncCmd`, immediate ones, volume, pan, pitch, loops and completion; a mixer that renders them to stereo float frames, for an audio device the host provides; and the frequencies of MIDI notes. | +| `GraphiteWindows` | The Window Manager: windows of every class, from documents, dialogs and alerts to palettes, sheets and drawers, each with the standard Mac OS 8 and 9 frame or a window definition the host brings (the WDEF); the window list ordered by layer, `FrontWindow`, and the active document and the active palette; `FindWindow` and every part of a frame; showing, hiding, selecting, zooming between the user and standard states, collapsing; `MoveWindow`, `SizeWindow` and `SetWindowBounds`, with centering, cascading and the alert position; each window's content in an offscreen buffer with its visible region — what no window in front covers — its update region with `BeginUpdate` and `EndUpdate`, and the part of it the host is told to flush. | | `Graphite` | Re-exports the modules above. | Everything depends only on the Swift standard library, the C library diff --git a/Sources/Graphite/Graphite.swift b/Sources/Graphite/Graphite.swift index 060c21c..6633d8f 100644 --- a/Sources/Graphite/Graphite.swift +++ b/Sources/Graphite/Graphite.swift @@ -9,3 +9,4 @@ @_exported import GraphiteQuickDraw @_exported import GraphiteText @_exported import GraphiteSound +@_exported import GraphiteWindows diff --git a/Sources/GraphiteWindows/Window.swift b/Sources/GraphiteWindows/Window.swift new file mode 100644 index 0000000..fe3a90b --- /dev/null +++ b/Sources/GraphiteWindows/Window.swift @@ -0,0 +1,407 @@ +// A window: where it sits on the screen and what its frame is; its title, +// its reference constant and its parent; whether it is shown, collapsed, +// zoomed and active; the buffer its content is drawn in, and the regions +// the Window Manager keeps for it. The host reads these and shows the +// window as it likes; Graphite holds the window, not its pixels on the +// screen. + +import GraphiteBase +import GraphiteQuickDraw + +public final class Window { + + public let windowClass: WindowClass + + /// The window's attributes, which ChangeWindowAttributes changes. + public private(set) var attributes: WindowAttributes + + /// The shape of the window's frame. The standard classes share one. + public let definition: any WindowDefinition + + weak var manager: WindowManager? + + /// SetWindowKind: what the program uses the window for. 2 is a dialog, + /// 8 (userKind) the rest. + public var kindCode: Int16 = 8 + + /// SetWRefCon: whatever the program keeps with the window. + public var referenceConstant: UInt = 0 + + /// The window this one belongs to: a sheet's or a drawer's parent. + public weak var parent: Window? + + /// SetWTitle and GetWTitle. + public var title: PascalString + + /// The structure region's bounds, in global coordinates. A collapsed + /// window's are its title bar's alone. + public private(set) var structureBounds: Rect + + /// The structure's bounds while the window is collapsed; nil while it + /// is not. + private var uncollapsedStructure: Rect? + + /// Whether the window is shown. ShowWindow and HideWindow change it. + public internal(set) var isVisible = false + + /// The part of the content that can be seen, in global coordinates: + /// what no window in front covers and no edge of the desktop hides. + /// The Window Manager keeps it; a host shows the rest as it likes. + public internal(set) var visibleRegion = Region() + + /// The update region, in global coordinates: what needs drawing. + public internal(set) var updateRegion = Region() + + /// What the port's clip and visible regions were before BeginUpdate. + var savedClipRegion: Region? + var savedVisibleRegion: Region? + + /// LockPortBits and UnlockPortBits: the buffer stays where it is + /// either way; programs ask before they touch it. + var portBitsLocks = 0 + + /// The state the window returns to when ZoomWindow zooms it back from + /// the standard state: its content's bounds. GetWindowUserState; + /// SetWindowUserState sets another. + public private(set) var userState: Rect + + /// SetWindowStandardState's answer, for a window the program sized + /// itself rather than letting the definition. + var standardStateOverride: Rect? + + /// The window's content: where the program draws, in local coordinates + /// with (0, 0) at the content's top left. On Mac OS X every window is + /// buffered; Graphite's are too. + public let port: Port + + /// The content's pixels, the buffer the port draws in. + public var pixels: PixelBuffer { + port.pixels! + } + + public init(windowClass: WindowClass, attributes: WindowAttributes, contentBounds: Rect, + title: PascalString = "", definition: (any WindowDefinition)? = nil, manager: WindowManager?) { + self.windowClass = windowClass + self.attributes = attributes + self.definition = definition ?? StandardWindowDefinition() + self.manager = manager + self.title = title + self.userState = contentBounds + let structure = self.definition.structureBounds(around: contentBounds, + of: WindowKind(windowClass: windowClass, attributes: attributes)) + structureBounds = structure + // The main screen's depth, as a window's buffer has on Mac OS X. + let format = manager?.quickDraw.mainDevice?.pixels.format ?? .argb32 + let local = Rect(top: 0, left: 0, bottom: Int16(contentBounds.height), right: Int16(contentBounds.width)) + let pixels = PixelBuffer(bounds: local, format: format) + pixels.fill(local, with: pixels.value(for: .white)) + port = Port(pixels: pixels) + // A window that isn't shown can be drawn in but seen nowhere. + port.visibleRegion = Region() + port.device = manager?.quickDraw.device(for: structure) + } + + public var kind: WindowKind { + WindowKind(windowClass: windowClass, attributes: attributes) + } + + /// What the frame's parts can do, as the window definition reports + /// them. + public var features: WindowFeatures { + definition.features(of: kind) + } + + // MARK: Bounds + + /// The content region's bounds, in global coordinates: empty when the + /// window is collapsed. + public var contentBounds: Rect { + guard uncollapsedStructure == nil else { return .zero } + return definition.contentBounds(within: structureBounds, of: kind, isCollapsed: false) + } + + /// The content's bounds as they are when the window is expanded, even + /// while it is collapsed. + public var uncollapsedContentBounds: Rect { + if let expanded = uncollapsedStructure { + return definition.contentBounds(within: expanded, of: kind, isCollapsed: false) + } + return definition.contentBounds(within: structureBounds, of: kind, isCollapsed: false) + } + + private var isCollapsed: Bool { uncollapsedStructure != nil } + + /// GetWindowBounds: the structure's, the content's, or the port's in + /// global coordinates (which collapsing doesn't change). paramErr for + /// any other region. + public func bounds(of region: WindowRegion) throws(MacError) -> Rect { + switch region { + case .structure: return structureBounds + case .content: return contentBounds + case .globalPort: return uncollapsedContentBounds + default: throw .parameter + } + } + + /// SetWindowBounds: the window's structure or its content, in global + /// coordinates; the other follows around it. paramErr for any other + /// region. + public func setBounds(_ rect: Rect, region: WindowRegion) throws(MacError) { + switch region { + case .structure: + apply(structure: rect) + case .content: + apply(structure: definition.structureBounds(around: rect, of: kind)) + default: + throw .parameter + } + } + + /// MoveWindow: the content's top left moves to (h, v). + public func move(h: Int16, v: Int16, front: Bool = false) { + var content = uncollapsedContentBounds + content.offset(dh: h &- content.left, dv: v &- content.top) + try? setBounds(content, region: .content) + if front { manager?.select(self) } + } + + /// MoveWindowStructure: the structure's top left moves to (h, v). A + /// collapsed window's is its title bar's; the window it stands for + /// moves with it. + public func moveStructure(h: Int16, v: Int16) { + var structure = uncollapsedStructure ?? structureBounds + structure.offset(dh: h &- structure.left, dv: v &- structure.top) + apply(structure: structure) + } + + /// SizeWindow: the content takes a new size, its top left staying + /// where it was. The buffer starts over: the content needs drawing + /// again, whole. + public func size(width: Int16, height: Int16) { + var content = uncollapsedContentBounds + content = Rect(top: content.top, left: content.left, bottom: content.top + height, right: content.left + width) + try? setBounds(content, region: .content) + } + + /// ChangeWindowAttributes. + public func changeAttributes(add: WindowAttributes = [], remove: WindowAttributes = []) { + attributes.subtract(remove) + attributes.formUnion(add) + manager?.recompute() + } + + // MARK: Regions and parts + + /// The structure region, in global coordinates: the window and its + /// frame; a collapsed window's title bar alone. + public var structureRegion: Region { + Region(rect: structureBounds) + } + + /// The content region, in global coordinates. + public var contentRegion: Region { + Region(rect: contentBounds) + } + + /// GetWindowRegion: any of the window's regions, in global + /// coordinates. + public func region(_ code: WindowRegion) -> Region { + switch code { + case .structure: return structureRegion + case .content: return contentRegion + case .update: return updateRegion + case .globalPort: return Region(rect: uncollapsedContentBounds) + case .opaque: return structureRegion + case .titleBar, .titleText, .drag, .closeBox, .zoomBox, .collapseBox, .grow, .titleProxyIcon, .toolbarButton: + return definition.region(code, of: structureBounds, kind: kind, isCollapsed: isCollapsed) + } + } + + /// FindWindow's answer for this window alone: the part the point is + /// on, nil outside the window's structure. + public func hitTest(_ point: Point) -> WindowPart? { + let part = definition.hitTest(point, in: structureBounds, kind: kind, + isCollapsed: isCollapsed, isInStandardState: isInStandardState) + guard part != .noHit else { return nil } + return WindowPart(definition: part) + } + + // MARK: Coordinates + + /// LocalToGlobal: the content's top left is where the port's local + /// coordinates start. + public func localToGlobal(_ point: Point) -> Point { + point + uncollapsedContentBounds.topLeft + } + + /// GlobalToLocal. + public func globalToLocal(_ point: Point) -> Point { + point - uncollapsedContentBounds.topLeft + } + + /// The screen most of the window is on (GetWindowDeviceH). + public var device: GraphicsDevice? { + manager?.quickDraw.device(for: structureBounds) + } + + // MARK: Zooming, collapsing, ordering + + /// IsWindowInStandardState: whether the window is where ZoomWindow + /// would put it. + public var isInStandardState: Bool { + contentBounds == standardState + } + + /// GetWindowStandardState: the content's bounds in the standard state, + /// as large as the desktop allows, centered on it — or the bounds the + /// program set. Without a Window Manager, the window's own. + public var standardState: Rect { + if let override = standardStateOverride { return override } + guard let manager else { return contentBounds } + let structure = definition.standardBounds(of: kind, + contentSize: Point(v: Int16(uncollapsedContentBounds.height), + h: Int16(uncollapsedContentBounds.width)), + on: manager.mainDesktopBounds) + return definition.contentBounds(within: structure, of: kind, isCollapsed: false) + } + + /// SetWindowUserState: where the window returns to when it zooms back + /// from the standard state. + public func setUserState(_ rect: Rect) { + userState = rect + } + + /// SetWindowStandardState. + public func setStandardState(_ rect: Rect) { + standardStateOverride = rect + } + + /// ZoomWindow: between the user state and the standard state, saving + /// the one it leaves. A window that can't zoom does nothing. With + /// `front`, the window comes to the front and is made active first. + public func zoom(front: Bool = false) { + guard !attributes.intersection([.horizontalZoom, .verticalZoom]).isEmpty else { return } + if front { manager?.select(self) } + if isInStandardState { + guard !userState.isEmpty else { return } + try? setBounds(userState, region: .content) + } else { + userState = contentBounds + try? setBounds(standardState, region: .content) + } + } + + /// CollapseWindow: the window to its title bar, or back. The content + /// keeps its pixels either way. A window without a title bar can't + /// collapse. + public func collapse(_ collapse: Bool = true) { + guard isCollapsed != collapse else { return } + if collapse { + let bar = definition.region(.titleBar, of: structureBounds, kind: kind, isCollapsed: false) + guard !bar.isEmpty else { return } + uncollapsedStructure = structureBounds + structureBounds = Rect(top: structureBounds.top, left: structureBounds.left, + bottom: min(structureBounds.top + Int16(bar.bounds.height), structureBounds.bottom), + right: structureBounds.right) + } else { + structureBounds = uncollapsedStructure ?? structureBounds + uncollapsedStructure = nil + } + manager?.recompute() + } + + /// ExpandWindow. + public func expand() { + collapse(false) + } + + /// ShowWindow: the window is seen, in front of its layer, and active + /// in its scope. + public func show() { + manager?.show(self) + } + + /// HideWindow. + public func hide() { + manager?.hide(self) + } + + /// SelectWindow: to the front, and active. A hidden window is shown. + public func select() { + manager?.select(self) + } + + /// BringToFront. + public func bringToFront() { + manager?.bringToFront(self) + } + + /// SendBehind: behind another window, which doesn't move. + public func sendBehind(_ window: Window) { + manager?.sendBehind(self, behind: window) + } + + /// ActivateWindow. + public func activate(_ activate: Bool) { + manager?.activate(self, activate) + } + + /// IsWindowActive. + public var isActive: Bool { + guard let manager else { return false } + switch windowClass.activationScope { + case .all: return manager.activeWindow === self + case .independent: return manager.activeFloatingWindow === self + case .none: return false + } + } + + /// DisposeWindow: the window is gone from the list. + public func dispose() { + manager?.dispose(self) + } + + // MARK: Changes the Window Manager hears of + + /// Moves the window, sizes its buffer to its content if the content + /// grew or shrank, and tells the Window Manager. + internal func apply(structure: Rect) { + let oldSize = Point(v: Int16(uncollapsedContentBounds.height), h: Int16(uncollapsedContentBounds.width)) + if isCollapsed { + uncollapsedStructure = structure + structureBounds = titleStrip(of: structure) + } else { + structureBounds = structure + } + let content = uncollapsedContentBounds + let size = Point(v: Int16(content.height), h: Int16(content.width)) + if size != oldSize { + rebuildContent(ofSize: size) + // The buffer starts over: the content needs drawing, whole. + if !attributes.contains(.noUpdates) { updateRegion = Region(rect: content) } + } + manager?.recompute() + } + + /// The structure's title bar alone, of the shape a collapsed window + /// keeps. + private func titleStrip(of structure: Rect) -> Rect { + let bar = definition.region(.titleBar, of: structure, kind: kind, isCollapsed: false) + guard !bar.isEmpty else { return structure } + return Rect(top: structure.top, left: structure.left, + bottom: min(structure.top + Int16(bar.bounds.height), structure.bottom), right: structure.right) + } + + /// A new buffer for a resized content, white as a new window's is. The + /// old contents aren't kept: a resized window draws itself again. + private func rebuildContent(ofSize size: Point) { + guard let old = port.pixels else { return } + let local = Rect(top: 0, left: 0, bottom: size.v, right: size.h) + let pixels = PixelBuffer(bounds: local, format: old.format, colorTable: old.colorTable) + pixels.reservedEntries = old.reservedEntries + pixels.fill(local, with: pixels.value(for: .white)) + port.pixels = pixels + port.pixelBounds = local + port.portRect = local + } +} diff --git a/Sources/GraphiteWindows/WindowDefinition.swift b/Sources/GraphiteWindows/WindowDefinition.swift new file mode 100644 index 0000000..e6c0192 --- /dev/null +++ b/Sources/GraphiteWindows/WindowDefinition.swift @@ -0,0 +1,229 @@ +// Window definitions, the WDEFs, as Swift sees them: the shape of a +// window's frame — where its content sits in its structure, where its +// title bar and its boxes are, what its parts can do — and the size its +// structure takes when the window is zoomed. The standard window classes +// have theirs built in, the look of Mac OS 8 and 9; the layer that exports +// Carbon implements this over a guest's WDEF. + +import GraphiteBase +import GraphiteQuickDraw + +/// A window definition procedure: the shape of a window of a kind. The +/// Window Manager asks it for everything the frame decides and nothing the +/// program does. +public protocol WindowDefinition: Sendable { + + /// kWindowMsgGetFeatures: what the frame's parts can do. + func features(of kind: WindowKind) -> WindowFeatures + + /// kWindowMsgCalculateShape: where the content sits in the structure. + /// A collapsed window has none. + func contentBounds(within structure: Rect, of kind: WindowKind, isCollapsed: Bool) -> Rect + + /// Where the structure sits around the content: what the Window Manager + /// works out for a window placed by its content, as CreateNewWindow + /// places it. + func structureBounds(around content: Rect, of kind: WindowKind) -> Rect + + /// kWindowMsgGetRegion: a part of the frame, in the structure's + /// coordinates. A part the window doesn't have is the empty region. + func region(_ code: WindowRegion, of structure: Rect, kind: WindowKind, isCollapsed: Bool) -> Region + + /// kWindowMsgHitTest: the part of the window a point of its structure + /// is on, wNoHit outside it. `isInStandardState` tells the zoom box's + /// state. + func hitTest(_ point: Point, in structure: Rect, kind: WindowKind, + isCollapsed: Bool, isInStandardState: Bool) -> WindowDefPart + + /// ZoomWindow's standard state: the structure the window takes to be + /// as large as `screen` allows, centered on it. The zoom attributes say + /// which of the window's dimensions grow to fill it; `contentSize` is + /// the window's own, which the others keep. + func standardBounds(of kind: WindowKind, contentSize: Point, on screen: Rect) -> Rect +} + +/// The definition the standard window classes use, the look of Mac OS 8 +/// and 9: a title bar with the boxes the attributes give it, a four-pixel +/// frame around a document's content, a shorter title bar and no frame on +/// a palette, and nothing at all on a frameless window. +public struct StandardWindowDefinition: WindowDefinition { + + public init() {} + + // MARK: The frame's shape + + /// The title bar's height, 0 for a class without one. + private func titleBarHeight(of kind: WindowKind) -> Int16 { + guard !kind.attributes.contains(.noTitleBar) else { return 0 } + switch kind.windowClass { + case .alert, .movableAlert, .modal, .movableModal, .document: return 20 + case .floating, .utility, .toolbar: return 17 + default: return 0 + } + } + + /// The frame around the content's left, right and bottom edges: a + /// document's platinum border, a plain window's single pixel, nothing + /// on a frameless window. + private func frameThickness(of kind: WindowKind) -> Int16 { + switch kind.windowClass { + case .alert, .movableAlert, .modal, .movableModal, .document: return 4 + case .plain, .alternatePlain: return 1 + default: return 0 + } + } + + private func hasTitleBar(of kind: WindowKind) -> Bool { + titleBarHeight(of: kind) > 0 + } + + public func features(of kind: WindowKind) -> WindowFeatures { + let attributes = kind.attributes + var features: WindowFeatures = [.canGetWindowRegion, .isOpaque] + if attributes.contains(.resizable) { features.insert(.canGrow) } + if attributes.contains(.fullZoom) { features.insert(.canZoom) } + if attributes.contains(.collapseBox) { features.insert(.canCollapse) } + if hasTitleBar(of: kind) { + features.formUnion([.hasTitleBar, .supportsModifiedBit, .canMeasureTitle]) + } + switch kind.windowClass { + case .modal, .movableModal: features.insert(.isModal) + case .alert, .movableAlert, .sheetAlert: features.insert(.isAlert) + default: break + } + return features + } + + public func contentBounds(within structure: Rect, of kind: WindowKind, isCollapsed: Bool) -> Rect { + guard !isCollapsed else { return .zero } + let title = titleBarHeight(of: kind), frame = frameThickness(of: kind) + let top = title > 0 ? title : frame + return Rect(top: structure.top + top, left: structure.left + frame, + bottom: structure.bottom - frame, right: structure.right - frame) + } + + public func structureBounds(around content: Rect, of kind: WindowKind) -> Rect { + let title = titleBarHeight(of: kind), frame = frameThickness(of: kind) + let top = title > 0 ? title : frame + return Rect(top: content.top - top, left: content.left - frame, + bottom: content.bottom + frame, right: content.right + frame) + } + + // MARK: The frame's parts + + /// A box in the title bar: 11 pixels square, four from a side, set to + /// the bar's middle. + private func boxRect(topOf bar: Int16, fromEdge: Int16, kind: WindowKind) -> Rect { + let top = bar + (titleBarHeight(of: kind) - 11) / 2 + return Rect(top: top, left: fromEdge, bottom: top + 11, right: fromEdge + 11) + } + + private func closeBoxRect(in structure: Rect, kind: WindowKind) -> Rect? { + guard kind.attributes.contains(.closeBox) else { return nil } + return boxRect(topOf: structure.top, fromEdge: structure.left + 4, kind: kind) + } + + private func zoomBoxRect(in structure: Rect, kind: WindowKind) -> Rect? { + guard kind.attributes.contains(.fullZoom) else { return nil } + return boxRect(topOf: structure.top, fromEdge: structure.right - 15, kind: kind) + } + + private func collapseBoxRect(in structure: Rect, kind: WindowKind) -> Rect? { + guard kind.attributes.contains(.collapseBox) else { return nil } + // A zoom box, when there is one, sits at the right edge; the + // collapse box takes the next place to its left. + let fromEdge = kind.attributes.contains(.fullZoom) ? structure.right - 30 : structure.right - 15 + return boxRect(topOf: structure.top, fromEdge: fromEdge, kind: kind) + } + + /// The grow box: the bottom-right corner of the content, where a + /// document's scroll bars meet. + private func growRect(in structure: Rect, kind: WindowKind) -> Rect? { + guard kind.attributes.contains(.resizable) else { return nil } + let content = contentBounds(within: structure, of: kind, isCollapsed: false) + guard !content.isEmpty, content.width > 15, content.height > 15 else { return nil } + return Rect(top: content.bottom - 15, left: content.right - 15, bottom: content.bottom, right: content.right) + } + + private func titleBarRect(of structure: Rect, kind: WindowKind) -> Rect? { + let height = titleBarHeight(of: kind) + guard height > 0 else { return nil } + return Rect(top: structure.top, left: structure.left, bottom: structure.top + height, right: structure.right) + } + + public func region(_ code: WindowRegion, of structure: Rect, kind: WindowKind, isCollapsed: Bool) -> Region { + switch code { + case .structure: + return Region(rect: structure) + case .content: + return Region(rect: contentBounds(within: structure, of: kind, isCollapsed: isCollapsed)) + case .grow: + return (isCollapsed ? nil : growRect(in: structure, kind: kind)).map { Region(rect: $0) } ?? Region() + case .update, .globalPort: + // The Window Manager's own, which it answers before asking the + // definition. + return Region() + case .titleBar, .titleText, .drag, .closeBox, .zoomBox, .collapseBox, .titleProxyIcon, .toolbarButton, .opaque: + guard let bar = titleBarRect(of: structure, kind: kind) else { return Region() } + let close = closeBoxRect(in: structure, kind: kind) + let zoom = isCollapsed ? nil : zoomBoxRect(in: structure, kind: kind) + let collapse = collapseBoxRect(in: structure, kind: kind) + switch code { + case .titleBar: + return Region(rect: bar) + case .titleText: + let left = (close?.right ?? bar.left) + 4 + let right = [zoom?.left, collapse?.left].compactMap { $0 }.min().map { $0 - 4 } ?? bar.right - 4 + guard left < right else { return Region() } + return Region(rect: Rect(top: bar.top, left: left, bottom: bar.bottom, right: right)) + case .drag: + var drag = Region(rect: bar) + for box in [close, zoom, collapse] { + if let box { drag = drag.subtracting(Region(rect: box)) } + } + return drag + case .closeBox: + return close.map { Region(rect: $0) } ?? Region() + case .zoomBox: + return zoom.map { Region(rect: $0) } ?? Region() + case .collapseBox: + return collapse.map { Region(rect: $0) } ?? Region() + default: + return Region() + } + } + } + + public func hitTest(_ point: Point, in structure: Rect, kind: WindowKind, + isCollapsed: Bool, isInStandardState: Bool) -> WindowDefPart { + guard structure.contains(point) else { return .noHit } + if hasTitleBar(of: kind), let bar = titleBarRect(of: structure, kind: kind), bar.contains(point) { + if let box = closeBoxRect(in: structure, kind: kind), Region(rect: box).contains(point) { return .goAway } + // A collapsed window keeps its close and collapse boxes but + // shows no zoom box. + if !isCollapsed, let box = zoomBoxRect(in: structure, kind: kind), Region(rect: box).contains(point) { + return isInStandardState ? .zoomOut : .zoomIn + } + if let box = collapseBoxRect(in: structure, kind: kind), Region(rect: box).contains(point) { return .collapseBox } + return .drag + } + if !isCollapsed, let box = growRect(in: structure, kind: kind), Region(rect: box).contains(point) { + return .grow + } + if contentBounds(within: structure, of: kind, isCollapsed: isCollapsed).contains(point) { + return .content + } + return .structure + } + + public func standardBounds(of kind: WindowKind, contentSize: Point, on screen: Rect) -> Rect { + let attributes = kind.attributes + let width = attributes.contains(.horizontalZoom) ? screen.width : Int(contentSize.h) + let height = attributes.contains(.verticalZoom) ? screen.height : Int(contentSize.v) + // Centered on the screen, at its edge where the window fills it. + let left = screen.left + Int16(clamping: (screen.width - width) / 2) + let top = screen.top + Int16(clamping: (screen.height - height) / 2) + return Rect(top: top, left: left, + bottom: top + Int16(clamping: height), right: left + Int16(clamping: width)) + } +} diff --git a/Sources/GraphiteWindows/WindowKind.swift b/Sources/GraphiteWindows/WindowKind.swift new file mode 100644 index 0000000..c32217d --- /dev/null +++ b/Sources/GraphiteWindows/WindowKind.swift @@ -0,0 +1,372 @@ +// The kinds of windows and their furniture: the class, which orders and +// activates them; the attributes, which give them close boxes, zoom boxes +// and the rest; the parts FindWindow answers with; the regions +// GetWindowRegion takes; and the features a window definition reports. + +import GraphiteBase + +/// A window's class: how the Window Manager orders it above the others, +/// when it can be active, and whether it floats above the documents. +/// CreateNewWindow takes one. +public enum WindowClass: UInt32, Hashable, Sendable { + + /// An alert: the user's attention at once. + case alert = 1 + /// A movable alert: an alert the user can drag, which lets the user go + /// on working in other applications. + case movableAlert = 2 + /// A modal window: a dialog the user must finish with first. + case modal = 3 + /// A movable modal window. + case movableModal = 4 + /// A floating window: a palette or an inspector above the documents. + case floating = 5 + /// A document window. + case document = 6 + /// A utility window: like a floating window, but above every + /// application's documents. + case utility = 8 + /// A help window: a help tag, with no frame. + case help = 10 + /// A sheet: a dialog attached to its parent window. + case sheet = 11 + /// A toolbar window: a palette below the floating windows. + case toolbar = 12 + /// A plain window: a one-pixel frame and no title bar. + case plain = 13 + /// An overlay window: transparent, above every other window, for + /// drawing over them all. + case overlay = 14 + /// A sheet alert, like a sheet. + case sheetAlert = 15 + /// An alternate plain window: a plain window with a black shadow. + case alternatePlain = 16 + /// A simple window: no frame at all; everything in it is the program's. + case simple = 18 + /// A drawer: a window that slides out from under its parent. + case drawer = 20 + + /// Whether the class floats: a palette above the documents, ordered + /// among themselves, which FrontWindow skips. + public var isFloating: Bool { + self == .floating || self == .utility || self == .toolbar + } + + /// The layer the window keeps: the Window Manager holds windows of a + /// higher layer in front of those of a lower one, however the program + /// orders them. Overlays are above all, help windows above them but + /// the palettes, alerts and modals above the palettes, and the + /// document classes at the bottom. + public var layer: Int { + switch self { + case .overlay: 7 + case .help: 6 + case .alert, .movableAlert, .modal, .movableModal, .sheet, .sheetAlert: 5 + case .floating, .utility: 4 + case .toolbar: 3 + default: 2 + } + } + + /// kWindowActivationScopeNone, Independent or All: when the window + /// can be the active one. Floating windows are active independently of + /// the documents; help windows, overlays and toolbars never are. + public var activationScope: WindowActivationScope { + switch self { + case .floating, .utility: .independent + case .help, .overlay, .toolbar: .none + default: .all + } + } +} + +/// kWindowActivationScope: which windows a window is active among. +public enum WindowActivationScope: Hashable, Sendable { + + /// Never active. + case none + + /// Active when frontmost among the floating windows, whatever the + /// documents are doing. + case independent + + /// Active when frontmost among the documents. + case all +} + +/// A window's class and attributes together: what a window definition is +/// asked about, and what a window's parts answer with. Classic procIDs +/// and variations map to these. +public struct WindowKind: Hashable, Sendable { + + public var windowClass: WindowClass + + public var attributes: WindowAttributes + + public init(windowClass: WindowClass, attributes: WindowAttributes = []) { + self.windowClass = windowClass + self.attributes = attributes + } +} + +/// WindowAttributes: a window's furniture and behavior, the bits +/// CreateNewWindow takes. Graphite reads the ones that govern the window's +/// shape and its parts (close box, zoom, collapse, resize, updates, +/// activation, clicks); the ones that describe the host's look (textured, +/// shadowed, live resize) it keeps for the layer that exports Carbon. +public struct WindowAttributes: OptionSet, Hashable, Sendable { + + public var rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + /// kWindowCloseBoxAttribute. + public static var closeBox: WindowAttributes { WindowAttributes(rawValue: 1 << 0) } + /// kWindowHorizontalZoomAttribute. + public static var horizontalZoom: WindowAttributes { WindowAttributes(rawValue: 1 << 1) } + /// kWindowVerticalZoomAttribute. + public static var verticalZoom: WindowAttributes { WindowAttributes(rawValue: 1 << 2) } + /// kWindowFullZoomAttribute: both zooms. + public static var fullZoom: WindowAttributes { [.horizontalZoom, .verticalZoom] } + /// kWindowCollapseBoxAttribute. + public static var collapseBox: WindowAttributes { WindowAttributes(rawValue: 1 << 3) } + /// kWindowResizableAttribute. + public static var resizable: WindowAttributes { WindowAttributes(rawValue: 1 << 4) } + /// kWindowSideTitlebarAttribute. + public static var sideTitlebar: WindowAttributes { WindowAttributes(rawValue: 1 << 5) } + /// kWindowToolbarButtonAttribute. + public static var toolbarButton: WindowAttributes { WindowAttributes(rawValue: 1 << 6) } + /// kWindowUnifiedTitleAndToolbarAttribute. + public static var unifiedTitleAndToolbar: WindowAttributes { WindowAttributes(rawValue: 1 << 7) } + /// kWindowMetalAttribute. + public static var textured: WindowAttributes { WindowAttributes(rawValue: 1 << 8) } + /// kWindowNoTitleBarAttribute. + public static var noTitleBar: WindowAttributes { WindowAttributes(rawValue: 1 << 9) } + /// kWindowTexturedSquareCornersAttribute. + public static var texturedSquareCorners: WindowAttributes { WindowAttributes(rawValue: 1 << 10) } + /// kWindowMetalNoContentSeparatorAttribute. + public static var noTexturedContentSeparator: WindowAttributes { WindowAttributes(rawValue: 1 << 11) } + /// kWindowHasRoundBottomBarCornersAttribute. + public static var roundBottomBarCorners: WindowAttributes { WindowAttributes(rawValue: 1 << 12) } + /// kWindowDoesNotCycleAttribute. + public static var doesNotCycle: WindowAttributes { WindowAttributes(rawValue: 1 << 15) } + /// kWindowNoUpdatesAttribute: the window keeps no update region, and + /// InvalWindowRect does nothing. + public static var noUpdates: WindowAttributes { WindowAttributes(rawValue: 1 << 16) } + /// kWindowNoActivatesAttribute. + public static var noActivates: WindowAttributes { WindowAttributes(rawValue: 1 << 17) } + /// kWindowOpaqueForEventsAttribute: clicks pass through the window. + public static var opaqueForEvents: WindowAttributes { WindowAttributes(rawValue: 1 << 18) } + /// kWindowCompositingAttribute. + public static var compositing: WindowAttributes { WindowAttributes(rawValue: 1 << 19) } + /// kWindowHighResolutionCapableAttribute. + public static var highResolutionCapable: WindowAttributes { WindowAttributes(rawValue: 1 << 20) } + /// kWindowNoShadowAttribute. + public static var noShadow: WindowAttributes { WindowAttributes(rawValue: 1 << 21) } + /// kWindowCanBeVisibleWithoutLoginAttribute. + public static var canBeVisibleWithoutLogin: WindowAttributes { WindowAttributes(rawValue: 1 << 22) } + /// kWindowAsyncDragAttribute. + public static var asyncDrag: WindowAttributes { WindowAttributes(rawValue: 1 << 23) } + /// kWindowStandardHandlerAttribute. + public static var standardHandler: WindowAttributes { WindowAttributes(rawValue: 1 << 25) } + /// kWindowHideOnFullScreenAttribute. + public static var hideOnFullScreen: WindowAttributes { WindowAttributes(rawValue: 1 << 26) } + /// kWindowInWindowMenuAttribute. + public static var inWindowMenu: WindowAttributes { WindowAttributes(rawValue: 1 << 27) } + /// kWindowLiveResizeAttribute. + public static var liveResize: WindowAttributes { WindowAttributes(rawValue: 1 << 28) } + /// kWindowIgnoreClicksAttribute: clicks pass through the window. + public static var ignoreClicks: WindowAttributes { WindowAttributes(rawValue: 1 << 29) } + /// kWindowNoConstrainAttribute. + public static var noConstrain: WindowAttributes { WindowAttributes(rawValue: 0x8000_0000) } + + /// kWindowStandardDocumentAttributes: the furniture a document window + /// usually has. + public static var standardDocument: WindowAttributes { [.closeBox, .fullZoom, .collapseBox, .resizable] } + + /// kWindowStandardFloatingAttributes. + public static var standardFloating: WindowAttributes { [.closeBox, .collapseBox] } +} + +/// The features a window definition reports of a frame (kWindowMsgGetFeatures): +/// what its parts can do. +public struct WindowFeatures: OptionSet, Hashable, Sendable { + + public var rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + /// kWindowCanGrow: the frame has a grow box. + public static var canGrow: WindowFeatures { WindowFeatures(rawValue: 1 << 0) } + /// kWindowCanZoom. + public static var canZoom: WindowFeatures { WindowFeatures(rawValue: 1 << 1) } + /// kWindowCanCollapse. + public static var canCollapse: WindowFeatures { WindowFeatures(rawValue: 1 << 2) } + /// kWindowIsModal. + public static var isModal: WindowFeatures { WindowFeatures(rawValue: 1 << 3) } + /// kWindowCanGetWindowRegion. + public static var canGetWindowRegion: WindowFeatures { WindowFeatures(rawValue: 1 << 4) } + /// kWindowIsAlert. + public static var isAlert: WindowFeatures { WindowFeatures(rawValue: 1 << 5) } + /// kWindowHasTitleBar. + public static var hasTitleBar: WindowFeatures { WindowFeatures(rawValue: 1 << 6) } + /// kWindowSupportsDragHilite. + public static var supportsDragHilite: WindowFeatures { WindowFeatures(rawValue: 1 << 7) } + /// kWindowSupportsModifiedBit. + public static var supportsModifiedBit: WindowFeatures { WindowFeatures(rawValue: 1 << 8) } + /// kWindowCanDrawInCurrentPort. + public static var canDrawInCurrentPort: WindowFeatures { WindowFeatures(rawValue: 1 << 9) } + /// kWindowCanSetupProxyDragImage. + public static var canSetupProxyDragImage: WindowFeatures { WindowFeatures(rawValue: 1 << 10) } + /// kWindowCanMeasureTitle. + public static var canMeasureTitle: WindowFeatures { WindowFeatures(rawValue: 1 << 11) } + /// kWindowWantsDisposeAtProcessDeath. + public static var wantsDisposeAtProcessDeath: WindowFeatures { WindowFeatures(rawValue: 1 << 12) } + /// kWindowSupportsGetGrowImageRegion. + public static var supportsGetGrowImageRegion: WindowFeatures { WindowFeatures(rawValue: 1 << 13) } + /// kWindowIsOpaque. + public static var isOpaque: WindowFeatures { WindowFeatures(rawValue: 1 << 14) } +} + +/// A region of a window (kWindowRegionCode): the structure and the content, +/// which GetWindowBounds also takes, and the parts of the frame. +public enum WindowRegion: UInt16, Hashable, Sendable { + + /// kWindowTitleBarRgn. + case titleBar = 0 + /// kWindowTitleTextRgn. + case titleText = 1 + /// kWindowCloseBoxRgn. + case closeBox = 2 + /// kWindowZoomBoxRgn. + case zoomBox = 3 + /// kWindowDragRgn: the part of the title bar DragWindow drags by. + case drag = 5 + /// kWindowGrowRgn. + case grow = 6 + /// kWindowCollapseBoxRgn. + case collapseBox = 7 + /// kWindowTitleProxyIconRgn. + case titleProxyIcon = 8 + /// kWindowStructureRgn: the window and its frame. + case structure = 32 + /// kWindowContentRgn: where the program draws; empty when the window + /// is collapsed. + case content = 33 + /// kWindowUpdateRgn: what needs drawing. + case update = 34 + /// kWindowOpaqueRgn. + case opaque = 35 + /// kWindowGlobalPortRgn: the content in global coordinates, not + /// affected by collapsing. + case globalPort = 40 + /// kWindowToolbarButtonRgn. + case toolbarButton = 41 +} + +/// A window definition's answer to kWindowMsgHitTest: the part of the +/// frame a point of the structure is on. +public enum WindowDefPart: Int16, Hashable, Sendable { + + /// wNoHit. + case noHit = 0 + /// wInContent. + case content = 1 + /// wInDrag. + case drag = 2 + /// wInGrow. + case grow = 3 + /// wInGoAway. + case goAway = 4 + /// wInZoomIn: the zoom box, the window in its user state. + case zoomIn = 5 + /// wInZoomOut: the zoom box, the window in its standard state. + case zoomOut = 6 + /// wInCollapseBox. + case collapseBox = 9 + /// wInProxyIcon. + case proxyIcon = 10 + /// wInToolbarButton. + case toolbarButton = 11 + /// wInStructure: the frame, out of the parts above. + case structure = 13 +} + +/// A part of a window, as FindWindow answers (inDesk, inContent, inDrag, +/// and the rest). inNoWindow is inDesk's other name; FindWindow answers +/// it for a point no window is at. +public enum WindowPart: Int16, Hashable, Sendable { + + /// inDesk. + case desk = 0 + /// inMenuBar. + case menuBar = 1 + /// inSysWindow. + case systemWindow = 2 + /// inContent. + case content = 3 + /// inDrag. + case drag = 4 + /// inGrow. + case grow = 5 + /// inGoAway. + case goAway = 6 + /// inZoomIn. + case zoomIn = 7 + /// inZoomOut. + case zoomOut = 8 + /// inCollapseBox. + case collapseBox = 11 + /// inProxyIcon. + case proxyIcon = 12 + /// inToolbarButton. + case toolbarButton = 13 + /// inStructure. + case structure = 15 + + /// The part a window definition's hit test names. + init(definition part: WindowDefPart) { + switch part { + case .content: self = .content + case .drag: self = .drag + case .grow: self = .grow + case .goAway: self = .goAway + case .zoomIn: self = .zoomIn + case .zoomOut: self = .zoomOut + case .collapseBox: self = .collapseBox + case .proxyIcon: self = .proxyIcon + case .toolbarButton: self = .toolbarButton + case .structure, .noHit: self = .structure + } + } +} + +/// How RepositionWindow places a window: centered, cascaded or at the +/// alert position, on the main screen or by a parent window. +public enum WindowPositionMethod: UInt32, Hashable, Sendable { + + /// kWindowCenterOnMainScreen. + case centerOnMainScreen = 1 + /// kWindowCenterOnParentWindow. + case centerOnParentWindow = 2 + /// kWindowCenterOnParentWindowScreen. + case centerOnParentWindowScreen = 3 + /// kWindowCascadeOnMainScreen. + case cascadeOnMainScreen = 4 + /// kWindowCascadeOnParentWindow. + case cascadeOnParentWindow = 5 + /// kWindowCascadeOnParentWindowScreen. + case cascadeOnParentWindowScreen = 6 + /// kWindowAlertPositionOnMainScreen. + case alertPositionOnMainScreen = 7 + /// kWindowAlertPositionOnParentWindow. + case alertPositionOnParentWindow = 8 + /// kWindowAlertPositionOnParentWindowScreen. + case alertPositionOnParentWindowScreen = 9 + /// kWindowCascadeStartAtParentWindowScreen. + case cascadeStartAtParentWindowScreen = 10 +} diff --git a/Sources/GraphiteWindows/WindowManager.swift b/Sources/GraphiteWindows/WindowManager.swift new file mode 100644 index 0000000..9a5cac3 --- /dev/null +++ b/Sources/GraphiteWindows/WindowManager.swift @@ -0,0 +1,341 @@ +// The Window Manager: a program's windows, front to back by class and +// selection; the desktop they sit on, which is QuickDraw's screens without +// the menu bar; FindWindow; and the showing, hiding, ordering, activating +// and zooming that keep every window's visible region and update region +// as the classic Window Manager kept them. The host shows the windows as +// it likes; Graphite holds their state. + +import GraphiteBase +import GraphiteQuickDraw + +/// A window the manager keeps a weak hold of, as part of its list. +private final class WindowBox { + + weak var window: Window? + + init(_ window: Window) { + self.window = window + } +} + +public final class WindowManager { + + /// The screens the windows sit on, and the current port and device. + public let quickDraw: QuickDraw + + /// The menu bar's height on the main screen, which no window draws + /// over and FindWindow keeps for the desk. Zero on a host with none. + public var menuBarHeight: Int16 = 20 + + /// How far apart cascaded windows sit: a title bar's worth, as an + /// appearance's own cascade was. + public var cascadeOffset = Point(v: 20, h: 20) + + /// GetCascadeOrigin: where the next window cascaded on the main screen + /// goes. The first is at the desktop's upper-left corner; each one + /// after is below and to the right of the last, from the corner again + /// when they would run off the desktop. + public var cascadeOrigin: Point + + /// QDFlushPortBuffer reaches this: the part of a window's content + /// buffer that has changed, in global coordinates. The host copies it + /// from the buffer to the screen as it likes. + public var flushObserver: ((Window, Region) -> Void)? + + /// The frontmost window the user works in: FrontWindow, which skips + /// the palettes, help windows and overlays. + public var frontWindow: Window? { + windows.first { + $0.isVisible && !$0.windowClass.isFloating && $0.windowClass.activationScope != .none + } + } + + /// The frontmost palette: the frontmost visible window of the + /// floating classes. + public var frontFloatingWindow: Window? { + windows.first { $0.isVisible && $0.windowClass.isFloating } + } + + /// The active window among the documents: the one SelectWindow last + /// brought to the front. + public internal(set) var activeWindow: Window? + + /// The active palette, active independently of the documents. + public internal(set) var activeFloatingWindow: Window? + + private var boxes: [WindowBox] = [] + + public init(quickDraw: QuickDraw) { + self.quickDraw = quickDraw + if let main = quickDraw.mainDevice { + cascadeOrigin = Point(v: main.bounds.top + menuBarHeight, h: main.bounds.left) + } else { + cascadeOrigin = .zero + } + } + + /// The program's windows, front to back. The Window Manager holds them + /// weakly: a window the program lets go of is gone from the list, its + /// pixels with it. + public var windows: [Window] { + boxes.removeAll { $0.window == nil } + return boxes.compactMap(\.window) + } + + // MARK: Making windows + + /// CreateNewWindow: a window of a class, with attributes, its content + /// at `bounds` in global coordinates, its title, and a window + /// definition — the standard one when none is given. paramErr for + /// empty bounds. + @discardableResult + public func newWindow(windowClass: WindowClass = .document, attributes: WindowAttributes = [], + bounds content: Rect, title: PascalString = "", + definition: (any WindowDefinition)? = nil) throws(MacError) -> Window { + guard !content.isEmpty else { throw .parameter } + let window = Window(windowClass: windowClass, attributes: attributes, contentBounds: content, + title: title, definition: definition, manager: self) + moveToFrontOfLayer(window) + return window + } + + /// GetWindowFromPort: the window a content port belongs to. + public func window(withPort port: Port) -> Window? { + windows.first { $0.port === port } + } + + // MARK: Finding + + /// FindWindow: the part of the desktop a point is on, and the window: + /// the frontmost whose structure holds it, nil over the menu bar (inMenuBar) + /// or the desk (inDesk). A window with the ignore-clicks or + /// opaque-for-events attribute lets the click through to what's + /// behind it. + public func findWindow(at point: Point) -> (part: WindowPart, window: Window?) { + if let menuBar = menuBarBounds, menuBar.contains(point) { + return (.menuBar, nil) + } + for window in windows where window.isVisible { + guard !window.attributes.contains(.ignoreClicks), !window.attributes.contains(.opaqueForEvents) else { continue } + if let part = window.hitTest(point) { + return (part, window) + } + } + return (.desk, nil) + } + + // MARK: The desktop + + /// The menu bar, on the main screen. + var menuBarBounds: Rect? { + guard menuBarHeight > 0, let main = quickDraw.mainDevice else { return nil } + return Rect(top: main.bounds.top, left: main.bounds.left, + bottom: main.bounds.top + menuBarHeight, right: main.bounds.right) + } + + /// GetGrayRgn's rectangle on the main screen: the screen below the + /// menu bar, where a window zooms to. + var mainDesktopBounds: Rect { + guard let main = quickDraw.mainDevice else { return .zero } + return Rect(top: main.bounds.top + menuBarHeight, left: main.bounds.left, + bottom: main.bounds.bottom, right: main.bounds.right) + } + + /// The screen most of a window is on, below that screen's menu bar if + /// it has one. + private func desktopBounds(of window: Window) -> Rect { + guard let device = quickDraw.device(for: window.structureBounds) else { return mainDesktopBounds } + let bounds = device.bounds + let top = bounds.top + (device === quickDraw.mainDevice ? menuBarHeight : 0) + return Rect(top: top, left: bounds.left, bottom: bounds.bottom, right: bounds.right) + } + + /// The desktop: every screen, without the menu bar. No window is + /// visible outside it. + public var desktopRegion: Region { + var region = Region() + for screen in quickDraw.screens { + region = region.union(Region(rect: screen.bounds)) + } + if let menuBar = menuBarBounds { + region = region.subtracting(Region(rect: menuBar)) + } + return region + } + + // MARK: Positioning + + /// RepositionWindow: centers the window, cascades it, or puts it at + /// the alert position, on the main screen or by a parent window. The + /// window keeps its size. paramErr when a parent method has none. + public func reposition(_ window: Window, method: WindowPositionMethod, + relativeTo parent: Window? = nil) throws(MacError) { + let structure = window.structureBounds + let width = Int(structure.width), height = Int(structure.height) + var topLeft: Point + switch method { + case .centerOnMainScreen: + topLeft = centered(width: width, height: height, on: mainDesktopBounds) + case .centerOnParentWindow, .centerOnParentWindowScreen: + guard let parent else { throw .parameter } + let target = method == .centerOnParentWindow ? parent.structureBounds : desktopBounds(of: parent) + topLeft = centered(width: width, height: height, on: target) + case .cascadeOnMainScreen: + topLeft = cascadeOrigin + advanceCascade(for: Point(v: Int16(height), h: Int16(width)), on: mainDesktopBounds) + case .cascadeOnParentWindow, .cascadeOnParentWindowScreen, .cascadeStartAtParentWindowScreen: + guard let parent else { throw .parameter } + let screen = desktopBounds(of: parent) + let base = method == .cascadeOnParentWindowScreen ? screen.topLeft : parent.structureBounds.topLeft + topLeft = base + cascadeOffset + case .alertPositionOnMainScreen, .alertPositionOnParentWindow, .alertPositionOnParentWindowScreen: + let target: Rect + switch method { + case .alertPositionOnMainScreen: target = mainDesktopBounds + case .alertPositionOnParentWindow: + guard let parent else { throw .parameter } + target = parent.structureBounds + default: + guard let parent else { throw .parameter } + target = desktopBounds(of: parent) + } + // The alert position: centered across, three eighths of the way + // down. + topLeft = Point(v: target.top + Int16(3 * target.height / 8 - height / 2), + h: target.left + Int16((target.width - width) / 2)) + } + window.apply(structure: Rect(top: topLeft.v, left: topLeft.h, + bottom: topLeft.v + Int16(height), right: topLeft.h + Int16(width))) + } + + /// A size's top left, centered on a rectangle. + private func centered(width: Int, height: Int, on target: Rect) -> Point { + Point(v: target.top + Int16((target.height - height) / 2), + h: target.left + Int16((target.width - width) / 2)) + } + + /// The next cascade's place, past this one, from the corner again when + /// the next window wouldn't fit. + private func advanceCascade(for size: Point, on screen: Rect) { + let next = cascadeOrigin + cascadeOffset + let off = next.h + size.h >= screen.right || next.v + size.v >= screen.bottom + cascadeOrigin = off ? screen.topLeft : next + } + + // MARK: Showing, ordering, activating + + internal func show(_ window: Window) { + guard !window.isVisible else { return } + window.isVisible = true + moveToFrontOfLayer(window) + activate(window) + recompute() + } + + internal func hide(_ window: Window) { + guard window.isVisible else { return } + window.isVisible = false + if activeWindow === window { activeWindow = nextActive(ofScope: .all) } + if activeFloatingWindow === window { activeFloatingWindow = nextActive(ofScope: .independent) } + recompute() + } + + internal func select(_ window: Window) { + guard window.isVisible else { + show(window) + return + } + bringToFront(window) + } + + internal func bringToFront(_ window: Window) { + moveToFrontOfLayer(window) + activate(window) + recompute() + } + + internal func sendBehind(_ window: Window, behind other: Window) { + guard window !== other else { return } + boxes.removeAll { $0.window === window } + let index = boxes.firstIndex { $0.window === other } ?? boxes.endIndex + boxes.insert(WindowBox(window), at: index + 1) + recompute() + } + + /// ActivateWindow. Making a window active makes no other one not + /// active: the documents and the palettes are active separately. + internal func activate(_ window: Window, _ active: Bool) { + if active { + guard window.isVisible else { return } + activate(window) + } else { + if activeWindow === window { activeWindow = nil } + if activeFloatingWindow === window { activeFloatingWindow = nil } + } + } + + private func activate(_ window: Window) { + guard window.isVisible, !window.attributes.contains(.noActivates) else { return } + switch window.windowClass.activationScope { + case .all: activeWindow = window + case .independent: activeFloatingWindow = window + case .none: break + } + } + + /// The window to make active when the active one goes: the frontmost + /// of the scope that can be. + private func nextActive(ofScope scope: WindowActivationScope) -> Window? { + windows.first { + $0.isVisible && $0.windowClass.activationScope == scope && !$0.attributes.contains(.noActivates) + } + } + + internal func dispose(_ window: Window) { + boxes.removeAll { $0.window === window } + window.isVisible = false + if activeWindow === window { activeWindow = nextActive(ofScope: .all) } + if activeFloatingWindow === window { activeFloatingWindow = nextActive(ofScope: .independent) } + recompute() + } + + /// The window's place in the list: in front of the windows of its + /// layer and below, behind those above it. A window brought forward + /// goes in front of the others of its layer. + private func moveToFrontOfLayer(_ window: Window) { + boxes.removeAll { $0.window == nil } + boxes.removeAll { $0.window === window } + let layer = window.windowClass.layer + let index = boxes.firstIndex { ($0.window?.windowClass.layer ?? 0) <= layer } ?? boxes.endIndex + boxes.insert(WindowBox(window), at: index) + } + + // MARK: What can be seen and what needs drawing + + /// Works out every visible window's visible region — its content on + /// the desktop, less what the windows in front of it cover — and adds + /// what each window has never been able to see, and so must draw, to + /// its update region. The part a window covers again stays drawn: the + /// buffer keeps it. + internal func recompute() { + boxes.removeAll { $0.window == nil } + let desktop = desktopRegion + var covering = Region() + for window in boxes.compactMap(\.window) { + guard window.isVisible else { + window.visibleRegion = Region() + window.port.visibleRegion = Region() + continue + } + let visible = window.contentRegion.intersection(desktop).subtracting(covering) + if !window.attributes.contains(.noUpdates) { + window.updateRegion = window.updateRegion.union(visible.subtracting(window.visibleRegion)) + } + window.visibleRegion = visible + let origin = window.contentBounds.topLeft + window.port.visibleRegion = visible.offsetBy(dh: -origin.h, dv: -origin.v) + window.port.device = quickDraw.device(for: window.structureBounds) + covering = covering.union(window.structureRegion) + } + } +} diff --git a/Sources/GraphiteWindows/WindowUpdates.swift b/Sources/GraphiteWindows/WindowUpdates.swift new file mode 100644 index 0000000..a46bea8 --- /dev/null +++ b/Sources/GraphiteWindows/WindowUpdates.swift @@ -0,0 +1,89 @@ +// The update region and the buffered content: InvalWindowRect, +// InvalWindowRgn, ValidWindowRect and ValidWindowRgn; BeginUpdate and +// EndUpdate, which hold a window's drawing to what needs it; and +// QDFlushPortBuffer, which tells the host what has changed in the buffer. + +import GraphiteBase +import GraphiteQuickDraw + +public extension Window { + + /// Whether any of the window needs drawing. + var needsUpdate: Bool { + !updateRegion.isEmpty + } + + /// InvalWindowRect: a part of the window needs drawing. Nothing for a + /// window with kWindowNoUpdatesAttribute, which draws when it likes. + func invalidate(_ rect: Rect) { + invalidate(Region(rect: rect)) + } + + /// InvalWindowRgn. + func invalidate(_ region: Region) { + guard !attributes.contains(.noUpdates) else { return } + updateRegion = updateRegion.union(region) + } + + /// ValidWindowRect: a part the program has drawn, which no longer + /// needs it. + func validate(_ rect: Rect) { + validate(Region(rect: rect)) + } + + /// ValidWindowRgn. + func validate(_ region: Region) { + updateRegion = updateRegion.subtracting(region) + } + + /// BeginUpdate: holds the window's drawing to the part that needs it. + /// The port's clip region is saved and set to the update region within + /// the visible region — the two the same part, in the port's local + /// coordinates — and the update region is emptied: what's drawn once + /// is drawn. EndUpdate brings the saved regions back. + func beginUpdate() { + guard savedVisibleRegion == nil else { return } + let origin = contentBounds.topLeft + let update = updateRegion.offsetBy(dh: -origin.h, dv: -origin.v) + let area = update.intersection(port.visibleRegion) + savedClipRegion = port.clipRegion + savedVisibleRegion = port.visibleRegion + port.visibleRegion = area + port.clipRegion = area + updateRegion = Region() + } + + /// EndUpdate: the clip and visible regions back as BeginUpdate found + /// them. + func endUpdate() { + guard let clip = savedClipRegion, let visible = savedVisibleRegion else { return } + port.clipRegion = clip + port.visibleRegion = visible + savedClipRegion = nil + savedVisibleRegion = nil + } + + /// QDFlushPortBuffer: tells the host the part of the window's content + /// buffer that has changed, in global coordinates — the whole content + /// when no part is given. The buffer is the host's to read; it stays + /// as it was. + func flush(_ region: Region? = nil) { + manager?.flushObserver?(self, region ?? contentRegion) + } + + /// LockPortBits: the host keeps the pixels where they are either way; + /// programs ask before they touch them. + func lockPortBits() { + portBitsLocks += 1 + } + + /// UnlockPortBits. + func unlockPortBits() { + portBitsLocks = max(0, portBitsLocks - 1) + } + + /// IsPortBitsLocked. + var arePortBitsLocked: Bool { + portBitsLocks > 0 + } +} diff --git a/Tests/GraphiteWindowsTests/WindowManagerTests.swift b/Tests/GraphiteWindowsTests/WindowManagerTests.swift new file mode 100644 index 0000000..b74bca8 --- /dev/null +++ b/Tests/GraphiteWindowsTests/WindowManagerTests.swift @@ -0,0 +1,200 @@ +import Testing +import GraphiteBase +import GraphiteQuickDraw +import GraphiteWindows + +@Suite struct WindowManagerTests { + + /// Windows by identity, in their order. + private func listed(_ windows: [Window]) -> [ObjectIdentifier] { + windows.map(ObjectIdentifier.init) + } + + private func makeManager() -> WindowManager { + WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + } + + @Test func ordering() throws { + let manager = makeManager() + let first = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + let second = try manager.newWindow(bounds: Rect(top: 60, left: 60, bottom: 160, right: 160)) + // A new window comes up in front of its layer. + #expect(listed(manager.windows) == listed([second, first])) + first.show() + second.show() + #expect(manager.frontWindow === second) + first.bringToFront() + #expect(manager.frontWindow === first) + #expect(listed(manager.windows) == listed([first, second])) + first.sendBehind(second) + #expect(listed(manager.windows) == listed([second, first])) + // Hidden windows keep their place in the list. + second.hide() + #expect(manager.frontWindow === first) + second.show() + #expect(manager.frontWindow === second) + } + + @Test func layers() throws { + let manager = makeManager() + let document = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + document.show() + let palette = try manager.newWindow(windowClass: .floating, attributes: .standardFloating, + bounds: Rect(top: 30, left: 30, bottom: 90, right: 150)) + palette.show() + // A palette floats above the documents, however they are ordered. + #expect(listed(manager.windows) == listed([palette, document])) + document.bringToFront() + #expect(listed(manager.windows) == listed([palette, document])) + // FrontWindow skips the palettes. + #expect(manager.frontWindow === document) + #expect(manager.frontFloatingWindow === palette) + let alert = try manager.newWindow(windowClass: .alert, bounds: Rect(top: 100, left: 100, bottom: 180, right: 200)) + alert.show() + #expect(listed(manager.windows) == listed([alert, palette, document])) + } + + @Test func activation() throws { + let manager = makeManager() + let first = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + first.show() + #expect(first.isActive && manager.activeWindow === first) + let second = try manager.newWindow(bounds: Rect(top: 60, left: 60, bottom: 160, right: 160)) + second.show() + #expect(second.isActive && !first.isActive) + first.select() + #expect(first.isActive && !second.isActive) + // Hiding the active window activates the one behind it. + first.hide() + #expect(manager.activeWindow === second && second.isActive) + // Selecting a hidden window shows it. + first.select() + #expect(first.isVisible && first.isActive) + // The palettes are active independently of the documents. + let palette = try manager.newWindow(windowClass: .floating, bounds: Rect(top: 30, left: 30, bottom: 90, right: 150)) + palette.show() + #expect(manager.activeFloatingWindow === palette && palette.isActive) + #expect(manager.activeWindow === first) + palette.hide() + #expect(manager.activeFloatingWindow == nil) + first.activate(false) + #expect(!first.isActive && manager.activeWindow == nil) + } + + @Test func withoutActivates() throws { + let manager = makeManager() + let quiet = try manager.newWindow(attributes: .noActivates, bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + quiet.show() + #expect(manager.activeWindow == nil && !quiet.isActive) + let loud = try manager.newWindow(bounds: Rect(top: 60, left: 60, bottom: 160, right: 160)) + loud.show() + #expect(manager.activeWindow === loud) + } + + @Test func finding() throws { + let manager = makeManager() + let back = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 340, right: 340)) + back.show() + let front = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 100, left: 100, bottom: 200, right: 200)) + front.show() + let (contentPart, contentWindow) = manager.findWindow(at: Point(v: 120, h: 120)) + #expect(contentPart == .content && contentWindow === front) + // The front window's frame, and the window behind it. + let (framePart, frameWindow) = manager.findWindow(at: Point(v: 25, h: 60)) + #expect(framePart == .drag && frameWindow === back) + let (deskPart, deskWindow) = manager.findWindow(at: Point(v: 450, h: 400)) + #expect(deskPart == .desk && deskWindow == nil) + let (barPart, barWindow) = manager.findWindow(at: Point(v: 10, h: 100)) + #expect(barPart == .menuBar && barWindow == nil) + } + + @Test func clicksPassingThrough() throws { + let manager = makeManager() + let back = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 340, right: 340)) + back.show() + let front = try manager.newWindow(attributes: .ignoreClicks, + bounds: Rect(top: 100, left: 100, bottom: 200, right: 200)) + front.show() + let (part, window) = manager.findWindow(at: Point(v: 120, h: 120)) + #expect(part == .content && window === back) + front.changeAttributes(add: .opaqueForEvents, remove: .ignoreClicks) + let (through, windowBehind) = manager.findWindow(at: Point(v: 120, h: 120)) + #expect(through == .content && windowBehind === back) + } + + @Test func desktop() throws { + let manager = makeManager() + #expect(manager.desktopRegion == Region(rect: Rect(top: 20, left: 0, bottom: 480, right: 640))) + let window = try manager.newWindow(bounds: Rect(top: 0, left: 0, bottom: 100, right: 100)) + window.show() + // The menu bar is nobody's to draw over. + #expect(window.visibleRegion == Region(rect: Rect(top: 20, left: 0, bottom: 100, right: 100))) + // Nor is anything past the edge of a screen. + let edge = try manager.newWindow(bounds: Rect(top: 400, left: 600, bottom: 500, right: 700)) + edge.show() + #expect(edge.visibleRegion == Region(rect: Rect(top: 400, left: 600, bottom: 480, right: 640))) + } + + @Test func centering() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 120, right: 140)) + // The structure — content, title bar and frame — is what centers. + #expect(window.structureBounds.width == 108 && window.structureBounds.height == 104) + try manager.reposition(window, method: .centerOnMainScreen) + #expect(window.structureBounds == Rect(top: 198, left: 266, bottom: 302, right: 374)) + let parent = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + try manager.reposition(window, method: .centerOnParentWindow, relativeTo: parent) + #expect(window.structureBounds == Rect(top: 30, left: 36, bottom: 134, right: 144)) + #expect(throws: MacError.parameter) { + try manager.reposition(window, method: .centerOnParentWindow) + } + } + + @Test func cascading() throws { + let manager = makeManager() + // The first window at the desktop's corner, the rest a title bar's + // worth below and to the right. + let first = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 120, right: 140)) + try manager.reposition(first, method: .cascadeOnMainScreen) + #expect(first.structureBounds == Rect(top: 20, left: 0, bottom: 124, right: 108)) + let second = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 120, right: 140)) + try manager.reposition(second, method: .cascadeOnMainScreen) + #expect(second.structureBounds == Rect(top: 40, left: 20, bottom: 144, right: 128)) + // From the corner again when the next wouldn't fit. + manager.cascadeOrigin = Point(v: 400, h: 500) + let third = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 120, right: 140)) + try manager.reposition(third, method: .cascadeOnMainScreen) + #expect(third.structureBounds == Rect(top: 400, left: 500, bottom: 504, right: 608)) + #expect(manager.cascadeOrigin == Point(v: 20, h: 0)) + // By a parent window: below and to the right of it. + let parent = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + let sheet = try manager.newWindow(windowClass: .sheet, bounds: Rect(top: 60, left: 60, bottom: 120, right: 120)) + try manager.reposition(sheet, method: .cascadeOnParentWindow, relativeTo: parent) + #expect(sheet.structureBounds == Rect(top: 40, left: 56, bottom: 100, right: 116)) + #expect(throws: MacError.parameter) { + try manager.reposition(sheet, method: .cascadeOnParentWindow) + } + } + + @Test func alertPosition() throws { + let manager = makeManager() + let alert = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 120, right: 140)) + try manager.reposition(alert, method: .alertPositionOnMainScreen) + // Centered across, three eighths of the way down the desktop. + #expect(alert.structureBounds == Rect(top: 140, left: 266, bottom: 244, right: 374)) + } + + @Test func lettingGo() throws { + let manager = makeManager() + // A window the program lets go of is gone from the list. + try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(manager.windows.isEmpty) + let kept = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(listed(manager.windows) == listed([kept])) + kept.dispose() + #expect(manager.windows.isEmpty && !kept.isVisible) + } +} diff --git a/Tests/GraphiteWindowsTests/WindowTests.swift b/Tests/GraphiteWindowsTests/WindowTests.swift new file mode 100644 index 0000000..bffb596 --- /dev/null +++ b/Tests/GraphiteWindowsTests/WindowTests.swift @@ -0,0 +1,295 @@ +import Testing +import GraphiteBase +import GraphiteQuickDraw +import GraphiteWindows + +@Suite struct WindowTests { + + /// Windows by identity, in their order. + private func listed(_ windows: [Window]) -> [ObjectIdentifier] { + windows.map(ObjectIdentifier.init) + } + + /// A 640×480 screen: a 20-pixel menu bar above a 620-pixel desktop. + private func makeManager() -> WindowManager { + WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + } + + @Test func classesAndAttributes() { + #expect(WindowClass(rawValue: 6) == .document) + #expect(WindowClass(rawValue: 20) == .drawer) + #expect(WindowClass.floating.isFloating && !WindowClass.document.isFloating) + #expect(WindowClass.overlay.layer > WindowClass.alert.layer) + #expect(WindowClass.alert.layer > WindowClass.floating.layer) + #expect(WindowClass.floating.layer > WindowClass.document.layer) + #expect(WindowClass.document.activationScope == .all) + #expect(WindowClass.floating.activationScope == .independent) + #expect(WindowClass.help.activationScope == .none) + #expect(WindowAttributes.closeBox.rawValue == 1) + #expect(WindowAttributes.horizontalZoom.rawValue == 2) + #expect(WindowAttributes.verticalZoom.rawValue == 4) + #expect(WindowAttributes.collapseBox.rawValue == 8) + #expect(WindowAttributes.resizable.rawValue == 16) + #expect(WindowAttributes.fullZoom == [.horizontalZoom, .verticalZoom]) + #expect(WindowAttributes.standardDocument == [.closeBox, .fullZoom, .collapseBox, .resizable]) + #expect(WindowAttributes.standardFloating == [.closeBox, .collapseBox]) + #expect(WindowRegion.structure.rawValue == 32 && WindowRegion.content.rawValue == 33) + #expect(WindowRegion.globalPort.rawValue == 40) + #expect(WindowPart.content.rawValue == 3 && WindowPart.drag.rawValue == 4) + #expect(WindowPart.grow.rawValue == 5 && WindowPart.goAway.rawValue == 6) + #expect(WindowPart.zoomIn.rawValue == 7 && WindowPart.zoomOut.rawValue == 8) + #expect(WindowPart.collapseBox.rawValue == 11 && WindowPart.structure.rawValue == 15) + #expect(WindowPositionMethod(rawValue: 4) == .cascadeOnMainScreen) + } + + @Test func newWindow() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140), title: "Report") + // The structure surrounds the content: a title bar above, a + // four-pixel frame around the rest. + #expect(window.structureBounds == Rect(top: 20, left: 36, bottom: 144, right: 144)) + #expect(window.contentBounds == Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(window.port.portRect == Rect(top: 0, left: 0, bottom: 100, right: 100)) + // A new window's buffer is white, and nothing has been shown. + #expect(window.pixels.color(at: Point(v: 50, h: 50)) == .white) + #expect(window.title == "Report") + #expect(window.kindCode == 8) + #expect(window.isVisible == false) + #expect(window.visibleRegion.isEmpty) + #expect(window.updateRegion.isEmpty) + #expect(listed(manager.windows) == listed([window])) + // The frame of a standard document window. + #expect(window.features.contains(.hasTitleBar)) + #expect(window.features.contains(.canGrow)) + #expect(window.features.contains(.canZoom)) + #expect(window.features.contains(.canCollapse)) + } + + @Test func emptyBounds() { + let manager = makeManager() + #expect(throws: MacError.parameter) { + try manager.newWindow(bounds: .zero) + } + } + + @Test func framelessClasses() throws { + let manager = makeManager() + let simple = try manager.newWindow(windowClass: .simple, bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(simple.contentBounds == simple.structureBounds) + #expect(!simple.features.contains(.hasTitleBar)) + let plain = try manager.newWindow(windowClass: .plain, bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(plain.structureBounds == Rect(top: 39, left: 39, bottom: 141, right: 141)) + #expect(plain.contentBounds == Rect(top: 40, left: 40, bottom: 140, right: 140)) + let palette = try manager.newWindow(windowClass: .floating, attributes: .standardFloating, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(palette.structureBounds == Rect(top: 23, left: 40, bottom: 140, right: 140)) + #expect(palette.contentBounds == Rect(top: 40, left: 40, bottom: 140, right: 140)) + let dialog = try manager.newWindow(windowClass: .modal, bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(dialog.features.contains(.hasTitleBar)) + // A modal window without attributes has a title bar but no boxes. + #expect(dialog.region(.closeBox).isEmpty) + #expect(dialog.hitTest(Point(v: 25, h: 100)) == .drag) + } + + @Test func regions() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(window.region(.structure) == Region(rect: Rect(top: 20, left: 36, bottom: 144, right: 144))) + #expect(window.region(.content) == Region(rect: Rect(top: 40, left: 40, bottom: 140, right: 140))) + #expect(window.region(.titleBar) == Region(rect: Rect(top: 20, left: 36, bottom: 40, right: 144))) + // The boxes: 11 pixels square, four from an edge, set to the bar's + // middle. + #expect(window.region(.closeBox) == Region(rect: Rect(top: 24, left: 40, bottom: 35, right: 51))) + #expect(window.region(.zoomBox) == Region(rect: Rect(top: 24, left: 129, bottom: 35, right: 140))) + #expect(window.region(.collapseBox) == Region(rect: Rect(top: 24, left: 114, bottom: 35, right: 125))) + #expect(window.region(.grow) == Region(rect: Rect(top: 125, left: 125, bottom: 140, right: 140))) + #expect(window.region(.titleText) == Region(rect: Rect(top: 20, left: 55, bottom: 40, right: 110))) + // The drag region is the title bar without its boxes. + #expect(window.region(.drag) == Region(rect: Rect(top: 20, left: 36, bottom: 40, right: 144)) + .subtracting(Region(rect: Rect(top: 24, left: 40, bottom: 35, right: 51))) + .subtracting(Region(rect: Rect(top: 24, left: 129, bottom: 35, right: 140))) + .subtracting(Region(rect: Rect(top: 24, left: 114, bottom: 35, right: 125)))) + // A window that can't grow has no grow region. + let fixed = try manager.newWindow(attributes: [.closeBox], bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(fixed.region(.grow).isEmpty) + } + + @Test func hitTesting() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + #expect(window.hitTest(Point(v: 100, h: 100)) == .content) + #expect(window.hitTest(Point(v: 25, h: 80)) == .drag) + #expect(window.hitTest(Point(v: 30, h: 44)) == .goAway) + #expect(window.hitTest(Point(v: 30, h: 132)) == .zoomIn) + #expect(window.hitTest(Point(v: 30, h: 118)) == .collapseBox) + #expect(window.hitTest(Point(v: 135, h: 135)) == .grow) + #expect(window.hitTest(Point(v: 10, h: 10)) == nil) + // The zoom box answers by the window's state; zoomed to the whole + // desktop, its structure moved with it. + window.zoom() + #expect(window.hitTest(Point(v: 30, h: 630)) == .zoomOut) + #expect(window.hitTest(Point(v: 30, h: 132)) == .drag) + // A window that can't grow takes the click as content. + let fixed = try manager.newWindow(attributes: [], bounds: Rect(top: 200, left: 200, bottom: 300, right: 300)) + fixed.show() + #expect(fixed.hitTest(Point(v: 295, h: 295)) == .content) + // The window's frame, out of its parts. + let framed = try manager.newWindow(windowClass: .plain, bounds: Rect(top: 400, left: 400, bottom: 440, right: 440)) + framed.show() + #expect(framed.hitTest(Point(v: 399, h: 401)) == .structure) + } + + @Test func titles() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140), title: "Zürich") + window.title = "Genève" + #expect(window.title == "Genève") + } + + @Test func zooming() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(!window.isInStandardState) + // The standard state: the desktop, minus the frame. + window.zoom() + #expect(window.isInStandardState) + #expect(window.contentBounds == Rect(top: 40, left: 4, bottom: 476, right: 636)) + #expect(window.userState == Rect(top: 40, left: 40, bottom: 140, right: 140)) + // Back to the user state, which the window keeps. + window.zoom() + #expect(!window.isInStandardState) + #expect(window.contentBounds == Rect(top: 40, left: 40, bottom: 140, right: 140)) + // The states the program sets, as SetWindowUserState and + // SetWindowStandardState. The user state is set in the standard + // state, which ZoomWindow returns to; ZoomWindow saves the state + // it leaves, so one set while the window sits in it is saved over, + // as the classic's does. + window.zoom() + window.setUserState(Rect(top: 60, left: 60, bottom: 120, right: 120)) + window.zoom() + #expect(window.contentBounds == Rect(top: 60, left: 60, bottom: 120, right: 120)) + window.setStandardState(Rect(top: 80, left: 80, bottom: 180, right: 180)) + window.zoom() + #expect(window.contentBounds == Rect(top: 80, left: 80, bottom: 180, right: 180)) + window.zoom() + #expect(window.contentBounds == Rect(top: 60, left: 60, bottom: 120, right: 120)) + // A window without a zoom attribute never zooms. + let fixed = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + fixed.zoom() + #expect(fixed.contentBounds == Rect(top: 40, left: 40, bottom: 140, right: 140)) + } + + @Test func collapsing() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + window.collapse() + // Collapsed: the structure is the title bar alone. + #expect(window.structureBounds == Rect(top: 20, left: 36, bottom: 40, right: 144)) + #expect(window.contentBounds == .zero) + #expect(window.contentRegion.isEmpty) + #expect(window.visibleRegion.isEmpty) + // The port's bounds are where they were: kWindowGlobalPortRgn + // isn't affected by collapsing. + #expect(window.region(.globalPort) == Region(rect: Rect(top: 40, left: 40, bottom: 140, right: 140))) + #expect(window.region(.zoomBox).isEmpty) + #expect(!window.region(.closeBox).isEmpty) + window.expand() + #expect(window.structureBounds == Rect(top: 20, left: 36, bottom: 144, right: 144)) + #expect(window.visibleRegion == window.contentRegion) + // Expanding shows everything again. + #expect(window.updateRegion == window.contentRegion) + // A window without a title bar can't collapse. + let simple = try manager.newWindow(windowClass: .simple, bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + simple.collapse() + #expect(simple.contentBounds == simple.structureBounds) + } + + @Test func bounds() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + // MoveWindow places the content; MoveWindowStructure the structure. + window.move(h: 200, v: 220) + #expect(window.contentBounds == Rect(top: 220, left: 200, bottom: 320, right: 300)) + #expect(window.structureBounds == Rect(top: 200, left: 196, bottom: 324, right: 304)) + window.moveStructure(h: 10, v: 30) + #expect(window.structureBounds == Rect(top: 30, left: 10, bottom: 154, right: 118)) + #expect(window.contentBounds == Rect(top: 50, left: 14, bottom: 150, right: 114)) + // SizeWindow sizes the content, from its top left. + window.size(width: 120, height: 80) + #expect(window.contentBounds == Rect(top: 50, left: 14, bottom: 130, right: 134)) + // SetWindowBounds with either region; the other follows. + try window.setBounds(Rect(top: 100, left: 100, bottom: 140, right: 140), region: .structure) + #expect(window.contentBounds == Rect(top: 120, left: 104, bottom: 136, right: 136)) + try window.setBounds(Rect(top: 40, left: 40, bottom: 100, right: 100), region: .content) + #expect(window.structureBounds == Rect(top: 20, left: 36, bottom: 104, right: 104)) + #expect(throws: MacError.parameter) { + try window.setBounds(.zero, region: .titleBar) + } + #expect(throws: MacError.parameter) { + _ = try window.bounds(of: .titleBar) + } + #expect(try window.bounds(of: .structure) == window.structureBounds) + #expect(try window.bounds(of: .content) == window.contentBounds) + } + + @Test func resizing() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + window.port.perform(.paint, rect: Rect(top: 10, left: 10, bottom: 11, right: 11)) + #expect(window.pixels.color(at: Point(v: 10, h: 10)) == .black) + window.size(width: 120, height: 80) + // The buffer starts over: a resized window draws itself again. + #expect(window.port.portRect == Rect(top: 0, left: 0, bottom: 80, right: 120)) + #expect(window.pixels.color(at: Point(v: 10, h: 10)) == .white) + #expect(window.updateRegion == window.contentRegion) + } + + @Test func changingAttributes() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(window.region(.closeBox).isEmpty) + window.changeAttributes(add: .closeBox) + #expect(!window.region(.closeBox).isEmpty) + window.changeAttributes(add: .resizable) + #expect(!window.region(.grow).isEmpty) + window.changeAttributes(remove: .resizable) + #expect(window.region(.grow).isEmpty) + } + + @Test func portAndCoordinates() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + #expect(manager.window(withPort: window.port) === window) + #expect(window.device === manager.quickDraw.mainDevice) + #expect(window.localToGlobal(.zero) == Point(v: 40, h: 40)) + #expect(window.globalToLocal(Point(v: 40, h: 40)) == .zero) + // The port's local bounds are the content's, and drawing in the + // port lands in the window's buffer. + window.port.perform(.paint, rect: Rect(top: 0, left: 0, bottom: 1, right: 1)) + #expect(window.pixels.color(at: Point(v: 0, h: 0)) == .black) + } + + @Test func parentAndReference() throws { + let manager = makeManager() + let parent = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + let sheet = try manager.newWindow(windowClass: .sheet, bounds: Rect(top: 60, left: 60, bottom: 120, right: 120)) + sheet.parent = parent + #expect(sheet.parent === parent) + sheet.referenceConstant = 42 + #expect(sheet.referenceConstant == 42) + sheet.kindCode = 2 + #expect(sheet.kindCode == 2) + } +} diff --git a/Tests/GraphiteWindowsTests/WindowUpdateTests.swift b/Tests/GraphiteWindowsTests/WindowUpdateTests.swift new file mode 100644 index 0000000..bf7790a --- /dev/null +++ b/Tests/GraphiteWindowsTests/WindowUpdateTests.swift @@ -0,0 +1,184 @@ +import Testing +import GraphiteBase +import GraphiteQuickDraw +import GraphiteWindows + +@Suite struct WindowUpdateTests { + + private func makeManager() -> WindowManager { + WindowManager(quickDraw: QuickDraw(screens: [GraphicsDevice.screen(width: 640, height: 480)])) + } + + /// Records what the host is told to flush. + private final class Flushed { + var regions: [Region] = [] + } + + @Test func shownNeedsDrawing() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(!window.needsUpdate) + // A window just shown has everything to draw: all it can be seen. + window.show() + #expect(window.updateRegion == window.contentRegion) + window.hide() + window.show() + #expect(window.updateRegion == window.contentRegion) + // Hidden, nothing is asked of it. + window.hide() + #expect(window.visibleRegion.isEmpty) + } + + @Test func invalidating() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + window.validate(window.contentBounds) + #expect(!window.needsUpdate) + window.invalidate(Rect(top: 60, left: 60, bottom: 70, right: 70)) + #expect(window.updateRegion == Region(rect: Rect(top: 60, left: 60, bottom: 70, right: 70))) + window.invalidate(Region(rect: Rect(top: 80, left: 80, bottom: 90, right: 90))) + #expect(window.updateRegion == Region(rect: Rect(top: 60, left: 60, bottom: 70, right: 70)) + .union(Region(rect: Rect(top: 80, left: 80, bottom: 90, right: 90)))) + window.validate(Rect(top: 60, left: 60, bottom: 70, right: 70)) + #expect(window.updateRegion == Region(rect: Rect(top: 80, left: 80, bottom: 90, right: 90))) + window.validate(window.contentRegion) + #expect(!window.needsUpdate) + } + + @Test func withoutUpdates() throws { + let manager = makeManager() + let window = try manager.newWindow(attributes: .noUpdates, bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + // A window with kWindowNoUpdatesAttribute is never asked to + // draw anything: it draws when it likes. + #expect(window.updateRegion.isEmpty && !window.needsUpdate) + window.invalidate(Rect(top: 60, left: 60, bottom: 70, right: 70)) + #expect(window.updateRegion.isEmpty) + } + + @Test func beginAndEndUpdate() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + window.validate(window.contentBounds) + window.invalidate(Rect(top: 60, left: 60, bottom: 70, right: 70)) + window.beginUpdate() + // Drawing is held to the update region, in the port's local + // coordinates, and the update region is spent. + #expect(window.updateRegion.isEmpty) + let clip = Region(rect: Rect(top: 20, left: 20, bottom: 30, right: 30)) + #expect(window.port.clipRegion == clip) + #expect(window.port.visibleRegion == clip) + window.port.perform(.paint, rect: Rect(top: 0, left: 0, bottom: 100, right: 100)) + #expect(window.pixels.color(at: Point(v: 25, h: 25)) == .black) + #expect(window.pixels.color(at: Point(v: 50, h: 50)) == .white) + window.endUpdate() + #expect(window.port.visibleRegion == Region(rect: window.port.portRect)) + #expect(!window.needsUpdate) + // EndUpdate without BeginUpdate does nothing. + window.endUpdate() + #expect(window.port.visibleRegion == Region(rect: window.port.portRect)) + } + + @Test func occlusion() throws { + let manager = makeManager() + let behind = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 340, right: 340)) + behind.show() + let front = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 100, left: 100, bottom: 200, right: 200)) + front.show() + // The window behind sees everything but what the front one's + // structure covers. + let frontStructure = Region(rect: Rect(top: 80, left: 96, bottom: 204, right: 204)) + let behindContent = Region(rect: Rect(top: 40, left: 40, bottom: 340, right: 340)) + #expect(behind.visibleRegion == behindContent.subtracting(frontStructure)) + #expect(front.visibleRegion == Region(rect: Rect(top: 100, left: 100, bottom: 200, right: 200))) + behind.validate(behind.contentRegion) + #expect(!behind.needsUpdate) + // The front window gone, what it covered is seen — and so drawn — + // again. + front.hide() + #expect(behind.visibleRegion == behindContent) + #expect(behind.updateRegion == frontStructure) + front.show() + #expect(behind.visibleRegion == behindContent.subtracting(frontStructure)) + // What was covered again stays drawn: the buffer keeps it. + #expect(behind.updateRegion == frontStructure) + } + + @Test func uncoveringByMove() throws { + let manager = makeManager() + let behind = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 40, left: 40, bottom: 340, right: 340)) + behind.show() + let front = try manager.newWindow(attributes: .standardDocument, + bounds: Rect(top: 100, left: 100, bottom: 200, right: 200)) + front.show() + behind.validate(behind.contentRegion) + front.move(h: 300, v: 300) + // The front window still covers a corner of the one behind; the + // part it let go of needs drawing. + let stillCovered = Region(rect: Rect(top: 280, left: 296, bottom: 340, right: 340)) + let letGo = Region(rect: Rect(top: 80, left: 96, bottom: 204, right: 204)) + #expect(behind.visibleRegion == Region(rect: Rect(top: 40, left: 40, bottom: 340, right: 340)) + .subtracting(stillCovered)) + #expect(behind.updateRegion == letGo) + #expect(behind.updateRegion.contains(Point(v: 100, h: 100))) + #expect(!behind.updateRegion.contains(Point(v: 300, h: 310))) + #expect(!behind.updateRegion.contains(Point(v: 60, h: 50))) + } + + @Test func flushing() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + let flushed = Flushed() + manager.flushObserver = { _, region in + flushed.regions.append(region) + } + window.flush() + #expect(flushed.regions == [window.contentRegion]) + let part = Region(rect: Rect(top: 50, left: 50, bottom: 60, right: 60)) + window.flush(part) + #expect(flushed.regions == [window.contentRegion, part]) + // Without a host to flush to, the buffer stays as it was. + manager.flushObserver = nil + window.flush() + #expect(window.pixels.color(at: Point(v: 50, h: 50)) == .white) + } + + @Test func portBits() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + #expect(!window.arePortBitsLocked) + window.lockPortBits() + #expect(window.arePortBitsLocked) + window.lockPortBits() + window.unlockPortBits() + #expect(window.arePortBitsLocked) + window.unlockPortBits() + #expect(!window.arePortBitsLocked) + window.unlockPortBits() + #expect(!window.arePortBitsLocked) + } + + @Test func drawingThroughThePort() throws { + let manager = makeManager() + let window = try manager.newWindow(bounds: Rect(top: 40, left: 40, bottom: 140, right: 140)) + window.show() + // Drawing in the port lands in the window's buffer, held to what + // can be seen. + window.port.perform(.paint, rect: Rect(top: -20, left: -20, bottom: 120, right: 120)) + #expect(window.pixels.color(at: Point(v: 0, h: 0)) == .black) + #expect(window.pixels.color(at: Point(v: 99, h: 99)) == .black) + // The flush carries it to the host as the whole content. + let flushed = Flushed() + manager.flushObserver = { _, region in + flushed.regions.append(region) + } + window.flush() + #expect(flushed.regions == [window.contentRegion]) + } +}