|
1 | 1 | use crate::notify_mutex::NotifyableMutex;
|
2 |
| -use crossbeam_channel::{unbounded, Receiver}; |
| 2 | +use anyhow::Result; |
| 3 | +use crossbeam_channel::{unbounded, Receiver, Sender}; |
3 | 4 | use crossterm::event::{self, Event};
|
4 | 5 | use std::{
|
| 6 | + process, |
5 | 7 | sync::{
|
6 | 8 | atomic::{AtomicBool, Ordering},
|
7 | 9 | Arc,
|
@@ -44,33 +46,12 @@ impl Input {
|
44 | 46 | let arc_desired = Arc::clone(&desired_state);
|
45 | 47 | let arc_current = Arc::clone(¤t_state);
|
46 | 48 |
|
47 |
| - thread::spawn(move || loop { |
48 |
| - if arc_desired.get() { |
49 |
| - if !arc_current.load(Ordering::Relaxed) { |
50 |
| - log::info!("input polling resumed"); |
51 |
| - |
52 |
| - tx.send(InputEvent::State(InputState::Polling)) |
53 |
| - .expect("send state failed"); |
54 |
| - } |
55 |
| - arc_current.store(true, Ordering::Relaxed); |
56 |
| - |
57 |
| - if let Some(e) = Self::poll(POLL_DURATION) |
58 |
| - .expect("failed to pull events.") |
59 |
| - { |
60 |
| - tx.send(InputEvent::Input(e)) |
61 |
| - .expect("send input failed"); |
62 |
| - } |
63 |
| - } else { |
64 |
| - if arc_current.load(Ordering::Relaxed) { |
65 |
| - log::info!("input polling suspended"); |
66 |
| - |
67 |
| - tx.send(InputEvent::State(InputState::Paused)) |
68 |
| - .expect("send state failed"); |
69 |
| - } |
70 |
| - |
71 |
| - arc_current.store(false, Ordering::Relaxed); |
72 |
| - |
73 |
| - arc_desired.wait(true); |
| 49 | + thread::spawn(move || { |
| 50 | + if let Err(e) = |
| 51 | + Self::input_loop(&arc_desired, &arc_current, &tx) |
| 52 | + { |
| 53 | + log::error!("input thread error: {}", e); |
| 54 | + process::abort(); |
74 | 55 | }
|
75 | 56 | });
|
76 | 57 |
|
@@ -108,4 +89,35 @@ impl Input {
|
108 | 89 | Ok(None)
|
109 | 90 | }
|
110 | 91 | }
|
| 92 | + |
| 93 | + fn input_loop( |
| 94 | + arc_desired: &Arc<NotifyableMutex<bool>>, |
| 95 | + arc_current: &Arc<AtomicBool>, |
| 96 | + tx: &Sender<InputEvent>, |
| 97 | + ) -> Result<()> { |
| 98 | + loop { |
| 99 | + if arc_desired.get() { |
| 100 | + if !arc_current.load(Ordering::Relaxed) { |
| 101 | + log::info!("input polling resumed"); |
| 102 | + |
| 103 | + tx.send(InputEvent::State(InputState::Polling))?; |
| 104 | + } |
| 105 | + arc_current.store(true, Ordering::Relaxed); |
| 106 | + |
| 107 | + if let Some(e) = Self::poll(POLL_DURATION)? { |
| 108 | + tx.send(InputEvent::Input(e))?; |
| 109 | + } |
| 110 | + } else { |
| 111 | + if arc_current.load(Ordering::Relaxed) { |
| 112 | + log::info!("input polling suspended"); |
| 113 | + |
| 114 | + tx.send(InputEvent::State(InputState::Paused))? |
| 115 | + } |
| 116 | + |
| 117 | + arc_current.store(false, Ordering::Relaxed); |
| 118 | + |
| 119 | + arc_desired.wait(true); |
| 120 | + } |
| 121 | + } |
| 122 | + } |
111 | 123 | }
|
0 commit comments