1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
//! Worker basic usage example
//!
//! Demonstrates WorkerHandle usage for background tasks.
//!
//! Run with: cargo run --example worker_basic
use revue::prelude::*;
use revue::worker::{WorkerHandle, WorkerState};
use std::time::Duration;
struct WorkerDemo {
handle: Option<WorkerHandle<String>>,
result: Option<String>,
status: String,
task_count: usize,
}
impl WorkerDemo {
fn new() -> Self {
Self {
handle: None,
result: None,
status: "Ready".to_string(),
task_count: 0,
}
}
fn start_task(&mut self, duration_ms: u64) {
if self.handle.is_some() {
self.status = "Task already running!".to_string();
return;
}
self.task_count += 1;
let count = self.task_count;
self.status = format!("Starting task #{} ({}ms)...", count, duration_ms);
let handle = WorkerHandle::spawn_blocking(move || {
// Simulate work
std::thread::sleep(Duration::from_millis(duration_ms));
format!("Task #{} completed after {}ms", count, duration_ms)
});
self.handle = Some(handle);
}
fn cancel_task(&mut self) {
if let Some(handle) = &self.handle {
handle.cancel();
self.status = "Cancelled!".to_string();
self.handle = None;
}
}
fn handle_key(&mut self, key: &Key) -> bool {
match key {
Key::Char('1') => {
self.start_task(1000); // 1 second
true
}
Key::Char('2') => {
self.start_task(3000); // 3 seconds
true
}
Key::Char('3') => {
self.start_task(5000); // 5 seconds
true
}
Key::Char('c') => {
self.cancel_task();
true
}
Key::Char('r') => {
self.result = None;
self.status = "Cleared".to_string();
true
}
_ => false,
}
}
fn tick(&mut self) -> bool {
if let Some(handle) = &mut self.handle {
let state = handle.state();
match state {
WorkerState::Running => {
self.status = "Task running...".to_string();
}
WorkerState::Completed => {
// Take ownership and get result
if let Some(h) = self.handle.take() {
match h.join() {
Ok(result) => {
self.result = Some(result);
self.status = "Completed!".to_string();
}
Err(e) => {
self.status = format!("Error: {}", e);
}
}
return true;
}
}
WorkerState::Failed => {
if let Some(h) = self.handle.take() {
if let Err(e) = h.join() {
self.status = format!("Failed: {}", e);
}
return true;
}
}
WorkerState::Cancelled => {
self.handle = None;
return true;
}
_ => {}
}
}
false
}
}
impl View for WorkerDemo {
fn render(&self, ctx: &mut RenderContext) {
let state = self.handle.as_ref().map(|h| h.state());
let _is_running = matches!(state, Some(WorkerState::Running));
let state_text = match state {
Some(WorkerState::Pending) => "Pending",
Some(WorkerState::Running) => "Running",
Some(WorkerState::Completed) => "Completed",
Some(WorkerState::Failed) => "Failed",
Some(WorkerState::Cancelled) => "Cancelled",
None => "None",
};
let state_color = match state {
Some(WorkerState::Running) => Color::YELLOW,
Some(WorkerState::Completed) => Color::GREEN,
Some(WorkerState::Failed) | Some(WorkerState::Cancelled) => Color::RED,
_ => Color::rgb(100, 100, 100),
};
let view = vstack()
.gap(1)
.child(
Border::panel().title("⚙️ Worker Handle Demo").child(
vstack()
.child(
hstack()
.gap(2)
.child(Text::new("Status:").bold())
.child(Text::new(&self.status).fg(Color::CYAN)),
)
.child(
hstack()
.gap(2)
.child(Text::new("Worker state:"))
.child(Text::new(state_text).fg(state_color)),
)
.child(
hstack()
.gap(2)
.child(Text::new("Tasks completed:"))
.child(Text::new(format!("{}", self.task_count))),
),
),
)
.child(
Border::single()
.title("Result")
.child(if let Some(result) = &self.result {
vstack()
.child(Text::success("✓ Task completed"))
.child(Text::new(result).fg(Color::WHITE))
} else {
vstack().child(Text::muted("No result yet"))
}),
)
.child(
Border::success_box()
.title("✨ Features Demonstrated")
.child(
vstack()
.child(Text::success("✓ WorkerHandle: Spawn blocking tasks"))
.child(Text::success(
"✓ State tracking: Pending → Running → Completed",
))
.child(Text::success("✓ Result retrieval with join()"))
.child(Text::success("✓ Cancellation support"))
.child(Text::success("✓ Panic handling")),
),
)
.child(
Border::rounded().title("Controls").child(
vstack()
.child(
hstack()
.gap(2)
.child(Text::muted("[1]"))
.child(Text::new("Start 1s task")),
)
.child(
hstack()
.gap(2)
.child(Text::muted("[2]"))
.child(Text::new("Start 3s task")),
)
.child(
hstack()
.gap(2)
.child(Text::muted("[3]"))
.child(Text::new("Start 5s task")),
)
.child(
hstack()
.gap(2)
.child(Text::muted("[c]"))
.child(Text::new("Cancel task")),
)
.child(
hstack()
.gap(2)
.child(Text::muted("[r]"))
.child(Text::new("Clear result")),
)
.child(
hstack()
.gap(2)
.child(Text::muted("[q]"))
.child(Text::new("Quit")),
),
),
);
view.render(ctx);
}
fn meta(&self) -> WidgetMeta {
WidgetMeta::new("WorkerDemo")
}
}
fn main() -> Result<()> {
println!("⚙️ Worker Handle Basic Usage Example");
println!("Demonstrates WorkerHandle state tracking and control.\n");
let mut app = App::builder().build();
let demo = WorkerDemo::new();
app.run(demo, |event, demo, _app| match event {
Event::Key(key_event) => demo.handle_key(&key_event.key),
Event::Tick => demo.tick(),
_ => false,
})
}