DEV Community

Cover image for Building a Terminal-Based Morse Code Translator
Tramposo
Tramposo

Posted on

Building a Terminal-Based Morse Code Translator

Project Overview

This Morse code translator is a terminal application that allows real-time translation between text and Morse code. It features a color-coded, interactive interface and supports letters, numbers, and common punctuation marks.

Terminal UI of a Morse code translator supporting letters, numbers and punctuation marks

Let's break down some key parts of the code to see these concepts in action.

Code Breakdown

The MorseTranslator Struct

pub struct MorseTranslator {
    to_morse: HashMap<char, String>,
    from_morse: HashMap<String, char>,
}

impl MorseTranslator {
    pub fn new() -> Self {
        let mut to_morse = HashMap::new();
        let mut from_morse = HashMap::new();

        // Populate with hashmaps...

        MorseTranslator { to_morse, from_morse }
    }

    pub fn to_morse(&self, text: &str) -> String {
        text.to_uppercase()
            .chars()
            .map(|c| {
                if c.is_whitespace() {
                    "  ".to_string()
                } else {
                    self.to_morse.get(&c).cloned().unwrap_or_else(|| c.to_string())
                }
            })
            .collect::<Vec<String>>()
            .join(" ")
    }

    // from_morse method...
}
Enter fullscreen mode Exit fullscreen mode

This struct allows:

  • Use of HashMap for efficient lookup
  • Implementation of methods
  • Rust's iterator methods like map and collect

Terminal UI Handling

pub fn run_terminal_ui() -> crossterm::Result<()> {
    let mut text = String::new();
    let mut morse = String::new();
    let translator = MorseTranslator::new();
    let mut active_field = 0; // 0 for text, 1 for morse

    execute!(stdout(), Hide)?;

    loop {
        // Clear screen and set colors...

        match read()? {
            Event::Key(event) => match event.code {
                KeyCode::Esc => break,
                KeyCode::Tab => {
                    active_field = 1 - active_field;
                    // Update translations...
                },
                KeyCode::Char(c) => {
                    // Handle character input...
                },
                _ => {}
            },
            _ => {}
        }
    }

    execute!(stdout(), Show)?;
    Ok(())
}
Enter fullscreen mode Exit fullscreen mode

This function showcases:

  • Error handling with the ? operator
  • Pattern matching with match
  • Mutable state management in a loop

Conclusion and Next Steps

Building this Morse code translator is an engaging way to learn Rust's fundamentals while creating something useful. As you become more comfortable with these concepts, you can extend the project in various ways:

  • Add sound output for Morse code
  • Implement file I/O for saving and loading translations

The full code for this project is available on GitHub. Feel free to fork, experiment, and learn.

Top comments (0)