crossterm-rs / crossterm

Cross platform terminal library rust
MIT License
3.27k stars 279 forks source link

Can not capture `MediaKeyCode`s #897

Open ZeroByter opened 5 months ago

ZeroByter commented 5 months ago

Describe the bug When listening to keyboard events, we should be able to also capture media key code events, such as for example MediaKeyCode::Stop, but this doesn't work.

To Reproduce Run this code:

use std::io::stdout;
use std::time::Duration;

use crossterm::event::{
    self, Event, KeyCode, KeyEvent, KeyboardEnhancementFlags, MediaKeyCode,
    PopKeyboardEnhancementFlags, PushKeyboardEnhancementFlags,
};
use crossterm::execute;
use crossterm::terminal::{
    disable_raw_mode, enable_raw_mode, EnterAlternateScreen, LeaveAlternateScreen,
};

fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let mut stdout = stdout();

    execute!(stdout, EnterAlternateScreen)?;

    enable_raw_mode();

    let push_result = execute!(
        stdout,
        PushKeyboardEnhancementFlags(
            KeyboardEnhancementFlags::DISAMBIGUATE_ESCAPE_CODES
                | KeyboardEnhancementFlags::REPORT_ALTERNATE_KEYS
        )
    );

    println!("PushKeyboardEnhancementFlags: {:?}", push_result);

    loop {
        // Wait for an event with a timeout of 500 milliseconds
        if crossterm::event::poll(Duration::from_millis(500))? {
            // Read the event
            if let Event::Key(KeyEvent {
                code,
                modifiers,
                kind,
                state,
            }) = event::read()?
            {
                println!("modifiers: {:?}", modifiers);
                println!("kind: {:?}", kind);
                println!("state: {:?}", state);

                match code {
                    KeyCode::Media(code) => match code {
                        MediaKeyCode::Stop => {
                            println!("Stop!")
                        }
                        _ => println!("Other media key pressed: {:?}", code),
                    },
                    // Handle other KeyCode variants here
                    KeyCode::Char('q') => {
                        println!("Exiting...");
                        break;
                    }
                    _ => println!("Other key pressed: {:?}", code),
                }
            }
        }
    }

    let pop_result = execute!(stdout, PopKeyboardEnhancementFlags);

    println!("PushKeyboardEnhancementFlags: {:?}", pop_result);

    execute!(stdout, LeaveAlternateScreen)?;

    disable_raw_mode();

    Ok(())
}

Expected behavior We should see the MediaKeyCode events triggering, but they do not.

OS Linux (Ubuntu 20.04)

Terminal/Console Standard default GNOME terminal.