ADDED: models and controllers for page "signal reducing"\n TODO: done table for page "signal reducing"

This commit is contained in:
doryan 2024-04-19 01:30:51 +04:00
parent 6e315907bc
commit b6d0eb0508
11 changed files with 228 additions and 97 deletions

View File

@ -1,6 +1,9 @@
use std::collections::HashMap; use std::collections::HashMap;
use crate::{controller::view_utils::input_utils::*, model::model::*}; use crate::{
controller::view_utils::{hamming_code_input_utils::*, input_utils::*},
model::model::*,
};
/// **Синдромы** /// **Синдромы**
/// ///
@ -23,7 +26,8 @@ pub fn hamming(raw_input: String, mode: HammingMode) -> Result<String, String> {
let prepared_input: String = processing_input(&raw_input); let prepared_input: String = processing_input(&raw_input);
let (fc, sc) = check_correct_input(&raw_input, &prepared_input, length_of_code); let (fc, sc): (bool, bool) =
check_correct_binary_code(&raw_input, &prepared_input, length_of_code);
if !fc || !sc { if !fc || !sc {
Err("Ошибка. Проверьте корректность ввода.".to_string()) Err("Ошибка. Проверьте корректность ввода.".to_string())
@ -45,7 +49,7 @@ pub fn hamming_encrypt_data(data: &Vec<u8>, result_string: &mut String, length_o
let mut i: usize = length_of_code; let mut i: usize = length_of_code;
while i <= data.len() { while i <= data.len() {
let data_bits = &data[i - length_of_code..i]; let data_bits: &[u8] = &data[i - length_of_code..i];
let (check_bit_1, check_bit_2, check_bit_3) = ( let (check_bit_1, check_bit_2, check_bit_3) = (
data_bits[0] ^ data_bits[1] ^ data_bits[3], data_bits[0] ^ data_bits[1] ^ data_bits[3],
data_bits[0] ^ data_bits[2] ^ data_bits[3], data_bits[0] ^ data_bits[2] ^ data_bits[3],
@ -87,30 +91,32 @@ pub fn hamming_decrypt_data(data: &Vec<u8>, result_string: &mut String, length_o
general_length += length_of_code; general_length += length_of_code;
continue; continue;
} else { } else {
let error_position = syndromes let error_position: &usize = syndromes
.iter() .iter()
.find(move |&(&_error_position, &error)| error == checked_bits) .find(move |&(&_error_position, &error)| error == checked_bits)
.unwrap() .unwrap()
.0; .0;
let correctly_code: Vec<u8> = data_bits let uncorrect_code: String = from_vec_bits_to_string(&data_bits);
let correct_code: String = from_vec_bits_to_string(
data_bits
.iter() .iter()
.enumerate() .enumerate()
.map(|(index, bit)| { .map(|(index, &bit)| {
if index == error_position - 1 { if index == error_position - 1 {
(*bit == 0u8).into() (bit == 0u8).into()
} else { } else {
*bit bit
} }
}) })
.collect(); .collect::<Vec<u8>>()
.as_slice(),
);
let error = format!( let error = format!(
"Ошибка в коде {} {:?}, позиция ошибки {}, корректный код: {:?}; \n", "Ошибка в коде {} [{uncorrect_code}], позиция ошибки {}, корректный код: [{correct_code}]; \n",
general_length / 7, general_length / 7,
&data_bits, error_position
error_position,
correctly_code
); );
errors.push_str(error.as_str()); errors.push_str(error.as_str());

View File

@ -1 +1,3 @@
pub mod hamming_code_seven_four; pub mod hamming_code_seven_four;
pub mod signal_reducer;

View File

@ -0,0 +1,15 @@
pub fn reactive_resistance_of_capacitor(Cm: f64, L: f64, f: f64) -> f64 {
1f64 / (2f64 * 3.14f64 * f * Cm * L)
}
pub fn full_resistance_of_capacitor(Xc: f64, Rs: f64, Rm: f64, L: f64) -> f64 {
(Xc.powf(2f64) + (Rs + Rm * L).powf(2f64)).sqrt()
}
pub fn voltage_from_signal_source(Vs: f64, Xc: f64, Z: f64) -> f64 {
(Vs * Xc) / Z
}
pub fn coef_of_signal_reduce(Vs: f64, V: f64) -> f64 {
Vs / V
}

View File

@ -0,0 +1,41 @@
use gtk4 as gtk;
use crate::{model::model::*, model_utils::hamming_code_seven_four::*};
use gtk::{prelude::*, *};
pub fn start_hamming_algorithm(input: &TextView, output: &TextView, mode: bool) -> () {
let (iter_start, iter_end) = input.buffer().bounds();
let parsed_input: String = input
.buffer()
.text(&iter_start, &iter_end, false)
.to_string()
.trim()
.parse()
.unwrap();
let operation = if mode == false {
HammingMode::Encrypt
} else {
HammingMode::Decrypt
};
match hamming(parsed_input, operation) {
Ok(res) => output.buffer().set_text(res.trim_end()),
Err(rej) => output.buffer().set_text(rej.as_str()),
}
}
pub fn check_correct_binary_code(
input: &String,
prepared_input: &String,
l: usize,
) -> (bool, bool) {
let first_condition: bool = input
.as_str()
.chars()
.all(|c| c == '1' || c == '0' || c == ' ');
let second_condition: bool = prepared_input.len() % l == 0;
(first_condition, second_condition)
}

View File

@ -4,29 +4,7 @@ use bitvec::{order::Lsb0, view::AsBits};
use gtk::{prelude::*, *}; use gtk::{prelude::*, *};
use std::ops::Deref; use std::ops::Deref;
use crate::{model::model::*, model_utils::hamming_code_seven_four::*}; const ASCII_ZERO_CHAR_POSITION: u8 = 48;
pub fn parse_input(input: &TextView, output: &TextView, mode: bool) -> () {
let (iter_start, iter_end) = input.buffer().bounds();
let parsed_input: String = input
.buffer()
.text(&iter_start, &iter_end, false)
.to_string()
.trim()
.parse()
.unwrap();
let operation = if mode == false {
HammingMode::Encrypt
} else {
HammingMode::Decrypt
};
match hamming(parsed_input, operation) {
Ok(res) => output.buffer().set_text(res.trim_end()),
Err(rej) => output.buffer().set_text(rej.as_str()),
}
}
pub fn processing_input(input: &String) -> String { pub fn processing_input(input: &String) -> String {
input input
@ -35,15 +13,11 @@ pub fn processing_input(input: &String) -> String {
.fold(String::new(), |c: String, n: &str| c + n) .fold(String::new(), |c: String, n: &str| c + n)
} }
pub fn check_correct_input(input: &String, prepared_input: &String, l: usize) -> (bool, bool) { pub fn from_vec_bits_to_string(raw_data: &[u8]) -> String {
let first_condition = input raw_data
.as_str() .iter()
.chars() .map(|bit| -> char { (bit + ASCII_ZERO_CHAR_POSITION).into() })
.all(|c| c == '1' || c == '0' || c == ' '); .collect()
let second_condition = prepared_input.len() % l == 0;
(first_condition, second_condition)
} }
pub fn from_string_to_vec_bits(raw_data: String) -> Vec<u8> { pub fn from_string_to_vec_bits(raw_data: String) -> Vec<u8> {

View File

@ -1 +1,4 @@
pub mod hamming_code_input_utils;
pub mod input_utils; pub mod input_utils;
pub mod signal_reduce_input_utils;

View File

@ -0,0 +1,63 @@
use gtk4 as gtk;
use crate::model::model::SchemeCharacteristics;
use gtk::{prelude::*, *};
pub fn check_characteristics(
raw_characteristics: &Vec<TextView>,
all_inputs_data: &mut Vec<f64>,
output: &mut String,
) -> bool {
for input in raw_characteristics {
let (iter_start, iter_end) = input.buffer().bounds();
let parsed_input: Result<f64, _> = input
.buffer()
.text(&iter_start, &iter_end, false)
.to_string()
.trim()
.parse();
match parsed_input {
Ok(int) => {
all_inputs_data.push(int);
println!("{:?}", int);
}
Err(err) => {
if output.len() == 0 {
output.push_str("Введите пожалуйста числа в полях");
println!("{:?}", err);
}
}
}
}
if output.len() != 0 {
false
} else {
true
}
}
pub fn start_algorithm(error_log_label: &Label, raw_characteristics: &Vec<TextView>) {
let mut all_inputs_data: Vec<f64> = Vec::new();
let mut output: String = String::new();
if let false = check_characteristics(raw_characteristics, &mut all_inputs_data, &mut output) {
error_log_label.set_text(output.as_str());
} else {
error_log_label.set_text("");
let (L, Rm, Cm, Vs, Rs, f): SchemeCharacteristics = (
all_inputs_data[0],
all_inputs_data[1],
all_inputs_data[2],
all_inputs_data[3],
all_inputs_data[4],
all_inputs_data[5],
);
let mut frequencies: Vec<usize> = vec![f as usize, 1usize];
frequencies.append(&mut (0..100).step_by(5).collect());
}
}

View File

@ -1,11 +1,13 @@
#[repr(usize)] #[repr(usize)]
#[derive(Clone)] #[derive(Clone)]
pub enum HammingMode{ pub enum HammingMode {
Encrypt = 4, Encrypt = 4,
Decrypt = 7 Decrypt = 7,
} }
pub struct EventHandler<F, C>{ pub struct EventHandler<F, C> {
pub(crate) component: C, pub(crate) component: C,
pub(crate) callback: F, pub(crate) callback: F,
} }
pub type SchemeCharacteristics = (f64, f64, f64, f64, f64, f64);

View File

@ -5,8 +5,10 @@ use gtk::{prelude::*, *};
pub type InputLabel = String; pub type InputLabel = String;
#[derive(Clone)]
pub struct Input { pub struct Input {
component: Box, component: Box,
input: TextView,
} }
pub struct InputBuilder { pub struct InputBuilder {
@ -32,6 +34,12 @@ impl Product<InputBuilder, Box> for Input {
} }
} }
impl Input {
pub fn get_input(self) -> TextView {
self.input
}
}
impl InputBuilder { impl InputBuilder {
pub fn set_label(mut self, label: &str) -> Self { pub fn set_label(mut self, label: &str) -> Self {
self.label = String::from(label); self.label = String::from(label);
@ -78,6 +86,7 @@ impl InputBuilder {
Input { Input {
component: input_component, component: input_component,
input: text_view_input,
} }
} }
} }

View File

@ -4,7 +4,7 @@ use crate::{
controller::{ controller::{
controller::*, controller::*,
event_handlers::{button_event_handlers::*, switch_event_handlers::*}, event_handlers::{button_event_handlers::*, switch_event_handlers::*},
view_utils::input_utils::*, view_utils::{hamming_code_input_utils::*, input_utils::*},
}, },
model::model::*, model::model::*,
view::{components::wrapper::*, properties::*}, view::{components::wrapper::*, properties::*},
@ -94,7 +94,7 @@ pub fn hamming_code_page(wrapper: &Box) -> () {
.on_click(); .on_click();
EventHandler::new(hamming_crypt_button.clone(), move |_button: &Button| { EventHandler::new(hamming_crypt_button.clone(), move |_button: &Button| {
parse_input( start_hamming_algorithm(
&text_view_input_for_parse, &text_view_input_for_parse,
&text_view_output_for_output, &text_view_output_for_output,
crypt_mode_switch_to_handle.state(), crypt_mode_switch_to_handle.state(),

View File

@ -2,11 +2,15 @@ use gtk4 as gtk;
use crate::{ use crate::{
controller::event_handlers::button_event_handlers::*, controller::event_handlers::button_event_handlers::*,
model::{builder_traits::Product, model::EventHandler}, model::{
builder_traits::Product,
model::{EventHandler, SchemeCharacteristics},
},
view::{ view::{
components::{input::Input, wrapper::Wrapper}, components::{input::Input, wrapper::Wrapper},
properties::*, properties::*,
}, },
view_utils::signal_reduce_input_utils::start_algorithm,
}; };
use gtk::{prelude::*, Align, WrapMode, *}; use gtk::{prelude::*, Align, WrapMode, *};
@ -19,26 +23,23 @@ pub fn signal_reducing_page(wrapper: &Box) {
vertical: Align::Fill, vertical: Align::Fill,
}; };
let wire_length_input = Input::builder() let wire_length_input: Input = Input::builder()
.set_label("l, м:") .set_label("l, м:")
.set_margins(MarginData::EqualsMargin(5)) .set_margins(MarginData::EqualsMargin(5))
.set_align(input_label_alignment) .set_align(input_label_alignment)
.build(monospace, input_wrapping, input_height) .build(monospace, input_wrapping, input_height);
.get();
let resistance_per_meter_input = Input::builder() let resistance_per_meter_input: Input = Input::builder()
.set_label("Rм, Ом:") .set_label("Rм, Ом:")
.set_margins(MarginData::EqualsMargin(5)) .set_margins(MarginData::EqualsMargin(5))
.set_align(input_label_alignment) .set_align(input_label_alignment)
.build(monospace, input_wrapping, input_height) .build(monospace, input_wrapping, input_height);
.get();
let capacity_per_meter_input = Input::builder() let capacity_per_meter_input: Input = Input::builder()
.set_label("Cм, пФ:") .set_label("Cм, пФ:")
.set_margins(MarginData::EqualsMargin(5)) .set_margins(MarginData::EqualsMargin(5))
.set_align(input_label_alignment) .set_align(input_label_alignment)
.build(monospace, input_wrapping, input_height) .build(monospace, input_wrapping, input_height);
.get();
let wrapper_first_row = Wrapper::col_builder() let wrapper_first_row = Wrapper::col_builder()
.halign(Align::Fill) .halign(Align::Fill)
@ -46,39 +47,38 @@ pub fn signal_reducing_page(wrapper: &Box) {
.spacing(5) .spacing(5)
.build(); .build();
let first_row_elements: Vec<&Box> = vec![ let first_row_elements: Vec<&Input> = vec![
&wire_length_input, &wire_length_input,
&resistance_per_meter_input, &resistance_per_meter_input,
&capacity_per_meter_input, &capacity_per_meter_input,
]; ];
for elem in first_row_elements { for elem in first_row_elements {
elem.set_halign(input_alignment); let input: Box = elem.clone().get();
elem.set_hexpand(true);
wrapper_first_row.append(elem); input.set_halign(input_alignment);
input.set_hexpand(true);
wrapper_first_row.append(&input);
} }
let info_signal_voltage_input = Input::builder() let info_signal_voltage_input: Input = Input::builder()
.set_label("Vи, мВ:") .set_label("Vи, мВ:")
.set_margins(MarginData::EqualsMargin(5)) .set_margins(MarginData::EqualsMargin(5))
.set_align(input_label_alignment) .set_align(input_label_alignment)
.build(monospace, input_wrapping, input_height) .build(monospace, input_wrapping, input_height);
.get();
let resistance_of_info_voltage_source_input = Input::builder() let resistance_of_info_voltage_source_input: Input = Input::builder()
.set_label("Rи, Ом:") .set_label("Rи, Ом:")
.set_margins(MarginData::EqualsMargin(5)) .set_margins(MarginData::EqualsMargin(5))
.set_align(input_label_alignment) .set_align(input_label_alignment)
.build(monospace, input_wrapping, input_height) .build(monospace, input_wrapping, input_height);
.get();
let info_voltage_source_frequency_input = Input::builder() let info_voltage_source_frequency_input: Input = Input::builder()
.set_label("f, мГц:") .set_label("f, мГц:")
.set_margins(MarginData::EqualsMargin(5)) .set_margins(MarginData::EqualsMargin(5))
.set_align(input_label_alignment) .set_align(input_label_alignment)
.build(monospace, input_wrapping, input_height) .build(monospace, input_wrapping, input_height);
.get();
let wrapper_second_row = Wrapper::col_builder() let wrapper_second_row = Wrapper::col_builder()
.halign(Align::Fill) .halign(Align::Fill)
@ -86,19 +86,30 @@ pub fn signal_reducing_page(wrapper: &Box) {
.spacing(5) .spacing(5)
.build(); .build();
let second_row_elements: Vec<&Box> = vec![ let second_row_elements: Vec<&Input> = vec![
&info_signal_voltage_input, &info_signal_voltage_input,
&resistance_of_info_voltage_source_input, &resistance_of_info_voltage_source_input,
&info_voltage_source_frequency_input, &info_voltage_source_frequency_input,
]; ];
for elem in second_row_elements { for elem in second_row_elements {
elem.set_halign(input_alignment); let input: Box = elem.clone().get();
elem.set_hexpand(true);
wrapper_second_row.append(elem); input.set_halign(input_alignment);
input.set_hexpand(true);
wrapper_second_row.append(&input);
} }
let all_text_views: Vec<TextView> = vec![
wire_length_input.get_input(),
resistance_per_meter_input.get_input(),
capacity_per_meter_input.get_input(),
info_signal_voltage_input.get_input(),
resistance_of_info_voltage_source_input.get_input(),
info_voltage_source_frequency_input.get_input(),
];
let main_wrapper = Wrapper::row_builder().spacing(5).build(); let main_wrapper = Wrapper::row_builder().spacing(5).build();
main_wrapper.append(&wrapper_first_row); main_wrapper.append(&wrapper_first_row);
@ -112,20 +123,21 @@ pub fn signal_reducing_page(wrapper: &Box) {
let table_header_labels = vec!["f, Гц", "Xc, пФ", "Vп, мВ", "ζ"]; let table_header_labels = vec!["f, Гц", "Xc, пФ", "Vп, мВ", "ζ"];
let table_header = Wrapper::col_builder() let table_header = ColumnView::builder()
.height_request(24) .focusable(false)
.spacing(5) .reorderable(true)
.halign(Align::Center)
.hexpand(true)
.build();
for header_label in table_header_labels {
let label = Label::builder()
.label(header_label)
.halign(Align::Fill) .halign(Align::Fill)
.hexpand(true) .hexpand(true)
.build(); .build();
table_header.append(&label);
for table_header_label in table_header_labels {
let column = ColumnViewColumn::builder()
.title(table_header_label)
.fixed_width(200)
.expand(true)
.build();
table_header.append_column(&column);
} }
let table_of_calculated_values = Frame::builder() let table_of_calculated_values = Frame::builder()
@ -136,13 +148,17 @@ pub fn signal_reducing_page(wrapper: &Box) {
.set_margin(MarginData::MultipleMargin((10, 5, 0, 0))) .set_margin(MarginData::MultipleMargin((10, 5, 0, 0)))
.build(); .build();
let errors_label: Label = Label::new(Some(""));
let errors_label_for_handler: Label = errors_label.clone();
EventHandler::new(calculate_button.clone(), move |_| { EventHandler::new(calculate_button.clone(), move |_| {
println!("button taped"); start_algorithm(&errors_label_for_handler, &all_text_views)
}) })
.on_click(); .on_click();
main_wrapper.append(&calculate_button); main_wrapper.append(&calculate_button);
main_wrapper.append(&table_of_calculated_values); main_wrapper.append(&table_of_calculated_values);
main_wrapper.append(&errors_label);
wrapper.append(&main_wrapper); wrapper.append(&main_wrapper);
} }