Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/hop/blob/main/Sources/SpiritField.swift # hop Hop: a small native macOS launcher. Clipboard history, find, on-device dictation and your coding agent behind one key. Brought by drakestapleton Sign in to star 1 stars 1 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `hop / Sources / SpiritField.swift` 408 lines · 22084 bytes Raw Blame History 1 import SwiftUI 2 import AppKit 3 4 /// The colours of Hop's window, in one place. They are the AienOS brand tokens of the Midnight theme; the name of 5 /// the token is beside each value. No other file types a colour for the sky, the cards or the bar. 6 enum Spirit { 7 static let ground = Color(red: 10 / 255, green: 10 / 255, blue: 15 / 255) // bg-primary #0a0a0f 8 static let card = Color(red: 20 / 255, green: 20 / 255, blue: 31 / 255) // bg-card #14141f 9 static let accent = Color(red: 99 / 255, green: 179 / 255, blue: 237 / 255) // accent #63b3ed 10 static let accentFill = Color(red: 37 / 255, green: 99 / 255, blue: 235 / 255) // accent-fill #2563eb 11 static let hairline = Color.white.opacity(0.08) // border 12 static let hairlineStrong = Color.white.opacity(0.10) // border-strong 13 static let inputFill = Color.white.opacity(0.05) // fill-input 14 static let textDim = Color.white.opacity(0.70) // text-tertiary 15 static let textQuiet = Color.white.opacity(0.50) // text-secondary 16 static let windowRadius: CGFloat = 22 17 static var windowShape: RoundedRectangle { RoundedRectangle(cornerRadius: windowRadius, style: .continuous) } 18 static let cardRadius: CGFloat = 16 // radius-2xl 19 /// How much of the desktop shows through the sky (blurred). With Reduce Transparency on, none. 20 static let groundStrength = 0.80 21 /// Frames a second while the sky moves. It stands still when Hop is hidden, in tests and with Reduce Motion. 22 static let framesPerSecond = 20.0 23 24 /// A card on the sky: the card colour, told apart from the ground by a hairline and not by a shadow. 25 static func glass(_ strength: Double = 0.55, edge: Color = hairline, radius: CGFloat = cardRadius) -> some View { 26 RoundedRectangle(cornerRadius: radius, style: .continuous).fill(card.opacity(strength)) 27 .overlay(RoundedRectangle(cornerRadius: radius, style: .continuous).strokeBorder(edge, lineWidth: 1)) 28 } 29 } 30 31 /// The order and strength of the messages on show. Hop keeps a conversation oldest first (the model is sent it 32 /// that way); only what is drawn is turned round, so the newest message is on top and older ones sink. 33 enum SpiritOrder { 34 nonisolated static func newestFirst(_ log: [ChatMessage]) -> [ChatMessage] { Array(log.reversed()) } 35 36 /// How strongly a message is drawn, by how far it has sunk (0 is the newest). Never weaker than 0.70, so the 37 /// dimmest text still reads. 38 nonisolated static let fadeFloor = 0.70 39 nonisolated static func fade(depth: Int) -> Double { max(fadeFloor, 1.0 - 0.05 * Double(max(0, depth))) } 40 41 /// Where the reader is: at the top, further down inside the newest message (reading a long answer), or 42 /// below it, among older messages. 43 enum Place: Equatable { case top, inNewest, older } 44 nonisolated static let topSlack: CGFloat = 24 45 nonisolated static func place(offset: CGFloat, newestHeight: CGFloat) -> Place { 46 if offset <= topSlack { return .top } 47 return offset <= newestHeight + topSlack ? .inNewest : .older 48 } 49 50 /// What is on show while the reader is somewhere in the conversation. 51 /// - held: the messages that were there when the reader left the top, by identity. Later ones wait behind the 52 /// "new" button, wherever in the conversation they are put (a "busy" note goes in before the answer it is 53 /// about), so nothing is put in above what is being read and the answer being read stays the answer on show. 54 /// - frozen: those messages as they were when the reader went below the newest one. An answer that is still 55 /// being written grows above the reader there and would push the page down, so its text waits too. While the 56 /// reader is inside the newest message it stays live: it grows below what has been read. 57 struct Hold: Equatable { 58 var held: [UUID]? = nil 59 var frozen: [ChatMessage]? = nil 60 61 func shown(_ log: [ChatMessage]) -> [ChatMessage] { 62 guard let held else { return SpiritOrder.newestFirst(log) } 63 if let frozen { // a message that has since been taken out of the conversation is not kept on show 64 let live = Set(log.map(\.id)) 65 return SpiritOrder.newestFirst(frozen.filter { live.contains($0.id) }) 66 } 67 let keep = Set(held) 68 return SpiritOrder.newestFirst(log.filter { keep.contains($0.id) }) 69 } 70 /// Messages that arrived since the reader left the top, oldest first. 71 func arrived(_ log: [ChatMessage]) -> [ChatMessage] { 72 guard let held else { return [] } 73 let keep = Set(held) 74 return log.filter { !keep.contains($0.id) } 75 } 76 func waiting(_ log: [ChatMessage]) -> Int { arrived(log).count } 77 var digging: Bool { held != nil } 78 /// You sent something yourself since you left the top: you are no longer reading the past, so the top comes 79 /// back with your message on it. Whatever was added with it (the empty answer Ask puts in at once) does not 80 /// change that. 81 func sentSince(_ log: [ChatMessage]) -> Bool { arrived(log).contains { $0.role == "user" } } 82 83 mutating func moved(to place: Place, log: [ChatMessage]) { 84 if place != .top, held == nil { held = log.map(\.id) } 85 switch place { 86 case .top: self = Hold() 87 case .inNewest: frozen = nil 88 case .older: if frozen == nil { let keep = Set(held ?? []); frozen = log.filter { keep.contains($0.id) } } 89 } 90 } 91 /// The conversation was cleared or replaced: there is nothing left to hold on to. 92 mutating func settle(_ log: [ChatMessage]) { 93 guard let held else { return } 94 let live = Set(log.map(\.id)) 95 if !held.contains(where: live.contains) { self = Hold() } 96 } 97 } 98 } 99 100 /// One star of the sky. Its place is a share of the window, so the same stars fill any window size. 101 struct SpiritStar: Equatable { 102 var x: Double, y: Double // 0 ..< 1 103 var size: Double // radius in points 104 var phase: Double, rate: Double // twinkle 105 var drift: Double // points a second, to the left 106 } 107 108 enum SpiritStars { 109 nonisolated static let count = 110 110 /// The same stars every time: made from a fixed number, not from the clock, so two pictures of the same 111 /// moment are the same picture. 112 nonisolated static func make(seed: UInt64 = 0x484F_5053_5049_5249, count: Int = SpiritStars.count) -> [SpiritStar] { 113 var s = seed 114 func next() -> Double { // SplitMix64, as a share of one 115 s &+= 0x9E37_79B9_7F4A_7C15 116 var z = s 117 z = (z ^ (z >> 30)) &* 0xBF58_476D_1CE4_E5B9 118 z = (z ^ (z >> 27)) &* 0x94D0_49BB_1331_11EB 119 z ^= z >> 31 120 return Double(z >> 11) / Double(1 << 53) 121 } 122 return (0.. 0, size.height > 0 else { return } 139 for s in stars { 140 var x = (s.x * size.width - t * s.drift).truncatingRemainder(dividingBy: size.width) 141 if x < 0 { x += size.width } 142 let a = 0.30 + 0.30 * (0.5 + 0.5 * sin(t * s.rate + s.phase)) 143 cg.setFillColor(white.copy(alpha: a) ?? white) 144 cg.fillEllipse(in: CGRect(x: x - s.size, y: s.y * size.height - s.size, width: s.size * 2, height: s.size * 2)) 145 } 146 } 147 148 /// How strong a ripple is at a share `u` of the way out: 22 percent at the point, 4 percent at the rim, and 149 /// gone over the last tenth so a ripple does not vanish with a jump. 150 nonisolated static func rippleStrength(_ u: Double) -> Double { 151 let v = min(max(u, 0), 1) 152 let base = 0.04 + 0.18 * (1 - v) * (1 - v) 153 return v > 0.9 ? base * (1 - v) / 0.1 : base 154 } 155 156 /// Stylized gravitational waves from a binary system, not a physical simulation. 157 /// The two-lobed deformation follows the retarded orbital phase as each ring expands. 158 nonisolated static func ripples(_ cg: CGContext, center: CGPoint, reach: CGFloat, t: Double, rings: Int = 6) { 159 guard reach > 0, rings > 0 else { return } 160 cg.saveGState() 161 defer { cg.restoreGState() } 162 cg.setLineWidth(0.8) 163 for k in 0.. 0 else { return } 186 let phase = t * 2 * Double.pi / 18 187 let orbit = radius * 5.8 188 // Draw the farther horizon first; apparent size subtly follows depth, never a brightness pulse. 189 let phases = [phase, phase + Double.pi].sorted { sin($0) < sin($1) } 190 for angle in phases { 191 let r = radius * (1.45 + 0.12 * sin(angle)) 192 let c = CGPoint(x: center.x + cos(angle) * orbit, y: center.y + sin(angle) * orbit * 0.60) 193 let warm = CGColor(red: 1, green: 0.73, blue: 0.42, alpha: 0.85) 194 cg.saveGState() 195 cg.setShadow(offset: .zero, blur: r * 1.1, color: warm.copy(alpha: 0.45)) 196 cg.setStrokeColor(warm) 197 cg.setLineWidth(max(0.65, r * 0.14)) 198 cg.strokeEllipse(in: CGRect(x: c.x - r * 2.4, y: c.y - r * 0.62, width: r * 4.8, height: r * 1.24)) 199 cg.setShadow(offset: .zero, blur: 0, color: nil) 200 cg.setFillColor(CGColor(red: 0.005, green: 0.005, blue: 0.009, alpha: 1)) 201 cg.fillEllipse(in: CGRect(x: c.x - r, y: c.y - r, width: r * 2, height: r * 2)) 202 cg.setStrokeColor(CGColor(red: 1, green: 0.88, blue: 0.67, alpha: 0.95)) 203 cg.setLineWidth(max(0.55, r * 0.10)) 204 cg.strokeEllipse(in: CGRect(x: c.x - r, y: c.y - r, width: r * 2, height: r * 2)) 205 cg.restoreGState() 206 } 207 } 208 209 /// One whole frame of the home screen: the sky, gravitational waves and orbiting horizons. 210 nonisolated static func frame(_ cg: CGContext, size: CGSize, t: Double) { 211 stars(cg, size: size, t: t) 212 let c = CGPoint(x: size.width / 2, y: size.height * 0.4) 213 ripples(cg, center: c, reach: max(size.width, size.height) * 0.6, t: t) 214 core(cg, center: c, radius: 5, t: t) 215 } 216 217 /// Draws `frames` whole frames into an off-screen picture of a window at twice the points (a Retina screen) 218 /// and returns the average milliseconds of processor time a frame. Processor time of this thread, not time on 219 /// the clock: a busy Mac makes the clock run long without the drawing costing more. Used by `--selftest`. 220 nonisolated static func averageFrameMilliseconds(size: CGSize = CGSize(width: 820, height: 520), frames: Int = 60) -> Double? { 221 let w = Int(size.width * 2), h = Int(size.height * 2) 222 guard frames > 0, let cg = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, 223 space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue) else { return nil } 224 cg.scaleBy(x: 2, y: 2) 225 for k in 0..<3 { frame(cg, size: size, t: Double(k)) } // first use of the drawing code is not counted 226 let start = clock_gettime_nsec_np(CLOCK_THREAD_CPUTIME_ID) 227 for k in 0.. NSVisualEffectView { 239 let v = NSVisualEffectView() 240 v.material = .hudWindow; v.blendingMode = .behindWindow; v.state = .active 241 let d = radius * 2 + 1 242 let mask = NSImage(size: NSSize(width: d, height: d), flipped: false) { rect in 243 NSColor.black.setFill(); NSBezierPath(roundedRect: rect, xRadius: radius, yRadius: radius).fill(); return true 244 } 245 mask.capInsets = NSEdgeInsets(top: radius, left: radius, bottom: radius, right: radius) 246 mask.resizingMode = .stretch 247 v.maskImage = mask 248 return v 249 } 250 func updateNSView(_ v: NSVisualEffectView, context: Context) {} 251 } 252 253 /// Whether Hop's window is on screen, for any view that moves. Set once, at the root. 254 private struct SpiritShowingKey: EnvironmentKey { static let defaultValue = true } 255 extension EnvironmentValues { 256 var spiritShowing: Bool { get { self[SpiritShowingKey.self] } set { self[SpiritShowingKey.self] = newValue } } 257 } 258 259 /// What the UI tests read back from the home screen: where each card was drawn and which one is highlighted. 260 @MainActor 261 enum HomeProbe { 262 static var cards: [String: CGRect] = [:] // by the line's id, in the window's own coordinates (top left origin) 263 static var highlighted: String? 264 } 265 266 /// When the moving parts stand still: Hop is hidden, the user asked macOS for less motion, or a test is running 267 /// (so two pictures of the same screen are the same). 268 struct SpiritClock { 269 let showing: Bool 270 let reduceMotion: Bool 271 var still: Bool { !showing || reduceMotion || SpiritClock.testing } 272 static let testing = CommandLine.arguments.contains("--uitest") || CommandLine.arguments.contains("--selftest") 273 /// The moment drawn when nothing moves. 274 static let restMoment = 12.0 275 func moment(_ date: Date) -> Double { still ? Self.restMoment : date.timeIntervalSinceReferenceDate.truncatingRemainder(dividingBy: 86_400) } 276 } 277 278 /// The night sky behind every screen of Hop: the desktop blurred, the ground colour over it, and the stars. 279 struct SpiritField: View { 280 let showing: Bool 281 @Environment(\.accessibilityReduceMotion) private var reduceMotion 282 @Environment(\.accessibilityReduceTransparency) private var reduceTransparency 283 284 var body: some View { 285 let clock = SpiritClock(showing: showing, reduceMotion: reduceMotion) 286 ZStack { 287 if reduceTransparency { Spirit.ground } else { 288 SpiritBackdrop(radius: Spirit.windowRadius) 289 Spirit.ground.opacity(Spirit.groundStrength) 290 } 291 TimelineView(.animation(minimumInterval: 1 / Spirit.framesPerSecond, paused: clock.still)) { line in 292 Canvas { ctx, size in 293 let t = clock.moment(line.date) 294 ctx.withCGContext { cg in SpiritPaint.stars(cg, size: size, t: t) } 295 } 296 } 297 .allowsHitTesting(false) 298 } 299 .accessibilityHidden(true) 300 } 301 } 302 303 /// A binary black-hole scene, large on the home screen and compact in the bar. 304 struct SpiritOrb: View { 305 let showing: Bool 306 var coreRadius: CGFloat = 5 307 var rings = 6 308 /// Where the binary system sits in this view, as a share of its size. 309 var anchor = UnitPoint(x: 0.5, y: 0.5) 310 /// How far the ripples travel, as a share of the longer side. 311 var reach: CGFloat = 0.6 312 @Environment(\.accessibilityReduceMotion) private var reduceMotion 313 314 var body: some View { 315 let clock = SpiritClock(showing: showing, reduceMotion: reduceMotion) 316 TimelineView(.animation(minimumInterval: 1 / Spirit.framesPerSecond, paused: clock.still)) { line in 317 Canvas { ctx, size in 318 let t = clock.moment(line.date) 319 let c = CGPoint(x: size.width * anchor.x, y: size.height * anchor.y) 320 ctx.withCGContext { cg in 321 SpiritPaint.ripples(cg, center: c, reach: max(size.width, size.height) * reach, t: t, rings: rings) 322 SpiritPaint.core(cg, center: c, radius: min(coreRadius, min(size.width, size.height) / 22), t: t) 323 } 324 } 325 } 326 .allowsHitTesting(false) 327 .accessibilityHidden(true) 328 } 329 } 330 331 /// The one box with nothing typed. No list: the spirit, at most a few things Hop thinks you want right now, and 332 /// the way to each screen. Everything else appears when you type. 333 struct SpiritHome: View { 334 @ObservedObject var m: AppModel 335 336 var body: some View { 337 let rows = Array(m.smartRows.prefix(m.smartShown)) 338 ZStack { 339 SpiritOrb(showing: m.panelShown, anchor: UnitPoint(x: 0.5, y: 0.34)) 340 VStack(spacing: 14) { 341 Spacer(minLength: 0).frame(maxHeight: .infinity) 342 if rows.isEmpty { 343 Text("Type an app, a file, something you copied, or a question.") 344 .font(.callout).foregroundStyle(Spirit.textQuiet).multilineTextAlignment(.center) 345 } else { 346 HStack(alignment: .top, spacing: 12) { 347 ForEach(Array(rows.enumerated()), id: \.element.id) { i, row in 348 SpiritPill(m: m, row: row, selected: i == m.selection) 349 .offset(y: i % 2 == 0 ? 0 : 10) 350 .onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { f in 351 if UITest.active { HomeProbe.cards[row.id] = f } 352 } 353 .onTapGesture(count: 2) { m.run(row) } 354 .onTapGesture { m.selection = i; m.boxFocus += 1 } 355 } 356 } 357 .padding(.horizontal, 20) 358 } 359 HStack(spacing: 8) { 360 ForEach(m.tabs.filter { $0 != .all }) { t in 361 Button { m.query = ""; m.tab = t; m.boxFocus += 1 } label: { 362 Label(t.rawValue, systemImage: t.icon).font(.caption.weight(.medium)) 363 .padding(.horizontal, 10).padding(.vertical, 5) 364 .background(Capsule().fill(Spirit.inputFill).overlay(Capsule().strokeBorder(Spirit.hairline, lineWidth: 1))) 365 .contentShape(Capsule()) 366 } 367 .buttonStyle(.plain).foregroundStyle(Spirit.textDim) 368 .help("Show \(t.rawValue)") 369 } 370 } 371 .padding(.top, 14).padding(.bottom, 18) 372 if !AXIsProcessTrusted(), m.clipboard.lockReason == nil, rows.contains(where: { if case .clip = $0.kind { true } else { false } }) { 373 PastePermissionBar() 374 } 375 } 376 } 377 .onChange(of: rows.map(\.id), initial: true) { _, ids in HomeProbe.cards = HomeProbe.cards.filter { ids.contains($0.key) } } 378 .onDisappear { HomeProbe.cards = [:]; HomeProbe.highlighted = nil } 379 } 380 } 381 382 /// One thing Hop offers before you type, as a small card. The highlighted one is what Enter does. 383 struct SpiritPill: View { 384 @ObservedObject var m: AppModel 385 let row: SmartRow 386 let selected: Bool 387 388 var body: some View { 389 let face = SmartRowFace(m: m, row: row) 390 HStack(spacing: 9) { 391 face.icon.frame(width: 20, height: 20) 392 VStack(alignment: .leading, spacing: 1) { 393 Text(face.title).font(.callout).lineLimit(1).truncationMode(.tail) 394 Text(face.detail).font(.caption2).foregroundStyle(Spirit.textDim).lineLimit(1).truncationMode(.tail) 395 } 396 Spacer(minLength: 0) 397 if selected { 398 Text(face.action + " ↩").font(.caption2.weight(.semibold)).foregroundStyle(Spirit.accent).fixedSize() 399 } 400 } 401 .padding(.horizontal, 12).padding(.vertical, 8) 402 .frame(maxWidth: 250, alignment: .leading) 403 .background(Spirit.glass(selected ? 0.75 : 0.5, edge: selected ? Spirit.accent.opacity(0.55) : Spirit.hairline)) 404 .contentShape(RoundedRectangle(cornerRadius: Spirit.cardRadius)) 405 .help(face.detail) 406 .onChange(of: selected, initial: true) { _, on in if on { HomeProbe.highlighted = row.id } } 407 } 408 }