Jotley / app / Shared / Views / RecordingIndicator.swift
| 1 | // Includes material adapted from AudioCap by Guilherme Rambo (copyright 2024). |
| 2 | // Upstream material retains BSD-2-Clause; see docs/Rambo-BSD-2-Clause.txt. |
| 3 | |
| 4 | import Combine |
| 5 | import SwiftUI |
| 6 | |
| 7 | struct RecordingIndicator: View { |
| 8 | #if os(macOS) |
| 9 | let appIcon: NSImage? |
| 10 | #else |
| 11 | let appIcon: UIImage? |
| 12 | #endif |
| 13 | let isRecording: Bool |
| 14 | let audioLevel: Float |
| 15 | var size: CGFloat = 22 |
| 16 | var isPaused: Bool = false // New parameter for paused state |
| 17 | var alwaysShowBars: Bool = false // New parameter to always show bars |
| 18 | |
| 19 | @ObservedObject private var themeManager = ThemeManager.shared |
| 20 | @State private var themeUpdateId = UUID() |
| 21 | |
| 22 | |
| 23 | var body: some View { |
| 24 | ZStack { |
| 25 | // The recordingViewContent will now handle what to display based on isRecording and isPaused |
| 26 | recordingViewContent |
| 27 | } |
| 28 | .id(themeUpdateId) |
| 29 | // Animate the transition between ready (green), recording (red), and paused (gray) states |
| 30 | .animation(.spring(response: 0.3, dampingFraction: 0.7), value: isRecording) |
| 31 | .animation(.spring(response: 0.3, dampingFraction: 0.7), value: isPaused) |
| 32 | .onChange(of: themeManager.currentThemeColor) { _, _ in |
| 33 | // Force a redraw so indicator bars immediately adopt the new theme accent. |
| 34 | themeUpdateId = UUID() |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | @ViewBuilder |
| 39 | private var recordingViewContent: some View { |
| 40 | if isPaused && isRecording { |
| 41 | // Paused state - grayed out |
| 42 | pausedStateView |
| 43 | .transition(.asymmetric( |
| 44 | insertion: .scale(scale: 0.5).combined(with: .opacity), |
| 45 | removal: .scale(scale: 0.5).combined(with: .opacity)) |
| 46 | ) |
| 47 | } else if isRecording { |
| 48 | recordingStateView |
| 49 | .transition(.asymmetric( |
| 50 | insertion: .scale(scale: 0.5).combined(with: .opacity), |
| 51 | removal: .scale(scale: 0.5).combined(with: .opacity)) |
| 52 | ) |
| 53 | } else { |
| 54 | readyStateView |
| 55 | .transition(.asymmetric( |
| 56 | insertion: .scale(scale: 0.5).combined(with: .opacity), |
| 57 | removal: .scale(scale: 0.5).combined(with: .opacity)) |
| 58 | ) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | @ViewBuilder |
| 63 | private var pausedStateView: some View { |
| 64 | ZStack { |
| 65 | Circle() |
| 66 | .fill(Color.gray.opacity(0.4)) |
| 67 | .frame(width: size, height: size) |
| 68 | |
| 69 | Image(systemName: "pause.fill") |
| 70 | .font(.system(size: self.size * 0.45)) |
| 71 | .foregroundColor(Color.gray) |
| 72 | } |
| 73 | .frame(width: size, height: size) // Ensure consistent frame |
| 74 | } |
| 75 | |
| 76 | @ViewBuilder |
| 77 | private var readyStateView: some View { |
| 78 | if alwaysShowBars { |
| 79 | // Always show bars for transcript button with random heights |
| 80 | HStack(spacing: size * 0.1) { |
| 81 | BarView(height: size, audioLevel: 0, delay: 0, alwaysShowBars: true) |
| 82 | BarView(height: size, audioLevel: 0, delay: 0.1, alwaysShowBars: true) |
| 83 | BarView(height: size, audioLevel: 0, delay: 0.2, alwaysShowBars: true) |
| 84 | } |
| 85 | .frame(width: size, height: size) |
| 86 | } else { |
| 87 | ZStack { |
| 88 | Circle() |
| 89 | .fill(Color.themePrimaryAccent) |
| 90 | .frame(width: size, height: size) |
| 91 | |
| 92 | // Use the parameterized iconView for the app icon |
| 93 | if appIcon != nil { |
| 94 | iconView(size: self.size * 0.55, fit: true) |
| 95 | } else { |
| 96 | // Fallback icon when no app icon is provided |
| 97 | Image(systemName: "mic.fill") |
| 98 | .font(.system(size: self.size * 0.5)) |
| 99 | .foregroundColor(Color.themeTextOnAccent) |
| 100 | } |
| 101 | } |
| 102 | .frame(width: size, height: size) // Ensure consistent frame |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | @ViewBuilder |
| 107 | private var recordingStateView: some View { |
| 108 | HStack(spacing: size * 0.1) { |
| 109 | // Recording bars should track meter level directly (no synthetic phase/jitter animation). |
| 110 | BarView( |
| 111 | height: size, |
| 112 | audioLevel: audioLevel, |
| 113 | delay: 0, |
| 114 | alwaysShowBars: true, |
| 115 | forceMotionAtLowInput: true, |
| 116 | baseHeightFactor: 0.10, |
| 117 | maxHeightFactor: 0.84, |
| 118 | growFromCenter: true |
| 119 | ) |
| 120 | BarView( |
| 121 | height: size, |
| 122 | audioLevel: audioLevel, |
| 123 | delay: 0, |
| 124 | alwaysShowBars: true, |
| 125 | forceMotionAtLowInput: true, |
| 126 | baseHeightFactor: 0.10, |
| 127 | maxHeightFactor: 1.0, |
| 128 | recordingResponseBoost: 1.28, |
| 129 | growFromCenter: true |
| 130 | ) |
| 131 | BarView( |
| 132 | height: size, |
| 133 | audioLevel: audioLevel, |
| 134 | delay: 0, |
| 135 | alwaysShowBars: true, |
| 136 | forceMotionAtLowInput: true, |
| 137 | baseHeightFactor: 0.10, |
| 138 | maxHeightFactor: 0.86, |
| 139 | growFromCenter: true |
| 140 | ) |
| 141 | } |
| 142 | .frame(width: size, height: size) |
| 143 | } |
| 144 | |
| 145 | // Bar component that animates based on audio level |
| 146 | private struct BarView: View { |
| 147 | let height: CGFloat |
| 148 | let audioLevel: Float |
| 149 | let delay: Double |
| 150 | var alwaysShowBars: Bool = false |
| 151 | var forceMotionAtLowInput: Bool = false |
| 152 | var baseHeightFactor: CGFloat = 0.2 |
| 153 | var maxHeightFactor: CGFloat = 0.95 |
| 154 | var recordingResponseBoost: CGFloat = 1.0 |
| 155 | var growFromCenter: Bool = false |
| 156 | |
| 157 | // Each bar gets its own motion state so bars move independently but smoothly. |
| 158 | @State private var randomFactor = Double.random(in: 0.75...1.1) |
| 159 | @State private var motionPhase = Double.random(in: 0...(2 * .pi)) |
| 160 | @State private var motionVelocity = Double.random(in: 0.32...0.54) |
| 161 | @State private var smoothedHeightFactor: CGFloat = 0.2 |
| 162 | // Keep timer identity stable across SwiftUI re-renders to avoid tick starvation. |
| 163 | @State private var animationTimer = Timer.publish(every: 1.0 / 60.0, on: .main, in: .common).autoconnect() |
| 164 | |
| 165 | private static let activeThreshold: Float = 0.001 |
| 166 | private static let minimumAnimatedLevel: Float = 0.05 |
| 167 | private static let levelBoost: Float = 5.4 |
| 168 | private static let recordingLevelGain: CGFloat = 18.0 |
| 169 | private static let recordingLevelCurveExponent: CGFloat = 0.38 |
| 170 | |
| 171 | // Constrain bar container size so unexpected parent layout never stretches bars vertically. |
| 172 | private var constrainedHeight: CGFloat { |
| 173 | min(max(height, 12), 28) |
| 174 | } |
| 175 | |
| 176 | private var barWidth: CGFloat { |
| 177 | constrainedHeight * 0.18 |
| 178 | } |
| 179 | |
| 180 | private var isActive: Bool { |
| 181 | effectiveLevel > 0 |
| 182 | } |
| 183 | |
| 184 | private var normalizedAudioLevel: CGFloat { |
| 185 | let clamped = min(max(CGFloat(audioLevel), 0), 1) |
| 186 | let gained = min(1, clamped * Self.recordingLevelGain) |
| 187 | // Strong low-end expansion so normal speech (not just loud peaks) visibly drives the bars. |
| 188 | let curved = CGFloat(pow(Double(gained), Double(Self.recordingLevelCurveExponent))) |
| 189 | return min(max(curved, 0), 1) |
| 190 | } |
| 191 | |
| 192 | private var effectiveLevel: Float { |
| 193 | if forceMotionAtLowInput { |
| 194 | return Float(normalizedAudioLevel) |
| 195 | } |
| 196 | |
| 197 | let boostedLevel = min(1.0, max(0, audioLevel) * Self.levelBoost) |
| 198 | guard boostedLevel >= Self.activeThreshold else { return 0 } |
| 199 | return max(boostedLevel, Self.minimumAnimatedLevel) |
| 200 | } |
| 201 | |
| 202 | private var targetHeightFactor: CGFloat { |
| 203 | if forceMotionAtLowInput { |
| 204 | let clampedMin = min(max(baseHeightFactor, 0.08), 0.45) |
| 205 | let clampedMax = min(max(maxHeightFactor, clampedMin + 0.2), 1.0) |
| 206 | // Keep low-volume bars shorter while preserving headroom at high input. |
| 207 | let shapedLevel = CGFloat(pow(Double(normalizedAudioLevel), 1.5)) |
| 208 | let boostedLevel = min(max(shapedLevel * recordingResponseBoost, 0), 1) |
| 209 | return clampedMin + boostedLevel * (clampedMax - clampedMin) |
| 210 | } |
| 211 | |
| 212 | // Expand quieter levels so activity remains visible with low amplitude inputs. |
| 213 | let normalized = min(max(CGFloat(pow(Double(effectiveLevel), 0.62)), 0), 1) |
| 214 | let floor = 0.26 + normalized * 0.2 |
| 215 | let ceil = 0.7 + normalized * 0.3 |
| 216 | let wave = CGFloat((sin(motionPhase + delay * 7.0) + 1.0) * 0.5) |
| 217 | let shapedWave = pow(wave, 0.78) |
| 218 | let pulse = min(max(shapedWave * CGFloat(randomFactor), 0), 1) |
| 219 | return min(max(floor + (ceil - floor) * pulse, 0.24), 1.0) |
| 220 | } |
| 221 | |
| 222 | private var activeBarHeight: CGFloat { |
| 223 | let minimumFactor = forceMotionAtLowInput ? 0.08 : 0.24 |
| 224 | return constrainedHeight * min(max(smoothedHeightFactor, minimumFactor), 1.0) |
| 225 | } |
| 226 | |
| 227 | private var snappedActiveBarHeight: CGFloat { |
| 228 | // Snap tiny updates to half-points to prevent shimmer/flicker at low heights. |
| 229 | max(1, (activeBarHeight * 2).rounded() / 2) |
| 230 | } |
| 231 | |
| 232 | private var barAlignment: Alignment { |
| 233 | growFromCenter ? .center : .bottom |
| 234 | } |
| 235 | |
| 236 | private func updateSmoothedHeight(animated: Bool, refreshJitter: Bool = false) { |
| 237 | let apply = { |
| 238 | if forceMotionAtLowInput { |
| 239 | // Track live audio with fast attack/medium release; no synthetic jitter in recording mode. |
| 240 | let response: CGFloat = targetHeightFactor > smoothedHeightFactor ? 0.82 : 0.58 |
| 241 | smoothedHeightFactor = smoothedHeightFactor * (1 - response) + targetHeightFactor * response |
| 242 | return |
| 243 | } |
| 244 | |
| 245 | if refreshJitter { |
| 246 | // Advance phase each tick for smooth motion and retune pulse subtly. |
| 247 | motionPhase += motionVelocity |
| 248 | if motionPhase > 2 * .pi { |
| 249 | motionPhase -= 2 * .pi |
| 250 | } |
| 251 | randomFactor = randomFactor * 0.8 + Double.random(in: 0.82...1.16) * 0.2 |
| 252 | motionVelocity = motionVelocity * 0.85 + Double.random(in: 0.3...0.58) * 0.15 |
| 253 | } |
| 254 | |
| 255 | if isActive || alwaysShowBars { |
| 256 | // Higher target weighting to follow live level changes more tightly. |
| 257 | smoothedHeightFactor = smoothedHeightFactor * 0.2 + targetHeightFactor * 0.8 |
| 258 | } else { |
| 259 | smoothedHeightFactor = 0.2 |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | if animated && !forceMotionAtLowInput { |
| 264 | let animation: Animation = .linear(duration: 0.06).delay(delay * 0.08) |
| 265 | withAnimation(animation) { |
| 266 | apply() |
| 267 | } |
| 268 | } else { |
| 269 | apply() |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | var body: some View { |
| 274 | ZStack(alignment: barAlignment) { |
| 275 | if isActive || forceMotionAtLowInput { |
| 276 | let accent = Color.themePrimaryAccent |
| 277 | |
| 278 | RoundedRectangle(cornerRadius: constrainedHeight * 0.1) |
| 279 | .fill(accent) |
| 280 | .frame(width: barWidth, height: snappedActiveBarHeight) |
| 281 | } else if alwaysShowBars { |
| 282 | // When alwaysShowBars is true: keep bars animated at moderate height. |
| 283 | let staticHeight = constrainedHeight * min(max(smoothedHeightFactor * 0.72, 0.22), 0.72) |
| 284 | let accent = Color.themePrimaryAccent |
| 285 | RoundedRectangle(cornerRadius: constrainedHeight * 0.1) |
| 286 | .fill(accent) |
| 287 | .frame(width: barWidth, height: staticHeight) |
| 288 | } else { |
| 289 | // When inactive: Display a small dot |
| 290 | let accent = Color.themePrimaryAccent |
| 291 | Circle() |
| 292 | .fill(accent) |
| 293 | .frame(width: barWidth, height: barWidth) |
| 294 | } |
| 295 | } |
| 296 | .frame(height: constrainedHeight, alignment: growFromCenter ? .center : .bottom) |
| 297 | .clipped() |
| 298 | // Apply the animation |
| 299 | .onChange(of: audioLevel) { oldValue, newValue in |
| 300 | if forceMotionAtLowInput { |
| 301 | updateSmoothedHeight(animated: false) |
| 302 | return |
| 303 | } |
| 304 | guard abs(newValue - oldValue) > 0.0001 else { return } |
| 305 | updateSmoothedHeight(animated: true) |
| 306 | } |
| 307 | .onReceive(animationTimer) { _ in |
| 308 | if forceMotionAtLowInput { |
| 309 | updateSmoothedHeight(animated: false) |
| 310 | return |
| 311 | } |
| 312 | guard isActive || alwaysShowBars else { return } |
| 313 | updateSmoothedHeight(animated: false, refreshJitter: true) |
| 314 | } |
| 315 | // Initialize state on appear |
| 316 | .onAppear { |
| 317 | // Initialize random factor for static bars |
| 318 | if alwaysShowBars && !isActive && !forceMotionAtLowInput { |
| 319 | randomFactor = Double.random(in: 0.3...0.8) // Different range for static display |
| 320 | } |
| 321 | smoothedHeightFactor = forceMotionAtLowInput ? targetHeightFactor : (isActive ? targetHeightFactor : 0.2) |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | |
| 326 | @ViewBuilder |
| 327 | private func iconView(size: CGFloat, fit: Bool = false) -> some View { |
| 328 | #if os(macOS) |
| 329 | if let appIcon = appIcon { |
| 330 | Image(nsImage: appIcon) |
| 331 | .resizable() |
| 332 | .aspectRatio(contentMode: fit ? .fit : .fill) // Use parameter |
| 333 | .frame(width: size, height: size) |
| 334 | } |
| 335 | #else |
| 336 | if let appIcon = appIcon { |
| 337 | Image(uiImage: appIcon) |
| 338 | .resizable() |
| 339 | .aspectRatio(contentMode: fit ? .fit : .fill) // Use parameter |
| 340 | .frame(width: size, height: size) |
| 341 | } |
| 342 | #endif |
| 343 | } |
| 344 | } |
| 345 | |
| 346 | #if DEBUG |
| 347 | struct RecordingIndicatorPreview: View { |
| 348 | @State private var isRecording = false |
| 349 | @State private var previewAudioLevel: Float = 0.0 |
| 350 | |
| 351 | var body: some View { |
| 352 | VStack { |
| 353 | HStack(spacing: 8) { |
| 354 | RecordingIndicator( |
| 355 | appIcon: nil, |
| 356 | isRecording: isRecording, |
| 357 | audioLevel: previewAudioLevel |
| 358 | ) |
| 359 | |
| 360 | Text(isRecording ? "Transcribing (Level: \(String(format: "%.2f", previewAudioLevel)))" : "Ready to Transcribe") |
| 361 | .font(.headline) |
| 362 | .contentTransition(.identity) |
| 363 | } |
| 364 | .animation(.bouncy(extraBounce: 0.1), value: isRecording) |
| 365 | .frame(maxWidth: .infinity, alignment: .leading) |
| 366 | .padding(32) |
| 367 | .contentShape(Rectangle()) |
| 368 | .onTapGesture { |
| 369 | isRecording.toggle() |
| 370 | if !isRecording { |
| 371 | previewAudioLevel = 0.0 |
| 372 | } |
| 373 | } |
| 374 | |
| 375 | if isRecording { |
| 376 | Slider(value: $previewAudioLevel, in: 0...1) |
| 377 | .padding() |
| 378 | } |
| 379 | } |
| 380 | } |
| 381 | } |
| 382 | #Preview("Transcription Indicator") { |
| 383 | RecordingIndicatorPreview() |
| 384 | } |
| 385 | #endif |