crossterm icon indicating copy to clipboard operation
crossterm copied to clipboard

How to restrict `crossterm::event::read` to future events?

Open Lioness100 opened this issue 3 years ago • 5 comments
trafficstars

crossterm::event::read is picking up key presses that occur before the function is even called. How do I prevent this?

Lioness100 avatar Aug 14 '22 15:08 Lioness100

Do you have a (minimum) working example?

Piturnah avatar Aug 14 '22 16:08 Piturnah

I am not entirely sure what you mean. Read will return directly if there are events to be read. You can use poll to check if there are events to read. Read is not meant to be an always blocking read waiting for the next event to occur.

TimonPost avatar Aug 14 '22 17:08 TimonPost

Do you have a (minimum) working example?

Run the example event-read and press a key immediately, while it's still building. The key event will still be grabbed by read

Read is not meant to be an always blocking read waiting for the next event to occur

Is there any way to get this behavior?

Lioness100 avatar Aug 14 '22 21:08 Lioness100

Why you wold care about this though? programs are not meant to be used when they're building

You can build then run the executable from target/debug/exe so you don't get this behavior

Also what you're describing is something that's not due to crossterm but its the way that all shell works, they buffer any pending key input and give it to the next available reader.

sigmaSd avatar Aug 14 '22 21:08 sigmaSd

The example of tracking keys whilst building was just a convenient example that was easy to reproduce, not my real use case. Regardless, I think I fixed it by collecting all buffered input before the read function is used for real:

while event::poll(Duration::from_millis(1)).unwrap() {
	event::read().unwrap();
}

loop {
	if let Ok(...) = event::read() {
		// ...
	}
}

When using Duration::from_millis(0) it only worked sometimes, which I don't understand, but it seems? to be fixed with from_millis(1). Is there anything definitely bad about this approach?

Lioness100 avatar Aug 14 '22 23:08 Lioness100