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 => { button::Status::Hovered => {
res_stile.border = Border { res_stile.border = Border {
color: Color::from_rgb(0.8, 0.3, 0.3), color: Color::from_rgb(0.8, 0.3, 0.3),
width: 2.0, width: 1.0,
radius: Radius::new(5.0), radius: Radius::new(5.0),
}; };
}, },
@@ -45,7 +45,7 @@ fn selected_button_style(theme: &Theme, status: button::Status) -> button::Style
button::Status::Hovered => { button::Status::Hovered => {
res_stile.border = Border { res_stile.border = Border {
color: Color::from_rgb(0.8, 0.3, 0.3), color: Color::from_rgb(0.8, 0.3, 0.3),
width: 2.0, width: 1.0,
radius: Radius::new(5.0), radius: Radius::new(5.0),
}; };
}, },
@@ -55,32 +55,6 @@ fn selected_button_style(theme: &Theme, status: button::Status) -> button::Style
return res_stile; 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 // Assuming your Item struct or type implements Display or has a text representation
pub fn list_view<T: Display>( pub fn list_view<T: Display>(
+5 -2
View File
@@ -22,6 +22,9 @@
"timezone.select_timezone": "Please select preffered time zone", "timezone.select_timezone": "Please select preffered time zone",
"timezone.init_error": "Error getting time zones data from system!", "timezone.init_error": "Error getting time zones data from system!",
"locale.select_language_locale": "The system language will be set to", "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"); rust_i18n::i18n!("src/locales", fallback = "en");
mod kira_theming; mod kira_theming;
mod kira_scroll_list;
mod stage; mod stage;
mod stages; 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> { fn view(k_state: &KiraState) -> Element<'_, Message> {
match &k_state.current_view { 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 { 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) let iced_result = iced::application(KiraState::boot, update, view)
.window(iced::window::Settings { .window(iced::window::Settings {
+230 -140
View File
@@ -15,225 +15,315 @@
// along with this program. If not, see <https://www.gnu.org/licenses/>. // 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 crate::stage::{ConfigValue, StageAction, StageResult};
use iced::{Alignment, Length, widget}; use iced::{Alignment, Length, widget};
use rust_i18n::t; use rust_i18n::t;
use std::collections::HashMap; use std::collections::HashMap;
mod scroll_list;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeZoneData { pub struct Layout {
region: String, layout: String,
zone: String, description: String,
} }
impl std::fmt::Display for Layout {
impl TimeZoneData { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
fn from_str(s: &str) -> Option<Self> { write!(f, "{} ({})", &self.layout, &self.description)
let idx = s.find('/')?; }
let (region, zone) = s.split_at(idx); }
Some(Self { impl Layout {
region: region.into(), pub fn from_str_touple(v: &(&str, &str)) -> Self {
zone: zone.trim_start_matches('/').into(), Self {
}) layout: v.0.trim().to_string(),
description: v.1.trim().to_string(),
}
} }
} }
impl std::fmt::Display for TimeZoneData {
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Variant {
variant: String,
description: String,
}
impl std::fmt::Display for Variant {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 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)] #[derive(Debug, Clone)]
pub struct TimeZoneStage { pub struct KeyboardStage {
time_zones: Result<HashMap<String, Vec<String>>, String>, models: Vec<KeyboarModel>,
regions: Vec<String>, layouts: Vec<Layout>,
region_id: Option<usize>, variants_map: HashMap<String, Vec<Variant>>,
zones: Vec<String>, variants: Vec<Variant>,
zone_id: Option<usize>, model: Option<KeyboarModel>,
selected_zone: Option<TimeZoneData>, layout: Option<usize>,
selected_zone_text: String, variant: Option<usize>,
keyboard_layouts: Vec<KeyboarLayout>,
selected_kbd_layout_id: Option<usize>,
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Message { pub enum Message {
SelectRegion(scroll_list::ListViewMessage), SelectKeyboardModel(KeyboarModel),
SelectZone(scroll_list::ListViewMessage), SelectLayout(kira_scroll_list::ListViewMessage),
SelectVariant(kira_scroll_list::ListViewMessage),
AddLayout(usize),
RemoveLayout(usize),
SelectAddedLayout(kira_scroll_list::ListViewMessage),
Next, Next,
Back, Back,
} }
/// Getting list of awailable timezones from system. const XKB_RULES_FILE_NAME: &str = "/usr/share/X11/xkb/rules/evdev.lst";
fn get_timezones_blocking() -> Result<Vec<TimeZoneData>, String> {
use std::process::Command; /// Getting list of awailable keyboard layouts from from xkb/rules/evdev.lst file.
//timedatectl list-timezones --no-pager fn get_layouts_blocking() -> std::io::Result<(
match Command::new("timedatectl") Vec<KeyboarModel>,
.arg("list-timezones") Vec<Layout>,
.arg("--no-pager") HashMap<String, Vec<Variant>>,
.output() )> {
use std::fs::File;
use std::io::{BufReader, Read};
let mut file_content = String::new();
{ {
Ok(cmd_output) => { let locgen_file = File::open(XKB_RULES_FILE_NAME)?;
if cmd_output.status.success() { let mut reader = BufReader::new(locgen_file);
//Etc/UTC reader.read_to_string(&mut file_content)?;
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 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))
} }
impl TimeZoneStage { impl KeyboardStage {
pub fn new() -> Self { pub fn new() -> Result<Self, String> {
match get_timezones_blocking() { match get_layouts_blocking() {
Ok(time_zones_data_list) => { Ok((models, layouts, variants_map)) => Ok({
let mut time_zones_map: HashMap<String, Vec<String>> = HashMap::new(); let def_layout = layouts
for tz_data in &time_zones_data_list { .iter()
if let Some(zones) = time_zones_map.get_mut(&tz_data.region) { .enumerate()
zones.push(tz_data.zone.clone()); .find_map(|(idx, l)| (l.layout == "us").then_some(idx));
} else { let variants = variants_map
time_zones_map.insert(tz_data.region.clone(), vec![tz_data.zone.clone()]); .get("us")
} .cloned()
} .unwrap_or_else(|| Vec::new());
// sort zones alphabetically
time_zones_map.values_mut().for_each(|v| v.sort()); let def_model = models[0].clone();
// sort region names alphabetically
let mut regions: Vec<String> = time_zones_map.keys().cloned().collect();
regions.sort();
Self { Self {
regions: regions, layouts: layouts,
zones: Vec::new(), variants_map: variants_map,
time_zones: Ok(time_zones_map), variants: variants,
region_id: None, model: Some(def_model),
zone_id: None, models: models,
selected_zone: None, layout: def_layout,
selected_zone_text: String::new(), variant: Some(0),
keyboard_layouts: Vec::new(),
selected_kbd_layout_id: None,
} }
} }),
Err(ex) => { Err(ex) => {
println!( let err = format!(
"Exception while trying to get time zones list from system {}", "Exception while trying to get kayboard layouts data from system {}",
ex ex
); );
Self { Err(err)
time_zones: Err(ex),
regions: Vec::new(),
zones: Vec::new(),
region_id: None,
zone_id: None,
selected_zone: None,
selected_zone_text: String::new(),
}
} }
} }
} }
fn gen_result(&self) -> StageResult { 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 { StageResult {
name: "time_zone".to_string(), name: "keyboard".to_string(),
config: Some(HashMap::from([ config: Some(HashMap::from([
( (
"name".to_string(), "model".to_string(),
ConfigValue::String(time_zone.to_string()), ConfigValue::String(model.model.clone()),
), ),
( (
"region".to_string(), "layouts".to_string(),
ConfigValue::String(time_zone.region.clone()), ConfigValue::Vector(self.keyboard_layouts.iter().map(|kl| ConfigValue::String(kl.to_result())).collect()),
),
(
"zone".to_string(),
ConfigValue::String(time_zone.zone.clone()),
), ),
])), ])),
resuts: None, resuts: None,
error: None, error: None,
} }
} else { }
else {
StageResult { StageResult {
name: "time_zone".to_string(), name: "keyboard".to_string(),
config: None, config: None,
resuts: 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 { pub fn update(&mut self, message: Message) -> StageAction {
match message { 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::Next => StageAction::Next(self.gen_result()),
Message::Back => StageAction::Back, Message::Back => StageAction::Back,
_ => StageAction::None,
} }
} }
pub fn view(&self) -> iced::Element<'_, Message> { 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) widget::button(widget::text(t!("button.next"))).on_press(Message::Next)
} else { } else {
widget::button(widget::text(t!("button.next"))) 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::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![ widget::row![
scroll_list::list_view(&self.regions, self.region_id, Length::Shrink) widget::column![
.map(Message::SelectRegion), widget::text(t!("keyboard.select_layout")),
scroll_list::list_view(&self.zones, self.zone_id, Length::FillPortion(1)) crate::kira_scroll_list::list_view(&self.layouts, self.layout, Length::Shrink)
.map(Message::SelectZone), .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) .padding(20)
.spacing(10) .spacing(10)
.height(Length::Shrink), .height(Length::Shrink),
widget::text(self.selected_zone_text.clone())
] ]
.spacing(10) .spacing(10)
.align_x(Alignment::Center), .align_x(Alignment::Center),
), )}
else {
widget::container(widget::text(t!("keyboard.init_error")))
};
Err(_) => widget::container(widget::text(t!("timezone.init_error"))),
};
let back_button = widget::button(widget::text(t!("button.back"))).on_press(Message::Back); let back_button = widget::button(widget::text(t!("button.back"))).on_press(Message::Back);
widget::column![ 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 network;
pub mod timezone; pub mod timezone;
pub mod locale; pub mod locale;
pub mod keyboard;
+8 -8
View File
@@ -23,7 +23,7 @@ use iced::{Alignment, Length, widget};
use rust_i18n::t; use rust_i18n::t;
use std::collections::HashMap; use std::collections::HashMap;
mod scroll_list; use crate::kira_scroll_list;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct TimeZoneData { pub struct TimeZoneData {
@@ -61,8 +61,8 @@ pub struct TimeZoneStage {
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub enum Message { pub enum Message {
SelectRegion(scroll_list::ListViewMessage), SelectRegion(kira_scroll_list::ListViewMessage),
SelectZone(scroll_list::ListViewMessage), SelectZone(kira_scroll_list::ListViewMessage),
Next, Next,
Back, Back,
} }
@@ -177,7 +177,7 @@ impl TimeZoneStage {
pub fn update(&mut self, message: Message) -> StageAction { pub fn update(&mut self, message: Message) -> StageAction {
match message { 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(); let region = self.regions.get(region_id).unwrap();
self.zones = self self.zones = self
.time_zones .time_zones
@@ -191,7 +191,7 @@ impl TimeZoneStage {
//self.selected_zone_text.clear(); //self.selected_zone_text.clear();
StageAction::None StageAction::None
} }
Message::SelectZone(scroll_list::ListViewMessage::Select(zone_id)) => { Message::SelectZone(kira_scroll_list::ListViewMessage::Select(zone_id)) => {
let zone = TimeZoneData { let zone = TimeZoneData {
region: self.regions[self.region_id.unwrap()].clone(), region: self.regions[self.region_id.unwrap()].clone(),
zone: self.zones[zone_id].clone(), zone: self.zones[zone_id].clone(),
@@ -218,12 +218,12 @@ impl TimeZoneStage {
widget::column![ widget::column![
widget::text(t!("timezone.select_timezone")), widget::text(t!("timezone.select_timezone")),
widget::row![ 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), .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), .map(Message::SelectZone),
] ]
.padding(20) .padding([0,10])
.spacing(10) .spacing(10)
.height(Length::Shrink), .height(Length::Shrink),
widget::text(self.selected_zone_text.clone()) widget::text(self.selected_zone_text.clone())