diff --git a/ios/DPIPWidgets/DPIPWidgetsBundle.swift b/ios/DPIPWidgets/DPIPWidgetsBundle.swift index a4c51ee4d..c0dd64ecc 100644 --- a/ios/DPIPWidgets/DPIPWidgetsBundle.swift +++ b/ios/DPIPWidgets/DPIPWidgetsBundle.swift @@ -5,5 +5,8 @@ import SwiftUI struct DPIPWidgetsBundle: WidgetBundle { var body: some Widget { DPIPWidgets() + if #available(iOS 16.1, *) { + EEWLiveActivity() + } } } diff --git a/ios/DPIPWidgets/EEWLiveActivity.swift b/ios/DPIPWidgets/EEWLiveActivity.swift new file mode 100644 index 000000000..6f82046bd --- /dev/null +++ b/ios/DPIPWidgets/EEWLiveActivity.swift @@ -0,0 +1,633 @@ +import ActivityKit +import SwiftUI +import WidgetKit + +@available(iOS 16.1, *) +struct EEWLiveActivity: Widget { + var body: some WidgetConfiguration { + ActivityConfiguration(for: EEWActivityAttributes.self) { context in + EEWLockScreenView(context: context) + .padding(14) + .foregroundStyle(.secondary) + .activitySystemActionForegroundColor(.secondary) + } dynamicIsland: { context in + DynamicIsland { + DynamicIslandExpandedRegion(.leading) { + EEWEventHeading(provider: context.attributes.provider) + } + DynamicIslandExpandedRegion(.trailing) { + HStack(spacing: 6) { + EEWReportNumber(number: context.state.reportNo) + .font(.caption) + .foregroundStyle(.secondary) + EEWTestBadge() + } + } + DynamicIslandExpandedRegion(.bottom) { + VStack(alignment: .center, spacing: 8) { + EEWPrimarySummary(state: context.state, island: true) + EEWExpandedEventDetails(state: context.state) + } + .padding(.top, 4) + .foregroundStyle(.white) + } + } compactLeading: { + EEWCompactIntensity(state: context.state) + } compactTrailing: { + EEWCompactArrival(state: context.state) + .font(.caption.bold()) + .foregroundStyle(.white) + } minimal: { + EEWMinimalView(state: context.state) + } + // Keep event details clear of the curved system mask. + .contentMargins(.horizontal, 28, for: .expanded) + .keylineTint(.red) + } + } +} + +@available(iOS 16.1, *) +private struct EEWLockScreenView: View { + let context: ActivityViewContext + + var body: some View { + VStack(alignment: .leading, spacing: 6) { + HStack(alignment: .top, spacing: 8) { + EEWEventHeading(provider: context.attributes.provider) + .layoutPriority(1) + Spacer(minLength: 4) + EEWReportNumber(number: context.state.reportNo) + .font(.caption) + .foregroundStyle(.secondary) + EEWTestBadge() + } + EEWEventDetails(state: context.state) + EEWPrimarySummary(state: context.state) + } + } +} + +@available(iOS 16.1, *) +private struct EEWEventHeading: View { + let provider: String + + var body: some View { + HStack(spacing: 6) { + Image(systemName: "waveform.path.ecg") + .foregroundStyle(.red) + .accessibilityHidden(true) + // A single text flow shares compression instead of truncating title/source separately. + Text( + "\(Text("eew.title").fontWeight(.semibold))\(Text(verbatim: " · " + provider).foregroundColor(.secondary))" + ) + .layoutPriority(1) + } + .font(.caption) + .foregroundStyle(.primary) + .lineLimit(1) + // The Island leading region must retain both title and source at large text sizes. + .minimumScaleFactor(0.6) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(verbatim: NSLocalizedString("eew.title", comment: "EEW title") + " " + provider)) + } +} + +@available(iOS 16.1, *) +private struct EEWPrimarySummary: View { + let state: EEWActivityAttributes.ContentState + var island = false + + var body: some View { + // Each optional field falls back independently; missing personalization + // does not identify why the local estimate or ETA is unavailable. + let intensity = EEWPresentation.intensity(for: state) + + HStack(alignment: .top, spacing: 16) { + VStack(alignment: .center, spacing: 4) { + Text(LocalizedStringKey(EEWPresentation.intensityLabel(for: state))) + .font(.caption) + .lineLimit(1) + .minimumScaleFactor(0.8) + EEWIntensityValue(intensity: intensity) + .font(.system(size: 42, weight: .bold)) + .frame(minHeight: 52) + .foregroundStyle(EEWIntensityColor.color(for: intensity)) + .lineLimit(1) + .minimumScaleFactor(0.8) + } + .frame(maxWidth: .infinity, alignment: .center) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(LocalizedStringKey(EEWPresentation.intensityLabel(for: state)))) + .accessibilityValue(EEWIntensityValue.text(intensity, spoken: true)) + + VStack(alignment: .center, spacing: 4) { + Text("eew.arrival.estimated") + .font(.caption) + .lineLimit(1) + .minimumScaleFactor(0.8) + // The live countdown supplies this label to VoiceOver. + .accessibilityHidden(!state.waveArrived && state.estimatedSArrivalAt != nil) + EEWArrivalView(state: state, island: island) + .frame(minHeight: 52) + } + .frame(maxWidth: .infinity, alignment: .center) + .accessibilityElement(children: .combine) + } + } +} + +@available(iOS 16.1, *) +private struct EEWEventDetails: View { + let state: EEWActivityAttributes.ContentState + + var body: some View { + // A single text flow gives long epicenters up to two lines without + // displacing magnitude/depth into a separate compressed column. + Text(verbatim: EEWEventDetailText(state: state).full) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(2) + .fixedSize(horizontal: false, vertical: true) + .accessibilityLabel(Text(verbatim: EEWEventDetailText(state: state).spoken)) + } +} + +@available(iOS 16.1, *) +private struct EEWExpandedEventDetails: View { + let state: EEWActivityAttributes.ContentState + + var body: some View { + let details = EEWEventDetailText(state: state) + + ViewThatFits(in: .horizontal) { + // Measure the richer candidates at their full single-line width, + // so truncation cannot make them win before detail is reduced. + Text(verbatim: details.full) + .fixedSize(horizontal: true, vertical: false) + Text(verbatim: details.epicenterMagnitude) + .fixedSize(horizontal: true, vertical: false) + Text(verbatim: state.epicenter) + .truncationMode(.tail) + } + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + // Visual reduction must not remove event information from VoiceOver. + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(verbatim: details.spoken)) + } +} + +@available(iOS 16.1, *) +private struct EEWEventDetailText { + let state: EEWActivityAttributes.ContentState + + var spoken: String { + String( + format: NSLocalizedString("eew.details.spoken.format", comment: "Spoken earthquake details"), + state.epicenter, state.magnitude, state.depthKm) + } + + var epicenterMagnitude: String { + state.epicenter + " · " + String(format: "M%.1f", state.magnitude) + } + + var full: String { + epicenterMagnitude + " · " + + String( + format: "%@ %.0f km", + NSLocalizedString("eew.depth", comment: "Earthquake depth"), state.depthKm) + } +} + +@available(iOS 16.1, *) +private struct EEWTestBadge: View { + var body: some View { + // All Phase 1 activities are mock data, including non-DEBUG builds. + // Keep the marker until a production contract explicitly identifies tests. + Text("eew.test.short") + .font(.caption2.bold()) + .foregroundStyle(.gray) + .padding(.horizontal, 4) + .padding(.vertical, 1) + .background(.gray.opacity(0.15), in: Capsule()) + .lineLimit(1) + .fixedSize() + .accessibilityLabel(Text("eew.test.spoken")) + } +} + +@available(iOS 16.1, *) +private struct EEWReportNumber: View { + let number: Int + + var body: some View { + Text(String(format: NSLocalizedString("eew.report.format", comment: "EEW report number"), number)) + .monospacedDigit() + .lineLimit(1) + // Preserve the complete report ordinal in the Island at large text sizes. + .minimumScaleFactor(0.7) + } +} + +@available(iOS 16.1, *) +private struct EEWIntensityValue: View { + let intensity: Int + var compact = false + + var body: some View { Self.text(intensity, compact: compact) } + + static func badgeText(_ intensity: Int) -> Text { + let content = EEWPresentation.intensityText(intensity, compact: true) + // Omit only the unit. Localized weak/strong labels remain indivisible. + if let level = content.level { return Text(level, format: .number) } + return text(intensity, compact: true) + } + + static func text(_ intensity: Int, compact: Bool = false, spoken: Bool = false) -> Text { + let content = EEWPresentation.intensityText(intensity, compact: compact, spoken: spoken) + if let level = content.level { + return Text(String(format: NSLocalizedString(content.key, comment: "Intensity level"), level)) + } + return Text(LocalizedStringKey(content.key)) + } +} + +@available(iOS 16.1, *) +private struct EEWArrivalView: View { + let state: EEWActivityAttributes.ContentState + var island = false + + var body: some View { + switch EEWPresentation.arrival(for: state) { + case .arrived: + Text("eew.arrived.short") + .font(.system(size: 42, weight: .bold)) + .foregroundStyle(.primary) + .lineLimit(1) + .minimumScaleFactor(0.6) + case .countdown(let arrival): + EEWCountdown(arrival: arrival, island: island) + .font(.system(size: 42, weight: .bold)) + .lineLimit(1) + .minimumScaleFactor(0.8) + case .unavailable: + Text("eew.unavailable") + .font(.system(size: 42, weight: .bold)) + .foregroundStyle(.secondary) + .lineLimit(1) + .minimumScaleFactor(0.6) + } + } +} + +@available(iOS 16.1, *) +private struct EEWCountdown: View { + let arrival: Date + var island = false + + var body: some View { + // Compatibility fallback: this Apple timer keeps updating in the system + // renderer while the app/extension is suspended, and clamps at zero. + // There is no verified seconds-only replacement in the installed SDK: + // Timer(maxFieldCount: 1) switches to minutes above 60 seconds; + // DateOffset(fields: [.second], sign: .never) counts up after the ETA; + // dateRange(endingAt:) + ComponentsFormatStyle stalls in Live Activities. + // Do not replace it with a static string or a custom DiscreteFormatStyle. + // Reaching zero never infers waveArrived or ends the existing activity. + let now = Date.now + let timer = Text(timerInterval: now...max(arrival, now), countsDown: true, showsHours: false) + timer + .monospacedDigit() + .multilineTextAlignment(.center) + .foregroundStyle(island ? Color.white : Color.primary) + .accessibilityLabel(Text("eew.arrival.estimated")) + .accessibilityValue(timer) + } +} + +@available(iOS 16.1, *) +private struct EEWCompactIntensity: View { + let state: EEWActivityAttributes.ContentState + + var body: some View { + EEWIslandWidthReader { limited in + EEWIslandIntensityPresentation( + intensity: EEWPresentation.intensity(for: state), limitedInWidth: limited + ) { + EEWIntensityValue.badgeText(EEWPresentation.intensity(for: state)) + } testBadge: { + EEWTestBadge() + } + } + .font(.caption.bold()) + .foregroundStyle(.white) + .accessibilityElement(children: .ignore) + .accessibilityLabel(Text(LocalizedStringKey(EEWPresentation.intensityLabel(for: state)))) + .accessibilityValue(EEWIntensityValue.text(EEWPresentation.intensity(for: state), spoken: true)) + .accessibilityHint(Text("eew.test.spoken")) + } +} + +@available(iOS 16.1, *) +private struct EEWCompactArrival: View { + let state: EEWActivityAttributes.ContentState + + var body: some View { + EEWIslandWidthReader { limited in + EEWIslandFittingView(limitedInWidth: limited) { + arrival + } compact: { + arrival.font(.caption2.bold()) + } fallback: { + EEWIslandArrivalSymbol(state: state) + } + } + } + + @ViewBuilder private var arrival: some View { + switch EEWPresentation.arrival(for: state) { + case .arrived: + Text("eew.arrived.short") + .accessibilityLabel(Text("eew.arrival.estimated")) + .accessibilityValue(Text("eew.arrived.short")) + case .countdown(let arrival): + EEWIslandTimerEnvelope(sample: EEWPresentation.islandTimerSample(for: state, now: .now)) { + EEWCountdown(arrival: arrival, island: true) + } + case .unavailable: + EEWIslandArrivalSymbol(state: state) + } + } +} + +@available(iOS 16.1, *) +private struct EEWIslandArrivalSymbol: View { + let state: EEWActivityAttributes.ContentState + + var body: some View { + Image(systemName: EEWPresentation.islandArrivalSymbol(for: state)) + .resizable() + .scaledToFit() + .frame(maxWidth: 14, maxHeight: 14) + .foregroundStyle(EEWPresentation.arrival(for: state) == .unavailable ? .secondary : .primary) + // Preserve live countdown semantics for VoiceOver even if the visible + // slot can only fit a clock. Never announce this as an arrived state. + .accessibilityRepresentation { + switch EEWPresentation.arrival(for: state) { + case .countdown(let arrival): + EEWCountdown(arrival: arrival, island: true) + case .arrived: + Text("eew.arrived.short") + .accessibilityLabel(Text("eew.arrival.estimated")) + .accessibilityValue(Text("eew.arrived.short")) + case .unavailable: + Text("eew.unavailable") + .accessibilityLabel(Text("eew.arrival.estimated")) + .accessibilityValue(Text("eew.unavailable")) + } + } + } +} + +@available(iOS 16.1, *) +private struct EEWMinimalView: View { + let state: EEWActivityAttributes.ContentState + + var body: some View { + EEWIslandWidthReader { limited in + EEWIslandFittingView(limitedInWidth: limited) { + HStack(spacing: 4) { + EEWIslandIntensityBadge(intensity: EEWPresentation.intensity(for: state), dense: true) { + EEWIntensityValue.badgeText(EEWPresentation.intensity(for: state)) + } + arrival + } + } compact: { + // A limited-width hint does not justify discarding a timer that + // actually fits. Minimal already uses the smallest approved font. + arrival + } fallback: { + EEWIslandArrivalSymbol(state: state) + } + } + .font(.caption.bold()) + .foregroundStyle(.white) + .accessibilityRepresentation { + HStack { + EEWIntensityValue.text(EEWPresentation.intensity(for: state), spoken: true) + .accessibilityLabel(Text(LocalizedStringKey(EEWPresentation.intensityLabel(for: state)))) + .accessibilityValue(EEWIntensityValue.text(EEWPresentation.intensity(for: state), spoken: true)) + arrival + } + .accessibilityElement(children: .combine) + .accessibilityHint(Text("eew.test.spoken")) + } + .accessibilityElement(children: .combine) + .accessibilityHint(Text("eew.test.spoken")) + } + + @ViewBuilder private var arrival: some View { + switch EEWPresentation.arrival(for: state) { + case .countdown(let arrival): + EEWIslandTimerEnvelope(sample: EEWPresentation.islandTimerSample(for: state, now: .now)) { + EEWCountdown(arrival: arrival, island: true) + } + .font(.caption2.bold()) + case .arrived: + EEWIslandArrivalSymbol(state: state) + case .unavailable: + Image(systemName: "waveform.path.ecg") + .foregroundStyle(.red) + .accessibilityLabel(Text("eew.arrival.estimated")) + .accessibilityValue(Text("eew.unavailable")) + } + } +} + +#if DEBUG + // Canvas-only fixtures: no Activity.request, Flutter bridge, or manager state. + @available(iOS 17.0, *) + private enum EEWActivityPreviewData { + static let personalizedAttributes = EEWActivityAttributes( + provider: "CWA", eventId: "preview-personalized" + ) + static let genericAttributes = EEWActivityAttributes( + provider: "CWA", eventId: "preview-generic" + ) + + static var personalized: EEWActivityAttributes.ContentState { state() } + static var generic: EEWActivityAttributes.ContentState { + state(localIntensity: nil, arrivalDelay: nil) + } + static var intensityOnly: EEWActivityAttributes.ContentState { + state(arrivalDelay: nil) + } + static var arrivalOnly: EEWActivityAttributes.ContentState { + state(localIntensity: nil) + } + static var waveArrived: EEWActivityAttributes.ContentState { state(waveArrived: true) } + static var seconds125: EEWActivityAttributes.ContentState { state(arrivalDelay: 125) } + static var seconds65: EEWActivityAttributes.ContentState { state(arrivalDelay: 65) } + static var seconds35: EEWActivityAttributes.ContentState { state(arrivalDelay: 35) } + static var seconds9: EEWActivityAttributes.ContentState { state(arrivalDelay: 9) } + static var zeroETA: EEWActivityAttributes.ContentState { state(arrivalDelay: 0) } + static var expiredETA: EEWActivityAttributes.ContentState { state(arrivalDelay: -5) } + static var intensity6Weak: EEWActivityAttributes.ContentState { state(localIntensity: 7) } + static var intensity6Strong: EEWActivityAttributes.ContentState { state(localIntensity: 8) } + static var intensity7: EEWActivityAttributes.ContentState { state(localIntensity: 9) } + static var layoutStress: EEWActivityAttributes.ContentState { + state( + reportNo: 123, epicenter: "花蓮縣壽豐鄉東南方外海(臺灣東部海域)", + localIntensity: 6, arrivalDelay: 653) + } + + private static func state( + waveArrived: Bool = false, + reportNo: Int = 4, epicenter: String = "臺東縣近海", + localIntensity: Int? = 4, arrivalDelay: TimeInterval? = 60 + ) -> EEWActivityAttributes.ContentState { + // Refresh the absolute ETA whenever Canvas recreates the fixture. + // Resume/reload a long-running preview to restart its countdown. + let now = Date.now + return EEWActivityAttributes.ContentState( + reportNo: reportNo, + originAt: now.addingTimeInterval(-10), + magnitude: 6.1, + depthKm: 20, + epicenter: epicenter, + reportMaxIntensity: 5, + estimatedLocalIntensity: localIntensity, + estimatedSArrivalAt: arrivalDelay.map { + now.addingTimeInterval(waveArrived ? -1 : $0) + }, + waveArrived: waveArrived + ) + } + } + + @available(iOS 17.0, *) + #Preview( + "Lock Screen — Personalized", as: .content, + using: EEWActivityPreviewData.personalizedAttributes) { + EEWLiveActivity() + } contentStates: { + EEWActivityPreviewData.personalized + EEWActivityPreviewData.seconds125 + EEWActivityPreviewData.seconds65 + EEWActivityPreviewData.seconds35 + EEWActivityPreviewData.seconds9 + EEWActivityPreviewData.zeroETA + EEWActivityPreviewData.expiredETA + EEWActivityPreviewData.intensity6Weak + EEWActivityPreviewData.intensity6Strong + EEWActivityPreviewData.intensity7 + } + + @available(iOS 17.0, *) + #Preview( + "Lock Screen — Generic", as: .content, + using: EEWActivityPreviewData.genericAttributes) { + EEWLiveActivity() + } contentStates: { + EEWActivityPreviewData.generic + } + + @available(iOS 17.0, *) + #Preview( + "Lock Screen — Partial Personalization", as: .content, + using: EEWActivityPreviewData.personalizedAttributes) { + EEWLiveActivity() + } contentStates: { + EEWActivityPreviewData.intensityOnly + EEWActivityPreviewData.arrivalOnly + } + + @available(iOS 17.0, *) + #Preview( + "Lock Screen — Wave Arrived", as: .content, + using: EEWActivityPreviewData.personalizedAttributes) { + EEWLiveActivity() + } contentStates: { + EEWActivityPreviewData.waveArrived + } + + @available(iOS 17.0, *) + #Preview( + "Lock Screen — Long Epicenter", as: .content, + using: EEWActivityPreviewData.personalizedAttributes) { + EEWLiveActivity() + } contentStates: { + EEWActivityPreviewData.layoutStress + } + + @available(iOS 17.0, *) + #Preview( + "Dynamic Island — Expanded", as: .dynamicIsland(.expanded), + using: EEWActivityPreviewData.personalizedAttributes) { + EEWLiveActivity() + } contentStates: { + EEWActivityPreviewData.seconds125 + EEWActivityPreviewData.seconds65 + EEWActivityPreviewData.seconds35 + EEWActivityPreviewData.seconds9 + EEWActivityPreviewData.zeroETA + EEWActivityPreviewData.expiredETA + EEWActivityPreviewData.intensity6Weak + EEWActivityPreviewData.intensity6Strong + EEWActivityPreviewData.intensity7 + EEWActivityPreviewData.personalized + EEWActivityPreviewData.generic + EEWActivityPreviewData.intensityOnly + EEWActivityPreviewData.arrivalOnly + EEWActivityPreviewData.waveArrived + EEWActivityPreviewData.layoutStress + } + + @available(iOS 17.0, *) + #Preview( + "Dynamic Island — Compact", as: .dynamicIsland(.compact), + using: EEWActivityPreviewData.personalizedAttributes) { + EEWLiveActivity() + } contentStates: { + EEWActivityPreviewData.seconds125 + EEWActivityPreviewData.seconds65 + EEWActivityPreviewData.seconds35 + EEWActivityPreviewData.seconds9 + EEWActivityPreviewData.zeroETA + EEWActivityPreviewData.expiredETA + EEWActivityPreviewData.intensity6Weak + EEWActivityPreviewData.intensity6Strong + EEWActivityPreviewData.intensity7 + EEWActivityPreviewData.personalized + EEWActivityPreviewData.generic + EEWActivityPreviewData.intensityOnly + EEWActivityPreviewData.arrivalOnly + EEWActivityPreviewData.waveArrived + EEWActivityPreviewData.layoutStress + } + + @available(iOS 17.0, *) + #Preview( + "Dynamic Island — Minimal", as: .dynamicIsland(.minimal), + using: EEWActivityPreviewData.personalizedAttributes) { + EEWLiveActivity() + } contentStates: { + EEWActivityPreviewData.seconds125 + EEWActivityPreviewData.seconds65 + EEWActivityPreviewData.seconds35 + EEWActivityPreviewData.seconds9 + EEWActivityPreviewData.zeroETA + EEWActivityPreviewData.expiredETA + EEWActivityPreviewData.intensity6Weak + EEWActivityPreviewData.intensity6Strong + EEWActivityPreviewData.intensity7 + EEWActivityPreviewData.personalized + EEWActivityPreviewData.generic + EEWActivityPreviewData.intensityOnly + EEWActivityPreviewData.arrivalOnly + EEWActivityPreviewData.waveArrived + EEWActivityPreviewData.layoutStress + } +#endif diff --git a/ios/DPIPWidgets/Localizable.xcstrings b/ios/DPIPWidgets/Localizable.xcstrings index c6e341ab7..71e5bea6b 100644 --- a/ios/DPIPWidgets/Localizable.xcstrings +++ b/ios/DPIPWidgets/Localizable.xcstrings @@ -16,9 +16,377 @@ "%.1f mm" : { "shouldTranslate" : false }, + "%@%@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@%2$@" + } + } + } + }, "%lld%%" : { "shouldTranslate" : false }, + "eew.arrival.estimated" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Estimated S-wave arrival" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "震波預計抵達" + } + } + } + }, + "eew.arrived.short" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Arrived" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "已抵達" + } + } + } + }, + "eew.depth" : { + "comment" : "Earthquake depth", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Depth" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "深度" + } + } + } + }, + "eew.details.spoken.format" : { + "comment" : "EEW accessibility description", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@, magnitude %.1f, depth %.0f kilometers" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%@,規模 %.1f,深度 %.0f 公里" + } + } + } + }, + "eew.intensity.5strong" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "5+" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "5強" + } + } + } + }, + "eew.intensity.5strong.spoken" : { + "comment" : "EEW accessibility description", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Level 5 strong" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "5強" + } + } + } + }, + "eew.intensity.5weak" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "5−" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "5弱" + } + } + } + }, + "eew.intensity.5weak.spoken" : { + "comment" : "EEW accessibility description", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Level 5 weak" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "5弱" + } + } + } + }, + "eew.intensity.6strong" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "6+" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "6強" + } + } + } + }, + "eew.intensity.6strong.spoken" : { + "comment" : "EEW accessibility description", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Level 6 strong" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "6強" + } + } + } + }, + "eew.intensity.6weak" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "6−" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "6弱" + } + } + } + }, + "eew.intensity.6weak.spoken" : { + "comment" : "EEW accessibility description", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Level 6 weak" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "6弱" + } + } + } + }, + "eew.intensity.compact.format" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "%d" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%d級" + } + } + } + }, + "eew.intensity.format" : { + "extractionState" : "stale", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Level %d" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "%d級" + } + } + } + }, + "eew.intensity.local" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Estimated here" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "所在地預估" + } + } + } + }, + "eew.intensity.max" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Report max. predicted" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "本報最大預測震度" + } + } + } + }, + "eew.report.format" : { + "comment" : "EEW report number", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Report %d" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "第 %d 報" + } + } + } + }, + "eew.test.short" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "TEST" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "測試" + } + } + } + }, + "eew.test.spoken" : { + "comment" : "EEW accessibility description", + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Test earthquake data" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "測試地震資料" + } + } + } + }, + "eew.title" : { + "comment" : "EEW title", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "EEW" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "地震速報" + } + } + } + }, + "eew.unavailable" : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "Unavailable" + } + }, + "zh-Hant" : { + "stringUnit" : { + "state" : "translated", + "value" : "未提供" + } + } + } + }, "weather.clear" : { "comment" : "Localized current weather condition for clear skies.", "extractionState" : "stale", diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj index cde9fb11e..6c50a2932 100644 --- a/ios/Runner.xcodeproj/project.pbxproj +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -108,11 +108,22 @@ EBD0CEACA5C57FA4948682B7 /* CurrentWeatherWidgetSnapshotWriter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2B840E208BA7F71D7AA787CD /* CurrentWeatherWidgetSnapshotWriter.swift */; }; EFC526F4C8EFA7517C766E95 /* ForecastWidgetSelection.swift in Sources */ = {isa = PBXBuildFile; fileRef = 238235236BC1A9B17B75A67C /* ForecastWidgetSelection.swift */; }; F3BC5F2663935A0CF6DCB4A4 /* Foundation.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2D70E5CCEA46A49349D6E800 /* Foundation.framework */; }; + EEA100000000000000000001 /* Shared/EEWActivityAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA100000000000000000003 /* Shared/EEWActivityAttributes.swift */; }; + EEA100000000000000000002 /* Shared/EEWActivityAttributes.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA100000000000000000003 /* Shared/EEWActivityAttributes.swift */; }; + EEA100000000000000000004 /* EEWLiveActivityManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA100000000000000000005 /* EEWLiveActivityManager.swift */; }; + EEA100000000000000000006 /* EEWLiveActivityPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA100000000000000000007 /* EEWLiveActivityPlugin.swift */; }; + EEA200000000000000000001 /* Shared/EEWPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA200000000000000000003 /* Shared/EEWPresentation.swift */; }; + EEA200000000000000000002 /* Shared/EEWPresentation.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA200000000000000000003 /* Shared/EEWPresentation.swift */; }; + EEA200000000000000000004 /* EEWPresentationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA200000000000000000005 /* EEWPresentationTests.swift */; }; F4E200000000000000000001 /* DPIPWidgetProviderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4E200000000000000000002 /* DPIPWidgetProviderTests.swift */; }; F4F200000000000000000001 /* WidgetTownshipResolverTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F4F200000000000000000002 /* WidgetTownshipResolverTests.swift */; }; F56D5186166227E46D96919D /* info.aiff in Resources */ = {isa = PBXBuildFile; fileRef = F9BCED8E5498E9FD7A454E8F /* info.aiff */; }; F765ECAAD6048A3511C79968 /* WidgetTownshipResolver.swift in Sources */ = {isa = PBXBuildFile; fileRef = C1923205FABD42A0835ACDC0 /* WidgetTownshipResolver.swift */; }; FA189DB6B5D2AEDE6B6F84EC /* ForecastClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8A4C17303E0719AE3C5AA97C /* ForecastClient.swift */; }; + EEA300000000000000000001 /* EEWLiveActivityAlerts.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = EEA300000000000000000002 /* EEWLiveActivityAlerts.xcstrings */; }; + EEA300000000000000000003 /* EEWLiveActivityManagerTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA300000000000000000004 /* EEWLiveActivityManagerTests.swift */; }; + EEA400000000000000000001 /* Shared/EEWIslandLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA400000000000000000003 /* Shared/EEWIslandLayout.swift */; }; + EEA400000000000000000002 /* Shared/EEWIslandLayout.swift in Sources */ = {isa = PBXBuildFile; fileRef = EEA400000000000000000003 /* Shared/EEWIslandLayout.swift */; }; LR0S00000000000000000002 /* LocationReportSender.swift in Sources */ = {isa = PBXBuildFile; fileRef = LR0S00000000000000000001 /* LocationReportSender.swift */; }; LR0S00000000000000000004 /* LocationReportSenderTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = LR0S00000000000000000003 /* LocationReportSenderTests.swift */; }; NL0G00000000000000000002 /* NativeLogPlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = NL0G00000000000000000001 /* NativeLogPlugin.swift */; }; @@ -303,11 +314,19 @@ E7A200000000000000000002 /* SavedCurrentWeatherWidgetRefreshServiceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SavedCurrentWeatherWidgetRefreshServiceTests.swift; sourceTree = ""; }; E9F000000000000000000002 /* ForecastWidgetTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ForecastWidgetTests.swift; sourceTree = ""; }; E9F000000000000000000012 /* WidgetHTTPTimeSourceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetHTTPTimeSourceTests.swift; sourceTree = ""; }; + EEA100000000000000000003 /* Shared/EEWActivityAttributes.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared/EEWActivityAttributes.swift; sourceTree = ""; }; + EEA100000000000000000005 /* EEWLiveActivityManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EEWLiveActivityManager.swift; sourceTree = ""; }; + EEA100000000000000000007 /* EEWLiveActivityPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EEWLiveActivityPlugin.swift; sourceTree = ""; }; + EEA200000000000000000003 /* Shared/EEWPresentation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared/EEWPresentation.swift; sourceTree = ""; }; + EEA200000000000000000005 /* EEWPresentationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EEWPresentationTests.swift; sourceTree = ""; }; F4E200000000000000000002 /* DPIPWidgetProviderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DPIPWidgetProviderTests.swift; sourceTree = ""; }; F4F200000000000000000002 /* WidgetTownshipResolverTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WidgetTownshipResolverTests.swift; sourceTree = ""; }; F715E0DC85C56822D8A35131 /* SavedCurrentWeatherWidgetRefreshService.swift */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = sourcecode.swift; name = SavedCurrentWeatherWidgetRefreshService.swift; path = DPIPWidgets/SavedCurrentWeatherWidgetRefreshService.swift; sourceTree = ""; }; F9BCED8E5498E9FD7A454E8F /* info.aiff */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = audio.aiff; path = Sounds/info.aiff; sourceTree = ""; }; FD769D73A7C4BE3619C1F9FB /* report.aiff */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = audio.aiff; path = Sounds/report.aiff; sourceTree = ""; }; + EEA300000000000000000002 /* EEWLiveActivityAlerts.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = EEWLiveActivityAlerts.xcstrings; sourceTree = ""; }; + EEA300000000000000000004 /* EEWLiveActivityManagerTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = EEWLiveActivityManagerTests.swift; sourceTree = ""; }; + EEA400000000000000000003 /* Shared/EEWIslandLayout.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Shared/EEWIslandLayout.swift; sourceTree = ""; }; LR0S00000000000000000001 /* LocationReportSender.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocationReportSender.swift; sourceTree = ""; }; LR0S00000000000000000003 /* LocationReportSenderTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LocationReportSenderTests.swift; sourceTree = ""; }; NL0G00000000000000000001 /* NativeLogPlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeLogPlugin.swift; sourceTree = ""; }; @@ -345,6 +364,9 @@ membershipExceptions = ( CurrentWeatherSnapshotAddress.swift, CurrentWeatherSnapshotStorage.swift, + EEWActivityAttributes.swift, + EEWPresentation.swift, + EEWIslandLayout.swift, ForecastSnapshotLocation.swift, NativeLog.swift, WidgetLocationCatalog.swift, @@ -431,6 +453,9 @@ isa = PBXFileSystemSynchronizedBuildFileExceptionSet; membershipExceptions = ( CurrentWeatherSnapshotStorage.swift, + EEWActivityAttributes.swift, + EEWPresentation.swift, + EEWIslandLayout.swift, ); target = 27CACBA0305BD77F0046F79C /* DPIPWidgetIntentsExtension */; }; @@ -591,6 +616,8 @@ isa = PBXGroup; children = ( 331C807B294A618700263BE5 /* RunnerTests.swift */, + EEA300000000000000000004 /* EEWLiveActivityManagerTests.swift */, + EEA200000000000000000005 /* EEWPresentationTests.swift */, 28A000000000000000000001 /* WidgetSNTPClientTests.swift */, 28A000000000000000000002 /* WidgetServerClockTests.swift */, 4F1000000000000000000001 /* WidgetCurrentLocationClientTests.swift */, @@ -634,6 +661,9 @@ isa = PBXGroup; children = ( 270FCE9B305CD066003D1E62 /* Shared */, + EEA100000000000000000003 /* Shared/EEWActivityAttributes.swift */, + EEA200000000000000000003 /* Shared/EEWPresentation.swift */, + EEA400000000000000000003 /* Shared/EEWIslandLayout.swift */, 272EFB373057247600B78F5D /* DPIPWidgetsExtension.entitlements */, 9740EEB11CF90186004384FC /* Flutter */, 97C146F01CF9000F007C117D /* Runner */, @@ -679,6 +709,9 @@ AA0000000000000000000E01 /* ScreenWakePlugin.swift */, AA0000000000000000000G01 /* LocationTrackStore.swift */, AA0000000000000000000F01 /* ApnsTokenPlugin.swift */, + EEA300000000000000000002 /* EEWLiveActivityAlerts.xcstrings */, + EEA100000000000000000005 /* EEWLiveActivityManager.swift */, + EEA100000000000000000007 /* EEWLiveActivityPlugin.swift */, AA0000000000000000000D01 /* DeviceInfoPlugin.swift */, NL0G00000000000000000001 /* NativeLogPlugin.swift */, IMSV00000000000000000001 /* ImageSaverPlugin.swift */, @@ -1003,6 +1036,7 @@ DP1PF1REBASE0001PL1ST010 /* GoogleService-Info.plist in Resources */, 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + EEA300000000000000000001 /* EEWLiveActivityAlerts.xcstrings in Resources */, 522508B9301F863A006148C2 /* InfoPlist.strings in Resources */, AE92AD9862B7A721B0924557 /* eew.aiff in Resources */, 17BD5D769AA990E7EE681203 /* eew_alert.aiff in Resources */, @@ -1107,6 +1141,9 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + EEA100000000000000000002 /* Shared/EEWActivityAttributes.swift in Sources */, + EEA200000000000000000002 /* Shared/EEWPresentation.swift in Sources */, + EEA400000000000000000002 /* Shared/EEWIslandLayout.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -1129,6 +1166,8 @@ 4F4000000000000000000002 /* WidgetRefreshTestSupport.swift in Sources */, 4F5000000000000000000002 /* CurrentWeatherWidgetTestFixtures.swift in Sources */, 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + EEA300000000000000000003 /* EEWLiveActivityManagerTests.swift in Sources */, + EEA200000000000000000004 /* EEWPresentationTests.swift in Sources */, D91A00000000000000000011 /* CurrentWeatherWidgetTests.swift in Sources */, D91A00000000000000000012 /* CurrentWeatherWidgetSnapshot.swift in Sources */, 27CACC80305C67530046F79C /* WidgetLocationCatalogTests.swift in Sources */, @@ -1206,6 +1245,11 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + EEA100000000000000000001 /* Shared/EEWActivityAttributes.swift in Sources */, + EEA200000000000000000001 /* Shared/EEWPresentation.swift in Sources */, + EEA400000000000000000001 /* Shared/EEWIslandLayout.swift in Sources */, + EEA100000000000000000004 /* EEWLiveActivityManager.swift in Sources */, + EEA100000000000000000006 /* EEWLiveActivityPlugin.swift in Sources */, 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, AA0000000000000000000C02 /* CompassPlugin.swift in Sources */, ACCE10000000000000000002 /* AccelerometerPlugin.swift in Sources */, diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index 86aef5407..32f131c2c 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -67,6 +67,10 @@ import UserNotifications NativeLogPlugin.register(with: registry.registrar(forPlugin: "NativeLogPlugin")!) NotificationSettingsLinkPlugin.register( with: registry.registrar(forPlugin: "NotificationSettingsLinkPlugin")!) + #if DEBUG + EEWLiveActivityPlugin.register( + with: registry.registrar(forPlugin: "EEWLiveActivityPlugin")!) + #endif // Re-post the launch notification the plugins just missed. // diff --git a/ios/Runner/EEWLiveActivityAlerts.xcstrings b/ios/Runner/EEWLiveActivityAlerts.xcstrings new file mode 100644 index 000000000..4e03f02fa --- /dev/null +++ b/ios/Runner/EEWLiveActivityAlerts.xcstrings @@ -0,0 +1,78 @@ +{ + "sourceLanguage": "en", + "strings": { + "eew.alert.title": { + "comment": "Debug-only local EEW arrival alert; always identify this as a test.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "TEST · Earthquake Early Warning" + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "測試 · 地震速報" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "测试 · 地震预警" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "テスト · 緊急地震速報" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "테스트 · 지진 조기 경보" + } + } + } + }, + "eew.alert.arrived": { + "comment": "Debug-only local EEW arrival alert; always identify this as a test.", + "extractionState": "manual", + "localizations": { + "en": { + "stringUnit": { + "state": "translated", + "value": "Mock seismic wave arrived. This is a developer test." + } + }, + "zh-Hant": { + "stringUnit": { + "state": "translated", + "value": "模擬地震波已抵達。此為開發測試。" + } + }, + "zh-Hans": { + "stringUnit": { + "state": "translated", + "value": "模拟地震波已抵达。此为开发测试。" + } + }, + "ja": { + "stringUnit": { + "state": "translated", + "value": "模擬地震波が到達しました。これは開発用テストです。" + } + }, + "ko": { + "stringUnit": { + "state": "translated", + "value": "모의 지진파가 도착했습니다. 개발용 테스트입니다." + } + } + } + } + }, + "version": "1.0" +} diff --git a/ios/Runner/EEWLiveActivityManager.swift b/ios/Runner/EEWLiveActivityManager.swift new file mode 100644 index 000000000..47b31cb59 --- /dev/null +++ b/ios/Runner/EEWLiveActivityManager.swift @@ -0,0 +1,379 @@ +import ActivityKit +import Foundation +#if DEBUG +import UIKit +#endif + +/// Local developer prototype only. The fixed event identity lets us find the +/// activity after an app restart without touching any future production EEW. +@available(iOS 16.1, *) +@MainActor +final class EEWLiveActivityManager { + static let shared = EEWLiveActivityManager() + private static let mockEventId = "dpip-local-mock-eew" + #if DEBUG + private static let genericMockEventId = "dpip-local-generic-mock-eew" + #endif + + enum Failure: LocalizedError { + case unavailable + case disabled + case alreadyActive + case notActive + case duplicateActivities + case invalidTransition + #if DEBUG + case delayedAlertPending + case backgroundUnavailable + #endif + + var errorDescription: String? { + switch self { + case .unavailable: "Live Activities are unavailable on this device." + case .disabled: "Live Activities are disabled in iOS settings." + case .alreadyActive: "The mock EEW activity is already active." + case .notActive: "Start the mock EEW activity first." + case .duplicateActivities: "Multiple mock EEW activities exist; end them before retrying." + case .invalidTransition: "The mock EEW activity has already reached wave arrival." + #if DEBUG + case .delayedAlertPending: "A delayed arrival alert is already scheduled." + case .backgroundUnavailable: "Unable to obtain background execution time for the delayed test." + #endif + } + } + } + + private init() {} + + private let arrivalUpdater = EEWMockArrivalUpdater() + #if DEBUG + private let delayedAlert = EEWDelayedArrivalAlertQA() + #endif + + var status: [String: Any] { + let supported = ActivityAuthorizationInfo().areActivitiesEnabled + var result: [String: Any] = [ + "supported": true, + "enabled": supported, + "active": !mockActivities.isEmpty, + "reportNo": mockActivities.first?.contentState.reportNo as Any? ?? NSNull(), + "waveArrived": mockActivities.first?.contentState.waveArrived ?? false, + "generic": mockActivities.first?.contentState.estimatedLocalIntensity == nil + && !mockActivities.isEmpty, + ] + #if DEBUG + result["delayedAlertStatus"] = delayedAlert.status.rawValue + #endif + return result + } + + private var mockActivities: [Activity] { + Activity.activities.filter { + guard EEWMockArrivalUpdater.canUpdate($0.activityState) else { return false } + #if DEBUG + if $0.attributes.eventId == Self.genericMockEventId { return true } + #endif + return $0.attributes.eventId == Self.mockEventId + } + } + + private func checkEnabled() throws { + guard ActivityAuthorizationInfo().areActivitiesEnabled else { + throw Failure.disabled + } + } + + private func current() throws -> Activity { + guard mockActivities.count <= 1 else { throw Failure.duplicateActivities } + guard let activity = mockActivities.first else { throw Failure.notActive } + return activity + } + + func start() throws { + try checkEnabled() + guard mockActivities.isEmpty else { throw Failure.alreadyActive } + let now = Date() + let attributes = EEWActivityAttributes(provider: "CWA", eventId: Self.mockEventId) + let state = EEWActivityAttributes.ContentState( + reportNo: 1, + originAt: now, + magnitude: 5.7, + depthKm: 20, + epicenter: "臺東縣近海", + reportMaxIntensity: 4, + estimatedLocalIntensity: 2, + estimatedSArrivalAt: now.addingTimeInterval(25), + waveArrived: false + ) + _ = try Activity.request(attributes: attributes, contentState: state, pushType: nil) + } + + #if DEBUG + /// Exercise the existing fallback UI without any location-derived values. + func startGeneric() throws { + try checkEnabled() + guard mockActivities.isEmpty else { throw Failure.alreadyActive } + let attributes = EEWActivityAttributes(provider: "CWA", eventId: Self.genericMockEventId) + let state = EEWActivityAttributes.ContentState( + reportNo: 1, + originAt: Date(), + magnitude: 5.7, + depthKm: 20, + epicenter: "臺東縣近海", + reportMaxIntensity: 4, + estimatedLocalIntensity: nil, + estimatedSArrivalAt: nil, + waveArrived: false + ) + _ = try Activity.request(attributes: attributes, contentState: state, pushType: nil) + } + #endif + + func update(reportNo: Int) async throws { + #if DEBUG + delayedAlert.cancel() + #endif + try checkEnabled() + let activity = try current() + guard activity.attributes.eventId == Self.mockEventId else { throw Failure.invalidTransition } + guard !activity.contentState.waveArrived else { throw Failure.invalidTransition } + guard !arrivalUpdater.hasArrived(activity.id) else { throw Failure.invalidTransition } + guard reportNo == 2 || reportNo == 4 else { throw Failure.invalidTransition } + let previous = activity.contentState + guard reportNo > previous.reportNo else { throw Failure.invalidTransition } + let state = EEWActivityAttributes.ContentState( + reportNo: reportNo, + originAt: previous.originAt, + magnitude: reportNo == 2 ? 5.9 : 6.1, + depthKm: 20, + epicenter: "臺東縣近海", + reportMaxIntensity: reportNo == 2 ? 4 : 5, + estimatedLocalIntensity: 3, + estimatedSArrivalAt: Date().addingTimeInterval(reportNo == 2 ? 18 : 10), + waveArrived: false + ) + await activity.update(using: state) + } + + func markWaveArrived() async throws { + #if DEBUG + delayedAlert.cancel() + #endif + try await markWaveArrived(mode: .silent) + } + + #if DEBUG + func markWaveArrivedWithAlert() async throws { + delayedAlert.cancel() + try await markWaveArrived(mode: .alert) + } + + func scheduleDelayedArrivalAlert() throws { + try checkEnabled() + let activity = try current() + guard activity.attributes.eventId == Self.mockEventId, + !activity.contentState.waveArrived, + !arrivalUpdater.hasArrived(activity.id) else { throw Failure.invalidTransition } + let activityId = activity.id + try delayedAlert.schedule { [weak self] in + guard let self, let current = try? self.current(), current.id == activityId else { + throw Failure.notActive + } + try await self.markWaveArrived(mode: .alert) + } + Task { @MainActor [weak self] in + for await state in activity.activityStateUpdates { + if !EEWMockArrivalUpdater.canUpdate(state) { + self?.delayedAlert.cancel() + break + } + } + } + } + #endif + + private func markWaveArrived(mode: EEWMockArrivalUpdater.Mode) async throws { + try checkEnabled() + let activity = try current() + guard activity.attributes.eventId == Self.mockEventId else { throw Failure.invalidTransition } + try await arrivalUpdater.update( + activityId: activity.id, previous: activity.contentState, + activityState: activity.activityState, mode: mode + ) { state, alert in + if #available(iOS 16.2, *) { + await activity.update(ActivityContent(state: state, staleDate: nil), alertConfiguration: alert) + } else { + await activity.update(using: state, alertConfiguration: alert) + } + } + } + + func end() async throws { + #if DEBUG + delayedAlert.cancel() + #endif + let activity = try current() + await activity.end(using: activity.contentState, dismissalPolicy: .immediate) + } +} + +#if DEBUG +/// One-shot manual QA only. iOS may suspend the app before the delay completes. +@available(iOS 16.1, *) +@MainActor +final class EEWDelayedArrivalAlertQA { + enum Status: String { + case idle = "Idle" + case scheduled = "Scheduled" + case triggered = "Triggered" + case cancelled = "Cancelled" + case expired = "Expired / Unable to execute" + } + + typealias Begin = @MainActor (@escaping @Sendable () -> Void) -> (@MainActor () -> Void)? + typealias Wait = () async throws -> Void + + private struct Pending { + let id: UUID + let finishBackgroundTask: @MainActor () -> Void + let task: Task + } + + private let begin: Begin + private let wait: Wait + private var pending: Pending? + private(set) var status = Status.idle + + init( + begin: Begin? = nil, + wait: @escaping Wait = { try await Task.sleep(nanoseconds: 8_000_000_000) } + ) { + self.begin = begin ?? Self.beginBackgroundTask + self.wait = wait + } + + private static func beginBackgroundTask(expired: @escaping @Sendable () -> Void) -> (@MainActor () -> Void)? { + let application = UIApplication.shared + let identifier = application.beginBackgroundTask(withName: "EEWDelayedArrivalAlertQA", expirationHandler: expired) + guard identifier != .invalid else { return nil } + return { application.endBackgroundTask(identifier) } + } + + func schedule(execute: @escaping () async throws -> Void) throws { + guard pending == nil else { throw EEWLiveActivityManager.Failure.delayedAlertPending } + let id = UUID() + guard let finish = begin({ [weak self] in + Task { @MainActor [weak self] in self?.expire(id: id) } + }) else { + status = .expired + throw EEWLiveActivityManager.Failure.backgroundUnavailable + } + let task = Task { @MainActor [weak self] in + guard let self else { return } + do { + try await self.wait() + try Task.checkCancellation() + guard self.pending?.id == id else { return } + try await execute() + guard self.pending?.id == id else { return } + self.status = .triggered // ActivityKit submission, not visible presentation. + self.clearPending() + } catch is CancellationError { + if self.pending?.id == id { self.cancel() } + } catch { + guard self.pending?.id == id else { return } + self.status = .expired + self.clearPending() + } + } + pending = Pending(id: id, finishBackgroundTask: finish, task: task) + status = .scheduled + } + + func cancel() { + guard let pending else { return } + pending.task.cancel() + status = .cancelled + clearPending() + } + + private func expire(id: UUID) { + guard pending?.id == id else { return } + pending?.task.cancel() + status = .expired + clearPending() + } + + private func clearPending() { + guard let pending else { return } + self.pending = nil + pending.finishBackgroundTask() + } +} +#endif + +/// Reserves explicit arrivals before suspending, including while ActivityKit's +/// contentState still reflects the previous update. Never driven by the ETA. +@available(iOS 16.1, *) +@MainActor +final class EEWMockArrivalUpdater { + enum Mode { + case silent + #if DEBUG + case alert + #endif + + var alertConfiguration: AlertConfiguration? { + switch self { + case .silent: return nil + #if DEBUG + case .alert: + return AlertConfiguration( + title: LocalizedStringResource("eew.alert.title", table: "EEWLiveActivityAlerts"), + body: LocalizedStringResource("eew.alert.arrived", table: "EEWLiveActivityAlerts"), + sound: .default) + #endif + } + } + } + + private var arrivedActivityIds = Set() + + static func canUpdate(_ state: ActivityState) -> Bool { + if state == .active { return true } + if #available(iOS 16.2, *) { return state == .stale } + return false + } + + func hasArrived(_ activityId: String) -> Bool { + arrivedActivityIds.contains(activityId) + } + + func update( + activityId: String, previous: EEWActivityAttributes.ContentState, + activityState: ActivityState, mode: Mode, + send: (EEWActivityAttributes.ContentState, AlertConfiguration?) async -> Void + ) async throws { + guard Self.canUpdate(activityState) else { + throw EEWLiveActivityManager.Failure.notActive + } + guard !previous.waveArrived, !hasArrived(activityId) else { + throw EEWLiveActivityManager.Failure.invalidTransition + } + // No await between checking and reserving. Both arrival actions share + // this guard, so a silent arrival cannot later be upgraded to an alert. + arrivedActivityIds.insert(activityId) + let state = EEWActivityAttributes.ContentState( + reportNo: previous.reportNo, + originAt: previous.originAt, + magnitude: previous.magnitude, + depthKm: previous.depthKm, + epicenter: previous.epicenter, + reportMaxIntensity: previous.reportMaxIntensity, + estimatedLocalIntensity: previous.estimatedLocalIntensity, + estimatedSArrivalAt: previous.estimatedSArrivalAt, + waveArrived: true + ) + await send(state, mode.alertConfiguration) + } +} diff --git a/ios/Runner/EEWLiveActivityPlugin.swift b/ios/Runner/EEWLiveActivityPlugin.swift new file mode 100644 index 000000000..2f9a86612 --- /dev/null +++ b/ios/Runner/EEWLiveActivityPlugin.swift @@ -0,0 +1,69 @@ +import Flutter +import Foundation + +/// Narrow Flutter bridge for manual, local mock controls. +public final class EEWLiveActivityPlugin: NSObject, FlutterPlugin { + public static func register(with registrar: FlutterPluginRegistrar) { + let channel = FlutterMethodChannel( + name: "com.exptech.dpip/eew_live_activity", + binaryMessenger: registrar.messenger()) + registrar.addMethodCallDelegate(EEWLiveActivityPlugin(), channel: channel) + } + + public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) { + guard #available(iOS 16.1, *) else { + if call.method == "getStatus" { + result(["supported": false, "enabled": false, "active": false, + "reportNo": NSNull(), "waveArrived": false]) + } else { + result(FlutterError(code: "unavailable", message: "Requires iOS 16.1 or later.", details: nil)) + } + return + } + + Task { @MainActor in + let manager = EEWLiveActivityManager.shared + do { + switch call.method { + case "getStatus": + result(manager.status) + case "mockStart": + try manager.start() + result(manager.status) + #if DEBUG + case "mockStartGeneric": + try manager.startGeneric() + result(manager.status) + case "mockWaveArrivedWithAlert": + try await manager.markWaveArrivedWithAlert() + result(manager.status) + case "mockScheduleDelayedArrivalAlert": + try manager.scheduleDelayedArrivalAlert() + result(manager.status) + #endif + case "mockUpdate": + guard let arguments = call.arguments as? [String: Any], + let reportNo = arguments["reportNo"] as? Int else { + result(FlutterError(code: "invalid_arguments", message: "reportNo is required.", details: nil)) + return + } + try await manager.update(reportNo: reportNo) + result(manager.status) + case "mockWaveArrived": + try await manager.markWaveArrived() + result(manager.status) + case "mockEnd": + try await manager.end() + result(manager.status) + default: + result(FlutterMethodNotImplemented) + } + } catch { + result(FlutterError( + code: "activity_error", + message: error.localizedDescription, + details: nil)) + } + } + } +} diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist index a0a33f3e2..7abc896b7 100644 --- a/ios/Runner/Info.plist +++ b/ios/Runner/Info.plist @@ -46,6 +46,8 @@ LSRequiresIPhoneOS + NSSupportsLiveActivities + MLNIdeographicFontFamilyName PingFang TC NSAppTransportSecurity diff --git a/ios/RunnerTests/EEWLiveActivityManagerTests.swift b/ios/RunnerTests/EEWLiveActivityManagerTests.swift new file mode 100644 index 000000000..0a9b5ac3a --- /dev/null +++ b/ios/RunnerTests/EEWLiveActivityManagerTests.swift @@ -0,0 +1,276 @@ +import ActivityKit +import XCTest +@testable import Runner + +#if DEBUG +@available(iOS 16.1, *) +@MainActor +final class EEWLiveActivityManagerTests: XCTestCase { + private let epoch = Date(timeIntervalSince1970: 1_000_000) + + func testNormalArrivalSendsUpdateWithoutAlert() async throws { + let updater = EEWMockArrivalUpdater() + var updates = 0 + try await updater.update(activityId: "silent", previous: state(), activityState: .active, mode: .silent) { + content, alert in + updates += 1 + XCTAssertTrue(content.waveArrived) + XCTAssertNil(alert) + } + XCTAssertEqual(updates, 1) + } + + func testExplicitAlertSendsExactlyOneAlertAndBlocksRepeatedArrival() async throws { + for firstMode in [EEWMockArrivalUpdater.Mode.silent, .alert] { + let updater = EEWMockArrivalUpdater() + var updates = 0 + var alerts = 0 + let send: (Runner.EEWActivityAttributes.ContentState, AlertConfiguration?) async -> Void = { content, alert in + updates += 1 + if alert != nil { alerts += 1 } + XCTAssertTrue(content.waveArrived) + } + try await updater.update(activityId: "mock", previous: state(), activityState: .active, + mode: firstMode, send: send) + for mode in [EEWMockArrivalUpdater.Mode.silent, .alert] { + do { + // Deliberately supply the old snapshot: ActivityKit may not + // have published the new contentState to a second caller yet. + try await updater.update(activityId: "mock", previous: state(), activityState: .active, + mode: mode, send: send) + XCTFail("Repeated arrival must be rejected") + } catch { + guard case EEWLiveActivityManager.Failure.invalidTransition = error else { + return XCTFail("Unexpected error: \(error)") + } + } + } + XCTAssertEqual(updates, 1) + XCTAssertEqual(alerts, firstMode == .alert ? 1 : 0) + } + } + + func testArrivalIsReservedBeforeAwaitingActivityKit() async throws { + let updater = EEWMockArrivalUpdater() + try await updater.update(activityId: "mock", previous: state(), activityState: .active, mode: .alert) { + _, alert in + XCTAssertNotNil(alert) + do { + try await updater.update(activityId: "mock", previous: self.state(), activityState: .active, + mode: .alert) { _, _ in XCTFail("Must not send another update") } + XCTFail("In-flight arrival must be rejected") + } catch { + guard case EEWLiveActivityManager.Failure.invalidTransition = error else { + return XCTFail("Unexpected error: \(error)") + } + } + } + } + + func testAlreadyArrivedAndEndedActivitiesAreNotUpdated() async { + for (lifecycle, arrived) in [(ActivityState.active, true), (.ended, false), (.dismissed, false)] { + let updater = EEWMockArrivalUpdater() + do { + try await updater.update(activityId: "mock", previous: state(arrived: arrived), + activityState: lifecycle, mode: .alert) { _, _ in + XCTFail("Must not update arrived or ended activities") + } + XCTFail("Invalid activity must be rejected") + } catch { + XCTAssertTrue(error is EEWLiveActivityManager.Failure) + } + XCTAssertFalse(updater.hasArrived("mock")) + } + } + + func testExpiredCountdownDoesNotInferArrivalOrRequestAnAlert() { + let updater = EEWMockArrivalUpdater() + for eta in [epoch, epoch.addingTimeInterval(-5)] { + let content = state(eta: eta) + XCTAssertFalse(content.waveArrived) + XCTAssertFalse(updater.hasArrived("mock")) + XCTAssertEqual(Runner.EEWPresentation.arrival(for: content), .countdown(eta)) + } + // There is no clock/timer input to the updater; only the explicit + // update method can reach the ActivityKit send closure. + XCTAssertNil(EEWMockArrivalUpdater.Mode.silent.alertConfiguration) + } + + @available(iOS 16.2, *) + func testArrivalPreservesGenericAndPersonalizedFieldsAndAllowsNewActivities() async throws { + let updater = EEWMockArrivalUpdater() + for local in [nil, 3] as [Int?] { + for eta in [nil, epoch] as [Date?] { + let previous = state(local: local, eta: eta) + try await updater.update(activityId: "local=\(String(describing: local)),eta=\(String(describing: eta))", previous: previous, + activityState: .stale, mode: .alert) { content, alert in + XCTAssertEqual(content.reportNo, previous.reportNo) + XCTAssertEqual(content.originAt, previous.originAt) + XCTAssertEqual(content.magnitude, previous.magnitude) + XCTAssertEqual(content.depthKm, previous.depthKm) + XCTAssertEqual(content.epicenter, previous.epicenter) + XCTAssertEqual(content.reportMaxIntensity, previous.reportMaxIntensity) + XCTAssertEqual(content.estimatedLocalIntensity, local) + XCTAssertEqual(content.estimatedSArrivalAt, eta) + XCTAssertEqual(Runner.EEWPresentation.intensity(for: content), local ?? 5) + XCTAssertEqual(Runner.EEWPresentation.arrival(for: content), .arrived) + XCTAssertNotNil(alert) + } + } + } + } + + func testAlertResourcesAreBundledAndLocalized() throws { + let bundle = Bundle(for: EEWLiveActivityManager.self) + for (language, title, body) in [ + ("en", "TEST · Earthquake Early Warning", "Mock seismic wave arrived. This is a developer test."), + ("zh-Hant", "測試 · 地震速報", "模擬地震波已抵達。此為開發測試。") + ] { + let path = try XCTUnwrap(bundle.path(forResource: language, ofType: "lproj")) + let localized = try XCTUnwrap(Bundle(path: path)) + XCTAssertEqual(localized.localizedString(forKey: "eew.alert.title", value: nil, + table: "EEWLiveActivityAlerts"), title) + XCTAssertEqual(localized.localizedString(forKey: "eew.alert.arrived", value: nil, + table: "EEWLiveActivityAlerts"), body) + } + } + + func testDelayedTriggerUsesExistingAlertPathOnlyAfterRelease() async throws { + let gate = DelayGate() + var ended = 0 + let completed = expectation(description: "background task ended") + var submissions = 0 + let scheduler = EEWDelayedArrivalAlertQA( + begin: { _ in { ended += 1; completed.fulfill() } }, + wait: { try await gate.wait() } + ) + let updater = EEWMockArrivalUpdater() + try scheduler.schedule { + try await updater.update(activityId: "mock", previous: self.state(), activityState: .active, + mode: .alert) { content, alert in + XCTAssertTrue(content.waveArrived) + XCTAssertNotNil(alert) + submissions += 1 + } + } + await fulfillment(of: [gate.entered], timeout: 2) + XCTAssertEqual(scheduler.status, .scheduled) + XCTAssertEqual(submissions, 0) + XCTAssertFalse(updater.hasArrived("mock")) + gate.release() + await fulfillment(of: [gate.finished], timeout: 2) + await fulfillment(of: [completed], timeout: 2) + XCTAssertEqual(scheduler.status, .triggered) + XCTAssertEqual(submissions, 1) + XCTAssertEqual(ended, 1) + } + + func testDuplicateSchedulingAndCancellationPreventUpdate() async throws { + let gate = DelayGate() + var ended = 0 + let completed = expectation(description: "background task ended") + var submissions = 0 + let scheduler = EEWDelayedArrivalAlertQA( + begin: { _ in { ended += 1; completed.fulfill() } }, + wait: { try await gate.wait() } + ) + try scheduler.schedule { submissions += 1 } + await fulfillment(of: [gate.entered], timeout: 2) + XCTAssertThrowsError(try scheduler.schedule { submissions += 1 }) { + guard case EEWLiveActivityManager.Failure.delayedAlertPending = $0 else { + return XCTFail("Unexpected error: \($0)") + } + } + scheduler.cancel() + gate.release() + await fulfillment(of: [gate.finished], timeout: 2) + await fulfillment(of: [completed], timeout: 2) + XCTAssertEqual(scheduler.status, .cancelled) + XCTAssertEqual(submissions, 0) + XCTAssertEqual(ended, 1) + } + + func testBackgroundExpirationCancelsAndEndsTaskOnce() async throws { + let gate = DelayGate() + var expire: (@Sendable () -> Void)? + var ended = 0 + let completed = expectation(description: "background task ended") + var submissions = 0 + let scheduler = EEWDelayedArrivalAlertQA( + begin: { callback in + expire = callback + return { ended += 1; completed.fulfill() } + }, + wait: { try await gate.wait() } + ) + try scheduler.schedule { submissions += 1 } + await fulfillment(of: [gate.entered], timeout: 2) + let expiration = try XCTUnwrap(expire) + await Task.detached { expiration() }.value + await fulfillment(of: [completed], timeout: 2) + gate.release() + await fulfillment(of: [gate.finished], timeout: 2) + XCTAssertEqual(scheduler.status, .expired) + XCTAssertEqual(submissions, 0) + XCTAssertEqual(ended, 1) + scheduler.cancel() + expiration() + XCTAssertEqual(ended, 1) + } + + func testEndedActivityCannotSubmitDelayedAlert() async throws { + let gate = DelayGate() + var ended = 0 + let completed = expectation(description: "background task ended") + var submissions = 0 + var active = true + let scheduler = EEWDelayedArrivalAlertQA( + begin: { _ in { ended += 1; completed.fulfill() } }, + wait: { try await gate.wait() } + ) + try scheduler.schedule { + guard active else { throw EEWLiveActivityManager.Failure.notActive } + submissions += 1 + } + await fulfillment(of: [gate.entered], timeout: 2) + active = false + gate.release() + await fulfillment(of: [gate.finished, completed], timeout: 2) + XCTAssertEqual(scheduler.status, .expired) + XCTAssertEqual(submissions, 0) + XCTAssertEqual(ended, 1) + } + + func testUnavailableBackgroundTimeDoesNotSchedule() { + let scheduler = EEWDelayedArrivalAlertQA(begin: { _ in nil }) + XCTAssertThrowsError(try scheduler.schedule { XCTFail("Must not execute") }) + XCTAssertEqual(scheduler.status, .expired) + } + + @MainActor + private final class DelayGate { + let entered = XCTestExpectation(description: "delay entered") + let finished = XCTestExpectation(description: "delay returned") + private var continuation: CheckedContinuation? + + func wait() async throws { + defer { finished.fulfill() } + try await withCheckedThrowingContinuation { continuation in + self.continuation = continuation + entered.fulfill() + } + } + + func release() { + continuation?.resume() + continuation = nil + } + } + + private func state(local: Int? = 3, eta: Date? = nil, arrived: Bool = false) -> Runner.EEWActivityAttributes.ContentState { + .init(reportNo: 4, originAt: epoch, magnitude: 6.1, depthKm: 20, + epicenter: "Synthetic epicenter", reportMaxIntensity: 5, estimatedLocalIntensity: local, + estimatedSArrivalAt: eta, waveArrived: arrived) + } +} +#endif diff --git a/ios/RunnerTests/EEWPresentationTests.swift b/ios/RunnerTests/EEWPresentationTests.swift new file mode 100644 index 000000000..e03de7744 --- /dev/null +++ b/ios/RunnerTests/EEWPresentationTests.swift @@ -0,0 +1,461 @@ +import SwiftUI +import Testing +import XCTest + +@testable import Runner + +@available(iOS 16.1, *) +final class EEWPresentationTests: XCTestCase { + private let epoch = Date(timeIntervalSince1970: 1_000_000) + + func testPersonalizationFallsBackIndependently() { + for local in [nil, 4] as [Int?] { + for eta in [nil, epoch] as [Date?] { + let state = state(local: local, eta: eta) + XCTAssertEqual(EEWPresentation.intensity(for: state), local ?? 5) + XCTAssertEqual( + EEWPresentation.intensityLabel(for: state), + local == nil ? "eew.intensity.max" : "eew.intensity.local") + XCTAssertEqual(EEWPresentation.arrival(for: state), eta.map { .countdown($0) } ?? .unavailable) + XCTAssertEqual(state.estimatedLocalIntensity, local) + XCTAssertEqual(state.estimatedSArrivalAt, eta) + } + } + } + + func testExplicitArrivalWinsWithOrWithoutPersonalization() { + for local in [nil, 4] as [Int?] { + for eta in [nil, epoch.addingTimeInterval(-5), epoch.addingTimeInterval(35)] as [Date?] { + let state = state(local: local, eta: eta, arrived: true) + XCTAssertEqual(EEWPresentation.arrival(for: state), .arrived) + XCTAssertEqual(EEWPresentation.intensity(for: state), local ?? 5) + } + } + } + + func testZeroAndExpiredETADoNotInferArrival() { + for eta in [epoch, epoch.addingTimeInterval(-5)] { + let state = state(local: nil, eta: eta) + XCTAssertEqual(EEWPresentation.arrival(for: state), .countdown(eta)) + XCTAssertFalse(state.waveArrived) + } + } + + func testDiscreteIntensityTextAndSpokenMapping() { + for (ordinal, key) in [(5, "5weak"), (6, "5strong"), (7, "6weak"), (8, "6strong")] { + for compact in [false, true] { + XCTAssertEqual( + EEWPresentation.intensityText(ordinal, compact: compact), + .init(key: "eew.intensity." + key, level: nil)) + XCTAssertEqual( + EEWPresentation.intensityText(ordinal, compact: compact, spoken: true), + .init(key: "eew.intensity." + key + ".spoken", level: nil)) + } + } + for (ordinal, level) in [(1, 1), (2, 2), (3, 3), (4, 4), (9, 7)] { + XCTAssertEqual(EEWPresentation.intensityText(ordinal), .init(key: "eew.intensity.format", level: level)) + XCTAssertEqual( + EEWPresentation.intensityText(ordinal, compact: true), + .init(key: "eew.intensity.compact.format", level: level)) + XCTAssertEqual( + EEWPresentation.intensityText(ordinal, compact: true, spoken: true), + .init(key: "eew.intensity.format", level: level)) + } + } + + func testReportDetailsDoNotChangePrimaryStateSelection() { + let state = state( + local: 8, eta: epoch, report: 123, + epicenter: "Long epicenter used only as synthetic layout stress data") + XCTAssertEqual(state.reportNo, 123) + XCTAssertEqual(EEWPresentation.intensity(for: state), 8) + XCTAssertEqual(EEWPresentation.arrival(for: state), .countdown(epoch)) + } + + func testIslandFallbackPreservesArrivalSemantics() { + for local in [nil, 4, 5, 8] as [Int?] { + XCTAssertEqual(EEWPresentation.islandArrivalSymbol(for: state(local: local, eta: epoch)), "clock") + XCTAssertEqual( + EEWPresentation.islandArrivalSymbol(for: state(local: local, eta: nil)), + "clock.badge.questionmark") + for eta in [nil, epoch] as [Date?] { + XCTAssertEqual( + EEWPresentation.islandArrivalSymbol(for: state(local: local, eta: eta, arrived: true)), + "checkmark") + } + } + } + + func testTimerEnvelopeReservesRemainingDigitsAcrossETABoundary() { + for (seconds, sample, afterOneSecond) in [ + (0.0, "8:88", "8:88"), (9, "8:88", "8:88"), (18, "8:88", "8:88"), + (59, "8:88", "8:88"), (60, "8:88", "8:88"), (120, "8:88", "8:88"), + (35, "8:88", "8:88"), (125, "8:88", "8:88"), + (599.9, "88:88", "8:88"), (599.1, "88:88", "8:88"), + (599, "8:88", "8:88"), (600, "88:88", "8:88"), (6_000, "888:88", "88:88"), + (5_999.9, "888:88", "88:88"), + ] { + let state = state(local: nil, eta: epoch.addingTimeInterval(seconds)) + for (elapsed, expected) in [(0.0, sample), (1.0, afterOneSecond), (seconds + 1, "8:88")] { + XCTAssertEqual( + EEWPresentation.islandTimerSample(for: state, now: epoch.addingTimeInterval(elapsed)), + expected) + XCTAssertEqual(EEWPresentation.arrival(for: state), .countdown(epoch.addingTimeInterval(seconds))) + } + } + XCTAssertEqual(EEWPresentation.islandTimerSample(for: state(local: nil, eta: nil), now: epoch), "8:88") + } + + func testBadgePaletteAndSmallTextContrast() { + // Pin the published DPIP palette, including every CWA weak/strong ordinal. + let expected = [ + 0x9E9E9E, 0x003264, 0x0064C8, 0x1E9632, 0xFFC800, + 0xFF9600, 0xFF6400, 0xFF0000, 0xC00000, 0x9600C8, + ] + for (ordinal, rgb) in expected.enumerated() { + let background = components(EEWIntensityColor.color(for: ordinal)) + XCTAssertEqual(background[0], Double((rgb >> 16) & 255) / 255, accuracy: 0.001) + XCTAssertEqual(background[1], Double((rgb >> 8) & 255) / 255, accuracy: 0.001) + XCTAssertEqual(background[2], Double(rgb & 255) / 255, accuracy: 0.001) + XCTAssertEqual(background[3], 1, accuracy: 0.001) + let foreground = components(EEWIntensityColor.foreground(for: ordinal)) + let luminances = [luminance(background), luminance(foreground)].sorted() + let contrast = (luminances[1] + 0.05) / (luminances[0] + 0.05) + XCTAssertGreaterThanOrEqual(contrast, 4.5, "Small badge text: ordinal \(ordinal)") + } + for unknown in [-1, 10] { + XCTAssertEqual( + components(EEWIntensityColor.color(for: unknown)), + components(EEWIntensityColor.color(for: 0))) + } + } + + func testEveryIntensityKeepsLocalAndMaximumFallbackSemantics() { + for ordinal in 0...9 { + for local in [nil, ordinal] as [Int?] { + for eta in [nil, epoch] as [Date?] { + let state = EEWActivityAttributes.ContentState( + reportNo: 1, originAt: epoch, magnitude: 6, depthKm: 20, + epicenter: "Synthetic epicenter", reportMaxIntensity: ordinal, + estimatedLocalIntensity: local, estimatedSArrivalAt: eta, waveArrived: false + ) + XCTAssertEqual(EEWPresentation.intensity(for: state), ordinal) + XCTAssertEqual( + EEWPresentation.intensityLabel(for: state), + local == nil ? "eew.intensity.max" : "eew.intensity.local" + ) + XCTAssertEqual(EEWPresentation.arrival(for: state), eta.map { .countdown($0) } ?? .unavailable) + } + } + } + } + + @MainActor + func testLargeTypeStillDegradesWithoutOverflow() { + for size in [DynamicTypeSize.xxxLarge, .accessibility3] { + for limited in [false, true] { + let content = EEWIslandIntensityPresentation(intensity: 8, limitedInWidth: limited) { + Text(verbatim: "6強") + } testBadge: { + Text(verbatim: "TEST").font(.system(size: 8, weight: .bold)) + } + .font(.caption.bold()) + .dynamicTypeSize(size) + for width in [4.0, 12, 24, 32, 40, 60, 100] { + let measuredSize = measured(content, width: width) + XCTAssertLessThanOrEqual(measuredSize.width, width + 0.5) + XCTAssertLessThanOrEqual(measuredSize.height, 36.5) + } + } + } + } + + @MainActor + func testBadgeCandidatesKeepWholeClassificationsAtEveryWidth() { + for (ordinal, label) in [ + (1, "1"), (2, "2"), (3, "3"), (4, "4"), + (5, "5弱"), (6, "5強"), (7, "6弱"), (8, "6強"), (9, "7"), + (5, "5−"), (6, "5+"), (7, "6−"), (8, "6+"), + ] { + for limited in [false, true] { + let content = EEWIslandIntensityPresentation(intensity: ordinal, limitedInWidth: limited) { + Text(verbatim: label) + } testBadge: { + Text(verbatim: "TEST").font(.system(size: 8, weight: .bold)) + } + .font(.caption.bold()) + let badge = EEWIslandIntensityBadge(intensity: ordinal) { Text(verbatim: label) } + let dense = EEWIslandIntensityBadge(intensity: ordinal, dense: true) { Text(verbatim: label) } + let badgeSize = measured(badge, width: 200) + let denseSize = measured(dense, width: 200) + XCTAssertLessThan(denseSize.width, badgeSize.width) + XCTAssertLessThan(denseSize.height, badgeSize.height) + let normal = measured(content, width: 200) + if limited { + XCTAssertEqual(normal.width, badgeSize.width, accuracy: 0.5) + } else { + XCTAssertGreaterThan(normal.width, badgeSize.width) + // TEST may disappear while waveform + full badge still fit. + let withoutTest = measured(content, width: normal.width - 1) + XCTAssertGreaterThan(withoutTest.width, badgeSize.width) + XCTAssertLessThan(withoutTest.width, normal.width) + } + let narrow = measured(content, width: denseSize.width + 0.5) + XCTAssertEqual(narrow.width, denseSize.width, accuracy: 0.5) + let textWidth = measured( + Text(verbatim: label).font(.caption2.bold()).monospacedDigit(), width: 200 + ).width + if textWidth < denseSize.width - 0.5 { + XCTAssertEqual(measured(content, width: textWidth + 0.25).width, textWidth, accuracy: 0.5) + } + for width in [4.0, 8, 12, 16, 24, 32, 40, 60, 100] { + let size = measured(content, width: width) + XCTAssertLessThanOrEqual(size.width, width + 0.5, "\(label), limited=\(limited)") + XCTAssertLessThanOrEqual(size.height, 36.5) + } + } + } + } + + @MainActor + func testTimerEnvelopeCentersItsOverlayWithoutChangingDigitProtection() throws { + // Pixel measurement of the shared overlay region, not a claim about + // ActivityKit's autonomous timer or the system-managed Island position. + for sample in ["8:88", "88:88", "888:88"] { + let content = EEWIslandTimerEnvelope(sample: sample) { + Color.white.frame(width: 6, height: 4) + } + .font(.caption.bold()) + let renderer = ImageRenderer(content: content) + renderer.scale = 3 + let image = try XCTUnwrap(renderer.cgImage) + let bytes = try XCTUnwrap(image.dataProvider?.data) + let data = try XCTUnwrap(CFDataGetBytePtr(bytes)) + var columns: [Int] = [] + for x in 0.. 128 { + columns.append(x) + break + } + } + } + let left = try XCTUnwrap(columns.min()) + let right = try XCTUnwrap(columns.max()) + XCTAssertEqual(Double(left + right) / 2, Double(image.width - 1) / 2, accuracy: 1) + } + } + + private func components(_ color: Color) -> [Double] { + var red: CGFloat = 0 + var green: CGFloat = 0 + var blue: CGFloat = 0 + var alpha: CGFloat = 0 + XCTAssertTrue(UIColor(color).getRed(&red, green: &green, blue: &blue, alpha: &alpha)) + return [red, green, blue, alpha].map(Double.init) + } + + private func luminance(_ components: [Double]) -> Double { + let linear = components.prefix(3).map { value in + value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4) + } + return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2] + } + + @MainActor + func testFittingMeasuresWholeIntensityInsteadOfAcceptingTruncatedText() { + // Real SwiftUI text measurement, not character-count width estimates. + // The same fitting container is used by both compact Island regions. + for (fullLabel, label) in [ + ("5弱", "5弱"), ("6強", "6強"), ("5−", "5−"), + ("6+", "6+"), ("7級", "7"), ("4級", "4"), + ] { + for limited in [false, true] { + let content = EEWIslandFittingView(limitedInWidth: limited) { + HStack(spacing: 4) { + Image(systemName: "waveform.path.ecg") + Text(verbatim: fullLabel) + Text(verbatim: "TEST") + } + } compact: { + Text(verbatim: label) + } fallback: { + Color.red.frame(width: 4, height: 4) + } + .font(.caption.bold()) + let labelWidth = measured(Text(verbatim: label).font(.caption.bold()), width: 200).width + let normal = measured(content, width: 200) + XCTAssertGreaterThanOrEqual(normal.width, labelWidth) + if limited { XCTAssertEqual(normal.width, labelWidth, accuracy: 0.5) } + let abbreviated = measured(content, width: labelWidth + 1) + XCTAssertEqual(abbreviated.width, labelWidth, accuracy: 0.5) + let tooNarrow = measured(content, width: labelWidth - 1) + XCTAssertEqual( + tooNarrow.width, 4, accuracy: 0.5, + "A partial intensity must never win: \(label), limited=\(limited)") + XCTAssertLessThanOrEqual(tooNarrow.height, 20) + } + } + } + + @MainActor + func testTerminalSymbolsRespectTinyProposedWidths() { + for symbol in ["waveform.path.ecg", "clock", "clock.badge.questionmark", "checkmark"] { + let content = EEWIslandFittingView(limitedInWidth: false) { + Text(verbatim: "Full candidate") + } compact: { + Text(verbatim: "5弱") + } fallback: { + Image(systemName: symbol) + .resizable() + .scaledToFit() + .frame(maxWidth: 14, maxHeight: 14) + } + for width in [4.0, 8, 12] { + let size = measured(content, width: width) + XCTAssertLessThanOrEqual(size.width, width + 0.5) + XCTAssertLessThanOrEqual(size.height, 14.5) + } + } + } + + @MainActor + func testMinimalKeepsTimerEnvelopeWhenItFitsEvenWithLimitedWidthHint() { + for sample in ["8:88", "88:88", "888:88"] { + for limited in [false, true] { + let envelope = EEWIslandTimerEnvelope(sample: sample) { + // A greedy overlay models timer Text's layout behavior. The + // real timer's autonomous rendering still needs system QA. + Color.green + } + .font(.caption2.bold()) + let width = measured(envelope, width: 200).width + let content = EEWIslandFittingView(limitedInWidth: limited) { + envelope + } compact: { + envelope + } fallback: { + Color.red.frame(width: 8, height: 8) + } + XCTAssertEqual(measured(content, width: width + 1).width, width, accuracy: 0.5) + XCTAssertEqual(measured(content, width: width - 1).width, 8, accuracy: 0.5) + } + } + } + + @MainActor + func testWidthReaderHasWorkingCompatibleContent() { + let content = EEWIslandWidthReader { _ in Text(verbatim: "EEW") } + XCTAssertGreaterThan(measured(content, width: 200).width, 0) + } + + @MainActor + func testWidthReaderUsesCompatibleFittingPath() { + // Every SDK uses false; narrow proposals still select smaller candidates + // through ViewThatFits, as exercised by the fitting tests above. + let content = EEWIslandWidthReader { limited in + Color.red.frame(width: limited ? 8 : 40, height: 8) + } + XCTAssertEqual(measured(content, width: 100).width, 40, accuracy: 0.5) + } + + @MainActor + private func measured(_ content: Content, width: CGFloat) -> CGSize { + autoreleasepool { + let host = UIHostingController(rootView: content) + return host.sizeThatFits(in: CGSize(width: width, height: 36)) + } + } + + private func state( + local: Int?, eta: Date?, arrived: Bool = false, + report: Int = 4, epicenter: String = "Synthetic epicenter" + ) -> EEWActivityAttributes.ContentState { + .init( + reportNo: report, originAt: epoch, magnitude: 6.1, depthKm: 20, + epicenter: epicenter, reportMaxIntensity: 5, estimatedLocalIntensity: local, + estimatedSArrivalAt: eta, waveArrived: arrived) + } +} + +@MainActor +struct EEWCountdownInkTests { + @Test + func completeSystemTimerFitsItsMeasuredEnvelope() throws { + guard #available(iOS 16.1, *) else { return } + // Pause only this rendering fixture, so both images contain the same + // real timer glyphs. ImageRenderer does not prove background ticking or + // SpringBoard's multi-activity mask; those require separate manual QA. + // Keep the interval in the future instead of racing the rendering + // host's current clock. Pin both integral and fractional timestamps; + // the explicit m:ss reference below also proves the fixture is paused + // at the intended duration rather than silently rendering zero. + for fraction in [0.0, 0.1, 0.5, 0.9] { + let now = Date(timeIntervalSince1970: 5_000_000_000 + fraction) + for seconds in [600.0, 599.9, 599.1, 599, 120, 60, 59, 18, 9, 0] { + let arrival = now.addingTimeInterval(seconds) + let state = EEWActivityAttributes.ContentState( + reportNo: 1, originAt: now, magnitude: 6, depthKm: 20, + epicenter: "Synthetic epicenter", reportMaxIntensity: 5, + estimatedLocalIntensity: 4, estimatedSArrivalAt: arrival, waveArrived: false) + let timer = Text(timerInterval: now...arrival, pauseTime: now, countsDown: true, showsHours: false) + .monospacedDigit() + .foregroundStyle(.white) + for font in [Font.caption.bold(), .caption2.bold()] { + for locale in [Locale(identifier: "zh_TW"), Locale(identifier: "en_US")] { + let envelope = EEWIslandTimerEnvelope( + sample: EEWPresentation.islandTimerSample(for: state, now: now) + ) { timer } + .font(font) + .environment(\.locale, locale) + .fixedSize() + let reference = timer.font(font) + .environment(\.locale, locale) + .frame(width: 200) + let actual = try inkBounds(envelope) + let complete = try inkBounds(reference) + let remaining = Int(ceil(seconds)) + let expectedText = String(format: "%d:%02d", remaining / 60, remaining % 60) + let expected = try inkBounds( + Text(verbatim: expectedText).monospacedDigit().foregroundStyle(.white) + .font(font).environment(\.locale, locale).frame(width: 200)) + #expect( + abs(complete.inkWidth - expected.inkWidth) <= 2, + "Paused timer must show \(expectedText), fraction=\(fraction), locale=\(locale.identifier)") + #expect( + abs(actual.inkWidth - complete.inkWidth) <= 2, + "seconds=\(seconds), fraction=\(fraction), font=\(font), locale=\(locale.identifier), actual=\(actual), complete=\(complete)") + #expect(actual.left >= 3) + #expect(actual.right < actual.imageWidth - 3) + #expect(abs(actual.left + actual.right - (actual.imageWidth - 1)) <= 4) + } + } + } + } + } + + @available(iOS 16.0, *) + private func inkBounds(_ content: Content) throws -> ( + left: Int, right: Int, inkWidth: Int, imageWidth: Int + ) { + let renderer = ImageRenderer(content: content) + renderer.scale = 3 + let image = try #require(renderer.cgImage) + let bytes = try #require(image.dataProvider?.data) + let data = try #require(CFDataGetBytePtr(bytes)) + var columns: [Int] = [] + for x in 0.. 128 { + columns.append(x) + break + } + } + } + let left = try #require(columns.min()) + let right = try #require(columns.max()) + return (left, right, right - left + 1, image.width) + } +} diff --git a/ios/Shared/EEWActivityAttributes.swift b/ios/Shared/EEWActivityAttributes.swift new file mode 100644 index 000000000..54d730d86 --- /dev/null +++ b/ios/Shared/EEWActivityAttributes.swift @@ -0,0 +1,22 @@ +import ActivityKit +import Foundation + +/// Phase 1's local-only EEW presentation contract. No production event is +/// converted into this type until its lifecycle semantics are specified. +@available(iOS 16.1, *) +struct EEWActivityAttributes: ActivityAttributes { + let provider: String + let eventId: String + + struct ContentState: Codable, Hashable { + let reportNo: Int + let originAt: Date + let magnitude: Double + let depthKm: Double + let epicenter: String + let reportMaxIntensity: Int + let estimatedLocalIntensity: Int? + let estimatedSArrivalAt: Date? + let waveArrived: Bool + } +} diff --git a/ios/Shared/EEWIslandLayout.swift b/ios/Shared/EEWIslandLayout.swift new file mode 100644 index 000000000..609390763 --- /dev/null +++ b/ios/Shared/EEWIslandLayout.swift @@ -0,0 +1,161 @@ +import SwiftUI +import WidgetKit + +/// Width is proposed by the host, not inferred from the device or activity count. +@available(iOS 16.1, *) +struct EEWIslandWidthReader: View { + @ViewBuilder let content: (Bool) -> Content + + var body: some View { + // CI's iOS 26 SDK has no Dynamic Island width environment key. + // Let ViewThatFits measure the host's proposal on every supported SDK. + content(false) + } +} + +@available(iOS 16.1, *) +struct EEWIslandFittingView: View { + let limitedInWidth: Bool + @ViewBuilder let regular: () -> Regular + @ViewBuilder let compact: () -> Compact + @ViewBuilder let smallest: () -> Smallest + @ViewBuilder let fallback: () -> Fallback + + var body: some View { + ViewThatFits { + if !limitedInWidth { + regular().fixedSize() + } + // A truncated Text must never count as a successful fit. Measure the + // complete candidate, including localized weak/strong intensity labels. + compact().fixedSize() + if Smallest.self != EmptyView.self { + smallest().fixedSize() + } + // The terminal candidate must degrade without a partial label. + fallback() + } + .lineLimit(1) + } +} + +// Preserve the existing three-candidate call sites. Badge presentations can +// insert one smaller, complete candidate without changing the fitting policy. +@available(iOS 16.1, *) +extension EEWIslandFittingView where Smallest == EmptyView { + init( + limitedInWidth: Bool, + @ViewBuilder regular: @escaping () -> Regular, + @ViewBuilder compact: @escaping () -> Compact, + @ViewBuilder fallback: @escaping () -> Fallback + ) { + self.limitedInWidth = limitedInWidth + self.regular = regular + self.compact = compact + self.smallest = { EmptyView() } + self.fallback = fallback + } +} + +/// Intrinsic text size determines the badge dimensions, including localized +/// weak/strong labels. The fitting container selects dense metrics before it +/// removes the badge; neither variant truncates or scales a classification. +@available(iOS 16.1, *) +struct EEWIslandIntensityBadge: View { + let intensity: Int + var dense = false + @ViewBuilder let label: () -> Label + + var body: some View { + label() + .font(dense ? .caption2.bold() : .caption.bold()) + .monospacedDigit() + .lineLimit(1) + .fixedSize() + .padding(.horizontal, dense ? 2 : 4) + .padding(.vertical, dense ? 1 : 2) + .foregroundStyle(EEWIntensityColor.foreground(for: intensity)) + .background(EEWIntensityColor.color(for: intensity), in: RoundedRectangle(cornerRadius: 4)) + } +} + +@available(iOS 16.1, *) +struct EEWIslandIntensityPresentation: View { + let intensity: Int + let limitedInWidth: Bool + @ViewBuilder let label: () -> Label + @ViewBuilder let testBadge: () -> TestBadge + + private var badge: some View { + EEWIslandIntensityBadge(intensity: intensity, label: label) + } + + var body: some View { + EEWIslandFittingView(limitedInWidth: limitedInWidth) { + HStack(spacing: 4) { + waveform + badge + testBadge() + } + } compact: { + if limitedInWidth { + badge + } else { + // Drop the visual TEST decoration before losing the waveform. + // The caller retains TEST's spoken hint at every width. + HStack(spacing: 4) { + waveform + badge + } + } + } smallest: { + EEWIslandIntensityBadge(intensity: intensity, dense: true, label: label) + } fallback: { + ViewThatFits { + // Never let clipped text win, even after removing the badge. + label().font(.caption2.bold()).monospacedDigit().fixedSize() + Image(systemName: "waveform.path.ecg") + .resizable() + .scaledToFit() + .frame(maxWidth: 16, maxHeight: 16) + .foregroundStyle(.red) + } + } + } + + private var waveform: some View { + Image(systemName: "waveform.path.ecg") + .foregroundStyle(.red) + .accessibilityHidden(true) + } +} + +/// A timer Text is greedy and has no useful intrinsic width in a widget host. +/// Measure a hidden monospaced envelope, then fix that width for the real +/// system timer. The envelope is layout only and never visible or accessible. +@available(iOS 16.1, *) +struct EEWIslandTimerEnvelope: View { + let sample: String + @ViewBuilder let timer: () -> Timer + + var body: some View { + Text(verbatim: sample) + .monospacedDigit() + .hidden() + .accessibilityHidden(true) + .overlay(alignment: .center) { + // Widget time Text is horizontally flexible. An overlay does + // not contribute to ViewThatFits' measurement, and maxWidth: + // .infinity is not a fixed width when fixedSize probes ideal + // sizes. Archive an explicit frame matching the measured sample. + GeometryReader { geometry in + timer() + .frame(width: geometry.size.width, height: geometry.size.height, alignment: .center) + .multilineTextAlignment(.center) + } + } + // Include breathing room in the fitting decision itself; adding it + // only to the overlay would let a cramped numeric candidate win. + .padding(.horizontal, 2) + } +} diff --git a/ios/Shared/EEWPresentation.swift b/ios/Shared/EEWPresentation.swift new file mode 100644 index 000000000..48c1fc551 --- /dev/null +++ b/ios/Shared/EEWPresentation.swift @@ -0,0 +1,114 @@ +import Foundation +import SwiftUI + +/// Pure presentation choices shared by the widget and its native regression tests. +@available(iOS 16.1, *) +enum EEWPresentation { + enum Arrival: Equatable { + case arrived + case countdown(Date) + case unavailable + } + + struct IntensityText: Equatable { + let key: String + let level: Int? + } + + static func intensity(for state: EEWActivityAttributes.ContentState) -> Int { + // Missing local intensity and ETA fall back independently; neither + // optional field is evidence that the other estimate exists. + state.estimatedLocalIntensity ?? state.reportMaxIntensity + } + + static func intensityLabel(for state: EEWActivityAttributes.ContentState) -> String { + state.estimatedLocalIntensity == nil ? "eew.intensity.max" : "eew.intensity.local" + } + + static func arrival(for state: EEWActivityAttributes.ContentState) -> Arrival { + // Absolute ETA lets the system timer update while the extension sleeps. + // Only an explicit domain update means arrived, even after ETA expires. + if state.waveArrived { return .arrived } + if let eta = state.estimatedSArrivalAt { return .countdown(eta) } + return .unavailable + } + + static func islandArrivalSymbol(for state: EEWActivityAttributes.ContentState) -> String { + switch arrival(for: state) { + case .arrived: return "checkmark" + case .countdown: return "clock" + case .unavailable: return "clock.badge.questionmark" + } + } + + static func islandTimerSample(for state: EEWActivityAttributes.ContentState, now: Date) -> String { + guard let arrival = state.estimatedSArrivalAt else { return "8:88" } + // Reserve the maximum remaining digit count at this render. A countdown + // can only lose digits while the extension sleeps; an ETA update renders + // a new envelope. Using originAt would unnecessarily reject a fitting + // 9:59 timer for an older event. This is not displayed ETA data. + let duration = max(0, arrival.timeIntervalSince(now)) + // The system countdown rounds a fractional remaining second up: 599.9s + // still displays 10:00. Floor division would reserve only 8:88 and clip + // the first second of the wider value in an archived widget layout. + let minutes = Int(ceil(duration) / 60) + return String(repeating: "8", count: max(1, String(minutes).count)) + ":88" + } + + static func intensityText(_ intensity: Int, compact: Bool = false, spoken: Bool = false) -> IntensityText { + // DPIP stores CWA's discrete ordinal, not the printed intensity number. + let key: String + switch intensity { + case 5: key = "eew.intensity.5weak" + case 6: key = "eew.intensity.5strong" + case 7: key = "eew.intensity.6weak" + case 8: key = "eew.intensity.6strong" + default: + return IntensityText( + key: compact && !spoken ? "eew.intensity.compact.format" : "eew.intensity.format", + level: intensity == 9 ? 7 : intensity) + } + return IntensityText(key: spoken ? key + ".spoken" : key, level: nil) + } +} + +@available(iOS 16.1, *) +enum EEWIntensityColor { + static func foreground(for intensity: Int) -> Color { + // Opaque sRGB backgrounds: choose the stronger black/white contrast. + // No intensity colour is changed to make its text readable. + let rgb = backgroundRGB(for: intensity) + func linear(_ component: Int) -> Double { + let value = Double(component) / 255 + return value <= 0.04045 ? value / 12.92 : pow((value + 0.055) / 1.055, 2.4) + } + let luminance = 0.2126 * linear(rgb.red) + 0.7152 * linear(rgb.green) + 0.0722 * linear(rgb.blue) + let blackContrast = (luminance + 0.05) / 0.05 + let whiteContrast = 1.05 / (luminance + 0.05) + return blackContrast >= whiteContrast ? .black : .white + } + + static func color(for intensity: Int) -> Color { + let rgb = backgroundRGB(for: intensity) + return Color( + .sRGB, red: Double(rgb.red) / 255, green: Double(rgb.green) / 255, + blue: Double(rgb.blue) / 255, opacity: 1) + } + + // The existing native palette matches lib/shared/seismic/intensity_colors.dart. + // Move it here unchanged so widget presentation and native tests share it. + private static func backgroundRGB(for intensity: Int) -> (red: Int, green: Int, blue: Int) { + switch intensity { + case 1: return (0, 50, 100) + case 2: return (0, 100, 200) + case 3: return (30, 150, 50) + case 4: return (255, 200, 0) + case 5: return (255, 150, 0) + case 6: return (255, 100, 0) + case 7: return (255, 0, 0) + case 8: return (192, 0, 0) + case 9: return (150, 0, 200) + default: return (158, 158, 158) + } + } +} diff --git a/lib/core/platform/eew_live_activity.dart b/lib/core/platform/eew_live_activity.dart new file mode 100644 index 000000000..711dde9b3 --- /dev/null +++ b/lib/core/platform/eew_live_activity.dart @@ -0,0 +1,78 @@ +/// Manual, local EEW Live Activity prototype controls for the developer page. +library; + +import 'package:flutter/services.dart'; + +class EewLiveActivityStatus { + const EewLiveActivityStatus({ + required this.supported, + required this.enabled, + required this.active, + required this.reportNo, + required this.waveArrived, + this.generic = false, + this.delayedAlertStatus, + }); + + final bool supported; + final bool enabled; + final bool active; + final int? reportNo; + final bool waveArrived; + final bool generic; + final String? delayedAlertStatus; + + factory EewLiveActivityStatus.fromMap(Map raw) => + EewLiveActivityStatus( + supported: raw['supported'] == true, + enabled: raw['enabled'] == true, + active: raw['active'] == true, + reportNo: raw['reportNo'] as int?, + waveArrived: raw['waveArrived'] == true, + generic: raw['generic'] == true, + delayedAlertStatus: raw['delayedAlertStatus'] as String?, + ); +} + +class EewLiveActivity { + const EewLiveActivity({MethodChannel? channel}) + : _channel = + channel ?? const MethodChannel('com.exptech.dpip/eew_live_activity'); + + final MethodChannel _channel; + + Future getStatus() => _invoke('getStatus'); + Future mockStart() => _invoke('mockStart'); + Future mockStartGeneric() => + _invoke('mockStartGeneric'); + Future mockUpdate(int reportNo) => + _invoke('mockUpdate', {'reportNo': reportNo}); + Future mockWaveArrived() => _invoke('mockWaveArrived'); + Future mockWaveArrivedWithAlert() => + _invoke('mockWaveArrivedWithAlert'); + Future mockScheduleDelayedArrivalAlert() => + _invoke('mockScheduleDelayedArrivalAlert'); + Future mockEnd() => _invoke('mockEnd'); + + Future _invoke( + String method, [ + Map? arguments, + ]) async { + try { + final raw = await _channel.invokeMapMethod( + method, + arguments, + ); + if (raw == null) throw StateError('Missing EEW Live Activity status'); + return EewLiveActivityStatus.fromMap(raw); + } on MissingPluginException { + return const EewLiveActivityStatus( + supported: false, + enabled: false, + active: false, + reportNo: null, + waveArrived: false, + ); + } + } +} diff --git a/lib/features/settings/presentation/pages/developer_page.dart b/lib/features/settings/presentation/pages/developer_page.dart index 26eda2783..dd37cec2d 100644 --- a/lib/features/settings/presentation/pages/developer_page.dart +++ b/lib/features/settings/presentation/pages/developer_page.dart @@ -16,6 +16,7 @@ import 'package:dpip/core/network/etag_cache_store.dart'; import 'package:dpip/core/network/network_usage_store.dart'; import 'package:dpip/core/notifications/notification_service.dart'; import 'package:dpip/core/platform/background_location.dart'; +import 'package:dpip/core/platform/eew_live_activity.dart'; import 'package:dpip/core/storage/app_database.dart'; import 'package:dpip/core/settings/experimental_settings.dart'; import 'package:dpip/core/storage/app_storage_scan.dart'; @@ -27,7 +28,7 @@ import 'package:dpip/shared/widgets/section_header.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; -import 'package:maplibre_gl/maplibre_gl.dart'; +import 'package:maplibre_gl/maplibre_gl.dart' show clearAmbientCache; import 'package:provider/provider.dart'; /// One labelled diagnostic value. @@ -54,6 +55,25 @@ class _DeveloperPageState extends State { List? _tables; bool _clearing = false; bool _clearingTrack = false; + final EewLiveActivity _eewLiveActivity = const EewLiveActivity(); + EewLiveActivityStatus? _eewStatus; + bool _eewBusy = false; + String? _eewError; + + bool get _canStartEewMock => + !_eewBusy && _eewStatus?.enabled == true && _eewStatus?.active != true; + + bool get _canEndEewMock => !_eewBusy && _eewStatus?.active == true; + + bool get _canUpdateEewMock => + _canEndEewMock && + _eewStatus?.generic != true && + _eewStatus?.waveArrived != true; + + bool get _canAlertEewMock => _canUpdateEewMock && _eewStatus?.enabled == true; + + bool get _canScheduleEewAlert => + _canAlertEewMock && _eewStatus?.delayedAlertStatus != 'Scheduled'; /// Version-row taps toward the experimental unlock. Deliberately not /// persisted — a fresh app start re-arms the easter egg. @@ -85,6 +105,70 @@ class _DeveloperPageState extends State { void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) => _load()); + if (kDebugMode) { + WidgetsBinding.instance.addPostFrameCallback((_) => _refreshEewStatus()); + } + } + + Future _refreshEewStatus() async { + try { + final status = await _eewLiveActivity.getStatus(); + if (!mounted) return; + setState(() { + _eewStatus = status; + _eewError = null; + }); + } on PlatformException catch (error) { + if (!mounted) return; + setState(() => _eewError = error.message ?? error.code); + } catch (error, stackTrace) { + _handleUnexpectedEewError(error, stackTrace, 'refresh status'); + } + } + + Future _runEewMock( + Future Function() action, + ) async { + if (_eewBusy) return; + setState(() { + _eewBusy = true; + _eewError = null; + }); + try { + final status = await action(); + if (!mounted) return; + setState(() => _eewStatus = status); + } on PlatformException catch (error) { + if (!mounted) return; + setState(() => _eewError = error.message ?? error.code); + } catch (error, stackTrace) { + _handleUnexpectedEewError(error, stackTrace, 'mock action'); + } finally { + if (mounted) setState(() => _eewBusy = false); + } + } + + void _handleUnexpectedEewError( + Object error, + StackTrace stackTrace, + String operation, + ) { + Log.handle(error, stackTrace, 'dev: EEW $operation'); + if (mounted) { + setState(() => _eewError = 'Unexpected EEW $operation failure: $error'); + } + // Keep programming errors visible to Flutter's error handlers as well as + // the diagnostic log, while allowing the controls to recover for a retry. + if (error is Error) { + FlutterError.reportError( + FlutterErrorDetails( + exception: error, + stack: stackTrace, + library: 'DPIP developer EEW controls', + context: ErrorDescription('while running EEW $operation'), + ), + ); + } } /// Empties the cache **and** the accounting that describes it. @@ -305,6 +389,105 @@ class _DeveloperPageState extends State { : ListView( padding: const EdgeInsets.only(bottom: AppSpacing.xl), children: [ + if (kDebugMode) ...[ + // l10n-ignore: developer-only mock controls, deliberately untranslated + const SectionHeader('EEW Live Activity · TEST / 測試'), + Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.md, + ), + child: Text( + _eewError ?? + (_eewStatus == null + ? 'Checking Live Activity support…' + : !_eewStatus!.supported + ? 'Unavailable (requires iOS 16.1+)' + : !_eewStatus!.enabled + ? 'Disabled in iOS settings' + : _eewStatus!.active + ? 'Mock active · report ${_eewStatus!.reportNo}' + '${_eewStatus!.waveArrived ? ' · wave arrived' : ''}' + : 'Ready for a local mock'), + ), + ), + Wrap( + spacing: AppSpacing.sm, + runSpacing: AppSpacing.xs, + children: [ + OutlinedButton( + onPressed: !_canStartEewMock + ? null + : () => _runEewMock(_eewLiveActivity.mockStart), + child: const Text('Start Mock EEW'), + ), + OutlinedButton( + onPressed: !_canStartEewMock + ? null + : () => _runEewMock( + _eewLiveActivity.mockStartGeneric, + ), + child: const Text('Start Generic Mock EEW'), + ), + OutlinedButton( + onPressed: !_canUpdateEewMock + ? null + : () => _runEewMock( + () => _eewLiveActivity.mockUpdate(2), + ), + child: const Text('Update → Report 2'), + ), + OutlinedButton( + onPressed: !_canUpdateEewMock + ? null + : () => _runEewMock( + () => _eewLiveActivity.mockUpdate(4), + ), + child: const Text('Update → Report 4'), + ), + OutlinedButton( + onPressed: !_canUpdateEewMock + ? null + : () => + _runEewMock(_eewLiveActivity.mockWaveArrived), + child: const Text('Mark Wave Arrived'), + ), + OutlinedButton( + onPressed: !_canAlertEewMock + ? null + : () => _runEewMock( + _eewLiveActivity.mockWaveArrivedWithAlert, + ), + child: const Text('Mark Wave Arrived + Alert'), + ), + OutlinedButton( + onPressed: !_canScheduleEewAlert + ? null + : () => _runEewMock( + _eewLiveActivity + .mockScheduleDelayedArrivalAlert, + ), + child: const Text('Test Delayed Arrival Alert (8s)'), + ), + OutlinedButton( + onPressed: !_canEndEewMock + ? null + : () => _runEewMock(_eewLiveActivity.mockEnd), + child: const Text('End Activity'), + ), + TextButton( + onPressed: _eewBusy ? null : _refreshEewStatus, + child: const Text('Refresh status'), + ), + ], + ), + if (_eewStatus?.delayedAlertStatus case final status?) + Padding( + padding: const EdgeInsets.symmetric( + horizontal: AppSpacing.md, + ), + child: Text('Delayed alert QA: $status'), + ), + ], for (var i = 0; i < sections.length; i++) ...[ SectionHeader(sections[i].title), for (final field in sections[i].fields) diff --git a/test/core/platform/eew_live_activity_test.dart b/test/core/platform/eew_live_activity_test.dart new file mode 100644 index 000000000..8e7c5c22f --- /dev/null +++ b/test/core/platform/eew_live_activity_test.dart @@ -0,0 +1,159 @@ +import 'package:dpip/core/platform/eew_live_activity.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + const channel = MethodChannel('test/eew_live_activity'); + const bridge = EewLiveActivity(channel: channel); + final messenger = + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + + tearDown(() => messenger.setMockMethodCallHandler(channel, null)); + + final operations = Function()>{ + 'getStatus': bridge.getStatus, + 'mockStart': bridge.mockStart, + 'mockStartGeneric': bridge.mockStartGeneric, + 'mockUpdate': () => bridge.mockUpdate(4), + 'mockWaveArrived': bridge.mockWaveArrived, + 'mockWaveArrivedWithAlert': bridge.mockWaveArrivedWithAlert, + 'mockScheduleDelayedArrivalAlert': bridge.mockScheduleDelayedArrivalAlert, + 'mockEnd': bridge.mockEnd, + }; + + for (final operation in operations.entries) { + group(operation.key, () { + test( + 'sends the native method and payload and parses the response', + () async { + final calls = []; + messenger.setMockMethodCallHandler(channel, (call) async { + calls.add(call); + return { + 'supported': true, + 'enabled': true, + 'active': true, + 'reportNo': 4, + 'waveArrived': true, + 'generic': true, + 'delayedAlertStatus': 'Triggered', + }; + }); + + final status = await operation.value(); + expect(calls, hasLength(1)); + expect(calls.single.method, operation.key); + expect( + calls.single.arguments, + operation.key == 'mockUpdate' ? {'reportNo': 4} : null, + ); + expect(status.supported, isTrue); + expect(status.enabled, isTrue); + expect(status.active, isTrue); + expect(status.reportNo, 4); + expect(status.waveArrived, isTrue); + expect(status.generic, isTrue); + expect(status.delayedAlertStatus, 'Triggered'); + }, + ); + + test('missing plugin returns an unsupported status', () async { + messenger.setMockMethodCallHandler(channel, (_) async { + throw MissingPluginException(); + }); + final status = await operation.value(); + expect(status.supported, isFalse); + expect(status.enabled, isFalse); + expect(status.active, isFalse); + expect(status.reportNo, isNull); + expect(status.waveArrived, isFalse); + expect(status.generic, isFalse); + expect(status.delayedAlertStatus, isNull); + }); + + test('propagates native errors with their details', () async { + messenger.setMockMethodCallHandler(channel, (_) async { + throw PlatformException( + code: 'activity_error', + message: 'Live Activities are disabled', + details: {'reason': 'disabled'}, + ); + }); + await expectLater( + operation.value(), + throwsA( + isA() + .having((e) => e.code, 'code', 'activity_error') + .having( + (e) => e.message, + 'message', + 'Live Activities are disabled', + ) + .having((e) => e.details, 'details', {'reason': 'disabled'}), + ), + ); + }); + + test('rejects a null status', () async { + messenger.setMockMethodCallHandler(channel, (_) async => null); + await expectLater( + operation.value(), + throwsA( + isA().having( + (e) => e.message, + 'message', + 'Missing EEW Live Activity status', + ), + ), + ); + }); + }); + } + + test('missing optional fields and false flags use safe defaults', () async { + messenger.setMockMethodCallHandler( + channel, + (_) async => {'supported': true}, + ); + final status = await bridge.getStatus(); + expect(status.supported, isTrue); + expect(status.enabled, isFalse); + expect(status.active, isFalse); + expect(status.reportNo, isNull); + expect(status.waveArrived, isFalse); + expect(status.generic, isFalse); + expect(status.delayedAlertStatus, isNull); + }); + + test('only literal true enables boolean flags', () async { + messenger.setMockMethodCallHandler( + channel, + (_) async => { + 'supported': 'true', + 'enabled': 1, + 'active': false, + 'waveArrived': 'true', + 'generic': 1, + }, + ); + final status = await bridge.getStatus(); + expect(status.supported, isFalse); + expect(status.enabled, isFalse); + expect(status.active, isFalse); + expect(status.waveArrived, isFalse); + expect(status.generic, isFalse); + }); + + for (final response in [ + {'reportNo': '4'}, + {'reportNo': 4.5}, + {'delayedAlertStatus': 8}, + ['not a status map'], + ]) { + test('rejects malformed status $response', () async { + messenger.setMockMethodCallHandler(channel, (_) async => response); + await expectLater(bridge.getStatus(), throwsA(isA())); + }); + } +} diff --git a/test/features/settings/presentation/pages/developer_page_test.dart b/test/features/settings/presentation/pages/developer_page_test.dart index 52e59e265..bf9e0dae5 100644 --- a/test/features/settings/presentation/pages/developer_page_test.dart +++ b/test/features/settings/presentation/pages/developer_page_test.dart @@ -3,8 +3,10 @@ /// hide the experimental menu or wipe the cache by accident. library; +import 'dart:async'; import 'dart:io'; +import 'package:dpip/core/logging/log.dart'; import 'package:dpip/core/network/etag_cache_store.dart'; import 'package:dpip/core/network/network_usage_store.dart'; import 'package:dpip/core/notifications/notification_service.dart'; @@ -33,6 +35,95 @@ const _device = MethodChannel('com.exptech.dpip/device_info'); const _package = MethodChannel('dev.fluttercommunity.plus/package_info'); const _storage = MethodChannel('com.exptech.dpip/storage_scan'); const _maplibre = MethodChannel('plugins.flutter.io/maplibre_gl'); +const _eew = MethodChannel('com.exptech.dpip/eew_live_activity'); + +const _start = 'Start Mock EEW'; +const _generic = 'Start Generic Mock EEW'; +const _update2 = 'Update → Report 2'; +const _update4 = 'Update → Report 4'; +const _arrived = 'Mark Wave Arrived'; +const _alert = 'Mark Wave Arrived + Alert'; +const _delayed = 'Test Delayed Arrival Alert (8s)'; +const _end = 'End Activity'; +const _refresh = 'Refresh status'; +const _eewButtons = [ + _start, + _generic, + _update2, + _update4, + _arrived, + _alert, + _delayed, + _end, + _refresh, +]; + +Map _eewStatus({ + bool supported = true, + bool enabled = true, + bool active = false, + int? reportNo, + bool waveArrived = false, + bool generic = false, + String? delayedAlertStatus, +}) => { + 'supported': supported, + 'enabled': enabled, + 'active': active, + 'reportNo': reportNo, + 'waveArrived': waveArrived, + 'generic': generic, + 'delayedAlertStatus': delayedAlertStatus, +}; + +Finder _eewButton(String label) => find.ancestor( + of: find.text(label), + matching: find.byWidgetPredicate((widget) => widget is ButtonStyleButton), +); + +void _expectEewButtons(WidgetTester tester, Set enabled) { + for (final label in _eewButtons) { + expect( + tester.widget(_eewButton(label)).onPressed != null, + enabled.contains(label), + reason: label, + ); + } +} + +Future _pumpEewPage(WidgetTester tester) async { + tester.view.physicalSize = _tall; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final store = SettingsStore.inMemory(); + await tester.pumpWidget( + MultiProvider( + providers: [ + Provider(create: (_) => NotificationService(store)), + Provider.value(value: const AppDatabase(durable: null, cache: null)), + Provider( + create: (_) => BackgroundLocationService( + platform: 0, + version: '1', + channel: _bg, + ), + ), + Provider.value(value: null), + Provider.value(value: null), + Provider.value(value: null), + ChangeNotifierProvider.value(value: ExperimentalSettings(store)), + ], + child: MaterialApp( + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const DeveloperPage(), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.text('Developer'), findsOneWidget); + expect(find.text('Maintenance'), findsOneWidget); +} class _FakePaths extends PathProviderPlatform { @override @@ -105,6 +196,656 @@ void main() { messenger.setMockMethodCallHandler(_package, null); messenger.setMockMethodCallHandler(_storage, null); messenger.setMockMethodCallHandler(_maplibre, null); + messenger.setMockMethodCallHandler(_eew, null); + }); + + group('debug EEW controls', () { + testWidgets('shows loading until initial status completes', (tester) async { + final pending = Completer>(); + final methods = []; + messenger.setMockMethodCallHandler(_eew, (call) { + methods.add(call.method); + return pending.future; + }); + await _pumpEewPage(tester); + expect(find.text('Checking Live Activity support…'), findsOneWidget); + expect(methods, ['getStatus']); + _expectEewButtons(tester, {_refresh}); + pending.complete(_eewStatus()); + await tester.pumpAndSettle(); + expect(find.text('Ready for a local mock'), findsOneWidget); + _expectEewButtons(tester, {_start, _generic, _refresh}); + }); + + final states = [ + ( + name: 'unsupported', + status: _eewStatus(supported: false, enabled: false), + text: 'Unavailable (requires iOS 16.1+)', + enabled: {_refresh}, + ), + ( + name: 'disabled', + status: _eewStatus(enabled: false), + text: 'Disabled in iOS settings', + enabled: {_refresh}, + ), + ( + name: 'ready', + status: _eewStatus(), + text: 'Ready for a local mock', + enabled: {_start, _generic, _refresh}, + ), + ( + name: 'active', + status: _eewStatus(active: true, reportNo: 1), + text: 'Mock active · report 1', + enabled: { + _update2, + _update4, + _arrived, + _alert, + _delayed, + _end, + _refresh, + }, + ), + ( + name: 'generic', + status: _eewStatus(active: true, reportNo: 1, generic: true), + text: 'Mock active · report 1', + enabled: {_end, _refresh}, + ), + ( + name: 'wave arrived', + status: _eewStatus(active: true, reportNo: 4, waveArrived: true), + text: 'Mock active · report 4 · wave arrived', + enabled: {_end, _refresh}, + ), + ( + name: 'delayed alert scheduled', + status: _eewStatus( + active: true, + reportNo: 1, + delayedAlertStatus: 'Scheduled', + ), + text: 'Mock active · report 1', + enabled: {_update2, _update4, _arrived, _alert, _end, _refresh}, + ), + ( + name: 'unsupported but enabled retains start eligibility', + status: _eewStatus(supported: false), + text: 'Unavailable (requires iOS 16.1+)', + enabled: {_start, _generic, _refresh}, + ), + ( + name: 'scheduled alert after settings disabled', + status: _eewStatus( + enabled: false, + active: true, + reportNo: 1, + delayedAlertStatus: 'Scheduled', + ), + text: 'Disabled in iOS settings', + enabled: {_update2, _update4, _arrived, _end, _refresh}, + ), + ( + name: 'expired alert can be scheduled again', + status: _eewStatus( + active: true, + reportNo: 1, + delayedAlertStatus: 'Expired / Unable to execute', + ), + text: 'Mock active · report 1', + enabled: { + _update2, + _update4, + _arrived, + _alert, + _delayed, + _end, + _refresh, + }, + ), + ( + name: 'active but disabled in settings', + status: _eewStatus(enabled: false, active: true, reportNo: 1), + text: 'Disabled in iOS settings', + enabled: {_update2, _update4, _arrived, _end, _refresh}, + ), + ]; + for (final state in states) { + testWidgets('${state.name} enables only eligible controls', ( + tester, + ) async { + final methods = []; + messenger.setMockMethodCallHandler(_eew, (call) async { + methods.add(call.method); + return state.status; + }); + await _pumpEewPage(tester); + expect(find.text(state.text), findsOneWidget); + _expectEewButtons(tester, state.enabled); + for (final label in _eewButtons.where( + (b) => !state.enabled.contains(b), + )) { + await tester.tap(_eewButton(label)); + } + await tester.pump(); + expect(methods, ['getStatus']); + }); + } + + testWidgets('missing plugin keeps the diagnostic page usable', ( + tester, + ) async { + messenger.setMockMethodCallHandler(_eew, (_) async { + throw MissingPluginException(); + }); + await _pumpEewPage(tester); + expect(find.text('Unavailable (requires iOS 16.1+)'), findsOneWidget); + _expectEewButtons(tester, {_refresh}); + expect(find.byTooltip('Copy all'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('starts, updates both reports, marks arrival, and ends', ( + tester, + ) async { + final methods = []; + var status = _eewStatus(); + messenger.setMockMethodCallHandler(_eew, (call) async { + methods.add(call); + status = switch (call.method) { + 'mockStart' => _eewStatus(active: true, reportNo: 1), + 'mockUpdate' => _eewStatus( + active: true, + reportNo: (call.arguments as Map)['reportNo'] as int, + ), + 'mockWaveArrived' => _eewStatus( + active: true, + reportNo: 4, + waveArrived: true, + ), + 'mockEnd' => _eewStatus(), + _ => status, + }; + return status; + }); + await _pumpEewPage(tester); + for (final (label, text) in [ + (_start, 'Mock active · report 1'), + (_update2, 'Mock active · report 2'), + (_update4, 'Mock active · report 4'), + (_arrived, 'Mock active · report 4 · wave arrived'), + (_end, 'Ready for a local mock'), + ]) { + await tester.tap(_eewButton(label)); + await tester.pumpAndSettle(); + expect(find.text(text), findsOneWidget); + } + expect(methods.map((c) => c.method), [ + 'getStatus', + 'mockStart', + 'mockUpdate', + 'mockUpdate', + 'mockWaveArrived', + 'mockEnd', + ]); + expect(methods[2].arguments, {'reportNo': 2}); + expect(methods[3].arguments, {'reportNo': 4}); + _expectEewButtons(tester, {_start, _generic, _refresh}); + }); + + testWidgets('generic start disables report and arrival controls', ( + tester, + ) async { + final methods = []; + messenger.setMockMethodCallHandler(_eew, (call) async { + methods.add(call.method); + return call.method == 'mockStartGeneric' + ? _eewStatus(active: true, reportNo: 1, generic: true) + : _eewStatus(); + }); + await _pumpEewPage(tester); + await tester.tap(_eewButton(_generic)); + await tester.pumpAndSettle(); + expect(find.text('Mock active · report 1'), findsOneWidget); + _expectEewButtons(tester, {_end, _refresh}); + await tester.tap(_eewButton(_end)); + await tester.pumpAndSettle(); + expect(methods, ['getStatus', 'mockStartGeneric', 'mockEnd']); + expect(find.text('Ready for a local mock'), findsOneWidget); + }); + + testWidgets('arrival with alert displays explicit arrival', (tester) async { + final methods = []; + messenger.setMockMethodCallHandler(_eew, (call) async { + methods.add(call.method); + return _eewStatus( + active: true, + reportNo: 2, + waveArrived: call.method == 'mockWaveArrivedWithAlert', + ); + }); + await _pumpEewPage(tester); + await tester.tap(_eewButton(_alert)); + await tester.pumpAndSettle(); + expect(methods, ['getStatus', 'mockWaveArrivedWithAlert']); + expect( + find.text('Mock active · report 2 · wave arrived'), + findsOneWidget, + ); + _expectEewButtons(tester, {_end, _refresh}); + }); + + testWidgets('delayed alert remains pending until refreshed native result', ( + tester, + ) async { + final methods = []; + var phase = 'Idle'; + messenger.setMockMethodCallHandler(_eew, (call) async { + methods.add(call.method); + if (call.method == 'mockScheduleDelayedArrivalAlert') { + phase = 'Scheduled'; + } + return _eewStatus( + active: true, + reportNo: 1, + waveArrived: phase == 'Triggered', + delayedAlertStatus: phase, + ); + }); + await _pumpEewPage(tester); + await tester.tap(_eewButton(_delayed)); + await tester.pumpAndSettle(); + expect(find.text('Delayed alert QA: Scheduled'), findsOneWidget); + expect(find.text('Mock active · report 1'), findsOneWidget); + _expectEewButtons(tester, { + _update2, + _update4, + _arrived, + _alert, + _end, + _refresh, + }); + phase = 'Triggered'; + await tester.tap(_eewButton(_refresh)); + await tester.pumpAndSettle(); + expect(find.text('Delayed alert QA: Triggered'), findsOneWidget); + expect( + find.text('Mock active · report 1 · wave arrived'), + findsOneWidget, + ); + _expectEewButtons(tester, {_end, _refresh}); + expect(methods, [ + 'getStatus', + 'mockScheduleDelayedArrivalAlert', + 'getStatus', + ]); + }); + + for (final message in ['Unable to read status', null]) { + testWidgets( + 'status error ${message ?? 'code'} is displayed and refresh recovers', + (tester) async { + var fail = true; + messenger.setMockMethodCallHandler(_eew, (_) async { + if (fail) { + throw PlatformException(code: 'status_error', message: message); + } + return _eewStatus(); + }); + await _pumpEewPage(tester); + expect(find.text(message ?? 'status_error'), findsOneWidget); + _expectEewButtons(tester, {_refresh}); + fail = false; + await tester.tap(_eewButton(_refresh)); + await tester.pumpAndSettle(); + expect(find.text('Ready for a local mock'), findsOneWidget); + expect(find.text(message ?? 'status_error'), findsNothing); + _expectEewButtons(tester, {_start, _generic, _refresh}); + expect(tester.takeException(), isNull); + }, + ); + } + + testWidgets('failed refresh retains the active state and recovers', ( + tester, + ) async { + var fail = false; + var status = _eewStatus(active: true, reportNo: 2); + messenger.setMockMethodCallHandler(_eew, (_) async { + if (fail) throw PlatformException(code: 'refresh_failed'); + return status; + }); + await _pumpEewPage(tester); + fail = true; + await tester.tap(_eewButton(_refresh)); + await tester.pumpAndSettle(); + expect(find.text('refresh_failed'), findsOneWidget); + _expectEewButtons(tester, { + _update2, + _update4, + _arrived, + _alert, + _delayed, + _end, + _refresh, + }); + fail = false; + status = _eewStatus(); + await tester.tap(_eewButton(_refresh)); + await tester.pumpAndSettle(); + expect(find.text('refresh_failed'), findsNothing); + expect(find.text('Ready for a local mock'), findsOneWidget); + _expectEewButtons(tester, {_start, _generic, _refresh}); + expect(tester.takeException(), isNull); + }); + + final actions = { + _start: 'mockStart', + _generic: 'mockStartGeneric', + _update2: 'mockUpdate', + _update4: 'mockUpdate', + _arrived: 'mockWaveArrived', + _alert: 'mockWaveArrivedWithAlert', + _delayed: 'mockScheduleDelayedArrivalAlert', + _end: 'mockEnd', + }; + for (final action in actions.entries) { + testWidgets('${action.key} error preserves status and permits retry', ( + tester, + ) async { + final methods = []; + var fail = true; + final isStart = action.key == _start || action.key == _generic; + final status = isStart + ? _eewStatus() + : _eewStatus(active: true, reportNo: 1); + messenger.setMockMethodCallHandler(_eew, (call) async { + methods.add(call.method); + if (call.method != 'getStatus' && fail) { + throw PlatformException( + code: 'activity_error', + message: isStart ? null : 'Native action failed', + ); + } + return status; + }); + await _pumpEewPage(tester); + await tester.tap(_eewButton(action.key)); + await tester.pumpAndSettle(); + expect( + find.text(isStart ? 'activity_error' : 'Native action failed'), + findsOneWidget, + ); + expect(find.text('Maintenance'), findsOneWidget); + _expectEewButtons( + tester, + isStart + ? {_start, _generic, _refresh} + : { + _update2, + _update4, + _arrived, + _alert, + _delayed, + _end, + _refresh, + }, + ); + fail = false; + await tester.tap(_eewButton(action.key)); + await tester.pumpAndSettle(); + expect(methods, ['getStatus', action.value, action.value]); + expect( + find.text( + isStart ? 'Ready for a local mock' : 'Mock active · report 1', + ), + findsOneWidget, + ); + expect(tester.takeException(), isNull); + }); + } + + // Use the binary handler: setMockMethodCallHandler wraps thrown objects in + // PlatformException, which would never exercise the unexpected-error path. + for (final programmingError in [false, true]) { + for (final action in actions.entries) { + testWidgets( + '${action.key} unexpected ${programmingError ? 'Error' : 'Exception'} recovers', + (tester) async { + final error = programmingError + ? StateError('broken mock') + : Exception('unexpected mock failure'); + final stack = StackTrace.fromString('EEW mock test stack'); + var fail = true; + final methods = []; + final isStart = action.key == _start || action.key == _generic; + final status = isStart + ? _eewStatus() + : _eewStatus(active: true, reportNo: 1); + messenger.setMockMessageHandler(_eew.name, (data) { + final call = _eew.codec.decodeMethodCall(data); + methods.add(call.method); + if (call.method != 'getStatus' && fail) { + Error.throwWithStackTrace(error, stack); + } + return Future.value( + _eew.codec.encodeSuccessEnvelope(status), + ); + }); + await _pumpEewPage(tester); + final before = Log.talker.history.length; + await tester.tap(_eewButton(action.key)); + await tester.pumpAndSettle(); + expect( + find.text('Unexpected EEW mock action failure: $error'), + findsOneWidget, + ); + final logged = Log.talker.history.skip(before).single; + expect(logged.message, 'dev: EEW mock action'); + expect(logged.stackTrace.toString(), stack.toString()); + expect( + tester.takeException(), + programmingError ? same(error) : isNull, + ); + _expectEewButtons( + tester, + isStart + ? {_start, _generic, _refresh} + : { + _update2, + _update4, + _arrived, + _alert, + _delayed, + _end, + _refresh, + }, + ); + fail = false; + await tester.tap(_eewButton(action.key)); + await tester.pumpAndSettle(); + expect(methods, ['getStatus', action.value, action.value]); + expect(find.textContaining('Unexpected EEW'), findsNothing); + expect( + find.text( + isStart ? 'Ready for a local mock' : 'Mock active · report 1', + ), + findsOneWidget, + ); + expect(tester.takeException(), isNull); + }, + ); + } + + for (final initial in [false, true]) { + testWidgets( + '${initial ? 'initial status' : 'refresh'} unexpected ${programmingError ? 'Error' : 'Exception'} recovers', + (tester) async { + final error = programmingError + ? StateError('broken status') + : Exception('unexpected status failure'); + final stack = StackTrace.fromString('EEW status test stack'); + var fail = initial; + messenger.setMockMessageHandler(_eew.name, (_) { + if (fail) Error.throwWithStackTrace(error, stack); + return Future.value( + _eew.codec.encodeSuccessEnvelope( + _eewStatus(active: true, reportNo: 2), + ), + ); + }); + final before = Log.talker.history.length; + await _pumpEewPage(tester); + if (!initial) { + fail = true; + await tester.tap(_eewButton(_refresh)); + await tester.pumpAndSettle(); + } + expect( + find.text('Unexpected EEW refresh status failure: $error'), + findsOneWidget, + ); + final logged = Log.talker.history + .skip(before) + .where((entry) => entry.message == 'dev: EEW refresh status') + .single; + expect(logged.stackTrace.toString(), stack.toString()); + expect( + tester.takeException(), + programmingError ? same(error) : isNull, + ); + _expectEewButtons( + tester, + initial + ? {_refresh} + : { + _update2, + _update4, + _arrived, + _alert, + _delayed, + _end, + _refresh, + }, + ); + fail = false; + await tester.tap(_eewButton(_refresh)); + await tester.pumpAndSettle(); + expect(find.textContaining('Unexpected EEW'), findsNothing); + expect(find.text('Mock active · report 2'), findsOneWidget); + expect(tester.takeException(), isNull); + }, + ); + } + } + + for (final operation in ['getStatus', 'mockStart']) { + testWidgets('$operation unexpected exception after disposal is logged', ( + tester, + ) async { + final pending = Completer(); + messenger.setMockMessageHandler(_eew.name, (data) { + final call = _eew.codec.decodeMethodCall(data); + return call.method == operation + ? pending.future + : Future.value(_eew.codec.encodeSuccessEnvelope(_eewStatus())); + }); + await _pumpEewPage(tester); + if (operation == 'mockStart') { + await tester.tap(_eewButton(_start)); + await tester.pump(); + } + await tester.pumpWidget(const SizedBox()); + final before = Log.talker.history.length; + final stack = StackTrace.fromString('disposed EEW test stack'); + pending.completeError(Exception('disposed failure'), stack); + await tester.pumpAndSettle(); + expect( + Log.talker.history.skip(before).single.stackTrace.toString(), + stack.toString(), + ); + expect(tester.takeException(), isNull); + }); + } + + testWidgets('busy operation rejects repeat taps before and after rebuild', ( + tester, + ) async { + final pending = Completer>(); + final methods = []; + messenger.setMockMethodCallHandler(_eew, (call) { + methods.add(call.method); + return call.method == 'getStatus' + ? Future.value(_eewStatus()) + : pending.future; + }); + await _pumpEewPage(tester); + await tester.tap(_eewButton(_start)); + // No frame between taps: the old enabled button must still be guarded. + await tester.tap(_eewButton(_start)); + await tester.tap(_eewButton(_generic)); + await tester.pump(); + expect(methods, ['getStatus', 'mockStart']); + _expectEewButtons(tester, {}); + for (final label in _eewButtons) { + await tester.tap(_eewButton(label)); + } + await tester.pump(); + expect(methods, ['getStatus', 'mockStart']); + pending.complete(_eewStatus(active: true, reportNo: 1)); + await tester.pumpAndSettle(); + expect(find.text('Mock active · report 1'), findsOneWidget); + _expectEewButtons(tester, { + _update2, + _update4, + _arrived, + _alert, + _delayed, + _end, + _refresh, + }); + }); + + for (final operation in ['getStatus', 'mockStart']) { + for (final fail in [false, true]) { + testWidgets( + '$operation ${fail ? 'failure' : 'success'} after disposal is safe', + (tester) async { + final pending = Completer>(); + final methods = []; + messenger.setMockMethodCallHandler(_eew, (call) { + methods.add(call.method); + return call.method == operation + ? pending.future + : Future.value(_eewStatus()); + }); + await _pumpEewPage(tester); + if (operation == 'mockStart') { + await tester.tap(_eewButton(_start)); + await tester.pump(); + } + expect( + methods, + operation == 'getStatus' + ? ['getStatus'] + : ['getStatus', 'mockStart'], + ); + await tester.pumpWidget(const SizedBox()); + if (fail) { + pending.completeError(PlatformException(code: 'disposed')); + } else { + pending.complete(_eewStatus(active: true, reportNo: 1)); + } + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + }, + ); + } + } }); testWidgets('loads rows, unlocks on the tenth version tap, and confirms', (