ActiveRecordingView.swift 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  1. import SwiftUI
  2. import SwiftData
  3. import UIKit
  4. // MARK: - ActiveRecordingView
  5. /// The live recording screen showing real-time waveform, elapsed time,
  6. /// and quick-action buttons for adding photos and notes during a session.
  7. /// Fully redesigned to use a minimalist business-focused line-drawn UI.
  8. struct ActiveRecordingView: View {
  9. @Environment(\.modelContext) private var modelContext
  10. @Environment(\.dismiss) private var dismiss
  11. @ObservedObject private var syncManager: SyncManager = .shared
  12. let session: CelestiaSession
  13. var initialDuration: TimeInterval = 0
  14. let recordingSource: RecordingSourceChoice
  15. var initialAction: RecordingLiveActivityAction? = nil
  16. var onFinishRecording: (() -> Void)? = nil
  17. @State private var recordingVM: RecordingViewModel
  18. @State private var showNoteSheet = false
  19. @State private var showPhotoEditor = false
  20. @State private var noteText = ""
  21. @State private var noteLocation: TimelineLocation?
  22. @State private var pendingNoteTimeMs: Double = 0
  23. @State private var pendingPhotoTimeMs: Double = 0
  24. @State private var latestEvent: CelestiaTimelineEvent?
  25. @State private var latestEventVisible = false
  26. @State private var isEndingRecording = false
  27. @State private var stopErrorMessage: String?
  28. @State private var photoSaveError: String?
  29. @State private var recordName: String
  30. @State private var showRecordNameEditor = false
  31. @State private var hasStartedLiveActivity = false
  32. @State private var hasAddedContinuationMarker = false
  33. @State private var pendingInitialAction: RecordingLiveActivityAction?
  34. init(
  35. session: CelestiaSession,
  36. initialDuration: TimeInterval = 0,
  37. recordingSource: RecordingSourceChoice = .iPhone,
  38. initialAction: RecordingLiveActivityAction? = nil,
  39. onFinishRecording: (() -> Void)? = nil
  40. ) {
  41. self.session = session
  42. self.initialDuration = initialDuration
  43. self.recordingSource = recordingSource
  44. self.initialAction = initialAction
  45. self.onFinishRecording = onFinishRecording
  46. _recordingVM = State(initialValue: RecordingViewModel(source: recordingSource))
  47. _recordName = State(initialValue: session.title)
  48. _pendingInitialAction = State(initialValue: initialAction)
  49. }
  50. var body: some View {
  51. ZStack(alignment: .top) {
  52. // Dynamic clean background
  53. Color.spaceBlack
  54. .ignoresSafeArea()
  55. .contentShape(Rectangle())
  56. .onTapGesture(count: 2) {
  57. endRecording()
  58. }
  59. VStack(spacing: 0) {
  60. recordNameSection
  61. .padding(.horizontal, 24)
  62. .padding(.top, 16)
  63. .padding(.bottom, 14)
  64. // Top Header Block (Timecode + Indicator)
  65. VStack(spacing: 16) {
  66. timecodeSection
  67. recordingIndicator
  68. }
  69. .padding(.bottom, 24)
  70. // Live Waveform
  71. waveformSection
  72. .padding(.horizontal, 24)
  73. .padding(.bottom, 20)
  74. // Latest Event Card
  75. latestEventCard
  76. .padding(.horizontal, 24)
  77. .padding(.bottom, 20)
  78. Spacer()
  79. // Action Buttons
  80. actionButtons
  81. .padding(.horizontal, 48)
  82. .padding(.bottom, 32)
  83. // Recording Controls
  84. recordingControlButtons
  85. .padding(.bottom, 24)
  86. }
  87. .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
  88. .ignoresSafeArea(.keyboard, edges: .bottom)
  89. }
  90. .ignoresSafeArea(.keyboard, edges: .bottom)
  91. .toolbar(.hidden, for: .tabBar)
  92. .toolbar(.hidden, for: .navigationBar)
  93. .navigationBarHidden(true)
  94. .navigationBarBackButtonHidden(true)
  95. .sheet(isPresented: $showRecordNameEditor) {
  96. recordNameEditorSheet
  97. }
  98. .sheet(isPresented: $showNoteSheet) {
  99. noteInputSheet
  100. }
  101. .sheet(isPresented: $showPhotoEditor) {
  102. PhotoRecordEditorSheet(
  103. timeLabel: formattedNoteTime(pendingPhotoTimeMs)
  104. ) { drafts, location in
  105. savePhotosAndAddEvents(drafts, location: location)
  106. }
  107. }
  108. .onAppear {
  109. UIApplication.shared.isIdleTimerDisabled = true
  110. recordingVM.startRecording(initialDuration: initialDuration)
  111. }
  112. .onChange(of: recordingVM.isRecording) { _, isRecording in
  113. if isRecording {
  114. addContinuationMarkerIfNeeded()
  115. performPendingInitialActionIfReady()
  116. }
  117. guard isRecording, !hasStartedLiveActivity else { return }
  118. hasStartedLiveActivity = true
  119. RecordingLiveActivityManager.shared.start(
  120. sessionID: session.id,
  121. title: session.title,
  122. sourceName: recordingVM.sourceDisplayName,
  123. elapsedSeconds: recordingVM.elapsedTime
  124. )
  125. }
  126. .onChange(of: recordingVM.outputFileURL) { _, outputURL in
  127. guard let outputURL else { return }
  128. RecordingRecoveryStore.setPendingSegment(outputURL, for: session.id)
  129. }
  130. .onChange(of: recordingVM.isPaused) { _, isPaused in
  131. guard hasStartedLiveActivity else { return }
  132. RecordingLiveActivityManager.shared.update(
  133. elapsedSeconds: recordingVM.elapsedTime,
  134. isPaused: isPaused
  135. )
  136. }
  137. .onOpenURL { url in
  138. handleRecordingURL(url)
  139. }
  140. .onReceive(NotificationCenter.default.publisher(for: .recordingLiveActivityCommand)) {
  141. handleLiveActivityCommand($0)
  142. }
  143. .onDisappear {
  144. UIApplication.shared.isIdleTimerDisabled = false
  145. commitRecordName()
  146. if recordingVM.isRecording {
  147. recordingVM.stopRecording()
  148. }
  149. if hasStartedLiveActivity {
  150. RecordingLiveActivityManager.shared.end(elapsedSeconds: recordingVM.elapsedTime)
  151. hasStartedLiveActivity = false
  152. }
  153. }
  154. .alert("无法结束设备录音", isPresented: Binding(
  155. get: { stopErrorMessage != nil },
  156. set: { if !$0 { stopErrorMessage = nil } }
  157. )) {
  158. Button("重试") { endRecording() }
  159. Button("继续录音", role: .cancel) { stopErrorMessage = nil }
  160. } message: {
  161. Text(stopErrorMessage ?? "请确认微光仍在附近并保持连接。")
  162. }
  163. .alert("照片保存失败", isPresented: Binding(
  164. get: { photoSaveError != nil },
  165. set: { if !$0 { photoSaveError = nil } }
  166. )) {
  167. Button("知道了", role: .cancel) {}
  168. } message: {
  169. Text(photoSaveError ?? "请稍后重试。")
  170. }
  171. }
  172. // MARK: - Record Name
  173. private var recordNameSection: some View {
  174. Button {
  175. recordName = session.title
  176. showRecordNameEditor = true
  177. } label: {
  178. VStack(alignment: .leading, spacing: 8) {
  179. HStack(spacing: 6) {
  180. Text("记录名称")
  181. .font(.system(size: 10, weight: .semibold, design: .monospaced))
  182. .tracking(1.4)
  183. Spacer()
  184. Image(systemName: "pencil")
  185. .font(.system(size: 11, weight: .semibold))
  186. }
  187. .foregroundStyle(Color.secondary)
  188. Text(session.title)
  189. .font(.system(size: 19, weight: .semibold))
  190. .foregroundStyle(Color.primary)
  191. .lineLimit(1)
  192. .frame(maxWidth: .infinity, alignment: .leading)
  193. Rectangle()
  194. .fill(Color.primary.opacity(0.16))
  195. .frame(height: 1)
  196. }
  197. .padding(.horizontal, 14)
  198. .padding(.vertical, 12)
  199. .background(Color.cardBackground.opacity(0.45))
  200. .businessBorder(cornerRadius: 8)
  201. .contentShape(Rectangle())
  202. }
  203. .buttonStyle(.plain)
  204. }
  205. private var recordNameEditorSheet: some View {
  206. RecordNameEditorSheet(recordName: $recordName) {
  207. saveRecordNameAndCloseEditor()
  208. } onCancel: {
  209. recordName = session.title
  210. showRecordNameEditor = false
  211. }
  212. }
  213. // MARK: - Timecode
  214. private var timecodeSection: some View {
  215. Text(recordingVM.elapsedTimeFormatted)
  216. .font(.system(size: 52, weight: .light))
  217. .monospacedDigit()
  218. .foregroundStyle(Color.primary)
  219. .contentTransition(.numericText(countsDown: false))
  220. .frame(height: 64)
  221. }
  222. // MARK: - Recording Indicator
  223. private var recordingIndicator: some View {
  224. VStack(spacing: 8) {
  225. HStack(spacing: 8) {
  226. TimelineView(.periodic(from: .now, by: 1.0)) { context in
  227. let isEven = Int(context.date.timeIntervalSince1970) % 2 == 0
  228. Circle()
  229. .fill(recordingVM.isRecording && !recordingVM.isPaused ? Color.recordingRed : Color.secondary)
  230. .frame(width: 8, height: 8)
  231. .opacity(recordingVM.isRecording && !recordingVM.isPaused ? (isEven ? 1.0 : 0.3) : 0.6)
  232. .animation(.easeInOut(duration: 0.5), value: isEven)
  233. }
  234. .frame(width: 10, height: 10)
  235. Text(recordingVM.isPaused ? "已暂停" : recordingVM.statusMessage)
  236. .font(.system(size: 11, weight: .semibold, design: .monospaced))
  237. .foregroundStyle(recordingVM.isRecording && !recordingVM.isPaused ? Color.recordingRed : Color.secondary)
  238. .tracking(1.2)
  239. }
  240. HStack(spacing: 6) {
  241. Image(systemName: recordingSource.systemImage)
  242. .font(.system(size: 11, weight: .medium))
  243. Text("设备:\(recordingVM.sourceDisplayName)")
  244. .font(.system(size: 11, weight: .medium))
  245. }
  246. .foregroundStyle(Color.primary.opacity(0.85))
  247. if let error = recordingVM.errorMessage {
  248. Text(error)
  249. .font(.system(size: 10))
  250. .foregroundStyle(Color.recordingRed)
  251. .multilineTextAlignment(.center)
  252. .lineLimit(2)
  253. }
  254. }
  255. .padding(.horizontal, 10)
  256. .padding(.vertical, 8)
  257. .businessBorder(cornerRadius: 6)
  258. }
  259. // MARK: - Waveform
  260. private var waveformSection: some View {
  261. VStack(spacing: 0) {
  262. LiveWaveformView(samples: recordingVM.waveformSamples)
  263. .frame(height: 90)
  264. // Graphical VU Meter + Numeric Display
  265. HStack(spacing: 10) {
  266. AmplitudeLevelMeterView(amplitude: recordingVM.currentAmplitude)
  267. Spacer(minLength: 0)
  268. Text(String(format: "%02.0f%%", recordingVM.currentAmplitude * 100))
  269. .font(.system(size: 9, weight: .medium, design: .monospaced))
  270. .foregroundStyle(recordingVM.currentAmplitude > 0.85 ? Color.recordingRed : Color.secondary)
  271. }
  272. .padding(.horizontal, 4)
  273. .padding(.top, 10)
  274. }
  275. .frame(height: 114)
  276. }
  277. // MARK: - Latest Event Card
  278. private var latestEventCard: some View {
  279. ZStack { // Fix: Use ZStack instead of Group to enforce the fixed frame even when empty
  280. if let event = latestEvent, latestEventVisible {
  281. HStack(spacing: 12) {
  282. Image(systemName: event.eventIcon)
  283. .font(.system(size: 12))
  284. .foregroundStyle(Color.primary)
  285. .frame(width: 28, height: 28)
  286. .businessBorder(cornerRadius: 14)
  287. VStack(alignment: .leading, spacing: 2) {
  288. Text(eventLabel(for: event.eventType))
  289. .font(.system(size: 11, weight: .semibold))
  290. .foregroundStyle(Color.primary)
  291. if let text = event.textContent {
  292. Text(text)
  293. .font(.system(size: 12))
  294. .foregroundStyle(Color.secondary)
  295. .lineLimit(1)
  296. }
  297. }
  298. Spacer()
  299. Text(event.relativeTimeFormatted)
  300. .font(.system(size: 11, weight: .regular, design: .monospaced))
  301. .foregroundStyle(Color.secondary)
  302. }
  303. .padding(12)
  304. .background(Color.cardBackground.opacity(0.4))
  305. .businessBorder(cornerRadius: 8)
  306. .transition(.asymmetric(
  307. insertion: .move(edge: .bottom).combined(with: .opacity),
  308. removal: .opacity
  309. ))
  310. }
  311. }
  312. .frame(height: 56)
  313. .animation(.spring(response: 0.35, dampingFraction: 0.8), value: latestEvent?.id)
  314. }
  315. // MARK: - Action Buttons
  316. private var actionButtons: some View {
  317. HStack(spacing: 40) {
  318. // Camera button
  319. actionButton(
  320. icon: "camera",
  321. label: "拍照打点"
  322. ) {
  323. capturePhoto()
  324. }
  325. // Note button
  326. actionButton(
  327. icon: "doc.text",
  328. label: "文字笔记"
  329. ) {
  330. presentNoteSheet()
  331. }
  332. }
  333. }
  334. private func actionButton(
  335. icon: String,
  336. label: String,
  337. action: @escaping () -> Void
  338. ) -> some View {
  339. Button(action: action) {
  340. VStack(spacing: 10) {
  341. ZStack {
  342. Circle()
  343. .fill(Color.primary.opacity(0.02))
  344. .frame(width: 60, height: 60)
  345. .businessBorder(cornerRadius: 30)
  346. Image(systemName: icon)
  347. .font(.system(size: 20, weight: .light))
  348. .foregroundStyle(Color.primary)
  349. }
  350. Text(label)
  351. .font(.system(size: 11, weight: .regular))
  352. .foregroundStyle(Color.secondary)
  353. }
  354. }
  355. .buttonStyle(.plain)
  356. }
  357. // MARK: - Recording Controls
  358. private var recordingControlButtons: some View {
  359. HStack(spacing: 52) {
  360. recordingControlButton(
  361. icon: recordingVM.isPaused ? "play.fill" : "pause.fill",
  362. label: recordingVM.isPaused ? "继续记录" : "暂停",
  363. tint: .primary
  364. ) {
  365. toggleRecordingPause()
  366. }
  367. recordingControlButton(
  368. icon: "stop.fill",
  369. label: isEndingRecording ? "正在结束" : "结束记录",
  370. tint: .recordingRed,
  371. isProminent: true
  372. ) {
  373. endRecording()
  374. }
  375. }
  376. }
  377. private func recordingControlButton(
  378. icon: String,
  379. label: String,
  380. tint: Color,
  381. isProminent: Bool = false,
  382. action: @escaping () -> Void
  383. ) -> some View {
  384. Button(action: action) {
  385. VStack(spacing: 9) {
  386. ZStack {
  387. Circle()
  388. .fill(isProminent ? tint : Color.primary.opacity(0.02))
  389. .frame(width: 64, height: 64)
  390. if !isProminent {
  391. Circle()
  392. .stroke(Color.primary.opacity(0.18), lineWidth: 1)
  393. .frame(width: 64, height: 64)
  394. }
  395. Image(systemName: icon)
  396. .font(.system(size: 21, weight: .semibold))
  397. .foregroundStyle(isProminent ? Color.white : tint)
  398. }
  399. Text(label)
  400. .font(.system(size: 11, weight: .medium))
  401. .foregroundStyle(tint)
  402. }
  403. .frame(width: 88)
  404. }
  405. .buttonStyle(.plain)
  406. .disabled(isEndingRecording)
  407. .opacity(isEndingRecording && !isProminent ? 0.4 : 1)
  408. .accessibilityLabel(label)
  409. }
  410. // MARK: - Note Input Sheet
  411. private var noteInputSheet: some View {
  412. NavigationStack {
  413. ZStack {
  414. Color.spaceBlack.ignoresSafeArea()
  415. VStack(alignment: .leading, spacing: 16) {
  416. Label(
  417. "添加到 \(formattedNoteTime(pendingNoteTimeMs))",
  418. systemImage: "clock"
  419. )
  420. .font(.system(size: 12, weight: .medium))
  421. .foregroundStyle(Color.secondary)
  422. ZStack(alignment: .topLeading) {
  423. if noteText.isEmpty {
  424. Text("这一刻的想法")
  425. .font(.system(size: 15))
  426. .foregroundStyle(Color.secondary.opacity(0.6))
  427. .padding(.horizontal, 18)
  428. .padding(.vertical, 16)
  429. .allowsHitTesting(false)
  430. }
  431. TextEditor(text: $noteText)
  432. .font(.system(size: 15))
  433. .foregroundStyle(Color.primary)
  434. .scrollContentBackground(.hidden)
  435. .padding(10)
  436. .frame(minHeight: 160)
  437. .background(Color.cardBackground.opacity(0.5))
  438. .businessBorder(cornerRadius: 8)
  439. }
  440. TimelineLocationButton(location: $noteLocation)
  441. Spacer()
  442. }
  443. .padding(20)
  444. }
  445. .navigationTitle("添加笔记")
  446. .navigationBarTitleDisplayMode(.inline)
  447. .toolbar {
  448. ToolbarItem(placement: .cancellationAction) {
  449. Button("取消") {
  450. showNoteSheet = false
  451. noteText = ""
  452. noteLocation = nil
  453. }
  454. }
  455. ToolbarItem(placement: .confirmationAction) {
  456. Button("保存") {
  457. addNote()
  458. }
  459. .disabled(noteText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
  460. }
  461. }
  462. }
  463. .presentationDetents([.medium])
  464. .presentationDragIndicator(.visible)
  465. .presentationBackground(Color.spaceBlack)
  466. }
  467. // MARK: - Actions
  468. private func capturePhoto() {
  469. pendingPhotoTimeMs = max(0, recordingVM.elapsedTime * 1_000)
  470. showPhotoEditor = true
  471. }
  472. private func savePhotosAndAddEvents(
  473. _ drafts: [PhotoRecordDraft],
  474. location: TimelineLocation?
  475. ) -> Bool {
  476. guard !drafts.isEmpty,
  477. let documentsURL = FileManager.default.urls(
  478. for: .documentDirectory,
  479. in: .userDomainMask
  480. ).first else {
  481. photoSaveError = "无法访问本地照片目录。"
  482. return false
  483. }
  484. var storedPhotos: [(filename: String, fileURL: URL, note: String)] = []
  485. do {
  486. for draft in drafts {
  487. guard let data = draft.image.jpegData(compressionQuality: 0.82) else {
  488. throw CocoaError(.fileWriteUnknown)
  489. }
  490. let filename = "photo_\(UUID().uuidString).jpg"
  491. let fileURL = documentsURL.appendingPathComponent(filename)
  492. try data.write(to: fileURL, options: .atomic)
  493. storedPhotos.append((filename, fileURL, draft.note))
  494. }
  495. } catch {
  496. for storedPhoto in storedPhotos {
  497. try? FileManager.default.removeItem(at: storedPhoto.fileURL)
  498. }
  499. photoSaveError = "照片文件写入失败:\(error.localizedDescription)"
  500. return false
  501. }
  502. let relativeTimeMs = Int64(pendingPhotoTimeMs.rounded())
  503. let events = storedPhotos.map { storedPhoto in
  504. let event = recordingVM.addPhotoEvent(
  505. to: session,
  506. relativeTimeMs: relativeTimeMs,
  507. localFilePath: storedPhoto.filename,
  508. note: storedPhoto.note
  509. )
  510. event.location = location
  511. return event
  512. }
  513. HapticManager.trigger(.photoCapture)
  514. if let latestPhotoEvent = events.last {
  515. showLatestEvent(latestPhotoEvent)
  516. }
  517. return true
  518. }
  519. private func addNote() {
  520. let text = noteText.trimmingCharacters(in: .whitespacesAndNewlines)
  521. guard !text.isEmpty else { return }
  522. let event = recordingVM.addNoteEvent(to: session, text: text)
  523. event.relativeTimeMs = Int64(pendingNoteTimeMs.rounded())
  524. event.location = noteLocation
  525. HapticManager.trigger(.noteAdded)
  526. showLatestEvent(event)
  527. noteText = ""
  528. noteLocation = nil
  529. showNoteSheet = false
  530. }
  531. private func addContinuationMarkerIfNeeded() {
  532. guard initialDuration > 0, !hasAddedContinuationMarker else { return }
  533. hasAddedContinuationMarker = true
  534. let event = CelestiaTimelineEvent(
  535. relativeTimeMs: Int64((initialDuration * 1_000).rounded()),
  536. eventType: "MARKER"
  537. )
  538. event.textContent = "续录时间:\(Self.continuationDateFormatter.string(from: Date()))"
  539. session.events.append(event)
  540. session.isSynced = false
  541. session.syncState = .pending
  542. try? modelContext.save()
  543. }
  544. private func presentNoteSheet() {
  545. pendingNoteTimeMs = max(0, recordingVM.elapsedTime * 1_000)
  546. noteText = ""
  547. noteLocation = nil
  548. showNoteSheet = true
  549. }
  550. private func formattedNoteTime(_ timeMs: Double) -> String {
  551. let totalSeconds = max(0, Int(timeMs / 1_000))
  552. let hours = totalSeconds / 3_600
  553. let minutes = (totalSeconds % 3_600) / 60
  554. let seconds = totalSeconds % 60
  555. if hours > 0 {
  556. return String(format: "%d:%02d:%02d", hours, minutes, seconds)
  557. }
  558. return String(format: "%02d:%02d", minutes, seconds)
  559. }
  560. private static let continuationDateFormatter: DateFormatter = {
  561. let formatter = DateFormatter()
  562. formatter.locale = Locale(identifier: "zh_CN")
  563. formatter.calendar = Calendar(identifier: .gregorian)
  564. formatter.dateFormat = "yyyy年M月d日 HH:mm:ss"
  565. return formatter
  566. }()
  567. private func toggleRecordingPause() {
  568. guard !isEndingRecording else { return }
  569. HapticManager.trigger(.tapFeedback)
  570. if recordingVM.isPaused {
  571. recordingVM.resumeRecording()
  572. } else {
  573. recordingVM.pauseRecording()
  574. }
  575. }
  576. private func endRecording() {
  577. guard !isEndingRecording else { return }
  578. commitRecordName()
  579. isEndingRecording = true
  580. recordingVM.stopRecording { result in
  581. switch result {
  582. case .success(let confirmedURL):
  583. finalizeRecording(newRecordedURL: confirmedURL ?? recordingVM.outputFileURL)
  584. case .failure(let error):
  585. isEndingRecording = false
  586. stopErrorMessage = error.localizedDescription
  587. }
  588. }
  589. }
  590. private func finalizeRecording(newRecordedURL: URL?) {
  591. let existingPath = session.localAudioPath
  592. let existingURL = AudioPathHelper.resolveURL(for: existingPath)
  593. let totalRecordedSeconds = recordingVM.elapsedTime
  594. RecordingLiveActivityManager.shared.end(elapsedSeconds: totalRecordedSeconds)
  595. hasStartedLiveActivity = false
  596. if let newRecordedURL = newRecordedURL {
  597. Task { @MainActor in
  598. let mergedURL = await AudioMerger.mergeAudioFiles(firstURL: existingURL, secondURL: newRecordedURL)
  599. session.localAudioPath = AudioPathHelper.relativePath(from: mergedURL.path)
  600. session.endTime = session.startTime.addingTimeInterval(totalRecordedSeconds)
  601. session.markContentModified()
  602. try? modelContext.save()
  603. scheduleAutomaticSync()
  604. RecordingRecoveryStore.clear(sessionID: session.id)
  605. HapticManager.trigger(.recordStop)
  606. isEndingRecording = false
  607. dismiss()
  608. onFinishRecording?()
  609. }
  610. } else {
  611. if existingURL != nil {
  612. session.endTime = session.startTime.addingTimeInterval(totalRecordedSeconds)
  613. session.markContentModified()
  614. try? modelContext.save()
  615. } else {
  616. session.endTime = Date()
  617. session.markContentModified()
  618. try? modelContext.save()
  619. }
  620. scheduleAutomaticSync()
  621. RecordingRecoveryStore.clear(sessionID: session.id)
  622. HapticManager.trigger(.recordStop)
  623. isEndingRecording = false
  624. dismiss()
  625. onFinishRecording?()
  626. }
  627. }
  628. private func showLatestEvent(_ event: CelestiaTimelineEvent) {
  629. withAnimation {
  630. latestEvent = event
  631. latestEventVisible = true
  632. }
  633. // Auto-dismiss after a few seconds
  634. DispatchQueue.main.asyncAfter(deadline: .now() + 4) {
  635. withAnimation {
  636. latestEventVisible = false
  637. }
  638. }
  639. }
  640. // MARK: - Helpers
  641. private func eventLabel(for type: String) -> String {
  642. switch type {
  643. case "PHOTO": return "已捕获照片"
  644. case "NOTE": return "已保存笔记"
  645. case "MARKER": return "标记点"
  646. case "VOICE": return "音轨事件"
  647. default: return "事件"
  648. }
  649. }
  650. private func commitRecordName() {
  651. let trimmedName = recordName.trimmingCharacters(in: .whitespacesAndNewlines)
  652. if trimmedName.isEmpty {
  653. recordName = session.title
  654. return
  655. }
  656. guard session.title != trimmedName else {
  657. if recordName != trimmedName {
  658. recordName = trimmedName
  659. }
  660. return
  661. }
  662. recordName = trimmedName
  663. session.title = trimmedName
  664. session.markContentModified()
  665. try? modelContext.save()
  666. }
  667. private func scheduleAutomaticSync() {
  668. syncManager.scheduleAutomaticSync(
  669. for: session,
  670. modelContext: modelContext
  671. )
  672. }
  673. private func saveRecordNameAndCloseEditor() {
  674. commitRecordName()
  675. guard !recordName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
  676. showRecordNameEditor = false
  677. }
  678. private func handleRecordingURL(_ url: URL) {
  679. guard let route = RecordingLiveActivityRoute(url: url),
  680. route.sessionID == session.id else { return }
  681. perform(route.action)
  682. }
  683. private func handleLiveActivityCommand(_ notification: Notification) {
  684. guard let sessionID = notification.userInfo?["sessionID"] as? String,
  685. UUID(uuidString: sessionID) == session.id,
  686. let rawCommand = notification.userInfo?["command"] as? String,
  687. let command = RecordingLiveActivityCommand(rawValue: rawCommand) else {
  688. return
  689. }
  690. switch command {
  691. case .togglePause:
  692. perform(.togglePause)
  693. case .stop:
  694. perform(.stop)
  695. }
  696. }
  697. private func performPendingInitialActionIfReady() {
  698. guard recordingVM.isRecording, let action = pendingInitialAction else { return }
  699. pendingInitialAction = nil
  700. perform(action)
  701. }
  702. private func perform(_ action: RecordingLiveActivityAction?) {
  703. switch action {
  704. case .photo:
  705. capturePhoto()
  706. case .note:
  707. presentNoteSheet()
  708. case .togglePause:
  709. toggleRecordingPause()
  710. case .stop:
  711. endRecording()
  712. case nil:
  713. return
  714. }
  715. }
  716. }
  717. struct RecordNameEditorSheet: View {
  718. @Binding var recordName: String
  719. let onSave: () -> Void
  720. let onCancel: () -> Void
  721. var body: some View {
  722. NavigationStack {
  723. ZStack {
  724. Color.spaceBlack.ignoresSafeArea()
  725. VStack(alignment: .leading, spacing: 10) {
  726. Text("记录名称")
  727. .font(.system(size: 10, weight: .semibold, design: .monospaced))
  728. .foregroundStyle(Color.secondary)
  729. .tracking(1.4)
  730. SuffixSelectingTextField(
  731. placeholder: "输入记录名称",
  732. text: $recordName,
  733. selectedSuffix: "现场记录",
  734. onSubmit: onSave
  735. )
  736. .padding(.horizontal, 14)
  737. .padding(.vertical, 12)
  738. .background(Color.cardBackground.opacity(0.5))
  739. .businessBorder(cornerRadius: 8)
  740. Spacer()
  741. }
  742. .padding(20)
  743. }
  744. .navigationTitle("修改记录名称")
  745. .navigationBarTitleDisplayMode(.inline)
  746. .toolbar {
  747. ToolbarItem(placement: .cancellationAction) {
  748. Button("取消", action: onCancel)
  749. .foregroundStyle(Color.secondary)
  750. }
  751. ToolbarItem(placement: .confirmationAction) {
  752. Button("保存", action: onSave)
  753. .disabled(recordName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
  754. }
  755. }
  756. }
  757. .presentationDetents([.height(190)])
  758. .presentationDragIndicator(.visible)
  759. .presentationBackground(Color.spaceBlack)
  760. }
  761. }
  762. private struct SuffixSelectingTextField: UIViewRepresentable {
  763. let placeholder: String
  764. @Binding var text: String
  765. let selectedSuffix: String
  766. let onSubmit: () -> Void
  767. func makeCoordinator() -> Coordinator {
  768. Coordinator(text: $text, selectedSuffix: selectedSuffix, onSubmit: onSubmit)
  769. }
  770. func makeUIView(context: Context) -> UITextField {
  771. let textField = UITextField()
  772. textField.placeholder = placeholder
  773. textField.text = text
  774. textField.font = .systemFont(ofSize: 18, weight: .semibold)
  775. textField.textColor = .label
  776. textField.tintColor = UIColor(Color.accentColor)
  777. textField.autocapitalizationType = .none
  778. textField.autocorrectionType = .no
  779. textField.returnKeyType = .done
  780. textField.delegate = context.coordinator
  781. textField.addTarget(
  782. context.coordinator,
  783. action: #selector(Coordinator.textDidChange(_:)),
  784. for: .editingChanged
  785. )
  786. DispatchQueue.main.async {
  787. textField.becomeFirstResponder()
  788. context.coordinator.selectSuffixIfNeeded(in: textField)
  789. }
  790. return textField
  791. }
  792. func updateUIView(_ textField: UITextField, context: Context) {
  793. if textField.text != text {
  794. textField.text = text
  795. }
  796. }
  797. final class Coordinator: NSObject, UITextFieldDelegate {
  798. @Binding private var text: String
  799. private let selectedSuffix: String
  800. private let onSubmit: () -> Void
  801. private var hasAppliedInitialSelection = false
  802. init(text: Binding<String>, selectedSuffix: String, onSubmit: @escaping () -> Void) {
  803. _text = text
  804. self.selectedSuffix = selectedSuffix
  805. self.onSubmit = onSubmit
  806. }
  807. @objc func textDidChange(_ textField: UITextField) {
  808. text = textField.text ?? ""
  809. }
  810. func textFieldShouldReturn(_ textField: UITextField) -> Bool {
  811. onSubmit()
  812. return true
  813. }
  814. func selectSuffixIfNeeded(in textField: UITextField) {
  815. guard !hasAppliedInitialSelection else { return }
  816. hasAppliedInitialSelection = true
  817. let fullText = textField.text ?? ""
  818. guard fullText.hasSuffix(selectedSuffix),
  819. let start = textField.position(
  820. from: textField.endOfDocument,
  821. offset: -selectedSuffix.utf16.count
  822. ),
  823. let range = textField.textRange(from: start, to: textField.endOfDocument) else {
  824. return
  825. }
  826. textField.selectedTextRange = range
  827. }
  828. }
  829. }
  830. // MARK: - Amplitude Level Meter View
  831. /// A minimalist graphical VU meter bar visualizing real-time audio amplitude.
  832. private struct AmplitudeLevelMeterView: View {
  833. let amplitude: Float // 0.0 to 1.0
  834. private let totalSegments: Int = 16
  835. var body: some View {
  836. HStack(spacing: 3) {
  837. ForEach(0..<totalSegments, id: \.self) { index in
  838. let threshold = Float(index) / Float(totalSegments)
  839. let isFilled = amplitude > threshold
  840. let isPeak = index >= totalSegments - 2
  841. RoundedRectangle(cornerRadius: 1)
  842. .fill(
  843. isFilled
  844. ? (isPeak ? Color.recordingRed : Color.primary.opacity(0.85))
  845. : Color.primary.opacity(0.12)
  846. )
  847. .frame(height: isFilled ? (isPeak ? 7 : 5) : 3)
  848. .animation(.spring(response: 0.15, dampingFraction: 0.75), value: amplitude)
  849. }
  850. }
  851. }
  852. }
  853. // MARK: - Preview
  854. #Preview {
  855. let session = CelestiaSession(title: "Preview Session")
  856. ActiveRecordingView(session: session)
  857. .modelContainer(for: CelestiaSession.self, inMemory: true)
  858. }