importCottonKitimportSwiftUI#if canImport(UIKit)import UIKit#elseif canImport(AppKit)importAppKitimportScreenCaptureKit#endif// MARK: - Shake to report (lane J4; to Cotton since 13 Nov 2026)//// A shake on the screen that looks wrong opens a sheet with one sentence in// it, and the app sends the sentence with what an agent needs to act on it:// a PNG of the screen as it was at the shake, the phone, the OS, the route// and the last two hundred lines of the log. Everything goes through// `feedback.send` in Rust, which keeps the report in its outbox and posts it// to Cotton's own database (`cotton-product`'s `app_report`), never the// reporter's Personal; the core stamps the app, the build and the platform.// This app has no HTTP client and never will (`SourceGuardTests`).//// Three pieces, in order of appearance: the SHAKE (a `UIWindow` override that// posts a notification, because SwiftUI has no motion event), the STAGING// (`RootView` takes the picture BEFORE the sheet is up, or the sheet would be// in it), and the MODEL, which holds a `ScreenWriter` and never the core// (`ScaffoldSweepTests`), gathers the facts, sends, and deletes the PNG.//// THE MAC HAS THE SAME REPORT AND A DIFFERENT GESTURE. A Mac has no motion// event; its way in is the Help menu's *Report a problem…* row// (`CottonHost/MainMenu.swift`), which posts the SAME notification, so the// staging, the picture, the sheet and the verb are one code path for both// destinations (H2: `CottonUI` compiles for both). The picture is the main// window's pixels as the window server has them, at the display's scale; the// report says `platform = "macos"` because the core stamps the platform it was// compiled for (`cotton-ffi/src/phone/feedback_send.rs`), never the caller.extensionNotification.Name {/// The report gesture: posted by `UIWindow.motionEnded` on a shake, and by/// the Mac's Help › Report a problem… row. `RootView` listens.publicstaticlet cottonShake = Notification.Name("com.cottondb.shake")}#if os(iOS)extension UIWindow {/// The one place the OS delivers a shake: the first responder chain ends/// at the window, and a SwiftUI app owns no view controller to hear it on.openoverridefunc motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?) {super.motionEnded(motion, with: event)if motion == .motionShake {NotificationCenter.default.post(name: .cottonShake, object: nil) } }}#endif/// The screen as a picture on disk, taken at the shake: a PNG when it fits/// under the core's ceiling, else a JPEG.publicenumScreenSnapshot {/// The core's ceiling for a report's picture (`feedback_send.rs`/// `SCREENSHOT_MAX`, the Worker's cap): a picture over it is refused, so/// it is never written. A full-resolution iPhone PNG of a photographic/// ground is about 6 MB (Books, walked 13 Nov 2026).publicstaticlet ceiling = 4 * 1024 * 1024/// The bytes to write and their extension: the lossless PNG when it fits/// under `ceiling`, else a JPEG of the same pixels, lowered in quality/// until it fits. `nil` when nothing fits.staticfunc encoded(png: Data?, jpeg: (Double) -> Data?) -> (bytes: Data, ext: String)? {iflet png, png.count <= ceiling { return (png, "png") }for quality in [0.85, 0.6, 0.4] {iflet bytes = jpeg(quality), bytes.count <= ceiling { return (bytes, "jpg") } }returnnil }/// What was written: where, and how big in pixels.publicstructTaken: Sendable, Equatable {publiclet path: Stringpubliclet image: FeedbackImageSize/// How the picture was taken when it is NOT the screen as the person saw/// it — a line that rides in the report's log so the reader knows why the/// page may be missing. `nil` for a picture of the window as composited.publiclet fallback: String?publicinit(path: String, image: FeedbackImageSize, fallback: String? = nil) {self.path = pathself.image = imageself.fallback = fallback } }/// Draw the key window into a picture in the temp directory. `drawHierarchy`/// rather than `ImageRenderer`: the latter renders a SwiftUI value/// offscreen, and what the person is looking at is the window — every/// screen, the toast, the keyboard's inset — not a value.////// On the Mac the window is asked of the WINDOW SERVER (ScreenCaptureKit,/// over this process's own shareable content, on this one window), for/// the same reason: the pixels as they are on screen. Drawing the content view/// through `cacheDisplay` was measured 2026-09-18 to give the sidebar and/// the toolbar and NONE of the page — the scrolled columns are layers the/// window server composites, not ones AppKit redraws for a bitmap./// `SCShareableContent.currentProcess` is the content a process may image/// WITHOUT Screen Recording — its own windows; that grant gates other apps'/// windows. (`CGWindowListCreateImage`, the old way, is unavailable from/// macOS 15.) A Mac where the window server still refuses (Screen/// Recording not granted — a Mac, 14 Oct 2026) falls back to AppKit's own/// window drawing (`cacheDisplay`) and the picture carries a `fallback`/// line saying so, which the report sends in its log: never a silent/// partial or empty capture. A window that is not on screen, which is what/// a test hands in, is drawn the same way. @MainActorpublicstaticfunc take(directory: URL = FileManager.default.temporaryDirectory) async -> Taken? { #if os(macOS)returnawait take(window: frontWindow(), directory: directory) #elseif os(iOS)let window = UIApplication.shared.connectedScenes .compactMap { $0 as? UIWindowScene } .flatMap(\.windows) .first(where: \.isKeyWindow)guardlet window else { returnnil }let format = UIGraphicsImageRendererFormat() format.scale = window.screen.scalelet image = UIGraphicsImageRenderer(bounds: window.bounds, format: format).image { _ in window.drawHierarchy(in: window.bounds, afterScreenUpdates: false) }guardlet picture = encoded(png: image.pngData(), jpeg: { image.jpegData(compressionQuality: $0) }) else { returnnil }let url = directory.appendingPathComponent("shake-\(UUID().uuidString).\(picture.ext)")do {try picture.bytes.write(to: url, options: .atomic) } catch {Log.write("shake: the screen could not be written: \(error)")returnnil }returnTaken( path: url.path, image: FeedbackImageSize( width: Int(image.size.width * image.scale), height: Int(image.size.height * image.scale) ) ) #else _ = directoryreturnnil #endif } #if os(macOS)/// The window the person is looking at. The key window when the app is/// active; otherwise the largest ordinary window that is on screen —/// AppKit answers nil for both `keyWindow` and `mainWindow` while another/// app is frontmost, and a check with no hands launches this one from a/// shell, which never activates it. @MainActorstaticfunc frontWindow() -> NSWindow? {let app = NSApplication.sharediflet window = app.keyWindow ?? app.mainWindow { return window }return app.windows .filter { $0.isVisible && $0.level == .normal && $0.contentView != nil } .max { $0.frame.width * $0.frame.height < $1.frame.width * $1.frame.height } }/// The Mac's capture, with the window named so a test can hand it one/// that is not on screen. `nil` when there is no window or nothing to/// draw in it — the sheet then says the log alone goes. @MainActorpublicstaticfunc take(window: NSWindow?, directory: URL = FileManager.default.temporaryDirectory) async -> Taken? {guardlet window, let view = window.contentView else { returnnil }let bounds = view.boundsguard bounds.width > 0, bounds.height > 0else { returnnil }var bitmap: NSBitmapImageRep?var fallback: String?if window.isVisible, window.windowNumber > 0 {switchawait composite(CGWindowID(window.windowNumber)) {case .success(let composited) where composited.width > 1 && composited.height > 1: bitmap = NSBitmapImageRep(cgImage: composited)case .success: fallback = drawnLine("the window server's picture was empty")case .failure(let error): fallback = drawnLine("the window server refused: \(error.localizedDescription)") } }if bitmap == nil {guardlet drawn = view.bitmapImageRepForCachingDisplay(in: bounds) else { returnnil } view.cacheDisplay(in: bounds, to: drawn) bitmap = drawn }guardlet bitmap, let picture = encoded( png: bitmap.representation(using: .png, properties: [:]), jpeg: { bitmap.representation(using: .jpeg, properties: [.compressionFactor: $0]) } ) else { returnnil }iflet fallback { Log.write(fallback) }let url = directory.appendingPathComponent("shake-\(UUID().uuidString).\(picture.ext)")do {try picture.bytes.write(to: url, options: .atomic) } catch {Log.write("report: the window could not be written: \(error)")returnnil }returnTaken( path: url.path, image: FeedbackImageSize(width: bitmap.pixelsWide, height: bitmap.pixelsHigh), fallback: fallback ) }/// The line a drawn (not composited) picture carries into the report./// Screen Recording is named because it is the grant that lets the window/// server answer on a Mac that refuses own-process content without it.staticfunc drawnLine(_ why: String) -> String {let granted = CGPreflightScreenCaptureAccess() ? "granted" : "not granted"return"report: screen drawn by AppKit, not the window server (\(why); Screen Recording \(granted)) — scrolled page content may be missing" }/// One of this process's windows as the window server composites it, at/// full backing resolution and without its shadow; nil when the window/// server has no such window for us.privatestaticfunc composite(_ id: CGWindowID) async -> Result<CGImage, Error> {do {let content = tryawait SCShareableContent.currentProcessguardlet window = content.windows.first(where: { $0.windowID == id }) else {return .failure(CompositeMissing()) }let filter = SCContentFilter(desktopIndependentWindow: window)let configuration = SCStreamConfiguration() configuration.width = Int(filter.contentRect.width * CGFloat(filter.pointPixelScale)) configuration.height = Int(filter.contentRect.height * CGFloat(filter.pointPixelScale)) configuration.showsCursor = falsereturn .success(tryawait SCScreenshotManager.captureImage(contentFilter: filter, configuration: configuration)) } catch {return .failure(error) } }privatestructCompositeMissing: LocalizedError {var errorDescription: String? { "this window is not in the process's shareable content" } } #endif}/// What `RootView` captured at the shake, handed to the sheet whole.publicstructShakeStaged: Identifiable, Sendable, Equatable {publiclet id: UUIDpubliclet snapshot: ScreenSnapshot.Taken?publiclet route: Stringpublicinit(snapshot: ScreenSnapshot.Taken?, route: String) {self.id = UUID()self.snapshot = snapshotself.route = route }}/// The facts about this phone. Gathered at SEND, so the ring holds what/// happened up to the moment the person tapped. The build is the core's to/// stamp, never the shell's.publicstructShakeFacts: Sendable, Equatable {publicvar device: Stringpublicvar os: Stringpublicvar log: [String]/// How many of the ring's newest lines a report carries.publicstaticlet logLines = 200publicinit(device: String, os: String, log: [String]) {self.device = deviceself.os = osself.log = log }/// The live process: the same facts `Reporting.report` dresses with.publicstaticfunc live() -> ShakeFacts {let hardware = Hardware.current()returnShakeFacts( device: hardware.model, os: hardware.os, log: Array(Log.ring.rendered().suffix(logLines)) ) }}/// `feedback.flush`: every report kept on this phone tried again. Once after/// the core opens and each time the app comes to the front; nobody asked for/// it, so its answer is only logged.publicenumFeedbackOutbox {publicstaticfunc flush(core: any CottonCalling) async {do {let answer = tryawait core.callJSON(CottonMethod.feedbackFlush)Log.write("reports kept on this phone: sent \(answer.number("sent") ?? 0), kept \(answer.number("kept") ?? 0), refused \(answer.number("refused") ?? 0)") } catch {Log.write("reports kept on this phone could not be sent again: \(error)") } }}@MainActor@ObservablepublicfinalclassShakeReportModel {publicenumStage: Equatable {case writingcase sendingcase sent }publicprivate(set) var stage: Stage = .writingpublicvar note = ""publicprivate(set) var sent: FeedbackSent?publiclet staged: ShakeStaged/// The projects the sheet's caps draw — every one this device has, active/// and archived alike, exactly as the sheet's own rules/// (`offeredProjects`) then narrow them. `feedback.send` takes no project,/// so the pick files nothing: the caps stay drawn as they were (owner,/// 13 Nov 2026: no change to how the sheet looks).publicprivate(set) var projects: [ProjectsSheetOption] = []/// The one this report is about, or nothing. A REPORT MAY STAY UNFILED and/// most do: a sheet that demanded a project before it would take a/// sentence is a sheet nobody shakes twice.publicvar projectId: String?privatelet writer: ScreenWriterprivatelet toasts: ToastCenterprivatelet gather: @Sendable () -> ShakeFactsprivatelet remove: (String) -> Voidprivatelet preferences: any DevicePreferences/// The open host the flavour hands `personal.code`, where a signed-out/// report goes.privatelet server: String?/// What the report's microphone listens for — the same hints every other/// microphone reads, so a report naming a person or a project is heard/// with that name.let hints: @MainActor () async -> DictationHints/// Where the last project a report was filed under is remembered. DEVICE/// LOCAL: which project you were last reporting about is a habit of this/// phone's, not a fact about the person's database.staticlet lastProjectKey = "report.lastProject"publicinit( writer: ScreenWriter, toasts: ToastCenter, staged: ShakeStaged, gather: @escaping @Sendable () -> ShakeFacts = { ShakeFacts.live() }, remove: @escaping (String) -> Void = { path intry? FileManager.default.removeItem(atPath: path) }, preferences: any DevicePreferences = UserDefaultsPreferences(), server: String? = FlavourManifest.current?.business?.server, hints: @escaping @MainActor () async -> DictationHints = { DictationHints() } ) {self.server = serverself.hints = hintsself.writer = writerself.toasts = toastsself.staged = stagedself.gather = gatherself.remove = removeself.preferences = preferences }/// The roster, and the project the sheet opens ticked.////// Asked ONCE, and a failure leaves the run of caps empty — the sheet then/// says "No projects yet…" in the picker's own words and the sentence can/// still be sent, because an unfiled report is a real report.publicfunc loadProjects() async {guard projects.isEmpty else { return }guardlet answer = try? await writer.call(CottonMethod.readProjects) else { return } projects = answer.list("projects").compactMap { row inguardlet id = row.text("id") else { returnnil }returnProjectsSheetOption( id: id, name: row.text("name") ?? id, status: row.text("status") == "archived" ? .archived : .active, slug: row.text("slug") ) } projectId = ReportProject.preselected( route: staged.route, lastUsed: preferences.string(ShakeReportModel.lastProjectKey), projects: projects ) }publicvar canSend: Bool { stage == .writing && !note.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty }/// Send, and say what happened. `false` is a refusal already shown as a/// toast, with the sentence still in the field. @discardableResultpublicfunc send() async -> Bool {guard canSend else { returnfalse } stage = .sendinglet facts = gather()let request = FeedbackSendRequest( sentence: note.trimmingCharacters(in: .whitespacesAndNewlines), screenshotPath: staged.snapshot?.path, route: staged.route, device: facts.device, os: facts.os, log: facts.log + (staged.snapshot?.fallback.map { [$0] } ?? []), server: server )do {let answer = tryawait writer.call(CottonMethod.feedbackSend, request, as: FeedbackSent.self) sent = answer stage = .sent// The caps' habit: the project last picked opens ticked next time. preferences.setString(projectId, ShakeReportModel.lastProjectKey)// The core copied the picture into its outbox: the temp PNG goes. discardSnapshot()Log.write("report \(answer.state)\(answer.sender.map { "as \($0)" } ?? ""): \(answer.id)")// No toast: the sheet's own card says what became of it.returntrue } catchlet refusal asCottonCallError {// Refused in words: nothing was kept. The sentence and the picture// stay for another try. stage = .writing toasts.show(ShellLines.line("feedback", "reports.not_accepted_said", ["said": "\(refusal.message)"]), tone: .error)returnfalse } catch { stage = .writingReporting.report(Report(kind: .unreadableAnswer, message: "\(error)", context: ["method": CottonMethod.feedbackSend]) ) toasts.show(CottonStrings.somethingWentWrong, tone: .error)returnfalse } }/// The app look's Send (`LookReportSheet`): the same `send`, the same/// request, then what became of it said once, quietly, in the app's own/// toast as the sheet closes, where the paper sheet turns to its card. @discardableResultpublicfunc sendAndSay() async -> Bool {guardawait send() else { returnfalse } toasts.show(outcomeLine)returntrue }/// What the sent card says: Cotton has it, or it is kept on this phone.publicvar outcomeLine: String {ShellLines.line("feedback", sent?.kept == true ? "sent.kept" : "sent.to_cotton") }/// The person changed their mind: the picture goes, nothing is written.publicfunc cancel() { discardSnapshot() }privatefunc discardSnapshot() {iflet path = staged.snapshot?.path { remove(path) } }}/// The sheet, as a complaint slip: torn cream paper, the question in the serif,/// the sentence typed on ruled lines, what goes with it handwritten under it,/// and Send as the ink circle. When the screen was captured, it rides in the/// slip's corner as a small print — the person never saw the screenshot taken,/// so the slip shows what they are about to send.publicstructShakeReportSheet: View { @Bindable privatevar model: ShakeReportModelprivatelet onClose: () -> Void @Environment(\.theme) privatevar theme/// Dictation into the sentence, the SAME host every other writing surface/// uses (`Capture/BodyDictation.swift`) over the app's ONE recogniser — so/// an improvement to speech lands here too, without this file knowing how/// speech works. Built in `.task`, never in `init`: a real recogniser opens/// the audio stack the moment it exists, and a `View.init` runs on every/// evaluation of the view value (`CapabilityGateSweepTests`). @State privatevar speech: BodyDictation?/// The centre and the taps the host publishes again for this sheet/// (`RootView`'s `.sheet`) — a sheet inherits neither on its own. @Environment(\.cottonHaptics) privatevar haptics @Environment(ToastCenter.self) privatevar toastspublicinit(model: ShakeReportModel, onClose: @escaping () -> Void) {self.model = modelself.onClose = onClose }publicvar body: someView { VStack(alignment: .leading, spacing: 0) {if model.stage == .sent { thanks } else { writing }Spacer(minLength: 0) } .padding(20) .frame(maxWidth: .infinity, alignment: .leading) #if os(macOS)// A Mac sheet is sized by its content, and this one's content is a// paper that grows to fill: give it the slip's own size, or AppKit// opens a sheet the width of the field and the height of nothing. .frame(width: 520, height: 400) #endif .accessibilityIdentifier("report-sheet") .task {// Once, on arrival. `@State` survives every redraw, so a second// recogniser is never built for the same sheet.if speech == nil { speech = makeSpeech() }await model.loadProjects() } }/// The dictation host, with the two ends of the wire a `View.init` cannot/// reach. `VoiceTake` decides which ending becomes a sentence; a discard/// and a dictation that landed its words owe none.privatefunc makeSpeech() -> BodyDictation {let model = modellet toasts = toastsreturnBodyDictation( dictation: DictationModel.live(), haptics: haptics, body: { model.note }, setBody: { model.note = $0 }, onEnded: { outcome iniflet sentence = VoiceTake.dictationMessage(outcome) { toasts.show(sentence, tone: .error) } } ) }/// What the field shows and what a keystroke writes.////// `BodyDictation` splices at the last cursor the field REPORTED, and a/// bare SwiftUI `TextField` reports none — so the words land at the end of/// whatever is already there. For one sentence that is the right place, and/// the note editor's cursor tracking is not worth carrying here.privatevar noteField: Binding<String> {Binding( get: { speech?.displayBody ?? model.note }, set: { text in// Dictation owns the field while it is live: the sentence is// written on FINISH, and a partial echoed back would be typed// over the splice.guard speech?.isActive != trueelse { return } model.note = text } ) }/// The microphone, and the two endings it becomes while it is listening —/// the streaming sentence is its own feedback, so nothing else is drawn./// Both endings are inert while the session is finishing. @ViewBuilder privatevar dictationControls: someView {iflet speech {if speech.isActive {NavCircle(symbol: "xmark", label: CottonStrings.discardDictation) {guard !speech.isFinishing else { return } haptics.press() speech.cancel() } .accessibilityIdentifier("report-dictate-cancel")NavCircle(symbol: "checkmark", label: CottonStrings.finishDictation) {guard !speech.isFinishing else { return } haptics.press()Task { await speech.finish() } } .accessibilityIdentifier("report-dictate-finish") } elseif model.stage == .writing {NavCircle(symbol: "mic", label: CottonStrings.dictateHint) { haptics.press()Task { await speech.start(hints: await model.hints()) } } .accessibilityIdentifier("report-dictate") } } }/// The slip, being written on. @ViewBuilder privatevar writing: someView { HStack(alignment: .center) {Button { model.cancel() onClose() } label: {Text(CottonStrings.cancel) .paperHand(18) .frame(minHeight: 44) .contentShape(Rectangle()) } .buttonStyle(MotionButtonStyle()) .accessibilityIdentifier("report-cancel")Spacer() dictationControlsButton {Task { await model.send() } } label: {Image(systemName: model.stage == .sending ? "ellipsis" : "arrow.up") .font(.system(size: 18, weight: .semibold)) .foregroundStyle(PaperDye.cream.fill) .frame(width: 48, height: 48) .background(Circle().fill(theme.print(.ink))) } .buttonStyle(MotionButtonStyle()) .disabled(!model.canSend) .opacity(model.canSend ? 1 : DisabledOpacity.control) .accessibilityLabel(ShellLines.line("feedback", model.stage == .sending ? "report.sending" : "report.send")) .accessibilityIdentifier("report-send") }ScrollView {Paper(dye: .cream, edge: .torn, seed: "shake-report", tilt: false, inset: 20) { VStack(alignment: .leading, spacing: 0) { HStack(alignment: .top, spacing: 12) { VStack(alignment: .leading, spacing: 4) {Text(ShellLines.line("feedback", "report.kicker")).paperMeta(12)Text(ShellLines.line("feedback", "report.title")) .paperTitle(24) .accessibilityAddTraits(.isHeader) }Spacer(minLength: 0) snapshotPrint }TextField(ShellLines.line("feedback", "report.placeholder"), text: noteField, axis: .vertical)// Plain on both: the Mac's default draws a white box// over the ruled lines the slip is typed on. .textFieldStyle(.plain) .font(CottonFonts.type(15)) .foregroundStyle(theme.print(.ink)) .lineSpacing(ReplySheetKnobs.paperRuledTypedSpacing) .lineLimit(3...) .padding(.top, 14) .background(alignment: .top) {RuledLines().padding(.top, 8) } .accessibilityIdentifier("report-note")Text(ShellLines.line("feedback", model.staged.snapshot == nil ? "report.goes_with.log" : "report.goes_with.screen_and_log")) .paperHand(15) .fixedSize(horizontal: false, vertical: true) .padding(.top, 14) projectCaps } .frame(maxWidth: .infinity, alignment: .leading) } .padding(.top, 8) } .scrollBounceBehavior(.basedOnSize) }/// Which project this is about, as the board's own caps — preselected to/// the project you were looking at, else the one you last reported under,/// else none. ONE at a time: a report is about one project or about none. @ViewBuilder privatevar projectCaps: someView {if !model.projects.isEmpty {ProjectsSheetContent( projects: model.projects, links: model.projectId.map { [ProjectsSheetLink(projectId: $0)] } ?? [], caption: ShellLines.line("feedback", "report.project_caption"), onLink: { model.projectId = $0 }, onUnlink: { _ in model.projectId = nil } ) .padding(.top, 18) } }/// What became of it, in the core's answer: Cotton has it, or it is kept/// on this phone until there is a connection. @ViewBuilder privatevar thanks: someView {Paper(dye: .cream, edge: .torn, seed: "shake-report-sent", tilt: false, inset: 20) { VStack(alignment: .leading, spacing: 0) {Text(model.outcomeLine) .paperTitle(24) .fixedSize(horizontal: false, vertical: true) .accessibilityAddTraits(.isHeader) .accessibilityIdentifier("report-outcome")Button { onClose() } label: {Text(ShellLines.line("feedback", "sent.done")) .paperHand(18) .frame(minHeight: 44) .contentShape(Rectangle()) } .buttonStyle(MotionButtonStyle()) .padding(.top, 14) .accessibilityIdentifier("report-done") } .frame(maxWidth: .infinity, alignment: .leading) } }/// The captured screen, small, tucked into the slip's corner. @ViewBuilder privatevar snapshotPrint: someView {iflet path = model.staged.snapshot?.path {SnapshotPrint(path: path) } }}/// The captured screen as a thumb print. A full-window capture is megapixels/// drawn 46 points wide, so it is decoded at that edge off the main actor/// (`MediaImages.thumbnail`) rather than read whole; until it is decoded the/// corner stays empty. `UIImage` is `NSImage` on the Mac/// (`Platform/AppKitAnswers.swift`), so one print serves both.privatestructSnapshotPrint: View {let path: String @State privatevar picture: UIImage? @Environment(\.displayScale) privatevar displayScaleprivatestaticvar width: CGFloat { 46 }var body: someView {Group {iflet picture {InstantPrint(seed: "shake-snapshot", size: .thumb) {Image(uiImage: picture) .resizable() .scaledToFill() } .frame(width: Self.width) .rotationEffect(.degrees(4)) .accessibilityLabel(ShellLines.line("feedback", "report.snapshot")) .accessibilityIdentifier("report-snapshot") } else {// Holds the corner's place so the task below has a view to run on.Color.clear.frame(width: Self.width, height: Self.width) } } .task(id: path) {// The capture is portrait, so its long edge is about twice the drawn width.let edge = Self.width * 2.5 * displayScale picture = awaitTask.detached(priority: .userInitiated) {MediaImages.thumbnail(at: path, edge: edge) }.value } }}/// Which project the caps open ticked. The pick files nothing since/// `feedback.send` (it takes no project); the caps keep their old behaviour so/// the sheet looks as it did.enumReportProject {/// The project a route is INSIDE, by slug — nil for every screen that is/// not one of a project's own.staticfunc projectSlug(inRoute path: String?) -> String? {guardlet path, let route = Route.parse(path) else { returnnil }switch route {case .projectsSlug(let slug), .projectsSlugSection(let slug, _), .projectsBrand(let slug), .projectsCode(let slug), .projectsFeedback(let slug), .projectsMemory(let slug), .projectsTodos(let slug):return slug.isEmpty ? nil : slugdefault:returnnil } }/// Which project the report sheet opens with, as a project ID.////// The rule, in order: the project whose page the person was looking at/// when they shook; else the last project they filed a report under on this/// device; else nothing, because a report may stay unfiled and a sheet that/// demanded a project before it would take a sentence is a sheet nobody/// shakes twice.////// Either source may name a project this device no longer has — an/// archived slug in a stale deep link, a project deleted since the last/// report — and a preselection that named one would tick a cap that is not/// on the sheet. So each is resolved against the offered list, and an/// unresolvable route falls through to the remembered one rather than/// stopping there.staticfunc preselected( route: String?, lastUsed: String?, projects: [ProjectsSheetOption] ) -> String? {iflet slug = projectSlug(inRoute: route),let named = projects.first(where: { $0.slug == slug }) {return named.id }iflet lastUsed, projects.contains(where: { $0.id == lastUsed }) {return lastUsed }returnnil }}