datafusion_tui/events/mod.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License. You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18mod key;
19
20use crossterm::event::KeyEvent;
21use log::debug;
22
23pub use self::key::Key;
24
25use crossterm::event;
26use std::time::Duration;
27use std::{sync::mpsc, thread};
28
29pub enum InputEvent {
30 /// Key event occured.
31 Input(KeyEvent),
32 /// Tick event occured
33 Tick,
34}
35
36pub enum Event {
37 KeyInput(Key),
38 Tick,
39}
40
41pub struct Events {
42 rx: mpsc::Receiver<Event>,
43 // Need to be kept around to prevent disposing the sender side.
44 _tx: mpsc::Sender<Event>,
45}
46
47impl Events {
48 pub fn new(tick_rate: Duration) -> Events {
49 let (tx, rx) = mpsc::channel();
50
51 let event_tx = tx.clone(); // the thread::spawn own event_tx
52 thread::spawn(move || {
53 loop {
54 // poll for tick rate duration, if no event, sent tick event.
55 if crossterm::event::poll(tick_rate).unwrap() {
56 if let event::Event::Key(key) = event::read().unwrap() {
57 debug!("Key Event: {:?}", key);
58 let key = Key::from(key);
59 event_tx.send(Event::KeyInput(key)).unwrap();
60 }
61 }
62 event_tx.send(Event::Tick).unwrap();
63 }
64 });
65
66 Events { rx, _tx: tx }
67 }
68
69 /// Attempts to read an event.
70 /// This function block the current thread.
71 pub fn next(&self) -> Result<Event, mpsc::RecvError> {
72 self.rx.recv()
73 }
74}