SPB Git

Repository Public

AmbientBackground.swift 13.0 KB 257 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Browser9// File             : SPBrowser/Shared/Aura/AmbientBackground.swift10// Module           : SPBrowser11// Repository       : https://git.spboucher.ai/sp-browser12// Created          : 2026-11-1913// Last Modified    : 2026-11-1914//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import SwiftUI8889/// The moving light behind the start page (AURA Ambient Home). Everything is drawn with a handful of gradients in a90/// `Canvas` at 20 fps at most — no blur filters, no off-screen passes — and stops entirely under Reduce Motion,91/// Low Power Mode, when the window is in the background, or when the user turns ambient motion off.92struct AmbientBackground: View {93    let theme: AmbientTheme94    var isPrivate = false95    @Environment(\.auraPolicy) private var policy96    @Environment(\.colorScheme) private var scheme9798    private var dark: Bool { scheme == .dark || theme.isAlwaysDark }99100    var body: some View {101        ZStack {102            base103            if theme != .minimal {104                if theme.isAnimated && policy.allowsDecorative {105                    TimelineView(.animation(minimumInterval: policy.decorativeFrameInterval)) { context in106                        layer(time: context.date.timeIntervalSinceReferenceDate)107                    }108                } else {109                    // A still frame of the same scene: the theme keeps its character without moving.110                    layer(time: 0)111                }112            }113        }114        .ignoresSafeArea()115        .accessibilityHidden(true)116        .allowsHitTesting(false)117    }118119    private var base: some View {120        Group {121            switch theme {122            case .obsidian: LinearGradient(colors: [Aura.Palette.obsidian, Color(red: 0.047, green: 0.051, blue: 0.071)], startPoint: .top, endPoint: .bottom)123            case .cosmos: LinearGradient(colors: [Color(red: 0.012, green: 0.016, blue: 0.039), Aura.Palette.deepSpace.opacity(0.9), Color(red: 0.020, green: 0.024, blue: 0.055)], startPoint: .top, endPoint: .bottom)124            default: Aura.Palette.surface125            }126        }127    }128129    private var tints: (Color, Color, Color) {130        if isPrivate { return (Aura.Palette.violet, Color(red: 0.62, green: 0.30, blue: 0.95), Aura.Palette.cyan) }131        return (Aura.Palette.violet, Aura.Palette.electricBlue, Aura.Palette.cyan)132    }133134    /// The glows are soft by nature, so they are rasterized at a quarter of the size and scaled up: sixteen times fewer135    /// pixels to fill per frame, with no visible difference. Only the stars of Cosmos need full resolution.136    private static let glowScale: CGFloat = 4137138    private func layer(time: Double) -> some View {139        GeometryReader { proxy in140            ZStack(alignment: .topLeading) {141                Canvas(opaque: false, rendersAsynchronously: true) { context, size in142                    switch theme {143                    case .obsidian: drawObsidian(&context, size)144                    case .aurora: drawAurora(&context, size, time)145                    case .liquid: drawLiquid(&context, size, time)146                    case .cosmos: drawCosmosGlow(&context, size)147                    case .minimal: break148                    }149                }150                .frame(width: proxy.size.width / Self.glowScale, height: proxy.size.height / Self.glowScale)151                .scaleEffect(Self.glowScale, anchor: .topLeading)152                .frame(width: proxy.size.width, height: proxy.size.height, alignment: .topLeading)153                if theme == .cosmos {154                    Canvas(opaque: false, rendersAsynchronously: true) { context, size in drawStars(&context, size, time) }155                }156            }157        }158    }159160    private func glow(_ context: inout GraphicsContext, _ size: CGSize, center: CGPoint, radius: CGFloat, color: Color, opacity: Double, stretch: CGFloat = 1) {161        var ctx = context162        ctx.translateBy(x: center.x, y: center.y)163        ctx.scaleBy(x: stretch, y: 1)164        let rect = CGRect(x: -radius, y: -radius, width: radius * 2, height: radius * 2)165        ctx.fill(Path(ellipseIn: rect), with: .radialGradient(Gradient(colors: [color.opacity(opacity), color.opacity(opacity * 0.35), .clear]),166                                                             center: .zero, startRadius: 0, endRadius: radius))167    }168169    private func drawObsidian(_ context: inout GraphicsContext, _ size: CGSize) {170        // One quiet highlight at the top and a breath of violet low on the right: depth without movement.171        glow(&context, size, center: CGPoint(x: size.width * 0.5, y: -size.height * 0.1), radius: size.width * 0.55, color: .white, opacity: 0.055, stretch: 1.3)172        glow(&context, size, center: CGPoint(x: size.width * 0.92, y: size.height * 1.02), radius: size.width * 0.45, color: tints.0, opacity: 0.10)173    }174175    private func drawAurora(_ context: inout GraphicsContext, _ size: CGSize, _ time: Double) {176        let t = time * 0.045177        let strength = dark ? 0.30 : 0.20178        let w = size.width, h = size.height179        glow(&context, size, center: CGPoint(x: w * (0.28 + 0.10 * sin(t * 1.3)), y: h * (0.08 + 0.06 * cos(t))), radius: max(w, h) * 0.52, color: tints.0, opacity: strength, stretch: 1.5)180        glow(&context, size, center: CGPoint(x: w * (0.72 + 0.09 * cos(t * 0.9 + 1)), y: h * (0.16 + 0.07 * sin(t * 1.1))), radius: max(w, h) * 0.46, color: tints.1, opacity: strength * 0.9, stretch: 1.4)181        glow(&context, size, center: CGPoint(x: w * (0.55 + 0.14 * sin(t * 0.7 + 2)), y: h * (0.92 + 0.05 * cos(t * 1.2))), radius: max(w, h) * 0.42, color: tints.2, opacity: strength * 0.55, stretch: 1.6)182    }183184    private func drawLiquid(_ context: inout GraphicsContext, _ size: CGSize, _ time: Double) {185        let t = time * 0.07186        let w = size.width, h = size.height187        let strength = dark ? 0.24 : 0.16188        // Slow, overlapping lobes whose stretch breathes: reads as glass in motion.189        for index in 0..<5 {190            let phase = Double(index) * 1.257191            let color = [tints.1, tints.2, tints.0, tints.2, tints.1][index]192            let center = CGPoint(x: w * (0.5 + 0.38 * sin(t * (0.6 + Double(index) * 0.11) + phase)), y: h * (0.5 + 0.36 * cos(t * (0.5 + Double(index) * 0.07) + phase * 1.7)))193            glow(&context, size, center: center, radius: max(w, h) * (0.30 + 0.05 * sin(t + phase)), color: color, opacity: strength * (index.isMultiple(of: 2) ? 1 : 0.7),194                 stretch: 1.2 + 0.5 * CGFloat(sin(t * 0.8 + phase)))195        }196        // A soft specular band, like light sliding across a pane.197        let bandY = h * (0.5 + 0.45 * sin(t * 0.35))198        var band = Path()199        band.addRect(CGRect(x: 0, y: bandY - h * 0.18, width: w, height: h * 0.36))200        context.fill(band, with: .linearGradient(Gradient(colors: [.clear, Color.white.opacity(dark ? 0.035 : 0.25), .clear]),201                                                startPoint: CGPoint(x: 0, y: bandY - h * 0.18), endPoint: CGPoint(x: 0, y: bandY + h * 0.18)))202    }203204    private func drawCosmosGlow(_ context: inout GraphicsContext, _ size: CGSize) {205        let w = size.width, h = size.height206        glow(&context, size, center: CGPoint(x: w * 0.22, y: h * 0.25), radius: max(w, h) * 0.5, color: tints.0, opacity: 0.20, stretch: 1.4)207        glow(&context, size, center: CGPoint(x: w * 0.85, y: h * 0.75), radius: max(w, h) * 0.45, color: tints.2, opacity: 0.11, stretch: 1.3)208    }209210    /// Three layers of stars drifting at different speeds give the depth; each star twinkles on its own phase.211    private func drawStars(_ context: inout GraphicsContext, _ size: CGSize, _ time: Double) {212        let w = size.width, h = size.height213        for star in Self.stars {214            let layer = Double(star.layer + 1)215            var x = (star.x + time * 0.0016 * layer).truncatingRemainder(dividingBy: 1)216            if x < 0 { x += 1 }217            let twinkle = 0.55 + 0.45 * sin(time * (0.5 + star.speed) + star.phase)218            let radius = (0.5 + star.size * 1.1) * (0.6 + layer * 0.22)219            let rect = CGRect(x: x * w - radius, y: star.y * h - radius, width: radius * 2, height: radius * 2)220            context.fill(Path(ellipseIn: rect), with: .color(Color.white.opacity((0.25 + 0.5 * star.size) * twinkle)))221        }222    }223224    private struct Star { var x: Double, y: Double, size: Double, phase: Double, speed: Double, layer: Int }225226    /// The same sky every time: generated once from a fixed seed.227    private static let stars: [Star] = {228        var seed: UInt64 = 0x5350_4252_4F57_5345229        func next() -> Double {230            seed = seed &* 6364136223846793005 &+ 1442695040888963407231            return Double((seed >> 33) & 0xFFFFFF) / Double(0xFFFFFF)232        }233        return (0..<150).map { index in Star(x: next(), y: next(), size: pow(next(), 3), phase: next() * 6.28, speed: next(), layer: index % 3) }234    }()235}236237/// A small live preview of a theme, for the customizer.238struct AmbientThemeSwatch: View {239    let theme: AmbientTheme240    var isSelected = false241242    var body: some View {243        VStack(spacing: 6) {244            AmbientBackground(theme: theme)245                .environment(\.auraPolicy, MotionPolicy(reduceMotion: true))246                .environment(\.colorScheme, theme.isAlwaysDark ? .dark : .light)247                .frame(width: 84, height: 54)248                .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))249                .overlay(RoundedRectangle(cornerRadius: 10, style: .continuous).strokeBorder(isSelected ? AnyShapeStyle(Aura.horizontalGradient) : AnyShapeStyle(Aura.Palette.hairline), lineWidth: isSelected ? 2 : 1))250            Text(theme.title).font(.caption).foregroundStyle(isSelected ? .primary : .secondary)251        }252        .accessibilityElement(children: .ignore)253        .accessibilityLabel("\(theme.title), \(theme.summary)")254        .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton)255    }256}257
Files main
Menu

Theme