SPB Git

Repository Public

KeyView.swift 22.0 KB 489 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Keyboard9// File             : KeyboardUI/KeyView.swift10// Description      : One key cap: gradient glass fill, luminous border, bounded11//                    glow, crisp label or SF Symbol. Layer-backed, no per-frame12//                    work; the pressed state is an instant overlay (never13//                    delays input).14// Module           : KeyboardUI15// Repository       : https://git.spboucher.ai/sp-keyboard16// Created          : 2026-12-0117// Last Modified    : 2026-12-0118//19// =============================================================================20// AUTHOR & PROFESSIONAL AFFILIATION21// =============================================================================22//23// Author           : Simon-Pierre Boucher24// Position         : Professor of Finance25// Institution      : Université du Québec en Outaouais (UQO)26// Department       : Département des sciences administratives27// Organization     : SP Boucher28//29// Website          : https://spboucher.ai30// Git              : https://git.spboucher.ai31//32// =============================================================================33// OFFICIAL CONTACT DIRECTORY34// =============================================================================35//36// General          : info@spboucher.ai37// Professional     : contact@spboucher.ai38// Direct           : simon@spboucher.ai39// Research         : research@spboucher.ai40// Development      : dev@spboucher.ai41// Support          : support@spboucher.ai42// Security/Admin   : admin@spboucher.ai43// Notifications    : notifications@spboucher.ai44//45// Preferred Contact: support@spboucher.ai46//47// =============================================================================48// COPYRIGHT & INTELLECTUAL PROPERTY49// =============================================================================50//51// Copyright (c) 202652// Simon-Pierre Boucher53//54// All rights reserved where applicable.55//56// This file is governed by the applicable project license,57// copyright notices, institutional agreements and relevant law.58//59// Unless expressly authorized by the applicable license or60// rights holder, copying, redistribution, sublicensing,61// publication and commercial exploitation are not permitted.62//63// Existing third-party rights and notices remain unaffected.64//65// =============================================================================66// CONFIDENTIALITY & SECURITY67// =============================================================================68//69// Classification   : Public70// Distribution     : Public repository; use is governed by the project license71// Security Contact : admin@spboucher.ai72//73// Access to this source does not independently grant permission74// to redistribute or disclose confidential materials.75//76// Do not embed credentials, private keys, access tokens,77// certificates or confidential personal information.78//79// =============================================================================80// LICENSE & MAINTENANCE81// =============================================================================82//83// License          : None specified (no license file in this repository)84// Maintainer       : Simon-Pierre Boucher85// Technical Contact: dev@spboucher.ai86//87// =============================================================================88// END OF SP BOUCHER SOURCE HEADER89// =============================================================================9091import UIKit92import KeyboardCore93import ThemeEngine9495extension KeyTypeface {96    func font(size: CGFloat, weight: UIFont.Weight) -> UIFont {97        let base = UIFont.systemFont(ofSize: size, weight: weight)98        let design: UIFontDescriptor.SystemDesign99        switch self {100        case .system: return base101        case .rounded: design = .rounded102        case .serif: design = .serif103        case .mono: design = .monospaced104        }105        return base.fontDescriptor.withDesign(design).map { UIFont(descriptor: $0, size: size) } ?? base106    }107}108109/// One key cap: a hard edge underneath, the fill, an optional halo, the legend and its small hint.110/// Everything is a Core Animation layer and the pressed state is applied without animation, so nothing111/// stands between the finger and the insertion; only the release fades.112final class KeyView: UIView {113    private(set) var key: Key114    private let edge = CAShapeLayer()115    private let fill = CAGradientLayer()116    private let pressOverlay = CALayer()117    private let label = UILabel()118    private let hintLabel = UILabel()119    private let icon = UIImageView()120    private var theme: Theme = BuiltInThemes.default121    private var row = 0122    private var metrics = ThemeMetrics()123    /// Shift indicator states drawn by the shift key.124    var shiftState: ShiftState = .off {125        didSet {126            guard oldValue != shiftState else { return }127            if key.action == .shift { applyStyle() }128            updateContent()129        }130    }131    /// Legends fade while the space bar is used as a trackpad.132    var legendsDimmed = false { didSet { if oldValue != legendsDimmed { updateLegendAlpha(animated: true) } } }133134    init(key: Key) {135        self.key = key136        super.init(frame: .zero)137        isUserInteractionEnabled = false138        edge.fillRule = .evenOdd139        layer.addSublayer(edge)140        layer.addSublayer(fill)141        fill.masksToBounds = true142        pressOverlay.opacity = 0143        fill.addSublayer(pressOverlay)144        label.textAlignment = .center145        label.adjustsFontSizeToFitWidth = true146        label.minimumScaleFactor = 0.6147        label.baselineAdjustment = .alignCenters148        addSubview(label)149        hintLabel.textAlignment = .right150        hintLabel.isHidden = true151        addSubview(hintLabel)152        icon.contentMode = .center153        addSubview(icon)154        isAccessibilityElement = true155        accessibilityTraits = .keyboardKey156        updateContent()157    }158159    @available(*, unavailable)160    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }161162    func update(key: Key) {163        guard key != self.key else { return }164        let roleChanged = key.role != self.key.role || key.action != self.key.action165        self.key = key166        if roleChanged { applyStyle() }167        updateContent()168    }169170    func apply(theme: Theme, row: Int) {171        self.theme = theme172        self.row = row173        metrics = theme.metrics174        applyStyle()175        updateContent()176        setNeedsLayout()177    }178179    /// The style this key is drawn with right now. An engaged shift key takes the letter style, the way the180    /// system keyboard lights it up.181    private var style: KeyStyle {182        if key.action == .shift, shiftState != .off { return theme.letterKey }183        switch key.role {184        case .letter: return theme.letterKey185        case .function: return theme.functionKey186        case .accent: return theme.accentKey187        }188    }189190    private func applyStyle() {191        let style = style192        let isLetter = key.role == .letter193        let tint = isLetter ? theme.tint(forKey: key.id, row: row, fallback: style.border) : (theme.keyTints[key.id] ?? style.border)194        CATransaction.begin()195        CATransaction.setDisableActions(true)196        style.fill.apply(to: fill)197        fill.opacity = Float(metrics.keyOpacity)198        fill.cornerRadius = metrics.cornerRadius199        fill.cornerCurve = .continuous200        fill.borderWidth = metrics.borderWidth201        fill.borderColor = (isLetter && tint.a > 0 ? tint.opacity(max(style.border.a, 0.55)) : tint).cgColor202        pressOverlay.backgroundColor = theme.pressedTint.cgColor203        let depth = metrics.edgeDepth204        edge.isHidden = depth <= 0.01205        edge.fillColor = UIColor.black.withAlphaComponent((theme.isDark ? 0.62 : 0.34) * depth).cgColor206        // Halo of the vivid themes: tight and low, so the caps stay crisp.207        let glow = isLetter ? (tint.a > 0 ? tint : style.glow) : style.glow208        let intensity = metrics.glowIntensity209        layer.shadowColor = glow.opacity(1).cgColor210        layer.shadowOpacity = glow.a > 0.01 && intensity > 0.01 ? Float(0.5 * intensity) : 0211        layer.shadowRadius = 3.5 * intensity + 0.5212        layer.shadowOffset = .zero213        CATransaction.commit()214        label.textColor = style.text.uiColor215        icon.tintColor = style.text.uiColor216        hintLabel.textColor = style.text.opacity(0.5).uiColor217        updateLegendAlpha(animated: false)218        setNeedsLayout()219    }220221    private func updateContent() {222        var symbolName = key.symbol223        if key.action == .shift {224            symbolName = shiftState == .locked ? "capslock.fill" : (shiftState == .once ? "shift.fill" : "shift")225        }226        if let symbolName, let image = UIImage(systemName: symbolName, withConfiguration: UIImage.SymbolConfiguration(pointSize: 18, weight: .regular)) {227            icon.image = image228            icon.isHidden = false229            label.isHidden = true230        } else {231            icon.isHidden = true232            label.isHidden = false233            label.text = key.label234        }235        let typeface = theme.typeface ?? .system236        let isGlyph = key.label.count <= 2 && key.role == .letter && key.action != .space237        if isGlyph {238            let isLowercaseLetter = key.label.count == 1 && key.label == key.label.lowercased() && key.label != key.label.uppercased()239            label.font = typeface.font(size: key.label.count == 1 ? (isLowercaseLetter ? 24 : 22) : 18, weight: .regular)240        } else {241            label.font = typeface.font(size: key.action == .space ? 15 : 16, weight: .regular)242        }243        hintLabel.isHidden = key.hint == nil244        hintLabel.text = key.hint245        hintLabel.font = typeface.font(size: 10, weight: .medium)246        accessibilityLabel = key.accessibilityLabel ?? spokenLabel(key.label)247        if key.action == .shift {248            accessibilityValue = shiftState == .locked ? "verrouillée" : (shiftState == .once ? "activée" : "désactivée")249        }250        if key.isEnabled { accessibilityTraits.remove(.notEnabled) } else { accessibilityTraits.insert(.notEnabled) }251        updateLegendAlpha(animated: false)252        setNeedsLayout()253    }254255    private func updateLegendAlpha(animated: Bool) {256        var alpha: CGFloat = key.isEnabled ? 1 : 0.38257        // The language name on the space bar is a quiet caption, not a legend.258        if key.action == .space { alpha = 0.62 }259        if legendsDimmed { alpha = key.action == .space ? 0 : 0.16 }260        let change = { [self] in261            label.alpha = alpha262            icon.alpha = alpha263            hintLabel.alpha = legendsDimmed ? 0 : 1264        }265        if animated { UIView.animate(withDuration: 0.16, delay: 0, options: [.beginFromCurrentState, .allowUserInteraction], animations: change) } else { change() }266    }267268    private func spokenLabel(_ text: String) -> String {269        switch text {270        case ".": "point"271        case ",": "virgule"272        case "'": "apostrophe"273        case "@": "arobase"274        case "/": "barre oblique"275        default: text276        }277    }278279    /// VoiceOver double tap.280    var onActivate: (() -> Void)?281282    override func accessibilityActivate() -> Bool {283        guard let onActivate, key.isEnabled else { return false }284        onActivate()285        return true286    }287288    var isPressed = false {289        didSet {290            guard oldValue != isPressed else { return }291            pressOverlay.removeAllAnimations()292            CATransaction.begin()293            CATransaction.setDisableActions(true)294            pressOverlay.opacity = isPressed ? 1 : 0295            CATransaction.commit()296            if !isPressed, window != nil {297                let fade = CABasicAnimation(keyPath: "opacity")298                fade.fromValue = 1299                fade.toValue = 0300                fade.duration = 0.14301                fade.timingFunction = CAMediaTimingFunction(name: .easeOut)302                pressOverlay.add(fade, forKey: "release")303            }304        }305    }306307    override func layoutSubviews() {308        super.layoutSubviews()309        let radius = metrics.cornerRadius310        CATransaction.begin()311        CATransaction.setDisableActions(true)312        fill.frame = bounds313        pressOverlay.frame = bounds314        // The edge is the sliver of a cap shifted one point down that the cap itself does not cover: a315        // translucent fill never shows it through.316        let cap = UIBezierPath(roundedRect: bounds, cornerRadius: radius)317        let lowered = UIBezierPath(roundedRect: bounds.offsetBy(dx: 0, dy: 1), cornerRadius: radius)318        lowered.append(cap)319        edge.frame = bounds320        edge.path = lowered.cgPath321        layer.shadowPath = layer.shadowOpacity > 0 ? cap.cgPath : nil322        CATransaction.commit()323        label.frame = bounds.insetBy(dx: 2, dy: 1)324        icon.frame = bounds325        hintLabel.frame = CGRect(x: 0, y: 2, width: bounds.width - 4.5, height: 12)326        // A hinted cap sets its letter a touch lower so the two legends do not crowd each other.327        if key.hint != nil, bounds.height < 46 { label.frame = label.frame.offsetBy(dx: 0, dy: 1.5) }328    }329}330331/// Balloon that grows out of a pressed key, also used as the long-press alternates strip. One shape joins the332/// bubble to the key cap, so the legend visibly belongs to the key under the finger.333final class KeyPopupView: UIView {334    private let shape = CAShapeLayer()335    private let stack = UIStackView()336    private var labels: [UILabel] = []337    private(set) var options: [String] = []338    private(set) var selectedIndex = 0339    private var theme: Theme = BuiltInThemes.default340    private var surfaceColor: RGBA = .white341    /// Bubble part of the balloon, in the superview's coordinates.342    private(set) var bubbleFrame: CGRect = .zero343344    override init(frame: CGRect) {345        super.init(frame: frame)346        isUserInteractionEnabled = false347        layer.addSublayer(shape)348        shape.shadowOffset = CGSize(width: 0, height: 3)349        shape.shadowRadius = 7350        shape.lineWidth = 0.5351        stack.axis = .horizontal352        stack.distribution = .fillEqually353        stack.spacing = 2354        addSubview(stack)355        isHidden = true356    }357358    @available(*, unavailable)359    required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }360361    func apply(theme: Theme) {362        self.theme = theme363        // The balloon is the key cap, enlarged: same colour, made opaque so the legend is never read through it.364        let cap = theme.surface(under: theme.letterKey)365        surfaceColor = (theme.metrics.keyOpacity < 0.9 || theme.letterKey.fill.average.a < 0.9)366            ? (theme.isDark ? cap.mixed(with: .white, 0.14) : cap.mixed(with: .white, 0.6)).opacity(1)367            : cap.opacity(1)368        shape.fillColor = surfaceColor.cgColor369        shape.strokeColor = (theme.isDark ? RGBA.white.opacity(0.10) : RGBA.black.opacity(0.14)).cgColor370        shape.shadowColor = UIColor.black.cgColor371        shape.shadowOpacity = theme.isDark ? 0.5 : 0.22372    }373374    /// Shows `options` in a bubble above `keyFrame`, kept inside `container`.375    func show(options: [String], above keyFrame: CGRect, in container: CGRect, selected: Int = 0) {376        self.options = options377        labels.forEach { $0.removeFromSuperview() }378        let typeface = theme.typeface ?? .system379        labels = options.map { text in380            let label = UILabel()381            label.text = text382            label.textAlignment = .center383            label.font = typeface.font(size: options.count == 1 ? 32 : (text.count > 2 ? 17 : 23), weight: .regular)384            label.adjustsFontSizeToFitWidth = true385            label.minimumScaleFactor = 0.5386            label.layer.cornerRadius = 6387            label.layer.cornerCurve = .continuous388            label.layer.masksToBounds = true389            stack.addArrangedSubview(label)390            return label391        }392        let single = options.count == 1393        let cell = max(keyFrame.width, 34)394        let width = single ? keyFrame.width + 24 : min(CGFloat(options.count) * cell + 12, container.width - 4)395        let height = keyFrame.height + (single ? 12 : 8)396        var x = single ? keyFrame.midX - width / 2 : keyFrame.midX - cell / 2 - 6397        x = min(max(container.minX + 2, x), container.maxX - width - 2)398        let y = max(container.minY + 1, keyFrame.minY - height - 7)399        bubbleFrame = CGRect(x: x, y: y, width: width, height: height)400        frame = bubbleFrame.union(keyFrame).insetBy(dx: -1, dy: -1)401        let bubble = bubbleFrame.offsetBy(dx: -frame.minX, dy: -frame.minY)402        let cap = keyFrame.offsetBy(dx: -frame.minX, dy: -frame.minY)403        let path = Self.balloon(bubble: bubble, key: cap, keyRadius: min(theme.metrics.cornerRadius, cap.height / 2))404        CATransaction.begin()405        CATransaction.setDisableActions(true)406        shape.frame = bounds407        shape.path = path408        shape.shadowPath = path409        CATransaction.commit()410        stack.frame = bubble.insetBy(dx: 6, dy: 4)411        select(selected)412        isHidden = false413    }414415    /// Outline of a bubble whose lower edge narrows into the key cap beneath it.416    static func balloon(bubble: CGRect, key: CGRect, keyRadius: CGFloat) -> CGPath {417        let radius = min(10, bubble.height / 2, bubble.width / 2)418        let path = UIBezierPath()419        // Where the neck meets the cap; a bubble pushed down onto the key (top row of a short keyboard) has none.420        let neckBottom = max(key.minY + min(8, key.height * 0.25), bubble.maxY)421        let neckTop = bubble.maxY - radius422        path.move(to: CGPoint(x: bubble.minX + radius, y: bubble.minY))423        path.addLine(to: CGPoint(x: bubble.maxX - radius, y: bubble.minY))424        path.addArc(withCenter: CGPoint(x: bubble.maxX - radius, y: bubble.minY + radius), radius: radius, startAngle: -.pi / 2, endAngle: 0, clockwise: true)425        // A side where the bubble overhangs the key widely (alternates strip) closes its own corner and runs426        // along its lower edge before narrowing; otherwise the side flows straight into the cap.427        let shoulder: CGFloat = 12428        if bubble.maxX - key.maxX > shoulder + radius {429            path.addLine(to: CGPoint(x: bubble.maxX, y: bubble.maxY - radius))430            path.addArc(withCenter: CGPoint(x: bubble.maxX - radius, y: bubble.maxY - radius), radius: radius, startAngle: 0, endAngle: .pi / 2, clockwise: true)431            path.addLine(to: CGPoint(x: key.maxX + shoulder, y: bubble.maxY))432            path.addCurve(to: CGPoint(x: key.maxX, y: neckBottom),433                          controlPoint1: CGPoint(x: key.maxX + shoulder * 0.3, y: bubble.maxY),434                          controlPoint2: CGPoint(x: key.maxX, y: bubble.maxY + (neckBottom - bubble.maxY) * 0.3))435        } else {436            path.addLine(to: CGPoint(x: bubble.maxX, y: neckTop))437            path.addCurve(to: CGPoint(x: key.maxX, y: neckBottom),438                          controlPoint1: CGPoint(x: bubble.maxX, y: neckTop + (neckBottom - neckTop) * 0.55),439                          controlPoint2: CGPoint(x: key.maxX, y: neckTop + (neckBottom - neckTop) * 0.45))440        }441        path.addLine(to: CGPoint(x: key.maxX, y: key.maxY - keyRadius))442        path.addArc(withCenter: CGPoint(x: key.maxX - keyRadius, y: key.maxY - keyRadius), radius: keyRadius, startAngle: 0, endAngle: .pi / 2, clockwise: true)443        path.addLine(to: CGPoint(x: key.minX + keyRadius, y: key.maxY))444        path.addArc(withCenter: CGPoint(x: key.minX + keyRadius, y: key.maxY - keyRadius), radius: keyRadius, startAngle: .pi / 2, endAngle: .pi, clockwise: true)445        path.addLine(to: CGPoint(x: key.minX, y: neckBottom))446        if key.minX - bubble.minX > shoulder + radius {447            path.addCurve(to: CGPoint(x: key.minX - shoulder, y: bubble.maxY),448                          controlPoint1: CGPoint(x: key.minX, y: bubble.maxY + (neckBottom - bubble.maxY) * 0.3),449                          controlPoint2: CGPoint(x: key.minX - shoulder * 0.3, y: bubble.maxY))450            path.addLine(to: CGPoint(x: bubble.minX + radius, y: bubble.maxY))451            path.addArc(withCenter: CGPoint(x: bubble.minX + radius, y: bubble.maxY - radius), radius: radius, startAngle: .pi / 2, endAngle: .pi, clockwise: true)452        } else {453            path.addCurve(to: CGPoint(x: bubble.minX, y: neckTop),454                          controlPoint1: CGPoint(x: key.minX, y: neckTop + (neckBottom - neckTop) * 0.45),455                          controlPoint2: CGPoint(x: bubble.minX, y: neckTop + (neckBottom - neckTop) * 0.55))456        }457        path.addLine(to: CGPoint(x: bubble.minX, y: bubble.minY + radius))458        path.addArc(withCenter: CGPoint(x: bubble.minX + radius, y: bubble.minY + radius), radius: radius, startAngle: .pi, endAngle: -.pi / 2, clockwise: true)459        path.close()460        return path.cgPath461    }462463    func select(_ index: Int) {464        guard !labels.isEmpty else { return }465        selectedIndex = min(max(index, 0), labels.count - 1)466        let text = theme.letterKey.text.opacity(1).contrast(with: surfaceColor) >= 3 ? theme.letterKey.text : (theme.isDark ? RGBA.white : RGBA.black)467        for (offset, label) in labels.enumerated() {468            let isSelected = offset == selectedIndex && labels.count > 1469            label.backgroundColor = isSelected ? theme.accentKey.fill.average.opacity(1).uiColor : .clear470            label.textColor = isSelected ? theme.accentKey.text.uiColor : text.uiColor471        }472    }473474    /// Index of the option under horizontal position `x` (in the popup's superview coordinates).475    func index(at x: CGFloat) -> Int {476        guard !labels.isEmpty else { return 0 }477        let local = x - bubbleFrame.minX - 6478        let cell = (bubbleFrame.width - 12) / CGFloat(labels.count)479        return min(max(Int(local / max(cell, 1)), 0), labels.count - 1)480    }481482    var selectedOption: String? { options.indices.contains(selectedIndex) ? options[selectedIndex] : nil }483484    func hide() {485        isHidden = true486        options = []487    }488}489
Files main
Menu

Theme