Compare commits

...

3 Commits

7 changed files with 248 additions and 307 deletions
@@ -23,7 +23,7 @@ fn unselected_button_style(theme: &Theme, status: button::Status) -> button::Sty
button::Status::Hovered => {
res_stile.border = Border {
color: Color::from_rgb(0.8, 0.3, 0.3),
width: 2.0,
width: 1.0,
radius: Radius::new(5.0),
};
},
@@ -45,7 +45,7 @@ fn selected_button_style(theme: &Theme, status: button::Status) -> button::Style
button::Status::Hovered => {
res_stile.border = Border {
color: Color::from_rgb(0.8, 0.3, 0.3),
width: 2.0,
width: 1.0,
radius: Radius::new(5.0),
};
},
@@ -55,32 +55,6 @@ fn selected_button_style(theme: &Theme, status: button::Status) -> button::Style
return res_stile;
}
// fn view() -> container::Style {
// container::Style {
// text_color: None,
// background: None,
// border: Border {
// color: Color::BLACK,
// width: 2.0,
// radius: Radius::new(5.0),
// },
// shadow: None,
// snap: false,
// }
// }
// fn border_style(theme: &Theme) -> container::Style {
// use iced::{Border, border::Radius};
// container::Style {
// border: Border {
// color: Color::from_rgb(0.8, 0.3, 0.3),
// width: 2.0,
// radius: Radius::new(5.0),
// },
// ..container::bordered_box(theme)
// }
// }
// Assuming your Item struct or type implements Display or has a text representation
pub fn list_view<T: Display>(
+5 -2
View File
@@ -22,6 +22,9 @@
"timezone.select_timezone": "Please select preffered time zone",
"timezone.init_error": "Error getting time zones data from system!",
"locale.select_language_locale": "The system language will be set to",
"locale.select_formats_locale": "The numbers and dates locale will be set to"
"locale.select_formats_locale": "The numbers and dates locale will be set to",
"keyboard.select_model": "Select keyboard model",
"keyboard.select_layout": "Select keyboard layout",
"keyboard.select_variant": "Select keyboard variant",
"keyboard.init_error": "Error getting keyboard layouts information from the system!"
}
+2 -19
View File
@@ -33,6 +33,7 @@ use crate::stages::welcome::WelcomeStage;
rust_i18n::i18n!("src/locales", fallback = "en");
mod kira_theming;
mod kira_scroll_list;
mod stage;
mod stages;
@@ -90,17 +91,6 @@ impl KiraState {
}
}
// impl KiraState {
// fn new(toml_config: toml::Table) -> Self {
// Self {
// current_view: Views::Start,
// toml_config: toml_config,
// config: KiraConfig { config_trail: Vec::new() }
// }
// }
// }
fn view(k_state: &KiraState) -> Element<'_, Message> {
match &k_state.current_view {
@@ -232,15 +222,8 @@ fn update(k_state: &mut KiraState, message: Message) -> Task<Message> {
}
}
// pub fn main_interface() -> iced::Result {
// iced::run(WellcomeStage::update, WellcomeStage::view)
// }
pub fn main() -> ExitCode {
// let app_init = || {
// let mut k_state = KiraState::default()
// k_state.current_view = Views::Welcome(WelcomeStage::new());
// k_stateapp_init
// };
let iced_result = iced::application(KiraState::boot, update, view)
.window(iced::window::Settings {
+231 -141
View File
@@ -15,225 +15,315 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/*
This is TimeZone stage, used to select timezone
This is Keyboar stage, used to select Keyboard Layouts
*/
use crate::kira_scroll_list;
use crate::stage::{ConfigValue, StageAction, StageResult};
use iced::{Alignment, Length, widget};
use rust_i18n::t;
use std::collections::HashMap;
mod scroll_list;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Layout {
layout: String,
description: String,
}
impl std::fmt::Display for Layout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", &self.layout, &self.description)
}
}
impl Layout {
pub fn from_str_touple(v: &(&str, &str)) -> Self {
Self {
layout: v.0.trim().to_string(),
description: v.1.trim().to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeZoneData {
region: String,
zone: String,
pub struct Variant {
variant: String,
description: 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 {
impl std::fmt::Display for Variant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", self.region, self.zone)
write!(f, "{} ({})", &self.variant, &self.description)
}
}
impl Variant {
pub fn from_str_touple(v: &(&str, &str)) -> Self {
Self {
variant: v.0.trim().to_string(),
description: v.1.trim().to_string(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyboarLayout {
layout: Layout,
variant: Variant,
}
impl KeyboarLayout {
pub fn to_result(&self) -> String {
format!("{}||{}", self.layout.layout, self.variant.variant)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyboarModel {
model: String,
description: String,
}
impl std::fmt::Display for KeyboarModel {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{} ({})", &self.model, &self.description)
}
}
impl KeyboarModel {
pub fn from_str_touple(v: &(&str, &str)) -> Self {
Self {
model: v.0.trim().to_string(),
description: v.1.trim().to_string(),
}
}
}
impl std::fmt::Display for KeyboarLayout {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}/{}", &self.layout.layout, &self.variant.variant)
}
}
#[derive(Debug, Clone)]
pub struct TimeZoneStage {
time_zones: Result<HashMap<String, Vec<String>>, String>,
regions: Vec<String>,
region_id: Option<usize>,
zones: Vec<String>,
zone_id: Option<usize>,
selected_zone: Option<TimeZoneData>,
selected_zone_text: String,
pub struct KeyboardStage {
models: Vec<KeyboarModel>,
layouts: Vec<Layout>,
variants_map: HashMap<String, Vec<Variant>>,
variants: Vec<Variant>,
model: Option<KeyboarModel>,
layout: Option<usize>,
variant: Option<usize>,
keyboard_layouts: Vec<KeyboarLayout>,
selected_kbd_layout_id: Option<usize>,
}
#[derive(Debug, Clone)]
pub enum Message {
SelectRegion(scroll_list::ListViewMessage),
SelectZone(scroll_list::ListViewMessage),
SelectKeyboardModel(KeyboarModel),
SelectLayout(kira_scroll_list::ListViewMessage),
SelectVariant(kira_scroll_list::ListViewMessage),
AddLayout(usize),
RemoveLayout(usize),
SelectAddedLayout(kira_scroll_list::ListViewMessage),
Next,
Back,
}
/// Getting list of awailable timezones from system.
fn get_timezones_blocking() -> Result<Vec<TimeZoneData>, String> {
use std::process::Command;
//timedatectl list-timezones --no-pager
match Command::new("timedatectl")
.arg("list-timezones")
.arg("--no-pager")
.output()
const XKB_RULES_FILE_NAME: &str = "/usr/share/X11/xkb/rules/evdev.lst";
/// Getting list of awailable keyboard layouts from from xkb/rules/evdev.lst file.
fn get_layouts_blocking() -> std::io::Result<(
Vec<KeyboarModel>,
Vec<Layout>,
HashMap<String, Vec<Variant>>,
)> {
use std::fs::File;
use std::io::{BufReader, Read};
let mut file_content = String::new();
{
Ok(cmd_output) => {
if cmd_output.status.success() {
//Etc/UTC
match String::from_utf8(cmd_output.stdout) {
Ok(str_tz_list) => Ok(str_tz_list
.split("\n")
.filter(|sb| sb.contains('/'))
.filter_map(|str_t_zone| TimeZoneData::from_str(str_t_zone.trim()))
.collect::<Vec<TimeZoneData>>()),
Err(ex) => Err(format!("Exception while converting to UTF8 {}", ex)),
}
} else {
Err(format!(
"Error getting timezones list: {}",
String::from_utf8(cmd_output.stderr).unwrap_or("UNKNOWN".into())
))
}
}
Err(ex) => Err(format!("Exception while trying to list time zones {}", ex)),
}
let locgen_file = File::open(XKB_RULES_FILE_NAME)?;
let mut reader = BufReader::new(locgen_file);
reader.read_to_string(&mut file_content)?;
}
impl TimeZoneStage {
pub fn new() -> Self {
match get_timezones_blocking() {
Ok(time_zones_data_list) => {
let mut time_zones_map: HashMap<String, Vec<String>> = HashMap::new();
for tz_data in &time_zones_data_list {
if let Some(zones) = time_zones_map.get_mut(&tz_data.region) {
zones.push(tz_data.zone.clone());
} else {
time_zones_map.insert(tz_data.region.clone(), vec![tz_data.zone.clone()]);
let raw_sections: Vec<String> = file_content.split("! ").map(str::to_string).collect();
// Parsing models data
let models: Vec<KeyboarModel> = raw_sections
.iter()
.find(|s| s.starts_with("model"))
.and_then(|s| {
Some(
s.lines()
.skip(1)
.filter_map(|s| s.trim().split_once(char::is_whitespace))
.map(|s_spl| KeyboarModel::from_str_touple(&s_spl))
.collect(),
)
})
.unwrap_or_else(Vec::new);
// Parsing layots data
let layouts: Vec<Layout> = raw_sections
.iter()
.find(|s| s.starts_with("layout"))
.and_then(|s| {
Some(
s.lines()
.skip(1)
.filter_map(|s| s.trim().split_once(char::is_whitespace))
.map(|s_spl| Layout::from_str_touple(&s_spl))
.collect(),
)
})
.unwrap_or_else(Vec::new);
// parsing variants data to HashMap
let mut variants: HashMap<String, Vec<Variant>> = HashMap::new();
raw_sections
.iter()
.find(|s| s.starts_with("variant"))
.and_then(|s| {
Some(
s.lines()
.skip(1)
.filter_map(|s| s.trim().split_once(char::is_whitespace))
.filter_map(|(vrnt, l_plus_descr)| {
l_plus_descr
.trim()
.split_once(": ")
.and_then(|(loc, descr)| {
Some((loc.trim(), Variant::from_str_touple(&(vrnt, descr))))
})
})
.for_each(|v| {
let maybe_key = variants
.get_mut(v.0)
.and_then(|vrn_vec| Some(vrn_vec.push(v.1.clone())));
if maybe_key.is_none() {
variants.insert(v.0.to_string(), vec![v.1.clone()]);
}
}),
)
});
Ok((models, layouts, variants))
}
// sort zones alphabetically
time_zones_map.values_mut().for_each(|v| v.sort());
// sort region names alphabetically
let mut regions: Vec<String> = time_zones_map.keys().cloned().collect();
regions.sort();
impl KeyboardStage {
pub fn new() -> Result<Self, String> {
match get_layouts_blocking() {
Ok((models, layouts, variants_map)) => Ok({
let def_layout = layouts
.iter()
.enumerate()
.find_map(|(idx, l)| (l.layout == "us").then_some(idx));
let variants = variants_map
.get("us")
.cloned()
.unwrap_or_else(|| Vec::new());
let def_model = models[0].clone();
Self {
regions: regions,
zones: Vec::new(),
time_zones: Ok(time_zones_map),
region_id: None,
zone_id: None,
selected_zone: None,
selected_zone_text: String::new(),
}
layouts: layouts,
variants_map: variants_map,
variants: variants,
model: Some(def_model),
models: models,
layout: def_layout,
variant: Some(0),
keyboard_layouts: Vec::new(),
selected_kbd_layout_id: None,
}
}),
Err(ex) => {
println!(
"Exception while trying to get time zones list from system {}",
let err = format!(
"Exception while trying to get kayboard layouts data from system {}",
ex
);
Self {
time_zones: Err(ex),
regions: Vec::new(),
zones: Vec::new(),
region_id: None,
zone_id: None,
selected_zone: None,
selected_zone_text: String::new(),
}
Err(err)
}
}
}
fn gen_result(&self) -> StageResult {
if let Some(time_zone) = &self.selected_zone {
if let Some(model) = &self.model && self.keyboard_layouts.len() > 0 {
StageResult {
name: "time_zone".to_string(),
name: "keyboard".to_string(),
config: Some(HashMap::from([
(
"name".to_string(),
ConfigValue::String(time_zone.to_string()),
"model".to_string(),
ConfigValue::String(model.model.clone()),
),
(
"region".to_string(),
ConfigValue::String(time_zone.region.clone()),
),
(
"zone".to_string(),
ConfigValue::String(time_zone.zone.clone()),
"layouts".to_string(),
ConfigValue::Vector(self.keyboard_layouts.iter().map(|kl| ConfigValue::String(kl.to_result())).collect()),
),
])),
resuts: None,
error: None,
}
} else {
}
else {
StageResult {
name: "time_zone".to_string(),
name: "keyboard".to_string(),
config: None,
resuts: None,
error: None,
error: Some("Something go terrible wrong, there is no keyboard layouts.".into()),
}
}
}
pub fn update(&mut self, message: Message) -> StageAction {
match message {
Message::SelectRegion(scroll_list::ListViewMessage::Select(region_id)) => {
let region = self.regions.get(region_id).unwrap();
self.zones = self
.time_zones
.as_ref()
.unwrap()
.get(region)
.unwrap()
.clone();
self.region_id = Some(region_id);
self.zone_id = None;
//self.selected_zone_text.clear();
StageAction::None
}
Message::SelectZone(scroll_list::ListViewMessage::Select(zone_id)) => {
let zone = TimeZoneData {
region: self.regions[self.region_id.unwrap()].clone(),
zone: self.zones[zone_id].clone(),
};
self.selected_zone_text =
format!("{} {}", t!("timezone.selected_timezone"), zone.to_string());
self.zone_id = Some(zone_id);
self.selected_zone = Some(zone);
StageAction::None
}
Message::Next => StageAction::Next(self.gen_result()),
Message::Back => StageAction::Back,
_ => StageAction::None,
}
}
pub fn view(&self) -> iced::Element<'_, Message> {
let next_button = if self.zone_id.is_some() {
let next_button = if self.model.is_some() && self.keyboard_layouts.len() > 0 {
widget::button(widget::text(t!("button.next"))).on_press(Message::Next)
} else {
widget::button(widget::text(t!("button.next")))
};
let main_content = match &self.time_zones {
Ok(_) => widget::container(
let main_content = if self.layouts.len() > 0 {
widget::container(
widget::column![
widget::text(t!("timezone.select_timezone")),
widget::text(t!("keyboard.select_model")),
widget::pick_list(
self.models.clone(),
self.model.clone(),
Message::SelectKeyboardModel,
),
widget::row![
scroll_list::list_view(&self.regions, self.region_id, Length::Shrink)
.map(Message::SelectRegion),
scroll_list::list_view(&self.zones, self.zone_id, Length::FillPortion(1))
.map(Message::SelectZone),
widget::column![
widget::text(t!("keyboard.select_layout")),
crate::kira_scroll_list::list_view(&self.layouts, self.layout, Length::Shrink)
.map(Message::SelectLayout)],
widget::column![
widget::text(t!("keyboard.select_variant")),
crate::kira_scroll_list::list_view(&self.variants, self.variant, Length::FillPortion(1))
.map(Message::SelectVariant)],
]
.padding(20)
.spacing(10)
.height(Length::Shrink),
widget::text(self.selected_zone_text.clone())
]
.spacing(10)
.align_x(Alignment::Center),
),
Err(_) => widget::container(widget::text(t!("timezone.init_error"))),
)}
else {
widget::container(widget::text(t!("keyboard.init_error")))
};
let back_button = widget::button(widget::text(t!("button.back"))).on_press(Message::Back);
widget::column![
-110
View File
@@ -1,110 +0,0 @@
use std::fmt::Display;
use iced::widget::{Column, button, container, scrollable, text};
use iced::{Alignment, Color, Element, Length, Theme};
#[derive(Debug, Clone)]
pub enum ListViewMessage {
Select(usize),
}
fn unselected_button_style(theme: &Theme, status: button::Status) -> button::Style {
//let palette = theme.extended_palette();
use iced::{Border, border::Radius};
match status {
button::Status::Hovered => button::Style {
border: Border {
color: Color::from_rgb(0.8, 0.3, 0.3),
width: 2.0,
radius: Radius::new(5.0),
},
..button::primary(theme, status)
},
button::Status::Active => button::Style {
background: Some(iced::Background::Color(crate::kira_theming::change_lightnes(
&theme.palette().primary,
-0.1,
))),
..button::primary(theme, status)
},
_ => button::primary(theme, status),
}
}
fn selected_button_style(theme: &Theme, status: button::Status) -> button::Style {
//let palette = theme.extended_palette();
match status {
button::Status::Active => button::Style {
background: Some(iced::Background::Color(Color::from_rgb(0.8, 0.3, 0.3))),
..button::primary(theme, status)
},
_ => button::Style {
background: Some(iced::Background::Color(Color::from_rgb(0.8, 0.3, 0.3))),
..button::primary(theme, status)
},
}
}
// fn view() -> container::Style {
// container::Style {
// text_color: None,
// background: None,
// border: Border {
// color: Color::BLACK,
// width: 2.0,
// radius: Radius::new(5.0),
// },
// shadow: None,
// snap: false,
// }
// }
// fn border_style(theme: &Theme) -> container::Style {
// use iced::{Border, border::Radius};
// container::Style {
// border: Border {
// color: Color::from_rgb(0.8, 0.3, 0.3),
// width: 2.0,
// radius: Radius::new(5.0),
// },
// ..container::bordered_box(theme)
// }
// }
// Assuming your Item struct or type implements Display or has a text representation
pub fn list_view<T: Display>(
items: &Vec<T>,
selected_id: Option<usize>,
container_height: Length,
) -> Element<'_, ListViewMessage> {
let mut column = Column::new()
.spacing(2)
.align_x(Alignment::Center)
.width(Length::Fill);
for (index, value) in items.iter().enumerate() {
// Create a row for each item, possibly with buttons or other controls
let list_item = if let Some(id) = selected_id
&& id == index
{
button(text(value.to_string())).style(selected_button_style)
} else {
button(text(value.to_string())).style(unselected_button_style)
};
let list_item = list_item
.width(Length::Fill)
.on_press(ListViewMessage::Select(index));
column = column.push(list_item);
}
// Wrap the column in a scrollable widget
container(scrollable(column).width(Length::Fill))
.style(container::bordered_box)
.height(container_height)
.padding(8)
.into()
}
+1
View File
@@ -20,3 +20,4 @@ pub mod license;
pub mod network;
pub mod timezone;
pub mod locale;
pub mod keyboard;
+8 -8
View File
@@ -23,7 +23,7 @@ use iced::{Alignment, Length, widget};
use rust_i18n::t;
use std::collections::HashMap;
mod scroll_list;
use crate::kira_scroll_list;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeZoneData {
@@ -61,8 +61,8 @@ pub struct TimeZoneStage {
#[derive(Debug, Clone)]
pub enum Message {
SelectRegion(scroll_list::ListViewMessage),
SelectZone(scroll_list::ListViewMessage),
SelectRegion(kira_scroll_list::ListViewMessage),
SelectZone(kira_scroll_list::ListViewMessage),
Next,
Back,
}
@@ -177,7 +177,7 @@ impl TimeZoneStage {
pub fn update(&mut self, message: Message) -> StageAction {
match message {
Message::SelectRegion(scroll_list::ListViewMessage::Select(region_id)) => {
Message::SelectRegion(kira_scroll_list::ListViewMessage::Select(region_id)) => {
let region = self.regions.get(region_id).unwrap();
self.zones = self
.time_zones
@@ -191,7 +191,7 @@ impl TimeZoneStage {
//self.selected_zone_text.clear();
StageAction::None
}
Message::SelectZone(scroll_list::ListViewMessage::Select(zone_id)) => {
Message::SelectZone(kira_scroll_list::ListViewMessage::Select(zone_id)) => {
let zone = TimeZoneData {
region: self.regions[self.region_id.unwrap()].clone(),
zone: self.zones[zone_id].clone(),
@@ -218,12 +218,12 @@ impl TimeZoneStage {
widget::column![
widget::text(t!("timezone.select_timezone")),
widget::row![
scroll_list::list_view(&self.regions, self.region_id, Length::Shrink)
kira_scroll_list::list_view(&self.regions, self.region_id, Length::Shrink)
.map(Message::SelectRegion),
scroll_list::list_view(&self.zones, self.zone_id, Length::FillPortion(1))
kira_scroll_list::list_view(&self.zones, self.zone_id, Length::FillPortion(1))
.map(Message::SelectZone),
]
.padding(20)
.padding([0,10])
.spacing(10)
.height(Length::Shrink),
widget::text(self.selected_zone_text.clone())