Compare commits

...
23 Commits
Author SHA256 Message Date
kira c80ffc897c Big commit that add guessing locale by selected lang and timezone, includes some refactoring 2026-12-04 22:25:39 +01:00
kira 2321d06af1 Implemented keyboard layout testing by forking text_input and using libxkbcommon 2026-12-03 00:28:16 +01:00
kira 1186932625 More work on install stage. Trying to implement keyboard layout test by Dbus switching, not working properly, dead end 2026-11-29 16:57:38 +01:00
kira 740bbdb4d8 More work on install stage, keyboard and time config 2026-11-26 16:41:02 +01:00
kira 7c57193bf1 Made crazy_bonker_console_keymap function for console keymap estimation from XKB layout. 2026-11-23 23:19:37 +01:00
kira 5597b56538 More work on install stage, locales/keyboard 2026-11-22 23:47:44 +01:00
kira ecc87066ad Fix for exec_cmd_chroot function 2026-11-21 22:55:53 +01:00
kira eee7fd17d6 More work on install stage, testing locales stuff 2026-11-21 21:23:58 +01:00
kira 9d68343219 Locale stage code cleanup 2026-11-20 22:30:49 +01:00
kira d494dbe3c8 Dependencies update 2026-11-20 17:36:01 +01:00
kira 7e72abb528 More work on install stage 2026-11-20 17:12:56 +01:00
kira 841090d3d6 Rework of locales, moving to use regexp_lite for saner parsing. 2026-11-20 17:11:42 +01:00
kira d68ee36afa More work on install stage 2026-11-18 22:15:57 +01:00
kira 1399c56135 More work on install stage 2026-11-18 14:53:12 +01:00
kira 029df21d3e Basestrap kernel and stuff 2026-11-08 00:16:17 +01:00
kira 279bd30463 Add install base step. 2026-11-04 23:15:56 +01:00
kira 1bdc4547d3 Add pacman.conf and some other stuff. 2026-11-04 23:13:20 +01:00
kira e40fa95cc8 Filter out posix from timezones list 2026-11-04 17:15:35 +01:00
kira 3899af1c79 Changing ls_dir_rec so it ignore symlinks. 2026-11-03 09:38:06 +01:00
kira fb90bc3092 In timezones stage changing get_timezones_blocking from using systemd timedatectl to query filesystem directly. 2026-11-03 08:38:51 +01:00
kira 6f921f3ff0 Continue working on installation stage 2026-11-01 16:25:05 +01:00
kira b5b5bd764a More work on installation stage 2026-10-01 17:10:26 +02:00
kira 3b086605cf Work on making partitions start-end calculate properly. Specifically 2mb at start and -33 sectors GPT reserved at the end. 2026-09-28 00:13:12 +02:00
23 changed files with 5423 additions and 1399 deletions

No files matched your search

