Skip to content

armgit / moli

Public Imported from GitHub
0

Best headless browser for AI agents. Lite, Fast, High-Compatibility. Built in Rust

8.4 KB
Raw Blame
use crate::support::char;

use std::ffi::CString;

unsafe extern "C" {
  fn ucal_open_78(
    zone: *const u16,
    length: i32,
    locale: *const char,
    kind: i32,
    error: *mut i32,
  ) -> *mut std::ffi::c_void;
  fn ucal_setMillis_78(
    calendar: *mut std::ffi::c_void,
    millis: f64,
    error: *mut i32,
  );
  fn ucal_get_78(
    calendar: *const std::ffi::c_void,
    field: i32,
    error: *mut i32,
  ) -> i32;
  fn ucal_close_78(calendar: *mut std::ffi::c_void);
  fn uloc_getDefault_78() -> *const char;
  fn uloc_getLanguage_78(
    locale: *const char,
    language: *mut char,
    capacity: i32,
    error: *mut i32,
  ) -> i32;
  fn uloc_setDefault_78(locale: *const char, error: *mut i32);
  fn ucal_setDefaultTimeZone_78(time_zone_id: *const u16, error: *mut i32);
  fn icu_get_default_locale(output: *mut char, output_len: usize) -> usize;
  fn icu_set_default_locale(locale: *const char);
  fn icu_get_default_time_zone(output: *mut char, output_len: usize) -> usize;
  fn icu_set_default_time_zone(time_zone_id: *const char) -> bool;
  fn udata_setCommonData_78(this: *const u8, error_code: *mut i32);
}

/// This function bypasses the normal ICU data loading process and allows you to force ICU's system
/// data to come out of a user-specified area in memory.
///
/// ICU data must be at least 8-aligned, and should be 16-aligned. See
/// https://unicode-org.github.io/icu/userguide/icu_data/
///
/// The format of this data is that of the icu common data file, as is generated by the pkgdata
/// tool with mode=common or mode=dll. You can read in a whole common mode file and pass the
/// address to the start of the data, or (with the appropriate link options) pass in the pointer to
/// the data that has been loaded from a dll by the operating system, as shown in this code:
///
/// ```c++
///       extern const char U_IMPORT U_ICUDATA_ENTRY_POINT [];
///        // U_ICUDATA_ENTRY_POINT is same as entry point specified to pkgdata tool
///       UErrorCode  status = U_ZERO_ERROR;
///
///       udata_setCommonData(&U_ICUDATA_ENTRY_POINT, &status);
/// ```
///
/// It is important that the declaration be as above. The entry point must not be declared as an
/// extern void*.
///
/// Starting with ICU 4.4, it is possible to set several data packages, one per call to this
/// function. udata_open() will look for data in the multiple data packages in the order in which
/// they were set. The position of the linked-in or default-name ICU .data package in the search
/// list depends on when the first data item is loaded that is not contained in the already
/// explicitly set packages. If data was loaded implicitly before the first call to this function
/// (for example, via opening a converter, constructing a UnicodeString from default-codepage data,
/// using formatting or collation APIs, etc.), then the default data will be first in the list.
///
/// This function has no effect on application (non ICU) data. See udata_setAppData() for similar
/// functionality for application data.
// TODO(ry) Map error code to something useful.
#[inline(always)]
pub fn set_common_data_78(data: &'static [u8]) -> Result<(), i32> {
  let mut error_code = 0i32;
  unsafe {
    udata_setCommonData_78(data.as_ptr(), &mut error_code);
  }
  if error_code == 0 {
    Ok(())
  } else {
    Err(error_code)
  }
}

/// Returns BCP47 language tag.
pub fn get_language_tag() -> String {
  let mut output = [0u8; 1024];
  let len = unsafe {
    icu_get_default_locale(output.as_mut_ptr() as *mut char, output.len())
  };
  std::str::from_utf8(&output[..len]).unwrap().to_owned()
}

pub fn set_default_locale(locale: &str) {
  unsafe {
    let c_str = CString::new(locale).expect("Invalid locale");
    icu_set_default_locale(c_str.as_ptr());
  }
}

/// Returns the exact ICU locale ID, including legacy variants/keywords. Use
/// this, not a BCP47 serialization, when saving a default for later restoration.
/// Callers must serialize access with changes to ICU's process-wide default.
pub fn get_default_locale_name() -> String {
  // SAFETY: ICU returns a NUL-terminated default locale name.
  unsafe { std::ffi::CStr::from_ptr(uloc_getDefault_78()) }
    .to_string_lossy()
    .into_owned()
}

