Search code examples
rustsdl-2keyboard-events

SDL2 not triggering on keys in terminal?


I'm currently using sdl2 (0.35.2) in a Rust application to detect Key Events but it seems to only be triggering for the Event::Quit and nothing else. I have a very simple example like this

use sdl2;
use sdl2::event::Event;
use sdl2::keyboard::Keycode;

fn main() {

    let sdl_context = sdl2::init().unwrap();
    let mut event_pump = sdl_context.event_pump().unwrap();

    'event_loop:loop {
        for event in event_pump.poll_iter() {
            match event {
                Event::Quit { .. } => {
                    println!("Quit"); break 'event_loop;
                },
                Event::KeyDown { keycode:Some(Keycode::Escape), .. } => {
                    println!("Escape"); break 'event_loop;
                },
                Event::KeyDown { .. } => {
                    println!("KeyDown Triggered");
                },
                _ => {}
            }
        }
    }

}

But both of the Event:KeyDown matches never trigger, only able to get Event::Quit to trigger with Ctrl+C. I'm doing this on Debian in a basic terminal.


Solution

  • All SDL2 backends require creating a SDL_Window to receive keyboard events; they don't handle console/terminal input.

    SDL 1.2 has back-ends for AAlib & libcaca but they weren't ported forward to SDL2 :(

    Options:

    • Create a window.
    • Drop back to SDL 1.2.
    • Port SDL 1.2's AAlib/libcaca backends to SDL2.