tukai 0.2.3

The app provides an interactive typing experience with switchable templates, designed to help users improve their typing speed and accuracy.
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
use ratatui::style::Style;
use rust_embed::RustEmbed;
use std::cell::{Ref, RefCell, RefMut};

use serde::{Deserialize, Serialize};

use std::path::{Path, PathBuf};
use std::{collections::HashMap, fmt::Display, hash::Hash};

use maplit::hashmap;
use ratatui::style::Color;

pub trait ToColor {
  /// Converts the `(u8, u8, u8)` tuple to a `Color::Rgb`
  ///
  /// # Example
  ///
  /// ```
  /// use ratatui::style::Color
  ///
  /// let rgb: (u8, u8, u8) = (128, 64, 255);
  /// let color = rgb.to_color();
  ///
  /// assert_eq!(color, Color::Rgb(128, 64, 255));
  /// ```
  fn to_color(self) -> Color;
}

/// Type alias for representing an RGB color as a tuple
type RgbColor = (u8, u8, u8);

impl ToColor for RgbColor {
  fn to_color(self) -> Color {
    Color::Rgb(self.0, self.1, self.2)
  }
}

/// Represents possible color combinations and preset types used in the layout.
///
/// Variants correspond to different semantic roles for colors:
/// - `Primary`: Main accent color.
/// - `Secondary`: Secondary accent color.
/// - `Text`: Standard text color.
/// - `TextReverse`: Inverted text color for contrast.
/// - `Background`: Background color.
/// - `Error`: Color used to indicate errors.
#[allow(dead_code)]
pub enum TukaiLayoutColorTypeEnum {
  Primary,
  Secondary,
  Text,
  TextReverse,
  Background,
  Error,
}

/// Layout name for Tukai application
/// Used for a switchable layout colors
///
/// Switchable with a `ctrl-s` shortcut
#[derive(PartialEq, Eq, Hash, Debug, Serialize, Deserialize, Clone)]
pub enum TukaiLayoutName {
  Iced,
  Rust,
  Anime,
  Deadpool,
  Wolverine,
  Goblin,
}

/// Display used in the Tukai paragraph block_title
impl Display for TukaiLayoutName {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    use TukaiLayoutName::*;

    let display_text = match self {
      Iced => "πŸ₯Ά Iced",
      Rust => "πŸ¦€ Rust",
      Anime => "🌸 Anime",
      Deadpool => "πŸ©ΈπŸ”ž Deadpool",
      Wolverine => "πŸ’ͺ🍺 Wolverine",
      Goblin => "🌳 Goblin",
    };

    write!(f, "{display_text}")
  }
}

/// Set of the colors used in the application.
pub struct TukaiLayoutColors {
  primary: RgbColor,
  text: RgbColor,
  text_current: RgbColor,
  text_current_bg: RgbColor,
  background: RgbColor,
  error: RgbColor,
}

impl TukaiLayoutColors {
  pub fn new(
    primary: RgbColor,
    text: RgbColor,
    text_current: RgbColor,
    text_current_bg: RgbColor,
    background: RgbColor,
    error: RgbColor,
  ) -> Self {
    Self {
      primary,
      text,
      text_current,
      text_current_bg,
      background,
      error,
    }
  }
}

/// Tukai layout includes all layouts
/// also, contains `transitions`, and the current selected layout name
pub struct TukaiLayout {
  // Set of the layouts
  layouts: HashMap<TukaiLayoutName, TukaiLayoutColors>,

  // Rules for switchable transition of the layout
  transitions: HashMap<TukaiLayoutName, TukaiLayoutName>,

  // Current selected layout name
  active_layout_name: TukaiLayoutName,
}

impl TukaiLayout {
  pub fn default() -> Self {
    use TukaiLayoutName::*;

    let layouts = hashmap! {
      Iced => {
        TukaiLayoutColors::new(
         (108, 181, 230),
         (232, 232, 232),
         (25, 74, 107),
         (200, 200, 200),
         (37, 40, 46),
         (214, 90, 90),
        )
      },
      Anime => {
        TukaiLayoutColors::new(
          (152, 117, 201),
          (222, 135, 174),
          (49, 45, 51),
          (222, 170, 146),
          (31, 27, 30),
          (227, 138, 138),
        )
      },
      Deadpool => {
        TukaiLayoutColors::new(
          (139, 35, 35),
          (210, 210, 210),
          (23, 23, 23),
          (210, 210, 210),
          (33, 29, 29),
          (110, 110, 110),
        )
      },
      Wolverine => {
        TukaiLayoutColors::new(
          (196, 166, 51),
          (200, 200, 200),
          (23,23,23),
          (210, 210, 210),
          (10, 14, 18),
          (110, 110, 110),
        )
      },
      Rust => {
        TukaiLayoutColors::new(
          (150, 63, 17),
          (255, 178, 137),
          (255, 178, 137),
          (150, 63, 17),
          (24, 8, 2),
          (120, 120, 120),
        )
      },
      Goblin => {
        TukaiLayoutColors::new(
          (82, 140, 25),
          (136, 207, 66),
          (220, 220, 220),
          (39, 61, 17),
          (32, 36, 30),
          (117, 71, 56),
        )
      }
    };

    // Define transtions for switch order
    let transitions = HashMap::from([
      (Iced, Anime),
      (Anime, Deadpool),
      (Deadpool, Wolverine),
      (Wolverine, Rust),
      (Rust, Goblin),
      (Goblin, Iced),
    ]);

    Self {
      layouts,
      transitions,
      active_layout_name: TukaiLayoutName::Iced,
    }
  }

