Compare commits

..

No commits in common. "0d2987a9686b168ba20de76f53422ff301fb1132" and "cd6403fb32d9ca245fa5c9046cdc1bf85fedb227" have entirely different histories.

5 changed files with 120 additions and 122 deletions

View File

@ -1,9 +1,8 @@
use std::collections::HashMap;
use std::sync::LazyLock;
use crate::{
controller::view_utils::{hamming_code_input_utils::*, input_utils::*},
model::{models::*, Result},
model::models::*,
};
static SYNDROMES: LazyLock<HashMap<usize, (bool, bool, bool)>> = LazyLock::new(|| {
@ -18,31 +17,32 @@ static SYNDROMES: LazyLock<HashMap<usize, (bool, bool, bool)>> = LazyLock::new(|
])
});
pub fn hamming(raw_input: String, mode: HammingMode) -> Result<String> {
pub fn hamming(raw_input: String, mode: HammingMode) -> Result<String, String> {
let length_of_code: usize = mode.clone() as usize;
let prepared_input: String = processing_input(&raw_input);
let (first_condition, second_condition): (bool, bool) =
let (fc, sc): (bool, bool) =
check_correct_binary_code(&raw_input, &prepared_input, length_of_code);
if raw_input.is_empty() {
Err("Введите код.".into())
} else if !first_condition || !second_condition {
Err("Проверьте корректность ввода.".into())
if !fc || !sc {
Err("Ошибка. Проверьте корректность ввода.".to_string())
} else {
let mut data: String = String::new();
let prepared_data: Vec<u8> = from_string_to_vec_bits(prepared_input);
match mode {
HammingMode::Encrypt => Ok(hamming_encrypt_data(&prepared_data, length_of_code)),
HammingMode::Decrypt => Ok(hamming_decrypt_data(&prepared_data, length_of_code)),
HammingMode::Encrypt => hamming_encrypt_data(&prepared_data, &mut data, length_of_code),
HammingMode::Decrypt => hamming_decrypt_data(&prepared_data, &mut data, length_of_code),
}
Ok(data)
}
}
pub fn hamming_encrypt_data(data: &[u8], length_of_code: usize) -> String {
pub fn hamming_encrypt_data(data: &Vec<u8>, result_string: &mut String, length_of_code: usize) {
let mut i: usize = length_of_code;
let mut result = String::new();
while i <= data.len() {
let data_bits: &[u8] = &data[i - length_of_code..i];
@ -51,23 +51,17 @@ pub fn hamming_encrypt_data(data: &[u8], length_of_code: usize) -> String {
data_bits[0] ^ data_bits[2] ^ data_bits[3],
data_bits[1] ^ data_bits[2] ^ data_bits[3],
);
result.push_str(
format!(
result_string.push_str(&*format!(
"{check_bit_1}{}{check_bit_2}{}{check_bit_3}{}{} ",
data_bits[0], data_bits[1], data_bits[2], data_bits[3]
)
.as_str(),
);
));
i += length_of_code;
}
result
}
pub fn hamming_decrypt_data(data: &[u8], length_of_code: usize) -> String {
pub fn hamming_decrypt_data(data: &Vec<u8>, result_string: &mut String, length_of_code: usize) {
let mut general_length: usize = length_of_code;
let mut result = String::new();
let mut errors: String = String::new();
@ -84,7 +78,7 @@ pub fn hamming_decrypt_data(data: &[u8], length_of_code: usize) -> String {
general_length += length_of_code;
continue;
} else {
let error_position: &usize = SYNDROMES
let error_position: &usize = syndromes
.iter()
.find(move |&(&_error_position, &error)| error == checked_bits)
.unwrap()
@ -120,11 +114,11 @@ pub fn hamming_decrypt_data(data: &[u8], length_of_code: usize) -> String {
if !data.is_empty() {
if errors.is_empty() {
result.push_str("Все коды корректны.");
result_string.push_str("Все коды корректны.");
} else {
result.push_str(errors.as_str());
result_string.push_str(errors.as_str());
}
} else {
result_string.push_str("Введите код для проверки.")
}
}
result
}

View File

@ -1,12 +1,9 @@
use gtk4 as gtk;
use crate::{
model::{models::*, Result},
model_utils::hamming_code_seven_four::*,
};
use crate::{model::models::*, model_utils::hamming_code_seven_four::*};
use gtk::{prelude::*, *};
pub fn start_hamming_algorithm(input: &TextView, state: bool) -> Result<String> {
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()
@ -16,19 +13,29 @@ pub fn start_hamming_algorithm(input: &TextView, state: bool) -> Result<String>
.parse()
.unwrap();
let operation = if !state {
let operation = if mode {
HammingMode::Encrypt
} else {
HammingMode::Decrypt
};
hamming(parsed_input, operation)
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: &str, prepared_input: &str, l: usize) -> (bool, bool) {
let first_condition: bool = prepared_input.len() % l == 0;
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 = input.chars().all(|c| c == '1' || c == '0' || c == ' ');
let second_condition: bool = prepared_input.len() % l == 0;
(first_condition, second_condition)
}

View File

@ -4,11 +4,14 @@ use std::{collections::VecDeque, sync::LazyLock};
use gtk::{
builders::{BoxBuilder, ButtonBuilder, LabelBuilder},
prelude::{BoxExt, ButtonExt, ObjectExt, WidgetExt},
prelude::{BoxExt, ObjectExt, WidgetExt},
Box, Button, Label, Revealer, RevealerTransitionType,
};
use crate::model::builder_traits::Product;
use crate::{
event_handlers::button_event_handlers::BtnEventHandler,
model::{builder_traits::Product, models::EventHandler},
};
use tokio::{
task::{spawn, JoinHandle},
@ -107,9 +110,10 @@ impl InfoBarBuilder {
let info_bar_to_close = info_bar.clone();
info_bar_close_btn.connect_clicked(move |_| {
EventHandler::new(info_bar_close_btn.clone(), move |_| {
info_bar_to_close.set_reveal_child(false);
});
})
.on_click();
&INFO_BAR_INSTANCE
}
@ -127,7 +131,7 @@ impl InfoBarBuilder {
}
}
impl Product<InfoBarBuilder, Revealer> for InfoBar {
impl Product<InfoBarBuilder, &'static Revealer> for InfoBar {
fn builder() -> InfoBarBuilder {
InfoBarBuilder {
label: Label::builder(),
@ -136,7 +140,7 @@ impl Product<InfoBarBuilder, Revealer> for InfoBar {
}
}
fn get(&self) -> &'static Revealer {
fn get(self) -> &'static Revealer {
&INFO_BAR_INSTANCE.instance
}
}

View File

@ -5,12 +5,10 @@ use gtk::{prelude::*, *};
pub type InputLabel = String;
#[derive(Clone, Debug)]
#[derive(Clone)]
pub struct Input {
component: Box,
input: TextView,
input_label: Label,
input_frame: Frame,
}
pub struct InputBuilder {
@ -31,39 +29,31 @@ impl Product<InputBuilder, Box> for Input {
}
}
fn get(&self) -> &Box {
&self.component
fn get(self) -> Box {
self.component
}
}
impl Input {
pub fn get_input(&self) -> &TextView {
&self.input
}
pub fn get_frame(&self) -> &Frame {
&self.input_frame
}
pub fn get_label(&self) -> &Label {
&self.input_label
pub fn get_input(self) -> TextView {
self.input
}
}
impl InputBuilder {
pub fn label(mut self, label: &str) -> Self {
self.label = label.into();
pub fn set_label(mut self, label: &str) -> Self {
self.label = String::from(label);
self
}
pub fn align(mut self, align: Alignment) -> Self {
pub fn set_align(mut self, align: Alignment) -> Self {
self.align = align;
self
}
pub fn margins(mut self, margin: MarginData) -> Self {
pub fn set_margins(mut self, margin: MarginData) -> Self {
self.margins = margin;
self
@ -72,7 +62,7 @@ impl InputBuilder {
pub fn build(self, monospace: bool, wrap_mode: WrapMode, input_height: i32) -> Input {
let input_component = Box::new(Orientation::Vertical, 0);
let text_view_label = Label::builder()
let input_label = Label::builder()
.halign(self.align.horizontal)
.valign(self.align.vertical)
.set_margin(self.margins)
@ -91,14 +81,12 @@ impl InputBuilder {
.set_margin(MarginData::MultipleMargin((0, 5, 0, 5)))
.build();
input_component.append(&text_view_label);
input_component.append(&input_label);
input_component.append(&text_view_input_frame);
Input {
component: input_component,
input: text_view_input.clone(),
input_frame: text_view_input_frame.clone(),
input_label: text_view_label.clone(),
input: text_view_input,
}
}
}

View File

@ -1,8 +1,12 @@
use std::cell::Cell;
use std::rc::Rc;
use std::{cell::Cell, rc::Rc};
use crate::{
model::{builder_traits::Product, models::SignalReduce, Frequency},
event_handlers::button_event_handlers::BtnEventHandler,
model::{
builder_traits::Product,
models::{EventHandler, SignalReduce},
ResultValue,
},
model_utils::signal_reducer::{
coef_of_signal_reduce, full_resistance_of_capacitor, reactive_resistance_of_capacitor,
voltage_from_signal_source,
@ -15,7 +19,7 @@ use crate::{
};
use gtk::{
prelude::{BoxExt, ButtonExt, Cast, CastNone, GridExt, ListItemExt, ListModelExt},
prelude::{BoxExt, Cast, CastNone, GridExt, ListItemExt},
Align, WrapMode, *,
};
use gtk4 as gtk;
@ -23,6 +27,8 @@ use gtk4 as gtk;
pub fn signal_reducing_page(wrapper: &Box) {
let values = Rc::new(Cell::new(SignalReduce::default()));
let last_query: Vec<TreeIter> = Vec::new();
let info_bar = InfoBar::get_instance();
let (input_height, monospace, input_wrapping): (i32, bool, WrapMode) =
@ -38,15 +44,22 @@ pub fn signal_reducing_page(wrapper: &Box) {
vertical: Align::Fill,
};
let input_labels: [&str; 6] = ["l, м:", "Rм, Ом", "Cм, пФ:", "Rи, Ом:", "Vи, мВ", "f, мГц:"];
let input_labels: [&str; 6] = [
"l, м:",
"Rм, Ом:",
"Cм, пФ:",
"Vи, мВ",
"Rи, Ом:",
"f, мГц:",
];
let all_inputs: Vec<Input> = input_labels
.iter()
.map(move |label| {
Input::builder()
.label(label)
.margins(MarginData::EqualsMargin(6))
.align(input_label_alignment)
.set_label(label)
.set_margins(MarginData::EqualsMargin(5))
.set_align(input_label_alignment)
.build(monospace, input_wrapping, input_height)
})
.collect();
@ -59,7 +72,7 @@ pub fn signal_reducing_page(wrapper: &Box) {
}
input_block.attach(
elem.clone().get(),
&elem.clone().get(),
(id as i32) - (3 * row_position),
row_position,
1,
@ -69,24 +82,16 @@ pub fn signal_reducing_page(wrapper: &Box) {
let calculate_button = Button::builder().label("Расчитать").build();
let result_table_headers_labels: [&str; 4] = ["f, МГц", "Xc, Ом", "Vп, мВ", "ζ"];
let result_table_headers_labels: [&str; 4] = ["f, МГц", "Xc, пФ", "Vп, мВ", "ζ"];
let model = gio::ListStore::new::<Frequency>();
let model_for_events = model.clone();
let model = gio::ListStore::new::<ResultValue>();
for number in (0..=100).step_by(5) {
if number == 0 {
model.append(&Frequency::new(1.0));
} else if (number >= 70 && number % 10 == 0) || (number < 70 && number % 5 == 0) {
model.append(&Frequency::new(number as f64));
}
}
let cloned_model = model.clone();
let selection_model = NoSelection::new(Some(model));
let selection_model = SingleSelection::new(Some(model));
let result_table = ColumnView::builder()
.reorderable(true)
.show_row_separators(true)
.model(&selection_model)
.build();
@ -107,7 +112,7 @@ pub fn signal_reducing_page(wrapper: &Box) {
.downcast_ref::<ListItem>()
.expect("Needs to be ListItem")
.item()
.and_downcast::<Frequency>()
.and_downcast::<ResultValue>()
.expect("The item has to be an `IntegerObject`.");
let cell_label = list_item
@ -117,42 +122,38 @@ pub fn signal_reducing_page(wrapper: &Box) {
.and_downcast::<Label>()
.expect("The child has to be a `Label`.");
let result_values = values_for_factory.get();
let result_values = values_for_factory.clone().get();
let reactive_resist: f64 = reactive_resistance_of_capacitor(
result_values.wire_capacity * 10f64.powi(-12),
result_values.length,
cell_value.frequency() * 10f64.powi(6),
result_values.2,
result_values.0,
cell_value.value(),
);
let full_resistance: f64 = full_resistance_of_capacitor(
reactive_resist,
result_values.source_resistance,
result_values.wire_resistance,
result_values.length,
result_values.4,
result_values.1,
result_values.0,
);
let signal_source_voltage: f64 = voltage_from_signal_source(
result_values.source_voltage * 10f64.powi(-3),
reactive_resist,
full_resistance,
) * 1000.0;
let signal_source_voltage: f64 =
voltage_from_signal_source(result_values.3, reactive_resist, full_resistance);
let coef: f64 = coef_of_signal_reduce(signal_source_voltage, signal_source_voltage);
match label {
"f, МГц" => {
cell_label.set_label(&cell_value.frequency().to_string());
cell_label.set_label(&cell_value.value().to_string());
}
"Xc, Ом" => {
cell_label.set_label(format!("{0:.1$}", reactive_resist, 6).as_str());
"Xc, пФ" => {
cell_label.set_label(&reactive_resist.to_string());
}
"Vп, мВ" => {
cell_label.set_label(format!("{0:.1$}", signal_source_voltage, 6).as_str());
cell_label.set_label(&signal_source_voltage.to_string());
}
"ζ" => {
let coef: f64 =
coef_of_signal_reduce(result_values.source_voltage, signal_source_voltage);
cell_label.set_label(format!("{0:.1$}", coef, 6).as_str());
cell_label.set_label(&coef.to_string());
}
_ => {}
}
@ -178,12 +179,14 @@ pub fn signal_reducing_page(wrapper: &Box) {
.vexpand(true)
.build();
calculate_button.connect_clicked(move |_| match parse_fields(all_inputs.clone()) {
EventHandler::new(calculate_button.clone(), move |_| {
match parse_fields(all_inputs.clone()) {
Ok(results) => {
values.set(results);
model_for_events.items_changed(0, 0, 18);
model_for_events.items_changed(18, 18, 0);
let tree_iter: TreeIter = cloned_model.append(&ResultValue::new(results.5));
last_query.append(tree_iter);
}
Err(error) => {
let error_kind: Option<&str> = get_error_message(error);
@ -191,7 +194,9 @@ pub fn signal_reducing_page(wrapper: &Box) {
info_bar.set_text_label(error_kind);
info_bar.show_infobar(5u64);
}
});
}
})
.on_click();
wrapper.append(&input_block);
wrapper.append(&calculate_button);