Generated
+469 -931
View File
File diff suppressed because it is too large. Load diff
+11 -5
View File
@@ -8,21 +8,26 @@ edition = "2024"
[dependencies] [dependencies]
blocking = "1.6" blocking = "1.6"
iced = { version = "0.14", default-features = false, features = ["crisp", "linux-theme-detection", "tiny-skia", "wgpu", "x11", "smol", "image"] } # smol = "2"
unicode-segmentation = "1"
iced = { version = "0.14", default-features = false, features = ["crisp", "linux-theme-detection", "tiny-skia", "x11", "smol", "image", "advanced"] }
#iced = { git = "https://github.com/iced-rs/iced", branch = "vello_cpu", default-features = false, features = ["crisp", "linux-theme-detection", "vello-cpu", "x11", "smol", "image"]} #iced = { git = "https://github.com/iced-rs/iced", branch = "vello_cpu", default-features = false, features = ["crisp", "linux-theme-detection", "vello-cpu", "x11", "smol", "image"]}
# zbus = { version = "6", default-features = false, features = ["default-rt", "comms"] }
iced_moving_picture = "0" iced_moving_picture = "0"
log = "0.4" log = "0.4"
rust-i18n = "3" rust-i18n = "4"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
time-format = "1.2" time-format = "1.2"
toml = "1" regex-lite = "0.1"
xkbcommon = { version = "0.9.0" }
[dev-dependencies] [dev-dependencies]
rand = "0.10" rand = "0.10"
[profile.dev] [profile.dev]
opt-level = 2 opt-level = 3
codegen-units = 16 codegen-units = 16
[profile.release] [profile.release]
@@ -31,7 +36,8 @@ debug = false
incremental = false incremental = false
codegen-units = 1 codegen-units = 1
# We need level 3 for tiny-skia otherwise render is lagging # We need level 3 for tiny-skia otherwise render is lagging
opt-level = "s" # opt-level = "s"
opt-level = 3
strip = true strip = true
+112
View File
@@ -0,0 +1,112 @@
#
# /etc/pacman.conf
#
# See the pacman.conf(5) manpage for option and repository directives
#
# GENERAL OPTIONS
#
[options]
# The following paths are commented out with their default values listed.
# If you wish to use different paths, uncomment and update the paths.
#RootDir = /
#DBPath = /var/lib/pacman/
#CacheDir = /var/cache/pacman/pkg/
#LogFile = /var/log/pacman.log
#GPGDir = /etc/pacman.d/gnupg/
#HookDir = /etc/pacman.d/hooks/
HoldPkg = pacman glibc
#XferCommand = /usr/bin/curl -L -C - -f -o %o %u
#XferCommand = /usr/bin/wget --passive-ftp -c -O %o %u
#CleanMethod = KeepInstalled
Architecture = auto
# Pacman won't upgrade packages listed in IgnorePkg and members of IgnoreGroup
#IgnorePkg =
#IgnoreGroup =
#NoUpgrade =
#NoExtract =
# Misc options
#UseSyslog
Color
ILoveCandy
#NoProgressBar
CheckSpace
#VerbosePkgLists
ParallelDownloads = 5
DownloadUser = alpm
#DisableSandboxFilesystem
#DisableSandboxSyscalls
# By default, pacman accepts packages signed by keys that its local keyring
# trusts (see pacman-key and its man page), as well as unsigned packages.
SigLevel = Required DatabaseOptional
LocalFileSigLevel = Optional
#RemoteFileSigLevel = Required
# NOTE: You must run `pacman-key --init` before first using pacman; the local
# keyring can then be populated with the keys of all official Artix Linux
# packagers with `pacman-key --populate artix`.
#
# REPOSITORIES
# - can be defined here or included from another file
# - pacman will search repositories in the order defined here
# - local/custom mirrors can be added here or in separate files
# - repositories listed first will take precedence when packages
# have identical names, regardless of version number
# - URLs will have $repo replaced by the name of the current repo
# - URLs will have $arch replaced by the name of the architecture
#
# Repository entries are of the format:
# [repo-name]
# Server = ServerName
# Include = IncludePath
#
# The header [repo-name] is crucial - it must be present and
# uncommented to enable the repo.
#
# kira linux base repository
[kira-base]
SigLevel = Required TrustedOnly
Include = /etc/pacman.d/kira-mirrorlist
# The gremlins repositories are disabled by default. To enable, uncomment the
# repo name header and Include lines. You can add preferred servers immediately
# after the header, and they will be used before the default mirrors.
#[system-gremlins]
#Include = /etc/pacman.d/mirrorlist
[system]
Include = /etc/pacman.d/mirrorlist
#[world-gremlins]
#Include = /etc/pacman.d/mirrorlist
[world]
Include = /etc/pacman.d/mirrorlist
#[galaxy-gremlins]
#Include = /etc/pacman.d/mirrorlist
[galaxy]
Include = /etc/pacman.d/mirrorlist
# If you want to run 32 bit applications on your x86_64 system,
# enable the lib32 repositories as required here.
#[lib32-gremlins]
#Include = /etc/pacman.d/mirrorlist
#[lib32]
#Include = /etc/pacman.d/mirrorlist
# An example of a custom package repository. See the pacman manpage for
# tips on creating your own repositories.
#[custom]
#SigLevel = Optional TrustAll
#Server = file:///home/custompkgs
+94 -24
View File
@@ -20,7 +20,7 @@
use crate::kira_size::KiraSize; use crate::kira_size::KiraSize;
use log; use log;
use std::{collections::HashMap}; use std::collections::HashMap;
/// ///
/// size - device size in bytes /// size - device size in bytes
/// sector size - default 4096 /// sector size - default 4096
@@ -117,20 +117,25 @@ impl BlkDev {
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct BcachefsProp { pub struct BcachefsProp {
pub password: Option<String>, pub password: Option<String>,
pub comp_alg: Option<String>, pub comp_alg: Option<String>,
} }
impl BcachefsProp { impl BcachefsProp {
pub fn new(password: Option<String>, comp_alg: Option<String>) -> Self { pub fn new(password: Option<String>, comp_alg: Option<String>) -> Self {
Self { password:password, comp_alg: comp_alg } Self {
password: password,
comp_alg: comp_alg,
}
} }
pub fn default() -> Self { pub fn default() -> Self {
Self { password: None, comp_alg: None } Self {
password: None,
comp_alg: None,
}
} }
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@@ -208,7 +213,7 @@ impl FSType {
pub enum PartRole { pub enum PartRole {
EFI, EFI,
ROOT, ROOT,
SWAP SWAP,
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@@ -230,6 +235,22 @@ impl std::fmt::Display for PartInfo {
} }
impl PartInfo { impl PartInfo {
///
/// calculate par end byte as 0 starting bytes index (for parted and such)
///
pub fn part_end(&self) -> KiraSize {
// important to shift here by 1 because disk index is starting from 0, and part end pointing to last byte of the partition.
(self.start + self.size) - KiraSize::new_b(1)
}
///
/// Returns zero based byte index of start of next (right after this one) partition
///
pub fn next_part_start(&self) -> KiraSize {
// important to shift here by 1 because disk index is starting from 0, and part end pointing to last byte of the partition.
self.start + self.size
}
pub fn from_hash_map(data: &HashMap<String, String>) -> Option<Self> { pub fn from_hash_map(data: &HashMap<String, String>) -> Option<Self> {
Some(Self { Some(Self {
name: data.get("NAME")?.clone(), name: data.get("NAME")?.clone(),
@@ -249,8 +270,14 @@ impl PartInfo {
}) })
} }
///
/// Returns partition full path by partlabel "/dev/disk/by-partlabel/{partlabel}"
/// Returns None if partition do not have partlabel
///
pub fn partlabel_dev(&self) -> Option<String> { pub fn partlabel_dev(&self) -> Option<String> {
self.gpt_label.as_ref().and_then(|l| Some(format!("/dev/disk/by-partlabel/{}", l))) self.gpt_label
.as_ref()
.and_then(|l| Some(format!("/dev/disk/by-partlabel/{}", l)))
} }
} }
@@ -260,9 +287,11 @@ fn get_dev_part_blocking(dev_name: &str) -> Result<Vec<PartInfo>, String> {
//"lsblk -o NAME,SIZE,FSTYPE -l -n /dev/nvme0n1" //"lsblk -o NAME,SIZE,FSTYPE -l -n /dev/nvme0n1"
// lsblk -o NAME,SIZE,FSTYPE,TYPE,PARTLABEL,LABEL,PARTFLAGS -b -P // lsblk -o NAME,SIZE,FSTYPE,TYPE,PARTLABEL,LABEL,PARTFLAGS -b -P
// -x NAME - sorting by name
match Command::new("lsblk") match Command::new("lsblk")
.args([ .args([
"-x",
"NAME",
"-o", "-o",
"NAME,SIZE,FSTYPE,TYPE,PARTLABEL,LABEL,MOUNTPOINT,PARTFLAGS", "NAME,SIZE,FSTYPE,TYPE,PARTLABEL,LABEL,MOUNTPOINT,PARTFLAGS",
"-b", "-b",
@@ -329,7 +358,7 @@ pub fn align_part(size: u64, start: u64, align: u64) -> Option<(u64, u64, u64)>
// decreasing end if not align // decreasing end if not align
let part_end = align_start + size; let part_end = align_start + size;
let end_mod = part_end % align; let end_mod = part_end % align;
log::debug!("part_end: {} end_mod: {}", part_end, end_mod);
let align_end = part_end - end_mod - 1; let align_end = part_end - end_mod - 1;
let align_size = align_end - align_start + 1; let align_size = align_end - align_start + 1;
@@ -342,7 +371,13 @@ pub fn align_part(size: u64, start: u64, align: u64) -> Option<(u64, u64, u64)>
); );
return None; return None;
} }
log::debug!(
"align_size: {}, align_start:{}, align_end: {} end_mod: {}",
align_size,
align_start,
align_end,
end_mod
);
Some((align_size, align_start, align_end)) Some((align_size, align_start, align_end))
} }
@@ -353,15 +388,31 @@ pub struct PartLayout {
pub part_list: Vec<PartInfo>, pub part_list: Vec<PartInfo>,
} }
///
/// GPT requires 33x512 sectors at the very end of the disk (16896 bytes):
/// 32 sectors - backup Partition Entry Array
/// 1 sector - backup GPT header
///
impl PartLayout { impl PartLayout {
pub fn new(dev: BlkDev) -> Self { pub fn new(dev: BlkDev) -> Self {
// 16896 - reserved space at the dev end for gpt
let usable_space = dev.size - KiraSize::new_b(16896);
Self { Self {
empty_space: dev.size, empty_space: usable_space,
dev: dev, dev: dev,
part_list: Vec::new(), part_list: Vec::new(),
} }
} }
pub fn get_part(&self, part_role: PartRole) -> Option<PartInfo> {
for part in &self.part_list {
if let Some(role) = &part.role && role.eq(&part_role) {
return Some(part.clone());
}
}
None
}
pub fn read_from_disk(dev: &BlkDev) -> Result<Self, String> { pub fn read_from_disk(dev: &BlkDev) -> Result<Self, String> {
let part_list = get_dev_part_blocking(&dev.name)?; let part_list = get_dev_part_blocking(&dev.name)?;
let parts_size = part_list let parts_size = part_list
@@ -374,11 +425,11 @@ impl PartLayout {
}) })
} }
pub fn new_table(mut self) -> Self { // pub fn new_table(mut self) -> Self {
self.empty_space = self.dev.size; // self.empty_space = self.dev.size;
self.part_list = Vec::new(); // self.part_list = Vec::new();
self // self
} // }
pub fn add_part( pub fn add_part(
mut self, mut self,
@@ -390,19 +441,29 @@ impl PartLayout {
role: Option<PartRole>, role: Option<PartRole>,
) -> Self { ) -> Self {
let part_start = if self.part_list.is_empty() { let part_start = if self.part_list.is_empty() {
// need to substract 2 mb offset from disk start.
self.empty_space = self.empty_space - KiraSize::new_mb(2);
KiraSize::new_mb(2) KiraSize::new_mb(2)
} else { } else {
self.dev.size - self.empty_space // last part end + 1
self.part_list.last().unwrap().next_part_start()
}; };
let (size, start, _) = let (a_size, a_start, _) =
align_part(part_size.b(), part_start.b(), self.dev.sector_size.b()).unwrap(); align_part(part_size.b(), part_start.b(), self.dev.sector_size.b()).unwrap();
log::debug!(
"PartLayout.add_part gpt_label{:?}, size_asked:{}, size_al:{}",
gpt_label,
part_size,
a_size
);
let part_name = format!("{}p{}", self.dev.name, self.part_list.len() + 1); let part_name = format!("{}p{}", self.dev.name, self.part_list.len() + 1);
self.part_list.push(PartInfo { self.part_list.push(PartInfo {
name: part_name, name: part_name,
size: KiraSize::new_b(size), size: KiraSize::new_b(a_size),
start: KiraSize::new_b(start), start: KiraSize::new_b(a_start),
fs_type: fs_type, fs_type: fs_type,
gpt_label: gpt_label, gpt_label: gpt_label,
fs_label: fs_label, fs_label: fs_label,
@@ -410,10 +471,14 @@ impl PartLayout {
role: role, role: role,
}); });
self.empty_space = self.empty_space - KiraSize::new_b(size); self.empty_space = self.empty_space - KiraSize::new_b(a_size);
self self
} }
///
/// Use this to add partition of (disk_empty_space - reserve_space)
/// Specifically to leave some space at the end for SWAP and such
///
pub fn add_part_reserve( pub fn add_part_reserve(
self, self,
reserve_space: KiraSize, reserve_space: KiraSize,
@@ -427,7 +492,13 @@ impl PartLayout {
self.add_part(p_size, fs_type, gpt_label, fs_label, mount_point, role) self.add_part(p_size, fs_type, gpt_label, fs_label, mount_point, role)
} }
pub fn gen_kira_layout(dev: BlkDev, efi_size: KiraSize, swap_size: KiraSize, maybe_password: Option<String>, maybe_compr: Option<String>) -> Self { pub fn gen_kira_layout(
dev: BlkDev,
efi_size: KiraSize,
swap_size: KiraSize,
maybe_password: Option<String>,
maybe_compr: Option<String>,
) -> Self {
let mut res: PartLayout = PartLayout::new(dev); let mut res: PartLayout = PartLayout::new(dev);
// UEFI partition // UEFI partition
@@ -454,7 +525,7 @@ impl PartLayout {
res = res.add_part( res = res.add_part(
swap_size, swap_size,
FSType::SWAP, FSType::SWAP,
Some("swap".into()), Some("bee-swap".into()),
None, None,
Some("SWAP".into()), Some("SWAP".into()),
Some(PartRole::SWAP), Some(PartRole::SWAP),
@@ -465,7 +536,6 @@ impl PartLayout {
} }
} }
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use rand::RngExt; use rand::RngExt;
+4
View File
@@ -0,0 +1,4 @@
const PACMAN_CONF: &str = include_str!("files/etc/pacman.conf");
+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()
}
}
}
}
+276 -25
View File
@@ -15,22 +15,32 @@
// 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::*;
use std::process::Command; use crate::kira_size::KiraSize;
use std::fmt::format;
use std::fs; use std::fs;
use std::io::Read;
use std::path::Path;
use std::process::Command;
#[derive(Debug)] #[derive(Debug)]
pub struct CommandFailed{ pub struct CommandFailed {
stderr: Vec<u8>, stderr: Vec<u8>,
cmd: String, cmd: String,
} }
impl std::fmt::Display for CommandFailed { impl std::fmt::Display for CommandFailed {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Command failed! Command: {}; Stderr: {}", self.cmd, String::from_utf8(self.stderr.clone()).unwrap_or_else(|_|{"STDEER IS NOT VALID UTF-8".to_string()})) write!(
f,
"Command failed! Command: {}; Stderr: {}",
self.cmd,
String::from_utf8(self.stderr.clone())
.unwrap_or_else(|_| { "STDEER IS NOT VALID UTF-8".to_string() })
)
} }
} }
@@ -95,7 +105,52 @@ impl std::fmt::Display for ExecCommandError {
impl std::error::Error for ExecCommandError {} impl std::error::Error for ExecCommandError {}
/// exec given sommand with arguments, capturing stderr in case or failure /// exec given sommand with arguments, capturing stderr in case or failure
fn exec_command(cmd: &str, args: &Vec<&str>) -> Result<(), ExecCommandError> { pub fn exec_command_stdin(
cmd: &str,
args: &Vec<&str>,
stdin_data: &str,
) -> Result<(), ExecCommandError> {
use std::io::Write;
use std::process::{Command, Stdio};
use std::thread;
let mut child = Command::new(cmd)
.args(args)
.stdin(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
let mut stdin = child
.stdin
.take()
.ok_or("Failed to capture stdin".to_string())?;
let mut stderr = child
.stderr
.take()
.ok_or("Failed to capture stderr".to_string())?;
let stderr_handle = thread::spawn(move || {
let mut buf = Vec::new();
use std::io::Read;
let _ = stderr.read_to_end(&mut buf);
buf
});
stdin.write_all(stdin_data.as_bytes())?;
let status = child.wait()?;
let stderr_output = stderr_handle.join().unwrap();
if status.success() {
Ok(())
} else {
Err(CommandFailed::new(cmd, args, stderr_output).into())
}
}
/// exec given sommand with arguments, capturing stderr in case or failure
pub fn exec_command(cmd: &str, args: &Vec<&str>) -> Result<(), ExecCommandError> {
let out = Command::new(cmd).args(args).output()?; let out = Command::new(cmd).args(args).output()?;
if out.status.success() { if out.status.success() {
Ok(()) Ok(())
@@ -106,7 +161,7 @@ fn exec_command(cmd: &str, args: &Vec<&str>) -> Result<(), ExecCommandError> {
/// exec given sommand with arguments, returning stdout parsed to UTF-8 string /// exec given sommand with arguments, returning stdout parsed to UTF-8 string
/// capturing stderr in case or failure /// capturing stderr in case or failure
fn exec_command_out(cmd: &str, args: &Vec<&str>) -> Result<String, ExecCommandError> { pub fn exec_command_out(cmd: &str, args: &Vec<&str>) -> Result<String, ExecCommandError> {
let out = Command::new(cmd).args(args).output()?; let out = Command::new(cmd).args(args).output()?;
if out.status.success() { if out.status.success() {
Ok(String::from_utf8(out.stdout)?) Ok(String::from_utf8(out.stdout)?)
@@ -115,6 +170,77 @@ fn exec_command_out(cmd: &str, args: &Vec<&str>) -> Result<String, ExecCommandEr
} }
} }
///
/// Exec command and logs its output via log::info! in real time
///
fn exec_command_log(cmd: &str, args: &Vec<&str>) -> Result<(), ExecCommandError> {
use std::io::{BufRead, BufReader};
use std::process::{Command, Stdio};
use std::thread;
log::debug!("Executing command {} {:?}", cmd, args);
// Configure the command to pipe stdout
let mut child = Command::new(cmd)
.args(args)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()?;
// Take ownership of the stdout handle
let stdout = child
.stdout
.take()
.ok_or("Failed to capture stdout".to_string())?;
let mut stderr = child
.stderr
.take()
.ok_or("Failed to capture stderr".to_string())?;
let stderr_handle = thread::spawn(move || {
let mut buf = Vec::new();
use std::io::Read;
let _ = stderr.read_to_end(&mut buf);
buf
});
// Wrap in BufReader for efficient line-by-line reading
let reader = BufReader::new(stdout);
// Iterate and log each line in real time
for line in reader.lines() {
match line {
Ok(text) => log::info!("{}: {}", cmd, text),
Err(e) => log::error!("Read error: {}", e),
}
}
// Wait for the process to finish to prevent zombies and check status
let status = child.wait()?;
let stderr_output = stderr_handle.join().unwrap();
if status.success() {
Ok(())
} else {
Err(CommandFailed::new(cmd, args, stderr_output).into())
}
}
///
/// Chroot to chroot_dir and executes specified command there
///
pub fn exec_cmd_chroot(
chroot_dir: &str,
cmd: &str,
args: &Vec<&str>,
) -> Result<(), ExecCommandError> {
let mut cmd_args: Vec<&str> = Vec::new();
cmd_args.push(chroot_dir);
cmd_args.push(cmd);
cmd_args.extend(args);
exec_command("artix-chroot", &cmd_args)
}
/// sync system time with chrony /// sync system time with chrony
/// dinitctl start chrony /// dinitctl start chrony
pub fn dinit_sync_time_chrony() -> Result<(), ExecCommandError> { pub fn dinit_sync_time_chrony() -> Result<(), ExecCommandError> {
@@ -124,7 +250,16 @@ pub fn dinit_sync_time_chrony() -> Result<(), ExecCommandError> {
/// Install base system /// Install base system
/// basestrap /mnt base base-devel dinit elogind-dinit /// basestrap /mnt base base-devel dinit elogind-dinit
pub fn basestrap_dinit(root_dir: &str) -> Result<(), ExecCommandError> { pub fn basestrap_dinit(root_dir: &str) -> Result<(), ExecCommandError> {
exec_command("basestrap", &vec![root_dir, "base", "base-devel", "dinit", "elogind-dinit"]) exec_command_log(
"basestrap",
&vec![root_dir, "base", "base-devel", "dinit", "elogind-dinit"],
)
}
pub fn basestrap(root_dir: &str, pkg_list: &[&str]) -> Result<(), ExecCommandError> {
let mut args: Vec<&str> = vec![root_dir];
args.extend(pkg_list);
exec_command_log("basestrap", &args)
} }
/// Executes parted command with given arguments /// Executes parted command with given arguments
@@ -151,12 +286,7 @@ fn parted_get_last_part_num(dev: &BlkDev) -> Result<u32, ExecCommandError> {
/// Its blocking function /// Its blocking function
pub fn parted_init_gpt_part_table(dev: &BlkDev) -> Result<(), ExecCommandError> { pub fn parted_init_gpt_part_table(dev: &BlkDev) -> Result<(), ExecCommandError> {
let dev_full_name = dev.full_name(); let dev_full_name = dev.full_name();
let args = vec![ let args = vec!["--script", &dev_full_name, "mklabel", "gpt"];
"--script",
&dev_full_name,
"mklabel",
"gpt",
];
exec_command("parted", &args) exec_command("parted", &args)
} }
@@ -166,7 +296,8 @@ const LINUX_ROOT_X86_64_TYPE: &str = "4F68BCE3-E8CD-4DB1-96E7-FBCAF984B709";
/// It assumes that we add partitions sequentially to empty space (for part attributes settings) /// It assumes that we add partitions sequentially to empty space (for part attributes settings)
/// Otherwise can produce bonkers layout /// Otherwise can produce bonkers layout
pub fn parted_mkpart(dev: &BlkDev, part: &PartInfo) -> Result<(), ExecCommandError> { pub fn parted_mkpart(dev: &BlkDev, part: &PartInfo) -> Result<(), ExecCommandError> {
let part_end = part.start + part.size; // important to shift here by 1 because disk index is starting from 0, and part end pointing to last byte of the partition.
let part_end = part.part_end();
// gpt label should be in double qutes // gpt label should be in double qutes
let gpt_label = if let Some(s) = &part.gpt_label { let gpt_label = if let Some(s) = &part.gpt_label {
@@ -174,6 +305,14 @@ pub fn parted_mkpart(dev: &BlkDev, part: &PartInfo) -> Result<(), ExecCommandErr
} else { } else {
"\"\"".to_string() "\"\"".to_string()
}; };
log::debug!(
"Creatin partition dev:{}, label:{}, fs_type:{}, start:{}, end:{}",
dev.full_name(),
gpt_label,
part.fs_type.to_parted_str(),
part.start.to_parted_bytes_str(),
part_end.to_parted_bytes_str()
);
// creating partition // creating partition
exec_parted(&vec![ exec_parted(&vec![
"--script", "--script",
@@ -218,7 +357,7 @@ pub fn parted_mkpart(dev: &BlkDev, part: &PartInfo) -> Result<(), ExecCommandErr
} }
/// creating single drive bcachefs volume /// creating single drive bcachefs volume
/// compression: lz4, zstd /// compression: lz4, zstd
pub fn bcachefs_format( pub fn bcachefs_format(
dev_name: &str, dev_name: &str,
compression: Option<String>, compression: Option<String>,
@@ -255,13 +394,11 @@ pub fn bcachefs_format(
/// unlok encrypted bcache volume /// unlok encrypted bcache volume
pub fn bcachefs_unlock(dev_name: &str, pass: &str) -> Result<(), ExecCommandError> { pub fn bcachefs_unlock(dev_name: &str, pass: &str) -> Result<(), ExecCommandError> {
// bcachefs unlock --file=/tmp/bzzpsspass.txt /dev/loop0 // bcachefs unlock --file=/tmp/bzzpsspass.txt /dev/loop0
let arg = vec!["unlock", "--file=/tmp/bzzpsspass.txt ", dev_name]; let arg = vec!["unlock", "--file=/tmp/bzzpsspass.txt ", dev_name];
// creating tmp file with password // creating tmp file with password
fs::write("/tmp/bzzpsspass.txt", &pass)?; fs::write("/tmp/bzzpsspass.txt", &pass)?;
let out = exec_command("bcachefs", &arg); let out = exec_command("bcachefs", &arg);
// ignore any errors while deleting pass tmp file // ignore any errors while deleting pass tmp file
let _ = fs::remove_file("/tmp/bzzpsspass.txt"); let _ = fs::remove_file("/tmp/bzzpsspass.txt");
@@ -281,6 +418,15 @@ pub fn bcachefs_mount(dev_name: &str, mount_point: &str) -> Result<(), ExecComma
exec_command("mount", &vec!["-t", "bcachefs", dev_name, mount_point]) exec_command("mount", &vec!["-t", "bcachefs", dev_name, mount_point])
} }
pub fn mount_fs(dev_name: &str, mount_point: &str) -> Result<(), ExecCommandError> {
// sudo mount -t bcachefs /dev/loop0 /mnt/test
exec_command("mount", &vec![dev_name, mount_point])
}
pub fn swapon(dev_name: &str) -> Result<(), ExecCommandError> {
exec_command("swapon", &vec![dev_name])
}
pub fn fatlabel(dev: &str, label: &str) -> Result<(), ExecCommandError> { pub fn fatlabel(dev: &str, label: &str) -> Result<(), ExecCommandError> {
//fatlabel /dev/sda1 ESP //fatlabel /dev/sda1 ESP
exec_command("fatlabel", &vec![dev, label]) exec_command("fatlabel", &vec![dev, label])
@@ -292,10 +438,10 @@ pub fn mkfs_fat32(dev: &str, maybe_label: Option<&str>) -> Result<(), ExecComman
// if need to set label // if need to set label
if let Some(label) = maybe_label { if let Some(label) = maybe_label {
fatlabel(dev, label) fatlabel(dev, label)
} else { } else {
Ok(()) Ok(())
} }
} }
/// mkfs.fat -F 32 /dev/sda1 /// mkfs.fat -F 32 /dev/sda1
@@ -304,8 +450,113 @@ pub fn mkfs_esp(dev: &str) -> Result<(), ExecCommandError> {
mkfs_fat32(dev, Some("ESP")) mkfs_fat32(dev, Some("ESP"))
} }
pub fn mkswap(dev: &str) -> Result<(), ExecCommandError> { pub fn mkswap(dev: &str) -> Result<(), ExecCommandError> {
//mkswap -L SWAP /dev/sda4 //mkswap -L SWAP /dev/sda4
exec_command("mkswap", &vec!["L", "SWAP", dev]) exec_command("mkswap", &vec!["-L", "bee-swap", dev])
} }
///
/// Returns list of files in directory and all subdirectories.
/// Files in subdirectories listed with path related to specified dir.
/// For example subdir1/subdir2/file.
/// Function do not traverse symlinks and ignores them in output.
///
pub fn ls_dir_rec(dir_part: &Path) -> Result<Vec<String>, std::io::Error> {
///
/// root_path should point to dir
///
fn ls_subdir_rec(
root_path: &Path,
prefix: String,
mut res: Vec<String>,
) -> Result<Vec<String>, std::io::Error> {
for dir_entry in fs::read_dir(root_path)? {
let dir_entry = dir_entry?;
let dir_entry_ft = dir_entry.file_type()?;
let next_prefix = format!("{}/{}", prefix, dir_entry.file_name().to_string_lossy());
if dir_entry_ft.is_dir() {
res = ls_subdir_rec(&dir_entry.path(), next_prefix, res)?;
} else if dir_entry_ft.is_file() {
res.push(next_prefix);
}
}
Ok(res)
}
let mut res: Vec<String> = Vec::new();
//let loc_path: &Path = Path::new("/usr/share/zoneinfo");
if dir_part.is_dir() {
for d_entry in fs::read_dir(dir_part)? {
let d_entry = d_entry?;
let d_entry_ft = d_entry.file_type()?;
let d_entry_name = d_entry.file_name().to_string_lossy().to_string();
if d_entry_ft.is_dir() {
res = ls_subdir_rec(&d_entry.path(), d_entry_name, res)?;
} else if d_entry_ft.is_file() {
// Add file to list
res.push(d_entry_name);
}
}
}
Ok(res)
}
///
/// Generates fstab file similar to
/// fstabgen -t PARTLABEL mnt_dir >> mnt_dir/etc/fstab
///
pub fn fstabgen(mnt_dir: &str) -> Result<(), ExecCommandError> {
let fstab_file_name = format!("{}/etc/fstab", mnt_dir);
let fstab = exec_command_out("fstabgen", &vec!["-t", "PARTLABEL", mnt_dir])?;
fs::write(&fstab_file_name, fstab)?;
Ok(())
}
///
/// Executes passwd --stdin --root chroot_dir root
/// To set new root password in specified chroot env
///
pub fn set_root_passwd(chroot_dir: &str, root_passwd: &str) -> Result<(), ExecCommandError> {
exec_command_stdin(
"passwd",
&vec!["--stdin", "--root", chroot_dir, "root"],
root_passwd,
)
}
// /
// / Sends Dbus message locale1 to change input method
// / SetX11Keyboard(layout: s, model: s, variant: s, options: s, convert: b, interactive: b)
// /
// pub async fn set_input_method(
// layout: &str,
// model: &str,
// variant: &str,
// options: &str,
// ) -> zbus::Result<()> {
// use zbus::Connection;
// let conn = Connection::system().await?;
// log::info!("Sending dbus message to change layout");
// log::info!(
// "layout: {}, model: {}, variant: {}, options: {}",
// layout,
// model,
// variant,
// options
// );
// let resp = conn
// .call_method(
// Some("org.freedesktop.locale1"),
// "/org/freedesktop/locale1",
// Some("org.freedesktop.locale1"),
// "SetX11Keyboard",
// &(layout, model, variant, options, true, false),
// )
// .await?;
// log::info!("Dbus response: {}", resp.to_string());
// Ok(())
// }
+189
View File
@@ -0,0 +1,189 @@
//! Track the cursor of a text input.
use crate::kira_text_input::Value;
/// The cursor of a text input.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Cursor {
state: State,
}
/// The state of a [`Cursor`].
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum State {
/// Cursor without a selection
Index(usize),
/// Cursor selecting a range of text
Selection {
/// The start of the selection
start: usize,
/// The end of the selection
end: usize,
},
}
impl Default for Cursor {
fn default() -> Self {
Cursor {
state: State::Index(0),
}
}
}
impl Cursor {
/// Returns the [`State`] of the [`Cursor`].
pub fn state(&self, value: &Value) -> State {
match self.state {
State::Index(index) => State::Index(index.min(value.len())),
State::Selection { start, end } => {
let start = start.min(value.len());
let end = end.min(value.len());
if start == end {
State::Index(start)
} else {
State::Selection { start, end }
}
}
}
}
/// Returns the current selection of the [`Cursor`] for the given [`Value`].
///
/// `start` is guaranteed to be <= than `end`.
pub fn selection(&self, value: &Value) -> Option<(usize, usize)> {
match self.state(value) {
State::Selection { start, end } => {
Some((start.min(end), start.max(end)))
}
State::Index(_) => None,
}
}
pub(crate) fn move_to(&mut self, position: usize) {
self.state = State::Index(position);
}
pub(crate) fn move_right(&mut self, value: &Value) {
self.move_right_by_amount(value, 1);
}
pub(crate) fn move_right_by_words(&mut self, value: &Value) {
self.move_to(value.next_end_of_word(self.right(value)));
}
pub(crate) fn move_right_by_amount(
&mut self,
value: &Value,
amount: usize,
) {
match self.state(value) {
State::Index(index) => {
self.move_to(index.saturating_add(amount).min(value.len()));
}
State::Selection { start, end } => self.move_to(end.max(start)),
}
}
pub(crate) fn move_left(&mut self, value: &Value) {
match self.state(value) {
State::Index(index) if index > 0 => self.move_to(index - 1),
State::Selection { start, end } => self.move_to(start.min(end)),
State::Index(_) => self.move_to(0),
}
}
pub(crate) fn move_left_by_words(&mut self, value: &Value) {
self.move_to(value.previous_start_of_word(self.left(value)));
}
pub(crate) fn select_range(&mut self, start: usize, end: usize) {
if start == end {
self.state = State::Index(start);
} else {
self.state = State::Selection { start, end };
}
}
pub(crate) fn select_left(&mut self, value: &Value) {
match self.state(value) {
State::Index(index) if index > 0 => {
self.select_range(index, index - 1);
}
State::Selection { start, end } if end > 0 => {
self.select_range(start, end - 1);
}
_ => {}
}
}
pub(crate) fn select_right(&mut self, value: &Value) {
match self.state(value) {
State::Index(index) if index < value.len() => {
self.select_range(index, index + 1);
}
State::Selection { start, end } if end < value.len() => {
self.select_range(start, end + 1);
}
_ => {}
}
}
pub(crate) fn select_left_by_words(&mut self, value: &Value) {
match self.state(value) {
State::Index(index) => {
self.select_range(index, value.previous_start_of_word(index));
}
State::Selection { start, end } => {
self.select_range(start, value.previous_start_of_word(end));
}
}
}
pub(crate) fn select_right_by_words(&mut self, value: &Value) {
match self.state(value) {
State::Index(index) => {
self.select_range(index, value.next_end_of_word(index));
}
State::Selection { start, end } => {
self.select_range(start, value.next_end_of_word(end));
}
}
}
pub(crate) fn select_all(&mut self, value: &Value) {
self.select_range(0, value.len());
}
pub(crate) fn start(&self, value: &Value) -> usize {
let start = match self.state {
State::Index(index) => index,
State::Selection { start, .. } => start,
};
start.min(value.len())
}
pub(crate) fn end(&self, value: &Value) -> usize {
let end = match self.state {
State::Index(index) => index,
State::Selection { end, .. } => end,
};
end.min(value.len())
}
fn left(&self, value: &Value) -> usize {
match self.state(value) {
State::Index(index) => index,
State::Selection { start, end } => start.min(end),
}
}
fn right(&self, value: &Value) -> usize {
match self.state(value) {
State::Index(index) => index,
State::Selection { start, end } => start.max(end),
}
}
}
+70
View File
@@ -0,0 +1,70 @@
use crate::kira_text_input::{Cursor, Value};
pub struct Editor<'a> {
value: &'a mut Value,
cursor: &'a mut Cursor,
}
impl<'a> Editor<'a> {
pub fn new(value: &'a mut Value, cursor: &'a mut Cursor) -> Editor<'a> {
Editor { value, cursor }
}
pub fn contents(&self) -> String {
self.value.to_string()
}
pub fn insert(&mut self, character: char) {
if let Some((left, right)) = self.cursor.selection(self.value) {
self.cursor.move_left(self.value);
self.value.remove_many(left, right);
}
self.value.insert(self.cursor.end(self.value), character);
self.cursor.move_right(self.value);
}
pub fn paste(&mut self, content: Value) {
let length = content.len();
if let Some((left, right)) = self.cursor.selection(self.value) {
self.cursor.move_left(self.value);
self.value.remove_many(left, right);
}
self.value.insert_many(self.cursor.end(self.value), content);
self.cursor.move_right_by_amount(self.value, length);
}
pub fn backspace(&mut self) {
match self.cursor.selection(self.value) {
Some((start, end)) => {
self.cursor.move_left(self.value);
self.value.remove_many(start, end);
}
None => {
let start = self.cursor.start(self.value);
if start > 0 {
self.cursor.move_left(self.value);
self.value.remove(start - 1);
}
}
}
}
pub fn delete(&mut self) {
match self.cursor.selection(self.value) {
Some(_) => {
self.backspace();
}
None => {
let end = self.cursor.end(self.value);
if end < self.value.len() {
self.value.remove(end);
}
}
}
}
}
File diff suppressed because it is too large. Load diff
+136
View File
@@ -0,0 +1,136 @@
use unicode_segmentation::UnicodeSegmentation;
/// The value of a [`TextInput`].
///
/// [`TextInput`]: super::TextInput
// TODO: Reduce allocations, cache results (?)
#[derive(Debug, Clone)]
pub struct Value {
graphemes: Vec<String>,
}
impl Value {
/// Creates a new [`Value`] from a string slice.
pub fn new(string: &str) -> Self {
let graphemes = UnicodeSegmentation::graphemes(string, true)
.map(String::from)
.collect();
Self { graphemes }
}
/// Returns whether the [`Value`] is empty or not.
///
/// A [`Value`] is empty when it contains no graphemes.
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Returns the total amount of graphemes in the [`Value`].
pub fn len(&self) -> usize {
self.graphemes.len()
}
/// Returns the position of the previous start of a word from the given
/// grapheme `index`.
pub fn previous_start_of_word(&self, index: usize) -> usize {
let previous_string =
&self.graphemes[..index.min(self.graphemes.len())].concat();
UnicodeSegmentation::split_word_bound_indices(previous_string as &str)
.filter(|(_, word)| !word.trim_start().is_empty())
.next_back()
.map(|(i, previous_word)| {
index
- UnicodeSegmentation::graphemes(previous_word, true)
.count()
- UnicodeSegmentation::graphemes(
&previous_string[i + previous_word.len()..] as &str,
true,
)
.count()
})
.unwrap_or(0)
}
/// Returns the position of the next end of a word from the given grapheme
/// `index`.
pub fn next_end_of_word(&self, index: usize) -> usize {
let next_string = &self.graphemes[index..].concat();
UnicodeSegmentation::split_word_bound_indices(next_string as &str)
.find(|(_, word)| !word.trim_start().is_empty())
.map(|(i, next_word)| {
index
+ UnicodeSegmentation::graphemes(next_word, true).count()
+ UnicodeSegmentation::graphemes(
&next_string[..i] as &str,
true,
)
.count()
})
.unwrap_or(self.len())
}
/// Returns a new [`Value`] containing the graphemes from `start` until the
/// given `end`.
pub fn select(&self, start: usize, end: usize) -> Self {
let graphemes =
self.graphemes[start.min(self.len())..end.min(self.len())].to_vec();
Self { graphemes }
}
/// Returns a new [`Value`] containing the graphemes until the given
/// `index`.
pub fn until(&self, index: usize) -> Self {
let graphemes = self.graphemes[..index.min(self.len())].to_vec();
Self { graphemes }
}
/// Inserts a new `char` at the given grapheme `index`.
pub fn insert(&mut self, index: usize, c: char) {
self.graphemes.insert(index, c.to_string());
self.graphemes =
UnicodeSegmentation::graphemes(&self.to_string() as &str, true)
.map(String::from)
.collect();
}
/// Inserts a bunch of graphemes at the given grapheme `index`.
pub fn insert_many(&mut self, index: usize, mut value: Value) {
let _ = self
.graphemes
.splice(index..index, value.graphemes.drain(..));
}
/// Removes the grapheme at the given `index`.
pub fn remove(&mut self, index: usize) {
let _ = self.graphemes.remove(index);
}
/// Removes the graphemes from `start` to `end`.
pub fn remove_many(&mut self, start: usize, end: usize) {
let _ = self.graphemes.splice(start..end, std::iter::empty());
}
/// Returns a new [`Value`] with all its graphemes replaced with the
/// dot ('•') character.
pub fn secure(&self) -> Self {
Self {
graphemes: std::iter::repeat_n(
String::from("•"),
self.graphemes.len(),
)
.collect(),
}
}
}
impl std::fmt::Display for Value {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.graphemes.concat())
}
}
+209
View File
@@ -0,0 +1,209 @@
// We need this file because wayland broke Linux desktop.
use iced::keyboard::key::{Code, NativeCode, Physical};
const XKB_OFFSET: u32 = 8;
///
/// Converts iced key::Physical to xkb numeric keycode
///
pub fn physical_to_xkb_keycode(physical: &Physical) -> Option<u32> {
match physical {
Physical::Unidentified(NativeCode::Xkb(code)) => Some(code.clone()),
Physical::Unidentified(_) => None,
Physical::Code(code) => code_to_xkb(code),
}
}
///
/// Converts iced key::Code to xkb numeric keycode
///
pub fn code_to_xkb(code: &Code) -> Option<u32> {
let evdev: u32 = match code {
// Alphanumeric & main typing block
Code::Backquote => 41,
Code::Backslash => 43,
Code::BracketLeft => 26,
Code::BracketRight => 27,
Code::Comma => 51,
Code::Digit0 => 11,
Code::Digit1 => 2,
Code::Digit2 => 3,
Code::Digit3 => 4,
Code::Digit4 => 5,
Code::Digit5 => 6,
Code::Digit6 => 7,
Code::Digit7 => 8,
Code::Digit8 => 9,
Code::Digit9 => 10,
Code::Equal => 13,
Code::IntlBackslash => 86, // KEY_102ND
Code::IntlRo => 89, // KEY_RO
Code::IntlYen => 124, // KEY_YEN
Code::KeyA => 30,
Code::KeyB => 48,
Code::KeyC => 46,
Code::KeyD => 32,
Code::KeyE => 18,
Code::KeyF => 33,
Code::KeyG => 34,
Code::KeyH => 35,
Code::KeyI => 23,
Code::KeyJ => 36,
Code::KeyK => 37,
Code::KeyL => 38,
Code::KeyM => 50,
Code::KeyN => 49,
Code::KeyO => 24,
Code::KeyP => 25,
Code::KeyQ => 16,
Code::KeyR => 19,
Code::KeyS => 31,
Code::KeyT => 20,
Code::KeyU => 22,
Code::KeyV => 47,
Code::KeyW => 17,
Code::KeyX => 45,
Code::KeyY => 21,
Code::KeyZ => 44,
Code::Minus => 12,
Code::Period => 52,
Code::Quote => 40,
Code::Semicolon => 39,
Code::Slash => 53,
// Modifiers, whitespace & editing
Code::AltLeft => 56,
Code::AltRight => 100,
Code::Backspace => 14,
Code::CapsLock => 58,
Code::ContextMenu => 139, // KEY_MENU
Code::ControlLeft => 29,
Code::ControlRight => 97,
Code::Enter => 28,
Code::SuperLeft => 125, // KEY_LEFTMETA
Code::SuperRight => 126, // KEY_RIGHTMETA
Code::ShiftLeft => 42,
Code::ShiftRight => 54,
Code::Space => 57,
Code::Tab => 15,
// CJK / IME keys
Code::Convert => 92, // KEY_HENKAN
Code::KanaMode => 93, // KEY_KATAKANAHIRAGANA
Code::Lang1 => 122, // KEY_HANGEUL / KEY_HANGUEL
Code::Lang2 => 123, // KEY_HANJA
Code::Lang3 => 90, // KEY_KATAKANA
Code::Lang4 => 91, // KEY_HIRAGANA
Code::Lang5 => 93, // KEY_KATAKANAHIRAGANA
Code::NonConvert => 94, // KEY_MUHENKAN
Code::Hiragana => 91, // KEY_HIRAGANA
Code::Katakana => 90, // KEY_KATAKANA
// Navigation & cluster
Code::Delete => 111,
Code::End => 107,
Code::Help => 138, // KEY_HELP
Code::Home => 102,
Code::Insert => 110,
Code::PageDown => 109,
Code::PageUp => 104,
Code::ArrowDown => 108,
Code::ArrowLeft => 105,
Code::ArrowRight => 106,
Code::ArrowUp => 103,
// Numpad
Code::NumLock => 69,
Code::Numpad0 => 82,
Code::Numpad1 => 79,
Code::Numpad2 => 80,
Code::Numpad3 => 81,
Code::Numpad4 => 75,
Code::Numpad5 => 76,
Code::Numpad6 => 77,
Code::Numpad7 => 71,
Code::Numpad8 => 72,
Code::Numpad9 => 73,
Code::NumpadAdd => 78,
Code::NumpadComma => 121, // KEY_KPCOMMA
Code::NumpadDecimal => 83,
Code::NumpadDivide => 98,
Code::NumpadEnter => 96,
Code::NumpadEqual => 117, // KEY_KPEQUAL
Code::NumpadMultiply => 55,
Code::NumpadParenLeft => 179, // KEY_KPLEFTPAREN
Code::NumpadParenRight => 180, // KEY_KPRIGHTPAREN
Code::NumpadSubtract => 74,
// System, lock & media keys
Code::Escape => 1,
Code::PrintScreen => 99,
Code::ScrollLock => 70,
Code::Pause => 119,
Code::BrowserBack => 158, // KEY_BACK
Code::BrowserFavorites => 156, // KEY_BOOKMARKS
Code::BrowserForward => 159, // KEY_FORWARD
Code::BrowserHome => 172, // KEY_HOMEPAGE
Code::BrowserRefresh => 173, // KEY_REFRESH
Code::BrowserSearch => 217, // KEY_SEARCH
Code::BrowserStop => 128, // KEY_STOP
Code::Eject => 161, // KEY_EJECTCD
Code::LaunchApp1 => 157, // KEY_COMPUTER
Code::LaunchApp2 => 140, // KEY_CALC
Code::LaunchMail => 155, // KEY_MAIL
Code::MediaPlayPause => 164, // KEY_PLAYPAUSE
Code::MediaSelect => 179, // varies by device; None is safer if ambiguous
Code::MediaStop => 166, // KEY_STOPCD
Code::MediaTrackNext => 163, // KEY_NEXTSONG
Code::MediaTrackPrevious => 165, // KEY_PREVIOUSSONG
Code::Power => 116, // KEY_POWER
Code::Sleep => 142, // KEY_SLEEP
Code::AudioVolumeDown => 114, // KEY_VOLUMEDOWN
Code::AudioVolumeMute => 113, // KEY_MUTE
Code::AudioVolumeUp => 115, // KEY_VOLUMEUP
Code::WakeUp => 143, // KEY_WAKEUP
Code::Suspend => 205, // KEY_SUSPEND
Code::Again => 129, // KEY_AGAIN
Code::Copy => 133, // KEY_COPY
Code::Cut => 137, // KEY_CUT
Code::Find => 136, // KEY_FIND
Code::Open => 134, // KEY_OPEN
Code::Paste => 135, // KEY_PASTE
Code::Props => 130, // KEY_PROPS
Code::Select => 353, // KEY_SELECT (0x161)
Code::Undo => 131, // KEY_UNDO
// Function keys F1–F35
Code::F1 => 59,
Code::F2 => 60,
Code::F3 => 61,
Code::F4 => 62,
Code::F5 => 63,
Code::F6 => 64,
Code::F7 => 65,
Code::F8 => 66,
Code::F9 => 67,
Code::F10 => 68,
Code::F11 => 87,
Code::F12 => 88,
Code::F13 => 183, // KEY_F13
Code::F14 => 184, // KEY_F14
Code::F15 => 185, // KEY_F15
Code::F16 => 186, // KEY_F16
Code::F17 => 187,
Code::F18 => 188,
Code::F19 => 189,
Code::F20 => 190,
Code::F21 => 191,
Code::F22 => 192,
Code::F23 => 193,
Code::F24 => 194, // KEY_F24
// Catch-all in case your `iced_core::keyboard::key::Code` has additional variants
_ => return None,
};
Some(evdev + XKB_OFFSET)
}
+29 -14
View File
@@ -35,14 +35,19 @@ use crate::stages::welcome::WelcomeStage;
rust_i18n::i18n!("src/locales", fallback = "en"); 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_system; 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;
mod kira_sysinfo; mod kira_sysinfo;
mod kira_system;
mod kira_text_input;
mod kira_theming; mod kira_theming;
mod kira_xkb;
mod stage; mod stage;
mod stages; mod stages;
mod tz_to_cc;
enum Views { enum Views {
Start, Start,
@@ -96,7 +101,7 @@ impl KiraState {
( (
Self { Self {
current_view: Views::Start, current_view: Views::Start,
k_config: KiraConfig ::default(), k_config: KiraConfig::default(),
stages_save: Vec::new(), stages_save: Vec::new(),
}, },
Task::done(Message::Start), Task::done(Message::Start),
@@ -122,10 +127,10 @@ fn view(k_state: &KiraState) -> Element<'_, Message> {
fn update(k_state: &mut KiraState, message: Message) -> Task<Message> { fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
match message { match message {
Message::Start => { Message::Start => {
log::info!("Starting!"); log::info!("Starting!");
k_state.current_view = Views::Welcome(WelcomeStage::new(k_state.k_config.clone())); k_state.current_view = Views::Welcome(WelcomeStage::new(k_state.k_config.clone()));
Task::none() Task::none()
}, }
Message::Welcome(wlc_msg) => { Message::Welcome(wlc_msg) => {
if let Views::Welcome(wlc_view) = &mut k_state.current_view { if let Views::Welcome(wlc_view) = &mut k_state.current_view {
match wlc_view.update(wlc_msg) { match wlc_view.update(wlc_msg) {
@@ -163,7 +168,7 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
k_state.current_view = k_state.stages_save.pop().unwrap(); k_state.current_view = k_state.stages_save.pop().unwrap();
Task::none() Task::none()
} }
StageAction::None => Task::none(), _ => Task::none(),
} }
} else { } else {
Task::none() Task::none()
@@ -179,7 +184,9 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
k_state.k_config = network_res; k_state.k_config = network_res;
let s_state = std::mem::replace( let s_state = std::mem::replace(
&mut k_state.current_view, &mut k_state.current_view,
Views::TimeZone(stages::timezone::TimeZoneStage::new(k_state.k_config.clone())), Views::TimeZone(stages::timezone::TimeZoneStage::new(
k_state.k_config.clone(),
)),
); );
k_state.stages_save.push(s_state); k_state.stages_save.push(s_state);
Task::none() Task::none()
@@ -203,7 +210,9 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
k_state.k_config = tz_res; k_state.k_config = tz_res;
let s_state = std::mem::replace( let s_state = std::mem::replace(
&mut k_state.current_view, &mut k_state.current_view,
Views::Locale(stages::locale::LocaleStage::new(k_state.k_config.clone())), Views::Locale(stages::locale::LocaleStage::new(
k_state.k_config.clone(),
)),
); );
k_state.stages_save.push(s_state); k_state.stages_save.push(s_state);
Task::none() Task::none()
@@ -213,7 +222,7 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
k_state.current_view = k_state.stages_save.pop().unwrap(); k_state.current_view = k_state.stages_save.pop().unwrap();
Task::none() Task::none()
} }
StageAction::None => Task::none(), _ => Task::none(),
} }
} else { } else {
Task::none() Task::none()
@@ -226,7 +235,9 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
k_state.k_config = locale_res; k_state.k_config = locale_res;
let s_state = std::mem::replace( let s_state = std::mem::replace(
&mut k_state.current_view, &mut k_state.current_view,
Views::Keyboard(stages::keyboard::KeyboardStage::new(k_state.k_config.clone())), Views::Keyboard(stages::keyboard::KeyboardStage::new(
k_state.k_config.clone(),
)),
); );
k_state.stages_save.push(s_state); k_state.stages_save.push(s_state);
Task::none() Task::none()
@@ -245,9 +256,9 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
if let Views::Keyboard(keyboard_view) = &mut k_state.current_view { if let Views::Keyboard(keyboard_view) = &mut k_state.current_view {
match keyboard_view.update(keyboard_msg) { match keyboard_view.update(keyboard_msg) {
StageAction::Next(keyboard_res) => { StageAction::Next(keyboard_res) => {
k_state.k_config = keyboard_res;
match stages::partition::PartitionStage::new(k_state.k_config.clone()) { match stages::partition::PartitionStage::new(k_state.k_config.clone()) {
Ok(part_stage) => { Ok(part_stage) => {
k_state.k_config = keyboard_res;
let s_state = std::mem::replace( let s_state = std::mem::replace(
&mut k_state.current_view, &mut k_state.current_view,
Views::Partition(part_stage), Views::Partition(part_stage),
@@ -277,7 +288,9 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
k_state.k_config = partition_res; k_state.k_config = partition_res;
let s_state = std::mem::replace( let s_state = std::mem::replace(
&mut k_state.current_view, &mut k_state.current_view,
Views::Security(stages::security::SecurityStage::new(k_state.k_config.clone())), Views::Security(stages::security::SecurityStage::new(
k_state.k_config.clone(),
)),
); );
k_state.stages_save.push(s_state); k_state.stages_save.push(s_state);
Task::none() Task::none()
@@ -299,7 +312,9 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
k_state.k_config = security_res; k_state.k_config = security_res;
let s_state = std::mem::replace( let s_state = std::mem::replace(
&mut k_state.current_view, &mut k_state.current_view,
Views::Install(stages::install::InstallStage::new(k_state.k_config.clone())), Views::Install(stages::install::InstallStage::new(
k_state.k_config.clone(),
)),
); );
k_state.stages_save.push(s_state); k_state.stages_save.push(s_state);
Task::none() Task::none()
Binary file not shown.

Before

Width:  |  Height:  |  Size: 251 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 56 KiB

After

Width:  |  Height:  |  Size: 9.1 KiB

+4 -116
View File
@@ -18,105 +18,8 @@
This file contains basic enums and structs to be used with stages. This file contains basic enums and structs to be used with stages.
*/ */
use iced::wgpu::naga::compact::KeepUnused::No;
use crate::stages; use crate::stages;
use iced::Task;
// #[derive(Debug, Clone)]
// pub enum StageResult {
// WelcomeStageResult(stages::welcome::WelcomeStageResult),
// NetworkStageResult(stages::network::NetworkStageResult),
// LocaleStageResult(stages::locale::LocaleStageResult),
// TimeZoneStageResult(stages::timezone::TimeZoneStageResult),
// KeyboardStageResult(stages::keyboard::KeyboardStageResult),
// SecurityStageResult(stages::security::SecurityStageResult),
// PartitionStageResult(stages::partition::PartitionStageResult),
// None,
// }
// impl StageResult {
// pub fn name(&self) -> String {
// match self {
// Self::LocaleStageResult(_) => "locale".into(),
// Self::WelcomeStageResult(_) => "welcome".into(),
// Self::NetworkStageResult(_) => "network".into(),
// Self::TimeZoneStageResult(_) => "timezone".into(),
// Self::KeyboardStageResult(_) => "keyboard".into(),
// Self::PartitionStageResult(_) => "partition".into(),
// Self::SecurityStageResult(_) => "security".into(),
// Self::None => "none".into(),
// }
// }
// }
// impl StageResult {
// pub fn new(name: &str) -> Self {
// Self {
// name: name.into(),
// config: None,
// error: None,
// }
// }
// pub fn add_error(mut self, ex: String) -> Self {
// self.error = Some(ex);
// self
// }
// pub fn add_val(mut self, val_name: &str, conf_val: ConfigValue) -> Self {
// match &mut self.config {
// Some(c) => {
// c.insert(val_name.into(), conf_val);
// }
// None => {
// self.config = Some(HashMap::from([(val_name.into(), conf_val)]));
// }
// }
// self
// }
// pub fn add_val_string(self, val_name: &str, v: String) -> Self {
// self.add_val(val_name, ConfigValue::String(v))
// }
// pub fn add_val_bool(self, val_name: &str, v: bool) -> Self {
// self.add_val(val_name, ConfigValue::Bool(v))
// }
// pub fn add_val_u64(self, val_name: &str, v: u64) -> Self {
// self.add_val(val_name, ConfigValue::U64(v))
// }
// pub fn get_val(&self, val_name: &str) -> Option<ConfigValue> {
// let v = self
// .config
// .as_ref()
// .and_then(|hm| hm.get(val_name).cloned());
// return v;
// }
// pub fn get_val_str(&self, val_name: &str) -> Option<String> {
// match self.get_val(val_name) {
// Some(ConfigValue::String(v)) => Some(v),
// _ => None,
// }
// }
// pub fn get_val_bool(&self, val_name: &str) -> Option<bool> {
// match self.get_val(val_name) {
// Some(ConfigValue::Bool(v)) => Some(v),
// _ => None,
// }
// }
// pub fn get_val_part_layout(&self, val_name: &str) -> Option<PartLayout> {
// match self.get_val(val_name) {
// Some(ConfigValue::PartLayout(v)) => Some(v),
// _ => None,
// }
// }
// }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct KiraConfig { pub struct KiraConfig {
@@ -128,7 +31,7 @@ pub struct KiraConfig {
pub res_keyboard: Option<stages::keyboard::KeyboardStageResult>, pub res_keyboard: Option<stages::keyboard::KeyboardStageResult>,
pub res_partition: Option<stages::partition::PartitionStageResult>, pub res_partition: Option<stages::partition::PartitionStageResult>,
pub res_security: Option<stages::security::SecurityStageResult>, pub res_security: Option<stages::security::SecurityStageResult>,
pub res_install: bool, pub res_install: Option<stages::install::InstallStageResult>,
} }
impl Default for KiraConfig { impl Default for KiraConfig {
@@ -142,27 +45,12 @@ impl Default for KiraConfig {
res_keyboard: None, res_keyboard: None,
res_partition: None, res_partition: None,
res_security: None, res_security: None,
res_install: false, res_install: None,
} }
} }
} }
// impl KiraConfig { #[derive(Debug)]
// pub fn get_stage(&self, name: &str) -> Option<StageResult> {
// self.config_trail
// .iter()
// .find(|v| v.name() == name)
// .and_then(|v| Some(v.clone()))
// }
// pub fn pop_last(&mut self) -> Option<StageResult> {
// self.config_trail.pop()
// }
// pub fn push(&mut self, stage_result: StageResult) {
// self.config_trail.push(stage_result);
// }
// }
#[derive(Debug, Clone)]
pub enum StageAction { pub enum StageAction {
Back, Back,
None, None,
+420 -86
View File
@@ -18,8 +18,10 @@
Actual installation script. Actual installation script.
*/ */
use std::{fs, path::Path};
use crate::{ use crate::{
kira_disk_layout::{self, BlkDev, FSType, PartLayout, PartRole}, kira_disk_layout::{self, BlkDev, FSType, PartInfo, PartLayout, PartRole},
kira_size::KiraSize, kira_size::KiraSize,
kira_system::{self, ExecCommandError}, kira_system::{self, ExecCommandError},
kira_theming, kira_theming,
@@ -36,10 +38,123 @@ use iced::{Color, Length, futures::channel::mpsc::Sender, widget::container};
use log; use log;
use rust_i18n::t; use rust_i18n::t;
const EFI_BOOT_MOUNT_POINT: &str = "/beefi"; const EFI_BOOT_MOUNT_POINT: &str = "/mnt/inst_root/beefi";
const MNT_DIR: &str = "/mnt/inst_root";
const ROOT_PARTLABEL_DEV: &str = "/dev/disk/by-partlabel/bee-root";
const EFI_PARTLABLE_DEV: &str = "/dev/disk/by-partlabel/bee-efi";
const SWAP_PARTLABLE_DEV: &str = "/dev/disk/by-partlabel/bee-swap";
const CONSOLE_FONT: &str = "ter-v24n";
///
/// List of packages for desktop (elogind-dinit no need for headles system)
///
const PKG_LIST_CORE_DESKTOP: [&str; 19] = [
"linux-kira-lts",
"linux-firmware",
"less",
"sudo",
"nano",
"diffutils",
"bcachefs-tools",
"xfsprogs",
"exfatprogs",
"f2fs-tools",
"dosfstools",
"efibootmgr",
"nvme-cli",
"hive-up",
"kira-blk-settings",
"kira-linux-keyring",
"kira-mirrorlist",
"ly",
"ly-dinit",
];
// const PKG_LIST_MORE_DESKTOP: [&str; 11] = [
// "wireless-regdb",
// "wpa_supplicant",
// "wpa_supplicant-dinit",
// "networkmanager",
// "networkmanager-dinit",
// "chrony", //internet time
// "chrony-dinit", //internet time
// "smartmontools",
// "cryptsetup",
// "btop",
// "fish",
// ];
// const PKG_LIST_SOUND_DESKTOP: [&str; 8] = [
// "pipewire",
// "pipewire-dinit",
// "pipewire-alsa",
// "pipewire-audio",
// "pipewire-jack",
// "pipewire-pulse",
// "wireplumber",
// "wireplumber-dinit",
// ];
// const PKG_LIST_MEDIA_DESKTOP: [&str; 4] = ["ffmpeg", "ffmpeg4.4", "strawberry", "mpv"];
const PKG_LIST_KDE_DESKTOP: [&str; 45] = [
"wireless-regdb",
"wpa_supplicant",
"wpa_supplicant-dinit",
"networkmanager", //networkmanager
"networkmanager-dinit",
"chrony", //internet time
"chrony-dinit", //internet time
"smartmontools",
"cryptsetup",
"btop",
"fish",
"pipewire", //sound
"pipewire-dinit",
"pipewire-alsa",
"pipewire-audio",
"pipewire-jack",
"pipewire-pulse",
"wireplumber",
"wireplumber-dinit",
"mesa",
"libva",
"libva-utils",
"power-profiles-daemon",
"power-profiles-daemon-dinit",
"plasma-desktop",
"plasma-workspace",
"xdg-desktop-portal-kde",
"kwallet-pam",
"kwayland-integration",
"libappindicator",
"okular",
"partitionmanager",
"plasma-browser-integration",
"plasma-desktop",
"plasma-disks",
"plasma-keyboard",
"plasma-nm",
"plasma-pa",
"plasma-systemmonitor",
"plasma-workspace",
"ffmpeg",
"ffmpeg4.4",
"strawberry",
"mpv",
"ttf-unifont",
];
// const PKG_LIST_AWESOME_DESKTOP: [&str; 5] = [
// "mesa",
// "libva",
// "libva-utils",
// "awesome",
// "wiremix", // pipewire sound control
// ];
/// Creates new GPT table and partitions from PartLayout /// Creates new GPT table and partitions from PartLayout
pub fn create_partitions(part_layout: &PartLayout) -> Result<(), ExecCommandError> { fn create_partitions(part_layout: &PartLayout) -> Result<(), ExecCommandError> {
log::info!("Creating GPT part table..."); log::info!("Creating GPT part table...");
kira_system::parted_init_gpt_part_table(&part_layout.dev)?; kira_system::parted_init_gpt_part_table(&part_layout.dev)?;
log::info!("Start to create partitions..."); log::info!("Start to create partitions...");
@@ -55,15 +170,11 @@ pub fn create_partitions(part_layout: &PartLayout) -> Result<(), ExecCommandErro
/// Unlock it if encryption used /// Unlock it if encryption used
/// Mount to specified dir /// Mount to specified dir
/// creates subvolumes bzz/root bzz/home /// creates subvolumes bzz/root bzz/home
pub fn bcachefs_init( fn bcachefs_init(
dev_name: &str, dev_name: &str,
mnt_dir: &str, mnt_dir: &str,
password: Option<String>, password: Option<String>,
comp_alg: Option<String>,
) -> Result<(), ExecCommandError> { ) -> Result<(), ExecCommandError> {
// format device
kira_system::bcachefs_format(dev_name, comp_alg, password.clone())?;
// if encryption used - unlock drive // if encryption used - unlock drive
if let Some(pass) = password { if let Some(pass) = password {
kira_system::bcachefs_unlock(dev_name, pass.as_str())?; kira_system::bcachefs_unlock(dev_name, pass.as_str())?;
@@ -76,9 +187,10 @@ pub fn bcachefs_init(
std::fs::create_dir(format!("{}{}", mnt_dir, "/bzz-snaps"))?; std::fs::create_dir(format!("{}{}", mnt_dir, "/bzz-snaps"))?;
// Creating boot directory for efi mounting // Creating boot directory for efi mounting
std::fs::create_dir_all(format!("{}{}", mnt_dir, EFI_BOOT_MOUNT_POINT))?; std::fs::create_dir_all(EFI_BOOT_MOUNT_POINT)?;
// create subvolumes // create subvolumes
log::info!("Creating subvolumes...");
for vol_name in ["/home", "/usr", "/var", "/var/tmp"] { for vol_name in ["/home", "/usr", "/var", "/var/tmp"] {
let vol_path = format!("{}{}", mnt_dir, vol_name); let vol_path = format!("{}{}", mnt_dir, vol_name);
kira_system::bcachefs_create_subvolume(vol_path.as_str())?; kira_system::bcachefs_create_subvolume(vol_path.as_str())?;
@@ -87,7 +199,14 @@ pub fn bcachefs_init(
Ok(()) Ok(())
} }
pub fn init_disk(part_layout: &PartLayout, mnt_dir: &str) -> Result<(), ExecCommandError> { fn init_disk(part_layout: &PartLayout, mnt_dir: &str) -> Result<(), ExecCommandError> {
let mnt_path = Path::new(mnt_dir);
log::info!("Cheking is MNT path exists: {}", mnt_dir);
if !mnt_path.exists() {
log::info!("MNT path do not exist, creating it...");
std::fs::create_dir_all(mnt_path)?;
}
// use parted to create partition gpt layout // use parted to create partition gpt layout
create_partitions(part_layout)?; create_partitions(part_layout)?;
@@ -96,17 +215,18 @@ pub fn init_disk(part_layout: &PartLayout, mnt_dir: &str) -> Result<(), ExecComm
match part.role { match part.role {
Some(PartRole::EFI) => { Some(PartRole::EFI) => {
if let Some(part_l) = part.partlabel_dev() { if let Some(part_l) = part.partlabel_dev() {
log::info!("Formating EFI partition.");
kira_system::mkfs_esp(&part_l)?; kira_system::mkfs_esp(&part_l)?;
} }
} }
Some(PartRole::ROOT) => { Some(PartRole::ROOT) => {
if let Some(part_l) = part.partlabel_dev() { if let Some(part_l) = part.partlabel_dev() {
if let FSType::BCACHEFS(bc_par) = &part.fs_type { if let FSType::BCACHEFS(bc_par) = &part.fs_type {
bcachefs_init( log::info!("Formating root partition.");
kira_system::bcachefs_format(
&part_l, &part_l,
mnt_dir,
bc_par.password.clone(),
bc_par.comp_alg.clone(), bc_par.comp_alg.clone(),
bc_par.password.clone(),
)?; )?;
} else { } else {
return Err(ExecCommandError::Other( return Err(ExecCommandError::Other(
@@ -117,6 +237,7 @@ pub fn init_disk(part_layout: &PartLayout, mnt_dir: &str) -> Result<(), ExecComm
} }
Some(PartRole::SWAP) => { Some(PartRole::SWAP) => {
if let Some(part_l) = part.partlabel_dev() { if let Some(part_l) = part.partlabel_dev() {
log::info!("Formating SWAP partition.");
kira_system::mkswap(&part_l)?; kira_system::mkswap(&part_l)?;
} }
} }
@@ -127,6 +248,137 @@ pub fn init_disk(part_layout: &PartLayout, mnt_dir: &str) -> Result<(), ExecComm
Ok(()) Ok(())
} }
///
/// Writes locales from loc_lines to locale.gen file passed in loc_gen_file_path
/// Checks if locales from loc_lines defined in locale.gen
///
fn locale_gen_write(
loc_gen_file_path: &str,
loc_lines: &Vec<String>,
) -> Result<(), ExecCommandError> {
use std::fs::OpenOptions;
use std::io::Write;
// need this to check for locales existance
let loc_gen_content = fs::read_to_string(loc_gen_file_path)?;
// Open locale.gen file in append mode
let mut locale_file = OpenOptions::new()
.create(false)
.append(true)
.open(loc_gen_file_path)?;
writeln!(
locale_file,
"\n# Next lines is autogenerated by Kira Installer"
)?;
for loc in loc_lines {
// check if locale defined
if loc_gen_content.contains(loc) {
writeln!(locale_file, "{}", loc)?;
log::info!("Added ({}) locale.", loc);
} else {
// if not defined write comment on this matter
log::info!("Locale ({}) is not defined in locale.gen file.", loc);
writeln!(locale_file, "# Missing: {}", loc)?;
}
}
Ok(())
}
fn config_stuff(k_config: KiraConfig) -> Result<(), ExecCommandError> {
use std::fs::OpenOptions;
use std::io::Write;
let loc_gen_fn = format!("{}/etc/locale.gen", MNT_DIR);
log::info!("Generating fstab...");
kira_system::fstabgen(MNT_DIR)?;
log::info!("Configuring locales...");
{
let loc_data = k_config.res_locale.as_ref().unwrap();
let lang_line = loc_data.lang_locale.locale_gen_line();
let formats_line = loc_data.formats_locale.locale_gen_line();
let mut loc_lines: Vec<String> = Vec::new();
// if selected locale is not en, we will add en_US.UTF-8 UTF-8 to locales.gen
if !lang_line.starts_with("en_") && !formats_line.starts_with("en_") {
loc_lines.push("en_US.UTF-8 UTF-8".into());
}
// write formats locale if it is different from lang locale
if lang_line != formats_line {
loc_lines.push(formats_line);
}
loc_lines.push(lang_line);
locale_gen_write(&loc_gen_fn, &loc_lines)?;
}
// Running locale-gen
kira_system::exec_cmd_chroot(MNT_DIR, "locale-gen", &vec![])?;
log::info!("Konfiguring keyboard...");
log::info!("Kayboard conf: {}", k_config.res_keyboard.as_ref().unwrap());
// dinit reads /etc/vconsole.conf
// but
// config /etc/conf.d/keymaps as a backup
log::info!("Writing /etc/conf.d/keymaps");
let kbd_conf = k_config.res_keyboard.as_ref().unwrap();
let console_keymap = kbd_conf.crazy_bonker_console_keymap();
fs::write(
"/etc/conf.d/keymaps",
format!(
"# Autogeneradet by Kira Installer\nkeymap={}",
console_keymap
),
)?;
log::info!("Writing /etc/vconsole.conf");
let vconsole_content = format!(
"Autogeneradet by Kira Installer \
FONT={} \
KEYMAP={} \
XKBMODEL={} \
XKBLAYOUT={} \
XKBVARIANT={}\n",
CONSOLE_FONT,
&console_keymap,
kbd_conf.xkb_model(),
kbd_conf.xkb_layout(),
kbd_conf.xkb_variant()
);
fs::write("/etc/vconsole.conf", vconsole_content)?;
//kira_system::exec_cmd_chroot(chroot_dir, cmd, args)
//locale-gen
//Configure the system clock
// Set the time zone:
// ln -sf /usr/share/zoneinfo/Region/City /etc/localtime
// Run hwclock to generate /etc/adjtime:
// hwclock --systohc
log::info!("Configuring timezone...");
let time_conf = k_config.res_timezone.as_ref().unwrap();
let tz_file_name = time_conf.time_zone.tz_file_name();
kira_system::exec_cmd_chroot(
MNT_DIR,
"ln",
&vec!["-sf", tz_file_name.as_ref(), "/etc/localtime"],
)?;
// Run hwclock to generate /etc/adjtime:
// hwclock --systohc
kira_system::exec_cmd_chroot(MNT_DIR, "hwclock", &vec!["--systohc"])?;
// set root password
log::info!("Setting root password...");
let sec_conf = k_config.res_security.as_ref().unwrap();
kira_system::set_root_passwd(MNT_DIR, &sec_conf.root_password)?;
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum InstallationState { enum InstallationState {
UserConfirmDialog, UserConfirmDialog,
@@ -135,12 +387,16 @@ enum InstallationState {
Error, Error,
} }
#[derive(Debug, Clone)]
pub struct InstallStageResult {
pub sucess: Result<(), String>,
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct InstallStage { pub struct InstallStage {
state: InstallationState, state: InstallationState,
progress: f32, progress: f32,
progress_message: String, progress_message: String,
part_config: PartitionStageResult,
modal_backgroud: Color, modal_backgroud: Color,
k_config: KiraConfig, k_config: KiraConfig,
} }
@@ -149,7 +405,7 @@ pub struct InstallStage {
pub enum Message { pub enum Message {
UserConfirms, UserConfirms,
UserDenies, UserDenies,
Sucess, Success,
Cancel, Cancel,
Finish, Finish,
UpdateProgress(Result<(f32, String), String>), UpdateProgress(Result<(f32, String), String>),
@@ -162,99 +418,150 @@ pub enum Update {
Task(Task<Message>), Task(Task<Message>),
} }
pub fn mount_and_init_root(
part_layout: &PartLayout,
mnt_dir: &str,
) -> Result<(), ExecCommandError> {
// init root
let root_part = part_layout
.get_part(PartRole::ROOT)
.expect("Root partition must be present!");
log::info!("Mount and init root partition.");
if let FSType::BCACHEFS(bcache_prop) = root_part.fs_type {
bcachefs_init(ROOT_PARTLABEL_DEV, mnt_dir, bcache_prop.password.clone())?;
} else {
return Err(ExecCommandError::Other(format!(
"Unexpected root partition type: {}",
root_part.fs_type
)));
}
log::info!("Mounting EFI partition");
kira_system::mount_fs(EFI_PARTLABLE_DEV, EFI_BOOT_MOUNT_POINT)?;
log::info!("Attaching swap partition");
kira_system::swapon(SWAP_PARTLABLE_DEV)?;
Ok(())
}
async fn init_disk_async(part_layout: PartLayout, mnt_dir: String) -> Result<(), ExecCommandError> { async fn init_disk_async(part_layout: PartLayout, mnt_dir: String) -> Result<(), ExecCommandError> {
use blocking; use blocking;
blocking::unblock(move || init_disk(&part_layout, &mnt_dir)).await blocking::unblock(move || init_disk(&part_layout, &mnt_dir)).await
} }
fn partition_disk( async fn mount_and_init_root_async(
disk_layout: PartLayout, part_layout: PartLayout,
password: Option<String>,
compression: Option<String>,
mnt_dir: String, mnt_dir: String,
) -> impl futures::Stream<Item = Result<(f32, String), ExecCommandError>> { ) -> Result<(), ExecCommandError> {
use blocking; use blocking;
blocking::unblock(move || mount_and_init_root(&part_layout, &mnt_dir)).await
}
async fn install_base_async(mnt_dir: String) -> Result<(), ExecCommandError> {
use blocking;
log::info!("Installing base system...");
blocking::unblock(move || kira_system::basestrap_dinit(&mnt_dir)).await
}
async fn install_core_desk_async(mnt_dir: String) -> Result<(), ExecCommandError> {
use blocking;
log::info!("Installing core desktop packages...");
blocking::unblock(move || kira_system::basestrap(&mnt_dir, &PKG_LIST_CORE_DESKTOP)).await
}
async fn install_kde_desk_async(mnt_dir: String) -> Result<(), ExecCommandError> {
use blocking;
log::info!("Installing KDE desktop packages...");
blocking::unblock(move || kira_system::basestrap(&mnt_dir, &PKG_LIST_KDE_DESKTOP)).await
}
async fn config_stuff_async(k_config: KiraConfig) -> Result<(), ExecCommandError> {
use blocking;
log::info!("Configuring installed system...");
blocking::unblock(move || config_stuff(k_config)).await
}
fn do_install(
k_config: KiraConfig,
) -> impl futures::Stream<Item = Result<(f32, String), ExecCommandError>> {
iced::stream::channel( iced::stream::channel(
100, 100,
|mut output: Sender<Result<(f32, String), ExecCommandError>>| async move { |mut output: Sender<Result<(f32, String), ExecCommandError>>| async move {
//sleep(Duration::from_millis(10)).await; //sleep(Duration::from_millis(10)).await;
let disk_layout_cloned = disk_layout.clone(); let disk_layout = k_config.res_partition.as_ref().unwrap().part_layout.clone();
// creating gpt partition table // creating gpt partition table
let res = init_disk_async(disk_layout_cloned, mnt_dir).await; let res = init_disk_async(disk_layout.clone(), MNT_DIR.into()).await;
let res_err = res.is_err();
output output
.send(res.map(|_| (1.1f32, "Formatting bcachefs".into()))) .send(res.map(|_| (1.1f32, "Formatting bcachefs".into())))
.await .await
.unwrap(); .unwrap();
if res.is_err() {
if res_err {
return; return;
} }
let res = init_disk_async(disk_layout_cloned).await; // Mount and init root
let res = mount_and_init_root_async(disk_layout, MNT_DIR.into()).await;
let res_err = res.is_err();
output output
.send(res.map(|_| (1.1f32, "Formatting bcachefs".into()))) .send(res.map(|_| (5.1f32, "Installing base".into())))
.await .await
.unwrap(); .unwrap();
if res.is_err() {
if res_err {
return; return;
} }
// creating partitions // installing base system
let dev = disk_layout.dev.clone(); let res = install_base_async(MNT_DIR.into()).await;
let part_list = disk_layout.part_list.clone(); let res_err = res.is_err();
match output output
.send( .send(res.map(|_| (10.0f32, "Installing core system".into())))
blocking::unblock(move || {
let mut res = Ok(());
for part in part_list {
match kira_system::parted_mkpart(&dev, &part) {
Ok(_) => (),
Err(ex) => {
res = Err(ex);
break;
}
}
}
res
})
.await
.and(Ok((5.0f32, "Creating partitions".into()))),
)
.await .await
{ .unwrap();
Err(ex) => {
log::error!("Error creating GPT partition table: {}", ex.to_string());
return;
}
_ => (),
};
// creating bcachefs filesystem if res_err {
// /dev/disk/by-partlabel/ return;
let compression_cloned = compression.clone(); }
let password_cloned = password.clone();
match output // installing core system
.send( let res = install_core_desk_async(MNT_DIR.into()).await;
blocking::unblock(move || { let res_err = res.is_err();
bcachefs_init( output
"/dev/disk/by-partlabel/bee-root", .send(res.map(|_| (20.0f32, "Installing KDE desktop envirometn".into())))
compression_cloned,
password_cloned,
"/mnt/bzzpss-install",
)
})
.await
.and(Ok((10.0f32, "Creating partition table".into()))),
)
.await .await
{ .unwrap();
Err(ex) => {
log::error!("Error creating GPT partition table: {}", ex.to_string()); if res_err {
return; return;
} }
_ => (),
}; // installing KDE
let res = install_kde_desk_async(MNT_DIR.into()).await;
let res_err = res.is_err();
output
.send(res.map(|_| (50.0f32, "Configuring system".into())))
.await
.unwrap();
if res_err {
return;
}
// configuring system
let res = config_stuff_async(k_config.clone()).await;
let res_err = res.is_err();
output
.send(res.map(|_| (60.0f32, "Next step".into())))
.await
.unwrap();
if res_err {
return;
}
// Check if send fails (receiver dropped/cancelled) // Check if send fails (receiver dropped/cancelled)
// if output.send(res).await.is_err() { // if output.send(res).await.is_err() {
@@ -267,6 +574,28 @@ fn partition_disk(
) )
} }
fn check_kconfig(k_config: &KiraConfig) -> Result<(), String> {
if k_config.res_welcome.is_none() {
Err("Missing wellcome stage result!".into())
} else if k_config.res_license == false {
Err("License is NOT accepted!".into())
} else if k_config.res_locale.is_none() {
Err("Missing locale stage result!".into())
} else if k_config.res_network.is_none() {
Err("Missing network stage result!".into())
} else if k_config.res_keyboard.is_none() {
Err("Missing keyboard stage result!".into())
} else if k_config.res_timezone.is_none() {
Err("Missing timezone stage result!".into())
} else if k_config.res_partition.is_none() {
Err("Missing partition stage result!".into())
} else if k_config.res_security.is_none() {
Err("Missing security stage result!".into())
} else {
Ok(())
}
}
impl InstallStage { impl InstallStage {
pub fn new(k_config: KiraConfig) -> Self { pub fn new(k_config: KiraConfig) -> Self {
let mut modal_backgroud = kira_theming::main_theme().palette().background; let mut modal_backgroud = kira_theming::main_theme().palette().background;
@@ -276,13 +605,12 @@ impl InstallStage {
state: InstallationState::UserConfirmDialog, state: InstallationState::UserConfirmDialog,
progress: 0.0, progress: 0.0,
progress_message: String::new(), progress_message: String::new(),
part_config: k_config.res_partition.clone().expect("Partition stage result should be present in KiraConfig!"),
k_config: k_config, k_config: k_config,
} }
} }
fn gen_result(&mut self) -> KiraConfig { fn gen_result(&mut self) -> KiraConfig {
self.k_config.res_install = true; self.k_config.res_install = Some(InstallStageResult { sucess: Ok(()) });
self.k_config.clone() self.k_config.clone()
} }
@@ -290,16 +618,22 @@ impl InstallStage {
match message { match message {
Message::UserDenies => Update::StgAct(StageAction::Back), Message::UserDenies => Update::StgAct(StageAction::Back),
Message::UserConfirms => { Message::UserConfirms => {
log::info!("Cheking config...");
match check_kconfig(&self.k_config) {
Ok(()) => log::info!("Config looks good."),
Err(ex) => {
log::error!("{}", ex);
self.state = InstallationState::Error;
return Update::StgAct(StageAction::None);
}
}
// starting installation process here // starting installation process here
log::info!("Starting disk partitioning."); log::info!("Starting disk partitioning.");
self.state = InstallationState::Installing; self.state = InstallationState::Installing;
let disk_layout = self.part_config.part_layout.clone();
let disk_password = self.part_config.password.clone();
let disk_compression = Some("lz4".to_string());
Update::Task(Task::run( Update::Task(Task::run(
partition_disk(disk_layout, disk_password, disk_compression) do_install(self.k_config.clone()).map_err(|ex| ex.to_string()),
.map_err(|ex| ex.to_string()),
Message::UpdateProgress, Message::UpdateProgress,
)) ))
//Update::Task(Task::perform(, Message::PartitioningFinish)) //Update::Task(Task::perform(, Message::PartitioningFinish))
@@ -324,7 +658,7 @@ impl InstallStage {
Update::StgAct(StageAction::Abort) Update::StgAct(StageAction::Abort)
} }
Message::Cancel => Update::StgAct(StageAction::Abort), Message::Cancel => Update::StgAct(StageAction::Abort),
Message::Sucess => Update::StgAct(StageAction::None), Message::Success => Update::StgAct(StageAction::None),
Message::Finish => Update::StgAct(StageAction::None), Message::Finish => Update::StgAct(StageAction::None),
} }
} }
+168 -7
View File
@@ -19,11 +19,14 @@
*/ */
use crate::kira_scroll_list::{self, ListViewMessage}; use crate::kira_scroll_list::{self, ListViewMessage};
use crate::kira_system;
use crate::kira_text_input;
use crate::stage::{KiraConfig, StageAction}; use crate::stage::{KiraConfig, StageAction};
use iced::{Alignment, Length, widget}; use iced::{Alignment, Length, Task, widget};
use log; use log;
use rust_i18n::t; use rust_i18n::t;
use std::collections::HashMap; use std::collections::HashMap;
use xkbcommon::xkb;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layout { pub struct Layout {
@@ -82,6 +85,19 @@ impl KeyboarLayout {
pub fn to_result(&self) -> String { pub fn to_result(&self) -> String {
format!("{}||{}", self.layout.layout, self.variant.variant) format!("{}||{}", self.layout.layout, self.variant.variant)
} }
pub fn xkb_layout(&self) -> String {
self.layout.layout.clone()
}
///
/// Returns string variant or empty string if variant is "default"
///
pub fn xkb_variant(&self) -> String {
if self.variant.variant == "default" {
"".into()
} else {
self.variant.variant.clone()
}
}
} }
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
@@ -102,6 +118,9 @@ impl KeyboarModel {
description: v.1.trim().to_string(), description: v.1.trim().to_string(),
} }
} }
pub fn xkb_model(&self) -> String {
self.model.clone()
}
} }
impl std::fmt::Display for KeyboarLayout { impl std::fmt::Display for KeyboarLayout {
@@ -110,7 +129,7 @@ impl std::fmt::Display for KeyboarLayout {
} }
} }
#[derive(Debug, Clone)] #[derive(Clone)]
pub struct KeyboardStage { pub struct KeyboardStage {
models: Vec<KeyboarModel>, models: Vec<KeyboarModel>,
model: Option<KeyboarModel>, model: Option<KeyboarModel>,
@@ -122,6 +141,8 @@ pub struct KeyboardStage {
keyboard_layout: Option<KeyboarLayout>, keyboard_layout: Option<KeyboarLayout>,
// selected_kbd_layout_id: Option<usize>, // selected_kbd_layout_id: Option<usize>,
k_config: KiraConfig, k_config: KiraConfig,
test_text: String,
xkb_keymap: Option<xkb::Keymap>,
} }
#[derive(Debug, Clone, PartialEq)] #[derive(Debug, Clone, PartialEq)]
@@ -130,11 +151,64 @@ pub struct KeyboardStageResult {
pub keyboard_layout: KeyboarLayout, pub keyboard_layout: KeyboarLayout,
} }
impl KeyboardStageResult {
///
/// doing crazy guess of console keymap
///
pub fn crazy_bonker_console_keymap(&self) -> String {
const LAT_MAP: [&str; 13] = [
"us", "fr", "it", "es", "pt", "pl", "cz", "no", "se", "fi", "dk", "nl", "hu",
];
const DE_MAP: &str = "de-latin1-nodeadkeys";
const DEAFULT_MAP: &str = "us";
let layout = self.keyboard_layout.layout.layout.as_str();
let model = self.keyboard_model.model.as_str();
if layout == "de" {
DE_MAP.to_string()
} else if LAT_MAP.contains(&layout) {
layout.to_string()
}
// if xkb_layout is non-Latin
else if model == "pc105" {
DE_MAP.to_string()
} else {
DEAFULT_MAP.to_string()
}
}
pub fn xkb_model(&self) -> String {
self.keyboard_model.xkb_model()
}
pub fn xkb_layout(&self) -> String {
self.keyboard_layout.xkb_layout()
}
///
/// Returns string variant or empty string if variant is "default"
///
pub fn xkb_variant(&self) -> String {
self.keyboard_layout.xkb_variant()
}
}
impl std::fmt::Display for KeyboardStageResult {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"keyboard_model: {} | keyboard_layout: {}",
&self.keyboard_model, &self.keyboard_layout
)
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Message { pub enum Message {
SelectKeyboardModel(KeyboarModel), SelectKeyboardModel(KeyboarModel),
SelectLayout(kira_scroll_list::ListViewMessage), SelectLayout(kira_scroll_list::ListViewMessage),
SelectVariant(kira_scroll_list::ListViewMessage), SelectVariant(kira_scroll_list::ListViewMessage),
TestTextChange(String),
// AddLayout(usize), // AddLayout(usize),
// RemoveLayout(usize), // RemoveLayout(usize),
@@ -259,6 +333,8 @@ impl KeyboardStage {
variant: Some(0), variant: Some(0),
keyboard_layout: keyboard_layout, keyboard_layout: keyboard_layout,
k_config: k_config, k_config: k_config,
test_text: String::new(),
xkb_keymap: None,
} }
} }
Err(ex) => { Err(ex) => {
@@ -276,11 +352,72 @@ impl KeyboardStage {
variant: None, variant: None,
keyboard_layout: None, keyboard_layout: None,
k_config: k_config, k_config: k_config,
test_text: String::new(),
xkb_keymap: None,
} }
} }
} }
} }
// fn set_input_method(&self) -> Task<Message> {
// log::info!("Preparing task!");
// let (layout, variant) = if let Some(kb_layout) = &self.keyboard_layout {
// (kb_layout.xkb_layout(), kb_layout.xkb_variant())
// } else {
// (String::new(), String::new())
// };
// let model = if let Some(kb_model) = &self.model {
// kb_model.xkb_model()
// } else {
// String::new()
// };
// log::info!("Task perform!");
// Task::perform(
// async move {
// let a = kira_system::set_input_method(&layout, &model, &variant, "").await;
// log::info!("Result: {:?}", a);
// },
// |_| Message::SysLayoutChanged,
// )
// }s
fn gen_keymap(&mut self) -> () {
log::debug!("Generating keyboard keymap!");
let (layout, variant) = if let Some(kb_layout) = &self.keyboard_layout {
(kb_layout.xkb_layout(), kb_layout.xkb_variant())
} else {
(String::new(), String::new())
};
let model = if let Some(kb_model) = &self.model {
kb_model.xkb_model()
} else {
String::new()
};
log::debug!(
"model:{:?}, layout:{:?}, variant:{:?}",
model,
layout,
variant
);
// create context
let ctx = xkb::Context::new(xkb::CONTEXT_NO_FLAGS);
let xkb_keymap = xkb::Keymap::new_from_names(
&ctx,
"evdev",
&model,
&layout,
&variant,
None,
xkb::COMPILE_NO_FLAGS,
);
if xkb_keymap.is_none() {
log::error!("Cannot compile XKB keymap!");
} else {
self.xkb_keymap = xkb_keymap;
}
}
fn gen_result(&mut self) -> KiraConfig { fn gen_result(&mut self) -> KiraConfig {
self.k_config.res_keyboard = Some(KeyboardStageResult { self.k_config.res_keyboard = Some(KeyboardStageResult {
keyboard_model: self.model.clone().expect("Keyboard model must be choosed!"), keyboard_model: self.model.clone().expect("Keyboard model must be choosed!"),
@@ -302,10 +439,15 @@ impl KeyboardStage {
self.variants = self.variants_map[self.layouts[l_id].layout.as_str()].clone(); self.variants = self.variants_map[self.layouts[l_id].layout.as_str()].clone();
self.variant = Some(0); self.variant = Some(0);
let layout = self.layouts[l_id].clone();
let variant = self.variants[0].clone();
self.keyboard_layout = Some(KeyboarLayout { self.keyboard_layout = Some(KeyboarLayout {
layout: self.layouts[l_id].clone(), layout: layout,
variant: self.variants[0].clone(), variant: variant,
}); });
self.gen_keymap();
} }
StageAction::None StageAction::None
} }
@@ -315,10 +457,18 @@ impl KeyboardStage {
layout: self.layouts[self.layout.unwrap()].clone(), layout: self.layouts[self.layout.unwrap()].clone(),
variant: self.variants[v_id].clone(), variant: self.variants[v_id].clone(),
}); });
self.gen_keymap();
StageAction::None StageAction::None
} }
Message::SelectKeyboardModel(k_m) => { Message::SelectKeyboardModel(k_m) => {
self.model = Some(k_m); self.model = Some(k_m);
self.gen_keymap();
StageAction::None
}
Message::TestTextChange(test_text) => {
let mut res: String = test_text;
res.retain(|c: char| !c.is_control());
self.test_text = res;
StageAction::None StageAction::None
} }
Message::Next => StageAction::Next(self.gen_result()), Message::Next => StageAction::Next(self.gen_result()),
@@ -350,7 +500,7 @@ impl KeyboardStage {
crate::kira_scroll_list::list_view( crate::kira_scroll_list::list_view(
&self.layouts, &self.layouts,
self.layout, self.layout,
Length::Shrink Length::Fill
) )
.map(Message::SelectLayout) .map(Message::SelectLayout)
], ],
@@ -359,15 +509,26 @@ impl KeyboardStage {
crate::kira_scroll_list::list_view( crate::kira_scroll_list::list_view(
&self.variants, &self.variants,
self.variant, self.variant,
Length::FillPortion(1) Length::Fill
) )
.map(Message::SelectVariant) .map(Message::SelectVariant)
], ],
] ]
.spacing(10) .spacing(10)
.height(Length::Shrink), .height(Length::Fill),
widget::row![
widget::text("Test Keyboard:"),
//widget::text_input("", &self.test_text).on_input(Message::TestTextChange),
kira_text_input::TextInput::new("", &self.test_text)
.keymap(self.xkb_keymap.clone())
.on_input(Message::TestTextChange),
]
.spacing(2)
.align_y(Alignment::Center)
.width(Length::Fill),
] ]
.spacing(10) .spacing(10)
.height(Length::Fill)
.align_x(Alignment::Center), .align_x(Alignment::Center),
) )
} else { } else {
+9 -134
View File
@@ -24,110 +24,8 @@ use crate::{
}; };
use iced::{Alignment, widget}; use iced::{Alignment, widget};
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};
const LOCALES_GEN_START_LINE: usize = 17;
// fn default_locale() -> (String, String) {
// ("C.UTF-8".to_string(), "UTF-8".to_string())
// }
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LocaleData {
code: String,
description: String,
}
impl std::fmt::Display for LocaleData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", self.code, self.description)
}
}
impl LocaleData {
pub fn default() -> Self {
Self {
code: "C.UTF-8".into(),
description: "C locale".into(),
}
}
}
/// gets locales list from system "/etc/locale.gen" file
/// Filters out non UTF-8 locales
fn get_locales_codes_list_blocking() -> std::io::Result<Vec<(String, String)>> {
use std::fs::File;
use std::io::{BufReader, Read};
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)?;
}
let mut res: Vec<(String, String)> = file_content
.split('\n')
.skip(LOCALES_GEN_START_LINE)
.filter_map(|l| {
let trimmed = l.trim_start_matches('#').trim();
if trimmed.len() > 0 {
trimmed.split_once(' ')
} else {
None
}
})
.map(|(loc, charset)| (loc.to_string(), charset.to_string()))
.filter(|(_, chrs)| chrs == "UTF-8") // yeld only UTF-8 locales
.collect();
res.push(("C.UTF-8".into(), "UTF-8".into()));
Ok(res)
}
/// Gets locales description from "/usr/share/i18n/locales/" directory.
fn get_locales_description_blocking() -> Result<HashMap<String, String>, String> {
use std::process::Command;
match Command::new("grep")
.args(["-r", "title ", "/usr/share/i18n/locales/"])
.output()
{
Ok(cmd_output) => {
if cmd_output.status.success() {
match String::from_utf8(cmd_output.stdout) {
Ok(raw_str_list) => Ok(raw_str_list
.split("\n")
.filter_map(|s| s.trim().split_once(":title"))
.filter_map(|(code_part, description_part)| {
code_part.rsplit_once("/").and_then(|(_, loc_code)| {
Some((
loc_code.trim().to_string(),
description_part.trim().trim_matches('\"').to_string(),
))
})
})
.collect()),
Err(ex) => Err(format!(
"Exception while converting locales description to UTF8 {}",
ex
)),
}
} else {
Err(format!(
"Error getting locales description list: {}",
String::from_utf8(cmd_output.stderr).unwrap_or("UNKNOWN".into())
))
}
}
Err(ex) => Err(format!(
"Exception while trying to get locales description {}",
ex
)),
}
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct LocaleStage { pub struct LocaleStage {
@@ -161,39 +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 raw_loc_codes = get_locales_codes_list_blocking().unwrap(); let maybe_tz = k_config
let raw_loc_descr = get_locales_description_blocking().unwrap(); .res_timezone
.as_ref()
.and_then(|tzr| Some(tzr.time_zone.clone()));
let locales: Vec<LocaleData> = raw_loc_codes let locales: Vec<LocaleData> = get_locales_blocking(Some("UTF-8")).unwrap();
.iter()
.filter_map(|(code, _)| {
code.split_once('.')
.and_then(|(key_code, _)| Some((key_code, code)))
})
.filter_map(|(key_code, code)| {
raw_loc_descr
.get(key_code)
.and_then(|descr| Some((code.clone(), descr.clone())))
})
.map(|(code, descr)| LocaleData {
code: code,
description: descr,
})
.collect();
// 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!(
"{}: {}", "{}: {}",
+4 -4
View File
@@ -20,7 +20,7 @@
*/ */
use iced::{Alignment, Task, widget}; use iced::{Alignment, Task, widget};
use iced_moving_picture::widget::apng; use iced_moving_picture::widget::moving_picture;
use log; use log;
use rust_i18n::t; use rust_i18n::t;
@@ -52,7 +52,7 @@ pub struct NetworkStage {
internet_active: bool, internet_active: bool,
state: State, state: State,
use_net_settings: bool, use_net_settings: bool,
spinner_frames: apng::Frames, spinner_frames: moving_picture::Frames,
logo_handle: widget::image::Handle, logo_handle: widget::image::Handle,
status_message: String, status_message: String,
k_config: KiraConfig, k_config: KiraConfig,
@@ -102,7 +102,7 @@ async fn check_connected() -> CheckResult {
impl NetworkStage { impl NetworkStage {
pub fn new(k_config: KiraConfig) -> Self { pub fn new(k_config: KiraConfig) -> Self {
let spinner_frames = let spinner_frames =
apng::Frames::from_bytes(crate::kira_theming::get_spiner_bytes()).unwrap(); moving_picture::Frames::from_bytes(crate::kira_theming::get_spiner_bytes(), moving_picture::Kind::Apng).unwrap();
let logo_handle = widget::image::Handle::from_bytes(crate::kira_theming::get_logo_bytes()); let logo_handle = widget::image::Handle::from_bytes(crate::kira_theming::get_logo_bytes());
@@ -188,7 +188,7 @@ impl NetworkStage {
let spinner_container = match self.state { let spinner_container = match self.state {
State::Cheking => widget::container( State::Cheking => widget::container(
apng(&self.spinner_frames) moving_picture(&self.spinner_frames)
.width(iced::Pixels(128.0).into()) .width(iced::Pixels(128.0).into())
.height(iced::Pixels(128.0).into()), .height(iced::Pixels(128.0).into()),
), ),
+1 -1
View File
@@ -18,7 +18,7 @@
This is Security stage, setup users logins and such This is Security stage, setup users logins and such
*/ */
use crate::stage::{StageAction, KiraConfig}; use crate::stage::{KiraConfig, StageAction};
use iced::{Alignment, Color, widget}; use iced::{Alignment, Color, widget};
use rust_i18n::t; use rust_i18n::t;
+31 -52
View File
@@ -26,28 +26,7 @@ use std::collections::HashMap;
use crate::kira_scroll_list; use crate::kira_scroll_list;
#[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(),
})
}
}
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 {
@@ -75,35 +54,35 @@ pub enum Message {
} }
/// Getting list of awailable timezones from system. /// Getting list of awailable timezones from system.
fn get_timezones_blocking() -> Result<Vec<TimeZoneData>, String> { // fn get_timezones_blocking_depr() -> Result<Vec<TimeZoneData>, String> {
use std::process::Command; // use std::process::Command;
//timedatectl list-timezones --no-pager // //timedatectl list-timezones --no-pager
match Command::new("timedatectl") // match Command::new("timedatectl")
.arg("list-timezones") // .arg("list-timezones")
.arg("--no-pager") // .arg("--no-pager")
.output() // .output()
{ // {
Ok(cmd_output) => { // Ok(cmd_output) => {
if cmd_output.status.success() { // if cmd_output.status.success() {
//Etc/UTC // //Etc/UTC
match String::from_utf8(cmd_output.stdout) { // match String::from_utf8(cmd_output.stdout) {
Ok(str_tz_list) => Ok(str_tz_list // Ok(str_tz_list) => Ok(str_tz_list
.split("\n") // .split("\n")
.filter(|sb| sb.contains('/')) // .filter(|sb| sb.contains('/'))
.filter_map(|str_t_zone| TimeZoneData::from_str(str_t_zone.trim())) // .filter_map(|str_t_zone| TimeZoneData::from_str(str_t_zone.trim()))
.collect::<Vec<TimeZoneData>>()), // .collect::<Vec<TimeZoneData>>()),
Err(ex) => Err(format!("Exception while converting to UTF8 {}", ex)), // Err(ex) => Err(format!("Exception while converting to UTF8 {}", ex)),
} // }
} else { // } else {
Err(format!( // Err(format!(
"Error getting timezones list: {}", // "Error getting timezones list: {}",
String::from_utf8(cmd_output.stderr).unwrap_or("UNKNOWN".into()) // String::from_utf8(cmd_output.stderr).unwrap_or("UNKNOWN".into())
)) // ))
} // }
} // }
Err(ex) => Err(format!("Exception while trying to list time zones {}", ex)), // Err(ex) => Err(format!("Exception while trying to list time zones {}", ex)),
} // }
} // }
impl TimeZoneStage { impl TimeZoneStage {
pub fn new(k_config: KiraConfig) -> Self { pub fn new(k_config: KiraConfig) -> Self {
@@ -140,7 +119,7 @@ impl TimeZoneStage {
ex ex
); );
Self { Self {
time_zones: Err(ex), time_zones: Err(ex.to_string()),
regions: Vec::new(), regions: Vec::new(),
zones: Vec::new(), zones: Vec::new(),
region_id: None, region_id: None,
+1167
View File
File diff suppressed because it is too large. Load diff