Debian Codegraph @

third_party/rust/dwrote/src/helpers.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use std::ffi::OsStr;
6 use std::os::windows::ffi::OsStrExt;
7 use winapi::ctypes::wchar_t;
8 use winapi::shared::minwindef::{BOOL, FALSE};
9 use winapi::shared::winerror::S_OK;
10 use winapi::um::dwrite::IDWriteLocalizedStrings;
11 use winapi::um::winnls::GetUserDefaultLocaleName;
12 use wio::com::ComPtr;
13
14 lazy_static! {
15 static ref SYSTEM_LOCALE: Vec<wchar_t> = {
16 unsafe {
17 let mut locale: Vec<wchar_t> = vec![0; 85];
18 GetUserDefaultLocaleName(locale.as_mut_ptr(), locale.len() as i32 - 1);
19 locale
20 }
21 };
22 static ref EN_US_LOCALE: Vec<wchar_t> = { OsStr::new("en-us").to_wide_null() };
23 }
24
25 pub fn get_locale_string(strings: &mut ComPtr<IDWriteLocalizedStrings>) -> String {
26 unsafe {
27 let mut index: u32 = 0;
28 let mut exists: BOOL = FALSE;
29 let hr = strings.FindLocaleName((*SYSTEM_LOCALE).as_ptr(), &mut index, &mut exists);
30 if hr != S_OK || exists == FALSE {
31 let hr = strings.FindLocaleName((*EN_US_LOCALE).as_ptr(), &mut index, &mut exists);
32 if hr != S_OK || exists == FALSE {
33 // Ultimately fall back to first locale on list
34 index = 0;
35 }
36 }
37
38 let mut length: u32 = 0;
39 let hr = strings.GetStringLength(index, &mut length);
40 assert!(hr == 0);
41
42 let mut name: Vec<wchar_t> = Vec::with_capacity(length as usize + 1);
43 let hr = strings.GetString(index, name.as_mut_ptr(), length + 1);
44 assert!(hr == 0);
45 name.set_len(length as usize);
46
47 String::from_utf16(&name).ok().unwrap()
48 }
49 }
50
51 // ToWide from https://github.com/retep998/wio-rs/blob/master/src/wide.rs
52
53 pub trait ToWide {
54 fn to_wide(&self) -> Vec<u16>;
55 fn to_wide_null(&self) -> Vec<u16>;
56 }
57
58 impl<T> ToWide for T
59 where
60 T: AsRef<OsStr>,
61 {
62 fn to_wide(&self) -> Vec<u16> {
63 self.as_ref().encode_wide().collect()
64 }
65 fn to_wide_null(&self) -> Vec<u16> {
66 self.as_ref().encode_wide().chain(Some(0)).collect()
67 }
68 }