1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634//#![windows_subsystem = "windows"] // Tells windows compiler not to show console window
#![warn(
clippy::all,
)]
mod ui {
pub mod components;
pub mod icons;
pub mod style;
}
mod analysis {
pub mod monte_carlo;
pub mod root_sum_square;
pub mod structures;
}
mod io {
pub mod dialogs;
pub mod export_csv;
pub mod saved_state;
}
use analysis::structures::*;
use io::{export_csv, saved_state::*};
use ui::{components::*, style};
use colored::*;
use iced::{
keyboard, text_input, time, window, Application, Column, Command, Container, Element,
HorizontalAlignment, Length, Row, Settings, Subscription, Text,
};
use image::GenericImageView;
use std::path::PathBuf;
fn main() {
let bytes = include_bytes!("ui/icon.png");
let img = image::load_from_memory(bytes).unwrap();
let img_dims = img.dimensions();
let img_raw = img.into_rgba8().into_raw();
let icon = window::Icon::from_rgba(img_raw, img_dims.0, img_dims.1).unwrap();
let settings = Settings {
window: window::Settings {
size: (1024, 768),
resizable: true,
decorations: true,
min_size: Some((800, 600)),
max_size: None,
transparent: false,
always_on_top: false,
icon: Some(icon),
},
antialiasing: true,
..Default::default()
};
TolStack::run(settings).unwrap();
}
// The state of the application
#[derive(Debug, Clone)]
struct State {
last_save: std::time::Instant,
iss: style::IcedStyleSheet,
header: Header,
stack_editor: StackEditor,
analysis_state: AnalysisState,
dirty: bool,
saving: bool,
file_path: Option<PathBuf>,
}
impl Default for State {
fn default() -> Self {
State {
last_save: std::time::Instant::now(),
iss: style::IcedStyleSheet::default(),
header: Header::default(),
stack_editor: StackEditor::default(),
analysis_state: AnalysisState::default(),
dirty: false,
saving: false,
file_path: None,
}
}
}
impl State {
/// Marks the state as having unsaved changes
fn mark_unsaved_changes(&mut self) {
self.dirty = true;
}
fn stack_is_not_empty(&self) -> bool {
self.stack_editor
.tolerances
.iter()
.filter(|x| x.active)
.count()
> 0
}
}
// Messages - events for users to change the application state
#[derive(Debug, Clone)]
enum Message {
// Subcomponent messages
Header(HeaderAreaMessage),
StackEditor(StackEditorAreaMessage),
Analysis(AnalysisAreaMessage),
//
AutoSave,
Loaded(Result<(Option<PathBuf>, SavedState), io::saved_state::LoadError>),
Saved(Result<Option<PathBuf>, io::saved_state::SaveError>),
ExportComplete(Result<(), io::export_csv::SaveError>),
EventOccurred(iced_native::Event),
//
StyleUpdateAvailable(bool),
LoadedStyle(Result<Box<style::IcedStyleSheet>, style::LoadError>),
StyleSaved(Result<(), style::SaveError>),
//
HelpOpened,
}
// Loading state wrapper
#[derive(Debug)]
enum TolStack {
Loading,
Loaded(Box<State>),
}
impl Application for TolStack {
type Executor = iced::executor::Default;
type Message = Message;
type Flags = ();
fn new(_flags: ()) -> (TolStack, Command<Message>) {
(
TolStack::Loading,
Command::perform(SavedState::new(), Message::Loaded),
//Command::perform(SavedState::load(), Message::Loaded),
)
}
fn title(&self) -> String {
let dirty = match self {
TolStack::Loading => false,
TolStack::Loaded(state) => state.dirty,
};
let project_name = match self {
TolStack::Loading => String::from("Loading..."),
TolStack::Loaded(state) => {
if state.stack_editor.title.text.is_empty() {
String::from("New Stack")
} else {
state.stack_editor.title.text.clone()
}
}
};
let path_str = match self {
TolStack::Loading => String::from(""),
TolStack::Loaded(state) => match &state.file_path {
Some(path) => match path.to_str() {
Some(str) => format!(" - {}", String::from(str)),
None => String::from(""),
},
None => String::from(""),
},
};
format!(
" {}{}{} - TolStack Tolerance Analysis",
project_name,
if dirty { "*" } else { "" },
path_str,
)
}
// Update logic - how to react to messages sent through the application
fn update(&mut self, message: Message) -> Command<Message> {
let is_event = matches!(message, Message::EventOccurred(_));
if cfg!(debug_assertions) && !is_event {
println!(
"\n\n{}{}\n{:#?}",
chrono::offset::Local::now(),
" MESSAGE RECEIVED:".yellow(),
message
);
}
match self {
TolStack::Loading => {
match message {
// Take the loaded state and assign to the working state
Message::Loaded(Ok((path, state))) => {
*self = TolStack::Loaded(Box::new(State {
stack_editor: StackEditor::new()
.tolerances(state.tolerances)
.title(state.name),
header: Header::new(),
analysis_state: AnalysisState::new()
.set_inputs(state.n_iteration, state.assy_sigma),
file_path: path,
dirty: false,
saving: false,
..State::default()
}));
if cfg!(debug_assertions) {
return Command::perform(
style::IcedStyleSheet::load(),
Message::LoadedStyle,
);
} else {
return Command::none();
}
}
Message::Loaded(Err(_)) => {
*self = TolStack::Loaded(Box::new(State { ..State::default() }));
}
_ => {}
}
Command::none()
}
TolStack::Loaded(state) => {
match message {
Message::EventOccurred(iced_native::Event::Keyboard(event)) => {
if let keyboard::Event::KeyPressed {
key_code,
modifiers: _,
} = event
{
if key_code == keyboard::KeyCode::Tab {
for entry in &mut state.stack_editor.tolerances {
match &mut entry.state {
entry_tolerance::State::Idle {
button_edit: _,
button_move_up: _,
button_move_down: _,
} => {}
entry_tolerance::State::Editing { form_tolentry } => {
match &mut **form_tolentry {
FormState::Linear {
button_save: _,
button_delete: _,
description,
dimension,
tolerance_pos,
tolerance_neg,
sigma,
} => {
if description.is_focused() {
*description = text_input::State::default();
*dimension = text_input::State::focused();
} else if dimension.is_focused() {
*dimension = text_input::State::default();
*tolerance_pos =
text_input::State::focused();
} else if tolerance_pos.is_focused() {
*tolerance_pos =
text_input::State::default();
*tolerance_neg =
text_input::State::focused();
} else if tolerance_neg.is_focused() {
*tolerance_neg =
text_input::State::default();
*sigma = text_input::State::focused();
} else if sigma.is_focused() {
*sigma = text_input::State::default();
*description = text_input::State::focused();
}
}
FormState::Float {
button_save: _,
button_delete: _,
description,
diameter_hole,
diameter_pin,
tolerance_hole_pos,
tolerance_hole_neg,
tolerance_pin_pos,
tolerance_pin_neg,
sigma,
} => {
if description.is_focused() {
*description = text_input::State::default();
*diameter_hole =
text_input::State::focused();
} else if diameter_hole.is_focused() {
*diameter_hole =
text_input::State::default();
*tolerance_hole_pos =
text_input::State::focused();
} else if tolerance_hole_pos.is_focused() {
*tolerance_hole_pos =
text_input::State::default();
*tolerance_hole_neg =
text_input::State::focused();
} else if tolerance_hole_neg.is_focused() {
*tolerance_hole_neg =
text_input::State::default();
*diameter_pin =
text_input::State::focused();
} else if diameter_pin.is_focused() {
*diameter_pin =
text_input::State::default();
*tolerance_pin_pos =
text_input::State::focused();
} else if tolerance_pin_pos.is_focused() {
*tolerance_pin_pos =
text_input::State::default();
*tolerance_pin_neg =
text_input::State::focused();
} else if tolerance_pin_neg.is_focused() {
*tolerance_pin_neg =
text_input::State::default();
*sigma = text_input::State::focused();
} else if sigma.is_focused() {
*sigma = text_input::State::default();
*description = text_input::State::focused();
}
}
}
}
}
}
} else {
}
}
}
Message::EventOccurred(_) => {}
Message::AutoSave => {
if let Some(path) = &state.file_path {
state.saving = true;
let save_data = SavedState {
name: state.stack_editor.title.text.clone(),
tolerances: state.stack_editor.tolerances.clone(),
n_iteration: state.analysis_state.entry_form.n_iteration,
assy_sigma: state.analysis_state.entry_form.assy_sigma,
};
return Command::perform(
SavedState::save(save_data, path.clone()),
Message::Saved,
);
} else {
return Command::none();
}
}
Message::Header(area_header::HeaderAreaMessage::NewFile) => {
return Command::perform(SavedState::new(), Message::Loaded)
}
Message::Header(area_header::HeaderAreaMessage::OpenFile) => {
return Command::perform(SavedState::open(), Message::Loaded)
}
Message::Header(area_header::HeaderAreaMessage::SaveFile) => {
let save_data = SavedState {
name: state.stack_editor.title.text.clone(),
tolerances: state.stack_editor.tolerances.clone(),
n_iteration: state.analysis_state.entry_form.n_iteration,
assy_sigma: state.analysis_state.entry_form.assy_sigma,
};
match &state.file_path {
Some(path) => {
return Command::perform(
SavedState::save(save_data, path.clone()),
Message::Saved,
)
}
None => {
return Command::perform(
SavedState::save_as(save_data),
Message::Saved,
)
}
};
}
Message::Header(area_header::HeaderAreaMessage::SaveAsFile) => {
let save_data = SavedState {
name: state.stack_editor.title.text.clone(),
tolerances: state.stack_editor.tolerances.clone(),
n_iteration: state.analysis_state.entry_form.n_iteration,
assy_sigma: state.analysis_state.entry_form.assy_sigma,
};
return Command::perform(SavedState::save_as(save_data), Message::Saved);
}
Message::Header(area_header::HeaderAreaMessage::ExportCSV) => {
return Command::perform(
export_csv::serialize_csv(
state.analysis_state.model_state.results.export(),
),
Message::ExportComplete,
)
}
Message::Header(area_header::HeaderAreaMessage::AddTolLinear) => {
state.mark_unsaved_changes();
state.stack_editor.update(
area_stack_editor::StackEditorAreaMessage::NewEntryMessage((
String::from("New Linear Tolerance"),
Tolerance::Linear(LinearTL::default()),
)),
)
}
Message::Header(area_header::HeaderAreaMessage::AddTolFloat) => {
state.mark_unsaved_changes();
state.stack_editor.update(
area_stack_editor::StackEditorAreaMessage::NewEntryMessage((
String::from("New Float Tolerance"),
Tolerance::Float(FloatTL::default()),
)),
)
}
Message::Header(area_header::HeaderAreaMessage::Help) => {
return Command::perform(help(), |_| Message::HelpOpened);
}
Message::HelpOpened => {}
Message::ExportComplete(_) => {}
Message::StackEditor(message) => {
let recompute = matches!(message, area_stack_editor::StackEditorAreaMessage::LabelMessage(
editable_label::Message::FinishEditing,
) | area_stack_editor::StackEditorAreaMessage::EntryMessage(_, _));
state.stack_editor.update(message);
if recompute {
state.mark_unsaved_changes();
return Command::perform(do_nothing(), |_| {
Message::Analysis(
area_mc_analysis::AnalysisAreaMessage::NewMcAnalysisMessage(
form_new_mc_analysis::Message::Calculate,
),
)
});
}
}
Message::Analysis(
area_mc_analysis::AnalysisAreaMessage::NewMcAnalysisMessage(
form_new_mc_analysis::Message::Calculate,
),
) => {
if state.stack_is_not_empty() {
// Clone the contents of the stack editor tolerance list into the monte
// carlo simulation's input tolerance list.
state.analysis_state.input_stack =
state.stack_editor.tolerances.clone();
// Pass this message into the child so the computation gets kicked off.
let calculate_message =
area_mc_analysis::AnalysisAreaMessage::NewMcAnalysisMessage(
form_new_mc_analysis::Message::Calculate,
);
return state
.analysis_state
.update(calculate_message)
.map(Message::Analysis);
}
}
Message::Analysis(message) => {
// TODO collect commands and run at end instead of breaking at match arm.
return state.analysis_state.update(message).map(Message::Analysis);
}
Message::StyleUpdateAvailable(_) => {
return Command::perform(
style::IcedStyleSheet::load(),
Message::LoadedStyle,
)
}
Message::LoadedStyle(Ok(iss)) => {
state.iss = *iss;
}
Message::LoadedStyle(Err(style::LoadError::FormatError)) => println!(
"\n\n{}{}",
chrono::offset::Local::now(),
" Error loading style file".red()
),
Message::LoadedStyle(Err(style::LoadError::FileError)) => {
return Command::perform(
style::IcedStyleSheet::save(state.iss.clone()),
Message::StyleSaved,
)
}
Message::StyleSaved(_) => {}
Message::Saved(save_result) => {
state.saving = false;
match save_result {
Ok(path_result) => {
if let Some(path) = path_result {
state.file_path = Some(path);
state.last_save = std::time::Instant::now();
}
state.dirty = false;
}
Err(e) => {
state.dirty = true;
println!("Save failed with {:?}", e);
}
}
}
Message::Loaded(Ok((path, save_state))) => {
*state = Box::new(State {
stack_editor: StackEditor::new()
.tolerances(save_state.tolerances)
.title(save_state.name),
header: Header::new(),
analysis_state: AnalysisState::new()
.set_inputs(save_state.n_iteration, save_state.assy_sigma),
file_path: path,
dirty: false,
saving: false,
..State::default()
});
}
Message::Loaded(Err(_)) => println!(
"\n\n{}{}",
chrono::offset::Local::now(),
" Error loading save file".red()
),
}
Command::none()
}
}
}
fn subscription(&self) -> Subscription<Self::Message> {
match self {
TolStack::Loading => Subscription::none(),
TolStack::Loaded(state) => {
let State {
last_save: _,
iss,
header: _,
stack_editor: _,
analysis_state: _,
dirty,
saving,
file_path,
} = &**state;
let auto_save = if *dirty && !saving && file_path.is_some()
//&& last_save.elapsed().as_secs() > 5
{
time::every(std::time::Duration::from_secs(5)).map(|_| Message::AutoSave)
} else {
Subscription::none()
};
let style_reload = if cfg!(debug_assertions) {
iss.check_style_file().map(Message::StyleUpdateAvailable)
} else {
Subscription::none()
};
let tab_field = iced_native::subscription::events().map(Message::EventOccurred);
Subscription::batch(vec![auto_save, style_reload, tab_field])
}
}
}
// View logic - a way to display the state of the application as widgets that can produce messages
fn view(&mut self) -> Element<Message> {
match self {
TolStack::Loading => loading_message(),
TolStack::Loaded(state) => {
let State {
last_save: _,
iss,
header,
stack_editor,
analysis_state,
dirty: _,
saving: _,
file_path: _,
} = &mut **state;
let header = header.view(&iss).map(Message::Header);
let stack_editor = stack_editor.view(&iss).map(Message::StackEditor);
let analysis_state = analysis_state.view(&iss).map(Message::Analysis);
let content = Column::new().push(
Row::new()
.push(
Container::new(stack_editor)
.padding(iss.padding(&iss.home_padding))
.width(Length::Fill),
)
.push(Container::new(analysis_state).width(Length::Units(400))),
);
let gui: Element<_> = Container::new(Column::new().push(header).push(content))
.style(iss.container(&iss.home_container))
.into();
gui.explain(iced::Color::BLACK)
}
}
}
}
fn loading_message() -> Element<'static, Message> {
Container::new(
Text::new("Loading...")
.horizontal_alignment(HorizontalAlignment::Center)
.size(50),
)
.width(Length::Fill)
.height(Length::Fill)
.center_y()
.center_x()
.into()
}
async fn help() {
webbrowser::open("https://aevyrie.github.io/tolstack/book/getting-started").unwrap();
}
async fn do_nothing() {}