Compare commits

..
1 Commits
6 changed files with 1434 additions and 174 deletions

No files matched your search

+253
View File
@@ -0,0 +1,253 @@
// <Kira Installer - universal Linux installer.>
// Copyright (C) <2026> <Kira Foundation>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/*
Different functions to help with localization, land locales timexone etc
*/
use crate::kira_system::{self, ExecCommandError};
use regex_lite::Regex;
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocaleData {
pub code: String,
pub charset: String,
pub description: Option<String>,
}
impl std::fmt::Display for LocaleData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(descr) = &self.description {
write!(f, "{} ({})", self.code, descr)
} else {
write!(f, "{}", self.code)
}
}
}
impl LocaleData {
pub fn default() -> Self {
Self {
code: "C.UTF-8".into(),
charset: "UTF-8".into(),
description: Some("C locale".into()),
}
}
// creates text to be appended to locale.gen file
// in case of C locale outputs empty string
pub fn locale_gen_line(&self) -> String {
format!("{} {}", &self.code, &self.charset)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeZoneData {
pub region: String,
pub zone: String,
}
impl TimeZoneData {
fn from_str(s: &str) -> Option<Self> {
let idx = s.find('/')?;
let (region, zone) = s.split_at(idx);
Some(Self {
region: region.into(),
zone: zone.trim_start_matches('/').into(),
})
}
///
/// Returns full path to timezone file
/// Example: "/usr/share/zoneinfo/Region/City"
///
pub fn tz_file_name(&self) -> String {
format!("/usr/share/zoneinfo/{}/{}", &self.region, &self.zone)
}
}
impl std::fmt::Display for TimeZoneData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.region, self.zone)
}
}
const LOCALES_GEN_FILE_NAME: &str = "/etc/locale.gen";
/// gets locales list from system "/etc/locale.gen" file
/// Filters result by filter_charset cahrset Some("UTF-8") to get only UTF-8 locales
pub fn get_locales_blocking(
filter_charset: Option<&str>,
) -> Result<Vec<LocaleData>, ExecCommandError> {
use std::fs::File;
use std::io::{BufReader, Read};
//pt_PT@euro ISO-8859-15
//ru_UA.UTF-8 UTF-8
//#ru_UA KOI8-U
//
// Example ru_UA.UTF-8 UTF-8
// Groups:
// 1: code, like ru_UA.UTF-8
// 3 charser: UTF-8
let key_re = Regex::new(r"^[[:word:]@]+").unwrap();
let loc_re = Regex::new(r"^#?([[:word:].@-]+) ([0-9A-Z-]+)$").unwrap();
let loc_desc = get_loc_descr_blocking()?;
let mut res: Vec<LocaleData> = Vec::new();
let mut file_content = String::new();
{
let locgen_file = File::open(LOCALES_GEN_FILE_NAME)?;
let mut reader = BufReader::new(locgen_file);
reader.read_to_string(&mut file_content)?;
}
for loc_line in file_content.lines() {
if let Some(captured) = loc_re.captures(loc_line.trim_end()) {
let code = captured[1].to_string();
let charset = captured[2].to_string();
// filters charset
if let Some(flt) = filter_charset
&& charset != flt
{
continue;
}
let description = key_re
.find(&code)
.and_then(|m| loc_desc.get(m.as_str()).cloned());
res.push(LocaleData {
code: code,
charset: charset,
description: description,
});
}
}
res.push(LocaleData::default());
Ok(res)
}
/// Gets locales description from "/usr/share/i18n/locales/" directory.
fn get_loc_descr_blocking() -> Result<HashMap<String, String>, ExecCommandError> {
// use std::process::Command;
// /usr/share/i18n/locales/uz_UZ:title "Uzbek (latin) locale for Uzbekistan"
// /usr/share/i18n/locales/uz_UZ@cyrillic:title "Uzbek (cyrillic) locale for Uzbekistan"
// 1 group - key code
// 2 group - description
let descr_re = Regex::new(r#"^/usr/share/i18n/locales/(.+):title[[:space:]]+"(.+)"$"#).unwrap();
let mut res: HashMap<String, String> = HashMap::new();
let raw_list =
kira_system::exec_command_out("grep", &vec!["-r", "title ", "/usr/share/i18n/locales/"])?;
for descr_line in raw_list.lines() {
if let Some(captured) = descr_re.captures(descr_line.trim_end()) {
res.insert(captured[1].to_string(), captured[2].to_string());
}
}
Ok(res)
}
/// Getting list of awailable timezones from system.
pub fn get_timezones_blocking() -> Result<Vec<TimeZoneData>, kira_system::ExecCommandError> {
use std::path::Path;
let loc_path: &Path = Path::new("/usr/share/zoneinfo");
let tz_list = kira_system::ls_dir_rec(loc_path)?;
Ok(tz_list
.iter()
.filter(|sb| sb.contains('/'))
.filter(|sb| !sb.starts_with("posix")) //filter out posix dir that contains copies
.filter_map(|str_t_zone| TimeZoneData::from_str(str_t_zone.trim()))
.collect::<Vec<TimeZoneData>>())
}
///
/// Function for making wild guess of locale by landguage code and timezone(if provided)
/// Ugly, needs some cleanups
///
pub fn guess_locale(
locales: &Vec<LocaleData>,
lang_code: &str,
maybe_tz: Option<TimeZoneData>,
) -> Option<LocaleData> {
use crate::tz_to_cc::get_cc;
// if we get lang code from wellcome stage, try to fing match with system locales
let lang = lang_code.replace("-", "_").to_lowercase();
let locales_filtered: Vec<LocaleData> = locales
.iter()
.filter(|l| l.code.to_lowercase().starts_with(&lang))
.cloned()
.collect();
if locales_filtered.len() == 0 {
None
}
// return locale if ve found exactly one
else if locales_filtered.len() == 1 {
locales_filtered.first().cloned()
}
// else do search
else {
// try to use country guessed from timezone
let loc_country_guess = maybe_tz
.and_then(|tz| get_cc(&tz.region, &tz.zone))
.and_then(|cc| {
// try to search for lang_contry in locales
let lang_search = if lang.contains('_') {
lang.clone()
} else {
format!("{}_{}", lang, cc.to_lowercase())
};
locales_filtered
.iter()
.find(|l| l.code.to_lowercase().starts_with(&lang_search))
.cloned()
});
// if we guessed locale by country return it
if loc_country_guess.is_some() {
loc_country_guess
// if language is en - return C locale
} else if lang == "en" {
Some(LocaleData::default())
// else try to gess purely by language code
} else {
if lang.contains('_') {
locales_filtered
.iter()
.find(|l| l.code.to_lowercase().starts_with(&lang))
.cloned()
} else {
let lang_search = format!("{}_{}", lang, lang);
locales_filtered
.iter()
.find(|l| l.code.to_lowercase().starts_with(&lang_search))
.cloned()
}
}
}
}
+1 -1
View File
@@ -15,7 +15,7 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // along with this program. If not, see <https://www.gnu.org/licenses/>.
/* /*
Functions for creating with disk layout Different functions for interacting with Linux system
*/ */
use crate::kira_disk_layout::*; use crate::kira_disk_layout::*;
+2
View File
@@ -36,6 +36,7 @@ rust_i18n::i18n!("src/locales", fallback = "en");
mod kira_color_bar; mod kira_color_bar;
mod kira_disk_layout; mod kira_disk_layout;
mod kira_include; mod kira_include;
mod kira_locales;
mod kira_logger; mod kira_logger;
mod kira_scroll_list; mod kira_scroll_list;
mod kira_size; mod kira_size;
@@ -46,6 +47,7 @@ mod kira_theming;
mod kira_xkb; mod kira_xkb;
mod stage; mod stage;
mod stages; mod stages;
mod tz_to_cc;
enum Views { enum Views {
Start, Start,
+9 -127
View File
@@ -19,126 +19,13 @@
*/ */
use crate::{ use crate::{
kira_system::{self, ExecCommandError},
kira_theming, kira_theming,
stage::{KiraConfig, StageAction}, stage::{KiraConfig, StageAction},
}; };
use iced::{Alignment, widget}; use iced::{Alignment, widget};
use regex_lite::Regex;
use rust_i18n::t; use rust_i18n::t;
use std::collections::HashMap;
const LOCALES_GEN_FILE_NAME: &str = "/etc/locale.gen"; use crate::kira_locales::{self, LocaleData, get_locales_blocking};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocaleData {
pub code: String,
pub charset: String,
pub description: Option<String>,
}
impl std::fmt::Display for LocaleData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(descr) = &self.description {
write!(f, "{} ({})", self.code, descr)
} else {
write!(f, "{}", self.code)
}
}
}
impl LocaleData {
pub fn default() -> Self {
Self {
code: "C.UTF-8".into(),
charset: "UTF-8".into(),
description: Some("C locale".into()),
}
}
// creates text to be appended to locale.gen file
// in case of C locale outputs empty string
pub fn locale_gen_line(&self) -> String {
format!("{} {}", &self.code, &self.charset)
}
}
/// gets locales list from system "/etc/locale.gen" file
/// Filters result by filter_charset cahrset Some("UTF-8") to get only UTF-8 locales
fn get_locales_blocking(filter_charset: Option<&str>) -> Result<Vec<LocaleData>, ExecCommandError> {
use std::fs::File;
use std::io::{BufReader, Read};
//pt_PT@euro ISO-8859-15
//ru_UA.UTF-8 UTF-8
//#ru_UA KOI8-U
//
// Example ru_UA.UTF-8 UTF-8
// Groups:
// 1: code, like ru_UA.UTF-8
// 3 charser: UTF-8
let key_re = Regex::new(r"^[[:word:]@]+").unwrap();
let loc_re = Regex::new(r"^#?([[:word:].@-]+) ([0-9A-Z-]+)$").unwrap();
let loc_desc = get_loc_descr_blocking()?;
let mut res: Vec<LocaleData> = Vec::new();
let mut file_content = String::new();
{
let locgen_file = File::open(LOCALES_GEN_FILE_NAME)?;
let mut reader = BufReader::new(locgen_file);
reader.read_to_string(&mut file_content)?;
}
for loc_line in file_content.lines() {
if let Some(captured) = loc_re.captures(loc_line.trim_end()) {
let code = captured[1].to_string();
let charset = captured[2].to_string();
// filters charset
if let Some(flt) = filter_charset
&& charset != flt
{
continue;
}
let description = key_re
.find(&code)
.and_then(|m| loc_desc.get(m.as_str()).cloned());
res.push(LocaleData {
code: code,
charset: charset,
description: description,
});
}
}
res.push(LocaleData::default());
Ok(res)
}
/// Gets locales description from "/usr/share/i18n/locales/" directory.
fn get_loc_descr_blocking() -> Result<HashMap<String, String>, ExecCommandError> {
// use std::process::Command;
// /usr/share/i18n/locales/uz_UZ:title "Uzbek (latin) locale for Uzbekistan"
// /usr/share/i18n/locales/uz_UZ@cyrillic:title "Uzbek (cyrillic) locale for Uzbekistan"
// 1 group - key code
// 2 group - description
let descr_re = Regex::new(r#"^/usr/share/i18n/locales/(.+):title[[:space:]]+"(.+)"$"#).unwrap();
let mut res: HashMap<String, String> = HashMap::new();
let raw_list =
kira_system::exec_command_out("grep", &vec!["-r", "title ", "/usr/share/i18n/locales/"])?;
for descr_line in raw_list.lines() {
if let Some(captured) = descr_re.captures(descr_line.trim_end()) {
res.insert(captured[1].to_string(), captured[2].to_string());
}
}
Ok(res)
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct LocaleStage { pub struct LocaleStage {
@@ -172,21 +59,16 @@ impl LocaleStage {
.as_ref() .as_ref()
.and_then(|rw| Some(rw.loc_code.clone())); .and_then(|rw| Some(rw.loc_code.clone()));
let maybe_tz = k_config
.res_timezone
.as_ref()
.and_then(|tzr| Some(tzr.time_zone.clone()));
let locales: Vec<LocaleData> = get_locales_blocking(Some("UTF-8")).unwrap(); let locales: Vec<LocaleData> = get_locales_blocking(Some("UTF-8")).unwrap();
// if we get lang code from wellcome stage, try to fing match with system locales let lang_match = maybe_lang
let lang_match = if let Some(lang) = maybe_lang .and_then(|lang| kira_locales::guess_locale(&locales, &lang, maybe_tz))
&& lang != "en" .unwrap_or_else(LocaleData::default);
{
let lang = lang.replace("-", "_").to_lowercase();
locales
.iter()
.find(|l| l.code.to_lowercase().starts_with(&lang))
.cloned()
.unwrap_or_else(LocaleData::default)
} else {
LocaleData::default()
};
let lang_locale_text = format!( let lang_locale_text = format!(
"{}: {}", "{}: {}",
+2 -46
View File
@@ -22,41 +22,11 @@ use crate::stage::{KiraConfig, StageAction};
use iced::{Alignment, Length, widget}; use iced::{Alignment, Length, widget};
use log; use log;
use rust_i18n::t; use rust_i18n::t;
use std::{collections::HashMap, path::Path}; use std::collections::HashMap;
use crate::kira_scroll_list; use crate::kira_scroll_list;
use crate::kira_system;
#[derive(Debug, Clone, PartialEq, Eq)] use crate::kira_locales::{TimeZoneData, get_timezones_blocking};
pub struct TimeZoneData {
region: String,
zone: String,
}
impl TimeZoneData {
fn from_str(s: &str) -> Option<Self> {
let idx = s.find('/')?;
let (region, zone) = s.split_at(idx);
Some(Self {
region: region.into(),
zone: zone.trim_start_matches('/').into(),
})
}
///
/// Returns full path to timezone file
/// Example: "/usr/share/zoneinfo/Region/City"
///
pub fn tz_file_name(&self) -> String {
format!("/usr/share/zoneinfo/{}/{}", &self.region, &self.zone)
}
}
impl std::fmt::Display for TimeZoneData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.region, self.zone)
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct TimeZoneStage { pub struct TimeZoneStage {
@@ -83,20 +53,6 @@ pub enum Message {
Back, Back,
} }
/// Getting list of awailable timezones from system.
fn get_timezones_blocking() -> Result<Vec<TimeZoneData>, kira_system::ExecCommandError> {
let loc_path: &Path = Path::new("/usr/share/zoneinfo");
let tz_list = kira_system::ls_dir_rec(loc_path)?;
Ok(tz_list
.iter()
.filter(|sb| sb.contains('/'))
.filter(|sb| !sb.starts_with("posix")) //filter out posix dir that contains copies
.filter_map(|str_t_zone| TimeZoneData::from_str(str_t_zone.trim()))
.collect::<Vec<TimeZoneData>>())
}
/// Getting list of awailable timezones from system. /// Getting list of awailable timezones from system.
// fn get_timezones_blocking_depr() -> Result<Vec<TimeZoneData>, String> { // fn get_timezones_blocking_depr() -> Result<Vec<TimeZoneData>, String> {
// use std::process::Command; // use std::process::Command;
+1167
View File
File diff suppressed because it is too large. Load diff