diff --git a/app/Madeira.xcodeproj/project.pbxproj b/app/Madeira.xcodeproj/project.pbxproj index cf86a5a9bb..44895cacf7 100644 --- a/app/Madeira.xcodeproj/project.pbxproj +++ b/app/Madeira.xcodeproj/project.pbxproj @@ -214,6 +214,7 @@ A1000961 /* LibraryGridZoomModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000961 /* LibraryGridZoomModel.swift */; }; A1000960 /* LibraryGridLevels.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000960 /* LibraryGridLevels.swift */; }; A1000401 /* GuestDisplay.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000401 /* GuestDisplay.swift */; }; + A1000D60 /* DisplayGeometry.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000D60 /* DisplayGeometry.swift */; }; A1000243 /* GamepadInput.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000243 /* GamepadInput.swift */; }; A1000260 /* PadKeyboardMouse.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000260 /* PadKeyboardMouse.swift */; }; A1000F51 /* PadAssist.swift in Sources */ = {isa = PBXBuildFile; fileRef = A2000F51 /* PadAssist.swift */; }; @@ -510,6 +511,7 @@ A2000961 /* LibraryGridZoomModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LibraryGridZoomModel.swift"; sourceTree = ""; }; A2000960 /* LibraryGridLevels.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "LibraryGridLevels.swift"; sourceTree = ""; }; A2000401 /* GuestDisplay.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = GuestDisplay.swift; sourceTree = ""; }; + A2000D60 /* DisplayGeometry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DisplayGeometry.swift; sourceTree = ""; }; A2000243 /* GamepadInput.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "GamepadInput.swift"; sourceTree = ""; }; A2000260 /* PadKeyboardMouse.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PadKeyboardMouse.swift"; sourceTree = ""; }; A2000F51 /* PadAssist.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "PadAssist.swift"; sourceTree = ""; }; @@ -753,6 +755,7 @@ A2000961 /* LibraryGridZoomModel.swift */, A2000960 /* LibraryGridLevels.swift */, A2000401 /* GuestDisplay.swift */, + A2000D60 /* DisplayGeometry.swift */, A2000004 /* JITAllocator.c */, A2000005 /* JITAllocator.h */, A200000B /* FEXBridge.mm */, @@ -1218,6 +1221,7 @@ A1000961 /* LibraryGridZoomModel.swift in Sources */, A1000960 /* LibraryGridLevels.swift in Sources */, A1000401 /* GuestDisplay.swift in Sources */, + A1000D60 /* DisplayGeometry.swift in Sources */, A1000004 /* JITAllocator.c in Sources */, A1000005 /* EntitlementChecker.swift in Sources */, A1000006 /* FEXBridge.mm in Sources */, diff --git a/app/Madeira/ContentView.swift b/app/Madeira/ContentView.swift index 0c8531537d..037934d800 100644 --- a/app/Madeira/ContentView.swift +++ b/app/Madeira/ContentView.swift @@ -1,5 +1,6 @@ import SwiftUI import UIKit +import Combine // Publishers.Merge for the touch-controls re-frame import QuartzCore import Metal import os.log @@ -284,6 +285,10 @@ final class MetalBackedView: UIView { NotificationCenter.default.addObserver(forName: UIDevice.orientationDidChangeNotification, object: nil, queue: .main) { _ in MetalBackedView.refreshDisplayMode(reason: "orientation") }, + // Foldables: a fold or unfold that keeps the orientation (DisplayGeometry.swift). + NotificationCenter.default.addObserver(forName: DisplayGeometry.changed, object: nil, queue: .main) { _ in + MetalBackedView.refreshDisplayMode(reason: "scene-geometry") + }, ] static func observeModeChanges() { _ = observers } @@ -1444,9 +1449,9 @@ struct ContentView: View { Color.black MadeiraMetalView() .onAppear { TouchControlsHost.attach() } - .onReceive(NotificationCenter.default.publisher( - for: UIDevice.orientationDidChangeNotification)) { _ in - TouchControlsHost.attach() // re-frame to the new bounds + .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification) + .merge(with: NotificationCenter.default.publisher(for: DisplayGeometry.changed))) { _ in + TouchControlsHost.attach() // re-frame to the new bounds (a rotation, or a fold in the same orientation) } } .ignoresSafeArea() @@ -1481,9 +1486,9 @@ struct ContentView: View { .frame(height: 240) .background(Color.black) .onAppear { TouchControlsHost.attach() } - .onReceive(NotificationCenter.default.publisher( - for: UIDevice.orientationDidChangeNotification)) { _ in - TouchControlsHost.attach() // re-frame to the new bounds + .onReceive(NotificationCenter.default.publisher(for: UIDevice.orientationDidChangeNotification) + .merge(with: NotificationCenter.default.publisher(for: DisplayGeometry.changed))) { _ in + TouchControlsHost.attach() // re-frame to the new bounds (a rotation, or a fold in the same orientation) } HStack(spacing: 6) { if pointerPanel { @@ -3675,7 +3680,7 @@ struct ContentView: View { if p.count == 2, p[0] >= 640, p[1] >= 360, p[0] <= 3840, p[1] <= 2160 { width = p[0]; height = p[1] } } // A Steam game's own Resolution (validated above) sizes its Dock desktop. - if let size = profile?.resolution.split(separator: "x").compactMap({ Int($0) }), size.count == 2 { + if let size = profile?.launchResolution.split(separator: "x").compactMap({ Int($0) }), size.count == 2 { width = size[0]; height = size[1] } setenv("MADEIRA_EXE", "explorer.exe", 1) diff --git a/app/Madeira/DisplayGeometry.swift b/app/Madeira/DisplayGeometry.swift new file mode 100644 index 0000000000..efc798132d --- /dev/null +++ b/app/Madeira/DisplayGeometry.swift @@ -0,0 +1,198 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright 2026 Lee Simpson +// Madeira Converter Exception: see LICENSE-EXCEPTION.md + +import Foundation +#if canImport(UIKit) +import UIKit +#endif + +// [display-geometry]: the screen as Madeira sees it, logged at launch and on +// every scene geometry or size-class change. The `[device]` line at launch +// (EntitlementChecker.swift) says nothing about a screen that changes while +// the app runs: a foldable (iPhone Duo) folds and unfolds, Stage Manager +// resizes. A line is written only when the reading differs from the scene's +// last one, so repeated callbacks for the same layout stay out of the log. + +/// One reading of a scene's display. Foundation-only so the host checks can +/// build it (tests/host/check-duo-display.py). +struct DisplayGeometry: Equatable { + /// Posted on the main queue when the app's own scene has a new reading. A + /// fold that stays in landscape changes the scene's size without an + /// orientation change, so the game layer and the touch controls re-frame + /// on this as well as on UIDevice.orientationDidChangeNotification. + static let changed = Notification.Name("MadeiraDisplayGeometryChanged") + + struct Insets: Equatable { var top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0 } + + /// The scene in points, as laid out now (Stage Manager or Split View can make it smaller than the screen). + var scene: CGSize + /// The scene's UIScreen in points, and UIScreen.nativeBounds in pixels (portrait-up). + var screen: CGSize + var native: CGSize + var scale: CGFloat + var nativeScale: CGFloat + var orientation: String + var horizontal: String + var vertical: String + var idiom: String + var safeArea: Insets + var screens: Int + var maxFPS: Int + + private static func size(_ s: CGSize) -> String { "\(Self.number(s.width))x\(Self.number(s.height))" } + private static func number(_ v: CGFloat) -> String { + v == v.rounded() ? String(Int(v)) : String(format: "%.1f", Double(v)) + } + + /// The log line's fields, without the `[display-geometry] ` prefix. + var line: String { + let i = safeArea + return "scene=\(Self.size(scene))pt screen=\(Self.size(screen))pt native=\(Self.size(native))px" + + " scale=\(Self.number(scale)) native-scale=\(String(format: "%.3f", Double(nativeScale)))" + + " orientation=\(orientation) size-class=\(horizontal)/\(vertical) idiom=\(idiom)" + + " safe-area=\(Self.number(i.top)),\(Self.number(i.left)),\(Self.number(i.bottom)),\(Self.number(i.right))" + + " screens=\(screens) max-fps=\(maxFPS)" + } +} + +#if canImport(UIKit) +extension DisplayGeometry { + @MainActor init(_ scene: UIWindowScene) { + let screen = scene.screen + let window = scene.keyWindow ?? scene.windows.first + let insets = window?.safeAreaInsets ?? .zero + self.init(scene: scene.coordinateSpace.bounds.size, + screen: screen.bounds.size, + native: screen.nativeBounds.size, + scale: screen.scale, + nativeScale: screen.nativeScale, + orientation: Self.name(scene.effectiveGeometry.interfaceOrientation), + horizontal: Self.name(scene.traitCollection.horizontalSizeClass), + vertical: Self.name(scene.traitCollection.verticalSizeClass), + idiom: Self.name(scene.traitCollection.userInterfaceIdiom), + safeArea: Insets(top: insets.top, left: insets.left, bottom: insets.bottom, right: insets.right), + screens: UIScreen.screens.count, + maxFPS: screen.maximumFramesPerSecond) + } + + static func name(_ o: UIInterfaceOrientation) -> String { + switch o { + case .portrait: return "portrait" + case .portraitUpsideDown: return "portrait-upside-down" + case .landscapeLeft: return "landscape-left" + case .landscapeRight: return "landscape-right" + case .unknown: return "unknown" + @unknown default: return "other(\(o.rawValue))" + } + } + + static func name(_ c: UIUserInterfaceSizeClass) -> String { + switch c { + case .compact: return "compact" + case .regular: return "regular" + case .unspecified: return "unspecified" + @unknown default: return "other(\(c.rawValue))" + } + } + + static func name(_ i: UIUserInterfaceIdiom) -> String { + switch i { + case .phone: return "phone" + case .pad: return "pad" + case .mac: return "mac" + case .tv: return "tv" + case .carPlay: return "carplay" + case .unspecified: return "unspecified" + default: return "other(\(i.rawValue))" + } + } +} + +/// Watches every window scene's effective geometry (KVO) and size classes +/// (trait registration) and writes a `[display-geometry]` line when either +/// changes. Started from MadeiraApp.init, before any scene connects. +@MainActor final class DisplayGeometryMonitor { + static let shared = DisplayGeometryMonitor() + + private struct Watch { + let geometry: NSKeyValueObservation + let traits: UITraitChangeRegistration + } + private var watches: [ObjectIdentifier: Watch] = [:] + private var last: [ObjectIdentifier: DisplayGeometry] = [:] + private var started = false + + func start() { + guard !started else { return } + started = true + let center = NotificationCenter.default + center.addObserver(forName: UIScene.willConnectNotification, object: nil, queue: .main) { note in + MainActor.assumeIsolated { + if let scene = note.object as? UIWindowScene { DisplayGeometryMonitor.shared.watch(scene, reason: "connect") } + } + } + center.addObserver(forName: UIScene.didActivateNotification, object: nil, queue: .main) { note in + MainActor.assumeIsolated { + if let scene = note.object as? UIWindowScene { DisplayGeometryMonitor.shared.report(scene, reason: "activate") } + } + } + center.addObserver(forName: UIScene.didDisconnectNotification, object: nil, queue: .main) { note in + MainActor.assumeIsolated { + guard let scene = note.object as? UIScene else { return } + LogStore.shared.log("[display-geometry] disconnect scenes=\(UIApplication.shared.connectedScenes.count)") + let id = ObjectIdentifier(scene) + DisplayGeometryMonitor.shared.watches[id] = nil + DisplayGeometryMonitor.shared.last[id] = nil + } + } + for name in [UIScreen.didConnectNotification, UIScreen.didDisconnectNotification] { + center.addObserver(forName: name, object: nil, queue: .main) { note in + MainActor.assumeIsolated { + let what = note.name == UIScreen.didConnectNotification ? "screen-connect" : "screen-disconnect" + LogStore.shared.log("[display-geometry] \(what) screens=\(UIScreen.screens.count)") + } + } + } + for scene in UIApplication.shared.connectedScenes.compactMap({ $0 as? UIWindowScene }) { + watch(scene, reason: "launch") + } + } + + private func watch(_ scene: UIWindowScene, reason: String) { + let id = ObjectIdentifier(scene) + guard watches[id] == nil else { return } + // UIKit changes effectiveGeometry on the main thread; the window's safe + // area follows in the same layout pass, so the line is read just after. + let geometry = scene.observe(\.effectiveGeometry, options: [.new]) { scene, _ in + DispatchQueue.main.async { + MainActor.assumeIsolated { DisplayGeometryMonitor.shared.report(scene, reason: "geometry") } + } + } + let traits = scene.registerForTraitChanges([UITraitHorizontalSizeClass.self, UITraitVerticalSizeClass.self]) { + (scene: UIWindowScene, _: UITraitCollection) in + MainActor.assumeIsolated { DisplayGeometryMonitor.shared.report(scene, reason: "traits") } + } + watches[id] = Watch(geometry: geometry, traits: traits) + report(scene, reason: reason) + } + + func report(_ scene: UIWindowScene, reason: String) { + let id = ObjectIdentifier(scene) + if watches[id] == nil { watch(scene, reason: reason); return } + let now = DisplayGeometry(scene) + guard last[id] != now else { return } + last[id] = now + LogStore.shared.log("[display-geometry] \(reason) \(now.line)") + // The app's own screen (not an external display's scene) sets the + // Resolution choices: a foldable's fold changes them, a rotation does not. + guard scene.session.role == .windowApplication else { return } + NotificationCenter.default.post(name: DisplayGeometry.changed, object: scene) + if ResolutionChoices.update(.landscape(points: now.screen, pixels: now.native)) { + let d = ResolutionChoices.defaultSize() + LogStore.shared.log("[display-geometry] resolution choices follow the screen: default \(d.w)x\(d.h)" + + (ResolutionChoices.screen720Value.map { " 720-lines \($0)" } ?? "")) + } + } +} +#endif diff --git a/app/Madeira/EntitlementChecker.swift b/app/Madeira/EntitlementChecker.swift index dae9fdc9b9..4dc32bebf8 100644 --- a/app/Madeira/EntitlementChecker.swift +++ b/app/Madeira/EntitlementChecker.swift @@ -85,7 +85,7 @@ struct SigningStatus { /// says by itself which device and set-up produced it. No names, identifiers or /// account data: the model code, versions, sizes and switches only. enum DeviceDiagnostics { - private static func machine() -> String { + static func machine() -> String { var sysinfo = utsname() uname(&sysinfo) return withUnsafePointer(to: &sysinfo.machine) { diff --git a/app/Madeira/GameRecommendationsApply.swift b/app/Madeira/GameRecommendationsApply.swift index 82572a3b6d..1bbdb5a97d 100644 --- a/app/Madeira/GameRecommendationsApply.swift +++ b/app/Madeira/GameRecommendationsApply.swift @@ -173,7 +173,9 @@ extension GameRecommendations { if let mode = rec.fpsMode { entry.fpsMode = mode } if let size = rec.resolution { // This screen's shape at 720 lines; a screen whose default has them keeps its own. + // Foldables: a foldable stores the token and resolves it for the screen the game starts on. if size != GameRecommendation.screen720 { entry.resolution = size } + else if ResolutionChoices.severalScreens { entry.resolution = ResolutionChoices.screen720Token } else if let lines720 = ResolutionChoices.screen720Value { entry.resolution = lines720 } } if let mode = rec.display { entry.display = mode == DisplayMode.fit.rawValue ? nil : mode } diff --git a/app/Madeira/GuestDisplay.swift b/app/Madeira/GuestDisplay.swift index 277db9002d..066e18ffb4 100644 --- a/app/Madeira/GuestDisplay.swift +++ b/app/Madeira/GuestDisplay.swift @@ -173,23 +173,56 @@ enum ResolutionChoices { } /// The screen in landscape: `points` give its shape, `pixels` its native size. - struct Screen { + struct Screen: Equatable { var points: CGSize var pixels: CGSize + + /// A screen's bounds and nativeBounds in any orientation, turned to landscape. + static func landscape(points b: CGSize, pixels n: CGSize) -> Screen { + Screen(points: CGSize(width: max(b.width, b.height), height: min(b.width, b.height)), + pixels: CGSize(width: max(n.width, n.height), height: min(n.width, n.height))) + } } - /// Read once. MadeiraApp.init touches it first, on the main thread; - /// library entries (whose default comes from it) are also made off it. - static var screen: Screen = { + /// Posted (on the thread that called update) when the screen changes shape: + /// a foldable folded or unfolded. Pickers built from `groups()` rebuild. + static let screenChanged = Notification.Name("MadeiraResolutionScreenChanged") + + private static let lock = NSLock() + private static var current: Screen? + + /// The screen the app is on. MadeiraApp.init reads it first, on the main + /// thread; library entries (whose default comes from it) are also made off + /// it. DisplayGeometryMonitor calls update(_:) when a scene's screen changes + /// shape, so on a foldable the choices follow the screen in use; on a device + /// with one screen it stays what the first read found. + static var screen: Screen { + lock.lock(); defer { lock.unlock() } + if let s = current { return s } #if canImport(UIKit) - let b = UIScreen.main.bounds, n = UIScreen.main.nativeBounds - return Screen(points: CGSize(width: max(b.width, b.height), height: min(b.width, b.height)), - pixels: CGSize(width: max(n.width, n.height), height: min(n.width, n.height))) + let s = Screen.landscape(points: UIScreen.main.bounds.size, pixels: UIScreen.main.nativeBounds.size) #else // Hosts without UIKit (the host tests): an 11-inch iPad. - return Screen(points: CGSize(width: 1180, height: 820), pixels: CGSize(width: 2360, height: 1640)) + let s = Screen(points: CGSize(width: 1180, height: 820), pixels: CGSize(width: 2360, height: 1640)) #endif - }() + current = s + return s + } + + /// Follows a screen that changed shape. Returns whether it changed (and + /// `screenChanged` was posted); a rotation of the same screen does not. + @discardableResult + static func update(_ s: Screen) -> Bool { + let s = Screen.landscape(points: s.points, pixels: s.pixels) + guard s.points.width > 0, s.points.height > 0, s.pixels.width > 0, s.pixels.height > 0 else { return false } + lock.lock() + let changed = current != s + current = s + lock.unlock() + noteShape(s) + if changed { NotificationCenter.default.post(name: screenChanged, object: nil) } + return changed + } /// Pixel counts of the screen-shaped choices: a light one (944x656's, 0.8x /// an 11-inch iPad's points), the default (1280x720's: 1408x648 on a 19.5:9 @@ -285,4 +318,69 @@ enum ResolutionChoices { guard p.count == 2, !groups.contains(where: { $0.choices.contains { $0.w == p[0] && $0.h == p[1] } }) else { return nil } return Choice(w: p[0], h: p[1], label: "\(p[0])×\(p[1]) · \(note)") } + + // MARK: A Resolution that follows the screen + + /// A stored Resolution meaning "this screen's default", resolved when the + /// game starts (resolve), so on a foldable a game added on one screen starts + /// screen-shaped on the other. Stored only on a device that has shown more + /// than one screen shape; every other device stores the concrete default, + /// as before. + static let screenToken = "screen" + /// "This screen's shape at 720 lines", or the default where that already has + /// 720 lines: the spelling GameRecommendation.screen720 already uses. + static let screen720Token = "screen@720" + + /// The shapes this device has shown, "WxH@WxH" (points@pixels, landscape). + static let seenKey = "madeira.resolution.screen-shapes" + static var store: UserDefaults = .standard + + static func encode(_ s: Screen) -> String { + "\(Int(s.points.width))x\(Int(s.points.height))@\(Int(s.pixels.width))x\(Int(s.pixels.height))" + } + static func decode(_ text: String) -> Screen? { + let n = text.split(whereSeparator: { $0 == "x" || $0 == "@" }).compactMap { Double($0) } + guard n.count == 4, n.allSatisfy({ $0 > 0 }) else { return nil } + return Screen(points: CGSize(width: n[0], height: n[1]), pixels: CGSize(width: n[2], height: n[3])) + } + static var seenScreens: [Screen] { (store.stringArray(forKey: seenKey) ?? []).compactMap(decode) } + + /// Remembers this screen's shape. A screen of a shape already seen (a + /// rotation, Display Zoom, More Space: within `fills`' 1.5%) adds nothing. + @discardableResult + static func noteShape(_ s: Screen = screen) -> Bool { + let s = Screen.landscape(points: s.points, pixels: s.pixels) + guard s.points.width > 0, s.points.height > 0 else { return false } + let d = defaultSize(for: s) + guard !seenScreens.contains(where: { fills(d.w, d.h, screen: $0) }) else { return false } + store.set((store.stringArray(forKey: seenKey) ?? []) + [encode(s)], forKey: seenKey) + return true + } + /// True once the device has shown screens of two shapes (a foldable). + static var severalScreens: Bool { seenScreens.count > 1 } + + /// What a new library entry stores. + static var newEntryValue: String { severalScreens ? screenToken : defaultValue } + + /// A stored Resolution as the "WxH" a game starts at on screen `s`. + static func resolve(_ value: String, for s: Screen = screen) -> String { + switch value { + case screenToken: + let d = defaultSize(for: s); return "\(d.w)x\(d.h)" + case screen720Token: + let l = screen720(for: s) ?? defaultSize(for: s); return "\(l.w)x\(l.h)" + default: + return value + } + } + + /// The one-time conversion on a device that has shown several shapes: + /// a value that is the default (or the 720-line size) of a shape it has + /// shown becomes the token, so it follows the screen from then on. + static func followTokens(for screens: [Screen]) -> [String: String] { + var out: [String: String] = [:] + for s in screens { if let l = screen720(for: s) { out["\(l.w)x\(l.h)"] = screen720Token } } + for s in screens { let d = defaultSize(for: s); out["\(d.w)x\(d.h)"] = screenToken } + return out + } } diff --git a/app/Madeira/Library.swift b/app/Madeira/Library.swift index 651c0d2515..7231061d99 100644 --- a/app/Madeira/Library.swift +++ b/app/Madeira/Library.swift @@ -192,7 +192,11 @@ struct LibraryEntry: Codable, Identifiable { /// desktop size. ml1172: new entries default to this screen's shape at /// 1280x720's pixel count (ResolutionChoices: 1408x648 on a 19.5:9 iPhone, /// as before, and 1152x800 on an 11-inch iPad, where a fixed 1408x648 left bars). - var resolution = ResolutionChoices.defaultValue + /// Foldables: on a device that has shown two screen shapes (a foldable) it is + /// ResolutionChoices.screenToken, resolved for the screen the game starts on. + var resolution = ResolutionChoices.newEntryValue + /// The "WxH" this entry starts at on the screen in use now. + var launchResolution: String { ResolutionChoices.resolve(resolution) } /// How the monitor is scaled to the screen (DisplayMode raw value; nil = Fit). var display: String? /// FPS limit: 1 = 60, 3 = 30, 4 = 40, 0 = display maximum, 2 = uncapped (madeira_set_vsync_locked). @@ -372,7 +376,7 @@ struct LibraryEntry: Codable, Identifiable { var displayMode: DisplayMode { display.flatMap(DisplayMode.init(rawValue:)) ?? .fit } var launchArguments: String { - if desktop == true { return "/desktop=shell,\(resolution) C:\\windows\\system32\\services.exe" } + if desktop == true { return "/desktop=shell,\(launchResolution) C:\\windows\\system32\\services.exe" } return launchCommand.args } @@ -508,7 +512,7 @@ struct LibraryEntry: Codable, Identifiable { let parent = batch ? nil : parent if runsInDesktop { let program = parent.map { quoted($0) + " " + quoted(path) } ?? quoted(path) - return ("explorer.exe", "/desktop=shell,\(resolution) " + withExtra(batch ? "cmd /c \(quoted(path))" : program)) + return ("explorer.exe", "/desktop=shell,\(launchResolution) " + withExtra(batch ? "cmd /c \(quoted(path))" : program)) } if batch { return ("C:\\windows\\system32\\cmd.exe", withExtra("/c \(quoted(path))")) } if let parent { return (parent, withExtra(quoted(path))) } @@ -735,7 +739,7 @@ struct LibraryEntry: Codable, Identifiable { var effectiveFPSMode: Int32 { ProMotionIntent.supportedMode(fpsMode) } func validate() throws { - let size = resolution.split(separator: "x").compactMap { Int($0) } + let size = launchResolution.split(separator: "x").compactMap { Int($0) } guard size.count == 2, (320...4096).contains(size[0]), (240...4096).contains(size[1]), (0...4).contains(fpsMode), !arguments.contains("\0"), !windowsPath.contains("\0"), !launchArguments.contains("\0"), !launchWindowsPath.contains("\0"), @@ -848,7 +852,8 @@ struct LibraryEntry: Codable, Identifiable { if usesLaunchOptions { fputs("[library] ml1163 start=\(runsInDesktop ? "desktop" : "direct") batch=\(isBatch ? 1 : 0) services=\(servicesScript != nil ? 1 : 0) cwd=\(launchDirectory)\n", stderr) } - LogStore.shared.log("[display-shape] resolution=\(resolution) mode=\(displayMode.rawValue)") + LogStore.shared.log("[display-shape] resolution=\(launchResolution)" + + (launchResolution != resolution ? " (\(resolution))" : "") + " mode=\(displayMode.rawValue)") } /// What the bridge starts. Set on the main thread before the session begins. @@ -861,7 +866,7 @@ struct LibraryEntry: Codable, Identifiable { // the virtual monitor follows this entry's Resolution, as below. "The game" starts // its own program below, like any library game. if !startsSteamGameDirectly { - GuestDisplay.configureSessionDefault(view: CGSize(width: 1280, height: 720), knob: resolution) + GuestDisplay.configureSessionDefault(view: CGSize(width: 1280, height: 720), knob: launchResolution) return } } @@ -896,7 +901,7 @@ struct LibraryEntry: Codable, Identifiable { // Every session's virtual monitor takes this entry's Resolution // (MADEIRA_SCREEN_W/H, source "knob"); for the Desktop entry it is the // same size as its /desktop= argument. - GuestDisplay.configureSessionDefault(view: CGSize(width: 1280, height: 720), knob: resolution) + GuestDisplay.configureSessionDefault(view: CGSize(width: 1280, height: 720), knob: launchResolution) } } @@ -1108,6 +1113,11 @@ final class LibraryModel: ObservableObject { } } resetPhoneResolution() + followScreenDefaults() + // A foldable's second screen shape can first appear while the app runs. + _ = NotificationCenter.default.addObserver(forName: ResolutionChoices.screenChanged, object: nil, queue: .main) { _ in + LibraryModel.shared.followScreenDefaults() + } applyRecommendations() } @@ -1143,6 +1153,26 @@ final class LibraryModel: ObservableObject { LogStore.shared.log("[library] ml1172 resolution default \(ResolutionChoices.defaultValue); \(reset) entries reset from \(phone)") } + /// Foldables: once this device has shown a second screen shape (a + /// foldable), entries still on the default (or the 720-line size) of a shape + /// it has shown take the token instead, once, so they start screen-shaped on + /// either screen. A device with one screen never meets the condition. A size + /// chosen on purpose that equals such a default converts too; nothing tells + /// them apart (as with ml1172). + private func followScreenDefaults() { + let key = "madeira.resolution.follow-screen" + guard !readOnly, ResolutionChoices.severalScreens, !UserDefaults.standard.bool(forKey: key) else { return } + let tokens = ResolutionChoices.followTokens(for: ResolutionChoices.seenScreens) + var next = entries, converted = 0 + for i in next.indices { + if let token = tokens[next[i].resolution] { next[i].resolution = token; converted += 1 } + } + if converted > 0 { guard persist(next, wait: true) else { return } } // try again at the next change or start + UserDefaults.standard.set(true, forKey: key) + LogStore.shared.log("[library] resolution follows the screen: \(converted) entries converted" + + " (shapes \(ResolutionChoices.seenScreens.map(ResolutionChoices.encode).joined(separator: " ")))") + } + func refreshFlag() { guard current == nil, wine_process_is_running() == 0 else { return } // Fixed for the whole run (FrontendChoice); a change applies at the next start. @@ -3946,6 +3976,8 @@ struct LibraryDetail: View { @Environment(\.dismiss) private var dismiss @ObservedObject private var model = LibraryModel.shared @State private var importCover = false + /// Bumped when ResolutionChoices.screen changes (a foldable folds), so the Resolution picker rebuilds. + @State private var screenRevision = 0 /// madeira-bcd: this game's own switches as the fork stores them (reloadBCD). @State private var bcd = BCDGameValues() @State private var findCover = false @@ -4156,7 +4188,7 @@ struct LibraryDetail: View { /// The value a page's row shows, when one setting sums it up. private func summary(_ page: Page) -> String? { switch page { - case .display: return entry.metalFXUpscale.map { "\(entry.resolution) · MetalFX \($0 == 2 ? "2" : "1.5")×" } ?? entry.resolution + case .display: return entry.metalFXUpscale.map { "\(entry.launchResolution) · MetalFX \($0 == 2 ? "2" : "1.5")×" } ?? entry.launchResolution case .controls: return entry.controllerMode == "keys" ? "Keyboard and mouse" : entry.controllerMode == "dinput" ? "XInput and DirectInput" : nil case .launch: return entry.usesLaunchOptions ? (entry.runsInDesktop ? L("Wine desktop") : L("Directly")) : nil case .steam: return entry.startsSteamGameDirectly ? "The game" : "Madeira Dock" @@ -4199,6 +4231,15 @@ struct LibraryDetail: View { let groups = ResolutionChoices.groups() let metalFX = ResolutionChoices.metalFX(in: groups) Picker("Resolution", selection: $entry.resolution) { + // Foldables: on a foldable, the default that follows the screen the game starts on. + if ResolutionChoices.severalScreens || entry.resolution == ResolutionChoices.screenToken { + Text("Default for this screen (\(ResolutionChoices.resolve(ResolutionChoices.screenToken).replacingOccurrences(of: "x", with: "×")))") + .tag(ResolutionChoices.screenToken) + } + if entry.resolution == ResolutionChoices.screen720Token { + Text("720 lines on this screen (\(ResolutionChoices.resolve(ResolutionChoices.screen720Token).replacingOccurrences(of: "x", with: "×")))") + .tag(ResolutionChoices.screen720Token) + } ForEach(groups, id: \.title) { group in Section(group.title) { ForEach(group.choices, id: \.value) { Text($0.label).tag($0.value) } @@ -4213,6 +4254,10 @@ struct LibraryDetail: View { Text(saved.label).tag(entry.resolution) } } + .id(screenRevision) + .onReceive(NotificationCenter.default.publisher(for: ResolutionChoices.screenChanged).receive(on: RunLoop.main)) { _ in + screenRevision &+= 1 + } Picker("Aspect & scaling", selection: Binding(get: { entry.displayMode.rawValue }, set: { entry.display = $0 })) { ForEach(DisplayMode.allCases, id: \.rawValue) { Text($0.label).tag($0.rawValue) } } diff --git a/app/Madeira/MadeiraApp.swift b/app/Madeira/MadeiraApp.swift index 10437152fa..1d6dbc2267 100644 --- a/app/Madeira/MadeiraApp.swift +++ b/app/Madeira/MadeiraApp.swift @@ -17,6 +17,11 @@ struct MadeiraApp: App { // ml1172: read the screen on the main thread; library entries, whose // default Resolution comes from it, are also made on other threads. _ = ResolutionChoices.screen + // Foldables: remember this screen's shape (a foldable shows two). + ResolutionChoices.noteShape() + // [display-geometry] lines at launch and whenever a scene's geometry or size + // classes change (a foldable folding, Stage Manager): DisplayGeometry.swift. + DisplayGeometryMonitor.shared.start() // A sign-in an installer left goes into the Keychain before anything else runs // (SigningRefresh.swift), only while the refresh is switched on. if SigningRefresh.enabled { SigningAccountStore.takeIn() } @@ -33,6 +38,7 @@ struct MadeiraApp: App { ContentView() .background(InteractionFrameRateInstaller()) // touch frame-rate request (New library grid) .modifier(ClaimGamepadEvents()) + .modifier(FoldableFillsWindow()) .onAppear { ExternalDrives.shared.mountAll() GamepadInput.shared.start() @@ -52,3 +58,23 @@ struct MadeiraApp: App { } } } + +/// iPhone Duo: the root fills the window, safe area included. The view +/// handlesGameControllerEvents wraps the root in is sized to the safe area, and +/// on the Duo the system draws the toolbar's buttons and the tab bar in the +/// right-hand status column (the safe area's right inset), outside it: drawn, +/// but every tap there missed. The navigation stack inside keeps the safe area +/// through UIKit. Other devices keep the layout they had: this was seen only on +/// the Duo, which is the only device it was tested on. +struct FoldableFillsWindow: ViewModifier { + /// Model codes of the foldable iPhones (iPhone19,4: iPhone Duo). + static let models: Set = ["iPhone19,4"] + static let active: Bool = { + let simulated = ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] + return models.contains(simulated ?? DeviceDiagnostics.machine()) + }() + + func body(content: Content) -> some View { + if Self.active { content.ignoresSafeArea() } else { content } + } +} diff --git a/tests/host/check-control-presets.py b/tests/host/check-control-presets.py index ff4d9bc9fb..00966ce5b5 100644 --- a/tests/host/check-control-presets.py +++ b/tests/host/check-control-presets.py @@ -51,6 +51,10 @@ ("13in tablet", ControlPresetScreen(width: 1366, height: 1024, top: 24, bottom: 20)), ("mini tablet", ControlPresetScreen(width: 1133, height: 744, top: 24, bottom: 20)), ("phone, portrait", ControlPresetScreen(width: 402, height: 874, left: 0, right: 0, top: 62, bottom: 34)), + // iPhone Duo (iPhone19,4), as held: inner 951x669 pt and outer 466x678 pt, both + // with a 0,0,34,84 safe area (status bar and bars in an 84 pt right-hand column). + ("Duo inner", ControlPresetScreen(width: 951, height: 669, right: 84, top: 0, bottom: 34)), + ("Duo outer", ControlPresetScreen(width: 466, height: 678, right: 84, top: 0, bottom: 34)), ] let expected = ["LS", "RS", "D↑", "D↓", "D←", "D→", "A", "B", "X", "Y", "LB", "RB", "LT", "RT", "View", "Menu", "L3", "R3"] diff --git a/tests/host/check-duo-display.py b/tests/host/check-duo-display.py new file mode 100644 index 0000000000..59bde3b19f --- /dev/null +++ b/tests/host/check-duo-display.py @@ -0,0 +1,561 @@ +#!/usr/bin/env python3 +"""Screen-shaped resolutions on the iPhone Duo's two screens, and no change +on today's iPhones and iPads. + +Compiles the production GuestDisplay.swift (GameSurfaceLayout, GuestDisplay, +ResolutionChoices) and DisplayGeometry.swift without UIKit and checks: + +- golden: what `groups`, `defaultSize`, `screen720` and `metalFX` return for + current iPhones and iPads, recorded before the Duo work, so no later change + can move them; +- Duo: each screen (inner and outer, measured on an iPhone Duo, iPhone19,4, + iOS 27.2.1), plus a taller 19.5:9 outer screen like other foldables', gets + choices of its own shape; +- the screen model follows the screen (ResolutionChoices.update): a fold + changes the default and the picker, a rotation does not; +- the [display-geometry] log line. + +`--record` prints the golden table from the current source instead of +checking it (use it only when a change to existing devices is intended). +""" +from pathlib import Path +import json +import os +import subprocess +import sys +import tempfile + +root = Path(__file__).resolve().parents[2] +app = root / "app/Madeira" +display = (app / "GuestDisplay.swift").read_text() +geometry = (app / "DisplayGeometry.swift").read_text() +content = (app / "ContentView.swift").read_text(encoding="utf-8") + +# P4: the game layer and the touch controls re-frame on a scene geometry change +# (a fold that keeps the orientation), not only on an orientation change. +assert 'forName: DisplayGeometry.changed, object: nil, queue: .main) { _ in\n MetalBackedView.refreshDisplayMode(reason: "scene-geometry")' in content, \ + "MetalBackedView re-applies the layout on DisplayGeometry.changed" +assert content.count('.merge(with: NotificationCenter.default.publisher(for: DisplayGeometry.changed))) { _ in\n' + ' TouchControlsHost.attach()') == 2, "both game views re-frame the touch controls on DisplayGeometry.changed" +assert 'NotificationCenter.default.post(name: DisplayGeometry.changed, object: scene)' in geometry +assert 'ResolutionChoices.update(.landscape(points: now.screen, pixels: now.native))' in geometry +print("PASS: fold re-frame hooks: game layer and touch controls follow scene geometry") + +# (name, landscape points, native pixels) +GOLDEN_SCREENS = [ + ("iphone-6.1", (852, 393), (2556, 1179)), + ("iphone-6.3", (874, 402), (2622, 1206)), + ("iphone-6.9", (956, 440), (2868, 1320)), + ("ipad-mini", (1133, 744), (2266, 1488)), + ("ipad-11", (1180, 820), (2360, 1640)), + ("ipad-pro-11", (1210, 834), (2420, 1668)), + ("ipad-13", (1366, 1024), (2732, 2048)), + ("ipad-pro-13", (1376, 1032), (2752, 2064)), +] +# Measured on an iPhone Duo (iPhone19,4, iOS 27.2.1): the inner screen is +# 951x669 pt on a 2670x1878 px panel (native scale 2.807), the outer 678x466 pt +# at @3x. The third is not a Duo screen: a taller outer screen, as on other foldables. +DUO_SCREENS = [ + ("duo-inner", (951, 669), (2670, 1878)), + ("duo-outer", (678, 466), (2034, 1398)), + ("foldable-outer-19.5:9", (812, 375), (2340, 1080)), +] + +# Recorded from fbad4304 (before any Duo change) with --record. +GOLDEN = json.loads(r''' +{ + "ipad-11": { + "default": "1152x800", + "groups": [ + { + "choices": [ + "944x656 944×656 · light", + "1152x800 1152×800 · default", + "1728x1200 1728×1200 · ≈1080p", + "2360x1640 2360×1640 · native" + ], + "title": "This screen's shape" + }, + { + "choices": [ + "960x540 960×540", + "1280x720 1280×720", + "1600x900 1600×900", + "1920x1080 1920×1080", + "2560x1440 2560×1440" + ], + "title": "16:9 widescreen · bars above and below" + }, + { + "choices": [ + "640x480 640×480", + "800x600 800×600", + "1024x768 1024×768", + "1280x960 1280×960" + ], + "title": "4:3 classic · bars at the sides" + } + ], + "metalFX": "688x480", + "screen720": "" + }, + "ipad-13": { + "default": "1112x832", + "groups": [ + { + "choices": [ + "904x680 904×680 · light", + "1112x832 1112×832 · default", + "1664x1248 1664×1248 · ≈1080p", + "2732x2048 2732×2048 · native" + ], + "title": "This screen's shape" + }, + { + "choices": [ + "960x540 960×540", + "1280x720 1280×720", + "1600x900 1600×900", + "1920x1080 1920×1080", + "2560x1440 2560×1440" + ], + "title": "16:9 widescreen · bars above and below" + }, + { + "choices": [ + "640x480 640×480", + "800x600 800×600", + "1024x768 1024×768", + "1280x960 1280×960" + ], + "title": "4:3 classic · fills this screen" + } + ], + "metalFX": "", + "screen720": "" + }, + "ipad-mini": { + "default": "1184x776", + "groups": [ + { + "choices": [ + "976x640 976×640 · light", + "1184x776 1184×776 · default", + "1776x1168 1776×1168 · ≈1080p", + "2266x1488 2266×1488 · native" + ], + "title": "This screen's shape" + }, + { + "choices": [ + "960x540 960×540", + "1280x720 1280×720", + "1600x900 1600×900", + "1920x1080 1920×1080", + "2560x1440 2560×1440" + ], + "title": "16:9 widescreen · bars above and below" + }, + { + "choices": [ + "640x480 640×480", + "800x600 800×600", + "1024x768 1024×768", + "1280x960 1280×960" + ], + "title": "4:3 classic · bars at the sides" + } + ], + "metalFX": "728x480", + "screen720": "" + }, + "ipad-pro-11": { + "default": "1160x800", + "groups": [ + { + "choices": [ + "952x656 952×656 · light", + "1160x800 1160×800 · default", + "1728x1192 1728×1192 · ≈1080p", + "2420x1668 2420×1668 · native" + ], + "title": "This screen's shape" + }, + { + "choices": [ + "960x540 960×540", + "1280x720 1280×720", + "1600x900 1600×900", + "1920x1080 1920×1080", + "2560x1440 2560×1440" + ], + "title": "16:9 widescreen · bars above and below" + }, + { + "choices": [ + "640x480 640×480", + "800x600 800×600", + "1024x768 1024×768", + "1280x960 1280×960" + ], + "title": "4:3 classic · bars at the sides" + } + ], + "metalFX": "696x480", + "screen720": "" + }, + "ipad-pro-13": { + "default": "1112x832", + "groups": [ + { + "choices": [ + "904x680 904×680 · light", + "1112x832 1112×832 · default", + "1664x1248 1664×1248 · ≈1080p", + "2752x2064 2752×2064 · native" + ], + "title": "This screen's shape" + }, + { + "choices": [ + "960x540 960×540", + "1280x720 1280×720", + "1600x900 1600×900", + "1920x1080 1920×1080", + "2560x1440 2560×1440" + ], + "title": "16:9 widescreen · bars above and below" + }, + { + "choices": [ + "640x480 640×480", + "800x600 800×600", + "1024x768 1024×768", + "1280x960 1280×960" + ], + "title": "4:3 classic · fills this screen" + } + ], + "metalFX": "", + "screen720": "" + }, + "iphone-6.1": { + "default": "1424x656", + "groups": [ + { + "choices": [ + "1160x536 1160×536 · light", + "1424x656 1424×656 · default", + "1560x720 1560×720 · 720 lines", + "2112x976 2112×976 · ≈1080p", + "2556x1179 2556×1179 · native" + ], + "title": "This screen's shape" + }, + { + "choices": [ + "960x540 960×540", + "1280x720 1280×720", + "1600x900 1600×900", + "1920x1080 1920×1080", + "2560x1440 2560×1440" + ], + "title": "16:9 widescreen · bars at the sides" + }, + { + "choices": [ + "640x480 640×480", + "800x600 800×600", + "1024x768 1024×768", + "1280x960 1280×960" + ], + "title": "4:3 classic · bars at the sides" + } + ], + "metalFX": "1040x480", + "screen720": "1560x720" + }, + "iphone-6.3": { + "default": "1408x648", + "groups": [ + { + "choices": [ + "1168x536 1168×536 · light", + "1408x648 1408×648 · default", + "1568x720 1568×720 · 720 lines", + "2120x976 2120×976 · ≈1080p", + "2622x1206 2622×1206 · native" + ], + "title": "This screen's shape" + }, + { + "choices": [ + "960x540 960×540", + "1280x720 1280×720", + "1600x900 1600×900", + "1920x1080 1920×1080", + "2560x1440 2560×1440" + ], + "title": "16:9 widescreen · bars at the sides" + }, + { + "choices": [ + "640x480 640×480", + "800x600 800×600", + "1024x768 1024×768", + "1280x960 1280×960" + ], + "title": "4:3 classic · bars at the sides" + } + ], + "metalFX": "1040x480", + "screen720": "1568x720" + }, + "iphone-6.9": { + "default": "1408x648", + "groups": [ + { + "choices": [ + "1168x536 1168×536 · light", + "1408x648 1408×648 · default", + "1568x720 1568×720 · 720 lines", + "2120x976 2120×976 · ≈1080p", + "2868x1320 2868×1320 · native" + ], + "title": "This screen's shape" + }, + { + "choices": [ + "960x540 960×540", + "1280x720 1280×720", + "1600x900 1600×900", + "1920x1080 1920×1080", + "2560x1440 2560×1440" + ], + "title": "16:9 widescreen · bars at the sides" + }, + { + "choices": [ + "640x480 640×480", + "800x600 800×600", + "1024x768 1024×768", + "1280x960 1280×960" + ], + "title": "4:3 classic · bars at the sides" + } + ], + "metalFX": "1040x480", + "screen720": "1568x720" + } +} +''') + + +def swift_screens(screens): + return ",\n".join( + f' ("{n}", ResolutionChoices.Screen(points: CGSize(width: {p[0]}, height: {p[1]}), ' + f'pixels: CGSize(width: {px[0]}, height: {px[1]})))' + for n, p, px in screens) + + +harness = r''' +func winios_display_mode_changed(_ w: Int32, _ h: Int32) {} + +let golden: [(String, ResolutionChoices.Screen)] = [ +GOLDEN_SCREENS +] +let duo: [(String, ResolutionChoices.Screen)] = [ +DUO_SCREENS +] + +var failed = false +func expect(_ ok: Bool, _ what: String) { + if ok { print("PASS: \(what)") } else { failed = true; FileHandle.standardError.write("FAIL: \(what)\n".data(using: .utf8)!) } +} + +func table(_ s: ResolutionChoices.Screen) -> [String: Any] { + let g = ResolutionChoices.groups(for: s) + let d = ResolutionChoices.defaultSize(for: s) + return [ + "default": "\(d.w)x\(d.h)", + "screen720": ResolutionChoices.screen720(for: s).map { "\($0.w)x\($0.h)" } ?? "", + "metalFX": ResolutionChoices.metalFX(for: s, in: g)?.value ?? "", + "groups": g.map { ["title": $0.title, "choices": $0.choices.map { "\($0.value) \($0.label)" }] as [String: Any] }, + ] +} + +if CommandLine.arguments.count > 1, CommandLine.arguments[1] == "record" { + var out: [String: Any] = [:] + for (name, s) in golden { out[name] = table(s) } + let data = try! JSONSerialization.data(withJSONObject: out, options: [.sortedKeys]) + print(String(data: data, encoding: .utf8)!) + exit(0) +} + +// Golden values for today's devices, passed in as JSON on stdin. +let goldenJSON = try! JSONSerialization.jsonObject(with: FileHandle.standardInput.readDataToEndOfFile()) as! [String: Any] +for (name, s) in golden { + let now = try! JSONSerialization.data(withJSONObject: table(s), options: [.sortedKeys]) + let was = try! JSONSerialization.data(withJSONObject: goldenJSON[name]!, options: [.sortedKeys]) + expect(now == was, "golden \(name): groups, default, screen720 and metalFX unchanged") +} + +// The Duo's screens: choices of the screen's own shape. +for (name, s) in duo { + let g = ResolutionChoices.groups(for: s) + let d = ResolutionChoices.defaultSize(for: s) + expect(g.first?.title == "This screen's shape", "\(name): the first group is the screen's shape") + let own = g.first?.choices ?? [] + expect(own.count >= 2 && own.allSatisfy { $0.label.hasSuffix("native") || ResolutionChoices.fills($0.w, $0.h, screen: s) }, + "\(name): every screen-shaped choice fills the screen (\(own.map(\.value)))") + expect(ResolutionChoices.fills(d.w, d.h, screen: s), "\(name): the default \(d.w)x\(d.h) fills the screen") + expect(d.w % 8 == 0 && d.h % 8 == 0, "\(name): the default is a multiple of 8") + let px = d.w * d.h, budget = 1280 * 720 + expect(abs(Double(px - budget)) / Double(budget) < 0.05, "\(name): the default costs about 1280x720's pixels (\(px))") + if let l = ResolutionChoices.screen720(for: s) { + expect(ResolutionChoices.fills(l.w, l.h, screen: s) || abs(Double(l.w) / 720 / ResolutionChoices.aspect(s) - 1) < 0.02, + "\(name): the 720-line choice \(l.w)x\(l.h) has the screen's shape") + } + let rect = GameSurfaceLayout.rect(guest: CGSize(width: d.w, height: d.h), aspect: .zero, bounds: CGRect(origin: .zero, size: s.points), mode: .fit) + expect(abs(rect.width - s.points.width) < 0.02 * s.points.width && abs(rect.height - s.points.height) < 0.02 * s.points.height, + "\(name): Fit fills the screen at the default (bars under 2%)") +} +// The outer and inner screens differ in shape, so a default chosen on one does not fill the other. +let inner = ResolutionChoices.defaultSize(for: duo[0].1), tall = ResolutionChoices.defaultSize(for: duo[2].1) +expect(!ResolutionChoices.fills(inner.w, inner.h, screen: duo[2].1) && !ResolutionChoices.fills(tall.w, tall.h, screen: duo[0].1), + "foldable: the inner default does not fill a 19.5:9 outer screen, and the other way round") + +// P2: the screen model follows the screen. The first read is the host's +// fallback; update(_:) switches it, posts screenChanged once per change and +// ignores a rotation of the same screen. +var posts = 0 +let token = NotificationCenter.default.addObserver(forName: ResolutionChoices.screenChanged, object: nil, queue: nil) { _ in posts += 1 } +let first = ResolutionChoices.screen +expect(!ResolutionChoices.update(first) && posts == 0, "update: the same screen is no change and posts nothing") +let portrait = ResolutionChoices.Screen(points: CGSize(width: first.points.height, height: first.points.width), + pixels: CGSize(width: first.pixels.height, height: first.pixels.width)) +expect(!ResolutionChoices.update(portrait) && posts == 0, "update: a rotation of the same screen is no change") +expect(!ResolutionChoices.update(.init(points: .zero, pixels: .zero)) && ResolutionChoices.screen == first, "update: an empty reading is ignored") +let duoInner = duo[0].1, duoOuter = duo[1].1 +func values(_ g: [ResolutionChoices.Group]) -> [[String]] { g.map { $0.choices.map(\.value) } } +expect(ResolutionChoices.update(duoInner) && posts == 1, "update: unfolding to the inner screen changes it and posts once") +expect(ResolutionChoices.defaultValue == "1152x808" && values(ResolutionChoices.groups()) == values(ResolutionChoices.groups(for: duoInner)), + "update: the default and the picker's groups follow the inner screen (\(ResolutionChoices.defaultValue))") +expect(ResolutionChoices.screen720Value == nil, "update: no 720-line choice on the inner screen") +expect(ResolutionChoices.update(duoOuter) && posts == 2 && ResolutionChoices.defaultValue == "1152x792" && ResolutionChoices.screen720Value == nil, + "update: folding to the outer screen follows it (\(ResolutionChoices.defaultValue), \(ResolutionChoices.screen720Value ?? "-"))") +expect(ResolutionChoices.update(duoInner) && posts == 3 && ResolutionChoices.defaultValue == "1152x808", "update: and back") +for (name, s) in golden { + ResolutionChoices.update(s) + let now = try! JSONSerialization.data(withJSONObject: table(ResolutionChoices.screen), options: [.sortedKeys]) + let was = try! JSONSerialization.data(withJSONObject: goldenJSON[name]!, options: [.sortedKeys]) + expect(now == was, "update: \(name) as the current screen gives its golden values") +} +NotificationCenter.default.removeObserver(token) + +// P3: the shapes a device has shown, and the token that follows the screen. +let suite = "duo-display-check-\(UUID().uuidString)" +ResolutionChoices.store = UserDefaults(suiteName: suite)! +for (name, s) in golden { + ResolutionChoices.store.removeObject(forKey: ResolutionChoices.seenKey) + let rotated = ResolutionChoices.Screen(points: CGSize(width: s.points.height, height: s.points.width), pixels: CGSize(width: s.pixels.height, height: s.pixels.width)) + ResolutionChoices.noteShape(s); ResolutionChoices.noteShape(rotated); ResolutionChoices.noteShape(s) + ResolutionChoices.update(s) + expect(!ResolutionChoices.severalScreens && ResolutionChoices.newEntryValue == ResolutionChoices.defaultValue, + "\(name): one shape however often it is seen; a new entry stores the concrete default (\(ResolutionChoices.newEntryValue))") + expect(ResolutionChoices.resolve("1280x720", for: s) == "1280x720" && ResolutionChoices.resolve(ResolutionChoices.screenToken, for: s) == "\(ResolutionChoices.defaultSize(for: s).w)x\(ResolutionChoices.defaultSize(for: s).h)", + "\(name): resolve keeps a size and turns the token into this screen's default") +} +// Display Zoom on a 6.3-inch iPhone (402 pt wide becomes 375): the same shape. +ResolutionChoices.store.removeObject(forKey: ResolutionChoices.seenKey) +ResolutionChoices.noteShape(golden[1].1) +ResolutionChoices.noteShape(.init(points: CGSize(width: 812, height: 375), pixels: CGSize(width: 2622, height: 1206))) +expect(!ResolutionChoices.severalScreens, "Display Zoom on an iPhone is not a second screen shape") +// The Duo: outer then inner. +ResolutionChoices.store.removeObject(forKey: ResolutionChoices.seenKey) +ResolutionChoices.noteShape(duoOuter) +expect(!ResolutionChoices.severalScreens, "duo: folded, one shape seen") +ResolutionChoices.noteShape(duoInner); ResolutionChoices.noteShape(duoInner) +expect(ResolutionChoices.severalScreens && ResolutionChoices.seenScreens.count == 2 && ResolutionChoices.newEntryValue == ResolutionChoices.screenToken, + "duo: unfolded, two shapes (seeing one again adds none), new entries take the token") +let tokens = ResolutionChoices.followTokens(for: ResolutionChoices.seenScreens) +expect(tokens == ["1152x792": ResolutionChoices.screenToken, "1152x808": ResolutionChoices.screenToken], + "duo: the one-time conversion maps both defaults; neither screen has a 720-line size (\(tokens))") +expect(ResolutionChoices.resolve(ResolutionChoices.screen720Token, for: duoOuter) == "1152x792" && ResolutionChoices.resolve(ResolutionChoices.screen720Token, for: duoInner) == "1152x808", + "duo: a 720-line token from another device resolves to each screen's default") +// A taller 19.5:9 outer screen (other foldables): also two shapes, each resolved to its own default. +ResolutionChoices.store.removeObject(forKey: ResolutionChoices.seenKey) +ResolutionChoices.noteShape(duo[2].1); ResolutionChoices.noteShape(duoInner) +expect(ResolutionChoices.severalScreens && ResolutionChoices.resolve(ResolutionChoices.screenToken, for: duo[2].1) == "1424x656", + "foldable: a 19.5:9 outer screen counts as a second shape; the token gives it its own 1424x656") +UserDefaults.standard.removePersistentDomain(forName: suite) + +// P4: folding and unfolding mid-game. The guest mode stays; the layer is laid +// out again for each new bounds and touch maps through the same rect, so the +// corners of the picture always hit the guest's corners. +let guest = CGSize(width: 1336, height: 936) +let steps: [(String, CGSize)] = [("inner", duoInner.points), ("outer", duoOuter.points), ("outer portrait", CGSize(width: 466, height: 678)), + ("inner", duoInner.points), ("19.5:9 outer", duo[2].1.points), ("inner portrait", CGSize(width: 669, height: 951))] +for mode in DisplayMode.allCases { + var ok = true, inside = true, notes: [String] = [] + for (name, size) in steps { + let bounds = CGRect(origin: .zero, size: size) + let r = GameSurfaceLayout.rect(guest: guest, aspect: .zero, bounds: bounds, mode: mode) + // Fit and Aspect stay inside the screen; Fill covers it; Stretch is the screen. + switch mode { + case .fit, .aspect: inside = inside && r.minX >= -0.01 && r.minY >= -0.01 && r.maxX <= size.width + 0.01 && r.maxY <= size.height + 0.01 && (abs(r.width - size.width) < 0.01 || abs(r.height - size.height) < 0.01) + case .fill: inside = inside && r.minX <= 0.01 && r.minY <= 0.01 && r.maxX >= size.width - 0.01 && r.maxY >= size.height - 0.01 + case .stretch: inside = inside && r == bounds + } + func at(_ p: CGPoint) -> CGPoint { GameSurfaceLayout.map(point: p, guest: guest, aspect: .zero, bounds: bounds, mode: mode) } + let corners = [(CGPoint(x: r.minX, y: r.minY), CGPoint(x: 0, y: 0)), (CGPoint(x: r.maxX, y: r.minY), CGPoint(x: 1335, y: 0)), + (CGPoint(x: r.minX, y: r.maxY), CGPoint(x: 0, y: 935)), (CGPoint(x: r.maxX, y: r.maxY), CGPoint(x: 1335, y: 935)), + (CGPoint(x: r.midX, y: r.midY), CGPoint(x: 668, y: 468))] + for (p, want) in corners { + let got = at(p) + if abs(got.x - want.x) > 1 || abs(got.y - want.y) > 1 { ok = false; notes.append("\(name) \(p) -> \(got) want \(want)") } + } + } + expect(inside, "fold \(mode): the picture is placed for every screen in the sequence") + expect(ok, "fold \(mode): touch at the picture's corners and centre hits the guest's after every fold \(notes.prefix(3))") +} +// [display-geometry]: the log line's fields. +// The Duo's inner screen as the device logged it. +let g = DisplayGeometry(scene: CGSize(width: 951, height: 669), screen: CGSize(width: 951, height: 669), native: CGSize(width: 1878, height: 2670), + scale: 3, nativeScale: 2.807, orientation: "landscape-left", horizontal: "regular", vertical: "regular", idiom: "phone", + safeArea: .init(top: 0, left: 0, bottom: 34, right: 84), screens: 2, maxFPS: 120) +expect(g.line == "scene=951x669pt screen=951x669pt native=1878x2670px scale=3 native-scale=2.807 orientation=landscape-left size-class=regular/regular idiom=phone safe-area=0,0,34,84 screens=2 max-fps=120", + "display-geometry: the line names every field (\(g.line))") +var h = g; h.safeArea.right = 0 +expect(g != h, "display-geometry: a safe-area change is a new reading") + +exit(failed ? 1 : 0) +'''.replace("GOLDEN_SCREENS", swift_screens(GOLDEN_SCREENS)).replace("DUO_SCREENS", swift_screens(DUO_SCREENS)) + +prelude = r'''import Foundation +#if canImport(CoreGraphics) +import CoreGraphics +#endif +#if os(Windows) +import ucrt +@discardableResult func setenv(_ name: String, _ value: String, _ overwrite: Int32) -> Int32 { _putenv_s(name, value) == 0 ? 0 : -1 } +#endif +''' + +with tempfile.TemporaryDirectory(prefix="duo-display-") as temp: + source, binary = Path(temp) / "main.swift", Path(temp) / "check" + source.write_text(prelude + display.replace("import Foundation\n", "", 1) + harness) + (Path(temp) / "DisplayGeometry.swift").write_text(geometry) + subprocess.run([os.environ.get("SWIFTC", "swiftc"), str(source), str(Path(temp) / "DisplayGeometry.swift"), + "-o", str(binary)], check=True) + if "--record" in sys.argv: + subprocess.run([str(binary), "record"], check=True) + sys.exit(0) + assert GOLDEN is not None, "no golden table recorded yet: run with --record and paste it into GOLDEN" + r = subprocess.run([str(binary)], input=json.dumps(GOLDEN).encode(), capture_output=True) + sys.stdout.write(r.stdout.decode()) + sys.stderr.write(r.stderr.decode()) + if r.returncode: + print("check-duo-display: FAIL") + sys.exit(1) + print("check-duo-display: PASS") diff --git a/tests/host/check-frontend.py b/tests/host/check-frontend.py index 7b263687b1..3042232c62 100644 --- a/tests/host/check-frontend.py +++ b/tests/host/check-frontend.py @@ -38,7 +38,9 @@ Run from anywhere; needs `swift` and `cc` on PATH. """ from pathlib import Path +import os import re +import shutil import subprocess import sys import tempfile @@ -79,6 +81,15 @@ def block(text, header): #if canImport(CoreGraphics) import CoreGraphics // CGRect.width and friends: Foundation alone no longer re-exports them on macOS (Swift 6.4) #endif +#if os(Windows) +import ucrt +// Windows hosts: the C runtime has _putenv_s, not POSIX setenv/unsetenv. +@discardableResult func setenv(_ name: String, _ value: String, _ overwrite: Int32) -> Int32 { + if overwrite == 0, getenv(name) != nil { return 0 } + return _putenv_s(name, value) == 0 ? 0 : -1 +} +@discardableResult func unsetenv(_ name: String) -> Int32 { _putenv_s(name, "") == 0 ? 0 : -1 } +#endif #if canImport(Combine) import Combine #else @@ -190,6 +201,44 @@ def block(text, header): expect((try? game.validate()) != nil, "a screen-shape resolution validates") game.resolution = "1280x720"; game.configureLaunch() +// Foldables: on a device that has shown two screen shapes (a foldable), a new +// entry follows the screen it starts on; a single-screen device stores the size. +do { + let suite = "madeira-frontend-check-\(UUID().uuidString)" + ResolutionChoices.store = UserDefaults(suiteName: suite)! + let pad = ResolutionChoices.screen + let inner = ResolutionChoices.Screen(points: CGSize(width: 951, height: 669), pixels: CGSize(width: 2670, height: 1878)) + let outer = ResolutionChoices.Screen(points: CGSize(width: 678, height: 466), pixels: CGSize(width: 2034, height: 1398)) + // Launched folded: the outer screen is the only shape seen so far. + ResolutionChoices.update(outer) + expect(LibraryEntry(title: "One", relativePath: "a.exe", bits: 64).resolution == "1152x792" && !ResolutionChoices.severalScreens, + "duo: one screen shape seen: a new entry stores the concrete default, as before") + // Unfolded: a second shape. + ResolutionChoices.update(inner) + var duo = LibraryEntry(title: "Duo", relativePath: "Games/duo.exe", bits: 64) + expect(ResolutionChoices.severalScreens && duo.resolution == ResolutionChoices.screenToken, + "duo: a second shape seen: a new entry stores the screen token") + duo.configureLaunch() + expect(env("MADEIRA_SCREEN_W") == "1152" && env("MADEIRA_SCREEN_H") == "808" && published == (1152, 808) && (try? duo.validate()) != nil, + "duo: started on the inner screen it gets the inner screen's default (1152x808)") + ResolutionChoices.update(outer) + duo.configureLaunch() + expect(env("MADEIRA_SCREEN_W") == "1152" && env("MADEIRA_SCREEN_H") == "792", + "duo: the same entry started on the outer screen gets the outer default (1152x792)") + duo.resolution = ResolutionChoices.screen720Token; duo.configureLaunch() + expect(env("MADEIRA_SCREEN_W") == "1152" && env("MADEIRA_SCREEN_H") == "792", "duo: the 720-line token on the outer screen, which has no 720-line size: its default") + ResolutionChoices.update(inner); duo.configureLaunch() + expect(env("MADEIRA_SCREEN_W") == "1152" && env("MADEIRA_SCREEN_H") == "808", "duo: and on the inner screen, whose default has 720 lines: 1152x808") + var desk = LibraryEntry(title: "Desktop", relativePath: "", bits: 64); desk.desktop = true + expect(desk.launchArguments.hasPrefix("/desktop=shell,1152x808 "), "duo: the Desktop entry's desktop follows the screen too") + duo.resolution = "1280x720"; duo.configureLaunch() + expect(env("MADEIRA_SCREEN_W") == "1280" && env("MADEIRA_SCREEN_H") == "720", "duo: a size picked on purpose stays fixed") + ResolutionChoices.update(pad) + UserDefaults.standard.removePersistentDomain(forName: suite) + ResolutionChoices.store = .standard +} +game.configureLaunch() + // A Steam game: Madeira Dock sets what starts, so its profile leaves MADEIRA_EXE alone... var steamGame = LibraryEntry(title: "Steam game", relativePath: "Program Files (x86)/Steam/steamapps/common/Some Game", bits: 0) steamGame.steamAppID = 4242 @@ -526,7 +575,12 @@ def block(text, header): with tempfile.TemporaryDirectory() as tmp: sp = Path(tmp) / 'frontend.swift' sp.write_text(swift) - r = subprocess.run(['swift', str(sp)], capture_output=True, text=True) + # Compile, then run: the `swift file.swift` immediate mode cannot link the + # harness on Windows hosts. + sexe = Path(tmp) / 'frontend' + r = subprocess.run([os.environ.get('SWIFTC', 'swiftc'), str(sp), '-o', str(sexe)], capture_output=True, text=True) + if not r.returncode: + r = subprocess.run([str(sexe)], capture_output=True, text=True) sys.stdout.write(r.stdout) if r.returncode: sys.stdout.write(r.stderr[-4000:]) @@ -534,7 +588,8 @@ def block(text, header): cp = Path(tmp) / 'exit.c' cp.write_text(c_src) exe = Path(tmp) / 'exit' - r = subprocess.run(['cc', '-std=c11', '-Wall', '-Werror', '-D_DEFAULT_SOURCE', '-o', str(exe), str(cp)], + cc = os.environ.get('CC') or shutil.which('cc') or shutil.which('gcc') or shutil.which('clang') + r = subprocess.run([cc, '-std=c11', '-Wall', '-Werror', '-D_DEFAULT_SOURCE', '-o', str(exe), str(cp)], capture_output=True, text=True) if r.returncode: sys.stdout.write(r.stderr[-4000:]) diff --git a/tests/host/check-game-recommendations.py b/tests/host/check-game-recommendations.py index 494d3f899e..8853ea2687 100644 --- a/tests/host/check-game-recommendations.py +++ b/tests/host/check-game-recommendations.py @@ -300,7 +300,10 @@ def block(source, start, end): bo1 = presets['black-ops-1'] assert bo1['tested'] == ['env.MADEIRA_EC_HOOK_TRACE = 0'] and bo1['switches'] == 'olderNvidia: true, resolution: "1280x720"' \ and bo1['version'] == 1, bo1 -assert 'if size != GameRecommendation.screen720 { entry.resolution = size }\n else if let lines720 = ResolutionChoices.screen720Value { entry.resolution = lines720 }' in apply_src +# madeira-duo: a device that has shown two screen shapes (a foldable) stores the token, resolved at launch. +assert 'if size != GameRecommendation.screen720 { entry.resolution = size }\n' \ + ' else if ResolutionChoices.severalScreens { entry.resolution = ResolutionChoices.screen720Token }\n' \ + ' else if let lines720 = ResolutionChoices.screen720Value { entry.resolution = lines720 }' in apply_src gta = presets['gta5e-steam'] assert 'env.MADEIRA_CHILD_ARGS = PlayGTAV.exe -nobattleye' in gta['lines'] assert 'env.MADEIRA_DOCK_KEEP_ALIVE = Launcher.exe;GTA5_Enhanced.exe' in gta['lines'] @@ -609,7 +612,11 @@ def settings(lines): enum DisplayMode: String { case fit, fill, stretch, aspect } -enum ResolutionChoices { static var screen720Value: String? { "1568x720" } } // a 19.5:9 iPhone +enum ResolutionChoices { // a 19.5:9 iPhone, one screen + static var screen720Value: String? { "1568x720" } + static var severalScreens: Bool { false } + static let screen720Token = "screen@720" +} final class LibraryModel { static let shared = LibraryModel() diff --git a/tests/host/check-library-zoom.py b/tests/host/check-library-zoom.py index 61840cfaed..6c95505ad0 100644 --- a/tests/host/check-library-zoom.py +++ b/tests/host/check-library-zoom.py @@ -165,6 +165,25 @@ def between(text, start, end): var distinct = true for i in 1.. 2, "title: landscape's finer levels step by half points (\(steps))") + // iPhone Duo (iPhone19,4) widths: inner 951x669 pt and outer 466x678 pt, each as + // held and turned, plus a taller 19.5:9 outer screen as on other foldables. + for (name, viewport) in [("Duo inner", 951.0), ("Duo inner, turned", 669.0), ("Duo outer", 466.0), + ("Duo outer, turned", 678.0), ("Foldable outer 19.5:9", 812.0), ("Foldable outer 19.5:9, portrait", 375.0)] { + let c = G.contentWidth(viewport: CGFloat(viewport)) + let stops = G.stops(content: c) + var ordered = stops.count >= 2 && stops.count <= G.maxStops + for i in stops.indices.dropFirst() { ordered = ordered && stops[i] > stops[i - 1] } + require(ordered, "\(name) (\(Int(viewport)) pt): two to five levels, fewest columns first (\(stops))") + var fills = true, titles = true + for n in stops { + let w = G.cardWidth(content: c, columns: n) + fills = fills && w > 0 && near(CGFloat(n) * w + CGFloat(n - 1) * G.columnGap, c) + let t = T.size(cardWidth: w) + titles = titles && t >= 12 && t <= 15 + } + require(fills && titles, "\(name): cards fill the width and titles stay in 12...15 at every level") + require(c <= 1100 - 32 + 0.01, "\(name): the page keeps its 1100 pt cap") + } // The page layout. let blocks: [LibraryGridLayoutModel.Block] = [.fixed(height: 44, spacing: 0), .fixed(height: 30, spacing: 24),