/// Validates the language component and sets ICU's default without panicking
/// on untrusted protocol input. Like Blink, this accepts ICU locale IDs rather
/// than requiring a BCP47 tag. A rejected value leaves the default unchanged.
pub fn try_set_default_locale(locale: &str) -> bool {
  let Ok(locale) = CString::new(locale) else {
    return false;
  };
  let mut error = 0;
  let mut language = [0u8; 128];
  // SAFETY: the input and output buffers are live for the call.
  let length = unsafe {
    uloc_getLanguage_78(
      locale.as_ptr(),
      language.as_mut_ptr().cast(),
      language.len() as i32,
      &mut error,
    )
  };
  if error > 0 || length <= 0 {
    return false;
  }
  // SAFETY: locale is NUL-terminated; ICU copies the locale ID.
  unsafe {
    uloc_setDefault_78(locale.as_ptr(), &mut error);
  }
  error <= 0
}

/// Restores a previously saved default, including ICU's valid fallback state
/// `Etc/Unknown`. Unlike the public override setter this must accept that state.
pub fn restore_default_time_zone(time_zone_id: &str) -> bool {
  if time_zone_id.contains('\0') {
    return false;
  }
  let mut id: Vec<u16> = time_zone_id.encode_utf16().collect();
  id.push(0);
  let mut error = 0;
  // SAFETY: id is a live, NUL-terminated UTF-16 string; ICU copies it.
  unsafe {
    ucal_setDefaultTimeZone_78(id.as_ptr(), &mut error);
  }
  error <= 0
}

/// Timestamp-sensitive offset from the same default ICU zone V8 uses. This
/// serves host Web APIs such as Document.lastModified without a second tzdb.
pub fn default_time_zone_offset_seconds(timestamp_ms: f64) -> Option<i32> {
  if !timestamp_ms.is_finite() {
    return None;
  }
  let mut error = 0;
  // ICU: null zone selects the process default, UCAL_GREGORIAN = 1.
  // SAFETY: ICU copies the locale. Every non-null calendar is closed below,
  // including errors from setMillis/get; no borrowed ICU pointer escapes.
  unsafe {
    let calendar =
      ucal_open_78(std::ptr::null(), 0, c"en_US_POSIX".as_ptr(), 1, &mut error);
    if calendar.is_null() {
      return None;
    }
    ucal_setMillis_78(calendar, timestamp_ms, &mut error);
    let standard = ucal_get_78(calendar, 15, &mut error); // UCAL_ZONE_OFFSET
    let daylight = ucal_get_78(calendar, 16, &mut error); // UCAL_DST_OFFSET
    ucal_close_78(calendar);
    (error <= 0).then(|| standard.saturating_add(daylight) / 1000)
  }
}

/// Returns the id of ICU's current default time zone, usually an IANA id such
/// as `"America/New_York"`. It can also be a custom offset id like
/// `"GMT+05:00"`, either because one was installed with
/// [`set_default_time_zone`] or because the host reported its zone that way,
/// so don't assume the result resolves against the tz database.
///
/// If the host time zone could not be determined, ICU reports the special
/// id `"Etc/Unknown"`, which behaves as GMT.
pub fn get_default_time_zone() -> String {
  let mut output = [0u8; 1024];
  let len = unsafe {
    icu_get_default_time_zone(output.as_mut_ptr() as *mut char, output.len())
  };
  std::str::from_utf8(&output[..len]).unwrap().to_owned()
}

/// Sets ICU's default time zone from a time zone id (e.g. `"UTC"`,
/// `"Asia/Manila"`). This makes `Date` resolve the given zone on every
/// platform, including Windows, where ICU otherwise reads the host time
/// zone from the OS and ignores the `TZ` environment variable.
///
/// Returns `false` — leaving the current default untouched — if `time_zone_id`
/// is not a time zone id ICU recognizes. Note that ICU's own "unknown zone"
/// id, `"Etc/Unknown"`, is rejected as well. Besides IANA ids, ICU accepts
/// custom offset ids such as `"GMT+05:00"`.
///
/// This mutates process wide state and is not synchronized with isolates
/// running on other threads, so it should be called before those isolates
/// evaluate any code observing the time zone. Afterwards, notify each isolate
/// via [`crate::Isolate::date_time_configuration_change_notification`] with
/// [`crate::TimeZoneDetection::Skip`] so cached values are refreshed without
/// re-detecting (and overwriting) the zone just set here.
#[must_use]
pub fn set_default_time_zone(time_zone_id: &str) -> bool {
  let Ok(c_str) = CString::new(time_zone_id) else {
    // An interior nul byte can't be a valid time zone id.
    return false;
  };
  unsafe { icu_set_default_time_zone(c_str.as_ptr()) }
}