Play your own Switch games on iPhone/iPad — one-click macOS app, no terminal. | 把 Switch 游戏装进 iPhone:图形界面一键构建,不用命令行。Bring your own game.
Swift apple-siliconcustom-formathomebrewiosipaipadipadosiphonemetalnative-portnintendo-switchnxnativeromfsswitch-games
Touch controls: arrange the controls in the shell settings (patch 0068)
v0lumehi2d439ff8ba7e
diff --git a/frontend-ios/README.md b/frontend-ios/README.mdindex dca6ff89..1b3b59c4 100644--- a/frontend-ios/README.md+++ b/frontend-ios/README.md@@ -63,7 +63,7 @@ The caller returns changed values through `games`. The views keep no second copy| `FolderPicker` | `DocumentFolderPicker` is a `UIDocumentPickerViewController` for a folder, opened in place. Tests use a fake. | `DocumentPicker` in `dm/ios/Sources/Launcher.swift` || Log | Show log reads the tail (256 KB) of `log.txt` in the game's data folder, else the app's folder, into a read-only sheet. | || Update | `ShellHostConfig.updateURL` is opened by Update app. | |-| Touch controls | The shell settings' Touch controls group, for every game: a preview of the controls on a phone held sideways (`TouchControlsPreview`, which mirrors the engine's `DmPadGeometry.h` for that screen) the Size row (small, medium, large) and the Left stick row (corner, higher, inward, the preview marks the default place with a dashed ring). `ShellSettingsStore.touchSize` and `touchStick` store them, and `gameDefaults` passes them to the engine as `DM_TOUCH_SIZE` and `DM_TOUCH_STICK` (medium and the corner are the engine's own and are not passed). The engine keeps a choice off a screen too small for it. Every game also gets `DM_TOUCH_HINT`, the words the engine shows once per launch where the 3D layout's undrawn right stick is (`ios.host.touchHint`). `TouchControlsCaptureTests` renders the group on the Mac. | `dm/ios/Sources/DmPadGeometry.h` (patches 0065 to 0067) |+| Touch controls | The shell settings' Touch controls group, for every game: a preview of the controls on a phone held sideways (`TouchControlsPreview`, which mirrors the engine's `DmPadGeometry.h` for that screen) the Size row (small, medium, large) and the Left stick row (corner, higher, inward, the preview marks the default place with a dashed ring). `ShellSettingsStore.touchSize` and `touchStick` store them, and `gameDefaults` passes them to the engine as `DM_TOUCH_SIZE` and `DM_TOUCH_STICK` (medium and the corner are the engine's own and are not passed). The engine keeps a choice off a screen too small for it. Every game also gets `DM_TOUCH_HINT`, the words the engine shows once per launch where the 3D layout's undrawn right stick is (`ios.host.touchHint`). The Arrangement row opens the layout editor (`TouchLayoutEditorView`, #414): the controls of one layout (2D or 3D, over the picture, and on an iPad or a foldable also below it) on this device's screen, dragged in steps of a quarter key, or chosen and moved with the arrows, a controller (A picks up, the D-pad moves, A or B puts down) or VoiceOver's actions, with Put back and Reset. A spot the engine would refuse (on another control, outside the area) turns red and sends the control back. `TouchLayout` holds the offsets and writes the engine's value, `ShellSettingsStore.touchLayout` stores it and `gameDefaults` passes it as `DM_TOUCH_LAYOUT` (nothing moved: not passed). `PadGeo` is a Swift copy of the engine's geometry, pinned to the engine's points by `TouchLayoutTests`, so the editor keeps only what the engine draws. `TouchControlsCaptureTests` renders the group and the editor on the Mac. | `dm/ios/Sources/DmPadGeometry.h` (patches 0065 to 0068) || Controllers | `ShellHostModel.startControllers()` runs `GamepadAdapter` and fills `controllers` (`ControllerInfo`) and `input` (`ShellInput`). Global mappings are stored in `ShellSettingsStore.padMap`, individual overrides in the game's suite under `GameDefaults.padMapKey`. At launch, each button resolves game > global > default and is passed to the engine as `DM_PAD_MAP`. A profile's own `DM_PAD_MAP` row takes precedence. Touch controls and shell navigation keep their original mapping. | |```swiftdiff --git a/frontend-ios/Sources/ShellUI/LibraryView.swift b/frontend-ios/Sources/ShellUI/LibraryView.swiftindex eb5e2ef8..42d856be 100644--- a/frontend-ios/Sources/ShellUI/LibraryView.swift+++ b/frontend-ios/Sources/ShellUI/LibraryView.swift@@ -50,6 +50,8 @@ public struct LibraryView: View {/// The button-mapping card, while open.@State private var padMapping: PadMappingState?@State private var buttonTestOpen: Bool+ /// The touch controls' layout editor, while open (over the shell settings).+ @State private var touchLayout: TouchLayoutEditorModel?@State private var focus: FocusAppearance@State private var targets = FocusTargetBuffer()@State private var settingsPosition = ScrollPosition()@@ -199,9 +201,17 @@ public struct LibraryView: View {.overlay(alignment: .leading) { Rectangle().fill(ShellPalette.hairline).frame(width: 1).ignoresSafeArea() }.offset(x: edgeDrag).frame(maxWidth: .infinity, alignment: .trailing)+ .accessibilityHidden(touchLayout != nil).accessibilityAddTraits(.isModal).transition(.move(edge: .trailing).combined(with: .opacity))}+ if let touchLayout {+ // The whole screen, so the preview is as large as the device allows.+ ShellPalette.background.ignoresSafeArea().accessibilityHidden(true)+ TouchLayoutEditorView(model: touchLayout, close: closeTouchLayout)+ .accessibilityAddTraits(.isModal)+ .transition(.opacity.combined(with: .scale(scale: 0.98)))+ }if let choice {Color.black.opacity(0.55).ignoresSafeArea().accessibilityHidden(true).onTapGesture { closeChoice() }@@ -237,17 +247,19 @@ public struct LibraryView: View {if buttonTestOpen { return target.id.hasPrefix("test.") }if padMapping != nil { return target.id.hasPrefix("map.") }if choice != nil { return target.id.hasPrefix("pick.") }+ if touchLayout != nil { return target.id.hasPrefix("lay.") }if controllersOpen { return target.id.hasPrefix("ctl.") }if shellSettingsOpen { return target.id.hasPrefix("shs.") }if helpGameID != nil { return target.id.hasPrefix("help.") }if deleteGameID != nil { return target.id.hasPrefix("del.") }- return !["ctl.", "help.", "pick.", "shs.", "del.", "map.", "test."].contains { target.id.hasPrefix($0) }+ return !["ctl.", "help.", "pick.", "shs.", "del.", "map.", "test.", "lay."].contains { target.id.hasPrefix($0) }}}.coordinateSpace(name: "shell")+ .environment(\.shellOpenTouchLayout, { openTouchLayout(whole, insets) }).background {EdgeSwipeBack(enabled: (settingsOpen || controllersOpen || shellSettingsOpen) && choice == nil && helpGameID == nil && deleteGameID == nil- && padMapping == nil && !buttonTestOpen,+ && padMapping == nil && !buttonTestOpen && touchLayout == nil,changed: { edgeDrag = $0 },ended: { finishEdgeSwipe(travel: $0, velocity: $1, span: controllersOpen || shellSettingsOpen ? min(width, 520) : pane) },cancelled: cancelEdgeSwipe)@@ -265,6 +277,7 @@ public struct LibraryView: View {.animation(reduceMotion ? nil : .smooth(duration: 0.25), value: choice).animation(reduceMotion ? nil : .smooth(duration: 0.25), value: padMapping).animation(reduceMotion ? nil : .smooth(duration: 0.25), value: buttonTestOpen)+ .animation(reduceMotion ? nil : .smooth(duration: 0.25), value: touchLayout != nil).environment(\.shellPickChoice, { request in openChoice(request) }).environment(\.shellOpenPadMapping, { id in openPadMapping(id) }).environment(\.shellOpenButtonTest, { openButtonTest() })@@ -411,6 +424,12 @@ public struct LibraryView: View {private func openControllers() { guard !shellSettingsOpen else { return }; noteTouch(); controllersOpen = true; focus.id = "ctl.close" }private func openShellSettings() { noteTouch(); shellSettingsOpen = true; focus.id = "shs.close" }private func closeShellSettings() { shellSettingsOpen = false; focus.id = "lib.shellSettings" }+ private func openTouchLayout(_ window: CGSize, _ insets: EdgeInsets) {+ noteTouch()+ touchLayout = TouchLayoutEditorModel.forDevice(window: window, insets: insets)+ focus.id = "lay.done"+ }+ private func closeTouchLayout() { touchLayout = nil; focus.id = "shs.arrange" }private func openHelp(_ id: String) { returnFocus = focus.id; helpGameID = id; focus.id = "help.done" }private func closeHelp() { helpGameID = nil; focus.id = returnFocus }/// The question starts on Cancel, with the saves kept.@@ -432,13 +451,15 @@ public struct LibraryView: View {private func closeChoice() {guard let request = choice else { return }choice = nil- focus.id = (request.gameID == ShellSettingsRows.gameID ? ShellSettingsRows.targetPrefix : "set.row.") + request.row.id+ let prefix = request.gameID == ShellSettingsRows.gameID ? ShellSettingsRows.targetPrefix : request.gameID == TouchLayoutEditorView.gameID ? "lay.row." : "set.row."+ focus.id = prefix + request.row.id}private func pickChoice(_ value: String) {noteTouch()guard let request = choice else { return }if value != request.row.value {- if request.gameID == ShellSettingsRows.gameID { ShellSettingsRows.apply(request.row.id, value: value, to: .current) }+ if request.gameID == TouchLayoutEditorView.gameID { touchLayout?.apply(row: request.row.id, value: value) }+ else if request.gameID == ShellSettingsRows.gameID { ShellSettingsRows.apply(request.row.id, value: value, to: .current) }else { actions.onChange(request.gameID, request.row.id, value) }}closeChoice()@@ -497,6 +518,7 @@ public struct LibraryView: View {else if padMapping?.row != nil { closePadRow() }else if padMapping != nil { closePadMapping() }else if choice != nil { closeChoice() }+ else if let touchLayout { if touchLayout.held { touchLayout.putDown() } else { closeTouchLayout() } }else if helpGameID != nil { closeHelp() }else if deleteGameID != nil { closeDelete() }else if controllersOpen { controllersOpen = false; focus.id = "lib.controllers" }@@ -512,6 +534,14 @@ public struct LibraryView: View {if device != source { device = source }if touchMode { touchMode = false }focus.visible = true+ // A control the editor holds: the D-pad (or the arrow keys) moves it, A or B puts it down.+ if let touchLayout, touchLayout.held, choice == nil {+ switch action {+ case .left, .right, .up, .down: touchLayout.nudge(action); return+ case .activate, .back: touchLayout.putDown(); return+ default: break+ }+ }if focus.id == nil || !targets.values.contains(where: { $0.id == focus.id }) {focus.id = defaultFocusif action != .activate && action != .back && action != .settings && action != .controllers { return }@@ -544,6 +574,7 @@ public struct LibraryView: View {if buttonTestOpen { return "test.close" }if let padMapping { return padMapping.row == nil ? "map.close" : "map.back" }if let choice { return "pick." + choice.row.value }+ if touchLayout != nil { return "lay.done" }if helpGameID != nil { return "help.done" }if deleteGameID != nil { return "del.cancel" }if controllersOpen { return "ctl.close" }diff --git a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstringsindex d0bb125d..4d1acaa1 100644--- a/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings+++ b/frontend-ios/Sources/ShellUI/Resources/Localizable.xcstrings@@ -369,6 +369,166 @@}}},+ "Arrange controls": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Tasten anordnen"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Arrange controls"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Disposer les commandes"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Disponi i comandi"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Ordna kontrollerna"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "排列按键"+ }+ }+ }+ },+ "Arrangement": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Anordnung"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Arrangement"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Disposition"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Disposizione"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Placering"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "按键位置"+ }+ }+ }+ },+ "Arrange…": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Anordnen …"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Arrange…"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Disposer…"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Disponi…"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Ordna…"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "排列…"+ }+ }+ }+ },+ "At the edge": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Am Rand"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "At the edge"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Au bord"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Al bordo"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Vid kanten"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "已到边缘"+ }+ }+ }+ },"Back": {"localizations": {"en": {@@ -385,6 +545,46 @@}}},+ "Below the picture": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Unter dem Bild"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Below the picture"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Sous l’image"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Sotto l’immagine"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Under bilden"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "在画面下方"+ }+ }+ }+ },"Bottom button": {"localizations": {"de": {@@ -537,6 +737,46 @@}}},+ "Built in": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Standard"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Built in"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Par défaut"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Predefinita"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Standard"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "默认"+ }+ }+ }+ },"Button mapping": {"localizations": {"de": {@@ -849,6 +1089,46 @@}}},+ "Choose a control": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Wähle eine Taste"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Choose a control"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Choisissez une commande"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Scegli un comando"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Välj en kontroll"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "选择一个按键"+ }+ }+ }+ },"Choose folder…": {"localizations": {"en": {@@ -1851,82 +2131,122 @@}}},- "Dutch": {+ "Drag a control to move it. Tap one to choose it, then move it step by step with the arrows. Where a control would cover another or leave the screen, it goes back. For every game.": {"localizations": {"de": {"stringUnit": {"state": "translated",- "value": "Niederländisch"+ "value": "Ziehe eine Taste, um sie zu verschieben. Tippe eine an, um sie zu wählen, und verschiebe sie dann Schritt für Schritt mit den Pfeilen. Würde eine Taste eine andere verdecken oder den Bildschirm verlassen, geht sie zurück. Für alle Spiele."}},"en": {"stringUnit": {"state": "translated",- "value": "Dutch"+ "value": "Drag a control to move it. Tap one to choose it, then move it step by step with the arrows. Where a control would cover another or leave the screen, it goes back. For every game."}},"fr": {"stringUnit": {"state": "translated",- "value": "Néerlandais"+ "value": "Faites glisser une commande pour la déplacer. Touchez-en une pour la choisir, puis déplacez-la pas à pas avec les flèches. Si une commande en couvrait une autre ou sortait de l’écran, elle revient. Pour tous les jeux."}},"it": {"stringUnit": {"state": "translated",- "value": "Olandese"+ "value": "Trascina un comando per spostarlo. Toccane uno per sceglierlo, poi spostalo passo per passo con le frecce. Se un comando ne coprisse un altro o uscisse dallo schermo, torna indietro. Per tutti i giochi."}},"sv": {"stringUnit": {"state": "translated",- "value": "Nederländska"+ "value": "Dra en kontroll för att flytta den. Tryck på en för att välja den och flytta den sedan steg för steg med pilarna. Om en kontroll skulle täcka en annan eller hamna utanför skärmen går den tillbaka. För alla spel."}},"zh-Hans": {"stringUnit": {"state": "translated",- "value": "荷兰语"+ "value": "拖动按键即可移动。点按一个按键选中它,再用箭头一步步移动。按键会挡住其他按键或超出屏幕时,会回到原位。适用于所有游戏。"}}}},- "Dynamic resolution": {+ "Dutch": {"localizations": {"de": {"stringUnit": {"state": "translated",- "value": "Dynamische Auflösung"+ "value": "Niederländisch"}},"en": {"stringUnit": {"state": "translated",- "value": "Dynamic resolution"+ "value": "Dutch"}},"fr": {"stringUnit": {"state": "translated",- "value": "Résolution dynamique"+ "value": "Néerlandais"}},"it": {"stringUnit": {"state": "translated",- "value": "Risoluzione dinamica"+ "value": "Olandese"}},"sv": {"stringUnit": {"state": "translated",- "value": "Dynamisk upplösning"+ "value": "Nederländska"}},"zh-Hans": {"stringUnit": {"state": "translated",- "value": "动态分辨率"+ "value": "荷兰语"+ }+ }+ }+ },+ "Dynamic resolution": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Dynamische Auflösung"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Dynamic resolution"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Résolution dynamique"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Risoluzione dinamica"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Dynamisk upplösning"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "动态分辨率"}}}@@ -2979,6 +3299,46 @@}}},+ "In its place": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "An ihrem Platz"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "In its place"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "À sa place"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Al suo posto"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "På sin plats"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "在原位"+ }+ }+ }+ },"Increase": {"localizations": {"en": {@@ -3347,6 +3707,46 @@}}},+ "Layout": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Aufteilung"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Layout"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Agencement"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Schema"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Layout"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "布局"+ }+ }+ }+ },"Left": {"localizations": {"de": {@@ -3797,6 +4197,46 @@}}},+ "Move A B X Y together": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "A B X Y zusammen bewegen"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Move A B X Y together"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Déplacer A B X Y ensemble"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Sposta A B X Y insieme"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Flytta A B X Y tillsammans"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "A B X Y 一起移动"+ }+ }+ }+ },"Move between controls": {"localizations": {"en": {@@ -3813,6 +4253,286 @@}}},+ "Move down": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Nach unten"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Move down"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Vers le bas"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Giù"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Ned"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "下移"+ }+ }+ }+ },+ "Move it with the D-pad. A or B puts it down.": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Mit dem Steuerkreuz verschieben. A oder B legt sie ab."+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Move it with the D-pad. A or B puts it down."+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Déplacez-la avec la croix. A ou B la pose."+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Spostalo con la croce direzionale. A o B lo posa."+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Flytta den med styrkorset. A eller B släpper den."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "用十字键移动它。按 A 或 B 放下。"+ }+ }+ }+ },+ "Move left": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Nach links"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Move left"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Vers la gauche"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "A sinistra"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Vänster"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "左移"+ }+ }+ }+ },+ "Move right": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Nach rechts"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Move right"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Vers la droite"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "A destra"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Höger"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "右移"+ }+ }+ }+ },+ "Move single controls where your thumbs want them.": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Einzelne Tasten dorthin schieben, wo die Daumen sie haben wollen."+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Move single controls where your thumbs want them."+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Placez chaque commande là où vos pouces la veulent."+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Sposta i singoli comandi dove li vogliono i pollici."+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Flytta enskilda kontroller dit tummarna vill ha dem."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "把单个按键移到拇指顺手的位置。"+ }+ }+ }+ },+ "Move up": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Nach oben"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Move up"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Vers le haut"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Su"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Upp"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "上移"+ }+ }+ }+ },+ "Moved": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Verschoben"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Moved"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Déplacée"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Spostato"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Flyttad"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "已移动"+ }+ }+ }+ },"Named as on a Switch controller, by where they sit.": {"localizations": {"de": {@@ -3962,29 +4682,109 @@"en": {"stringUnit": {"state": "translated",- "value": "No data selected"+ "value": "No data selected"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "未选择数据"+ }+ }+ }+ },+ "No folder chosen": {+ "localizations": {+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "No folder chosen"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "未选择文件夹"+ }+ }+ }+ },+ "No room there": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Dort ist kein Platz"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "No room there"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Pas de place ici"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Non c’è spazio"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Ingen plats där"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "那里放不下"+ }+ }+ }+ },+ "No room there. It went back to where it was.": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Dort ist kein Platz. Die Taste ist zurück an ihrem Platz."+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "No room there. It went back to where it was."}},- "zh-Hans": {+ "fr": {"stringUnit": {"state": "translated",- "value": "未选择数据"+ "value": "Pas de place ici. La commande est revenue à sa place."}- }- }- },- "No folder chosen": {- "localizations": {- "en": {+ },+ "it": {"stringUnit": {"state": "translated",- "value": "No folder chosen"+ "value": "Non c’è spazio. Il comando è tornato al suo posto."+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Ingen plats där. Kontrollen gick tillbaka dit den var."}},"zh-Hans": {"stringUnit": {"state": "translated",- "value": "未选择文件夹"+ "value": "那里放不下,已回到原来的位置。"}}}@@ -4245,6 +5045,46 @@}}},+ "Over the picture": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Über dem Bild"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Over the picture"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Sur l’image"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Sopra l’immagine"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Över bilden"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "叠在画面上"+ }+ }+ }+ },"Performance": {"localizations": {"de": {@@ -4633,6 +5473,46 @@}}},+ "Put back": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Zurückstellen"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Put back"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Remettre"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Rimetti"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Lägg tillbaka"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "放回原位"+ }+ }+ }+ },"Puts A on the bottom button, where Xbox and PlayStation controllers confirm.": {"localizations": {"de": {@@ -4801,6 +5681,46 @@}}},+ "Reset this layout": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Dieses Layout zurücksetzen"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Reset this layout"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Réinitialiser cet agencement"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Ripristina questo schema"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Återställ den här layouten"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "重置此布局"+ }+ }+ }+ },"Reset to tested defaults": {"localizations": {"en": {@@ -5257,6 +6177,46 @@}}},+ "Screen": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Bildschirm"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Screen"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Écran"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Schermo"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Skärm"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "屏幕"+ }+ }+ }+ },"See each button light up as you press it.": {"localizations": {"de": {@@ -5705,6 +6665,46 @@}}},+ "Tap a control in the picture.": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Tippe auf eine Taste im Bild."+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Tap a control in the picture."+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Touchez une commande dans l’image."+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Tocca un comando nell’immagine."+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Tryck på en kontroll i bilden."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "点按画面中的一个按键。"+ }+ }+ }+ },"The first start waits a few minutes for it, once.": {"localizations": {"de": {@@ -6009,6 +7009,46 @@}}},+ "Turn the phone sideways for a larger preview.": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Halte das iPhone quer für eine größere Vorschau."+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Turn the phone sideways for a larger preview."+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Tournez le téléphone à l’horizontale pour un aperçu plus grand."+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Ruota il telefono in orizzontale per un’anteprima più grande."+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Vänd telefonen på sidan för en större förhandsvisning."+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "把手机横过来,预览会更大。"+ }+ }+ }+ },"Unavailable": {"localizations": {"en": {@@ -6376,6 +7416,46 @@}}}+ },+ "Your own": {+ "localizations": {+ "de": {+ "stringUnit": {+ "state": "translated",+ "value": "Eigene"+ }+ },+ "en": {+ "stringUnit": {+ "state": "translated",+ "value": "Your own"+ }+ },+ "fr": {+ "stringUnit": {+ "state": "translated",+ "value": "Personnalisée"+ }+ },+ "it": {+ "stringUnit": {+ "state": "translated",+ "value": "Personalizzata"+ }+ },+ "sv": {+ "stringUnit": {+ "state": "translated",+ "value": "Egen"+ }+ },+ "zh-Hans": {+ "stringUnit": {+ "state": "translated",+ "value": "自定义"+ }+ }+ }}},"version": "1.0"diff --git a/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift b/frontend-ios/Sources/ShellUI/ShellSettingsStore.swiftindex 6a9cb6c0..30a68419 100644--- a/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift+++ b/frontend-ios/Sources/ShellUI/ShellSettingsStore.swift@@ -17,6 +17,7 @@ public final class ShellSettingsStore: @unchecked Sendable {public static let touchStickKey = "touchStick" // corner, higher or inward: DM_TOUCH_STICK for every game/// Where the left stick sits, as the engine reads DM_TOUCH_STICK. The corner is the built-in place and is never stored.public static let touchStickPlaces = ["corner", "higher", "inward"]+ public static let touchLayoutKey = "touchLayout" // the player's arrangement: DM_TOUCH_LAYOUT for every game/// The store the app reads and writes. Tests and previews swap it.nonisolated(unsafe) public static var current = ShellSettingsStore()@@ -63,6 +64,21 @@ public final class ShellSettingsStore: @unchecked Sendable {if place == "corner" { defaults.removeObject(forKey: Self.touchStickKey) } else { defaults.set(place, forKey: Self.touchStickKey) }}+ /// The player's arrangement of the touch controls for every game (#414): stored as the value the engine reads, so what the+ /// settings show is what a game gets. A stored value the engine would ignore reads as the built-in layout.+ public var touchLayout: TouchLayout {+ defaults.string(forKey: Self.touchLayoutKey).flatMap { TouchLayout(encoded: $0) } ?? TouchLayout()+ }+ public func storeTouchLayout(_ layout: TouchLayout) {+ if layout.isEmpty { defaults.removeObject(forKey: Self.touchLayoutKey) } else { defaults.set(layout.encoded, forKey: Self.touchLayoutKey) }+ }+ /// Every control of one layout back to its built-in place.+ public func resetTouchLayout(_ kind: TouchLayout.Kind) {+ var layout = touchLayout+ layout.reset(kind)+ storeTouchLayout(layout)+ }+public var padMap: PadMap { PadMap(defaults.dictionary(forKey: Self.padMapKey) as? [String: String] ?? [:]) }public func setPadButton(_ button: String, to output: String) {var map = padMap@@ -82,6 +98,8 @@ public final class ShellSettingsStore: @unchecked Sendable {var values = performanceHUD.map { ["DM_METAL_HUD": $0 ? "1" : "0"] } ?? [:]if touchSize != "medium" { values["DM_TOUCH_SIZE"] = touchSize }if touchStick != "corner" { values["DM_TOUCH_STICK"] = touchStick }+ let layout = touchLayout.encoded+ if !layout.isEmpty { values["DM_TOUCH_LAYOUT"] = layout }return values}}diff --git a/frontend-ios/Sources/ShellUI/ShellSettingsView.swift b/frontend-ios/Sources/ShellUI/ShellSettingsView.swiftindex 2dff6ea6..2da725a1 100644--- a/frontend-ios/Sources/ShellUI/ShellSettingsView.swift+++ b/frontend-ios/Sources/ShellUI/ShellSettingsView.swift@@ -101,13 +101,14 @@ struct ShellSettingsView: View {}}SettingsGroup(title: ShellStrings.text("Touch controls")) {- TouchControlsPreview(size: store.touchSize, stick: store.touchStick)+ TouchControlsPreview(size: store.touchSize, stick: store.touchStick, layout: store.touchLayout)TouchControlsNote()ForEach([ShellSettingsRows.touchSizeRow(store), ShellSettingsRows.touchStickRow(store)]) { row inSettingControl(gameID: ShellSettingsRows.gameID, row: row, targetPrefix: ShellSettingsRows.targetPrefix) {ShellSettingsRows.apply(row.id, value: $0, to: store)}.equatable()}+ TouchArrangeRow(arranged: !store.touchLayout.isEmpty)}SettingsGroup(title: ShellStrings.text("Interface")) {let hud = ShellSettingsRows.hudRow(store)diff --git a/frontend-ios/Sources/ShellUI/TouchControlsPreview.swift b/frontend-ios/Sources/ShellUI/TouchControlsPreview.swiftindex 2281318f..d4431551 100644--- a/frontend-ios/Sources/ShellUI/TouchControlsPreview.swift+++ b/frontend-ios/Sources/ShellUI/TouchControlsPreview.swift@@ -1,12 +1,11 @@import SwiftUI/// Where the touch controls sit on an iPhone Pro Max held sideways (932 x 430 points, the side insets of the Dynamic Island and the home-/// indicator), for the preview in the settings. It mirrors the engine's `DmPadGeometry.h` (patch 0065) for that one screen, in the 3D-/// layout so every control shows: the same constants in u, the bottom corners halfway into the side insets, the left stick's place (patch-/// 0066). The engine stays the truth on the device, where a choice that does not fit a screen moves toward the built-in layout.+/// indicator), for the preview in the settings, in the 3D layout so every control shows. It is the engine's geometry for that screen+/// (`PadGeo`, the Swift copy of `DmPadGeometry.h`): the size, the left stick's place and the player's 3D arrangement. The engine stays the+/// truth on the device, where a choice that does not fit a screen moves toward the built-in layout.struct TouchPadPreviewGeometry: Equatable {- static let screen = CGSize(width: 932, height: 430)- static let insets = (left: 59.0, right: 59.0, bottom: 21.0)+ static let screen = PadScreen.proMax.sizeenum Shape: Equatable {case circle(CGPoint, CGFloat, label: String?)@@ -17,54 +16,30 @@ struct TouchPadPreviewGeometry: Equatable {}/// DM_TOUCH_SIZE's scale: small 0.8, medium 1, large 1.2.- static func scale(_ size: String) -> CGFloat { size == "small" ? 0.8 : size == "large" ? 1.2 : 1 }+ static func scale(_ size: String) -> CGFloat { PadGeo.scale(size) }- let u: CGFloat- /// DM_TOUCH_STICK: corner, higher or inward.- let place: String- init(size: String, stick: String = "corner") { u = Self.scale(size); place = stick }-- private var safe: CGRect { CGRect(x: Self.insets.left, y: 0, width: Self.screen.width - Self.insets.left - Self.insets.right, height: Self.screen.height) }- private var corner: CGRect {- CGRect(x: Self.insets.left / 2, y: 0, width: Self.screen.width - (Self.insets.left + Self.insets.right) / 2, height: Self.screen.height - Self.insets.bottom)- }- private func side(_ r: CGRect, right: Bool, _ dx: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: right ? r.maxX - dx : r.minX + dx, y: y) }-- private var cornerStick: CGPoint { side(corner, right: false, 81 * u, corner.maxY - 82 * u) }- /// How far the stick moves for its place: higher up to 70 u, until its ring would reach L's circle, inward 60 u (the engine- /// shrinks either in 2 u steps until nothing overlaps; on this screen only higher meets something, L, at the large size).- private var shift: CGVector {- switch place {- case "higher":- let l = side(safe, right: false, 44 * u, 108 * u), r = 24 * u- var d = 70 * u- while d > 0 && hypot(cornerStick.x - l.x, cornerStick.y - d - l.y) < 77 * u + r { d -= 2 * u }- return CGVector(dx: 0, dy: -max(d, 0))- case "inward": return CGVector(dx: 60 * u, dy: 0)- default: return .zero- }+ let geo: PadGeo+ var u: CGFloat { geo.u }+ init(size: String, stick: String = "corner", layout: TouchLayout = TouchLayout()) {+ geo = PadGeo.make(.proMax, full: true, size: size, stick: stick, layout: layout)}- var stick: CGPoint { CGPoint(x: cornerStick.x + shift.dx, y: cornerStick.y + shift.dy) }- var face: CGPoint { side(corner, right: true, 81 * u, corner.maxY - 82 * u) }- /// The D-pad sits inward of the stick and moves with it when the stick moves inward.- var dpad: CGPoint { side(corner, right: false, 231 * u + (place == "inward" ? shift.dx : 0), corner.maxY - 64 * u) }- var shapes: [Shape] {+ var stick: CGPoint { geo.stick }+ var face: CGPoint { geo.face }+ var dpad: CGPoint { geo.dpad }++ var shapes: [Shape] { Self.shapes(geo) }++ /// The drawn controls of a geometry, as the gamepad draws them.+ static func shapes(_ g: PadGeo) -> [Shape] {var out: [Shape] = []- let f = face, gap = 50 * u- for (dx, dy, name) in [(gap, 0.0, "A"), (0, gap, "B"), (0, -gap, "X"), (-gap, 0, "Y")] {- out.append(.circle(CGPoint(x: f.x + dx, y: f.y + dy), 27 * u, label: name))- }- out.append(.ring(stick, 77 * u, knob: 30 * u))- out.append(.dpad(dpad, 48 * u))- for right in [false, true] {- out.append(.drop(side(safe, right: right, 44 * u, 40 * u), 26 * u, tipRight: right, label: right ? "ZR" : "ZL"))- out.append(.drop(side(safe, right: right, 44 * u, 108 * u), 24 * u, tipRight: right, label: right ? "R" : "L"))- out.append(.circle(side(safe, right: right, 102 * u, 40 * u), 17 * u, label: right ? "R3" : "L3"))- let w = 50 * u, h = 28 * u, x = safe.midX + (right ? 52 : -52) * u- out.append(.pill(CGRect(x: x - w / 2, y: 22 * u - h / 2, width: w, height: h), label: right ? "+" : "−"))- }- out.append(.circle(CGPoint(x: safe.midX, y: 22 * u), 15 * u, label: nil))+ for (i, name) in ["A", "B", "X", "Y"].enumerated() { out.append(.circle(g.faceKey[i], g.faceR, label: name)) }+ out.append(.ring(g.stick, g.stickR, knob: g.knobR))+ if g.full { out.append(.dpad(g.dpad, g.dpadR)) }+ for (i, name) in ["ZL", "L", "ZR", "R"].enumerated() { out.append(.drop(g.drop[i], g.dropR[i], tipRight: i >= 2, label: name)) }+ if g.full { for (i, name) in ["L3", "R3"].enumerated() { out.append(.circle(g.click[i], g.clickR, label: name)) } }+ for (i, name) in ["−", "+"].enumerated() { out.append(.pill(g.pill[i], label: name)) }+ out.append(.circle(g.swap, g.swapR, label: nil))return out}@@ -92,39 +67,77 @@ struct TouchControlsNote: View {struct TouchControlsPreview: View {var size: Stringvar stick = "corner"+ var layout = TouchLayout()var body: some View {- let geometry = TouchPadPreviewGeometry(size: size, stick: stick)+ let geometry = TouchPadPreviewGeometry(size: size, stick: stick, layout: layout)let home = TouchPadPreviewGeometry(size: size).stickCanvas { context, canvas inlet k = canvas.width / TouchPadPreviewGeometry.screen.widthcontext.scaleBy(x: k, y: k)// A moved stick leaves a dashed cream outline where it sits by default, so the move reads at a glance.if geometry.stick != home {- let r = 77 * geometry.u+ let r = geometry.geo.stickRcontext.stroke(Path(ellipseIn: CGRect(x: home.x - r, y: home.y - r, width: 2 * r, height: 2 * r)),with: .color(ShellPalette.cream.opacity(0.45)), style: StrokeStyle(lineWidth: 2, dash: [7, 6]))}- for shape in geometry.shapes { draw(shape, in: &context) }+ for shape in geometry.shapes { PadDrawing.draw(shape, in: &context) }}.aspectRatio(TouchPadPreviewGeometry.screen.width / TouchPadPreviewGeometry.screen.height, contentMode: .fit)- .background(- LinearGradient(colors: [Color(red: 0.20, green: 0.24, blue: 0.30), Color(red: 0.11, green: 0.13, blue: 0.12)], startPoint: .top, endPoint: .bottom)- )+ .background(PadDrawing.backdrop).clipShape(RoundedRectangle(cornerRadius: 22, style: .continuous)).overlay(RoundedRectangle(cornerRadius: 22, style: .continuous).strokeBorder(.white.opacity(0.14), lineWidth: 3))- .animation(.smooth(duration: 0.2), value: size + stick)+ .animation(.smooth(duration: 0.2), value: size + stick + layout.encoded).accessibilityElement().accessibilityLabel(ShellStrings.text("Preview of the touch controls")).accessibilityIdentifier("touch.preview")}+}++/// How the gamepad's controls look, for the previews: white keys of low opacity, a thin line, the labels.+enum PadDrawing {+ struct Style {+ var fill = Color.white.opacity(0.14), line = Color.white.opacity(0.38), text = Color.white.opacity(0.6), ring = Color.white.opacity(0.06)+ var lineWidth: CGFloat = 1.5+ }+ static let backdrop = LinearGradient(colors: [Color(red: 0.20, green: 0.24, blue: 0.30), Color(red: 0.11, green: 0.13, blue: 0.12)],+ startPoint: .top, endPoint: .bottom)++ /// The outline of a shape, for a highlight or the dashed place it came from.+ static func outline(_ shape: TouchPadPreviewGeometry.Shape) -> Path {+ switch shape {+ case .circle(let c, let r, _), .ring(let c, let r, _): Path(ellipseIn: CGRect(x: c.x - r, y: c.y - r, width: 2 * r, height: 2 * r))+ case .drop(let c, let r, let right, _): dropPath(c, r, right)+ case .pill(let rect, _): Path(roundedRect: rect, cornerRadius: rect.height / 2)+ case .dpad(let c, let r): dpadPath(c, r)+ }+ }++ static func dropPath(_ c: CGPoint, _ r: CGFloat, _ right: Bool) -> Path {+ let angle = right ? -Double.pi / 4 : -3 * Double.pi / 4, d = r * 1.45, th = acos(r / d)+ var p = Path()+ p.move(to: CGPoint(x: c.x + d * cos(angle), y: c.y + d * sin(angle)))+ p.addArc(center: c, radius: r, startAngle: .radians(angle + th), endAngle: .radians(angle - th + 2 * .pi), clockwise: false)+ p.closeSubpath()+ return p+ }- private static let fill = Color.white.opacity(0.14), line = Color.white.opacity(0.38), text = Color.white.opacity(0.6)+ static func dpadPath(_ c: CGPoint, _ r: CGFloat) -> Path {+ let w = r * 17 / 48, inner = r * 11 / 48+ var all = Path()+ for turn in 0..<4 {+ var p = Path()+ p.addLines([CGPoint(x: -w, y: -r), CGPoint(x: w, y: -r), CGPoint(x: w, y: -(inner + w)), CGPoint(x: 0, y: -inner), CGPoint(x: -w, y: -(inner + w))])+ p.closeSubpath()+ all.addPath(p.applying(CGAffineTransform(rotationAngle: CGFloat(turn) * .pi / 2).concatenating(CGAffineTransform(translationX: c.x, y: c.y))))+ }+ return all+ }- private func draw(_ shape: TouchPadPreviewGeometry.Shape, in context: inout GraphicsContext) {- func key(_ path: Path) { context.fill(path, with: .color(Self.fill)); context.stroke(path, with: .color(Self.line), lineWidth: 1.5) }+ static func draw(_ shape: TouchPadPreviewGeometry.Shape, in context: inout GraphicsContext, style: Style = Style()) {+ func key(_ path: Path) { context.fill(path, with: .color(style.fill)); context.stroke(path, with: .color(style.line), lineWidth: style.lineWidth) }func label(_ s: String, _ c: CGPoint, _ size: CGFloat) {- context.draw(Text(s).font(.system(size: size, weight: .semibold)).foregroundStyle(Self.text), at: c)+ context.draw(Text(verbatim: s).font(.system(size: size, weight: .semibold)).foregroundStyle(style.text), at: c)}switch shape {case .circle(let c, let r, let name):@@ -132,27 +145,17 @@ struct TouchControlsPreview: View {if let name { label(name, c, r * 0.75) }case .ring(let c, let r, let knob):let ring = Path(ellipseIn: CGRect(x: c.x - r, y: c.y - r, width: 2 * r, height: 2 * r))- context.fill(ring, with: .color(.white.opacity(0.06))); context.stroke(ring, with: .color(Self.line), lineWidth: 1.5)+ context.fill(ring, with: .color(style.ring)); context.stroke(ring, with: .color(style.line), lineWidth: style.lineWidth)key(Path(ellipseIn: CGRect(x: c.x - knob, y: c.y - knob, width: 2 * knob, height: 2 * knob)))case .drop(let c, let r, let right, let name):- let angle = right ? -Double.pi / 4 : -3 * Double.pi / 4, d = r * 1.45, th = acos(r / d)- var p = Path()- p.move(to: CGPoint(x: c.x + d * cos(angle), y: c.y + d * sin(angle)))- p.addArc(center: c, radius: r, startAngle: .radians(angle + th), endAngle: .radians(angle - th + 2 * .pi), clockwise: false)- p.closeSubpath()- key(p)+ key(dropPath(c, r, right))label(name, c, r * 0.62)case .pill(let rect, let name):key(Path(roundedRect: rect, cornerRadius: rect.height / 2))label(name, CGPoint(x: rect.midX, y: rect.midY), rect.height * 0.64)case .dpad(let c, let r):- let w = r * 17 / 48, inner = r * 11 / 48- for turn in 0..<4 {- var p = Path()- p.addLines([CGPoint(x: -w, y: -r), CGPoint(x: w, y: -r), CGPoint(x: w, y: -(inner + w)), CGPoint(x: 0, y: -inner), CGPoint(x: -w, y: -(inner + w))])- p.closeSubpath()- key(p.applying(CGAffineTransform(rotationAngle: CGFloat(turn) * .pi / 2).concatenating(CGAffineTransform(translationX: c.x, y: c.y))))- }+ key(dpadPath(c, r))}}}+diff --git a/frontend-ios/Sources/ShellUI/TouchLayout.swift b/frontend-ios/Sources/ShellUI/TouchLayout.swiftnew file mode 100644index 00000000..8c19ba10--- /dev/null+++ b/frontend-ios/Sources/ShellUI/TouchLayout.swift@@ -0,0 +1,111 @@+import Foundation++/// The player's arrangement of the touch controls (#414): for each layout, how far each moved control sits from its built-in place.+/// The shell keeps it and passes it to every game as one `DM_TOUCH_LAYOUT` value, which the engine reads in `DmPadGeometry.h`+/// (`dm_pad_layout_parse`): `1`, then per layout `;`, its name and `/control:dx,dy` per moved control, for example+/// `1;2d/face:0,-2/stick:1,-1;3d/a:-1,0`. A step is a quarter of a face key's width at the player's size, y grows downward.+/// The engine stores nothing and places a control only where it fits, so a value can never break the layout.+public struct TouchLayout: Equatable, Sendable {+ /// The layouts with an arrangement of their own: 2D and 3D over the picture (a phone, an iPad held sideways), and both again+ /// below the picture (an iPad held upright, iPhone Duo upright or half open). The raw values are the engine's names.+ public enum Kind: String, CaseIterable, Sendable {+ case twoD = "2d", threeD = "3d", twoDSplit = "2s", threeDSplit = "3s"+ public var full: Bool { self == .threeD || self == .threeDSplit }+ public var split: Bool { self == .twoDSplit || self == .threeDSplit }+ public static func of(full: Bool, split: Bool) -> Kind { split ? (full ? .threeDSplit : .twoDSplit) : (full ? .threeD : .twoD) }+ }++ /// The controls that move, in the engine's order (the order it places them). `face` is the whole diamond, `a b x y` one key of+ /// it, from where the diamond is. The layout button does not move.+ public enum Control: String, CaseIterable, Sendable {+ case face, a, b, x, y, stick, dpad, zl, l, zr, r, l3, r3, minus, plus+ /// Drawn in this layout (the D-pad, L3 and R3 only in 3D).+ public func drawn(full: Bool) -> Bool { full || ![.dpad, .l3, .r3].contains(self) }+ public var isFaceKey: Bool { [.a, .b, .x, .y].contains(self) }+ }++ public struct Offset: Equatable, Hashable, Sendable {+ public var dx: Int+ public var dy: Int+ public init(dx: Int = 0, dy: Int = 0) { self.dx = dx; self.dy = dy }+ public static let zero = Offset()+ public var isZero: Bool { dx == 0 && dy == 0 }+ }++ /// The engine's limits: a step is -64 to 64, a value at most 1024 characters.+ public static let maxStep = 64+ public static let maxLength = 1024++ private var offsets: [Kind: [Control: Offset]] = [:]++ public init() {}++ public subscript(kind: Kind, control: Control) -> Offset {+ get { offsets[kind]?[control] ?? .zero }+ set {+ let clamped = Offset(dx: min(Self.maxStep, max(-Self.maxStep, newValue.dx)), dy: min(Self.maxStep, max(-Self.maxStep, newValue.dy)))+ var set = offsets[kind] ?? [:]+ set[control] = clamped.isZero ? nil : clamped+ offsets[kind] = set.isEmpty ? nil : set+ }+ }++ public var isEmpty: Bool { offsets.isEmpty }+ public func isEmpty(_ kind: Kind) -> Bool { offsets[kind] == nil }+ /// Every control of one layout back to its built-in place.+ public mutating func reset(_ kind: Kind) { offsets[kind] = nil }+ /// The moved controls of one layout.+ public func moved(_ kind: Kind) -> [Control: Offset] { offsets[kind] ?? [:] }++ /// The value for `DM_TOUCH_LAYOUT`, empty when nothing is moved (the engine's built-in layout, nothing is passed).+ public var encoded: String {+ guard !offsets.isEmpty else { return "" }+ var out = "1"+ for kind in Kind.allCases {+ guard let set = offsets[kind] else { continue }+ out += ";" + kind.rawValue+ for control in Control.allCases { if let o = set[control] { out += "/\(control.rawValue):\(o.dx),\(o.dy)" } }+ }+ return out+ }++ /// Reads a value as the engine does: an unknown layout or control is skipped, anything else that is not the form, or longer+ /// than the engine reads, gives nil (the engine ignores it whole). Empty is the built-in layout.+ public init?(encoded value: String) {+ self.init()+ guard !value.isEmpty else { return }+ let bytes = Array(value.utf8)+ guard bytes.count <= Self.maxLength, bytes[0] == UInt8(ascii: "1"), bytes.count == 1 || bytes[1] == UInt8(ascii: ";") else { return nil }+ var i = 1+ func step() -> Int? {+ var sign = 1, v = 0, digits = 0+ if i < bytes.count, bytes[i] == UInt8(ascii: "-") { sign = -1; i += 1 }+ while i < bytes.count, (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(bytes[i]) {+ digits += 1+ if digits > 3 { return nil }+ v = v * 10 + Int(bytes[i] - UInt8(ascii: "0")); i += 1+ }+ return digits > 0 && v <= Self.maxStep ? sign * v : nil+ }+ while i < bytes.count, bytes[i] == UInt8(ascii: ";") {+ i += 1+ let nameStart = i+ while i < bytes.count, bytes[i] != UInt8(ascii: "/"), bytes[i] != UInt8(ascii: ";") { i += 1 }+ let kind = Kind(rawValue: String(decoding: bytes[nameStart..<i], as: UTF8.self))+ while i < bytes.count, bytes[i] == UInt8(ascii: "/") {+ i += 1+ let start = i+ while i < bytes.count, (UInt8(ascii: "a")...UInt8(ascii: "z")).contains(bytes[i]) || (UInt8(ascii: "0")...UInt8(ascii: "9")).contains(bytes[i]) { i += 1 }+ guard i > start, i < bytes.count, bytes[i] == UInt8(ascii: ":") else { return nil }+ let name = String(decoding: bytes[start..<i], as: UTF8.self)+ i += 1+ guard let dx = step(), i < bytes.count, bytes[i] == UInt8(ascii: ",") else { return nil }+ i += 1+ guard let dy = step() else { return nil }+ if let kind, let control = Control(rawValue: name) { self[kind, control] = Offset(dx: dx, dy: dy) }+ }+ if i < bytes.count, bytes[i] != UInt8(ascii: ";") { return nil }+ }+ if i < bytes.count { return nil }+ }+}diff --git a/frontend-ios/Sources/ShellUI/TouchLayoutEditing.swift b/frontend-ios/Sources/ShellUI/TouchLayoutEditing.swiftnew file mode 100644index 00000000..0626de4f--- /dev/null+++ b/frontend-ios/Sources/ShellUI/TouchLayoutEditing.swift@@ -0,0 +1,126 @@+import CoreGraphics+import Foundation++/// The layout editor's rules, pure so the tests drive them (#414): one layout of the player's arrangement on one screen. A move is+/// kept only when the engine places the control there (`PadGeo`, the copy of `DmPadGeometry.h`) and every other control stays where it+/// was, so what the editor shows is what the game draws, and a rejected spot leaves the layout as it was.+struct TouchLayoutEditing: Equatable {+ typealias Control = TouchLayout.Control+ typealias Offset = TouchLayout.Offset++ var layout: TouchLayout+ var kind: TouchLayout.Kind+ /// The screen of this layout: the device held sideways for 2D and 3D, held upright for the split ones.+ var screen: PadScreen+ var size = "medium"+ var stick = "corner"+ /// A B X Y move as one diamond. Off, each key moves on its own (the engine keeps the diamond for a key that does not fit).+ var together = true++ func geometry(_ l: TouchLayout) -> PadGeo { PadGeo.make(screen, full: kind.full, size: size, stick: stick, layout: l) }+ var geo: PadGeo { geometry(layout) }++ /// The control a touch on `c` moves: the whole diamond while its keys move together.+ func mover(_ c: Control) -> Control { together && c.isFaceKey ? .face : c }+ func offset(_ c: Control) -> Offset { layout[kind, c] }+ /// Away from its built-in place: a key also when the diamond moved.+ func isMoved(_ c: Control) -> Bool { !offset(c).isZero || (c.isFaceKey && !offset(.face).isZero) || (c == .face && Control.allCases.contains { $0.isFaceKey && !offset($0).isZero }) }++ /// The controls whose place a move of `c` may change: `c` itself, and the four keys when the diamond moves.+ private func follows(_ other: Control, _ c: Control) -> Bool { other == c || (c == .face && other.isFaceKey) }++ /// The arrangement with `c` at `o`, when the engine puts it there and leaves every other control where it is. nil: rejected.+ func trying(_ c: Control, _ o: Offset) -> TouchLayout? {+ var l = layout+ l[kind, c] = o+ let before = geo, after = geometry(l)+ if !o.isZero && !after.moved.contains(c) { return nil }+ // No other control may lose its place, a key of the diamond included.+ if !after.dropped.subtracting(before.dropped).isEmpty { return nil }+ for other in Control.allCases where other.drawn(full: kind.full) && !follows(other, c) {+ if !Self.same(before.anchor(other), after.anchor(other)) { return nil }+ }+ return normalized(l, c)+ }+ static func same(_ a: CGPoint, _ b: CGPoint) -> Bool { abs(a.x - b.x) < 0.01 && abs(a.y - b.y) < 0.01 }++ /// A control dragged past the edge stops at the edge (the engine pushes it back in). Its offset is then kept one step past the+ /// edge at most, so the first step back moves it.+ private func normalized(_ l: TouchLayout, _ c: Control) -> TouchLayout {+ let g = geometry(l), o = l[kind, c]+ var zero = l; zero[kind, c] = .zero+ let base = geometry(zero).anchor(c), at = g.anchor(c), step = g.step+ func axis(_ want: Int, _ b: CGFloat, _ a: CGFloat) -> Int {+ let target = b + CGFloat(want) * step+ if abs(target - a) < 0.01 { return want }+ let q = (a - b) / step+ return target > a ? Int(ceil(q - 1e-6)) : Int(floor(q + 1e-6))+ }+ let n = Offset(dx: axis(o.dx, base.x, at.x), dy: axis(o.dy, base.y, at.y))+ guard n != o else { return l }+ var m = l+ m[kind, c] = n+ let mg = geometry(m)+ return Control.allCases.allSatisfy { Self.same(mg.anchor($0), g.anchor($0)) } && mg.dropped == g.dropped ? m : l+ }++ /// The offset a drag by `translation` (in the screen's points) from `start` asks for, snapped to whole steps.+ func dragged(from start: Offset, by translation: CGSize) -> Offset {+ let step = geo.step+ return Offset(dx: start.dx + Int((translation.width / step).rounded()), dy: start.dy + Int((translation.height / step).rounded()))+ }++ enum Outcome: Equatable { case moved, atEdge, rejected }+ /// One step of `c` in a direction, from the arrows, a controller or VoiceOver.+ mutating func nudge(_ c: Control, dx: Int, dy: Int) -> Outcome {+ let m = mover(c)+ var o = offset(m)+ o.dx += dx; o.dy += dy+ guard let l = trying(m, o) else { return .rejected }+ if Self.same(geometry(l).anchor(m), geo.anchor(m)) { return .atEdge }+ layout = l+ return .moved+ }+ /// A drag's spot: kept when the engine takes it.+ mutating func place(_ c: Control, _ o: Offset) -> Bool {+ let m = mover(c)+ if o == offset(m) { return true }+ guard let l = trying(m, o) else { return false }+ layout = l+ return true+ }++ /// `c` back to its built-in place (with the diamond: its keys too). A control another one now covers that place for goes back as well,+ /// and offsets the engine does not use on this screen are dropped, so the stored value says what the game shows.+ mutating func putBack(_ c: Control) {+ let m = mover(c)+ layout[kind, m] = .zero+ if m == .face { for k in Control.allCases where k.isFaceKey { layout[kind, k] = .zero } }+ prune()+ }+ /// Every control of this layout back to its built-in place.+ mutating func reset() { layout.reset(kind) }++ /// Forgets the offsets of controls the engine keeps at their place on this screen.+ mutating func prune() {+ let g = geo+ for c in g.dropped { layout[kind, c] = .zero }+ }++ /// Where control `c` may go: the safe area, or for the bottom corners the area reaching halfway into the side insets.+ func allowedArea(_ c: Control) -> CGRect? { geo.box(of: mover(c) == .face ? .face : c)?.within }++ /// The drawn control at a point of the screen, the nearest within `slop` points of its shape.+ func control(at p: CGPoint, slop: CGFloat) -> Control? {+ let g = geo+ var best: (Control, CGFloat)?+ for c in g.drawnControls {+ guard let (box, _) = g.box(of: c) else { continue }+ let grown = box.insetBy(dx: -slop, dy: -slop)+ guard grown.contains(p) else { continue }+ let d = hypot(p.x - g.anchor(c).x, p.y - g.anchor(c).y)+ if best == nil || d < best!.1 { best = (c, d) }+ }+ return best?.0+ }+}diff --git a/frontend-ios/Sources/ShellUI/TouchLayoutEditorModel.swift b/frontend-ios/Sources/ShellUI/TouchLayoutEditorModel.swiftnew file mode 100644index 00000000..4c40ee0f--- /dev/null+++ b/frontend-ios/Sources/ShellUI/TouchLayoutEditorModel.swift@@ -0,0 +1,161 @@+import Observation+import SwiftUI+#if os(iOS)+import UIKit+#endif++/// The layout editor's state while it is open (#414): which layout, which control is chosen, whether a controller holds it, and the+/// feedback of the last move. The library owns it, so a controller's D-pad moves a held control instead of the focus. Every kept move+/// goes to the shell settings at once (`ShellSettingsStore.storeTouchLayout`), so the next game start gets it.+@MainActor @Observable final class TouchLayoutEditorModel {+ typealias Control = TouchLayout.Control++ @ObservationIgnored let store: ShellSettingsStore+ /// The device held sideways, and upright where the controls can sit below the picture (an iPad, iPhone Duo), else nil.+ let sideways: PadScreen+ let upright: PadScreen?+ private(set) var editing: TouchLayoutEditing+ /// The control the arrows and VoiceOver's actions move.+ var selected: Control?+ /// A controller or keyboard holds the selected control: the D-pad moves it, A or B puts it down.+ private(set) var held = false+ /// Counts the kept steps and the rejected spots, for the haptics.+ private(set) var stepCount = 0+ private(set) var rejectCount = 0+ /// The last move had no room: the line under the preview says so until the next move.+ private(set) var rejected = false++ init(store: ShellSettingsStore = .current, sideways: PadScreen = .proMax, upright: PadScreen? = nil, kind: TouchLayout.Kind = .threeD) {+ self.store = store+ self.sideways = sideways+ self.upright = upright+ let k = upright == nil && kind.split ? TouchLayout.Kind.of(full: kind.full, split: false) : kind+ editing = TouchLayoutEditing(layout: store.touchLayout, kind: k, screen: k.split ? (upright ?? sideways) : sideways,+ size: store.touchSize, stick: store.touchStick)+ }++ var kind: TouchLayout.Kind { editing.kind }+ var geo: PadGeo { editing.geo }+ var together: Bool { editing.together }+ var layoutIsBuiltIn: Bool { editing.layout.isEmpty(editing.kind) }++ func setKind(_ kind: TouchLayout.Kind) {+ guard kind != editing.kind, !kind.split || upright != nil else { return }+ editing.kind = kind+ editing.screen = kind.split ? (upright ?? sideways) : sideways+ if let s = selected, !s.drawn(full: kind.full) { selected = nil }+ held = false; rejected = false+ }+ func setTogether(_ on: Bool) {+ editing.together = on+ rejected = false+ }++ func select(_ c: Control?) {+ selected = c+ rejected = false+ if c == nil { held = false }+ }+ /// A controller's A on a control: it is held until A or B puts it down.+ func pickUp(_ c: Control) { selected = c; held = true; rejected = false }+ func putDown() { held = false }++ /// One step of the chosen control. Reports the outcome for VoiceOver.+ @discardableResult func nudge(dx: Int, dy: Int) -> TouchLayoutEditing.Outcome? {+ guard let c = selected else { return nil }+ let outcome = editing.nudge(c, dx: dx, dy: dy)+ switch outcome {+ case .moved: stepCount += 1; rejected = false; save()+ case .rejected: rejectCount += 1; rejected = true+ case .atEdge: rejectCount += 1; rejected = false+ }+ return outcome+ }+ func nudge(_ action: ShellInput.Action) {+ switch action {+ case .left: nudge(dx: -1, dy: 0)+ case .right: nudge(dx: 1, dy: 0)+ case .up: nudge(dx: 0, dy: -1)+ case .down: nudge(dx: 0, dy: 1)+ default: break+ }+ }++ /// A drag: the offset of the control it holds, as asked so far. Kept spots are drawn at once and saved when the drag ends.+ func dragOffset(_ c: Control) -> TouchLayout.Offset { editing.offset(editing.mover(c)) }+ func dragTo(_ c: Control, from start: TouchLayout.Offset, by translation: CGSize) -> (offset: TouchLayout.Offset, kept: Bool) {+ let o = editing.dragged(from: start, by: translation)+ let before = editing.offset(editing.mover(c))+ let kept = editing.place(c, o)+ if kept && editing.offset(editing.mover(c)) != before { stepCount += 1 }+ return (o, kept)+ }+ /// The end of a drag: a rejected spot sends the control back (the view animates it) and says so.+ func dragEnded(rejected spot: Bool) {+ if spot { rejectCount += 1; rejected = true } else { rejected = false }+ save()+ }++ func putBack() {+ guard let c = selected else { return }+ editing.putBack(c)+ rejected = false+ save()+ }+ /// Every control of the shown layout back to its built-in place.+ func reset() {+ editing.reset()+ rejected = false+ save()+ }++ private func save() { store.storeTouchLayout(editing.layout) }+}++extension TouchLayoutEditorModel {+ /// The editor for this device, opened on the 3D layout (every control shows) held sideways.+ static func forDevice(window: CGSize, insets: EdgeInsets, store: ShellSettingsStore = .current) -> TouchLayoutEditorModel {+ #if os(iOS)+ let screens = TouchLayoutScreens.device(window: window, insets: insets, isPad: UIDevice.current.userInterfaceIdiom == .pad)+ #else+ let screens = (sideways: PadScreen.proMax, upright: PadScreen?.none)+ #endif+ return TouchLayoutEditorModel(store: store, sideways: screens.sideways, upright: screens.upright)+ }++ /// A change of one of the editor's rows from the list of choices (a row too narrow for its segments).+ func apply(row id: String, value: String) {+ switch id {+ case TouchLayoutEditorView.layoutRow: setKind(.of(full: value == "3d", split: kind.split))+ case TouchLayoutEditorView.poseRow: setKind(.of(full: kind.full, split: value == "below"))+ case TouchLayoutEditorView.togetherRow: setTogether(value == "1")+ default: break+ }+ }+}++/// The game's screen on this device, for the editor: the shell's window (on a phone the screen) held sideways, and upright where a+/// game puts the controls below the picture (an iPad, and a foldable's inner display, which is about 1.4 to 1 where a phone is above 2+/// to 1). The side insets of a phone held sideways are its top inset upright (the Dynamic Island or the notch), and the home indicator+/// takes 21 points. An approximation for the preview: the engine places the controls on the real screen.+enum TouchLayoutScreens {+ static func device(window: CGSize, insets: EdgeInsets, isPad: Bool) -> (sideways: PadScreen, upright: PadScreen?) {+ let long = max(window.width, window.height), short = min(window.width, window.height)+ guard long > 0, short > 0 else { return (.proMax, nil) }+ if isPad {+ let i = PadScreen.Insets(top: 24, bottom: 20)+ return (PadScreen(size: CGSize(width: long, height: short), insets: i), PadScreen(size: CGSize(width: short, height: long), insets: i))+ }+ let upright = window.height > window.width+ let island = upright ? insets.top : max(insets.leading, insets.trailing)+ let home: CGFloat = insets.bottom > 0 ? 21 : 0+ let side = island > 30 ? island : 0+ let sideways = PadScreen(size: CGSize(width: long, height: short), insets: PadScreen.Insets(left: side, bottom: home, right: side))+ guard long / short < 1.7 else { return (sideways, nil) }+ // A foldable's inner display upright: the fold across the middle, the picture above it keeps only the top inset.+ let fold = CGRect(x: 0, y: long / 2 - 20, width: short, height: 40)+ let top = upright ? insets.top : max(insets.leading, insets.trailing)+ return (sideways, PadScreen(size: CGSize(width: short, height: long), insets: PadScreen.Insets(top: top, bottom: insets.bottom > 0 ? 34 : 0),+ division: fold, topSafeOnly: true))+ }+}diff --git a/frontend-ios/Sources/ShellUI/TouchLayoutEditorView.swift b/frontend-ios/Sources/ShellUI/TouchLayoutEditorView.swiftnew file mode 100644index 00000000..bdec51dd--- /dev/null+++ b/frontend-ios/Sources/ShellUI/TouchLayoutEditorView.swift@@ -0,0 +1,440 @@+import SwiftUI++/// The touch controls' layout editor (#414), a screen of the shell settings: the controls of one layout drawn as the game draws them, on+/// this device's screen at its own proportions. Drag a control and it snaps to steps of a quarter key. Where it would cover another+/// control or leave its area it turns red and goes back when let go. The area it may use shows while it is chosen. A chosen control also+/// moves step by step with the arrows, a controller (A picks it up, the D-pad moves it, A or B puts it down) or VoiceOver's actions.+/// Put back and Reset return one control or the whole layout to the built-in places. The engine places every control again on the+/// device, so nothing the editor stores can break a game's layout.+struct TouchLayoutEditorView: View {+ @Bindable var model: TouchLayoutEditorModel+ var close: () -> Void+ @Environment(\.shellFocus) private var focus+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ /// The drag in progress: the control, where its offset started, and the spot drawn under the finger when the engine refuses it.+ @State private var drag: DragState?+ @State private var bounce: CGSize = .zero++ private struct DragState: Equatable {+ var control: TouchLayout.Control+ var start: TouchLayout.Offset+ var refused: TouchLayout.Offset?+ var travelled: CGFloat = 0+ }++ /// The width of each button role, the same in every language (the longest label fits at the type's size).+ static let buttonWidth: CGFloat = 148+ static let arrowSize: CGFloat = 52++ var body: some View {+ GeometryReader { proxy in+ // Held sideways the preview takes the room the column beside it leaves: on a phone it is then nearly as large as the game.+ let wide = proxy.size.width > proxy.size.height * 1.1 && proxy.size.width >= 640+ if wide {+ let column: CGFloat = 340, aspect = screen.size.width / screen.size.height+ let w = max(200, min(proxy.size.width - column - 22 - 40, (proxy.size.height - 32 - 70) * aspect))+ HStack(alignment: .top, spacing: 22) {+ // The preview, and under it what is chosen with the buttons that act on it.+ VStack(alignment: .leading, spacing: 14) {+ canvas.frame(width: w, height: w / aspect)+ HStack(alignment: .center, spacing: 10) { status; buttons }+ }+ .padding(.vertical, 16)+ ScrollView {+ VStack(alignment: .leading, spacing: 16) { header; pickers; panel(compact: true) }.padding(.vertical, 16)+ }+ .scrollIndicators(.hidden)+ .frame(width: column)+ }+ .padding(.horizontal, 20)+ .frame(maxWidth: .infinity)+ } else {+ ScrollView {+ VStack(alignment: .leading, spacing: 18) {+ header+ pickers+ canvas+ if !model.kind.split && proxy.size.width < 560 {+ Label(ShellStrings.text("Turn the phone sideways for a larger preview."), systemImage: "rotate.right")+ .shellType(ShellType.note).foregroundStyle(.white.opacity(0.55))+ }+ panel(compact: false)+ }+ .padding(.horizontal, 24).padding(.vertical, 20)+ .frame(maxWidth: 640).frame(maxWidth: .infinity)+ }+ .scrollIndicators(.hidden)+ .scrollDisabled(drag != nil)+ }+ }+ .foregroundStyle(.white).preferredColorScheme(.dark)+ .sensoryFeedback(.selection, trigger: model.stepCount)+ .sensoryFeedback(.warning, trigger: model.rejectCount)+ }++ // MARK: Header and pickers++ private var header: some View {+ HStack(alignment: .center) {+ Text(ShellStrings.text("Arrange controls")).shellType(ShellType.pageTitle)+ .lineLimit(1).minimumScaleFactor(0.7).accessibilityAddTraits(.isHeader)+ Spacer(minLength: 8)+ Button(action: close) { Text(ShellStrings.text("Done")) }+ .buttonStyle(ChipButtonStyle())+ .accessibilityIdentifier("touchLayout.done")+ .shellTarget("lay.done", radius: 22, action: close)+ }+ }++ /// The rows report to the editor, not to a game or the shell settings (LibraryView.pickChoice).+ static let gameID = "touchLayout"+ static let layoutRow = "lay.layout", poseRow = "lay.pose", togetherRow = "lay.together"++ private var pickers: some View {+ VStack(alignment: .leading, spacing: 12) {+ let layoutRow = SettingRow(id: Self.layoutRow, label: ShellStrings.text("Layout"),+ kind: .choice([SettingOption("2d", "2D"), SettingOption("3d", "3D")]),+ value: model.kind.full ? "3d" : "2d")+ SettingControl(gameID: Self.gameID, row: layoutRow, targetPrefix: "lay.row.") { value in+ model.setKind(.of(full: value == "3d", split: model.kind.split))+ }.equatable()+ if model.upright != nil {+ let poseRow = SettingRow(id: Self.poseRow, label: ShellStrings.text("Screen"),+ kind: .choice([SettingOption("over", ShellStrings.text("Over the picture")),+ SettingOption("below", ShellStrings.text("Below the picture"))]),+ value: model.kind.split ? "below" : "over")+ SettingControl(gameID: Self.gameID, row: poseRow, targetPrefix: "lay.row.") { value in+ model.setKind(.of(full: model.kind.full, split: value == "below"))+ }.equatable()+ }+ }+ }++ // MARK: The preview++ private var screen: PadScreen { model.editing.screen }++ private var canvas: some View {+ let g = model.geo+ let active = drag?.control ?? model.selected+ return GeometryReader { proxy in+ let k = proxy.size.width / screen.size.width+ ZStack(alignment: .topLeading) {+ Canvas { context, _ in+ context.scaleBy(x: k, y: k)+ drawBackdrop(g, in: &context)+ if let active { drawGuides(for: active, g, k: k, in: &context) }+ for c in g.drawnControls where !isActive(c, active) { draw(c, g, in: &context) }+ }+ if let active {+ Canvas { context, _ in+ context.scaleBy(x: k, y: k)+ for c in g.drawnControls where isActive(c, active) { draw(c, g, highlight: drag?.refused == nil ? .chosen : .refused, in: &context) }+ }+ .offset(x: activeOffset(g).width * k, y: activeOffset(g).height * k)+ .allowsHitTesting(false)+ }+ accessibilityElements(g, k: k)+ }+ .contentShape(Rectangle())+ .gesture(dragGesture(k: k))+ }+ .aspectRatio(screen.size.width / screen.size.height, contentMode: .fit)+ .background(PadDrawing.backdrop)+ .clipShape(RoundedRectangle(cornerRadius: 22, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 22, style: .continuous).strokeBorder(.white.opacity(0.14), lineWidth: 3))+ .accessibilityElement(children: .contain)+ .accessibilityLabel(ShellStrings.text("Preview of the touch controls"))+ .accessibilityIdentifier("touchLayout.preview")+ }++ /// Where the active control is drawn beyond its kept place: under the finger on a refused spot, or on its way back.+ private func activeOffset(_ g: PadGeo) -> CGSize {+ if let drag, let refused = drag.refused {+ let kept = model.dragOffset(drag.control)+ return CGSize(width: CGFloat(refused.dx - kept.dx) * g.step + bounce.width, height: CGFloat(refused.dy - kept.dy) * g.step + bounce.height)+ }+ return bounce+ }++ /// The active control and the controls that move with it: the diamond's keys while they move together.+ private func isActive(_ c: TouchLayout.Control, _ active: TouchLayout.Control?) -> Bool {+ guard let active else { return false }+ return model.editing.mover(c) == model.editing.mover(active)+ }++ private func drawBackdrop(_ g: PadGeo, in context: inout GraphicsContext) {+ // The picture: the whole screen over which the controls float, or its own area above the controls on a split screen.+ let picture = g.region.separated ? g.region.game : g.region.game.intersection(CGRect(origin: .zero, size: screen.size))+ context.fill(Path(roundedRect: picture, cornerRadius: 10), with: .color(.white.opacity(g.region.separated ? 0.07 : 0.03)))+ if g.region.separated {+ context.fill(Path(g.region.controls), with: .color(.black.opacity(0.18)))+ }+ }++ private func drawGuides(for active: TouchLayout.Control, _ g: PadGeo, k: CGFloat, in context: inout GraphicsContext) {+ let m = model.editing.mover(active)+ // The area it may use: a calm cream tint with a dashed edge.+ if let area = model.editing.allowedArea(active) {+ let path = Path(roundedRect: area.insetBy(dx: 1, dy: 1), cornerRadius: 14)+ context.fill(path, with: .color(ShellPalette.cream.opacity(0.06)))+ context.stroke(path, with: .color(ShellPalette.cream.opacity(0.55)), style: StrokeStyle(lineWidth: 1.5 / k, dash: [8 / k, 6 / k]))+ }+ // Its built-in place, dashed, once it has moved.+ if model.editing.isMoved(m) {+ var built = model.editing+ built.putBack(m)+ let home = built.geo+ for c in home.drawnControls where model.editing.mover(c) == m {+ for shape in Self.shapes(c, home) {+ context.stroke(PadDrawing.outline(shape), with: .color(ShellPalette.cream.opacity(0.5)), style: StrokeStyle(lineWidth: 1.5 / k, dash: [5 / k, 5 / k]))+ }+ }+ }+ }++ private enum Highlight { case none, chosen, refused }++ private func draw(_ c: TouchLayout.Control, _ g: PadGeo, highlight: Highlight = .none, in context: inout GraphicsContext) {+ var style = PadDrawing.Style()+ switch highlight {+ case .none: break+ case .chosen:+ style.fill = ShellPalette.cream.opacity(model.held ? 0.42 : 0.26); style.line = ShellPalette.cream; style.text = .white; style.lineWidth = 2.5+ case .refused:+ style.fill = DeleteStyle.red.opacity(0.32); style.line = DeleteStyle.red; style.text = .white; style.lineWidth = 2.5+ }+ for shape in Self.shapes(c, g) { PadDrawing.draw(shape, in: &context, style: style) }+ }++ /// The drawn shapes of one control, in the gamepad's look.+ static func shapes(_ c: TouchLayout.Control, _ g: PadGeo) -> [TouchPadPreviewGeometry.Shape] {+ switch c {+ case .face: (0..<4).map { .circle(g.faceKey[$0], g.faceR, label: ["A", "B", "X", "Y"][$0]) }+ case .a: [.circle(g.faceKey[0], g.faceR, label: "A")]+ case .b: [.circle(g.faceKey[1], g.faceR, label: "B")]+ case .x: [.circle(g.faceKey[2], g.faceR, label: "X")]+ case .y: [.circle(g.faceKey[3], g.faceR, label: "Y")]+ case .stick: [.ring(g.stick, g.stickR, knob: g.knobR)]+ case .dpad: [.dpad(g.dpad, g.dpadR)]+ case .zl, .l, .zr, .r:+ [.drop(g.drop[PadGeo.dropIndex(c)], g.dropR[PadGeo.dropIndex(c)], tipRight: c == .zr || c == .r, label: c.title)]+ case .l3: [.circle(g.click[0], g.clickR, label: "L3")]+ case .r3: [.circle(g.click[1], g.clickR, label: "R3")]+ case .minus: [.pill(g.pill[0], label: "−")]+ case .plus: [.pill(g.pill[1], label: "+")]+ }+ }++ // MARK: Touch++ private func dragGesture(k: CGFloat) -> some Gesture {+ DragGesture(minimumDistance: 0, coordinateSpace: .local)+ .onChanged { value in+ let t = CGSize(width: value.translation.width / k, height: value.translation.height / k)+ if drag == nil {+ let start = CGPoint(x: value.startLocation.x / k, y: value.startLocation.y / k)+ // A finger is wider than a key in a small preview: anything within about 22 points of the screen counts.+ guard let c = model.editing.control(at: start, slop: max(22 / k, 6)) else { return }+ bounce = .zero+ model.select(c)+ drag = DragState(control: c, start: model.dragOffset(c))+ }+ guard var d = drag else { return }+ d.travelled = max(d.travelled, hypot(value.translation.width, value.translation.height))+ if d.travelled < 4 { drag = d; return } // a tap chooses the control and moves nothing+ let result = model.dragTo(d.control, from: d.start, by: t)+ d.refused = result.kept ? nil : result.offset+ drag = d+ }+ .onEnded { _ in+ guard let d = drag else { model.select(nil); return }+ if let refused = d.refused {+ // Back to its kept place, from under the finger.+ let g = model.geo, kept = model.dragOffset(d.control)+ bounce = CGSize(width: CGFloat(refused.dx - kept.dx) * g.step, height: CGFloat(refused.dy - kept.dy) * g.step)+ drag = nil+ withAnimation(reduceMotion ? nil : .spring(duration: 0.35, bounce: 0.25)) { bounce = .zero }+ model.dragEnded(rejected: true)+ } else {+ drag = nil+ if d.travelled >= 4 { model.dragEnded(rejected: false) }+ }+ }+ }++ // MARK: VoiceOver and the controller++ /// One element per control over the picture: VoiceOver names it and moves it with its actions, a controller focuses it (A picks it+ /// up). They take no touches, the drag above does.+ private func accessibilityElements(_ g: PadGeo, k: CGFloat) -> some View {+ let controls = model.together ? [TouchLayout.Control.face] + g.drawnControls.filter { !$0.isFaceKey } : g.drawnControls+ return ForEach(controls, id: \.self) { c in+ let box = g.box(of: c)?.box ?? .zero+ Color.clear+ .frame(width: max(box.width * k, 30), height: max(box.height * k, 30))+ .position(x: box.midX * k, y: box.midY * k)+ .accessibilityElement()+ .accessibilityLabel(c.title)+ .accessibilityValue(ShellStrings.text(model.editing.isMoved(c) ? "Moved" : "In its place"))+ .accessibilityAddTraits(model.selected.map { model.editing.mover($0) == c } == true ? [.isButton, .isSelected] : .isButton)+ .accessibilityAction { model.select(c) }+ .accessibilityAction(named: ShellStrings.text("Move up")) { voiceOverMove(c, 0, -1) }+ .accessibilityAction(named: ShellStrings.text("Move down")) { voiceOverMove(c, 0, 1) }+ .accessibilityAction(named: ShellStrings.text("Move left")) { voiceOverMove(c, -1, 0) }+ .accessibilityAction(named: ShellStrings.text("Move right")) { voiceOverMove(c, 1, 0) }+ .accessibilityAction(named: ShellStrings.text("Put back")) { model.select(c); model.putBack() }+ .shellTarget("lay.ctl.\(c.rawValue)", radius: max(box.width, box.height) * k / 2) { model.pickUp(c) }+ .allowsHitTesting(false)+ }+ }++ private func voiceOverMove(_ c: TouchLayout.Control, _ dx: Int, _ dy: Int) {+ model.select(c)+ let outcome = model.nudge(dx: dx, dy: dy)+ let text = outcome == .moved ? ShellStrings.text("Moved") : outcome == .atEdge ? ShellStrings.text("At the edge") : ShellStrings.text("No room there")+ AccessibilityNotification.Announcement(text).post()+ }++ // MARK: The panel++ /// The arrows, the diamond's switch and the note. compact: the status and the buttons sit under the preview instead.+ private func panel(compact: Bool) -> some View {+ VStack(alignment: .leading, spacing: 16) {+ if compact {+ arrows.frame(maxWidth: .infinity)+ } else {+ status+ // The arrows with the two buttons beside them, or below them side by side, or below them stacked: whatever the width holds.+ ViewThatFits(in: .horizontal) {+ HStack(alignment: .center, spacing: 18) { arrows; VStack(alignment: .leading, spacing: 10) { buttons } }+ VStack(alignment: .leading, spacing: 14) { arrows; HStack(spacing: 10) { buttons } }+ VStack(alignment: .leading, spacing: 14) { arrows; VStack(alignment: .leading, spacing: 10) { buttons } }+ }+ }+ let together = SettingRow(id: Self.togetherRow, label: ShellStrings.text("Move A B X Y together"),+ kind: .toggle(on: "1", off: "0"), value: model.together ? "1" : "0")+ SettingControl(gameID: Self.gameID, row: together, targetPrefix: "lay.row.") { model.setTogether($0 == "1") }+ .equatable()+ Text(ShellStrings.text("Drag a control to move it. Tap one to choose it, then move it step by step with the arrows. Where a control would cover another or leave the screen, it goes back. For every game."))+ .shellType(ShellType.note).foregroundStyle(.white.opacity(0.5)).fixedSize(horizontal: false, vertical: true)+ }+ .shellCard()+ }++ /// Put back (the chosen control) and Reset (the shown layout), each of the same fixed width in every language.+ @ViewBuilder private var buttons: some View {+ Button(ShellStrings.text("Put back")) { model.putBack() }+ .buttonStyle(ShellButtonStyle(fills: true)).frame(width: Self.buttonWidth)+ .disabled(model.selected.map { !model.editing.isMoved($0) } ?? true)+ .accessibilityIdentifier("touchLayout.putBack")+ .shellTarget("lay.putBack", enabled: model.selected.map { model.editing.isMoved($0) } ?? false) { model.putBack() }+ Button(ShellStrings.text("Reset")) { model.reset() }+ .buttonStyle(ShellButtonStyle(fills: true, destructive: true)).frame(width: Self.buttonWidth)+ .disabled(model.layoutIsBuiltIn)+ .accessibilityLabel(ShellStrings.text("Reset this layout"))+ .accessibilityIdentifier("touchLayout.reset")+ .shellTarget("lay.reset", enabled: !model.layoutIsBuiltIn) { model.reset() }+ }++ /// The chosen control and what to do next, or why it went back.+ private var status: some View {+ VStack(alignment: .leading, spacing: 4) {+ if let c = model.selected {+ let m = model.editing.mover(c)+ Text(m.title).shellType(ShellType.cardTitle)+ Text(model.rejected ? ShellStrings.text("No room there. It went back to where it was.")+ : model.held ? ShellStrings.text("Move it with the D-pad. A or B puts it down.")+ : ShellStrings.text(model.editing.isMoved(m) ? "Moved" : "In its place"))+ .shellType(ShellType.note)+ .foregroundStyle(model.rejected ? DeleteStyle.red : .white.opacity(0.6))+ } else {+ Text(ShellStrings.text("Choose a control")).shellType(ShellType.cardTitle)+ Text(model.rejected ? ShellStrings.text("No room there. It went back to where it was.") : ShellStrings.text("Tap a control in the picture."))+ .shellType(ShellType.note).foregroundStyle(model.rejected ? DeleteStyle.red : .white.opacity(0.6))+ }+ }+ .frame(maxWidth: .infinity, minHeight: 44, alignment: .leading)+ .accessibilityElement(children: .combine)+ .accessibilityIdentifier("touchLayout.status")+ }++ /// Four arrows in a cross: one step of the chosen control each.+ private var arrows: some View {+ let enabled = model.selected != nil+ return Grid(horizontalSpacing: 6, verticalSpacing: 6) {+ GridRow { Color.clear.frame(width: Self.arrowSize, height: Self.arrowSize); arrow("chevron.up", "Move up", "up", 0, -1); Color.clear.frame(width: Self.arrowSize, height: Self.arrowSize) }+ GridRow { arrow("chevron.left", "Move left", "left", -1, 0); Color.clear.frame(width: Self.arrowSize, height: Self.arrowSize); arrow("chevron.right", "Move right", "right", 1, 0) }+ GridRow { Color.clear.frame(width: Self.arrowSize, height: Self.arrowSize); arrow("chevron.down", "Move down", "down", 0, 1); Color.clear.frame(width: Self.arrowSize, height: Self.arrowSize) }+ }+ .disabled(!enabled)+ }++ private func arrow(_ symbol: String, _ label: String.LocalizationValue, _ id: String, _ dx: Int, _ dy: Int) -> some View {+ Button { model.nudge(dx: dx, dy: dy) } label: {+ Image(systemName: symbol).font(.system(size: 18, weight: .semibold)).frame(width: Self.arrowSize, height: Self.arrowSize)+ }+ .buttonStyle(RoundIconButtonStyle(size: Self.arrowSize))+ .opacity(model.selected == nil ? 0.4 : 1)+ .buttonRepeatBehavior(.enabled)+ .accessibilityLabel(ShellStrings.text(label))+ .accessibilityIdentifier("touchLayout.\(id)")+ .shellTarget("lay.arrow.\(id)", enabled: model.selected != nil, radius: Self.arrowSize / 2) { model.nudge(dx: dx, dy: dy) }+ }+}++/// The Arrangement row of the shell settings' Touch controls group: whether the controls are where they are built in, and the button+/// that opens the editor.+struct TouchArrangeRow: View {+ var arranged: Bool+ @Environment(\.shellOpenTouchLayout) private var open+ var body: some View {+ HStack(alignment: .center, spacing: 12) {+ VStack(alignment: .leading, spacing: 3) {+ Text(ShellStrings.text("Arrangement")).shellType(ShellType.settingLabel)+ Text(ShellStrings.text(arranged ? "Your own" : "Built in")).shellType(ShellType.note).foregroundStyle(.white.opacity(0.5))+ }+ .accessibilityElement(children: .combine)+ Spacer(minLength: 8)+ Button(ShellStrings.text("Arrange…")) { open?() }+ .buttonStyle(ShellButtonStyle(fills: true)).frame(width: TouchLayoutEditorView.buttonWidth)+ .accessibilityIdentifier("shellSettings.arrange")+ .accessibilityHint(ShellStrings.text("Move single controls where your thumbs want them."))+ .shellTarget("shs.arrange") { open?() }+ }+ }+}++private struct ShellOpenTouchLayoutKey: EnvironmentKey {+ nonisolated(unsafe) static let defaultValue: (() -> Void)? = nil+}+extension EnvironmentValues {+ /// Opens the touch controls' layout editor. The library provides it.+ var shellOpenTouchLayout: (() -> Void)? {+ get { self[ShellOpenTouchLayoutKey.self] }+ set { self[ShellOpenTouchLayoutKey.self] = newValue }+ }+}++extension TouchLayout.Control {+ /// The control's name, for the status line and VoiceOver.+ var title: String {+ switch self {+ case .face: "A B X Y"+ case .a: "A"+ case .b: "B"+ case .x: "X"+ case .y: "Y"+ case .stick: ShellStrings.text("Left stick")+ case .dpad: ShellStrings.text("D-pad")+ case .zl: "ZL"+ case .l: "L"+ case .zr: "ZR"+ case .r: "R"+ case .l3: "L3"+ case .r3: "R3"+ case .minus: ShellStrings.text("Minus")+ case .plus: ShellStrings.text("Plus")+ }+ }+}diff --git a/frontend-ios/Sources/ShellUI/TouchPadGeometry.swift b/frontend-ios/Sources/ShellUI/TouchPadGeometry.swiftnew file mode 100644index 00000000..8b53fc0e--- /dev/null+++ b/frontend-ios/Sources/ShellUI/TouchPadGeometry.swift@@ -0,0 +1,369 @@+import CoreGraphics+import Foundation++/// A screen the touch controls are laid out on, as the engine sees it: the game view's size in points, its safe-area insets and,+/// on a foldable, the fold.+public struct PadScreen: Equatable, Sendable {+ public struct Insets: Equatable, Sendable {+ public var top: CGFloat, left: CGFloat, bottom: CGFloat, right: CGFloat+ public init(top: CGFloat = 0, left: CGFloat = 0, bottom: CGFloat = 0, right: CGFloat = 0) {+ self.top = top; self.left = left; self.bottom = bottom; self.right = right+ }+ }+ public var size: CGSize+ public var insets: Insets+ public var partiallyOpen = false+ /// The fold (a division region), nil for none.+ public var division: CGRect?+ /// iPhone Duo's inner display upright: the picture keeps only the top inset (front_ios.m's duoPortrait).+ public var topSafeOnly = false++ public init(size: CGSize, insets: Insets = Insets(), partiallyOpen: Bool = false, division: CGRect? = nil, topSafeOnly: Bool = false) {+ self.size = size; self.insets = insets; self.partiallyOpen = partiallyOpen; self.division = division; self.topSafeOnly = topSafeOnly+ }++ /// iPhone Pro Max held sideways, the screen the settings preview has always shown.+ public static let proMax = PadScreen(size: CGSize(width: 932, height: 430), insets: Insets(left: 59, bottom: 21, right: 59))+ /// iPad Pro 13 inch upright: the controls below the picture.+ public static let iPadUpright = PadScreen(size: CGSize(width: 1032, height: 1376), insets: Insets(top: 24, bottom: 20))+ /// iPhone Duo's inner display upright, with the fold across the middle.+ public static let duoUpright = PadScreen(size: CGSize(width: 669, height: 951), insets: Insets(top: 62, bottom: 34),+ division: CGRect(x: 0, y: 455.5, width: 669, height: 40), topSafeOnly: true)+}++/// The touch controls' geometry, a Swift copy of the engine's `DmPadGeometry.h` (patches 0065 to 0067 and the arrangement of+/// DM_TOUCH_LAYOUT): `dm_layout`, `dm_pad_geo_at`, the fit test, the size and stick fallbacks and `dm_pad_arrange`, line by line, so the+/// layout editor shows and accepts exactly what the engine will draw. `TouchPadGeometryTests` pins it to points the engine's own+/// test program computes. The engine stays the truth on the device.+struct PadGeo: Equatable {+ // dm_layout: the overlay layout, or the split one with the controls below the picture.+ struct Region: Equatable { var game: CGRect, controls: CGRect, separated: Bool, topSafeOnly: Bool }++ struct Shape: Equatable {+ var c: CGPoint+ var r: CGFloat+ var rect: CGRect+ var isRect: Bool+ var within: CGRect+ var id: Int+ init(c: CGPoint = .zero, r: CGFloat = 0, rect: CGRect = .null, isRect: Bool = false, within: CGRect, id: Int) {+ self.c = c; self.r = r; self.rect = rect; self.isRect = isRect; self.within = within; self.id = id+ }+ var box: CGRect { isRect ? rect : CGRect(x: c.x - r, y: c.y - r, width: 2 * r, height: 2 * r) }+ }+ // dm_pad_shapes ids.+ static let shapeFace = 0, shapeStick = 4, shapeDpad = 5, shapeDrop = 6, shapeTip = 10, shapeClick = 14, shapePill = 16, shapeSwap = 18++ var u: CGFloat = 0+ var safe: CGRect = .null, corner: CGRect = .null+ var portrait = false+ var face: CGPoint = .zero, faceGap: CGFloat = 0, faceR: CGFloat = 0, faceHitR: CGFloat = 0+ var stick: CGPoint = .zero, stickR: CGFloat = 0, knobR: CGFloat = 0+ var dpad: CGPoint = .zero, dpadR: CGFloat = 0, armW: CGFloat = 0, armIn: CGFloat = 0+ var drop: [CGPoint] = Array(repeating: .zero, count: 4), dropR: [CGFloat] = Array(repeating: 0, count: 4) // ZL, L, ZR, R+ var click: [CGPoint] = [.zero, .zero], clickR: CGFloat = 0 // L3, R3+ var pill: [CGRect] = [.zero, .zero] // −, ++ var swap: CGPoint = .zero, swapR: CGFloat = 0+ var faceKey: [CGPoint] = Array(repeating: .zero, count: 4) // A, B, X, Y+ var faceSplit = false+ var moved: Set<TouchLayout.Control> = [], dropped: Set<TouchLayout.Control> = []+ var full = false+ var region = Region(game: .zero, controls: .zero, separated: false, topSafeOnly: false)++ /// A quarter of a face key's width: one step of the arrangement.+ var step: CGFloat { faceR / 2 }++ // MARK: DmLayout.h++ static func aspectFit(_ b: CGRect) -> CGRect {+ var w = b.width, h = b.height+ if w <= 0 || h <= 0 { return .zero }+ if w / h > 16.0 / 9.0 { w = h * 16.0 / 9.0 } else { h = w * 9.0 / 16.0 }+ return CGRect(x: floor(b.midX - w / 2), y: floor(b.midY - h / 2), width: w, height: h)+ }+ static func horizontalDivision(_ b: CGRect, _ division: CGRect?) -> CGRect? {+ guard let d = division, !d.isNull, d.width > d.height else { return nil }+ let x = max(b.minX, d.minX), y = max(b.minY, d.minY), right = min(b.maxX, d.maxX), bottom = min(b.maxY, d.maxY)+ if right - x < b.width * 0.9 || bottom < y || y <= b.minY || bottom >= b.maxY { return nil }+ return CGRect(x: x, y: y, width: right - x, height: bottom - y)+ }+ static func inset(_ r: CGRect, _ i: PadScreen.Insets) -> CGRect {+ CGRect(x: r.minX + i.left, y: r.minY + i.top, width: r.width - i.left - i.right, height: r.height - i.top - i.bottom)+ }+ static func gameSafeInsets(_ b: CGRect, _ i: PadScreen.Insets, _ duo: Bool) -> PadScreen.Insets {+ duo && b.height > b.width ? PadScreen.Insets(top: i.top) : i+ }+ static func region(_ screen: PadScreen) -> Region {+ let b = CGRect(origin: .zero, size: screen.size)+ let insets = gameSafeInsets(b, screen.insets, screen.topSafeOnly)+ var l = Region(game: aspectFit(b), controls: b, separated: false, topSafeOnly: screen.topSafeOnly)+ if b.isEmpty { return l }+ let division = horizontalDivision(b, screen.division)+ let portrait = b.height > b.width+ if !portrait && (!screen.partiallyOpen || division == nil) { return l }+ let d = division ?? CGRect(x: b.minX, y: b.midY, width: b.width, height: 0)+ let safe = inset(b, insets)+ let upper = CGRect(x: safe.minX, y: safe.minY, width: safe.width, height: d.minY - safe.minY)+ let lower = CGRect(x: b.minX, y: d.maxY, width: b.width, height: b.maxY - d.maxY)+ if upper.height <= 0 || safe.maxY <= lower.minY { return l }+ l.game = aspectFit(upper); l.controls = lower; l.separated = true+ return l+ }++ // MARK: dm_pad_geo_at++ static func side(_ s: CGRect, right: Bool, _ dx: CGFloat, _ y: CGFloat) -> CGPoint { CGPoint(x: right ? s.maxX - dx : s.minX + dx, y: y) }+ static func diamondKey(_ c: CGPoint, _ d: CGFloat, _ i: Int) -> CGPoint {+ switch i { case 0: CGPoint(x: c.x + d, y: c.y); case 1: CGPoint(x: c.x, y: c.y + d); case 2: CGPoint(x: c.x, y: c.y - d); default: CGPoint(x: c.x - d, y: c.y) }+ }++ static func at(_ screen: PadScreen, _ region: Region, full: Bool, u: CGFloat) -> PadGeo {+ let bounds = CGRect(origin: .zero, size: screen.size), insets = screen.insets+ var g = PadGeo()+ let sep = region.separated+ g.u = u; g.full = full; g.region = region+ g.safe = region.controls.intersection(inset(bounds, gameSafeInsets(bounds, insets, region.topSafeOnly)))+ var ci = insets; ci.left *= 0.5; ci.right *= 0.5+ g.corner = sep ? g.safe : inset(bounds, ci)+ g.portrait = sep && bounds.height > bounds.width+ let s = g.safe, c = g.corner+ let thumbL = CGPoint(x: s.minX + s.width * 0.28, y: s.minY + s.height * 0.58)+ let thumbR = CGPoint(x: s.minX + s.width * 0.72, y: thumbL.y)+ g.faceGap = 50 * u; g.faceR = 27 * u; g.faceHitR = max(g.faceR * 1.25, sep ? 22 : 0)+ g.stickR = 77 * u; g.knobR = 30 * u+ g.dpadR = 48 * u; g.armW = 17 * u; g.armIn = 11 * u+ if g.portrait {+ g.face = thumbR+ g.stick = thumbL; if full { g.stick.x -= g.dpadR + 6 * u }+ g.dpad = CGPoint(x: thumbL.x + g.stickR + 6 * u, y: thumbL.y)+ } else {+ let edge: CGFloat = sep ? g.faceGap + g.faceHitR : 0+ g.face = side(c, right: true, max(81 * u, edge), c.maxY - max(82 * u, edge))+ g.stick = side(c, right: false, 81 * u, c.maxY - 82 * u)+ g.dpad = side(c, right: false, 231 * u, c.maxY - 64 * u)+ }+ let edge: CGFloat = sep ? 22 : 0+ for i in 0..<4 {+ let z = i == 0 || i == 2+ g.drop[i] = side(s, right: i >= 2, max((z ? 44 : 44) * u, edge), s.minY + max((z ? 40 : 108) * u, edge))+ g.dropR[i] = (z ? 26 : 24) * u+ }+ for i in 0..<2 { g.click[i] = side(s, right: i == 1, max(102 * u, edge), s.minY + max(40 * u, edge)) }+ g.clickR = 17 * u+ let top = s.minY + max(22 * u, sep ? 14 : 0), w = 50 * u, h = 28 * u+ for i in 0..<2 {+ let x = s.midX + (i == 1 ? 52 : -52) * u+ g.pill[i] = CGRect(x: x - w / 2, y: top - h / 2, width: w, height: h)+ }+ g.swap = CGPoint(x: s.midX, y: top); g.swapR = 15 * u+ for i in 0..<4 { g.faceKey[i] = diamondKey(g.face, g.faceGap, i) }+ return g+ }++ func dropTip(_ i: Int) -> CGPoint {+ let a = i >= 2 ? -Double.pi / 4 : -3 * Double.pi / 4, d = dropR[i] * 1.45+ return CGPoint(x: drop[i].x + d * cos(a), y: drop[i].y + d * sin(a))+ }++ var shapes: [Shape] {+ var out: [Shape] = []+ for i in 0..<4 { out.append(Shape(c: faceKey[i], r: faceR, within: corner, id: Self.shapeFace + i)) }+ out.append(Shape(c: stick, r: stickR, within: corner, id: Self.shapeStick))+ if full { out.append(Shape(c: dpad, r: hypot(dpadR, armW), within: corner, id: Self.shapeDpad)) }+ for i in 0..<4 {+ out.append(Shape(c: drop[i], r: dropR[i], within: safe, id: Self.shapeDrop + i))+ out.append(Shape(c: dropTip(i), r: 0, within: safe, id: Self.shapeTip + i))+ }+ if full { for i in 0..<2 { out.append(Shape(c: click[i], r: clickR, within: safe, id: Self.shapeClick + i)) } }+ for i in 0..<2 { out.append(Shape(rect: pill[i], isRect: true, within: safe, id: Self.shapePill + i)) }+ out.append(Shape(c: swap, r: swapR, within: safe, id: Self.shapeSwap))+ return out+ }+ static func inside(_ s: Shape) -> Bool {+ let e: CGFloat = 0.5, b = s.box, w = s.within+ return b.minX >= w.minX - e && b.maxX <= w.maxX + e && b.minY >= w.minY - e && b.maxY <= w.maxY + e+ }+ static func overlap(_ a: Shape, _ b: Shape) -> Bool {+ let e: CGFloat = 0.5+ if a.isRect && b.isRect { return a.rect.insetBy(dx: e, dy: e).intersects(b.rect.insetBy(dx: e, dy: e)) }+ if a.isRect || b.isRect {+ let r = a.isRect ? a : b, c = a.isRect ? b : a+ let nx = max(r.rect.minX, min(c.c.x, r.rect.maxX)), ny = max(r.rect.minY, min(c.c.y, r.rect.maxY))+ return hypot(c.c.x - nx, c.c.y - ny) < c.r - e+ }+ return hypot(a.c.x - b.c.x, a.c.y - b.c.y) < a.r + b.r - e+ }+ static func sameControl(_ a: Shape, _ b: Shape) -> Bool {+ (a.id >= shapeDrop && a.id < shapeTip && b.id == a.id + 4) || (b.id >= shapeDrop && b.id < shapeTip && a.id == b.id + 4)+ }+ var fits: Bool {+ let s = shapes+ for i in s.indices {+ if !Self.inside(s[i]) { return false }+ for j in s.indices where j > i { if !Self.sameControl(s[i], s[j]) && Self.overlap(s[i], s[j]) { return false } }+ }+ return true+ }++ // MARK: dm_pad_geo_placed++ static func baseUnit(_ screen: PadScreen, _ region: Region) -> CGFloat {+ let bounds = CGRect(origin: .zero, size: screen.size)+ if !region.separated { return min(bounds.height / 430.0, 1.3) }+ let s = region.controls.intersection(inset(bounds, gameSafeInsets(bounds, screen.insets, region.topSafeOnly)))+ return min(min(s.height / 430.0, s.width / 700.0), 1.3)+ }+ /// DM_TOUCH_SIZE's scale: small 0.8, medium 1, large 1.2.+ static func scale(_ size: String) -> CGFloat { size == "small" ? 0.8 : size == "large" ? 1.2 : 1 }++ /// The geometry before the arrangement: the size, moved toward medium until it fits, and the left stick's place.+ static func placed(_ screen: PadScreen, full: Bool, size: String, stick place: String) -> PadGeo {+ let region = region(screen)+ let u0 = baseUnit(screen, region)+ var scale = Self.scale(size)+ var g = at(screen, region, full: full, u: u0 * scale)+ while scale != 1 && !g.fits {+ scale = scale > 1 ? max(1, scale - 0.05) : min(1, scale + 0.05)+ g = at(screen, region, full: full, u: u0 * scale)+ }+ if place == "higher" || place == "inward" {+ let up = place == "higher"+ let stick = g.stick, dpad = g.dpad+ var d = (up ? 70 : 60) * g.u+ while d > 0 {+ if up { g.stick = CGPoint(x: stick.x, y: stick.y - d) }+ else { g.stick = CGPoint(x: stick.x + d, y: stick.y); g.dpad = CGPoint(x: dpad.x + d, y: dpad.y) }+ if g.fits { return g }+ d -= 2 * g.u+ }+ g.stick = stick; g.dpad = dpad+ }+ return g+ }++ // MARK: dm_pad_arrange++ static func isShape(_ id: Int, of c: TouchLayout.Control) -> Bool {+ switch c {+ case .face: id >= shapeFace && id < shapeFace + 4+ case .a: id == shapeFace+ case .b: id == shapeFace + 1+ case .x: id == shapeFace + 2+ case .y: id == shapeFace + 3+ case .stick: id == shapeStick+ case .dpad: id == shapeDpad+ case .l3: id == shapeClick+ case .r3: id == shapeClick + 1+ case .minus: id == shapePill+ case .plus: id == shapePill + 1+ case .zl, .l, .zr, .r:+ id == shapeDrop + dropIndex(c) || id == shapeTip + dropIndex(c)+ }+ }+ static func dropIndex(_ c: TouchLayout.Control) -> Int { c == .zl ? 0 : c == .l ? 1 : c == .zr ? 2 : 3 }++ mutating func move(_ c: TouchLayout.Control, _ dx: CGFloat, _ dy: CGFloat) {+ func shift(_ p: inout CGPoint) { p.x += dx; p.y += dy }+ switch c {+ case .face: shift(&face); for i in 0..<4 { shift(&faceKey[i]) }+ case .a: shift(&faceKey[0])+ case .b: shift(&faceKey[1])+ case .x: shift(&faceKey[2])+ case .y: shift(&faceKey[3])+ case .stick: shift(&stick)+ case .dpad: shift(&dpad)+ case .l3: shift(&click[0])+ case .r3: shift(&click[1])+ case .minus: shift(&pill[0].origin)+ case .plus: shift(&pill[1].origin)+ case .zl, .l, .zr, .r: shift(&drop[Self.dropIndex(c)])+ }+ }+ static func near(_ a: Shape, _ b: Shape, _ gap: CGFloat) -> Bool {+ var x = a+ if x.isRect { x.rect = x.rect.insetBy(dx: -gap, dy: -gap) } else { x.r += gap }+ return overlap(x, b)+ }+ /// The engine's rule for a moved control: inside its area, and every other control at least the gap away.+ func controlFits(_ c: TouchLayout.Control) -> Bool {+ let s = shapes, gap = max(10 * u, 10)+ for i in s.indices where Self.isShape(s[i].id, of: c) {+ if !Self.inside(s[i]) { return false }+ for j in s.indices where !Self.isShape(s[j].id, of: c) { if Self.near(s[i], s[j], gap) { return false } }+ }+ return true+ }+ static func clamp1(_ lo: CGFloat, _ hi: CGFloat, _ rlo: CGFloat, _ rhi: CGFloat) -> CGFloat {+ if hi - lo > rhi - rlo { return (rlo + rhi) / 2 - (lo + hi) / 2 }+ return lo < rlo ? rlo - lo : hi > rhi ? rhi - hi : 0+ }+ /// The shapes' box of a control and the area it must stay in.+ func box(of c: TouchLayout.Control) -> (box: CGRect, within: CGRect)? {+ var x0 = CGFloat.greatestFiniteMagnitude, y0 = x0, x1 = -x0, y1 = -x0, within: CGRect?+ for s in shapes where Self.isShape(s.id, of: c) {+ let b = s.box; within = s.within+ x0 = min(x0, b.minX); y0 = min(y0, b.minY); x1 = max(x1, b.maxX); y1 = max(y1, b.maxY)+ }+ guard let within else { return nil }+ return (CGRect(x: x0, y: y0, width: x1 - x0, height: y1 - y0), within)+ }+ func clamp(_ c: TouchLayout.Control) -> CGVector {+ guard let (b, w) = box(of: c) else { return .zero }+ return CGVector(dx: Self.clamp1(b.minX, b.maxX, w.minX, w.maxX), dy: Self.clamp1(b.minY, b.maxY, w.minY, w.maxY))+ }++ mutating func arrange(_ offsets: [TouchLayout.Control: TouchLayout.Offset]) {+ let step = self.step+ let want = TouchLayout.Control.allCases.filter { $0.drawn(full: full) && !(offsets[$0]?.isZero ?? true) }+ for round in 0..<2 {+ var todo = want.filter { $0.isFaceKey == (round == 1) }+ var progress = true+ while !todo.isEmpty && progress {+ progress = false+ for c in TouchLayout.Control.allCases where todo.contains(c) {+ var t = self+ let o = offsets[c] ?? .zero+ t.move(c, CGFloat(o.dx) * step, CGFloat(o.dy) * step)+ let d = t.clamp(c)+ t.move(c, d.dx, d.dy)+ if !t.controlFits(c) { continue }+ self = t; moved.insert(c); todo.removeAll { $0 == c }; progress = true+ if c.isFaceKey { faceSplit = true }+ }+ }+ dropped.formUnion(todo)+ }+ }++ /// What the engine draws for this layout: `dm_pad_geo` with the player's options.+ static func make(_ screen: PadScreen, full: Bool, size: String = "medium", stick: String = "corner", layout: TouchLayout = TouchLayout()) -> PadGeo {+ var g = placed(screen, full: full, size: size, stick: stick)+ let kind = TouchLayout.Kind.of(full: full, split: g.region.separated)+ if !layout.isEmpty(kind) { g.arrange(layout.moved(kind)) }+ return g+ }++ // MARK: Where a control is, for the editor++ /// The point a control's offset moves: the diamond's centre, a key, the stick's or D-pad's centre, a teardrop's circle, a pill's centre.+ func anchor(_ c: TouchLayout.Control) -> CGPoint {+ switch c {+ case .face: face+ case .a: faceKey[0]+ case .b: faceKey[1]+ case .x: faceKey[2]+ case .y: faceKey[3]+ case .stick: stick+ case .dpad: dpad+ case .l3: click[0]+ case .r3: click[1]+ case .minus: CGPoint(x: pill[0].midX, y: pill[0].midY)+ case .plus: CGPoint(x: pill[1].midX, y: pill[1].midY)+ case .zl, .l, .zr, .r: drop[Self.dropIndex(c)]+ }+ }+ /// The controls drawn in this layout, the diamond as its four keys.+ var drawnControls: [TouchLayout.Control] {+ TouchLayout.Control.allCases.filter { $0 != .face && $0.drawn(full: full) }+ }+}diff --git a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swiftindex 7b01ab80..472a0145 100644--- a/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift+++ b/frontend-ios/Tests/ShellHostTests/ShellHostModelTests.swift@@ -48,6 +48,15 @@ final class Clock: @unchecked Sendable { var date: Date; init(_ d: Date) { dateshell.storeTouchStick("higher")await model.playNow(Fixtures.orbit)#expect(launcher.launched.last?.environment["DM_TOUCH_STICK"] == "higher")+ #expect(launcher.launched.last?.environment["DM_TOUCH_LAYOUT"] == nil, "no arrangement: nothing is passed")+ var layout = TouchLayout()+ layout[.threeD, .face] = TouchLayout.Offset(dx: -2, dy: -1)+ shell.storeTouchLayout(layout)+ await model.playNow(Fixtures.orbit)+ #expect(launcher.launched.last?.environment["DM_TOUCH_LAYOUT"] == "1;3d/face:-2,-1")+ shell.resetTouchLayout(.threeD)+ await model.playNow(Fixtures.orbit)+ #expect(launcher.launched.last?.environment["DM_TOUCH_LAYOUT"] == nil, "reset: the engine's built-in layout")}/// The engine draws the right-stick hint's words as they come (patch 0067), so the shell hands them over in the player's language.diff --git a/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift b/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swiftindex d682c3a6..f1d5f71e 100644--- a/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift+++ b/frontend-ios/Tests/ShellHostTests/ShellSettingsStoreTests.swift@@ -62,6 +62,25 @@ import ShellUI#expect(store.defaults.object(forKey: ShellSettingsStore.touchStickKey) == nil && store.gameDefaults == ["DM_TOUCH_SIZE": "small"])}+ /// The arrangement (#414) is stored as the engine's value and goes to every game as DM_TOUCH_LAYOUT. Reset removes it per layout.+ @Test func theArrangementGoesToEveryGameAndResetRemovesIt() {+ let store = shell()+ #expect(store.touchLayout.isEmpty && store.gameDefaults["DM_TOUCH_LAYOUT"] == nil, "settings saved before the editor: the built-in layout")+ var layout = TouchLayout()+ layout[.twoD, .stick] = TouchLayout.Offset(dx: 1, dy: -2)+ layout[.threeD, .a] = TouchLayout.Offset(dx: -1, dy: 0)+ store.storeTouchLayout(layout)+ #expect(store.defaults.string(forKey: ShellSettingsStore.touchLayoutKey) == "1;2d/stick:1,-2;3d/a:-1,0")+ #expect(ShellSettingsStore(defaults: store.defaults).touchLayout == layout)+ #expect(store.gameDefaults == ["DM_TOUCH_LAYOUT": "1;2d/stick:1,-2;3d/a:-1,0"])+ store.resetTouchLayout(.twoD)+ #expect(store.gameDefaults == ["DM_TOUCH_LAYOUT": "1;3d/a:-1,0"])+ store.resetTouchLayout(.threeD)+ #expect(store.defaults.object(forKey: ShellSettingsStore.touchLayoutKey) == nil && store.gameDefaults.isEmpty)+ store.defaults.set("1;2d/a:99,0", forKey: ShellSettingsStore.touchLayoutKey)+ #expect(store.touchLayout.isEmpty && store.gameDefaults.isEmpty, "a stored value the engine would ignore is not passed")+ }+@Test func theFolderNamesAreKept() {let store = shell()store.storeDataFolderName("Switch")diff --git a/frontend-ios/Tests/ShellUITests/TouchControlsCaptureTests.swift b/frontend-ios/Tests/ShellUITests/TouchControlsCaptureTests.swiftindex bd0322ba..5a6d0d0c 100644--- a/frontend-ios/Tests/ShellUITests/TouchControlsCaptureTests.swift+++ b/frontend-ios/Tests/ShellUITests/TouchControlsCaptureTests.swift@@ -62,6 +62,30 @@ final class TouchControlsCaptureTests: XCTestCase {}}+ /// The layout editor (#414): a phone held sideways and upright, 2D and 3D, a chosen control, a moved one, a refused spot, and an+ /// iPad upright with the controls below the picture.+ func testCaptureTheLayoutEditor() throws {+ var moved = TouchLayout()+ moved[.threeD, .face] = TouchLayout.Offset(dx: -4, dy: -3)+ moved[.threeD, .stick] = TouchLayout.Offset(dx: 0, dy: -4)+ moved[.threeD, .plus] = TouchLayout.Offset(dx: 2, dy: 1)+ let store = store([ShellSettingsStore.touchLayoutKey: moved.encoded])+ func editor(_ kind: TouchLayout.Kind, upright: PadScreen? = nil, select: TouchLayout.Control? = nil, rejected: Bool = false, held: Bool = false) -> TouchLayoutEditorModel {+ let m = TouchLayoutEditorModel(store: store, sideways: .proMax, upright: upright, kind: kind)+ if let select { held ? m.pickUp(select) : m.select(select) }+ if rejected { m.nudge(dx: 40, dy: 0) } // the stick toward the diamond: no room+ return m+ }+ try capture("touch-editor-phone-sideways", width: 932, height: 430, TouchLayoutEditorView(model: editor(.threeD, select: .stick), close: {}))+ try capture("touch-editor-phone-upright", width: 402, height: 874, TouchLayoutEditorView(model: editor(.threeD, select: .face), close: {}))+ try capture("touch-editor-2d", width: 932, height: 430, TouchLayoutEditorView(model: editor(.twoD), close: {}))+ try capture("touch-editor-refused", width: 932, height: 430, TouchLayoutEditorView(model: editor(.threeD, select: .stick, rejected: true), close: {}))+ try capture("touch-editor-held", width: 932, height: 430, TouchLayoutEditorView(model: editor(.threeD, select: .plus, held: true), close: {}))+ try capture("touch-editor-ipad-upright", width: 1032, height: 1376,+ TouchLayoutEditorView(model: editor(.threeDSplit, upright: .iPadUpright, select: .x), close: {}))+ try capture("touch-settings-arranged", width: 402, height: 1400, ShellSettingsView(store: store, actions: ShellActions(), onClose: {}))+ }+private func captureGroup(_ name: String, _ values: [String: String]) throws {let s = store(values)let group = SettingsGroup(title: ShellStrings.text("Touch controls")) {diff --git a/frontend-ios/Tests/ShellUITests/TouchLayoutTests.swift b/frontend-ios/Tests/ShellUITests/TouchLayoutTests.swiftnew file mode 100644index 00000000..f9156b98--- /dev/null+++ b/frontend-ios/Tests/ShellUITests/TouchLayoutTests.swift@@ -0,0 +1,191 @@+import CoreGraphics+import Foundation+import Testing+@testable import ShellUI++/// The touch controls' arrangement (#414): the value the engine reads, the Swift copy of the engine's geometry, and the editor's rules.+@Suite struct TouchLayoutTests {+ private typealias Offset = TouchLayout.Offset++ // MARK: The value++ @Test func theValueIsWrittenAsTheEngineReadsIt() {+ var l = TouchLayout()+ #expect(l.encoded == "" && l.isEmpty)+ l[.twoD, .face] = Offset(dx: 0, dy: -2)+ l[.twoD, .stick] = Offset(dx: 1, dy: -1)+ l[.threeD, .a] = Offset(dx: -1, dy: 0)+ l[.threeDSplit, .zl] = Offset(dx: 99, dy: -99) // kept inside the engine's range+ #expect(l.encoded == "1;2d/face:0,-2/stick:1,-1;3d/a:-1,0;3s/zl:64,-64")+ #expect(TouchLayout(encoded: l.encoded) == l)+ l[.threeD, .a] = .zero+ #expect(l.encoded == "1;2d/face:0,-2/stick:1,-1;3s/zl:64,-64", "a control back at 0 0 is not written")+ l.reset(.twoD); l.reset(.threeDSplit)+ #expect(l.isEmpty && l.encoded == "")+ }++ /// The same cases as the engine's test (pad_geometry_check.m): what it reads, skips and ignores whole.+ @Test func theValueIsReadAsTheEngineReadsIt() throws {+ #expect(TouchLayout(encoded: "")?.isEmpty == true)+ #expect(TouchLayout(encoded: "1")?.isEmpty == true)+ #expect(TouchLayout(encoded: "1;3d")?.isEmpty == true)+ let skipped = try #require(TouchLayout(encoded: "1;4d/a:1,1;2d/home:3,3/b:2,0"))+ #expect(skipped.encoded == "1;2d/b:2,0", "an unknown layout or control is skipped")+ for bad in ["2;2d/a:1,1", "x", "1x", "1;2d/a", "1;2d/a:", "1;2d/a:1", "1;2d/a:1,", "1;2d/a:1,1,1", "1;2d/a:+1,1", "1;2d/a:65,0", "1;2d/a:0,-65",+ "1;2d/a:1000,0", "1;2d/a:0001,0", "1;2d/A:1,1", "1;2d/a:1,1 ", " 1;2d/a:1,1", "1;2d/a:1,1/", "1;2d/:1,1", "1;2d/a:--1,1",+ "1;2d/a:1.5,1", "1;2d/a:1,1\n2d", "1;2d/a=1,1", "1;2d//a:1,1"] {+ #expect(TouchLayout(encoded: bad) == nil, "\(bad) is not ignored")+ }+ let long = "1;2d" + String(repeating: "/a:1,1", count: 200)+ #expect(TouchLayout(encoded: long) == nil, "too long: ignored whole")+ }++ // MARK: The geometry, pinned to the engine++ private struct Pin { var face: CGPoint; var stick: CGPoint; var dpad: CGPoint; var keys: [CGPoint]; var drops: [CGPoint]; var moved: Set<TouchLayout.Control>; var dropped: Set<TouchLayout.Control> }++ private func expect(_ g: PadGeo, _ p: Pin, _ what: String) {+ func near(_ a: CGPoint, _ b: CGPoint) -> Bool { abs(a.x - b.x) < 0.01 && abs(a.y - b.y) < 0.01 }+ #expect(near(g.face, p.face) && near(g.stick, p.stick) && near(g.dpad, p.dpad), "\(what): \(g.face) \(g.stick) \(g.dpad)")+ for i in 0..<4 { #expect(near(g.faceKey[i], p.keys[i]) && near(g.drop[i], p.drops[i]), "\(what): key or shoulder \(i)") }+ #expect(g.moved == p.moved && g.dropped == p.dropped, "\(what): moved \(g.moved) dropped \(g.dropped)")+ }+ private func pts(_ v: [CGFloat]) -> [CGPoint] { stride(from: 0, to: v.count, by: 2).map { CGPoint(x: v[$0], y: v[$0 + 1]) } }++ /// The points the engine's own geometry gives for these cases (DmPadGeometry.h built on the Mac, printed with four decimals).+ @Test func theCopyOfTheGeometryIsTheEngines() throws {+ let proMax = PadScreen.proMax+ expect(PadGeo.make(proMax, full: true, layout: try #require(TouchLayout(encoded: "1;3d/face:-4,-4/stick:0,-3/minus:-2,2/b:0,1"))),+ Pin(face: CGPoint(x: 767.5, y: 273), stick: CGPoint(x: 110.5, y: 286.5), dpad: CGPoint(x: 260.5, y: 345),+ keys: pts([817.5, 273, 767.5, 336.5, 767.5, 223, 717.5, 273]), drops: pts([103, 40, 103, 108, 829, 40, 829, 108]),+ moved: [.face, .b, .stick, .minus], dropped: []), "Pro Max 3D")+ expect(PadGeo.make(proMax, full: true, size: "large", stick: "higher", layout: try #require(TouchLayout(encoded: "1;3d/stick:52,0/zl:0,-40/dpad:-30,0/r3:-2,3"))),+ Pin(face: CGPoint(x: 805.3, y: 310.6), stick: CGPoint(x: 126.7, y: 250.6), dpad: CGPoint(x: 306.7, y: 332.2),+ keys: pts([865.3, 310.6, 805.3, 370.6, 805.3, 250.6, 745.3, 310.6]), drops: pts([111.8, 31.9895, 111.8, 129.6, 820.2, 48, 820.2, 129.6]),+ moved: [.zl, .r3], dropped: [.stick, .dpad]), "Pro Max 3D large higher")+ expect(PadGeo.make(proMax, full: false, size: "small", stick: "inward", layout: try #require(TouchLayout(encoded: "1;2d/zr:-3,2/x:-1,-2/plus:5,1"))),+ Pin(face: CGPoint(x: 837.7, y: 343.4), stick: CGPoint(x: 142.3, y: 343.4), dpad: CGPoint(x: 262.3, y: 357.8),+ keys: pts([877.7, 343.4, 837.7, 383.4, 826.9, 281.8, 797.7, 343.4]), drops: pts([94.2, 32, 94.2, 86.4, 837.8, 32, 837.8, 86.4]),+ moved: [.x, .plus], dropped: [.zr]), "Pro Max 2D small inward")+ let iPad = PadScreen(size: CGSize(width: 1032, height: 1376), insets: .init(top: 24, bottom: 20))+ expect(PadGeo.make(iPad, full: false, size: "large", layout: try #require(TouchLayout(encoded: "1;2s/face:2,-3/zr:-3,2"))),+ Pin(face: CGPoint(x: 785.16, y: 1012.26), stick: CGPoint(x: 288.96, y: 1075.44), dpad: CGPoint(x: 418.44, y: 1075.44),+ keys: pts([863.16, 1012.26, 785.16, 1090.26, 785.16, 934.26, 707.16, 1012.26]), drops: pts([68.64, 750.4, 68.64, 856.48, 963.36, 750.4, 963.36, 856.48]),+ moved: [.face], dropped: [.zr]), "iPad upright 2D large")+ // The engine's test screens leave the Duo's topSafeOnly off: the same here.+ let duo = PadScreen(size: CGSize(width: 669, height: 951), insets: .init(top: 62, bottom: 34), division: CGRect(x: 0, y: 455.5, width: 669, height: 40))+ expect(PadGeo.make(duo, full: true, size: "small", layout: try #require(TouchLayout(encoded: "1;3s/stick:3,-2/a:1,0/x:0,-1"))),+ Pin(face: CGPoint(x: 481.68, y: 739.97), stick: CGPoint(x: 146.0331, y: 739.97), dpad: CGPoint(x: 250.7794, y: 739.97),+ keys: pts([530.2303, 739.97, 481.68, 778.1986, 481.68, 691.4197, 443.4514, 739.97]),+ drops: pts([33.6411, 526.0829, 33.6411, 578.0737, 635.3589, 526.0829, 635.3589, 578.0737]), moved: [.a, .x], dropped: [.stick]), "Duo upright 3D small")+ let tabletop = PadScreen(size: CGSize(width: 951, height: 669), insets: .init(left: 62, bottom: 20, right: 62), partiallyOpen: true,+ division: CGRect(x: 0, y: 314.5, width: 951, height: 40))+ expect(PadGeo.make(tabletop, full: true, stick: "inward", layout: try #require(TouchLayout(encoded: "1;3s/face:-6,0/dpad:4,-1/l:3,1"))),+ Pin(face: CGPoint(x: 776.1654, y: 591.641), stick: CGPoint(x: 158.5686, y: 592.8395), dpad: CGPoint(x: 298.2849, y: 595.9215),+ keys: pts([810.4096, 591.641, 776.1654, 625.8852, 776.1654, 557.3968, 741.9212, 591.641]),+ drops: pts([92.1349, 381.8953, 119.8727, 437.7134, 858.8651, 381.8953, 858.8651, 428.4674]), moved: [.face, .dpad, .l], dropped: []), "Duo tabletop 3D inward")+ let se = PadScreen(size: CGSize(width: 667, height: 375))+ expect(PadGeo.make(se, full: true, stick: "inward", layout: try #require(TouchLayout(encoded: "1;3d/dpad:-2,-5/l3:3,3/y:-1,0"))),+ Pin(face: CGPoint(x: 596.3605, y: 303.4884), stick: CGPoint(x: 122.9651, y: 303.4884), dpad: CGPoint(x: 253.7791, y: 319.186),+ keys: pts([639.9651, 303.4884, 596.3605, 347.093, 596.3605, 259.8837, 540.9826, 303.4884]),+ drops: pts([38.3721, 34.8837, 38.3721, 94.186, 628.6279, 34.8837, 628.6279, 94.186]), moved: [.y, .l3], dropped: [.dpad]), "iPhone SE 3D inward")+ }++ /// No arrangement, or a reset one, is the built-in geometry exactly.+ @Test(arguments: [PadScreen.proMax, .iPadUpright, .duoUpright])+ func aResetLayoutIsTheBuiltInOne(screen: PadScreen) {+ var l = TouchLayout()+ l[.threeD, .stick] = Offset(dx: 2, dy: -2); l[.threeDSplit, .face] = Offset(dx: -2, dy: 0)+ l.reset(.threeD); l.reset(.threeDSplit)+ #expect(PadGeo.make(screen, full: true, layout: l) == PadGeo.make(screen, full: true))+ }++ // MARK: The editor++ private func editing(_ kind: TouchLayout.Kind = .threeD, screen: PadScreen = .proMax) -> TouchLayoutEditing {+ TouchLayoutEditing(layout: TouchLayout(), kind: kind, screen: screen)+ }++ @Test func aMoveThatFitsIsKeptAndOneOntoAnotherControlIsNot() {+ var e = editing()+ let before = e.geo+ let r1 = e.nudge(.stick, dx: 0, dy: -1)+ #expect(r1 == .moved)+ #expect(e.offset(.stick) == Offset(dx: 0, dy: -1) && abs(e.geo.stick.y - (before.stick.y - 13.5)) < 0.01)+ // The stick dragged onto the diamond: refused, nothing changes.+ let kept = e.layout+ let r2 = e.place(.stick, Offset(dx: 52, dy: 0))+ #expect(!r2 && e.layout == kept)+ // A spot that covers another control's place is refused even when the engine would only push that one back.+ let r3 = e.place(.dpad, Offset(dx: -11, dy: -1))+ #expect(!r3 && e.layout == kept)+ }++ @Test func aControlDraggedPastTheEdgeStopsThereAndComesBackAtOnce() {+ var e = editing()+ let r4 = e.place(.zl, Offset(dx: 0, dy: -40))+ #expect(r4)+ let at = e.geo.drop[0]+ #expect(e.offset(.zl).dy > -40, "kept at most one step past the edge, not 40")+ let r5 = e.nudge(.zl, dx: 0, dy: -1)+ #expect(r5 == .atEdge)+ let r6 = e.nudge(.zl, dx: 0, dy: 1)+ #expect(r6 == .moved && e.geo.drop[0].y > at.y, "the first step back moves it")+ }++ @Test func theDiamondMovesTogetherOrKeyByKey() {+ var e = editing(.twoD)+ #expect(e.mover(.b) == .face)+ let r7 = e.nudge(.b, dx: -1, dy: -1)+ #expect(r7 == .moved && e.offset(.face) == Offset(dx: -1, dy: -1) && e.offset(.b).isZero)+ e.together = false+ let r8 = e.nudge(.b, dx: 0, dy: 1)+ #expect(r8 == .moved && e.offset(.b) == Offset(dx: 0, dy: 1))+ #expect(e.geo.faceSplit && e.isMoved(.a))+ e.putBack(.b)+ #expect(e.offset(.b).isZero && !e.offset(.face).isZero)+ e.together = true+ e.putBack(.a)+ #expect(e.layout.isEmpty, "putting the diamond back also puts its keys back")+ }++ @Test func resetIsOneLayoutOnly() {+ var e = editing(.twoD)+ _ = e.nudge(.l, dx: 1, dy: 1)+ e.kind = .threeD+ _ = e.nudge(.minus, dx: -1, dy: 0)+ e.reset()+ #expect(e.layout.isEmpty(.threeD) && !e.layout.isEmpty(.twoD))+ }++ /// Whatever the editor keeps, the engine draws it as the editor showed it: every kept spot is one the geometry places.+ @Test(arguments: [TouchLayout.Kind.twoD, .threeD])+ func randomEditsOnlyKeepPlacesTheEngineTakes(kind: TouchLayout.Kind) {+ var e = editing(kind)+ var rng: UInt32 = 414+ func next() -> Int { rng ^= rng << 13; rng ^= rng >> 17; rng ^= rng << 5; return Int(rng % 1000) }+ let controls = TouchLayout.Control.allCases.filter { $0.drawn(full: kind.full) }+ for i in 0..<300 {+ e.together = i % 3 != 0+ let c = controls[next() % controls.count]+ if next() % 2 == 0 { _ = e.nudge(c, dx: next() % 3 - 1, dy: next() % 3 - 1) }+ else { _ = e.place(c, Offset(dx: next() % 31 - 15, dy: next() % 31 - 15)) }+ let g = e.geo+ #expect(g.dropped.isEmpty, "step \(i): the engine keeps \(g.dropped) back")+ #expect(g.fits, "step \(i): controls overlap or leave the screen")+ #expect(TouchLayout(encoded: e.layout.encoded) == e.layout)+ }+ }++ @Test func theDeviceScreensFollowTheWindow() {+ let phone = TouchLayoutScreens.device(window: CGSize(width: 440, height: 956), insets: EdgeInsetsLike.portrait, isPad: false)+ #expect(phone.sideways.size == CGSize(width: 956, height: 440) && phone.sideways.insets.left == 62 && phone.upright == nil)+ let pad = TouchLayoutScreens.device(window: CGSize(width: 1376, height: 1032), insets: .init(), isPad: true)+ #expect(pad.sideways.size.width == 1376 && pad.upright?.size == CGSize(width: 1032, height: 1376))+ let duo = TouchLayoutScreens.device(window: CGSize(width: 669, height: 951), insets: .init(top: 62, leading: 0, bottom: 34, trailing: 0), isPad: false)+ #expect(duo.upright?.topSafeOnly == true && duo.upright?.division != nil)+ }+}++import SwiftUI+private enum EdgeInsetsLike { static let portrait = EdgeInsets(top: 62, leading: 0, bottom: 34, trailing: 0) }diff --git a/frontend/l10n/de.json b/frontend/l10n/de.jsonindex d078eee9..e2e6c5f5 100644--- a/frontend/l10n/de.json+++ b/frontend/l10n/de.json@@ -675,10 +675,33 @@"ios.ui.padTestNote": "Jede Taste leuchtet auf, wenn du sie drückst.","ios.ui.padTopButton": "Obere Taste","ios.ui.padUp": "Oben",+ "ios.ui.touchArrange": "Tasten anordnen",+ "ios.ui.touchArrangeButton": "Anordnen …",+ "ios.ui.touchArrangeHint": "Einzelne Tasten dorthin schieben, wo die Daumen sie haben wollen.",+ "ios.ui.touchArrangement": "Anordnung",+ "ios.ui.touchAtEdge": "Am Rand",+ "ios.ui.touchBelowPicture": "Unter dem Bild",+ "ios.ui.touchBuiltIn": "Standard",+ "ios.ui.touchChoose": "Wähle eine Taste","ios.ui.touchControls": "Touch-Steuerung",+ "ios.ui.touchEditorNote": "Ziehe eine Taste, um sie zu verschieben. Tippe eine an, um sie zu wählen, und verschiebe sie dann Schritt für Schritt mit den Pfeilen. Würde eine Taste eine andere verdecken oder den Bildschirm verlassen, geht sie zurück. Für alle Spiele.",+ "ios.ui.touchHeld": "Mit dem Steuerkreuz verschieben. A oder B legt sie ab.",+ "ios.ui.touchInPlace": "An ihrem Platz","ios.ui.touchLarge": "Groß",+ "ios.ui.touchLayout": "Aufteilung","ios.ui.touchMedium": "Mittel",+ "ios.ui.touchMoveDown": "Nach unten",+ "ios.ui.touchMoveLeft": "Nach links",+ "ios.ui.touchMoveRight": "Nach rechts",+ "ios.ui.touchMoveUp": "Nach oben",+ "ios.ui.touchMoved": "Verschoben",+ "ios.ui.touchNoRoom": "Dort ist kein Platz",+ "ios.ui.touchNoRoomBack": "Dort ist kein Platz. Die Taste ist zurück an ihrem Platz.",+ "ios.ui.touchOverPicture": "Über dem Bild","ios.ui.touchPreview": "Vorschau der Touch-Steuerung",+ "ios.ui.touchPutBack": "Zurückstellen",+ "ios.ui.touchResetLayout": "Dieses Layout zurücksetzen",+ "ios.ui.touchScreen": "Bildschirm","ios.ui.touchSize": "Größe","ios.ui.touchSizeNote": "Für alle Spiele. Ist der Bildschirm für eine Wahl zu klein, bleiben die Tasten näher an ihrem alten Platz.","ios.ui.touchSmall": "Klein",@@ -686,6 +709,10 @@"ios.ui.touchStickCorner": "Ecke","ios.ui.touchStickHigher": "Höher","ios.ui.touchStickInward": "Innen",+ "ios.ui.touchTapControl": "Tippe auf eine Taste im Bild.",+ "ios.ui.touchTogether": "A B X Y zusammen bewegen",+ "ios.ui.touchTurnSideways": "Halte das iPhone quer für eine größere Vorschau.",+ "ios.ui.touchYourOwn": "Eigene","key.clear": "Löschen","key.code": "Taste %ld","key.delete": "Rückschritt",diff --git a/frontend/l10n/en.json b/frontend/l10n/en.jsonindex f3f5cd67..3c85f1ed 100644--- a/frontend/l10n/en.json+++ b/frontend/l10n/en.json@@ -793,10 +793,33 @@"ios.ui.showLog": "Show log","ios.ui.tagline": "A little room for adventure","ios.ui.titleId": "Title ID %@",+ "ios.ui.touchArrange": "Arrange controls",+ "ios.ui.touchArrangeButton": "Arrange…",+ "ios.ui.touchArrangeHint": "Move single controls where your thumbs want them.",+ "ios.ui.touchArrangement": "Arrangement",+ "ios.ui.touchAtEdge": "At the edge",+ "ios.ui.touchBelowPicture": "Below the picture",+ "ios.ui.touchBuiltIn": "Built in",+ "ios.ui.touchChoose": "Choose a control","ios.ui.touchControls": "Touch controls",+ "ios.ui.touchEditorNote": "Drag a control to move it. Tap one to choose it, then move it step by step with the arrows. Where a control would cover another or leave the screen, it goes back. For every game.",+ "ios.ui.touchHeld": "Move it with the D-pad. A or B puts it down.",+ "ios.ui.touchInPlace": "In its place","ios.ui.touchLarge": "Large",+ "ios.ui.touchLayout": "Layout","ios.ui.touchMedium": "Medium",+ "ios.ui.touchMoveDown": "Move down",+ "ios.ui.touchMoveLeft": "Move left",+ "ios.ui.touchMoveRight": "Move right",+ "ios.ui.touchMoveUp": "Move up",+ "ios.ui.touchMoved": "Moved",+ "ios.ui.touchNoRoom": "No room there",+ "ios.ui.touchNoRoomBack": "No room there. It went back to where it was.",+ "ios.ui.touchOverPicture": "Over the picture","ios.ui.touchPreview": "Preview of the touch controls",+ "ios.ui.touchPutBack": "Put back",+ "ios.ui.touchResetLayout": "Reset this layout",+ "ios.ui.touchScreen": "Screen","ios.ui.touchSize": "Size","ios.ui.touchSizeNote": "For every game. On a screen too small for a choice, the controls stay closer to where they were.","ios.ui.touchSmall": "Small",@@ -804,6 +827,10 @@"ios.ui.touchStickCorner": "Corner","ios.ui.touchStickHigher": "Higher","ios.ui.touchStickInward": "Inward",+ "ios.ui.touchTapControl": "Tap a control in the picture.",+ "ios.ui.touchTogether": "Move A B X Y together",+ "ios.ui.touchTurnSideways": "Turn the phone sideways for a larger preview.",+ "ios.ui.touchYourOwn": "Your own","ios.ui.turnOff": "Turn off","ios.ui.turnOffCloudSaves": "Turn off cloud saves","ios.ui.unavailable": "Unavailable",diff --git a/frontend/l10n/fr.json b/frontend/l10n/fr.jsonindex b5f62f8a..d0fcd10d 100644--- a/frontend/l10n/fr.json+++ b/frontend/l10n/fr.json@@ -677,10 +677,33 @@"ios.ui.padTestNote": "Chaque bouton s’allume quand vous appuyez dessus.","ios.ui.padTopButton": "Bouton du haut","ios.ui.padUp": "Haut",+ "ios.ui.touchArrange": "Disposer les commandes",+ "ios.ui.touchArrangeButton": "Disposer…",+ "ios.ui.touchArrangeHint": "Placez chaque commande là où vos pouces la veulent.",+ "ios.ui.touchArrangement": "Disposition",+ "ios.ui.touchAtEdge": "Au bord",+ "ios.ui.touchBelowPicture": "Sous l’image",+ "ios.ui.touchBuiltIn": "Par défaut",+ "ios.ui.touchChoose": "Choisissez une commande","ios.ui.touchControls": "Commandes tactiles",+ "ios.ui.touchEditorNote": "Faites glisser une commande pour la déplacer. Touchez-en une pour la choisir, puis déplacez-la pas à pas avec les flèches. Si une commande en couvrait une autre ou sortait de l’écran, elle revient. Pour tous les jeux.",+ "ios.ui.touchHeld": "Déplacez-la avec la croix. A ou B la pose.",+ "ios.ui.touchInPlace": "À sa place","ios.ui.touchLarge": "Grande",+ "ios.ui.touchLayout": "Agencement","ios.ui.touchMedium": "Moyenne",+ "ios.ui.touchMoveDown": "Vers le bas",+ "ios.ui.touchMoveLeft": "Vers la gauche",+ "ios.ui.touchMoveRight": "Vers la droite",+ "ios.ui.touchMoveUp": "Vers le haut",+ "ios.ui.touchMoved": "Déplacée",+ "ios.ui.touchNoRoom": "Pas de place ici",+ "ios.ui.touchNoRoomBack": "Pas de place ici. La commande est revenue à sa place.",+ "ios.ui.touchOverPicture": "Sur l’image","ios.ui.touchPreview": "Aperçu des commandes tactiles",+ "ios.ui.touchPutBack": "Remettre",+ "ios.ui.touchResetLayout": "Réinitialiser cet agencement",+ "ios.ui.touchScreen": "Écran","ios.ui.touchSize": "Taille","ios.ui.touchSizeNote": "Pour tous les jeux. Sur un écran trop petit pour un choix, les commandes restent plus près de leur place.","ios.ui.touchSmall": "Petite",@@ -688,6 +711,10 @@"ios.ui.touchStickCorner": "Coin","ios.ui.touchStickHigher": "Plus haut","ios.ui.touchStickInward": "Au centre",+ "ios.ui.touchTapControl": "Touchez une commande dans l’image.",+ "ios.ui.touchTogether": "Déplacer A B X Y ensemble",+ "ios.ui.touchTurnSideways": "Tournez le téléphone à l’horizontale pour un aperçu plus grand.",+ "ios.ui.touchYourOwn": "Personnalisée","key.clear": "Effacer","key.code": "Touche %ld","key.delete": "Supprimer",diff --git a/frontend/l10n/it.json b/frontend/l10n/it.jsonindex 95ebe41f..b30ebcf6 100644--- a/frontend/l10n/it.json+++ b/frontend/l10n/it.json@@ -678,10 +678,33 @@"ios.ui.padTestNote": "Ogni tasto si illumina quando lo premi.","ios.ui.padTopButton": "Tasto in alto","ios.ui.padUp": "Su",+ "ios.ui.touchArrange": "Disponi i comandi",+ "ios.ui.touchArrangeButton": "Disponi…",+ "ios.ui.touchArrangeHint": "Sposta i singoli comandi dove li vogliono i pollici.",+ "ios.ui.touchArrangement": "Disposizione",+ "ios.ui.touchAtEdge": "Al bordo",+ "ios.ui.touchBelowPicture": "Sotto l’immagine",+ "ios.ui.touchBuiltIn": "Predefinita",+ "ios.ui.touchChoose": "Scegli un comando","ios.ui.touchControls": "Comandi touch",+ "ios.ui.touchEditorNote": "Trascina un comando per spostarlo. Toccane uno per sceglierlo, poi spostalo passo per passo con le frecce. Se un comando ne coprisse un altro o uscisse dallo schermo, torna indietro. Per tutti i giochi.",+ "ios.ui.touchHeld": "Spostalo con la croce direzionale. A o B lo posa.",+ "ios.ui.touchInPlace": "Al suo posto","ios.ui.touchLarge": "Grande",+ "ios.ui.touchLayout": "Schema","ios.ui.touchMedium": "Media",+ "ios.ui.touchMoveDown": "Giù",+ "ios.ui.touchMoveLeft": "A sinistra",+ "ios.ui.touchMoveRight": "A destra",+ "ios.ui.touchMoveUp": "Su",+ "ios.ui.touchMoved": "Spostato",+ "ios.ui.touchNoRoom": "Non c’è spazio",+ "ios.ui.touchNoRoomBack": "Non c’è spazio. Il comando è tornato al suo posto.",+ "ios.ui.touchOverPicture": "Sopra l’immagine","ios.ui.touchPreview": "Anteprima dei comandi touch",+ "ios.ui.touchPutBack": "Rimetti",+ "ios.ui.touchResetLayout": "Ripristina questo schema",+ "ios.ui.touchScreen": "Schermo","ios.ui.touchSize": "Dimensione","ios.ui.touchSizeNote": "Per tutti i giochi. Su uno schermo troppo piccolo per una scelta, i comandi restano più vicini al loro posto.","ios.ui.touchSmall": "Piccola",@@ -689,6 +712,10 @@"ios.ui.touchStickCorner": "Angolo","ios.ui.touchStickHigher": "In alto","ios.ui.touchStickInward": "Al centro",+ "ios.ui.touchTapControl": "Tocca un comando nell’immagine.",+ "ios.ui.touchTogether": "Sposta A B X Y insieme",+ "ios.ui.touchTurnSideways": "Ruota il telefono in orizzontale per un’anteprima più grande.",+ "ios.ui.touchYourOwn": "Personalizzata","key.clear": "Cancella","key.code": "Tasto %ld","key.delete": "Elimina",diff --git a/frontend/l10n/sv.json b/frontend/l10n/sv.jsonindex 533a9e47..13e3a2d3 100644--- a/frontend/l10n/sv.json+++ b/frontend/l10n/sv.json@@ -520,10 +520,33 @@"ios.ui.padTestNote": "Se varje knapp lysa upp när du trycker på den.","ios.ui.padTopButton": "Övre knappen","ios.ui.padUp": "Upp",+ "ios.ui.touchArrange": "Ordna kontrollerna",+ "ios.ui.touchArrangeButton": "Ordna…",+ "ios.ui.touchArrangeHint": "Flytta enskilda kontroller dit tummarna vill ha dem.",+ "ios.ui.touchArrangement": "Placering",+ "ios.ui.touchAtEdge": "Vid kanten",+ "ios.ui.touchBelowPicture": "Under bilden",+ "ios.ui.touchBuiltIn": "Standard",+ "ios.ui.touchChoose": "Välj en kontroll","ios.ui.touchControls": "Pekkontroller",+ "ios.ui.touchEditorNote": "Dra en kontroll för att flytta den. Tryck på en för att välja den och flytta den sedan steg för steg med pilarna. Om en kontroll skulle täcka en annan eller hamna utanför skärmen går den tillbaka. För alla spel.",+ "ios.ui.touchHeld": "Flytta den med styrkorset. A eller B släpper den.",+ "ios.ui.touchInPlace": "På sin plats","ios.ui.touchLarge": "Stor",+ "ios.ui.touchLayout": "Layout","ios.ui.touchMedium": "Mellan",+ "ios.ui.touchMoveDown": "Ned",+ "ios.ui.touchMoveLeft": "Vänster",+ "ios.ui.touchMoveRight": "Höger",+ "ios.ui.touchMoveUp": "Upp",+ "ios.ui.touchMoved": "Flyttad",+ "ios.ui.touchNoRoom": "Ingen plats där",+ "ios.ui.touchNoRoomBack": "Ingen plats där. Kontrollen gick tillbaka dit den var.",+ "ios.ui.touchOverPicture": "Över bilden","ios.ui.touchPreview": "Förhandsvisning av pekkontrollerna",+ "ios.ui.touchPutBack": "Lägg tillbaka",+ "ios.ui.touchResetLayout": "Återställ den här layouten",+ "ios.ui.touchScreen": "Skärm","ios.ui.touchSize": "Storlek","ios.ui.touchSizeNote": "För alla spel. På en skärm som är för liten för ett val stannar kontrollerna närmare sin plats.","ios.ui.touchSmall": "Liten",@@ -531,6 +554,10 @@"ios.ui.touchStickCorner": "Hörn","ios.ui.touchStickHigher": "Högre","ios.ui.touchStickInward": "Längre in",+ "ios.ui.touchTapControl": "Tryck på en kontroll i bilden.",+ "ios.ui.touchTogether": "Flytta A B X Y tillsammans",+ "ios.ui.touchTurnSideways": "Vänd telefonen på sidan för en större förhandsvisning.",+ "ios.ui.touchYourOwn": "Egen","key.clear": "Rensa","key.code": "Tangent %ld","key.delete": "Radera",diff --git a/frontend/l10n/zh.json b/frontend/l10n/zh.jsonindex a13ce41c..ae256737 100644--- a/frontend/l10n/zh.json+++ b/frontend/l10n/zh.json@@ -794,10 +794,33 @@"ios.ui.showLog": "显示日志","ios.ui.tagline": "给冒险留一点空间","ios.ui.titleId": "Title ID %@",+ "ios.ui.touchArrange": "排列按键",+ "ios.ui.touchArrangeButton": "排列…",+ "ios.ui.touchArrangeHint": "把单个按键移到拇指顺手的位置。",+ "ios.ui.touchArrangement": "按键位置",+ "ios.ui.touchAtEdge": "已到边缘",+ "ios.ui.touchBelowPicture": "在画面下方",+ "ios.ui.touchBuiltIn": "默认",+ "ios.ui.touchChoose": "选择一个按键","ios.ui.touchControls": "触控按键",+ "ios.ui.touchEditorNote": "拖动按键即可移动。点按一个按键选中它,再用箭头一步步移动。按键会挡住其他按键或超出屏幕时,会回到原位。适用于所有游戏。",+ "ios.ui.touchHeld": "用十字键移动它。按 A 或 B 放下。",+ "ios.ui.touchInPlace": "在原位","ios.ui.touchLarge": "大",+ "ios.ui.touchLayout": "布局","ios.ui.touchMedium": "中",+ "ios.ui.touchMoveDown": "下移",+ "ios.ui.touchMoveLeft": "左移",+ "ios.ui.touchMoveRight": "右移",+ "ios.ui.touchMoveUp": "上移",+ "ios.ui.touchMoved": "已移动",+ "ios.ui.touchNoRoom": "那里放不下",+ "ios.ui.touchNoRoomBack": "那里放不下,已回到原来的位置。",+ "ios.ui.touchOverPicture": "叠在画面上","ios.ui.touchPreview": "触控按键预览",+ "ios.ui.touchPutBack": "放回原位",+ "ios.ui.touchResetLayout": "重置此布局",+ "ios.ui.touchScreen": "屏幕","ios.ui.touchSize": "大小","ios.ui.touchSizeNote": "适用于所有游戏。屏幕放不下所选设置时,按键会尽量留在原来的位置附近。","ios.ui.touchSmall": "小",@@ -805,6 +828,10 @@"ios.ui.touchStickCorner": "角落","ios.ui.touchStickHigher": "靠上","ios.ui.touchStickInward": "靠内",+ "ios.ui.touchTapControl": "点按画面中的一个按键。",+ "ios.ui.touchTogether": "A B X Y 一起移动",+ "ios.ui.touchTurnSideways": "把手机横过来,预览会更大。",+ "ios.ui.touchYourOwn": "自定义","ios.ui.turnOff": "关闭","ios.ui.turnOffCloudSaves": "关闭云存档","ios.ui.unavailable": "不可用",diff --git a/patches/0068-ios-touch-layout.patch b/patches/0068-ios-touch-layout.patchnew file mode 100644index 00000000..10aa29f6--- /dev/null+++ b/patches/0068-ios-touch-layout.patch@@ -0,0 +1,686 @@+From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001+From: v0lumehi <[email protected]>+Date: Tue, 3 Nov 2026 18:13:58 +0100+Subject: [PATCH] ios: the player's arrangement of the touch controls+ (DM_TOUCH_LAYOUT)++Players want to move the touch controls themselves (LNPANDY/NX2Apple#414,+#347, seedds/nxnative#740). The earlier editor (patch 0036, reverted in+#345) scattered the controls and broke the layout on a multi-game+install. This one is safe by construction.++DM_TOUCH_LAYOUT is one value, written by a front end's layout editor:+"1", then per layout ";", its name and "/control:dx,dy" for each moved+control, for example 1;2d/face:0,-2/stick:1,-1;3d/a:-1,0. There is one+arrangement each for 2D, 3D and both again for the split screen (2s, 3s:+DmLayout.separated, an iPad upright and iPhone Duo upright or half open).+The controls are the diamond as a whole (face) and each of its keys (a b x+y, from where the diamond is), the left stick, the D-pad, ZL L ZR R, L3+R3, minus and plus. The layout button stays. Offsets are steps of a+quarter of a face key's width at the player's size, so a layout scales+with the controls and not with the screen. The engine stores nothing.++The geometry (DmPadGeometry.h) applies it after the size and the left+stick's place. Each moved control is pushed back inside the area its+built-in place uses (the safe area, the bottom corners halfway into the+side insets as always) and placed only if it stays 10 u (at least 10+points) clear of every other drawn control. Otherwise it keeps its+built-in place. The diamond goes first, then its single keys. Each round+places what fits and tries the rest again, so a control can take a place+another one has left. Whatever the value, the result is a layout with+every control inside and none on another. An unknown layout or control+is skipped. Any other malformed value, or one longer than 1024+characters, is ignored whole. The log says when a value is ignored and+which moved controls kept their place.++The touch-down decision moves out of DmGamepad.m into dm_pad_hit, a pure+function of the same geometry, so drawing, hit-test and grab cannot+disagree. Without an arrangement it decides exactly as before. With one,+the locked keys go to the nearest, and a diamond whose keys were moved+one by one is grabbed key by key.++test_pad_geometry.py: a value of zeros gives the built-in layout exactly+on every screen, the value's form (malformed and too-long values ignored,+unknown names skipped, random bytes), and seeded random arrangements on+every screen, layout, size and stick place: every control inside its+area and on the screen, no two overlapping, a moved one clear by the gap,+and a touch inside any drawn control taken by that control.++Upstream-Status: pending (on seedds/nxnative#683)+Reason: Players arrange the touch controls themselves (#414, #347)+Issue: LNPANDY/NX2Apple#414+---+ dm/ios/Sources/DmGamepad.m | 63 ++---+ dm/ios/Sources/DmPadGeometry.h | 230 +++++++++++++++++-+ .../tests/pad_geometry/pad_geometry_check.m | 181 +++++++++++++-+ dm/ios/tests/test_pad_geometry.py | 7 +-+ 4 files changed, 432 insertions(+), 49 deletions(-)++diff --git a/dm/ios/Sources/DmGamepad.m b/dm/ios/Sources/DmGamepad.m+index 7653b5a..7cd4255 100644+--- a/dm/ios/Sources/DmGamepad.m++++ b/dm/ios/Sources/DmGamepad.m+@@ -7,8 +7,9 @@+ // (a touch landing in the right third of the screen on no control holds it: centred where it lands, the centre dragged along once the finger passes the stick radius) and L3 / R3 (small round keys in the top row, inward of ZL / ZR).+ // Breath of the Wild crouches with L3 and uses the scope with R3; 3D World and Breath of the Wild turn the camera with the right stick.+ // The first time the 3D layout shows in a launch, a few words (DM_TOUCH_HINT) say where the undrawn right stick is, for two seconds; see "The right-stick hint".+-// Touch-down ownership: locked keys first (shoulders, − / +, the layout button, L3 / R3), then whichever of the diamond, the D-pad and the left stick has the smallest distance / grab radius (the left stick's grab circle borders the D-pad),+-// then in 3D the right stick for a touch in the right third.++// Touch-down ownership (dm_pad_hit in DmPadGeometry.h): locked keys first (shoulders, − / +, the layout button, L3 / R3), then whichever of the diamond, the D-pad and the left stick has the smallest distance / grab radius++// (the left stick's grab circle borders the D-pad), then in 3D the right stick for a touch in the right third.++// The player can move single controls in the shell's settings (DM_TOUCH_LAYOUT, one arrangement per layout): the geometry places each only where it fits and keeps the rest where they were.+ // Everything hugs the edges and corners to leave the picture room; controls sit over the picture, one CAShapeLayer each: a press only swaps the fill, a stick only moves its knob, nothing redraws the whole screen.+ // Where each control sits is DmPadGeometry.h (pure, tested on the Mac); the player picks the size there through DM_TOUCH_SIZE (small, medium, large; a size that does not fit the screen moves toward medium) and the left stick's place through DM_TOUCH_STICK (corner, higher, inward).+ // Touches no control takes (in 3D, those outside the right third) go to the game's touch screen when DmLayout assigns a local game viewport (pushGame; Super Mario Galaxy's pointer in handheld mode).+@@ -115,11 +116,9 @@ static void phone_motion_start(UIView *body) {+ // The bottom-corner controls reach halfway into the side safe-area inset (in landscape there is only the rounded screen corner there; the Dynamic Island is mid-edge);+ // the stick's ring is as large as the whole diamond (key distance + key radius), the knob a little larger than a diamond key; the D-pad sits inward of and below the+ // left stick, as on a Pro Controller. What stays here is how touches are taken:+-static const CGFloat+- K_STICK_GRAB = 1.4, // how near the ring centre a touch-down grabs a stick (times the ring radius)++static const CGFloat // (the grab radii of the stick and the D-pad are DmPadGeometry.h's DM_PAD_STICK_GRAB and DM_PAD_DPAD_GRAB)+ K_FULL = 0.8, // full tilt at this fraction of the ring radius (the knob still travels to the ring edge)+ K_DEAD = 0.1, // stick dead zone (times the ring radius)+- K_DPAD_GRAB = 1.3, // D-pad grab radius (times the outer edge)+ K_RSTICK_R = 60, // right stick (not drawn): radius around its centre, the touch-down point+ K_RSWIPE = 1.0 / 3; // right stick area: this fraction of the screen width from the right edge (not in u)+ static const int k_btns[] = {B_ZL, B_L, B_ZR, B_R, B_MINUS, B_PLUS, B_LS, B_RS}; // keys locked at touch-down (L3 / R3 only in the 3D layout)+@@ -149,8 +148,10 @@ @implementation DmGamepad {+ CALayer *_controls; // holds every control layer: hidden while a physical controller is connected (the view itself stays, for game touches)+ BOOL _padOff; // a physical controller is connected: every touch goes to the game+ DmLayout _layout;+- DmPadOptions _opts; // the player's options from the environment (DM_TOUCH_SIZE, DM_TOUCH_STICK)++ DmPadOptions _opts; // the player's options from the environment (DM_TOUCH_SIZE, DM_TOUCH_STICK, DM_TOUCH_LAYOUT)++ DmPadLayout _arrangement; // DM_TOUCH_LAYOUT, which _opts.layout points to+ DmPadGeo _geo; CGRect _geoBounds; UIEdgeInsets _geoInsets; BOOL _geoFull, _geoValid; // where the controls are, and what it was computed for++ unsigned _loggedDropped; // the moved controls that kept their place, as last logged+ UITouch *_game[16]; // touches on the game's touch screen by finger slot+ }++@@ -177,6 +178,10 @@ - (instancetype)initWithFrame:(CGRect)f {+ const char *stick = getenv("DM_TOUCH_STICK");+ _opts.stick = dm_pad_stick_place(stick);+ if (stick && *stick) LOG("front end: left stick %s (DM_TOUCH_STICK)", _opts.stick == DM_PAD_STICK_HIGHER ? "higher" : _opts.stick == DM_PAD_STICK_INWARD ? "inward" : "in the corner");++ const char *arrangement = getenv("DM_TOUCH_LAYOUT");++ if (!dm_pad_layout_parse(arrangement, &_arrangement)) LOG("front end: DM_TOUCH_LAYOUT ignored (not a layout the engine reads, %zu characters): every control keeps its place", strlen(arrangement));++ else if (dm_pad_layout_count(&_arrangement)) LOG("front end: touch controls arranged by the player (DM_TOUCH_LAYOUT, %d moved over every layout)", dm_pad_layout_count(&_arrangement));++ _opts.layout = &_arrangement;+ [self registerForTraitChanges:@[UITraitDisplayScale.class] withHandler:^(id<UITraitEnvironment> environment, UITraitCollection *previous) {+ [(UIView *)environment setNeedsLayout];+ }];+@@ -251,6 +256,12 @@ - (const DmPadGeo *)geo { // DmPadGeometry.h, computed again whenever the boun+ if (!_geoValid || !CGRectEqualToRect(b, _geoBounds) || !UIEdgeInsetsEqualToEdgeInsets(i, _geoInsets) || _geoFull != _full) {+ _geo = dm_pad_geo(b, i, _layout, _full, _opts);+ _geoBounds = b; _geoInsets = i; _geoFull = _full; _geoValid = YES;++ if (_geo.dropped != _loggedDropped) { // a moved control with no room on this screen: said once per change, for the log a player sends++ _loggedDropped = _geo.dropped;++ NSMutableArray<NSString *> *names = [NSMutableArray array];++ for (int c = 0; c < DM_PAD_C_N; c++) if (_geo.dropped & (1u << c)) [names addObject:@(dm_pad_control_names[c])];++ if (names.count) LOG("front end: touch layout: %s kept at the built-in place (no room there on this screen, or on another control)", [names componentsJoinedByString:@" "].UTF8String);++ }+ }+ return &_geo;+ }+@@ -276,29 +287,11 @@ - (CGRect)pillRect:(int)b { return self.geo->pill[b == B_PLUS ? DM_PAD_PLUS : DM+ - (CGPoint)swapCenter { return self.geo->swap; }++ static CGFloat dist(CGPoint a, CGPoint b) { return hypot(a.x - b.x, a.y - b.y); }+-- (CGFloat)buttonDistance:(int)b point:(CGPoint)p {+- CGFloat u = self.u;+- if (isDrop(b)) return dist(p, [self dropCenter:b]) / MAX([self dropR:b] * 1.35, _layout.separated ? 22 : 0);+- if (isClick(b)) return dist(p, [self clickCenter:b]) / MAX(self.geo->clickR * 1.35, _layout.separated ? 22 : 0);+- CGRect r = CGRectInset([self pillRect:b], -8 * u, -8 * u);+- if (!_layout.separated && !CGRectContainsPoint(r, p)) return CGFLOAT_MAX;+- CGFloat w = MAX(r.size.width, _layout.separated ? 28 : 0), h = MAX(r.size.height, _layout.separated ? 28 : 0);+- return MAX(fabs(p.x - CGRectGetMidX(r)) / (w / 2), fabs(p.y - CGRectGetMidY(r)) / (h / 2));+-}+-- (int)btnAt:(CGPoint)p { // Locked at touch-down; nearest normalized target wins overlapping separated-layout hits.+- int best = -1; CGFloat distance = 1;+- for (int i = 0; i < (int)(sizeof k_btns / sizeof *k_btns); i++) { int b = k_btns[i];+- if (fullOnly(b) && !_full) continue;+- CGFloat d = [self buttonDistance:b point:p];+- if (d <= 1 && (best < 0 || d < distance)) {+- best = b; distance = d;+- if (!_layout.separated) return b;+- }+- }+- return best;++static int lockedKey(int c) { // DmPadGeometry.h's control → the key it presses++ switch (c) { case DM_PAD_C_ZL: return B_ZL; case DM_PAD_C_L: return B_L; case DM_PAD_C_ZR: return B_ZR; case DM_PAD_C_R: return B_R;++ case DM_PAD_C_MINUS: return B_MINUS; case DM_PAD_C_PLUS: return B_PLUS; case DM_PAD_C_L3: return B_LS; default: return B_RS; }+ }+-- (CGFloat)swapDistance:(CGPoint)p { return dist(p, self.swapCenter) / MAX(self.geo->swapR * 1.6, _layout.separated ? 14 : 0); }+-- (BOOL)inSwap:(CGPoint)p { return [self swapDistance:p] <= 1; }++- (BOOL)inSwap:(CGPoint)p { return dm_pad_swap_distance(self.geo, _layout.separated, p) <= 1; }+ - (uint64_t)faceAt:(CGPoint)p { // keys under the finger in the diamond (between two keys both count)+ uint64_t m = 0; CGFloat r = self.faceHitR;+ for (int b = B_A; b <= B_Y; b++) if (dist(p, [self facePos:b]) <= r) m |= 1ull << b;+@@ -374,17 +367,11 @@ - (void)touchesBegan:(NSSet<UITouch *> *)ts withEvent:(UIEvent *)e {+ if (_padOff) { game |= [self gameBegin:t]; continue; }+ CGPoint p = [t locationInView:self];+ if (_layout.separated && !CGRectContainsPoint(_layout.controls, p)) { game |= [self gameBegin:t]; continue; }+- int hit = _tap ? -1 : [self btnAt:p];+- if ([self inSwap:p] && (hit < 0 || (_layout.separated && [self swapDistance:p] < [self buttonDistance:hit point:p]))) {+- [_owner setObject:@(C_SWAP) forKey:t]; continue;+- }+- if (hit >= 0) { [_owner setObject:@(C_BTN | (uint64_t)hit << 8) forKey:t]; continue; }++ DmPadHit hit = dm_pad_hit(self.geo, _full, _layout.separated, _tap, !_stick[0], p); // the same geometry the controls are drawn with++ if (hit.kind == DM_PAD_HIT_SWAP) { [_owner setObject:@(C_SWAP) forKey:t]; continue; }++ if (hit.kind == DM_PAD_HIT_KEY) { [_owner setObject:@(C_BTN | (uint64_t)lockedKey(hit.key) << 8) forKey:t]; continue; }+ if (_tap) { game |= [self gameBegin:t]; continue; }+- // diamond, D-pad, left stick: take the one with the smallest distance / grab radius, if it is <= 1+- CGFloat best = 1; int kind = C_NONE, idx = 0;+- CGFloat f = dist(p, self.faceCenter) / (self.faceGap + MAX(self.faceR * 1.6, self.faceHitR)); if (f <= best) { best = f; kind = C_FACE; }+- if (_full) { CGFloat d = dist(p, self.dpadCenter) / MAX(self.dpadR * K_DPAD_GRAB, _layout.separated ? 22 : 0); if (d < best) { best = d; kind = C_DPAD; } }+- if (!_stick[0]) { CGFloat s = dist(p, self.stickHome) / MAX([self stickR:0] * K_STICK_GRAB, _layout.separated ? 22 : 0); if (s < best) { best = s; kind = C_STICK; } }++ int kind = hit.kind == DM_PAD_HIT_FACE ? C_FACE : hit.kind == DM_PAD_HIT_DPAD ? C_DPAD : hit.kind == DM_PAD_HIT_STICK ? C_STICK : C_NONE, idx = 0;+ if (kind == C_NONE && _full && !_stick[1] && [self inRightArea:p]) { kind = C_STICK; idx = 1; _rCentre = p; [self hideHint]; } // the right stick: centred where the touch lands (the hint's job is done)+ if (kind == C_FACE) { [_owner setObject:@(C_FACE) forKey:t]; [_faceOf setObject:@([self faceAt:p]) forKey:t]; }+ else if (kind == C_DPAD) [_owner setObject:@(C_DPAD) forKey:t];+diff --git a/dm/ios/Sources/DmPadGeometry.h b/dm/ios/Sources/DmPadGeometry.h+index e6abdd0..7eeb8bc 100644+--- a/dm/ios/Sources/DmPadGeometry.h++++ b/dm/ios/Sources/DmPadGeometry.h+@@ -3,8 +3,9 @@+ // Every length is in u (1 = 430 points tall, iPhone Pro Max landscape), x measured from the outer edge, the right half mirrors.+ // The options come from the environment (the shell's settings, Documents/env.txt): DM_TOUCH_SIZE = small | medium | large scales u.+ // DM_TOUCH_STICK = corner | higher | inward places the left stick (inward takes the D-pad along); the right-hand controls never move.++// DM_TOUCH_LAYOUT moves single controls, one arrangement per layout (2D, 3D, and both again for the split screen): see "The player's arrangement".+ // An option never moves a control off the screen or onto another one: a size that does not fit falls back step by step to the size that does+-// (dm_pad_geo_fits: every drawn shape inside its rectangle, no two drawn shapes overlap).++// (dm_pad_geo_fits: every drawn shape inside its rectangle, no two drawn shapes overlap), and a moved control that does not fit goes back to its place.+ #pragma once+ #import "DmLayout.h"+ #include <math.h>+@@ -16,9 +17,22 @@ enum { DM_PAD_ZL = 0, DM_PAD_L, DM_PAD_ZR, DM_PAD_R }; // the order of DmPadGe+ enum { DM_PAD_MINUS = 0, DM_PAD_PLUS }; // the order of DmPadGeo.pill++ enum { DM_PAD_STICK_CORNER = 0, DM_PAD_STICK_HIGHER, DM_PAD_STICK_INWARD }; // DM_TOUCH_STICK++++// The controls DM_TOUCH_LAYOUT can move, in the order they are placed, by their names in the value. face is the whole A B X Y diamond,++// a b x y one key of it (from where the diamond is). The layout button stays where it is.++enum { DM_PAD_C_FACE = 0, DM_PAD_C_A, DM_PAD_C_B, DM_PAD_C_X, DM_PAD_C_Y, DM_PAD_C_STICK, DM_PAD_C_DPAD, DM_PAD_C_ZL, DM_PAD_C_L, DM_PAD_C_ZR, DM_PAD_C_R,++ DM_PAD_C_L3, DM_PAD_C_R3, DM_PAD_C_MINUS, DM_PAD_C_PLUS, DM_PAD_C_N };++// The layouts a value holds an arrangement for: 2D, 3D, and the same two when the controls sit below the picture (DmLayout.separated:++// an iPad held upright, iPhone Duo's inner display upright or half open).++enum { DM_PAD_SET_2D = 0, DM_PAD_SET_3D, DM_PAD_SET_2D_SPLIT, DM_PAD_SET_3D_SPLIT, DM_PAD_SET_N };++// Each control's offset from its built-in place, in steps of a quarter of a face key's width at the player's size, so it scales with the++// controls and not with the screen. 0 0 is the built-in place.++typedef struct { signed char dx[DM_PAD_SET_N][DM_PAD_C_N], dy[DM_PAD_SET_N][DM_PAD_C_N]; } DmPadLayout;+++ typedef struct {+ CGFloat scale; // DM_TOUCH_SIZE: 0.8 small, 1 medium (the built-in size), 1.2 large+ int stick; // DM_TOUCH_STICK: where the left stick sits (the D-pad moves with it when it moves inward); the right-hand controls keep their place++ const DmPadLayout *_Nullable layout; // DM_TOUCH_LAYOUT: the player's arrangement, NULL for none+ } DmPadOptions;++ typedef struct {+@@ -32,6 +46,9 @@ typedef struct {+ CGPoint click[2]; CGFloat clickR; // L3, R3 (3D only)+ CGRect pill[2]; // −, ++ CGPoint swap; CGFloat swapR; // the layout button++ CGPoint faceKey[4]; // A B X Y where they are: the diamond around face, unless a key was moved on its own++ BOOL faceSplit; // a key of the diamond was moved on its own: the diamond is then grabbed key by key++ unsigned moved, dropped; // DM_TOUCH_LAYOUT: the controls (1 << DM_PAD_C_*) it moved, and the ones it asked to move that kept their place+ } DmPadGeo;++ // Layout constants (in u), the values DmGamepad.m has always used.+@@ -65,6 +82,10 @@ static inline int dm_pad_stick_place(const char *_Nullable v) {+ static const CGFloat DM_PAD_STICK_UP = 70, DM_PAD_STICK_IN = 60; // how far higher / inward moves the left stick (in u), at most++ static inline CGPoint dm_pad_side(CGRect s, int right, CGFloat dx, CGFloat y) { return CGPointMake(right ? CGRectGetMaxX(s) - dx : CGRectGetMinX(s) + dx, y); }++// A key of the diamond around c: A right, B bottom, X top, Y left (i = 0..3 in that order).++static inline CGPoint dm_pad_diamond_key(CGPoint c, CGFloat d, int i) {++ switch (i) { case 0: return CGPointMake(c.x + d, c.y); case 1: return CGPointMake(c.x, c.y + d); case 2: return CGPointMake(c.x, c.y - d); default: return CGPointMake(c.x - d, c.y); }++}++ // The geometry at one unit, with no fitting.+ static inline DmPadGeo dm_pad_geo_at(CGRect bounds, UIEdgeInsets insets, DmLayout layout, BOOL full, CGFloat u) {+@@ -105,14 +126,12 @@ static inline DmPadGeo dm_pad_geo_at(CGRect bounds, UIEdgeInsets insets, DmLayou+ g.pill[i] = CGRectMake(x - w / 2, top - h / 2, w, h);+ }+ g.swap = CGPointMake(CGRectGetMidX(s), top); g.swapR = DM_PAD_SWAP_R * u;++ for (int i = 0; i < 4; i++) g.faceKey[i] = dm_pad_diamond_key(g.face, g.faceGap, i);+ return g;+ }++ // The face key positions: A right, B bottom, X top, Y left (i = 0..3 in that order).+-static inline CGPoint dm_pad_face_key(const DmPadGeo *g, int i) {+- CGPoint c = g->face; CGFloat d = g->faceGap;+- switch (i) { case 0: return CGPointMake(c.x + d, c.y); case 1: return CGPointMake(c.x, c.y + d); case 2: return CGPointMake(c.x, c.y - d); default: return CGPointMake(c.x - d, c.y); }+-}++static inline CGPoint dm_pad_face_key(const DmPadGeo *g, int i) { return g->faceKey[i]; }+ static inline CGPoint dm_pad_drop_tip(const DmPadGeo *g, int i) {+ CGFloat a = i >= DM_PAD_ZR ? -M_PI_4 : -3 * M_PI_4, d = g->dropR[i] * DM_PAD_DROP_TIP; // tip toward the near top corner+ return CGPointMake(g->drop[i].x + d * cos(a), g->drop[i].y + d * sin(a));+@@ -172,9 +191,10 @@ static inline CGFloat dm_pad_base_unit(CGRect bounds, UIEdgeInsets insets, DmLay+ return MIN(MIN(s.size.height / 430.0, s.size.width / 700.0), 1.3);+ }++-// The geometry the gamepad draws: the player's size, moved toward the built-in size in steps until it fits (a large size that does+-// not fit gets smaller; a small one in a split region whose minimum edges crowd it gets larger). The built-in size is never changed.+-static inline DmPadGeo dm_pad_geo(CGRect bounds, UIEdgeInsets insets, DmLayout layout, BOOL full, DmPadOptions o) {++// The geometry before the player's arrangement: the player's size, moved toward the built-in size in steps until it fits (a large size++// that does not fit gets smaller; a small one in a split region whose minimum edges crowd it gets larger), and the left stick's place.++// The built-in size is never changed.++static inline DmPadGeo dm_pad_geo_placed(CGRect bounds, UIEdgeInsets insets, DmLayout layout, BOOL full, DmPadOptions o) {+ CGFloat u0 = dm_pad_base_unit(bounds, insets, layout), scale = o.scale > 0 ? o.scale : 1;+ DmPadGeo g = dm_pad_geo_at(bounds, insets, layout, full, u0 * scale);+ while (scale != 1 && !dm_pad_geo_fits(&g, full)) {+@@ -196,6 +216,200 @@ static inline DmPadGeo dm_pad_geo(CGRect bounds, UIEdgeInsets insets, DmLayout l+ return g;+ }+++// ---- The player's arrangement (DM_TOUCH_LAYOUT) ----++// One value for every game, written by the shell's layout editor: "1", then for each layout ";", its name and "/control:dx,dy" for each moved++// control, for example 1;2d/face:0,-2/stick:1,-1;3d/a:-1,0 (layouts 2d 3d 2s 3s, controls as dm_pad_control_names, steps -64 to 64, y down).++// An unknown layout or control is skipped (a newer shell). Anything else that is not this form, or a value longer than DM_PAD_LAYOUT_MAX,++// is ignored whole, so every control keeps its built-in place. A value with no field for a control or a layout leaves it where it is.++// dm_pad_arrange then moves a control only to where it stays inside the area its built-in place uses and clear of every other control.++static const char *_Nonnull const dm_pad_control_names[DM_PAD_C_N] = {"face", "a", "b", "x", "y", "stick", "dpad", "zl", "l", "zr", "r", "l3", "r3", "minus", "plus"};++static const char *_Nonnull const dm_pad_set_names[DM_PAD_SET_N] = {"2d", "3d", "2s", "3s"};++enum { DM_PAD_LAYOUT_MAX = 1024, DM_PAD_STEP_MAX = 64 };++static const CGFloat DM_PAD_MOVE_GAP = 10; // a moved control keeps this far from every other drawn control: 10 u, and at least 10 points++++static inline int dm_pad_name_index(const char *p, size_t n, const char *_Nonnull const *_Nonnull names, int count) {++ for (int i = 0; i < count; i++) if (strlen(names[i]) == n && !strncmp(p, names[i], n)) return i;++ return -1;++}++static inline BOOL dm_pad_parse_step(const char *_Nonnull *_Nonnull pp, signed char *out) {++ const char *p = *pp; int sign = 1, v = 0, digits = 0;++ if (*p == '-') { sign = -1; p++; }++ while (*p >= '0' && *p <= '9') { if (++digits > 3) return NO; v = v * 10 + (*p++ - '0'); }++ if (!digits || v > DM_PAD_STEP_MAX) return NO;++ *out = (signed char)(sign * v); *pp = p;++ return YES;++}++// NO for a value it ignored. out is then the built-in layout, as for an unset or empty value (which give YES).++static inline BOOL dm_pad_layout_parse(const char *_Nullable v, DmPadLayout *out) {++ memset(out, 0, sizeof *out);++ if (!v || !*v) return YES;++ if (strnlen(v, DM_PAD_LAYOUT_MAX + 1) > DM_PAD_LAYOUT_MAX || v[0] != '1' || (v[1] && v[1] != ';')) return NO;++ DmPadLayout l; memset(&l, 0, sizeof l);++ const char *p = v + 1;++ while (*p == ';') {++ const char *name = ++p;++ while (*p && *p != '/' && *p != ';') p++;++ int set = dm_pad_name_index(name, (size_t)(p - name), dm_pad_set_names, DM_PAD_SET_N);++ while (*p == '/') {++ const char *control = ++p;++ while ((*p >= 'a' && *p <= 'z') || (*p >= '0' && *p <= '9')) p++;++ size_t n = (size_t)(p - control);++ signed char dx, dy;++ if (!n || *p != ':') return NO;++ p++;++ if (!dm_pad_parse_step(&p, &dx) || *p != ',') return NO;++ p++;++ if (!dm_pad_parse_step(&p, &dy)) return NO;++ int c = dm_pad_name_index(control, n, dm_pad_control_names, DM_PAD_C_N);++ if (set >= 0 && c >= 0) { l.dx[set][c] = dx; l.dy[set][c] = dy; }++ }++ if (*p && *p != ';') return NO;++ }++ if (*p) return NO;++ *out = l;++ return YES;++}++static inline int dm_pad_layout_count(const DmPadLayout *l) { // the moved controls a value holds, over every layout++ int n = 0;++ for (int s = 0; s < DM_PAD_SET_N; s++) for (int c = 0; c < DM_PAD_C_N; c++) n += l->dx[s][c] || l->dy[s][c];++ return n;++}++++// The drawn shapes (dm_pad_shapes ids) of a control.++static inline BOOL dm_pad_is_shape_of(int id, int c) {++ switch (c) {++ case DM_PAD_C_FACE: return id >= DM_PAD_SHAPE_FACE && id < DM_PAD_SHAPE_FACE + 4;++ case DM_PAD_C_A: case DM_PAD_C_B: case DM_PAD_C_X: case DM_PAD_C_Y: return id == DM_PAD_SHAPE_FACE + (c - DM_PAD_C_A);++ case DM_PAD_C_STICK: return id == DM_PAD_SHAPE_STICK;++ case DM_PAD_C_DPAD: return id == DM_PAD_SHAPE_DPAD;++ case DM_PAD_C_L3: case DM_PAD_C_R3: return id == DM_PAD_SHAPE_CLICK + (c - DM_PAD_C_L3);++ case DM_PAD_C_MINUS: case DM_PAD_C_PLUS: return id == DM_PAD_SHAPE_PILL + (c - DM_PAD_C_MINUS);++ default: return id == DM_PAD_SHAPE_DROP + (c - DM_PAD_C_ZL) || id == DM_PAD_SHAPE_TIP + (c - DM_PAD_C_ZL);++ }++}++static inline BOOL dm_pad_control_drawn(int c, BOOL full) { return full || (c != DM_PAD_C_DPAD && c != DM_PAD_C_L3 && c != DM_PAD_C_R3); }++static inline void dm_pad_shift(CGPoint *p, CGFloat dx, CGFloat dy) { p->x += dx; p->y += dy; }++static inline void dm_pad_move(DmPadGeo *g, int c, CGFloat dx, CGFloat dy) {++ switch (c) {++ case DM_PAD_C_FACE: dm_pad_shift(&g->face, dx, dy); for (int i = 0; i < 4; i++) dm_pad_shift(&g->faceKey[i], dx, dy); break;++ case DM_PAD_C_A: case DM_PAD_C_B: case DM_PAD_C_X: case DM_PAD_C_Y: dm_pad_shift(&g->faceKey[c - DM_PAD_C_A], dx, dy); break;++ case DM_PAD_C_STICK: dm_pad_shift(&g->stick, dx, dy); break;++ case DM_PAD_C_DPAD: dm_pad_shift(&g->dpad, dx, dy); break;++ case DM_PAD_C_L3: case DM_PAD_C_R3: dm_pad_shift(&g->click[c - DM_PAD_C_L3], dx, dy); break;++ case DM_PAD_C_MINUS: case DM_PAD_C_PLUS: dm_pad_shift(&g->pill[c - DM_PAD_C_MINUS].origin, dx, dy); break;++ default: dm_pad_shift(&g->drop[c - DM_PAD_C_ZL], dx, dy); break;++ }++}++static inline CGRect dm_pad_shape_box(const DmPadShape *s) { return s->isRect ? s->rect : CGRectMake(s->c.x - s->r, s->c.y - s->r, 2 * s->r, 2 * s->r); }++// a and b closer than gap (a grown by gap all round, a rectangle with square corners: on the safe side).++static inline BOOL dm_pad_shapes_near(const DmPadShape *a, const DmPadShape *b, CGFloat gap) {++ DmPadShape x = *a;++ if (x.isRect) x.rect = CGRectInset(x.rect, -gap, -gap); else x.r += gap;++ return dm_pad_shapes_overlap(&x, b);++}++// Control c where g has it: every shape of it inside its rectangle (the one its built-in place uses), and none closer than the gap to a shape of++// another control.++static inline BOOL dm_pad_control_fits(const DmPadGeo *g, BOOL full, int c) {++ DmPadShape s[20]; int n = dm_pad_shapes(g, full, s);++ CGFloat gap = fmax(DM_PAD_MOVE_GAP * g->u, DM_PAD_MOVE_GAP);++ for (int i = 0; i < n; i++) {++ if (!dm_pad_is_shape_of(s[i].id, c)) continue;++ if (!dm_pad_shape_inside(&s[i])) return NO;++ for (int j = 0; j < n; j++) if (!dm_pad_is_shape_of(s[j].id, c) && dm_pad_shapes_near(&s[i], &s[j], gap)) return NO;++ }++ return YES;++}++static inline CGFloat dm_pad_clamp_1d(CGFloat lo, CGFloat hi, CGFloat rlo, CGFloat rhi) { // the shift that brings lo..hi inside rlo..rhi (centred if wider)++ if (hi - lo > rhi - rlo) return (rlo + rhi) / 2 - (lo + hi) / 2;++ return lo < rlo ? rlo - lo : hi > rhi ? rhi - hi : 0;++}++// How far control c has to move to be inside its rectangle: a control dragged past the edge stops at the edge.++static inline CGPoint dm_pad_clamp(const DmPadGeo *g, BOOL full, int c) {++ DmPadShape s[20]; int n = dm_pad_shapes(g, full, s);++ CGFloat x0 = CGFLOAT_MAX, y0 = CGFLOAT_MAX, x1 = -CGFLOAT_MAX, y1 = -CGFLOAT_MAX; CGRect within = CGRectNull;++ for (int i = 0; i < n; i++) if (dm_pad_is_shape_of(s[i].id, c)) {++ CGRect b = dm_pad_shape_box(&s[i]); within = s[i].within;++ x0 = fmin(x0, CGRectGetMinX(b)); y0 = fmin(y0, CGRectGetMinY(b)); x1 = fmax(x1, CGRectGetMaxX(b)); y1 = fmax(y1, CGRectGetMaxY(b));++ }++ if (CGRectIsNull(within)) return CGPointZero;++ return CGPointMake(dm_pad_clamp_1d(x0, x1, CGRectGetMinX(within), CGRectGetMaxX(within)), dm_pad_clamp_1d(y0, y1, CGRectGetMinY(within), CGRectGetMaxY(within)));++}++// The arrangement of the current layout, on top of the size and the stick's place. Two rounds: the diamond and the other controls, then the++// keys of the diamond on their own, from where the diamond ended up. Each round places every control that fits and tries the rest again,++// so a control can take a place another one has left. A control that never fits keeps its place (dropped). Whatever the value, the result++// is a layout in which every control is inside its area and no two overlap.++static inline void dm_pad_arrange(DmPadGeo *g, BOOL full, BOOL separated, const DmPadLayout *layout) {++ int set = (separated ? DM_PAD_SET_2D_SPLIT : DM_PAD_SET_2D) + (full ? 1 : 0);++ CGFloat step = g->faceR / 2; // a quarter of a face key's width++ const unsigned keys = 1u << DM_PAD_C_A | 1u << DM_PAD_C_B | 1u << DM_PAD_C_X | 1u << DM_PAD_C_Y;++ unsigned want = 0;++ for (int c = 0; c < DM_PAD_C_N; c++) if (dm_pad_control_drawn(c, full) && (layout->dx[set][c] || layout->dy[set][c])) want |= 1u << c;++ for (int round = 0; round < 2; round++) {++ unsigned todo = want & (round ? keys : ~keys);++ for (BOOL progress = YES; todo && progress; ) {++ progress = NO;++ for (int c = 0; c < DM_PAD_C_N; c++) if (todo & (1u << c)) {++ DmPadGeo t = *g;++ dm_pad_move(&t, c, layout->dx[set][c] * step, layout->dy[set][c] * step);++ CGPoint d = dm_pad_clamp(&t, full, c);++ dm_pad_move(&t, c, d.x, d.y);++ if (!dm_pad_control_fits(&t, full, c)) continue;++ *g = t; g->moved |= 1u << c; todo &= ~(1u << c); progress = YES;++ if ((1u << c) & keys) g->faceSplit = YES;++ }++ }++ g->dropped |= todo;++ }++}++++// The geometry the gamepad draws, hit-tests and grabs with: the size and the stick's place (dm_pad_geo_placed), then the player's arrangement.++static inline DmPadGeo dm_pad_geo(CGRect bounds, UIEdgeInsets insets, DmLayout layout, BOOL full, DmPadOptions o) {++ DmPadGeo g = dm_pad_geo_placed(bounds, insets, layout, full, o);++ if (o.layout) dm_pad_arrange(&g, full, layout.separated, o.layout);++ return g;++}++++// ---- Which control a touch-down takes ----++// Locked keys first (the shoulders, − and +, L3 / R3: in the overlay layout the first in this order that is near enough, in the split one++// or with a moved control the nearest), the layout button, then whichever of the diamond, the D-pad and the left stick is nearest in units++// of its grab radius. NONE: no control (in 3D the right third then holds the right stick, else the touch goes to the game).++enum { DM_PAD_HIT_NONE = 0, DM_PAD_HIT_KEY, DM_PAD_HIT_SWAP, DM_PAD_HIT_FACE, DM_PAD_HIT_DPAD, DM_PAD_HIT_STICK };++typedef struct { int kind, key; } DmPadHit; // key: the DM_PAD_C_* of a locked key++static const int dm_pad_locked[8] = {DM_PAD_C_ZL, DM_PAD_C_L, DM_PAD_C_ZR, DM_PAD_C_R, DM_PAD_C_MINUS, DM_PAD_C_PLUS, DM_PAD_C_L3, DM_PAD_C_R3};++static const CGFloat DM_PAD_STICK_GRAB = 1.4, DM_PAD_DPAD_GRAB = 1.3; // grab radius: times the ring radius, times the D-pad's outer edge++static inline CGFloat dm_pad_dist(CGPoint a, CGPoint b) { return hypot(a.x - b.x, a.y - b.y); }++// A locked key's distance from p in units of its hit radius (1 or less is a hit).++static inline CGFloat dm_pad_key_distance(const DmPadGeo *g, BOOL sep, int c, CGPoint p) {++ if (c >= DM_PAD_C_ZL && c <= DM_PAD_C_R) return dm_pad_dist(p, g->drop[c - DM_PAD_C_ZL]) / MAX(g->dropR[c - DM_PAD_C_ZL] * 1.35, sep ? 22 : 0);++ if (c == DM_PAD_C_L3 || c == DM_PAD_C_R3) return dm_pad_dist(p, g->click[c - DM_PAD_C_L3]) / MAX(g->clickR * 1.35, sep ? 22 : 0);++ CGRect r = CGRectInset(g->pill[c - DM_PAD_C_MINUS], -8 * g->u, -8 * g->u);++ if (!sep && !CGRectContainsPoint(r, p)) return CGFLOAT_MAX;++ CGFloat w = MAX(r.size.width, sep ? 28 : 0), h = MAX(r.size.height, sep ? 28 : 0);++ return MAX(fabs(p.x - CGRectGetMidX(r)) / (w / 2), fabs(p.y - CGRectGetMidY(r)) / (h / 2));++}++static inline CGFloat dm_pad_swap_distance(const DmPadGeo *g, BOOL sep, CGPoint p) { return dm_pad_dist(p, g->swap) / MAX(g->swapR * 1.6, sep ? 14 : 0); }++// tap: the Tap layout (only the layout button is a control). stickFree: no touch holds the left stick yet.++static inline DmPadHit dm_pad_hit(const DmPadGeo *g, BOOL full, BOOL sep, BOOL tap, BOOL stickFree, CGPoint p) {++ int key = -1; CGFloat kd = 1;++ if (!tap) for (int i = 0; i < 8; i++) {++ int c = dm_pad_locked[i];++ if ((c == DM_PAD_C_L3 || c == DM_PAD_C_R3) && !full) continue;++ CGFloat d = dm_pad_key_distance(g, sep, c, p);++ if (d <= 1 && (key < 0 || d < kd)) { key = c; kd = d; if (!sep && !g->moved) break; }++ }++ CGFloat sd = dm_pad_swap_distance(g, sep, p);++ if (sd <= 1 && (key < 0 || (sep && sd < kd))) return (DmPadHit){DM_PAD_HIT_SWAP, -1};++ if (key >= 0) return (DmPadHit){DM_PAD_HIT_KEY, key};++ if (tap) return (DmPadHit){DM_PAD_HIT_NONE, -1};++ CGFloat best = 1, f = CGFLOAT_MAX; int kind = DM_PAD_HIT_NONE;++ if (g->faceSplit) for (int i = 0; i < 4; i++) f = fmin(f, dm_pad_dist(p, g->faceKey[i]) / MAX(g->faceR * 1.6, g->faceHitR));++ else f = dm_pad_dist(p, g->face) / (g->faceGap + MAX(g->faceR * 1.6, g->faceHitR));++ if (f <= best) { best = f; kind = DM_PAD_HIT_FACE; }++ if (full) { CGFloat d = dm_pad_dist(p, g->dpad) / MAX(g->dpadR * DM_PAD_DPAD_GRAB, sep ? 22 : 0); if (d < best) { best = d; kind = DM_PAD_HIT_DPAD; } }++ if (stickFree) { CGFloat s = dm_pad_dist(p, g->stick) / MAX(g->stickR * DM_PAD_STICK_GRAB, sep ? 22 : 0); if (s < best) { best = s; kind = DM_PAD_HIT_STICK; } }++ return (DmPadHit){kind, -1};++}+++ // Where the 3D layout's right-stick hint goes: a few words, no shape, in the area the undrawn right stick answers in (x from areaMinX to+ // the right edge), between the top row and the diamond, inside the safe area and clear of every drawn control (a gap of 6 u around it).+ // text is the label's size including its padding. CGRectNull when there is no room: the hint is then not shown.+diff --git a/dm/ios/tests/pad_geometry/pad_geometry_check.m b/dm/ios/tests/pad_geometry/pad_geometry_check.m+index 7bf7e8f..598327d 100644+--- a/dm/ios/tests/pad_geometry/pad_geometry_check.m++++ b/dm/ios/tests/pad_geometry/pad_geometry_check.m+@@ -33,6 +33,182 @@ static void check_fits(const Screen *s, BOOL full, const char *size, DmPadOption+ }+ }+++// ---- DM_TOUCH_LAYOUT ----++++static int g_arranged;++static BOOL layout_empty(const DmPadLayout *l) { return dm_pad_layout_count(l) == 0; }++++// The value's form: what is read, what is skipped, what is ignored whole.++static void check_layout_values(void) {++ DmPadLayout l;++ if (!dm_pad_layout_parse(NULL, &l) || !layout_empty(&l)) FAIL("DM_TOUCH_LAYOUT unset: the built-in layout");++ if (!dm_pad_layout_parse("", &l) || !layout_empty(&l)) FAIL("DM_TOUCH_LAYOUT empty: the built-in layout");++ if (!dm_pad_layout_parse("1", &l) || !layout_empty(&l)) FAIL("DM_TOUCH_LAYOUT 1: nothing moved");++ if (!dm_pad_layout_parse("1;3d", &l) || !layout_empty(&l)) FAIL("DM_TOUCH_LAYOUT 1;3d: a layout with no field moves nothing");++ if (!dm_pad_layout_parse("1;2d/face:0,-2/stick:1,-1;3d/a:-1,0;3s/zl:64,-64", &l)++ || l.dx[DM_PAD_SET_2D][DM_PAD_C_FACE] != 0 || l.dy[DM_PAD_SET_2D][DM_PAD_C_FACE] != -2 || l.dx[DM_PAD_SET_2D][DM_PAD_C_STICK] != 1++ || l.dy[DM_PAD_SET_2D][DM_PAD_C_STICK] != -1 || l.dx[DM_PAD_SET_3D][DM_PAD_C_A] != -1 || l.dx[DM_PAD_SET_3D_SPLIT][DM_PAD_C_ZL] != 64++ || l.dy[DM_PAD_SET_3D_SPLIT][DM_PAD_C_ZL] != -64 || dm_pad_layout_count(&l) != 4) FAIL("DM_TOUCH_LAYOUT: a valid value is not read as written");++ // A newer shell's layout or control: skipped, the rest is read.++ if (!dm_pad_layout_parse("1;4d/a:1,1;2d/home:3,3/b:2,0", &l) || dm_pad_layout_count(&l) != 1 || l.dx[DM_PAD_SET_2D][DM_PAD_C_B] != 2)++ FAIL("DM_TOUCH_LAYOUT: an unknown layout or control is not skipped");++ // Anything else is ignored whole: the controls keep their built-in places.++ static const char *bad[] = {++ "2;2d/a:1,1", "x", "1x", "1;2d/a", "1;2d/a:", "1;2d/a:1", "1;2d/a:1,", "1;2d/a:1,1,1", "1;2d/a:+1,1", "1;2d/a:65,0", "1;2d/a:0,-65",++ "1;2d/a:1000,0", "1;2d/a:0001,0", "1;2d/A:1,1", "1;2d/a:1,1 ", " 1;2d/a:1,1", "1;2d/a:1,1/", "1;2d/:1,1", "1;2d/a:--1,1", "1;2d/a:1.5,1",++ "1;2d/a:1,1\n2d", "1;2d/a=1,1", "1;2d//a:1,1",++ };++ for (size_t i = 0; i < sizeof bad / sizeof *bad; i++) {++ memset(&l, 0x55, sizeof l);++ if (dm_pad_layout_parse(bad[i], &l) || !layout_empty(&l)) FAIL("DM_TOUCH_LAYOUT '%s' is not ignored", bad[i]);++ }++ // Too long: ignored whole, even when every part of it is a valid field.++ char longv[DM_PAD_LAYOUT_MAX + 64]; size_t n = 0;++ n += (size_t)snprintf(longv + n, sizeof longv - n, "1;2d");++ while (n < DM_PAD_LAYOUT_MAX + 8) n += (size_t)snprintf(longv + n, sizeof longv - n, "/a:1,1");++ if (dm_pad_layout_parse(longv, &l) || !layout_empty(&l)) FAIL("DM_TOUCH_LAYOUT of %zu characters is not ignored", n);++ longv[DM_PAD_LAYOUT_MAX - (DM_PAD_LAYOUT_MAX - 4) % 6] = 0; // the same fields, cut at a field's end below the limit++ if (!dm_pad_layout_parse(longv, &l) || l.dx[DM_PAD_SET_2D][DM_PAD_C_A] != 1) FAIL("DM_TOUCH_LAYOUT: a value just under the limit is not read");++ // Random bytes never crash the reader, and what it does not reject is a layout like any other (checked below by the arrangement).++ uint32_t r = 7;++ for (int k = 0; k < 20000; k++) {++ char v[48]; int len = 1 + (int)(r % 46);++ static const char alphabet[] = "1;/:,-0123456789abcdfilmnprstuvxyz23d2s3s";++ v[0] = '1';++ for (int i = 1; i < len; i++) { r ^= r << 13; r ^= r >> 17; r ^= r << 5; v[i] = alphabet[r % (sizeof alphabet - 1)]; }++ v[len] = 0;++ BOOL ok = dm_pad_layout_parse(v, &l);++ if (!ok && !layout_empty(&l)) FAIL("DM_TOUCH_LAYOUT '%s': rejected but not empty", v);++ for (int s = 0; s < DM_PAD_SET_N; s++) for (int c = 0; c < DM_PAD_C_N; c++)++ if (abs(l.dx[s][c]) > DM_PAD_STEP_MAX || abs(l.dy[s][c]) > DM_PAD_STEP_MAX) FAIL("DM_TOUCH_LAYOUT '%s': a step out of range", v);++ }++}++++static BOOL geo_equal(const DmPadGeo *a, const DmPadGeo *b) {++ #define SAME_PT(p, q) (CGPointEqualToPoint((p), (q)))++ if (a->u != b->u || !SAME_PT(a->face, b->face) || !SAME_PT(a->stick, b->stick) || !SAME_PT(a->dpad, b->dpad) || !SAME_PT(a->swap, b->swap)) return NO;++ for (int i = 0; i < 4; i++) if (!SAME_PT(a->drop[i], b->drop[i]) || !SAME_PT(a->faceKey[i], b->faceKey[i]) || a->dropR[i] != b->dropR[i]) return NO;++ for (int i = 0; i < 2; i++) if (!SAME_PT(a->click[i], b->click[i]) || !CGRectEqualToRect(a->pill[i], b->pill[i])) return NO;++ return a->faceSplit == b->faceSplit && a->moved == b->moved && a->dropped == b->dropped && a->faceR == b->faceR && a->stickR == b->stickR;++ #undef SAME_PT++}++++// Which control a shape id belongs to, as dm_pad_hit names it.++static void shape_owner(int id, int *kind, int *key) {++ *key = -1;++ if (id < DM_PAD_SHAPE_STICK) *kind = DM_PAD_HIT_FACE;++ else if (id == DM_PAD_SHAPE_STICK) *kind = DM_PAD_HIT_STICK;++ else if (id == DM_PAD_SHAPE_DPAD) *kind = DM_PAD_HIT_DPAD;++ else if (id < DM_PAD_SHAPE_TIP) { *kind = DM_PAD_HIT_KEY; *key = DM_PAD_C_ZL + (id - DM_PAD_SHAPE_DROP); }++ else if (id < DM_PAD_SHAPE_CLICK) *kind = -1; // a teardrop's tip: a point, no touch target of its own++ else if (id < DM_PAD_SHAPE_PILL) { *kind = DM_PAD_HIT_KEY; *key = DM_PAD_C_L3 + (id - DM_PAD_SHAPE_CLICK); }++ else if (id < DM_PAD_SHAPE_SWAP) { *kind = DM_PAD_HIT_KEY; *key = DM_PAD_C_MINUS + (id - DM_PAD_SHAPE_PILL); }++ else *kind = DM_PAD_HIT_SWAP;++}++++// Every rule of a geometry the gamepad may draw: every shape inside its rectangle and on the screen, no two overlapping, a moved control++// clear of every other by the gap, and a touch well inside a drawn control taken by that control (the hit-test reads the same geometry).++static void check_geo(const Screen *s, BOOL full, const DmPadGeo *g, const char *what) {++ DmLayout l = dm_layout(s->bounds, s->insets, s->partiallyOpen, s->division);++ DmPadShape sh[20]; int n = dm_pad_shapes(g, full, sh);++ for (int i = 0; i < n; i++) {++ if (!dm_pad_shape_inside(&sh[i])) FAIL("%s %s %s: shape %d leaves its rectangle", s->name, full ? "3D" : "2D", what, sh[i].id);++ CGRect b = dm_pad_shape_box(&sh[i]);++ if (!CGRectContainsRect(CGRectInset(s->bounds, -0.5, -0.5), b)) FAIL("%s %s %s: shape %d is off the screen", s->name, full ? "3D" : "2D", what, sh[i].id);++ for (int j = i + 1; j < n; j++)++ if (!dm_pad_same_control(&sh[i], &sh[j]) && dm_pad_shapes_overlap(&sh[i], &sh[j]))++ FAIL("%s %s %s: shapes %d and %d overlap", s->name, full ? "3D" : "2D", what, sh[i].id, sh[j].id);++ }++ for (int c = 0; c < DM_PAD_C_N; c++)++ if ((g->moved & (1u << c)) && !dm_pad_control_fits(g, full, c)) FAIL("%s %s %s: moved control %s is too close to another", s->name, full ? "3D" : "2D", what, dm_pad_control_names[c]);++ if (g->moved & g->dropped) FAIL("%s %s: a control is both moved and dropped", s->name, what);++ // Touches: the centre of each control and points halfway to its edge (the D-pad on its arms, a pill along its length).++ for (int i = 0; i < n; i++) {++ int kind, key; shape_owner(sh[i].id, &kind, &key);++ if (kind < 0) continue;++ CGPoint pts[5]; int np = 0; pts[np++] = sh[i].isRect ? CGPointMake(CGRectGetMidX(sh[i].rect), CGRectGetMidY(sh[i].rect)) : sh[i].c;++ if (sh[i].isRect) { CGFloat w = sh[i].rect.size.width * 0.3; pts[np++] = CGPointMake(pts[0].x - w, pts[0].y); pts[np++] = CGPointMake(pts[0].x + w, pts[0].y); }++ else {++ CGFloat r = sh[i].id == DM_PAD_SHAPE_DPAD ? g->dpadR * 0.6 : sh[i].r * 0.5;++ for (int k = 0; k < 4; k++) pts[np++] = CGPointMake(sh[i].c.x + (k == 0 ? r : k == 1 ? -r : 0), sh[i].c.y + (k == 2 ? r : k == 3 ? -r : 0));++ }++ for (int k = 0; k < np; k++) {++ DmPadHit h = dm_pad_hit(g, full, l.separated, NO, YES, pts[k]);++ if (h.kind != kind || (kind == DM_PAD_HIT_KEY && h.key != key))++ FAIL("%s %s %s: a touch at %.0f %.0f inside shape %d goes to %d/%d (moved %#x)", s->name, full ? "3D" : "2D", what, pts[k].x, pts[k].y, sh[i].id, h.kind, h.key, g->moved);++ }++ }++}++++static uint32_t g_rng = 2026;++static uint32_t rnd(void) { g_rng ^= g_rng << 13; g_rng ^= g_rng >> 17; g_rng ^= g_rng << 5; return g_rng; }++++static void check_arrangement(const Screen *screens, int nscreens) {++ // Reset: a layout of zeros, a value that names a control at 0 0, and a value for other layouts are the built-in geometry exactly,++ // the points the gamepad has always used (pinned above on the Pro Max).++ DmPadLayout zero, named, other; memset(&zero, 0, sizeof zero);++ dm_pad_layout_parse("1;2d/face:0,0/stick:0,0;3d/a:0,0/zl:0,0", &named);++ dm_pad_layout_parse("1;2s/face:3,-2/stick:2,-2;3s/a:-2,0", &other); // only the split layouts++ for (int i = 0; i < nscreens; i++)++ for (int full = 0; full < 2; full++)++ for (int z = 0; z < 3; z++) {++ DmLayout l = dm_layout(screens[i].bounds, screens[i].insets, screens[i].partiallyOpen, screens[i].division);++ DmPadOptions o = {dm_pad_size_scale(k_sizes[z]), 0, NULL};++ DmPadGeo none = dm_pad_geo(screens[i].bounds, screens[i].insets, l, full, o);++ o.layout = &zero; DmPadGeo a = dm_pad_geo(screens[i].bounds, screens[i].insets, l, full, o);++ o.layout = &named; DmPadGeo b = dm_pad_geo(screens[i].bounds, screens[i].insets, l, full, o);++ if (!geo_equal(&none, &a) || !geo_equal(&none, &b)) FAIL("%s %s %s: an arrangement of zeros is not the built-in layout", screens[i].name, full ? "3D" : "2D", k_sizes[z]);++ o.layout = &other; DmPadGeo c = dm_pad_geo(screens[i].bounds, screens[i].insets, l, full, o);++ if (!l.separated && !geo_equal(&none, &c)) FAIL("%s %s: the split layouts' arrangement moved the overlay layout", screens[i].name, full ? "3D" : "2D");++ check_geo(&screens[i], full, &none, k_sizes[z]);++ }++ { // On the Pro Max: a move that fits lands where asked, a move onto another control is dropped, a move past the edge stops at it.++ const Screen *s = &screens[3];++ DmLayout l = dm_layout(s->bounds, s->insets, NO, CGRectNull);++ DmPadLayout m; dm_pad_layout_parse("1;3d/face:-4,-4/stick:0,-3/minus:-2,2/b:0,1", &m);++ DmPadOptions o = {1, 0, &m};++ DmPadGeo base = dm_pad_geo(s->bounds, s->insets, l, YES, (DmPadOptions){1}), g = dm_pad_geo(s->bounds, s->insets, l, YES, o);++ CGFloat step = 13.5; // a quarter of the 54-point face key++ if (!NEAR(g.face.x, base.face.x - 4 * step) || !NEAR(g.face.y, base.face.y - 4 * step)) FAIL("Pro Max: the diamond did not move by 4 4 steps");++ if (!NEAR(g.faceKey[0].x, base.faceKey[0].x - 4 * step) || !NEAR(g.faceKey[1].y, base.faceKey[1].y - 3 * step)) FAIL("Pro Max: the keys did not follow the diamond, B its own step");++ if (!NEAR(g.stick.x, base.stick.x) || !NEAR(g.stick.y, base.stick.y - 3 * step)) FAIL("Pro Max: the stick did not move");++ if (!NEAR(g.pill[DM_PAD_MINUS].origin.x, base.pill[DM_PAD_MINUS].origin.x - 2 * step) || !NEAR(g.pill[DM_PAD_MINUS].origin.y, base.pill[DM_PAD_MINUS].origin.y + 2 * step)) FAIL("Pro Max: minus did not move");++ if (g.dropped || !g.faceSplit) FAIL("Pro Max: a move that fits was dropped (%#x)", g.dropped);++ dm_pad_layout_parse("1;3d/stick:52,0/zl:0,-40/dpad:-30,0", &m); // the stick onto the diamond, ZL past the top, the D-pad past the left edge++ g = dm_pad_geo(s->bounds, s->insets, l, YES, o);++ if (!CGPointEqualToPoint(g.stick, base.stick) || !(g.dropped & 1u << DM_PAD_C_STICK)) FAIL("Pro Max: the stick moved onto the diamond");++ if (!NEAR(g.drop[DM_PAD_ZL].y - g.dropR[DM_PAD_ZL] * DM_PAD_DROP_TIP * sin(M_PI_4), CGRectGetMinY(g.safe))) FAIL("Pro Max: ZL past the top does not stop at the edge (%.1f)", g.drop[DM_PAD_ZL].y);++ if (g.moved & 1u << DM_PAD_C_DPAD) {++ if (!NEAR(g.dpad.x - hypot(g.dpadR, g.armW), CGRectGetMinX(g.corner))) FAIL("Pro Max: the D-pad past the edge does not stop at it");++ }++ // A control can take the place another one left: the stick into the D-pad's place while the D-pad goes elsewhere (ordered after the stick).++ dm_pad_layout_parse("1;3d/stick:11,1/dpad:0,-12", &m);++ g = dm_pad_geo(s->bounds, s->insets, l, YES, o);++ if (g.dropped) FAIL("Pro Max: the stick could not take the D-pad's old place (%#x)", g.dropped);++ check_geo(s, YES, &g, "swap");++ }++ // The fuzz: seeded random arrangements on every screen, layout, size and stick place. Whatever is asked, the result keeps every rule.++ for (int i = 0; i < nscreens; i++)++ for (int full = 0; full < 2; full++)++ for (int z = 0; z < 3; z++)++ for (int p = 0; p < 3; p++)++ for (int k = 0; k < 40; k++) {++ DmPadLayout m; memset(&m, 0, sizeof m);++ int moves = 1 + (int)(rnd() % 10);++ for (int j = 0; j < moves; j++) {++ int set = (int)(rnd() % DM_PAD_SET_N), c = (int)(rnd() % DM_PAD_C_N), wide = rnd() % 3 == 0;++ int range = wide ? DM_PAD_STEP_MAX : 8;++ m.dx[set][c] = (signed char)((int)(rnd() % (2 * range + 1)) - range);++ m.dy[set][c] = (signed char)((int)(rnd() % (2 * range + 1)) - range);++ }++ DmLayout l = dm_layout(screens[i].bounds, screens[i].insets, screens[i].partiallyOpen, screens[i].division);++ DmPadGeo g = dm_pad_geo(screens[i].bounds, screens[i].insets, l, full, (DmPadOptions){dm_pad_size_scale(k_sizes[z]), p, &m});++ char what[64]; snprintf(what, sizeof what, "%s stick %d fuzz %d", k_sizes[z], p, k);++ check_geo(&screens[i], full, &g, what);++ g_arranged++;++ }++}+++ int main(void) {+ const Screen screens[] = {+ // iPhone landscape (the phone's only orientation): the Dynamic Island or notch on one side, the home indicator at the bottom.+@@ -136,6 +312,9 @@ int main(void) {+ for (int k = 0; k < n; k++) if (dm_pad_shapes_overlap(&me, &sh[k])) FAIL("%s %s: the hint covers shape %d", screens[i].name, k_sizes[z], sh[k].id);+ }++- if (!g_fail) printf("ok: %d screens\n", nscreens);++ check_layout_values();++ check_arrangement(screens, nscreens);++++ if (!g_fail) printf("ok: %d screens, %d arrangements\n", nscreens, g_arranged);+ return g_fail > 100 ? 100 : g_fail;+ }+diff --git a/dm/ios/tests/test_pad_geometry.py b/dm/ios/tests/test_pad_geometry.py+index 9854dfd..44d0344 100644+--- a/dm/ios/tests/test_pad_geometry.py++++ b/dm/ios/tests/test_pad_geometry.py+@@ -3,8 +3,11 @@+ pad_geometry/pad_geometry_check.m runs the same pure functions DmGamepad.m draws, hit-tests and grabs with, on the iPhone, iPad+ and iPhone Duo screens (portrait, landscape, tabletop), in the 2D and the 3D layout and every DM_TOUCH_SIZE: every control stays+ inside the safe area (the bottom corners reach halfway into the side insets, as always), no two drawn controls overlap, and the+-built-in size is the layout the gamepad has always drawn. pad_geometry/UIKit/UIKit.h stands in for the few UIKit names the+-headers use, so no simulator is needed.++built-in size is the layout the gamepad has always drawn. The player's arrangement (DM_TOUCH_LAYOUT): a value of zeros is the++built-in layout exactly, a malformed or too-long value is ignored whole, and seeded random arrangements on every screen, layout,++size and stick place never put a control outside its area, onto another or nearer than the gap, and a touch inside a drawn control++always goes to that control (dm_pad_hit, the gamepad's own hit-test). pad_geometry/UIKit/UIKit.h stands in for the few UIKit names++the headers use, so no simulator is needed.+ """+ import shutil+ import subprocessdiff --git a/patches/series b/patches/seriesindex 447a07bd..25aaf86e 100644--- a/patches/series+++ b/patches/series@@ -43,3 +43,4 @@0065-ios-touch-controls-size.patch0066-ios-touch-stick-place.patch0067-ios-touch-right-stick-hint.patch+0068-ios-touch-layout.patch