  /// Returns the currect active layout name
  pub fn get_active_layout_name(&self) -> &TukaiLayoutName {
    &self.active_layout_name
  }

  /// Sets a new active layout name
  pub fn active_layout_name(&mut self, active_layout_name: TukaiLayoutName) {
    self.active_layout_name = active_layout_name;
  }

  /// Switches to a next layout, then returns that layout
  ///
  /// Check `self.transitions`.
  pub fn switch_to_next_layout(&mut self) -> TukaiLayoutName {
    if let Some(next_layout_name) = self.transitions.get(&self.active_layout_name) {
      self.active_layout_name = next_layout_name.clone();
    };

    self.active_layout_name.clone()
  }

  fn get_layout_colors(&self) -> &TukaiLayoutColors {
    self.layouts.get(&self.active_layout_name).unwrap()
  }

  pub fn get_primary_color(&self) -> Color {
    self.get_layout_colors().primary.to_color()
  }

  pub fn get_text_color(&self) -> Color {
    self.get_layout_colors().text.to_color()
  }

  pub fn get_text_current_color(&self) -> Color {
    self.get_layout_colors().text_current.to_color()
  }

  pub fn get_text_current_bg_color(&self) -> Color {
    self.get_layout_colors().text_current_bg.to_color()
  }

  pub fn get_error_color(&self) -> Color {
    self.get_layout_colors().error.to_color()
  }

  pub fn get_background_color(&self) -> Color {
    self.get_layout_colors().background.to_color()
  }
}

#[derive(RustEmbed)]
#[folder = "dictionary/"]
struct LanguageDictionary;

pub struct Language {
  // Language files paths from the `words` folder
  language_files: Vec<String>,

  // Current used language index
  current_index: usize,

  // Current used language shortcut
  lang_code: String,

  // Current selected language words
  words: Vec<String>,
}

impl Language {
  // Creates default empty list of the language files
  pub fn default() -> Self {
    Self {
      language_files: Vec::new(),
      current_index: 0,
      lang_code: String::from("en"),
      words: Vec::new(),
    }
  }

  pub fn init_lang_code(&mut self) {
    let filename = &self.language_files[self.current_index];

    let lang_code = Path::new(filename)
      .file_stem()
      .and_then(|s| s.to_str())
      .unwrap_or("unknown")
      .to_string();

    self.lang_code = lang_code;
  }

  /// Load language files from the `words` folder
  pub fn init(mut self) -> Self {
    if let Ok(language_files) = self.load_language_files() {
      self.language_files = language_files;
    }

    // If language dictionary files were founded
    // Sets the words
    if !self.language_files.is_empty()
      && let Ok(words) = self.load_language_words()
    {
      self.words = words;
    }

    self
  }

  pub fn current_index(&mut self, index: usize) {
    self.current_index = index;
    self.init_lang_code();
  }

  #[allow(unused)]
  pub fn get_current_index(&self) -> &usize {
    &self.current_index
  }

  /// Switches a current language
  pub fn switch_language(&mut self) -> usize {
    self.current_index += 1;

    if self.current_index >= self.language_files.len() {
      self.current_index = 0;
    }

    self.init_lang_code();
    self.current_index
  }

  /// Returns the paths of all available language files in the `words` folder.
  ///
  /// So i.e. available languages
  pub fn load_language_files(&self) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let languages = LanguageDictionary::iter()
      .map(|file| file.to_string())
      .collect::<Vec<String>>();

    // Maybe in feature manual load custom languages
    //
    // let languages = entries
    //   .filter_map(|entry| entry.ok())
    //   .filter(|entry| entry.path().is_file())
    //   .map(|entry| entry.path())
    //   .collect::<Vec<PathBuf>>();

    Ok(languages)
  }

  /// Returns current selected languages words from the language file
  ///
  /// So i.e. language words
  pub fn load_language_words(&self) -> Result<Vec<String>, Box<dyn std::error::Error>> {
    let language_file_path = self
      .language_files
      .get(self.current_index)
      .ok_or("Not found a language dictionary file")?;

    let file = LanguageDictionary::get(language_file_path).unwrap();

    let words = std::str::from_utf8(&file.data)?
      .lines()
      .flat_map(|line| {
        line
          .split_whitespace()
          .map(String::from)
          .collect::<Vec<String>>()
      })
      .collect::<Vec<String>>();

    Ok(words)
  }

  pub fn get_lang_code(&self) -> &String {
    &self.lang_code
  }
}

