diff --git a/host/apple/Sources/ExactKit/IOS/BackIOS.swift b/host/apple/Sources/ExactKit/IOS/BackIOS.swift index 6e1f6958c..106d3b882 100644 --- a/host/apple/Sources/ExactKit/IOS/BackIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/BackIOS.swift @@ -93,6 +93,12 @@ extension NavigationHost { return presenter.carrying("id").contains { $0.props["id"] == name && ($0 === route || $0.isDescendant(of: route)) } } + var traceBack: String { + let route = selectedRoute + let beneath = route?.props["navigationKey"].flatMap { presenter.session?.runtime.locationBeneath($0) } + return "selected=\(selectedKey ?? "nil") selectedRoute=\(route.map { "#\($0.id)" } ?? "nil") control=\(backControl.map { "#\($0.id)" } ?? "nil") declared=\(route.map(declaresBack) ?? false) beneath=\(beneath.map { $0.isEmpty ? "empty" : "some" } ?? "nil") servingMain=\(Owner.shared.isServingMain) window=\(presenter.session?.view?.window != nil)" + } + /// Why Back does not go from the selected route, for the journal. var backRefusal: String { if let route = selectedRoute, declaresBack(route) { return "its navigationBack control is disabled or has no press handler" } diff --git a/host/apple/Sources/ExactKit/IOS/ModalIOS.swift b/host/apple/Sources/ExactKit/IOS/ModalIOS.swift index 14009a3b7..823b8d44c 100644 --- a/host/apple/Sources/ExactKit/IOS/ModalIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/ModalIOS.swift @@ -377,7 +377,13 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { } #endif - init(presenter: Presenter) { self.presenter = presenter } + private var traceObservers: [NSObjectProtocol] = [] + init(presenter: Presenter) { + self.presenter = presenter + super.init() + traceObservers = SheetTrace.watch(self) + } + deinit { traceObservers.forEach(NotificationCenter.default.removeObserver) } #if os(iOS) /// Why a word of a bound `navigationDetent` is dropped. @@ -532,7 +538,9 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { func updatePermissions() { for layer in layers { - layer.controller.isModalInPresentation = refusesDismissal(of: layer.route) + let refuses = refusesDismissal(of: layer.route) + if refuses != layer.controller.isModalInPresentation { SheetTrace.note("updatePermissions modal \(layer.controller.isModalInPresentation)->\(refuses) \(traceState(layer))") } + layer.controller.isModalInPresentation = refuses layer.controller.updateSheet(detent: layer.route.props["navigationDetent"], cornerRadius: ModalController.cornerRadius(of: layer.route), grabber: layer.route.props["navigationGrabber"]) #if os(iOS) layer.controller.paintSurface() @@ -690,6 +698,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { } layers.append(layer) controller.isModalInPresentation = refusesDismissal(of: route) + SheetTrace.note("present \(traceState(layer))") controller.loadViewIfNeeded() // What it inherits, from its first frame: a sheet a deferred sync // presents (the second of two, after the first is up) waits for the next batch otherwise. @@ -753,6 +762,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { func closeTop(animated: Bool = !ExactEnv.agentFreezes, refit: Bool = true) { guard let layer = layers.last else { return } + SheetTrace.note("closeTop route=#\(layer.route.id) key=\(layer.route.props["navigationKey"] ?? "?") alreadyDismissed=\(layer.alreadyDismissed)") closing = true if !layer.alreadyDismissed { presenter.cancelPendingFocus() } presenter.elementScrolls.cancel(inside: layer.controller.view) @@ -826,11 +836,34 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { } func presentationControllerShouldDismiss(_ presentationController: UIPresentationController) -> Bool { - guard let layer = layers.last, layer.controller === presentationController.presentedViewController else { return false } - return !refusesDismissal(of: layer.route) + guard let layer = layers.last, layer.controller === presentationController.presentedViewController else { + SheetTrace.note("shouldDismiss false: not the top layer (layers \(layers.count), retiring \(retiring.count))") + return false + } + let refuses = refusesDismissal(of: layer.route) + // UIKit asks every frame of a drag: the line, which reads the runtime, only when this key changes. + let asked = "\(refuses) \(layer.controller.isModalInPresentation) \(layer.route.id) \(presenter.navigation.selectedKey ?? "") \(presenter.navigation.isInactiveRoute(containing: layer.route))" + if asked != lastAsked { SheetTrace.note("shouldDismiss \(!refuses) \(traceState(layer))") } + lastAsked = asked + return !refuses + } + private var lastAsked: String? + + private func traceState(_ layer: Presentation) -> String { + let route = layer.route, nav = presenter.navigation + let replaced = presenter.views[route.id] !== route + let inactive = nav.isInactiveRoute(containing: route) + let dismissal = nav.sheetDismissal(route) != nil + return "route=#\(route.id) key=\(route.props["navigationKey"] ?? "?") modal=\(layer.controller.isModalInPresentation) refuses=\(refusesDismissal(of: route)) replaced=\(replaced) closedby=\(route.props["closedby"] ?? "-") inactive=\(inactive) sheetDismissal=\(dismissal) canBack=\(nav.canInvokeBack) \(nav.traceBack) presenting=\(layer.presenting) closing=\(closing) layers=\(layers.count) retiring=\(retiring.count) dismissing=\(dismissing != nil) inTransition=\(inTransition) beingPresented=\(layer.controller.isBeingPresented) beingDismissed=\(layer.controller.isBeingDismissed) pendingSync=\(nav.pendingSync) changing=\(nav.changing) app=\(UIApplication.shared.applicationState.rawValue)" + } + + func traceLayers(_ edge: String) { + guard !layers.isEmpty || !retiring.isEmpty else { return } + SheetTrace.note("\(edge): " + (layers.map(traceState).joined(separator: " | ")) + (retiring.isEmpty ? "" : " retiring=\(retiring.count)")) } func presentationControllerDidAttemptToDismiss(_ presentationController: UIPresentationController) { + SheetTrace.note("didAttemptToDismiss top=\(layers.last?.controller === presentationController.presentedViewController) \(layers.last.map(traceState) ?? "no layer")") guard layers.last?.controller === presentationController.presentedViewController, !presenter.navigation.canInvokeBack else { return } presenter.session?.log("modal dismissal refused: \(presenter.navigation.backRefusal)") @@ -840,6 +873,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { /// dismissal's first frame, not when the app hears of it after (Observe's /// render mark); a swipe let go cancels it. func presentationControllerWillDismiss(_ presentationController: UIPresentationController) { + SheetTrace.note("willDismiss") guard let layer = layers.last, layer.controller === presentationController.presentedViewController else { return } NavigationMarks.shared.platformBeganShowing() presentationController.presentedViewController.transitionCoordinator?.animate(alongsideTransition: nil) { context in @@ -848,6 +882,7 @@ final class ModalHost: NSObject, UIAdaptivePresentationControllerDelegate { } func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { + SheetTrace.note("didDismiss top=\(layers.last?.controller === presentationController.presentedViewController)") guard let layer = layers.last, layer.controller === presentationController.presentedViewController else { return } HostLog.note(presenter.session, "presentation: the person dismissed the \(layer.kind) \(layer.route.props["navigationKey"] ?? "?")") closing = true diff --git a/host/apple/Sources/ExactKit/IOS/NavigationIOS.swift b/host/apple/Sources/ExactKit/IOS/NavigationIOS.swift index d37d38143..bbe9f14b8 100644 --- a/host/apple/Sources/ExactKit/IOS/NavigationIOS.swift +++ b/host/apple/Sources/ExactKit/IOS/NavigationIOS.swift @@ -445,6 +445,7 @@ final class NavigationHost: NSObject, UINavigationControllerDelegate, UIGestureR // Initial content draws before a presentation covers it. if parts.count > 1, let session = presenter.session, session.firstDrawMs == nil { return } guard !changing, !presenter.modals.inTransition else { + if !pendingSync { presenter.modals.traceLayers("sync deferred (changing=\(changing))") } pendingSync = true owePress() reportCovers() diff --git a/host/apple/Sources/ExactKit/IOS/SheetTraceIOS.swift b/host/apple/Sources/ExactKit/IOS/SheetTraceIOS.swift new file mode 100644 index 000000000..1aad991bb --- /dev/null +++ b/host/apple/Sources/ExactKit/IOS/SheetTraceIOS.swift @@ -0,0 +1,59 @@ +#if os(iOS) || os(tvOS) +import UIKit + +/// Each sheet dismissal decision and what it read, for a refused swipe seen +/// on a phone: lines in the unified log (`exact-sheet`) and in +/// `app:/cache/exact-sheet-trace.log`, which an app shares with the `fs.read` +/// grant. The file keeps its last 200 to 400 KB. +enum SheetTrace { + static let path = "app:/cache/exact-sheet-trace.log" + private static let limit = 400_000 + private static var opened = false + private static let stamp: ISO8601DateFormatter = { + let f = ISO8601DateFormatter() + f.formatOptions = [.withInternetDateTime, .withFractionalSeconds] + return f + }() + + static func note(_ line: String) { + NSLog("exact-sheet %@", line) + guard let url = AppFiles.url(path) else { return } + var text = "" + if !opened { + opened = true + let info = Bundle.main.infoDictionary + text += "\(stamp.string(from: Date())) launch \(UIDevice.current.systemName) \(UIDevice.current.systemVersion) build \(info?["CFBundleVersion"] as? String ?? "?")\n" + } + text += "\(stamp.string(from: Date())) \(line)\n" + let data = Data(text.utf8) + guard let handle = try? FileHandle(forWritingTo: url) else { + try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try? data.write(to: url) + return + } + defer { try? handle.close() } + if (try? handle.seekToEnd()) ?? 0 > limit, let all = try? Data(contentsOf: url) { + try? (all.suffix(limit / 2) + data).write(to: url) + return + } + try? handle.write(contentsOf: data) + } + + /// The presentations' state at each edge of the app's lifecycle, and a turn after it. + static func watch(_ host: ModalHost) -> [NSObjectProtocol] { + let edges: [(Notification.Name, String)] = [ + (UIApplication.willResignActiveNotification, "willResignActive"), + (UIApplication.didEnterBackgroundNotification, "didEnterBackground"), + (UIApplication.willEnterForegroundNotification, "willEnterForeground"), + (UIApplication.didBecomeActiveNotification, "didBecomeActive"), + (UIApplication.didReceiveMemoryWarningNotification, "memoryWarning"), + ] + return edges.map { name, edge in + NotificationCenter.default.addObserver(forName: name, object: nil, queue: .main) { [weak host] _ in + host?.traceLayers(edge) + DispatchQueue.main.async { [weak host] in host?.traceLayers(edge + " +1 turn") } + } + } + } +} +#endif diff --git a/host/apple/tests/ExactKitTests/ModalStackIOSTests.swift b/host/apple/tests/ExactKitTests/ModalStackIOSTests.swift index f9918a6db..b52ba255b 100644 --- a/host/apple/tests/ExactKitTests/ModalStackIOSTests.swift +++ b/host/apple/tests/ExactKitTests/ModalStackIOSTests.swift @@ -152,6 +152,32 @@ final class ModalStackIOSTests: XCTestCase { XCTAssertEqual(primary.viewControllers, background) } + /// Each answer to UIKit's swipe down goes to the sheet trace with the terms it read. + func testTheSheetTraceRecordsEachDismissalAnswerAndWhatItRead() throws { + guard UIApplication.shared.connectedScenes.contains(where: { $0 is UIWindowScene }) else { + throw missing("scene", "the trace answers UIKit's presented sheet") + } + let session = try fixture("sheet-trace", plan: "EXACT_PUSHED_TITLE_PLAN", fullScreen: true) + let p = session.presenter, agent = Agent(session: session) + let file = try XCTUnwrap(AppFiles.url(SheetTrace.path)) + try? FileManager.default.removeItem(at: file) + try press(session, "home-open-inline") + until("the background stack settles") { !agent.nativeInFlight() } + try press(session, "inline-open-sheet") + until("the sheet's own navigation settles") { p.navigation.modalNavigation != nil && !agent.nativeInFlight() } + let sheet = try XCTUnwrap(presented().last?.presentationController) + XCTAssertTrue(p.modals.presentationControllerShouldDismiss(sheet)) + try press(session, "sheet-open-long") + until("the push inside the sheet settles") { p.navigation.modalNavigation?.viewControllers.count == 2 && !agent.nativeInFlight() } + XCTAssertTrue(p.modals.presentationControllerShouldDismiss(sheet)) + let lines = try String(contentsOf: file, encoding: .utf8).split(separator: "\n").map(String.init) + XCTAssertTrue(lines.contains { $0.contains(" present route=#") && $0.contains("modal=false") }, "the presentation and its flag") + let answers = lines.filter { $0.contains(" shouldDismiss true ") } + XCTAssertEqual(answers.count, 2, "a line only when what the answer read changes: \(answers)") + XCTAssertTrue(answers.first?.contains("inactive=false") == true) + XCTAssertTrue(answers.last?.contains("inactive=true sheetDismissal=true") == true, "the push inside the sheet: \(answers)") + } + func testBackHistoryUsesTheChosenDestinationInThePrimaryStack() throws { guard UIApplication.shared.connectedScenes.contains(where: { $0 is UIWindowScene }) else { throw missing("scene", "native Back history uses UIKit's completed transition")