Parcourir la source

Update dependencies

Johannes Zellner il y a 1 mois
Parent
commit
8669741b49
4 fichiers modifiés avec 478 ajouts et 230 suppressions
  1. 270 217
      Cargo.lock
  2. 6 6
      Cargo.toml
  3. 18 7
      src/desktop_install.rs
  4. 184 0
      src/locale.rs

Fichier diff supprimé car celui-ci est trop grand
+ 270 - 217
Cargo.lock


+ 6 - 6
Cargo.toml

@@ -4,11 +4,11 @@ version = "0.1.0"
 edition = "2024"
 
 [dependencies]
-clap = { version = "4.5", features = ["derive"] }
-gtk4 = { version = "0.11.1", features = ["v4_10"] }
-libadwaita = { version = "0.9.1", features = ["v1_9"] }
-scraper = "0.22"
-sha2 = "0.10"
-ureq = { version = "2.12", features = ["native-certs"] }
+clap = { version = "4.6", features = ["derive"] }
+gtk4 = { version = "0.11.5", features = ["v4_10"] }
+libadwaita = { version = "0.9.2", features = ["v1_9"] }
+scraper = "0.27"
+sha2 = "0.11"
+ureq = { version = "3.4", features = ["platform-verifier"] }
 url = "2.5"
 webkit6 = "0.6.1"

+ 18 - 7
src/desktop_install.rs