#[derive(Serialize, Deserialize, Hash, PartialEq, Eq, Debug, Clone)]
/// Represents the available durations for the test
///
/// This enum defines default durations
///
/// # Variants
/// - `ThirtySec` - 30 seconds typing duration
/// - `Minute` - 60 seconds typing duration
/// - `ThreeMinutes` - 180 seconds typing duration
pub enum TypingDuration {
  FifteenSec,
  ThirtySec,
  Minute,
  ThreeMinutes,
}

impl Default for TypingDuration {
  fn default() -> Self {
    Self::Minute
  }
}

impl TypingDuration {
  pub fn as_seconds(&self) -> usize {
    use TypingDuration::*;

    match self {
      FifteenSec => 15,
      ThirtySec => 30,
      Minute => 60,
      ThreeMinutes => 180,
    }
  }
}

#[allow(unused)]
pub trait ConfigBuilder<T> {
  fn new() -> Self;
  fn build(self) -> T;
}

pub struct TukaiConfig {
  // Path to the storage file
  file_path: PathBuf,

  // Choosen layout
  layout: RefCell<TukaiLayout>,

  // Current language
  language: RefCell<Language>,

  // App background is transparent
  pub has_transparent_bg: bool,

  // Typing duration
  pub typing_duration: TypingDuration,
}

impl TukaiConfig {
  pub fn default() -> Self {
    Self {
      file_path: PathBuf::from("tukai.bin"),
      layout: RefCell::new(TukaiLayout::default()),
      language: RefCell::new(Language::default().init()),
      has_transparent_bg: false,
      typing_duration: TypingDuration::default(),
    }
  }

  pub fn get_layout(&self) -> Ref<TukaiLayout> {
    self.layout.borrow()
  }

  pub fn get_language(&self) -> Ref<Language> {
    self.language.borrow()
  }

  pub fn get_layout_mut(&mut self) -> RefMut<TukaiLayout> {
    self.layout.borrow_mut()
  }

  pub fn get_language_mut(&mut self) -> RefMut<Language> {
    self.language.borrow_mut()
  }

  pub fn get_file_path(&self) -> &PathBuf {
    &self.file_path
  }

  /// Toggles the background between transparent and the layout color.
  ///
  /// Flips the `has_transparent_bg` flag and returns the updated state.
  ///
  /// # Returns
  /// The new state of the background transparency (`true` if transparent, `false` otherwise).
  pub fn toggle_transparent_bg(&mut self) -> bool {
    self.has_transparent_bg = !self.has_transparent_bg;
    self.has_transparent_bg
  }

  /// Switches the typing duration.
  ///
  /// Options:
  /// 1. Minute
  /// 2. Three minutes
  /// 3. Fifteen seconds
  /// 4. Thirty seconds
  pub fn switch_typing_duration(&mut self) -> TypingDuration {
    self.typing_duration = match self.typing_duration {
      TypingDuration::Minute => TypingDuration::ThreeMinutes,
      TypingDuration::ThreeMinutes => TypingDuration::FifteenSec,
      TypingDuration::FifteenSec => TypingDuration::ThirtySec,
      TypingDuration::ThirtySec => TypingDuration::Minute,
    };

    self.typing_duration.clone()
  }

  /// Returns the background color of the selected layout.
  ///
  /// If `has_transparent_bg` is `true`, no background color is applied.
  pub fn get_bg_color(&self) -> Style {
    let style = Style::default();
    if self.has_transparent_bg {
      style
    } else {
      style.bg(self.get_layout().get_background_color())
    }
  }
}

pub struct TukaiConfigBuilder {
  // Path to the `language file`
  file_path: Option<PathBuf>,

  // Selected layout
  layout: Option<RefCell<TukaiLayout>>,

  // Selected language
  language: Option<RefCell<Language>>,

  // Has application background transparent
  has_transparent_bg: bool,

  // Typing duration per run
  typing_duration: Option<TypingDuration>,
}

impl TukaiConfigBuilder {
  pub fn new() -> Self {
    Self {
      file_path: None,
      layout: None,
      language: None,
      has_transparent_bg: true,
      typing_duration: None,
    }
  }

  #[allow(unused)]
  pub fn file_path<P: AsRef<Path>>(mut self, file_path: P) -> Self {
    self.file_path = Some(file_path.as_ref().to_path_buf());
    self
  }

  #[allow(unused)]
  pub fn layout(mut self, layout: TukaiLayout) -> Self {
    self.layout = Some(RefCell::new(layout));
    self
  }

  pub fn build(self) -> TukaiConfig {
    let config_default = TukaiConfig::default();

    TukaiConfig {
      file_path: self.file_path.unwrap_or(config_default.file_path),
      layout: self.layout.unwrap_or(config_default.layout),
      language: self.language.unwrap_or(config_default.language),
      has_transparent_bg: self.has_transparent_bg,
      typing_duration: self
        .typing_duration
        .unwrap_or(config_default.typing_duration),
    }
  }
}