Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Settings ▸ Profiles lists each profile's website languages and opens Chromium's page for them (#209)

Victorb528590f669a
diff --git a/Packages/CraCore/Sources/CraCore/BrowserLanguages.swift b/Packages/CraCore/Sources/CraCore/BrowserLanguages.swift
new file mode 100644
index 0000000..7d3d9a1
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/BrowserLanguages.swift
@@ -0,0 +1,54 @@
+import Foundation
+
+/// The languages a profile asks websites for, most wanted first (GitHub #209): Chromium's
+/// `intl.accept_languages`, which becomes the Accept-Language header and `navigator.languages`.
+/// It is not Cra's interface language, which stays English (#34).
+///
+/// Arc has no control of its own for it. Its Translate bubble's "Language Settings" item and
+/// Settings ▸ Advanced ▸ More Settings open Chromium's page, arc://settings/languages, which is
+/// per profile (Arc 1.171's binary: `chrome://settings/languages`, `settings/languages`). Cra
+/// lists each profile's languages under Settings ▸ Profiles and opens that page in the profile.
+/// The page edits `intl.selected_languages` and Chromium derives `intl.accept_languages` from it.
+/// Open pages pick a change up at once, so no reload is needed (checked in
+/// Tests/Scenarios/accept-languages.scenario).
+public enum BrowserLanguages {
+ public static let settingsPage = "chrome://settings/languages"
+ /// language::prefs::kAcceptLanguages.
+ public static let pref = "intl.accept_languages"
+
+ /// The codes in a pref value, in order: "da,en-GB" or its JSON form "\"da,en-GB\"", which is
+ /// how CraCEFRuntime.preference returns it. Empty for anything else.
+ public static func codes(_ value: String) -> [String] {
+ var list = value.trimmingCharacters(in: .whitespacesAndNewlines)
+ if list.hasPrefix("\"") {
+ guard let data = list.data(using: .utf8),
+ let decoded = try? JSONDecoder().decode(String.self, from: data) else { return [] }
+ list = decoded
+ }
+ var seen = Set<String>()
+ return list.split(separator: ",")
+ .map { $0.trimmingCharacters(in: .whitespaces) }
+ .filter { !$0.isEmpty && $0.allSatisfy { $0.isLetter || $0.isNumber || $0 == "-" || $0 == "_" } }
+ .filter { seen.insert($0.lowercased()).inserted }
+ }
+
+ /// The codes saved in a profile's Preferences file, for a profile Chromium hasn't loaded in
+ /// this session. Nil when the file doesn't hold the pref (a profile never opened).
+ public static func codes(preferencesFile data: Data) -> [String]? {
+ guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
+ let value = (root["intl"] as? [String: Any])?["accept_languages"] as? String else { return nil }
+ let list = codes(value)
+ return list.isEmpty ? nil : list
+ }
+
+ /// A code's English name, as Cra's interface is English: "da" is "Danish", "en-GB" "English
+ /// (United Kingdom)". A code Foundation doesn't know stays as it is.
+ public static func name(_ code: String) -> String {
+ Locale(identifier: "en_US").localizedString(forIdentifier: code) ?? code
+ }
+
+ /// The row's summary: "Danish, English (United Kingdom), English".
+ public static func summary(_ codes: [String]) -> String {
+ codes.map(name).joined(separator: ", ")
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/BrowserLanguagesTests.swift b/Packages/CraCore/Tests/CraCoreTests/BrowserLanguagesTests.swift
new file mode 100644
index 0000000..229da83
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/BrowserLanguagesTests.swift
@@ -0,0 +1,33 @@
+import CraCore
+import Foundation
+import Testing
+
+/// Each profile's website languages under Settings ▸ Profiles (#209).
+struct BrowserLanguagesTests {
+ @Test func readsThePrefAsChromiumListsIt() {
+ #expect(BrowserLanguages.codes("da,en-GB,en-US,en") == ["da", "en-GB", "en-US", "en"])
+ // CraCEFRuntime.preference hands back JSON.
+ #expect(BrowserLanguages.codes("\"zh-CN,zh,en\"") == ["zh-CN", "zh", "en"])
+ #expect(BrowserLanguages.codes(" en-US , en ") == ["en-US", "en"])
+ }
+
+ @Test func dropsWhatIsNotALanguageList() {
+ #expect(BrowserLanguages.codes("") == [])
+ #expect(BrowserLanguages.codes("\"unterminated") == [])
+ #expect(BrowserLanguages.codes("[\"en\"]") == [])
+ #expect(BrowserLanguages.codes("en,,de;q=0.9,en") == ["en"])
+ }
+
+ @Test func readsAProfilesPreferencesFile() {
+ let file = #"{"intl":{"accept_languages":"da-DK,da,en-US,en","selected_languages":"da-DK,da,en-US,en"},"profile":{}}"#
+ #expect(BrowserLanguages.codes(preferencesFile: Data(file.utf8)) == ["da-DK", "da", "en-US", "en"])
+ #expect(BrowserLanguages.codes(preferencesFile: Data(#"{"profile":{}}"#.utf8)) == nil)
+ #expect(BrowserLanguages.codes(preferencesFile: Data("not json".utf8)) == nil)
+ }
+
+ @Test func namesLanguagesInEnglish() {
+ #expect(BrowserLanguages.name("da") == "Danish")
+ #expect(BrowserLanguages.name("en-GB") == "English (United Kingdom)")
+ #expect(BrowserLanguages.summary(["da", "en-US", "en"]) == "Danish, English (United States), English")
+ }
+}
diff --git a/Sources/Cra/App/AppDelegate.swift b/Sources/Cra/App/AppDelegate.swift
index 71b54f3..2d13c73 100644
--- a/Sources/Cra/App/AppDelegate.swift
+++ b/Sources/Cra/App/AppDelegate.swift
@@ -386,7 +386,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
/// A page an extension opens as a tab. Its options page stays one tab, as in Chrome and
/// Arc: opening it again selects the open one (GitHub #38).
/// `profile` is the Chromium profile folder whose extension asked, nil for the focused page's.
- func openExtensionPage(_ url: String, window: UUID, profile: String? = nil) {
+ /// `singleton`: an open tab with the page in that profile is selected instead of a new one.
+ func openExtensionPage(_ url: String, window: UUID, profile: String? = nil, singleton: Bool = false) {
// Extensions run in the normal profile, so Chrome opens their pages in a normal window:
// in an incognito one the page can't load (#107). Incognito is Default's off the record.
var window = window, profile = profile
@@ -407,7 +408,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
let target = ExtensionPagePlacement.target(
focused: space(store.focusedSpaceID(window: window)),
spaces: store.orderedSpaces.filter { !store.isIncognito(space: $0.id) }.map { space($0.id) },
- profile: profile, openTabs: open, singleton: ExtensionStore.shared.optionsPageOwner(url) != nil)
+ profile: profile, openTabs: open, singleton: singleton || ExtensionStore.shared.optionsPageOwner(url) != nil)
switch target {
case .select(let tab): store.selectTab(tab, window: window)
case .create(let sid): store.createTab(url: url, in: sid, select: true, window: window)
@@ -1152,6 +1153,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
case "rebuildArcProfiles": ArcProfileRebuilder.run(store: store) { [weak self] in self?.relaunch() }
case "setDefaultBrowser": Task { await SystemIntegration.shared.makeDefaultBrowser() }
case "checkForUpdates": SoftwareUpdater.shared.checkForUpdates(nil)
+ case "languageSettings":
+ // Chromium's page edits the profile of the space it opens in.
+ let normal = useNormalWindow()
+ _ = store.createTab(url: BrowserLanguages.settingsPage, select: true)
+ normal.showWindow(nil)
case "clearBrowsingData":
// Chrome's dialog, in a normal window: what it deletes from history leaves the command bar too.
let normal = useNormalWindow()
@@ -1208,6 +1214,14 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
self.settingsWindow?.close()
self.main.showWindow(nil)
},
+ openProfilePage: { [weak self] url, profileID in
+ guard let self else { return }
+ let window = self.useNormalWindow()
+ self.openExtensionPage(url, window: window.windowID,
+ profile: self.store.profile(profileID)?.directoryName ?? "Default", singleton: true)
+ self.settingsWindow?.close()
+ window.showWindow(nil)
+ },
exportDiagnostics: { [weak self] in self?.exportDiagnostics() },
newProfile: { [weak self] in
guard let self, let w = self.settingsWindow else { return }
@@ -1217,6 +1231,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuItemValidation {
settingsController = c
settingsWindow = c.window
}
+ settingsController?.didShow()
settingsWindow?.makeKeyAndOrderFront(nil)
}
diff --git a/Sources/Cra/App/KeyBindings.swift b/Sources/Cra/App/KeyBindings.swift
index 8168ae1..234c196 100644
--- a/Sources/Cra/App/KeyBindings.swift
+++ b/Sources/Cra/App/KeyBindings.swift
@@ -220,6 +220,9 @@ final class KeyBindingRegistry {
// Chrome's app menu item and key; Arc has neither, only Settings ▸ Profiles ▸ Clear Browsing Data.
KeyAction(id: "clearBrowsingData", name: "Clear Browsing Data…", section: .app, shortcuts: [Shortcut(Shortcut.delete, cmdShift)],
triggers: ["clear history", "delete history", "clear browsing data", "delete browsing data"], symbol: "trash"),
+ // Arc's Translate bubble item "Language Settings": Chromium's page, in the space's profile (#209).
+ KeyAction(id: "languageSettings", name: "Language Settings", section: .app, shortcuts: [],
+ triggers: ["language", "languages", "preferred language", "accept language"], symbol: "globe"),
KeyAction(id: "checkForUpdates", name: "Check for Updates…", section: .app, shortcuts: [],
triggers: ["update", "upgrade", "new version"], symbol: "arrow.down.circle"),
]
diff --git a/Sources/Cra/UI/Settings/ProfilesPane.swift b/Sources/Cra/UI/Settings/ProfilesPane.swift
index 81d6a99..eafd582 100644
--- a/Sources/Cra/UI/Settings/ProfilesPane.swift
+++ b/Sources/Cra/UI/Settings/ProfilesPane.swift
@@ -1,10 +1,12 @@
import AppKit
+import CraCEF
import SwiftUI
/// Dia's Profiles pane (and Arc's Profiles preferences): the profiles and how many spaces
/// use each, "Create Profile…" under the card. A space picks its profile in Edit Space.
/// Arc only deletes profiles no space uses, and never Default.
struct ProfilesPane: View {
+ let nav: SettingsNavigation
let actions: SettingsActions
@Environment(SidebarStore.self) private var store
@State private var naming: BrowserProfile?
@@ -47,6 +49,17 @@ struct ProfilesPane: View {
}
}
SettingsFootnote("Where each Profile saves downloaded files. Choose Ask Where to Save Each File to pick a place every time.")
+ // Chromium's per-profile website languages (#209); Arc leaves them to arc://settings/languages.
+ SettingsHeader("Languages").padding(.top, 20)
+ SettingsCard {
+ languageRow(name: "Default", profileID: nil)
+ ForEach(store.profiles) { p in
+ SettingsCardDivider()
+ languageRow(name: p.name, profileID: p.id)
+ }
+ }
+ .id(nav.shown) // read again each time Settings comes up: Chromium's page may have changed them
+ SettingsFootnote("The languages websites show their pages in for each Profile, most wanted first. Change opens Chromium’s language settings for that Profile. Cra itself stays in English.")
}
.alert("Rename Profile", isPresented: Binding(get: { naming != nil }, set: { if !$0 { naming = nil } })) {
TextField("Profile name", text: $name)
@@ -105,6 +118,35 @@ struct ProfilesPane: View {
}
}
+ private func languageRow(name: String, profileID: UUID?) -> some View {
+ let summary = BrowserLanguages.summary(languages(profileID: profileID))
+ let hasSpace = !store.spaces(usingProfile: profileID).isEmpty
+ return SettingsCardRow {
+ VStack(alignment: .leading, spacing: 2) {
+ Text(name).font(.system(size: 13))
+ Text(summary.isEmpty ? "Chromium’s default languages" : summary)
+ .font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1)
+ .help(summary)
+ }
+ } trailing: {
+ Button("Change…") { actions.openProfilePage(BrowserLanguages.settingsPage, profileID) }
+ .disabled(!hasSpace)
+ .help(hasSpace ? "Open Chromium’s language settings for \(name)." : "Set \(name) on a Space first.")
+ }
+ }
+
+ /// What Chromium holds for the profile now, else what its Preferences file saved (a profile no
+ /// page has loaded in since launch).
+ private func languages(profileID: UUID?) -> [String] {
+ let path = store.profilePath(profile: profileID)
+ if let json = CraCEFRuntime.preference(BrowserLanguages.pref, forProfile: path) {
+ return BrowserLanguages.codes(json)
+ }
+ let folder = path.map { URL(fileURLWithPath: $0) } ?? AppPaths.chromiumCache.appendingPathComponent("Default")
+ return (try? Data(contentsOf: folder.appendingPathComponent("Preferences")))
+ .flatMap(BrowserLanguages.codes(preferencesFile:)) ?? []
+ }
+
private var trimmed: String { name.trimmingCharacters(in: .whitespaces) }
private func row<Trailing: View>(name: String, profileID: UUID?, @ViewBuilder trailing: () -> Trailing) -> some View {
diff --git a/Sources/Cra/UI/Settings/SettingsWindowController.swift b/Sources/Cra/UI/Settings/SettingsWindowController.swift
index 8ebe44f..f0cad8b 100644
--- a/Sources/Cra/UI/Settings/SettingsWindowController.swift
+++ b/Sources/Cra/UI/Settings/SettingsWindowController.swift
@@ -6,6 +6,8 @@ struct SettingsActions {
var importData: () -> Void = {}
var rebuildArcProfiles: () -> Void = {}
var openURL: (String) -> Void = { _ in }
+ /// A page in a space on that profile (nil is Default), e.g. its chrome://settings/languages.
+ var openProfilePage: (String, UUID?) -> Void = { _, _ in }
var exportDiagnostics: () -> Void = {}
var newProfile: () -> Void = {}
}
@@ -58,6 +60,10 @@ final class SettingsNavigation {
private(set) var forward: [SettingsPane] = []
/// The window is on screen: panes that refresh (Performance) stop while it is closed or covered.
var isOpen = false
+ /// Counts each time Settings is brought up: panes showing what changed elsewhere (a profile's
+ /// languages, set on Chromium's page) read it again.
+ private(set) var shown = 0
+ func didShow() { shown += 1 }
func show(_ p: SettingsPane) {
guard p != pane else { return }
@@ -88,6 +94,7 @@ final class SettingsWindowController: NSWindowController, NSToolbarDelegate {
private let nav = SettingsNavigation()
func show(_ pane: SettingsPane) { nav.show(pane) }
+ func didShow() { nav.didShow() }
init(store: SidebarStore, bindings: KeyBindingRegistry, actions: SettingsActions) {
let window = NSWindow(contentRect: NSRect(origin: .zero, size: SettingsMetrics.windowSize),
@@ -246,7 +253,7 @@ struct SettingsContent: View {
case .tabs: TabsPane()
case .max: MaxPane()
case .privacy: PrivacyPane(actions: actions)
- case .profiles: ProfilesPane(actions: actions)
+ case .profiles: ProfilesPane(nav: nav, actions: actions)
case .extensions: ExtensionsPane(actions: actions)
case .shortcuts: ShortcutsPane()
case .performance: PerformancePane(nav: nav, actions: actions)
diff --git a/Sources/Cra/UI/Settings/ShortcutsPane.swift b/Sources/Cra/UI/Settings/ShortcutsPane.swift
index 84cb0cd..4852ca9 100644
--- a/Sources/Cra/UI/Settings/ShortcutsPane.swift
+++ b/Sources/Cra/UI/Settings/ShortcutsPane.swift
@@ -314,6 +314,7 @@ enum ShortcutDescriptions {
"importData": "Bring tabs, spaces and extensions over from Arc or Dia.",
"rebuildArcProfiles": "Put spaces imported from Arc back on their Arc profiles, with their sign-ins and extensions.",
"clearBrowsingData": "Delete history, cookies and cached files with Chrome’s dialog.",
+ "languageSettings": "Choose the languages websites show their pages in, for this space’s profile.",
"checkForUpdates": "Look for a newer version of Cra.",
]
}
diff --git a/Tests/Scenarios/accept-languages.scenario b/Tests/Scenarios/accept-languages.scenario
new file mode 100644
index 0000000..69c3a9a
--- /dev/null
+++ b/Tests/Scenarios/accept-languages.scenario
@@ -0,0 +1,23 @@
+# GitHub #209: the languages websites see (Accept-Language, navigator.languages) are each profile's
+# chrome://settings/languages, as in Chrome and Arc. Language Settings in the command bar opens that
+# page; a language added there reaches the open page at once and new pages too. Icelandic, which
+# neither this Mac's nor CI's macOS languages bring in.
+cra://open?url=${PAGE}
+expect-log loaded 127.0.0.1
+cra://debug?cdp=Runtime.evaluate&params={"expression":"'before:'+navigator.languages.includes('is')"}
+expect-log Cra cdp Runtime.evaluate .*"value":"before:false"
+cra://action/languageSettings
+wait 4
+cra://debug?cdp=Runtime.evaluate&params={"expression":"'page:'+location.href"}
+expect-log Cra cdp Runtime.evaluate .*"value":"page:chrome://settings/languages"
+# What the page's Add languages and Move to the top do.
+cra://debug?cdp=Runtime.evaluate&params={"expression":"new Promise(r=>{chrome.languageSettingsPrivate.enableLanguage('is');chrome.languageSettingsPrivate.moveLanguage('is','TOP');setTimeout(()=>chrome.settingsPrivate.getPref('intl.accept_languages',p=>r('pref:'+p.value)),500)})","awaitPromise":true}
+expect-log Cra cdp Runtime.evaluate .*"value":"pref:is,
+cra://action/previousTab
+wait 1
+cra://debug?cdp=Runtime.evaluate&params={"expression":"'open:'+location.host+'|'+navigator.languages[0]"}
+expect-log Cra cdp Runtime.evaluate .*"value":"open:127.0.0.1:[0-9]+\|is"
+cra://open?url=${PAGE}?n=2
+wait 3
+cra://debug?cdp=Runtime.evaluate&params={"expression":"'new:'+navigator.language"}
+expect-log Cra cdp Runtime.evaluate .*"value":"new:is"