diff --git a/frontend-qt/nspb_qt/localization.py b/frontend-qt/nspb_qt/localization.py index 4813e2142..0b8857ec5 100644 --- a/frontend-qt/nspb_qt/localization.py +++ b/frontend-qt/nspb_qt/localization.py @@ -395,10 +395,10 @@ 'nav.settings': ('设置', 'Settings', 'Inställningar', 'Einstellungen'), 'settings.language': ('界面语言', 'Language', 'Språk', 'Sprache'), 'settings.language.system': ('跟随系统', 'Follow system', 'Följ systemet', 'Systemsprache'), - 'settings.language.zh': ('中文', '中文', 'Kinesiska', '中文'), + 'settings.language.zh': ('中文', '中文', '中文', '中文'), 'settings.language.en': ('English', 'English', 'English', 'English'), - 'settings.language.sv': ('瑞典语', 'Swedish', 'Svenska', 'Schwedisch'), - 'settings.language.de': ('德语', 'German', 'Tyska', 'Deutsch'), + 'settings.language.sv': ('Svenska', 'Svenska', 'Svenska', 'Svenska'), + 'settings.language.de': ('Deutsch', 'Deutsch', 'Deutsch', 'Deutsch'), 'settings.appNote2': ('构建你自己的 Switch 游戏', 'Build your own Switch games', 'Bygg dina egna Switch-spel', 'Baue deine eigenen Switch-Spiele'), 'library.setupHint': ('首次构建前,请完成以下设置。', 'Before your first build, finish the setup below.', 'Slutför inställningen nedan före ditt första bygge.', 'Beende vor deinem ersten Build die Einrichtung weiter unten.'), 'library.ready': ('可在 Mac 上运行', 'Ready on Mac', 'Klar på Mac', 'Bereit auf dem Mac'), diff --git a/frontend/Sources/NSPortBuilder/ContentView.swift b/frontend/Sources/NSPortBuilder/ContentView.swift index 8137655a8..545e65de3 100644 --- a/frontend/Sources/NSPortBuilder/ContentView.swift +++ b/frontend/Sources/NSPortBuilder/ContentView.swift @@ -3122,7 +3122,7 @@ struct BuilderView: View { row(m.t("dev.target"), detail: m.devicesChecked && m.devices.isEmpty ? m.t("dev.noDevices") : "") { if !m.devicesChecked { ProgressView().controlSize(.small) } Button(m.t("dev.refresh")) { m.refreshDevices() }.buttonStyle(.plain).font(.manrope(13)).foregroundStyle(.secondary) - LauncherMenuPicker(options: devices, selection: m.installDevice) { m.installDevice = $0 } + LauncherDropdown(options: devices, selection: m.installDevice, label: m.t("dev.target")) { m.installDevice = $0 } } if !m.installDevice.isEmpty { divider @@ -3130,7 +3130,7 @@ struct BuilderView: View { row(m.t("dev.team"), detail: m.t("dev.noTeam"), dot: LauncherPalette.building) { EmptyView() } } else { row(m.t("dev.team")) { - LauncherMenuPicker(options: teams, selection: m.signingTeam) { m.signingTeam = $0 } + LauncherDropdown(options: teams, selection: m.signingTeam, label: m.t("dev.team")) { m.signingTeam = $0 } } } } @@ -3457,17 +3457,14 @@ struct BuilderView: View { row(m.t("settings.language"), detail: Lang.saved.map { m.t("settings.language.\($0.rawValue)") } ?? m.t("settings.language.system"), dot: LauncherPalette.ready, help: "") { - // The launcher's own list (as in Launch options), drawn like the buttons beside it and as wide - LauncherMenuPicker(options: [(value: "", label: m.t("settings.language.system")), - (value: "zh", label: m.t("settings.language.zh")), - (value: "en", label: m.t("settings.language.en")), - (value: "sv", label: m.t("settings.language.sv")), - (value: "de", label: m.t("settings.language.de"))], - selection: Lang.saved.map { $0.rawValue } ?? "", fill: true, buttonLike: true) { v in + // The launcher's own list, drawn like the buttons beside it and as wide as its label needs. + // The language names are in their own language (see "settings.language.*"), only "system" follows the UI. + LauncherDropdown(options: Self.languageCodes.map { (value: $0, label: m.t("settings.language." + ($0.isEmpty ? "system" : $0))) }, + selection: Lang.saved.map { $0.rawValue } ?? "", label: m.t("settings.language"), + style: .button, minWidth: Self.settingsPickerWidth) { v in Lang.saved = v.isEmpty ? nil : Lang(rawValue: v) m.lang = Lang.initial() } - .frame(width: Self.settingsPickerWidth) .padTarget("set.language", scope: "main", activate: { cycleLanguage(1) }, adjust: { cycleLanguage($0) }) } divider @@ -3516,8 +3513,12 @@ struct BuilderView: View { } /// The interface language one step on (a controller's left / right on the language list). + /// The language picker's choices in order, "" being the system's. A new language is one more code here and its + /// "settings.language." entry, which is its own name (Svenska, Deutsch) in every language. + static let languageCodes = ["", "zh", "en", "sv", "de"] + private func cycleLanguage(_ by: Int) { - let values = ["", "zh", "en", "sv", "de"] + let values = Self.languageCodes let at = values.firstIndex(of: Lang.saved.map { $0.rawValue } ?? "") ?? 0 let v = values[(at + by + values.count) % values.count] Lang.saved = v.isEmpty ? nil : Lang(rawValue: v) diff --git a/frontend/Sources/NSPortBuilder/ControlPresets.swift b/frontend/Sources/NSPortBuilder/ControlPresets.swift index 0e8359c87..e170c3d4a 100644 --- a/frontend/Sources/NSPortBuilder/ControlPresets.swift +++ b/frontend/Sources/NSPortBuilder/ControlPresets.swift @@ -60,8 +60,8 @@ struct PadModeSection: View { Text(connected).font(.manrope(12)).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) } Spacer(minLength: 12) - LauncherMenuPicker(options: PadMode.allCases.map { (value: $0.rawValue, label: label($0)) }, - selection: layout.padMode.rawValue, fill: true) { v in PadMode(rawValue: v).map(layout.setPadMode) } + LauncherDropdown(options: PadMode.allCases.map { (value: $0.rawValue, label: label($0)) }, + selection: layout.padMode.rawValue, label: m.t("controls.modeRow"), fill: true) { v in PadMode(rawValue: v).map(layout.setPadMode) } .frame(width: 168) // as wide as the button rows' choices below it .frame(width: LaunchControl.width, alignment: .trailing) } diff --git a/frontend/Sources/NSPortBuilder/Controls.swift b/frontend/Sources/NSPortBuilder/Controls.swift index aecac273a..be1873b0b 100644 --- a/frontend/Sources/NSPortBuilder/Controls.swift +++ b/frontend/Sources/NSPortBuilder/Controls.swift @@ -248,8 +248,8 @@ struct ControlsView: View { let at = choices.firstIndex(of: layout.sends(button)) ?? 0 layout.setSends(button, choices[(at + by + choices.count) % choices.count]) }) { - LauncherMenuPicker(options: ControlLayout.buttons.map { (value: $0, label: m.t("controls.fn." + $0)) } + [(value: "none", label: m.t("controls.none"))], - selection: layout.sends(button), fill: true) { layout.setSends(button, $0) } + LauncherDropdown(options: ControlLayout.buttons.map { (value: $0, label: m.t("controls.fn." + $0)) } + [(value: "none", label: m.t("controls.none"))], + selection: layout.sends(button), label: m.t("controls.fn." + button), fill: true) { layout.setSends(button, $0) } .frame(width: 168) // the keyboard rows' width (× and key field), and "Right stick press" fits } } diff --git a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift index 38cb5f1f8..6b6c93466 100644 --- a/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift +++ b/frontend/Sources/NSPortBuilder/LaunchOptionsView.swift @@ -210,7 +210,7 @@ struct LaunchOptionsView: View { if options.count <= 3 { LauncherSegmented(options: options, selection: value) { set(s, $0) } } else { - LauncherMenuPicker(options: options, selection: value, fill: true) { set(s, $0) } + LauncherDropdown(options: options, selection: value, label: s.label, fill: true) { set(s, $0) } } case "range": let lo = s.min ?? 0, hi = s.max ?? 1 diff --git a/frontend/Sources/NSPortBuilder/LauncherDropdown.swift b/frontend/Sources/NSPortBuilder/LauncherDropdown.swift new file mode 100644 index 000000000..dd90c00ce --- /dev/null +++ b/frontend/Sources/NSPortBuilder/LauncherDropdown.swift @@ -0,0 +1,305 @@ +import SwiftUI + +/// How a LauncherDropdown's button is drawn: `pill` is the round choice beside a launch option, `button` is +/// LauncherSecondaryButtonStyle's rounded rectangle (the Settings cards). +enum LauncherDropdownStyle { case pill, button } + +/// Where the list of an open dropdown goes and how big it is. Pure, so the rules are tested (LauncherDropdownTests). +enum LauncherDropdownLayout { + static let rowHeight: CGFloat = 34 + static let rowSpacing: CGFloat = 2 + static let padding: CGFloat = 6 + static let gap: CGFloat = 6 // between the button and its list + static let margin: CGFloat = 8 // kept free at the edges of the window + static let maxHeight: CGFloat = 320 + static let minWidth: CGFloat = 180 + static let maxWidth: CGFloat = 360 + + static func contentHeight(rows: Int) -> CGFloat { + CGFloat(rows) * rowHeight + CGFloat(max(rows - 1, 0)) * rowSpacing + padding * 2 + } + + /// As wide as the longest label needs (plus room for the checkmark), never narrower than the button. + static func width(labels: [String], button: CGFloat) -> CGFloat { + let font = NSFont.systemFont(ofSize: 13, weight: .semibold) + let widest = labels.map { ceil(($0 as NSString).size(withAttributes: [.font: font]).width * 1.1) }.max() ?? 0 + return min(max(widest + 12 * 2 + 16 + 12 + padding * 2, button, minWidth), maxWidth) + } + + /// The list opens below the button, above it when there is no room below, and takes the bigger side when it fits on + /// neither (then it scrolls). A button in the right half of the window gets its list aligned to its right edge. + static func place(button: CGRect, container: CGSize, rows: Int, width: CGFloat) -> (origin: CGPoint, size: CGSize) { + let wanted = min(contentHeight(rows: rows), maxHeight) + let below = container.height - margin - (button.maxY + gap) + let above = button.minY - gap - margin + let opensBelow = below >= wanted || below >= above + let height = max(min(wanted, opensBelow ? below : above), rowHeight + padding * 2) + let y = opensBelow ? button.maxY + gap : button.minY - gap - height + let preferredX = button.midX > container.width / 2 ? button.maxX - width : button.minX + let x = min(max(preferredX, margin), max(margin, container.width - width - margin)) + return (CGPoint(x: x, y: max(y, margin)), CGSize(width: width, height: height)) + } + + /// The row an arrow key lands on, wrapping at the ends. Without a highlighted row Down takes the first, Up the last. + static func step(from current: Int?, by delta: Int, count: Int) -> Int? { + guard count > 0 else { return nil } + guard let current else { return delta > 0 ? 0 : count - 1 } + return (current + delta % count + count) % count + } +} + +/// One dropdown being open: what its list shows and what a pick does. +struct LauncherDropdownRequest { + let id: UUID + let options: [(value: String, label: String)] + let selection: String + let label: String + let choose: (String) -> Void +} + +/// The open dropdown of one window or sheet, shared by the host (which draws the list) and the buttons (which open it). +final class LauncherDropdownState: ObservableObject { + @Published var request: LauncherDropdownRequest? + func close() { withAnimation(.easeOut(duration: 0.12)) { request = nil } } +} + +private struct LauncherDropdownHostKey: EnvironmentKey { static let defaultValue: LauncherDropdownState? = nil } + +extension EnvironmentValues { + var launcherDropdownHost: LauncherDropdownState? { + get { self[LauncherDropdownHostKey.self] } + set { self[LauncherDropdownHostKey.self] = newValue } + } +} + +/// Each dropdown button reports its frame here, so the list opens against it and follows it when the page scrolls. +struct LauncherDropdownAnchorKey: PreferenceKey { + static var defaultValue: [UUID: Anchor] = [:] + static func reduce(value: inout [UUID: Anchor], nextValue: () -> [UUID: Anchor]) { + value.merge(nextValue()) { _, new in new } + } +} + +extension View { + /// Draws the open LauncherDropdown's list over this view, outside the clipping of the scroll view the button sits in. + /// Every window and sheet with dropdowns needs one at its root, because a sheet is a window of its own. + /// A dropdown without a host opens its list as a popover. + func launcherDropdownHost() -> some View { modifier(LauncherDropdownHost()) } +} + +extension View { + /// The list's own surface: the app's dark card with its border, radius and shadow. + func launcherDropdownSurface() -> some View { + background(LauncherPalette.surface, in: RoundedRectangle(cornerRadius: 12)) + .overlay(RoundedRectangle(cornerRadius: 12).strokeBorder(Color.white.opacity(0.10))) + .shadow(color: .black.opacity(0.5), radius: 18, y: 6) + } +} + +private struct LauncherDropdownHost: ViewModifier { + @StateObject private var state = LauncherDropdownState() + func body(content: Content) -> some View { + content + .environment(\.launcherDropdownHost, state) + .overlayPreferenceValue(LauncherDropdownAnchorKey.self) { anchors in + LauncherDropdownLayer(state: state, anchors: anchors) + } + } +} + +private struct LauncherDropdownLayer: View { + @ObservedObject var state: LauncherDropdownState + let anchors: [UUID: Anchor] + var body: some View { + GeometryReader { g in + if let request = state.request, let anchor = anchors[request.id] { + let button = g[anchor] + let width = LauncherDropdownLayout.width(labels: request.options.map(\.label), button: button.width) + let spot = LauncherDropdownLayout.place(button: button, container: g.size, rows: request.options.count, width: width) + ZStack(alignment: .topLeading) { + Color.black.opacity(0.001).contentShape(Rectangle()) + .onTapGesture { state.close() } + .accessibilityHidden(true) + LauncherDropdownList(options: request.options, selection: request.selection, label: request.label, + choose: { value in request.choose(value); state.close() }, close: { state.close() }) + .frame(width: spot.size.width, height: spot.size.height) + .launcherDropdownSurface() + .offset(x: spot.origin.x, y: spot.origin.y) + .transition(.opacity) + } + } + } + } +} + +/// The rows of an open dropdown: the chosen one with a checkmark, the one under the pointer or the arrow keys lit. +/// Arrow keys move, Return or Space pick, Esc closes (a local key monitor while it is open, as in the Manage menu). +struct LauncherDropdownList: View { + let options: [(value: String, label: String)] + let selection: String + let label: String + let choose: (String) -> Void + let close: () -> Void + @State private var highlighted: Int? + @State private var monitor: Any? + @AccessibilityFocusState private var spoken: Int? + + var body: some View { + ScrollViewReader { proxy in + ScrollView { + VStack(alignment: .leading, spacing: LauncherDropdownLayout.rowSpacing) { + ForEach(Array(options.enumerated()), id: \.offset) { index, option in row(option, index: index).id(index) } + } + .padding(LauncherDropdownLayout.padding) + } + .onChange(of: highlighted) { index in if let index { proxy.scrollTo(index) } } + .onAppear { + let at = options.firstIndex { $0.value == selection } + highlighted = at + if let at { proxy.scrollTo(at, anchor: .center) } + spoken = at ?? 0 + startKeys() + } + } + .onDisappear(perform: stopKeys) + .accessibilityElement(children: .contain) + .accessibilityLabel(label) + .accessibilityAddTraits(.isModal) + .accessibilityAction(.escape, close) + } + + private func row(_ option: (value: String, label: String), index: Int) -> some View { + let selected = option.value == selection + return Button { choose(option.value) } label: { + HStack(spacing: 10) { + Text(option.label).font(.manrope(13, selected ? .bold : .medium)).lineLimit(1) + Spacer(minLength: 16) + Image(systemName: "checkmark").font(.system(size: 11, weight: .bold)).foregroundStyle(LauncherPalette.cream) + .opacity(selected ? 1 : 0) + } + .foregroundStyle(Color.white.opacity(0.92)) + .padding(.horizontal, 12).frame(height: LauncherDropdownLayout.rowHeight) + .background(highlighted == index ? Color.white.opacity(0.09) : (selected ? Color.white.opacity(0.045) : .clear), + in: RoundedRectangle(cornerRadius: 8)) + .contentShape(RoundedRectangle(cornerRadius: 8)) + } + .buttonStyle(.plain) + .onHover { inside in + if inside { highlighted = index } else if highlighted == index { highlighted = nil } + } + .accessibilityLabel(option.label) + .accessibilityAddTraits(selected ? .isSelected : []) + .accessibilityFocused($spoken, equals: index) + } + + private func startKeys() { + stopKeys() + monitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in + switch event.keyCode { + case 125: highlighted = LauncherDropdownLayout.step(from: highlighted, by: 1, count: options.count) + case 126: highlighted = LauncherDropdownLayout.step(from: highlighted, by: -1, count: options.count) + case 36, 76, 49: if let i = highlighted, options.indices.contains(i) { choose(options[i].value) } + case 53: close() + case 48: close(); return event + default: return event + } + return nil + } + } + + private func stopKeys() { + if let monitor { NSEvent.removeMonitor(monitor) } + monitor = nil + } +} + +/// The launcher's dropdown: a button with the current choice that opens a list drawn in the app's own style +/// (its dark surface, Manrope, a checkmark on the chosen row). It never cuts the label short unless it is given +/// `fill` (the width of its container). With `minWidth` it is at least that wide and grows with its label. +/// `label` names the setting for VoiceOver, which then reads the choice as the value. +struct LauncherDropdown: View { + let options: [(value: String, label: String)] + let selection: String + var label = "" + var style: LauncherDropdownStyle = .pill + var fill = false + var minWidth: CGFloat? + let choose: (String) -> Void + @Environment(\.launcherDropdownHost) private var host + @State private var id = UUID() + + var body: some View { + if let host { + Hosted(host: host, dropdown: self) + } else { + Popped(dropdown: self) + } + } + + fileprivate var current: String { options.first { $0.value == selection }?.label ?? selection } + + fileprivate func face(open: Bool) -> some View { + let rounded = style == .button + let shape = RoundedRectangle(cornerRadius: rounded ? 9 : 99) + return HStack(spacing: 8) { + Text(current).font(.manrope(rounded ? 13 : 12.5, .semibold)).lineLimit(1) + .fixedSize(horizontal: !fill, vertical: false) + if fill || minWidth != nil { Spacer(minLength: 0) } + Image(systemName: "chevron.down").font(.system(size: 9, weight: .bold)).foregroundStyle(.secondary) + .rotationEffect(.degrees(open ? 180 : 0)) + } + .padding(.horizontal, rounded ? 15 : 14).padding(.vertical, rounded ? 9 : 7) + .frame(minWidth: minWidth) + .frame(maxWidth: fill ? .infinity : nil) + .fixedSize(horizontal: !fill && minWidth != nil, vertical: false) + .background(Color.white.opacity(open ? 0.13 : (rounded ? 0.055 : 0.06)), in: shape) + .overlay(shape.strokeBorder(Color.white.opacity(open ? 0.18 : 0.10))) + .foregroundStyle(Color.white.opacity(0.92)) + .contentShape(shape) + } + + fileprivate func accessible(_ view: V) -> some View { + view.accessibilityLabel(label.isEmpty ? current : label).accessibilityValue(label.isEmpty ? "" : current) + } + + private struct Hosted: View { + @ObservedObject var host: LauncherDropdownState + let dropdown: LauncherDropdown + @Environment(\.isEnabled) private var enabled + var body: some View { + let open = host.request?.id == dropdown.id + dropdown.accessible( + Button { + withAnimation(.easeOut(duration: 0.12)) { + host.request = open ? nil : LauncherDropdownRequest(id: dropdown.id, options: dropdown.options, selection: dropdown.selection, + label: dropdown.label, choose: dropdown.choose) + } + } label: { dropdown.face(open: open) } + .buttonStyle(.plain) + .opacity(enabled ? 1 : 0.55) + .anchorPreference(key: LauncherDropdownAnchorKey.self, value: .bounds) { [dropdown.id: $0] } + ) + } + } + + /// Without a host the same list opens in a popover. + private struct Popped: View { + let dropdown: LauncherDropdown + @State private var open = false + @Environment(\.isEnabled) private var enabled + var body: some View { + dropdown.accessible( + Button { open.toggle() } label: { dropdown.face(open: open) } + .buttonStyle(.plain) + .opacity(enabled ? 1 : 0.55) + .popover(isPresented: $open, arrowEdge: .bottom) { + LauncherDropdownList(options: dropdown.options, selection: dropdown.selection, label: dropdown.label, + choose: { dropdown.choose($0); open = false }, close: { open = false }) + .frame(width: LauncherDropdownLayout.width(labels: dropdown.options.map(\.label), button: 0), + height: min(LauncherDropdownLayout.contentHeight(rows: dropdown.options.count), LauncherDropdownLayout.maxHeight)) + .preferredColorScheme(.dark) + } + ) + } + } +} diff --git a/frontend/Sources/NSPortBuilder/LauncherStyles.swift b/frontend/Sources/NSPortBuilder/LauncherStyles.swift index eb31ffbfe..4179e864b 100644 --- a/frontend/Sources/NSPortBuilder/LauncherStyles.swift +++ b/frontend/Sources/NSPortBuilder/LauncherStyles.swift @@ -137,55 +137,6 @@ struct LauncherSegmented: View { } } -/// A longer list of choices: a pill with the current one that opens the list. With `fill` it takes the width it is -/// given, the chevron at its right end; `buttonLike` draws it as LauncherSecondaryButtonStyle draws a button (Settings). -struct LauncherMenuPicker: View { - let options: [(value: String, label: String)] - let selection: String - var fill = false - var buttonLike = false - let choose: (String) -> Void - @State private var open = false - var body: some View { - Button { open.toggle() } label: { - HStack(spacing: 8) { - Text(options.first { $0.value == selection }?.label ?? selection).font(.manrope(buttonLike ? 13 : 12.5, .semibold)).lineLimit(1) - if fill { Spacer(minLength: 0) } - Image(systemName: "chevron.down").font(.system(size: 9, weight: .bold)).foregroundStyle(.secondary) - } - .padding(.horizontal, buttonLike ? 15 : 14).padding(.vertical, buttonLike ? 9 : 7) - .frame(maxWidth: fill ? .infinity : nil) - .background(Color.white.opacity(buttonLike ? 0.055 : 0.06), in: RoundedRectangle(cornerRadius: buttonLike ? 9 : 99)) - .overlay(RoundedRectangle(cornerRadius: buttonLike ? 9 : 99).strokeBorder(Color.white.opacity(0.10))) - .foregroundStyle(Color.white.opacity(0.92)) - .contentShape(RoundedRectangle(cornerRadius: buttonLike ? 9 : 99)) - } - .buttonStyle(.plain) - .popover(isPresented: $open, arrowEdge: .bottom) { - ScrollView { - VStack(alignment: .leading, spacing: 2) { - ForEach(options, id: \.value) { o in - Button { choose(o.value); open = false } label: { - HStack { - Text(o.label).font(.manrope(13, o.value == selection ? .bold : .regular)) - Spacer(minLength: 16) - if o.value == selection { Image(systemName: "checkmark").font(.system(size: 11, weight: .bold)).foregroundStyle(LauncherPalette.cream) } - } - .padding(.horizontal, 12).padding(.vertical, 7) - .background(o.value == selection ? Color.white.opacity(0.07) : .clear, in: RoundedRectangle(cornerRadius: 7)) - .contentShape(Rectangle()) - } - .buttonStyle(.plain) - } - } - .padding(6) - } - .frame(width: 240, height: min(CGFloat(options.count) * 33 + 12, 320)) - .preferredColorScheme(.dark) - } - } -} - /// A slider without tick marks: a thin track, a cream fill and a round knob; snaps to its step. struct LauncherSlider: View { let value: Double diff --git a/frontend/Sources/NSPortBuilder/LauncherView.swift b/frontend/Sources/NSPortBuilder/LauncherView.swift index 1cda18156..8eebd9a05 100644 --- a/frontend/Sources/NSPortBuilder/LauncherView.swift +++ b/frontend/Sources/NSPortBuilder/LauncherView.swift @@ -140,6 +140,7 @@ struct ContentView: View { .environmentObject(padFocus) .manageMenuOverlay(items: manageOpenFor.flatMap { id in library.games.first { $0.id == id } }.map(manageItems), label: m.t("library.manage"), pad: padFocus) { manageOpenFor = nil } + .launcherDropdownHost() .onChange(of: manageOpenFor) { id in padFocus.scope = id != nil ? "manage" : currentPadScope if id != nil, padFocus.visible { // opened by the controller: its focus lands on the first usable row @@ -224,16 +225,16 @@ struct ContentView: View { } } message: { Text(m.t("library.removeNote")) } .sheet(isPresented: Binding(get: { optionsFor != nil }, set: { if !$0 { optionsFor = nil } })) { - if let id = optionsFor { LaunchOptionsView(m: m, library: library, gameID: id).environmentObject(padFocus) } + if let id = optionsFor { LaunchOptionsView(m: m, library: library, gameID: id).environmentObject(padFocus).launcherDropdownHost() } } - .sheet(isPresented: $controlsOpen) { ControlsView(m: m, layout: controls).environmentObject(padFocus) } + .sheet(isPresented: $controlsOpen) { ControlsView(m: m, layout: controls).environmentObject(padFocus).launcherDropdownHost() } .sheet(isPresented: Binding(get: { freeSpaceFor != nil }, set: { if !$0 { freeSpaceFor = nil } })) { if let game = library.games.first(where: { $0.id == freeSpaceFor }) { FreeSpaceView(m: m, game: game).environmentObject(padFocus) } } .onChange(of: freeSpaceFor) { id in padFocus.scope = id != nil ? "free" : currentPadScope } .sheet(isPresented: $m.showUpdateSheet) { UpdateSheet(m: m) } .sheet(isPresented: Binding(get: { savesFor != nil }, set: { if !$0 { savesFor = nil } })) { - if let id = savesFor { SavesView(m: m, library: library, gameID: id).environmentObject(padFocus) } + if let id = savesFor { SavesView(m: m, library: library, gameID: id).environmentObject(padFocus).launcherDropdownHost() } } .onChange(of: savesFor) { id in padFocus.scope = id != nil ? "saves" : currentPadScope } .cheatsSheet(for: $cheatsFor, m: m, library: library, pad: padFocus) { currentPadScope } diff --git a/frontend/Sources/NSPortBuilder/Localization.swift b/frontend/Sources/NSPortBuilder/Localization.swift index 9d5f8a998..f7a6f8694 100644 --- a/frontend/Sources/NSPortBuilder/Localization.swift +++ b/frontend/Sources/NSPortBuilder/Localization.swift @@ -438,10 +438,10 @@ enum L10n { "nav.settings": ("\u{8bbe}\u{7f6e}", "Settings"), "settings.language": ("界面语言", "Language"), "settings.language.system": ("跟随系统", "Follow system"), - "settings.language.zh": ("中文", "\u{4e2d}\u{6587}"), + "settings.language.zh": ("中文", "中文"), "settings.language.en": ("English", "English"), - "settings.language.sv": ("\u{745e}\u{5178}\u{8bed}", "Swedish"), - "settings.language.de": ("\u{5fb7}\u{8bed}", "German"), + "settings.language.sv": ("Svenska", "Svenska"), + "settings.language.de": ("Deutsch", "Deutsch"), "settings.appNote2": ("构建你自己的 Switch 游戏", "Build your own Switch games"), "library.setupHint": ("\u{9996}\u{6b21}\u{6784}\u{5efa}\u{524d}\u{ff0c}\u{8bf7}\u{5b8c}\u{6210}\u{4ee5}\u{4e0b}\u{8bbe}\u{7f6e}\u{3002}", "Before your first build, finish the setup below."), "library.ready": ("\u{53ef}\u{5728} Mac \u{4e0a}\u{8fd0}\u{884c}", "Ready on Mac"), @@ -1062,7 +1062,7 @@ enum L10n { static let sv: [String: String] = [ "settings.language": "Språk", "settings.language.system": "Följ systemet", - "settings.language.zh": "Kinesiska", + "settings.language.zh": "中文", "settings.language.en": "English", "settings.language.sv": "Svenska", "launch.frameTimes": "Bildtider", @@ -1074,7 +1074,7 @@ enum L10n { "launch.frameTimesSummary": "%d bildrutor · %.0f fps · median %.1f ms · 99 %% %.1f ms · långsammast %.0f ms · hack %d · tappade %d", "settings.returnAfterPlay": "Kom tillbaka när ett spel avslutas", "settings.returnAfterPlayNote": "När ett spel som startats med Spela eller i konsolläget avslutas kommer startprogrammet fram, så att du kan välja nästa", - "settings.language.de": "Tyska", + "settings.language.de": "Deutsch", "settings.heading": "Inställningar", "onboarding.welcome.title": "Välkommen.", "onboarding.welcome.note": "Spela dina Switch-spel direkt på din Mac på ungefär 15 minuter.", @@ -2157,7 +2157,7 @@ enum L10n { "settings.language.system": "Systemsprache", "settings.language.zh": "中文", "settings.language.en": "English", - "settings.language.sv": "Schwedisch", + "settings.language.sv": "Svenska", "settings.appNote2": "Baue deine eigenen Switch-Spiele", "library.setupHint": "Beende vor deinem ersten Build die Einrichtung weiter unten.", "library.ready": "Bereit auf dem Mac", diff --git a/frontend/Sources/NSPortBuilder/SaveTransfer.swift b/frontend/Sources/NSPortBuilder/SaveTransfer.swift index 842d4adfb..805a03b71 100644 --- a/frontend/Sources/NSPortBuilder/SaveTransfer.swift +++ b/frontend/Sources/NSPortBuilder/SaveTransfer.swift @@ -441,9 +441,9 @@ struct SavesView: View { if model.showsSelector { HStack(spacing: 12) { Text(m.t("saves.device")).font(.manrope(13)).foregroundStyle(.secondary) - LauncherMenuPicker(options: model.devices.map { d in + LauncherDropdown(options: model.devices.map { d in (value: d.id, label: d.name + (d.reachable ? "" : " (" + m.t("dev.notConnected") + ")")) - }, selection: model.selected) { model.select($0) } + }, selection: model.selected, label: m.t("saves.device")) { model.select($0) } .padTarget("saves.device", scope: "saves") {} } .padding(.horizontal, 30).padding(.bottom, 16) diff --git a/frontend/Tests/NSPortBuilderTests/GermanLocalizationTests.swift b/frontend/Tests/NSPortBuilderTests/GermanLocalizationTests.swift index 794dae4f7..f8c1a3fb0 100644 --- a/frontend/Tests/NSPortBuilderTests/GermanLocalizationTests.swift +++ b/frontend/Tests/NSPortBuilderTests/GermanLocalizationTests.swift @@ -11,7 +11,7 @@ final class GermanLocalizationTests: XCTestCase { "onboarding.demo.mario", "console.kind.gamepad", "console.brand", "console.platform.mac", "console.platform.iphone", "console.version", "console.fps30", "console.fps60", "saves.toDevice", "saves.toMac", "cheats.title", "section.app", "app.version", "nav.builds", "settings.language.zh", - "settings.language.en", "library.ok", "build.ios", "data.update", "data.keys", "msg.ipaAt", + "settings.language.en", "settings.language.sv", "settings.language.de", "library.ok", "build.ios", "data.update", "data.keys", "msg.ipaAt", "dep.iossdk", "dep.tool.xcodegen", "dep.tool.zstd", "dep.tool.spirv-cross", "dep.tool.glslangValidator", "dep.glslang", "dep.xcode", "dep.metal", "dep.brew", "dep.xcodegen", "dep.zstd", "dep.spirv.win", "dep.zstd.win", "dep.spirv", "dep.dotnet", "dep.phase.download", "dep.python.hint", @@ -60,7 +60,7 @@ final class GermanLocalizationTests: XCTestCase { func testGermanCatalogIsUsed() { XCTAssertEqual(L10n.string("settings.language.de", .de), "Deutsch") - XCTAssertEqual(L10n.string("settings.language.de", .en), "German") + XCTAssertEqual(L10n.string("settings.language.de", .en), "Deutsch") XCTAssertEqual(L10n.string("onboarding.start", .de), "Los geht\u{2019}s") XCTAssertEqual(L10n.string("onboarding.later", .de), "Sp\u{e4}ter einrichten") XCTAssertEqual(L10n.string("dep.recheck", .de), "Erneut pr\u{fc}fen") @@ -76,6 +76,15 @@ final class GermanLocalizationTests: XCTestCase { } } } + + func testLanguageNamesAreTheLanguagesOwnNames() { + let endonyms = ["zh": "中文", "en": "English", "sv": "Svenska", "de": "Deutsch"] + for lang: Lang in [.zh, .en, .sv, .de] { + for (code, name) in endonyms { + XCTAssertEqual(L10n.string("settings.language.\(code)", lang), name, "\(code) in \(lang)") + } + } + } } /// The opt-in capture tests render in English (and Chinese). Set `NX_CAPTURE_LANG=de` (or `sv`, `zh`) diff --git a/frontend/Tests/NSPortBuilderTests/LauncherDropdownTests.swift b/frontend/Tests/NSPortBuilderTests/LauncherDropdownTests.swift new file mode 100644 index 000000000..6c635ee9f --- /dev/null +++ b/frontend/Tests/NSPortBuilderTests/LauncherDropdownTests.swift @@ -0,0 +1,108 @@ +import SwiftUI +import XCTest +@testable import NSPortBuilder + +final class LauncherDropdownTests: XCTestCase { + private let window = CGSize(width: 1000, height: 700) + + func testListOpensBelowTheButton() { + let button = CGRect(x: 100, y: 100, width: 150, height: 36) + let spot = LauncherDropdownLayout.place(button: button, container: window, rows: 5, width: 200) + XCTAssertEqual(spot.origin.y, button.maxY + LauncherDropdownLayout.gap) + XCTAssertEqual(spot.origin.x, 100) + XCTAssertEqual(spot.size.height, LauncherDropdownLayout.contentHeight(rows: 5)) + } + + func testListOpensAboveWhenThereIsNoRoomBelow() { + let button = CGRect(x: 100, y: 600, width: 150, height: 36) + let spot = LauncherDropdownLayout.place(button: button, container: window, rows: 5, width: 200) + XCTAssertEqual(spot.origin.y + spot.size.height, button.minY - LauncherDropdownLayout.gap) + } + + func testListScrollsWhenItFitsNeitherSide() { + let short = CGSize(width: 1000, height: 300) + let button = CGRect(x: 100, y: 130, width: 150, height: 36) + let spot = LauncherDropdownLayout.place(button: button, container: short, rows: 14, width: 200) + XCTAssertLessThan(spot.size.height, LauncherDropdownLayout.contentHeight(rows: 14)) + XCTAssertGreaterThanOrEqual(spot.origin.y, LauncherDropdownLayout.margin) + XCTAssertLessThanOrEqual(spot.origin.y + spot.size.height, short.height - LauncherDropdownLayout.margin) + } + + func testAButtonOnTheRightGetsItsListAlignedToItsRightEdge() { + let button = CGRect(x: 800, y: 100, width: 150, height: 36) + let spot = LauncherDropdownLayout.place(button: button, container: window, rows: 5, width: 200) + XCTAssertEqual(spot.origin.x + spot.size.width, button.maxX) + } + + func testListStaysInsideTheWindow() { + let button = CGRect(x: 960, y: 100, width: 150, height: 36) + let spot = LauncherDropdownLayout.place(button: button, container: window, rows: 5, width: 300) + XCTAssertLessThanOrEqual(spot.origin.x + spot.size.width, window.width - LauncherDropdownLayout.margin) + } + + func testWidthFollowsTheLongestLabelAndNeverGoesBelowTheButton() { + let narrow = LauncherDropdownLayout.width(labels: ["A", "B"], button: 150) + XCTAssertEqual(narrow, LauncherDropdownLayout.minWidth) + XCTAssertEqual(LauncherDropdownLayout.width(labels: ["A"], button: 250), 250) + let long = LauncherDropdownLayout.width(labels: ["An iPhone with a rather long name (not connected)"], button: 100) + XCTAssertGreaterThan(long, LauncherDropdownLayout.minWidth) + XCTAssertLessThanOrEqual(long, LauncherDropdownLayout.maxWidth) + } + + func testEveryLanguageInThePickerHasAName() { + XCTAssertEqual(BuilderView.languageCodes.first, "") + for code in BuilderView.languageCodes.dropFirst() { + XCTAssertNotNil(Lang(rawValue: code), code) + for lang: Lang in [.zh, .en, .sv, .de] { XCTAssertNotEqual(L10n.string("settings.language." + code, lang), "settings.language." + code) } + } + } + + func testArrowKeysWrapAndStartAtTheEnds() { + XCTAssertEqual(LauncherDropdownLayout.step(from: nil, by: 1, count: 4), 0) + XCTAssertEqual(LauncherDropdownLayout.step(from: nil, by: -1, count: 4), 3) + XCTAssertEqual(LauncherDropdownLayout.step(from: 3, by: 1, count: 4), 0) + XCTAssertEqual(LauncherDropdownLayout.step(from: 0, by: -1, count: 4), 3) + XCTAssertEqual(LauncherDropdownLayout.step(from: 1, by: 1, count: 4), 2) + XCTAssertNil(LauncherDropdownLayout.step(from: nil, by: 1, count: 0)) + } + + /// Opt-in native rendering for pull request screenshots (NX_LAUNCHER_CAPTURE_DIR): the Settings language row with its list open. + @MainActor func testRenderDropdownForScreenshots() throws { + guard let directory = ProcessInfo.processInfo.environment["NX_LAUNCHER_CAPTURE_DIR"] else { throw XCTSkip("Set NX_LAUNCHER_CAPTURE_DIR to capture native views") } + let output = URL(fileURLWithPath: directory) + try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true) + let app = NSApplication.shared + app.setActivationPolicy(.accessory) + let options = [(value: "", label: L10n.string("settings.language.system", .de)), (value: "zh", label: L10n.string("settings.language.zh", .de)), + (value: "en", label: L10n.string("settings.language.en", .de)), (value: "sv", label: L10n.string("settings.language.sv", .de)), + (value: "de", label: L10n.string("settings.language.de", .de))] + let width: CGFloat = 620, height: CGFloat = 330 + let rows = VStack(alignment: .trailing, spacing: 6) { + HStack { + VStack(alignment: .leading, spacing: 3) { + Text(L10n.string("settings.language", .de)).font(.manrope(14)) + Text(L10n.string("settings.language.system", .de)).font(.manrope(12.5)).foregroundStyle(.secondary) + } + Spacer() + LauncherDropdown(options: options, selection: "", label: "Sprache", style: .button, minWidth: 150) { _ in } + } + .padding(.horizontal, 18).padding(.vertical, 13) + .background(LauncherPalette.surface.opacity(0.75), in: RoundedRectangle(cornerRadius: 14)) + LauncherDropdownList(options: options, selection: "de", label: "Sprache", choose: { _ in }, close: {}) + .frame(width: LauncherDropdownLayout.width(labels: options.map(\.label), button: 150), height: LauncherDropdownLayout.contentHeight(rows: options.count)) + .launcherDropdownSurface() + } + .padding(24) + let host = NSHostingView(rootView: ZStack { LauncherPalette.background; rows }.preferredColorScheme(.dark).frame(width: width, height: height)) + let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: width, height: height), styleMask: [.titled], backing: .buffered, defer: false) + window.contentView = host + window.appearance = NSAppearance(named: .darkAqua) + window.orderFront(nil) + RunLoop.main.run(until: Date().addingTimeInterval(0.4)) + host.layoutSubtreeIfNeeded() + let rep = try XCTUnwrap(host.bitmapImageRepForCachingDisplay(in: host.bounds)) + host.cacheDisplay(in: host.bounds, to: rep) + try XCTUnwrap(rep.representation(using: .png, properties: [:])).write(to: output.appendingPathComponent("dropdown-settings.png")) + window.orderOut(nil) + } +}