SPB Git

Repository Public

BackdropView.swift 15.9 KB 363 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : KeyboardUI/BackdropView.swift10// Description      : Keyboard backdrop: multi-stop gradient, optional local11//                    photo, and one cheap Core Animation recipe per theme12//                    effect (aurora ribbons, plasma, stars, iridescent sweep…).13//                    Animations run only while the view is on screen and motion14//                    is allowed; a static frame is the fallback.15// Module           : KeyboardUI16// Repository       : https://git.spboucher.ai/sp-keyboard17// Created          : 2026-12-0118// Last Modified    : 2026-12-0119//20// =============================================================================21// AUTHOR & PROFESSIONAL AFFILIATION22// =============================================================================23//24// Author           : Simon-Pierre Boucher25// Position         : Professor of Finance26// Institution      : Université du Québec en Outaouais (UQO)27// Department       : Département des sciences administratives28// Organization     : SP Boucher29//30// Website          : https://spboucher.ai31// Git              : https://git.spboucher.ai32//33// =============================================================================34// OFFICIAL CONTACT DIRECTORY35// =============================================================================36//37// General          : info@spboucher.ai38// Professional     : contact@spboucher.ai39// Direct           : simon@spboucher.ai40// Research         : research@spboucher.ai41// Development      : dev@spboucher.ai42// Support          : support@spboucher.ai43// Security/Admin   : admin@spboucher.ai44// Notifications    : notifications@spboucher.ai45//46// Preferred Contact: support@spboucher.ai47//48// =============================================================================49// COPYRIGHT & INTELLECTUAL PROPERTY50// =============================================================================51//52// Copyright (c) 202653// Simon-Pierre Boucher54//55// All rights reserved where applicable.56//57// This file is governed by the applicable project license,58// copyright notices, institutional agreements and relevant law.59//60// Unless expressly authorized by the applicable license or61// rights holder, copying, redistribution, sublicensing,62// publication and commercial exploitation are not permitted.63//64// Existing third-party rights and notices remain unaffected.65//66// =============================================================================67// CONFIDENTIALITY & SECURITY68// =============================================================================69//70// Classification   : Public71// Distribution     : Public repository; use is governed by the project license72// Security Contact : admin@spboucher.ai73//74// Access to this source does not independently grant permission75// to redistribute or disclose confidential materials.76//77// Do not embed credentials, private keys, access tokens,78// certificates or confidential personal information.79//80// =============================================================================81// LICENSE & MAINTENANCE82// =============================================================================83//84// License          : None specified (no license file in this repository)85// Maintainer       : Simon-Pierre Boucher86// Technical Contact: dev@spboucher.ai87//88// =============================================================================89// END OF SP BOUCHER SOURCE HEADER90// =============================================================================9192import UIKit93import ThemeEngine9495extension RGBA {96    var uiColor: UIColor { UIColor(red: r, green: g, blue: b, alpha: a) }97    var cgColor: CGColor { uiColor.cgColor }98}99100extension GradientSpec {101    /// Configures a gradient layer; a single colour is drawn as a flat fill.102    func apply(to layer: CAGradientLayer) {103        let list = colors.isEmpty ? [RGBA.black] : colors104        layer.colors = (list.count == 1 ? [list[0], list[0]] : list).map(\.cgColor)105        let points = unitPoints106        layer.startPoint = CGPoint(x: points.start.x, y: points.start.y)107        layer.endPoint = CGPoint(x: points.end.x, y: points.end.y)108    }109}110111/// How one `BackdropEffect` is drawn.112struct EffectRecipe {113    var blobs = 0114    var blobOpacity: Float = 0.5115    var blobScale: CGFloat = 0.9116    var duration: CFTimeInterval = 10117    var sweep = false118    var sweepOpacity: Float = 0.18119    var stars = 0120    var topLine = false121122    static func recipe(for effect: BackdropEffect) -> EffectRecipe {123        switch effect {124        case .none: EffectRecipe()125        case .aurora: EffectRecipe(blobs: 4, blobOpacity: 0.55, blobScale: 1.1, duration: 11, sweep: true, sweepOpacity: 0.10)126        case .neon: EffectRecipe(blobs: 2, blobOpacity: 0.32, blobScale: 0.8, duration: 7, topLine: true)127        case .plasma: EffectRecipe(blobs: 3, blobOpacity: 0.5, blobScale: 1.0, duration: 6)128        case .waves: EffectRecipe(blobs: 3, blobOpacity: 0.4, blobScale: 1.3, duration: 9, sweep: true, sweepOpacity: 0.12)129        case .stars: EffectRecipe(blobs: 2, blobOpacity: 0.3, blobScale: 1.0, duration: 16, stars: 26)130        case .iridescence: EffectRecipe(blobs: 6, blobOpacity: 0.45, blobScale: 0.8, duration: 8, sweep: true, sweepOpacity: 0.22)131        case .glass: EffectRecipe(blobs: 3, blobOpacity: 0.5, blobScale: 1.0, duration: 14, sweep: true, sweepOpacity: 0.25)132        case .energy: EffectRecipe(blobs: 2, blobOpacity: 0.16, blobScale: 0.9, duration: 5, topLine: true)133        case .crystal: EffectRecipe(blobs: 2, blobOpacity: 0.45, blobScale: 1.0, duration: 13, sweep: true, sweepOpacity: 0.35)134        case .luxe: EffectRecipe(blobs: 2, blobOpacity: 0.20, blobScale: 1.0, duration: 15, sweep: true, sweepOpacity: 0.10, stars: 8)135        case .heat: EffectRecipe(blobs: 3, blobOpacity: 0.36, blobScale: 1.0, duration: 6)136        }137    }138}139140final class BackdropView: UIView {141    private let gradient = CAGradientLayer()142    private let imageLayer = CALayer()143    private let dimLayer = CALayer()144    private let effectContainer = CALayer()145    private var blobLayers: [CAGradientLayer] = []146    private var starLayers: [CALayer] = []147    private let sweepLayer = CAGradientLayer()148    private let topLine = CAGradientLayer()149    private var theme: Theme = BuiltInThemes.default150    private var recipe = EffectRecipe()151    private var loadedImageName: String?152    private var isAnimating = false153    /// Set by the owner on a memory warning: the backdrop stays static until the next theme change.154    var forceStatic = false { didSet { if forceStatic { stopAnimating() } } }155156    override init(frame: CGRect) {157        super.init(frame: frame)158        isUserInteractionEnabled = false159        clipsToBounds = true160        layer.addSublayer(gradient)161        imageLayer.contentsGravity = .resizeAspectFill162        imageLayer.masksToBounds = true163        layer.addSublayer(imageLayer)164        layer.addSublayer(dimLayer)165        effectContainer.masksToBounds = true166        layer.addSublayer(effectContainer)167        sweepLayer.startPoint = CGPoint(x: 0, y: 0.5)168        sweepLayer.endPoint = CGPoint(x: 1, y: 0.5)169        topLine.startPoint = CGPoint(x: 0, y: 0.5)170        topLine.endPoint = CGPoint(x: 1, y: 0.5)171    }172173    @available(*, unavailable)174    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }175176    func apply(_ theme: Theme) {177        self.theme = theme178        recipe = EffectRecipe.recipe(for: theme.effect)179        forceStatic = false180        theme.background.apply(to: gradient)181        loadImage(named: theme.backgroundImage)182        dimLayer.backgroundColor = (theme.isDark ? UIColor.black : UIColor.white).withAlphaComponent(theme.imageDim).cgColor183        dimLayer.isHidden = imageLayer.contents == nil184        rebuildEffectLayers()185        setNeedsLayout()186        updateAnimationState()187    }188189    private func loadImage(named name: String?) {190        guard let name else {191            imageLayer.contents = nil192            loadedImageName = nil193            return194        }195        guard name != loadedImageName else { return }196        loadedImageName = name197        imageLayer.contents = nil198        guard let url = ThemeLibrary.backgroundURL(named: name),199              let size = (try? url.resourceValues(forKeys: [.fileSizeKey]))?.fileSize, size <= ThemeLibrary.maxBackgroundBytes * 2,200              let source = CGImageSourceCreateWithURL(url as CFURL, nil) else { return }201        // Decode at most at the stored size: the photo was already resized by the app.202        let options: [CFString: Any] = [kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceCreateThumbnailWithTransform: true,203                                        kCGImageSourceThumbnailMaxPixelSize: ThemeLibrary.maxBackgroundPixels]204        imageLayer.contents = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary)205    }206207    private func rebuildEffectLayers() {208        effectContainer.sublayers?.forEach { $0.removeFromSuperlayer() }209        blobLayers = []210        starLayers = []211        let colors = theme.effectColors.isEmpty ? [theme.accentKey.glow] : theme.effectColors212        guard theme.effect != .none, imageLayer.contents == nil || recipe.sweep else { return }213        if imageLayer.contents == nil {214            for index in 0..<recipe.blobs {215                let blob = CAGradientLayer()216                blob.type = .radial217                let color = colors[index % colors.count]218                blob.colors = [color.opacity(1).cgColor, color.opacity(0.35).cgColor, color.opacity(0).cgColor]219                blob.locations = [0, 0.45, 1]220                blob.startPoint = CGPoint(x: 0.5, y: 0.5)221                blob.endPoint = CGPoint(x: 1, y: 1)222                blob.opacity = recipe.blobOpacity223                effectContainer.addSublayer(blob)224                blobLayers.append(blob)225            }226            for index in 0..<recipe.stars {227                let star = CALayer()228                let color = colors[index % colors.count]229                star.backgroundColor = color.opacity(1).cgColor230                star.opacity = 0.35 + Float(index % 5) * 0.12231                effectContainer.addSublayer(star)232                starLayers.append(star)233            }234        }235        if recipe.sweep {236            let tint = theme.isDark ? UIColor.white : UIColor.white237            sweepLayer.colors = [tint.withAlphaComponent(0).cgColor, tint.withAlphaComponent(CGFloat(recipe.sweepOpacity)).cgColor, tint.withAlphaComponent(0).cgColor]238            sweepLayer.locations = [0, 0.5, 1]239            effectContainer.addSublayer(sweepLayer)240        }241        if recipe.topLine {242            let list = colors.count > 1 ? colors : [colors[0], colors[0]]243            topLine.colors = list.map { $0.opacity(0.9).cgColor }244            effectContainer.addSublayer(topLine)245        }246    }247248    override func layoutSubviews() {249        super.layoutSubviews()250        CATransaction.begin()251        CATransaction.setDisableActions(true)252        gradient.frame = bounds253        imageLayer.frame = bounds254        dimLayer.frame = bounds255        effectContainer.frame = bounds256        let width = bounds.width, height = bounds.height257        for (index, blob) in blobLayers.enumerated() {258            let side = max(width, height) * recipe.blobScale * (0.7 + 0.12 * CGFloat(index % 3))259            let count = CGFloat(max(blobLayers.count, 1))260            let x = width * (CGFloat(index) + 0.5) / count261            let y = height * (index % 2 == 0 ? 0.28 : 0.72)262            blob.bounds = CGRect(x: 0, y: 0, width: side, height: side * 0.75)263            blob.position = CGPoint(x: x, y: y)264        }265        // Deterministic pseudo-random star field (same layout for the same size).266        var seed: UInt64 = 0x9E3779B97F4A7C15267        func next() -> CGFloat {268            seed ^= seed << 13269            seed ^= seed >> 7270            seed ^= seed << 17271            return CGFloat(seed % 10_000) / 10_000272        }273        for star in starLayers {274            let size = 1.2 + next() * 1.8275            star.frame = CGRect(x: next() * width, y: next() * height, width: size, height: size)276            star.cornerRadius = size / 2277        }278        sweepLayer.bounds = CGRect(x: 0, y: 0, width: width * 0.6, height: height * 1.6)279        sweepLayer.position = CGPoint(x: width * 0.3, y: height / 2)280        sweepLayer.setAffineTransform(CGAffineTransform(rotationAngle: -0.35))281        topLine.frame = CGRect(x: 0, y: 0, width: width, height: 1.5)282        CATransaction.commit()283        if isAnimating { restartAnimations() }284    }285286    override func didMoveToWindow() {287        super.didMoveToWindow()288        updateAnimationState()289    }290291    func updateAnimationState() {292        let shouldAnimate = window != nil && theme.motion != .off && !forceStatic && theme.effect != .none293            && !ProcessInfo.processInfo.isLowPowerModeEnabled294        if shouldAnimate { startAnimating() } else { stopAnimating() }295    }296297    private func startAnimating() {298        guard !isAnimating else { return }299        isAnimating = true300        restartAnimations()301    }302303    func stopAnimating() {304        guard isAnimating else { return }305        isAnimating = false306        (blobLayers as [CALayer] + starLayers + [sweepLayer, topLine]).forEach { $0.removeAllAnimations() }307    }308309    private func restartAnimations() {310        guard bounds.width > 0 else { return }311        let slow = theme.motion == .subtle ? 1.8 : 1.0312        let travel = theme.motion == .subtle ? 0.5 : 1.0313        for (index, blob) in blobLayers.enumerated() {314            blob.removeAllAnimations()315            let drift = CABasicAnimation(keyPath: "position")316            let dx = bounds.width * 0.22 * travel * (index % 2 == 0 ? 1 : -1)317            let dy = bounds.height * 0.18 * travel * (index % 3 == 0 ? -1 : 1)318            drift.fromValue = NSValue(cgPoint: blob.position)319            drift.toValue = NSValue(cgPoint: CGPoint(x: blob.position.x + dx, y: blob.position.y + dy))320            let pulse = CABasicAnimation(keyPath: "opacity")321            pulse.fromValue = recipe.blobOpacity322            pulse.toValue = recipe.blobOpacity * 0.55323            let group = CAAnimationGroup()324            group.animations = [drift, pulse]325            group.duration = (recipe.duration + Double(index) * 1.7) * slow326            group.autoreverses = true327            group.repeatCount = .infinity328            group.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)329            blob.add(group, forKey: "drift")330        }331        for (index, star) in starLayers.enumerated() where index % 2 == 0 {332            star.removeAllAnimations()333            let twinkle = CABasicAnimation(keyPath: "opacity")334            twinkle.fromValue = star.opacity335            twinkle.toValue = 0.08336            twinkle.duration = (2.4 + Double(index % 7) * 0.5) * slow337            twinkle.autoreverses = true338            twinkle.repeatCount = .infinity339            star.add(twinkle, forKey: "twinkle")340        }341        if recipe.sweep {342            sweepLayer.removeAllAnimations()343            let sweep = CABasicAnimation(keyPath: "position.x")344            sweep.fromValue = -bounds.width * 0.4345            sweep.toValue = bounds.width * 1.4346            sweep.duration = recipe.duration * 0.9 * slow347            sweep.repeatCount = .infinity348            sweep.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)349            sweepLayer.add(sweep, forKey: "sweep")350        }351        if recipe.topLine {352            topLine.removeAllAnimations()353            let glow = CABasicAnimation(keyPath: "opacity")354            glow.fromValue = 1355            glow.toValue = 0.35356            glow.duration = 1.6 * slow357            glow.autoreverses = true358            glow.repeatCount = .infinity359            topLine.add(glow, forKey: "glow")360        }361    }362}363
Files main
Menu

Theme