@@ -212,7 +212,11 @@ pub fn list_launchers() -> Result<Vec<DesktopLauncher>, String> {
 pub(crate) fn stable_id(url: &str) -> String {
     let mut h = Sha256::new();
     h.update(url.as_bytes());
-    let full = format!("{:x}", h.finalize());
+    let full = h
+        .finalize()
+        .iter()
+        .map(|b| format!("{b:02x}"))
+        .collect::<String>();
     full[..ID_HEX_LEN].to_string()
 }
 
@@ -369,7 +373,10 @@ fn escape_desktop_value(s: &str) -> String {
 }
 
 fn ureq_agent() -> ureq::Agent {
-    ureq::Agent::new()
+    ureq::Agent::config_builder()
+        .http_status_as_error(false)
+        .build()
+        .into()
 }
 
 fn fetch_bytes(agent: &ureq::Agent, url: &str) -> Result<Vec<u8>, String> {
@@ -383,17 +390,21 @@ fn fetch_bytes_with_content_type(
 ) -> Result<(Vec<u8>, Option<String>), String> {
     let resp = agent
         .get(url)
-        .set("User-Agent", "appiphany/1.0 (desktop-install)")
+        .header("User-Agent", "appiphany/1.0 (desktop-install)")
         .call()
         .map_err(|e| e.to_string())?;
-    if !(200..300).contains(&resp.status()) {
-        return Err(format!("HTTP {} for {url}", resp.status()));
+    let status = resp.status().as_u16();
+    if !(200..300).contains(&status) {
+        return Err(format!("HTTP {status} for {url}"));
     }
     let content_type = resp
-        .header("Content-Type")
+        .headers()
+        .get("Content-Type")
+        .and_then(|s| s.to_str().ok())
         .map(|s| s.split(';').next().unwrap_or(s).trim().to_ascii_lowercase());
     let mut buf = Vec::new();
-    resp.into_reader()
+    resp.into_body()
+        .into_reader()
         .read_to_end(&mut buf)
         .map_err(|e| e.to_string())?;
     Ok((buf, content_type))

+ 184 - 0
src/locale.rs

@@ -0,0 +1,184 @@
+//! GNOME locale integration: make web content `Intl` formatting follow the
+//! GNOME "Formats" region (`org.gnome.system.locale` `region`), like other
+//! GNOME apps that honor `LC_TIME`.
+//!
+//! WebKitGTK derives the JavaScript default locale from the first entry of the
+//! web context's preferred languages, so the region has to be prepended before
+//! any web view or network session is created.
+
+use gtk4::gio;
+use gtk4::gio::prelude::*;
+use gtk4::glib;
+
+/// GSettings schema/key holding the user's date/number format region.
+const GNOME_LOCALE_SCHEMA: &str = "org.gnome.system.locale";
+const GNOME_LOCALE_REGION_KEY: &str = "region";
+
+/// Key used to keep the [`gio::Settings`] watch alive on the application object.
+const LOCALE_SETTINGS_KEY: &str = "appiphany-locale-settings";
+
+/// Convert a POSIX locale (e.g. `de_DE.UTF-8@euro`) to a BCP 47-ish language
+/// tag (`de-DE`).
+///
+/// Returns `None` for the C/POSIX locales and for input that is not a plain
+/// `language[_region]` locale.
+pub(crate) fn posix_locale_to_tag(raw: &str) -> Option<String> {
+    // POSIX syntax: language[_territory][.codeset][@modifier]
+    let base = raw
+        .split('@')
+        .next()
+        .unwrap_or_default()
+        .split('.')
+        .next()
+        .unwrap_or_default()
+        .trim();
+
+    if base.is_empty() || base.eq_ignore_ascii_case("C") || base.eq_ignore_ascii_case("POSIX") {
+        return None;
+    }
+
+    let mut parts = base.split('_');
+    let language = parts.next()?.to_ascii_lowercase();
+    if language.len() < 2 || !language.chars().all(|c| c.is_ascii_alphabetic()) {
+        return None;
+    }
+
+    match (parts.next(), parts.next()) {
+        (None, None) => Some(language),
+        (Some(region), None) if is_alpha_region(region) => {
+            Some(format!("{language}-{}", region.to_ascii_uppercase()))
+        }
+        (Some(region), None) if is_numeric_region(region) => Some(format!("{language}-{region}")),
+        _ => None,
+    }
+}
+
+fn is_alpha_region(region: &str) -> bool {
+    region.len() == 2 && region.chars().all(|c| c.is_ascii_alphabetic())
+}
+
+fn is_numeric_region(region: &str) -> bool {
+    region.len() == 3 && region.chars().all(|c| c.is_ascii_digit())
+}
+
+fn locale_schema_available() -> bool {
+    gio::SettingsSchemaSource::default()
+        .and_then(|source| source.lookup(GNOME_LOCALE_SCHEMA, true))
+        .is_some()
+}
+
+/// The region to use for dates/numbers: GNOME's Formats setting when set,
+/// otherwise the process `LC_TIME` locale.
+fn gnome_formats_region() -> Option<String> {
+    if locale_schema_available() {
+        let settings = gio::Settings::new(GNOME_LOCALE_SCHEMA);
+        if let Some(tag) = posix_locale_to_tag(settings.string(GNOME_LOCALE_REGION_KEY).as_str()) {
+            return Some(tag);
+        }
+    }
+
+    glib::language_names_with_category("LC_TIME")
+        .into_iter()
+        .find_map(|name| posix_locale_to_tag(name.as_str()))
+}
+
+/// Preferred language list for WebKit: GNOME formats region first, then the
+/// session's language names. WebKit uses the first entry as the JavaScript
+/// `Intl` default locale.
+pub(crate) fn preferred_languages() -> Vec<String> {
+    let mut languages = Vec::new();
+
+    if let Some(region) = gnome_formats_region() {
+        languages.push(region);
+    }
+
+    for name in glib::language_names() {
+        let Some(tag) = posix_locale_to_tag(name.as_str()) else {
+            continue;
+        };
+        if languages
+            .iter()
+            .any(|existing| existing.eq_ignore_ascii_case(&tag))
+        {
+            continue;
+        }
+        languages.push(tag);
+    }
+
+    languages
+}
+
+/// Apply the preferred languages to the default WebKit context.
+///
+/// Must be called before any web view/network session is created so both the
+/// web and network processes pick the list up. Returns the list that was
+/// applied (empty when there is nothing to do).
+pub(crate) fn apply_to_webkit() -> Vec<String> {
+    let languages = preferred_languages();
+    if languages.is_empty() {
+        return languages;
+    }
+
+    if let Some(context) = webkit6::WebContext::default() {
+        let tags: Vec<&str> = languages.iter().map(String::as_str).collect();
+        context.set_preferred_languages(&tags);
+    }
+
+    languages
+}
+
+/// Re-apply the preferred languages when the GNOME Formats region changes.
+///
+/// Pages already loaded may need a reload; pages loaded after the change use
+/// the new locale.
+pub(crate) fn watch_region_changes(app: &impl IsA<glib::Object>) {
+    if !locale_schema_available() {
+        return;
+    }
+
+    let settings = gio::Settings::new(GNOME_LOCALE_SCHEMA);
+    settings.connect_changed(Some(GNOME_LOCALE_REGION_KEY), |_, _| {
+        let languages = apply_to_webkit();
+        if !languages.is_empty() {
+            eprintln!(
+                "appiphany: preferred languages changed: {}",
+                languages.join(", ")
+            );
+        }
+    });
+
+    // Keep the settings object (and its signal connection) alive with the app.
+    unsafe {
+        app.as_ref().set_data(LOCALE_SETTINGS_KEY, settings);
+    }
+}
+
+#[cfg(test)]
+mod tests {
+    use super::posix_locale_to_tag;
+
+    #[test]
+    fn parses_posix_locales() {
+        assert_eq!(posix_locale_to_tag("de_DE.UTF-8"), Some("de-DE".into()));
+        assert_eq!(
+            posix_locale_to_tag("de_DE.UTF-8@euro"),
+            Some("de-DE".into())
+        );
+        assert_eq!(posix_locale_to_tag("de_DE"), Some("de-DE".into()));
+        assert_eq!(posix_locale_to_tag("en_US"), Some("en-US".into()));
+        assert_eq!(posix_locale_to_tag("en"), Some("en".into()));
+        assert_eq!(posix_locale_to_tag("sr_RS@latin"), Some("sr-RS".into()));
+        assert_eq!(posix_locale_to_tag("es_419"), Some("es-419".into()));
+    }
+
+    #[test]
+    fn rejects_c_and_unexpected_locales() {
+        assert_eq!(posix_locale_to_tag(""), None);
+        assert_eq!(posix_locale_to_tag("C"), None);
+        assert_eq!(posix_locale_to_tag("C.UTF-8"), None);
+        assert_eq!(posix_locale_to_tag("POSIX"), None);
+        assert_eq!(posix_locale_to_tag("123_DE"), None);
+        assert_eq!(posix_locale_to_tag("de_DE_extra"), None);
+        assert_eq!(posix_locale_to_tag("de_DEU"), None);
+    }
+}

Certains fichiers n'ont pas été affichés car il y a eu trop de fichiers modifiés dans ce diff