Repository navigation
Expand file tree
/
Copy pathsimple.rs
More file actions
365 lines (332 loc) · 11 KB
/
Copy pathsimple.rs
File metadata and controls
365 lines (332 loc) · 11 KB
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
#[path = "util/fill.rs"]
mod fill;
use accesskit::{
Action, ActionRequest, Affine, Live, Node, NodeId, Rect, Role, TreeId, TreeInfo, TreeUpdate,
Vec2,
};
use accesskit_winit::{Adapter, Event as AccessKitEvent, WindowEvent as AccessKitWindowEvent};
use std::error::Error;
use std::time::{Duration, Instant};
use winit::{
application::ApplicationHandler,
event::{ElementState, KeyEvent, WindowEvent},
event_loop::ControlFlow,
event_loop::{ActiveEventLoop, EventLoop, EventLoopProxy},
keyboard::Key,
window::{Window, WindowId},
};
const WINDOW_TITLE: &str = "Hello world";
const WINDOW_ID: NodeId = NodeId(0);
const BUTTON_1_ID: NodeId = NodeId(1);
const BUTTON_2_ID: NodeId = NodeId(2);
const ANNOUNCEMENT_ID: NodeId = NodeId(3);
const INITIAL_FOCUS: NodeId = BUTTON_1_ID;
const WINDOW_RECT: Rect = Rect {
x0: 0.0,
y0: 0.0,
x1: 393.0,
y1: 759.0,
};
const BUTTON_1_RECT: Rect = Rect {
x0: 20.0,
y0: 20.0,
x1: 200.0,
y1: 64.0,
};
const BUTTON_2_RECT: Rect = Rect {
x0: 20.0,
y0: 84.0,
x1: 200.0,
y1: 128.0,
};
#[cfg(target_os = "ios")]
fn safe_area_inset(window: &Window) -> Vec2 {
let Ok(outer) = window.outer_position() else {
return Vec2::ZERO;
};
let Ok(inner) = window.inner_position() else {
return Vec2::ZERO;
};
Vec2::new((inner.x - outer.x) as f64, (inner.y - outer.y) as f64)
}
#[cfg(not(target_os = "ios"))]
fn safe_area_inset(_: &Window) -> Vec2 {
Vec2::ZERO
}
fn build_button(id: NodeId, label: &str) -> Node {
let rect = match id {
BUTTON_1_ID => BUTTON_1_RECT,
BUTTON_2_ID => BUTTON_2_RECT,
_ => unreachable!(),
};
let mut node = Node::new(Role::Button);
node.set_bounds(rect);
node.set_label(label);
node.add_action(Action::Focus);
node.add_action(Action::Click);
node
}
fn build_announcement(text: &str) -> Node {
let mut node = Node::new(Role::Label);
node.set_value(text);
node.set_live(Live::Polite);
node
}
const ANNOUNCEMENT_DELAY: Duration = Duration::from_millis(150);
struct UiState {
focus: NodeId,
announcement: Option<&'static str>,
pending_announcement: Option<(&'static str, Instant)>,
scale_factor: f64,
inset: Vec2,
}
impl UiState {
fn new(scale_factor: f64, inset: Vec2) -> Self {
Self {
focus: INITIAL_FOCUS,
announcement: None,
pending_announcement: None,
scale_factor,
inset,
}
}
fn build_root(&mut self) -> Node {
let mut node = Node::new(Role::Window);
node.set_bounds(WINDOW_RECT);
node.set_transform(Affine::translate(self.inset) * Affine::scale(self.scale_factor));
node.set_children(vec![BUTTON_1_ID, BUTTON_2_ID]);
if self.announcement.is_some() {
node.push_child(ANNOUNCEMENT_ID);
}
node.set_label(WINDOW_TITLE);
node
}
fn build_initial_tree(&mut self) -> TreeUpdate {
let root = self.build_root();
let button_1 = build_button(BUTTON_1_ID, "Button 1");
let button_2 = build_button(BUTTON_2_ID, "Button 2");
let tree = TreeInfo::new(WINDOW_ID);
let mut result = TreeUpdate {
nodes: vec![
(WINDOW_ID, root),
(BUTTON_1_ID, button_1),
(BUTTON_2_ID, button_2),
],
tree: Some(tree),
tree_id: TreeId::ROOT,
focus: self.focus,
};
if let Some(announcement) = &self.announcement {
result
.nodes
.push((ANNOUNCEMENT_ID, build_announcement(announcement)));
}
result
}
fn set_focus(&mut self, adapter: &mut Adapter, focus: NodeId) {
self.focus = focus;
adapter.update_if_active(|| TreeUpdate {
nodes: vec![],
tree: None,
tree_id: TreeId::ROOT,
focus,
});
}
fn press_button(&mut self, id: NodeId) {
let text = if id == BUTTON_1_ID {
"You pressed button 1"
} else {
"You pressed button 2"
};
// On iOS, VoiceOver announces the label of the activated button.
// Postpone the live region update so the messages don't overlap.
self.pending_announcement = Some((text, Instant::now()));
}
fn flush_announcement(&mut self, adapter: &mut Adapter) -> bool {
let Some((_, queued_at)) = &self.pending_announcement else {
return false;
};
if queued_at.elapsed() < ANNOUNCEMENT_DELAY {
return true;
}
if let Some((text, _)) = self.pending_announcement.take() {
self.announcement = Some(text);
adapter.update_if_active(|| {
let announcement = build_announcement(text);
let root = self.build_root();
TreeUpdate {
nodes: vec![(ANNOUNCEMENT_ID, announcement), (WINDOW_ID, root)],
tree: None,
tree_id: TreeId::ROOT,
focus: self.focus,
}
});
}
false
}
}
struct WindowState {
window: Window,
adapter: Adapter,
ui: UiState,
}
impl WindowState {
fn new(window: Window, adapter: Adapter, ui: UiState) -> Self {
Self {
window,
adapter,
ui,
}
}
}
struct Application {
event_loop_proxy: EventLoopProxy<AccessKitEvent>,
window: Option<WindowState>,
}
impl Application {
fn new(event_loop_proxy: EventLoopProxy<AccessKitEvent>) -> Self {
Self {
event_loop_proxy,
window: None,
}
}
fn create_window(&mut self, event_loop: &ActiveEventLoop) -> Result<(), Box<dyn Error>> {
let window_attributes = Window::default_attributes()
.with_title(WINDOW_TITLE)
.with_visible(false);
let window = event_loop.create_window(window_attributes)?;
let ui = UiState::new(window.scale_factor(), safe_area_inset(&window));
let adapter =
Adapter::with_event_loop_proxy(event_loop, &window, self.event_loop_proxy.clone());
window.set_visible(true);
self.window = Some(WindowState::new(window, adapter, ui));
Ok(())
}
}
impl ApplicationHandler<AccessKitEvent> for Application {
fn window_event(&mut self, _: &ActiveEventLoop, _: WindowId, event: WindowEvent) {
let window = match &mut self.window {
Some(window) => window,
None => return,
};
let adapter = &mut window.adapter;
let state = &mut window.ui;
adapter.process_event(&window.window, &event);
match event {
WindowEvent::CloseRequested => {
fill::cleanup_window(&window.window);
self.window = None;
}
WindowEvent::Resized(_) => {
state.scale_factor = window.window.scale_factor();
state.inset = safe_area_inset(&window.window);
adapter.update_if_active(|| state.build_initial_tree());
window.window.request_redraw();
}
WindowEvent::RedrawRequested => {
fill::fill_window(&window.window);
}
WindowEvent::KeyboardInput {
event:
KeyEvent {
logical_key: virtual_code,
state: ElementState::Pressed,
..
},
..
} => match virtual_code {
Key::Named(winit::keyboard::NamedKey::Tab) => {
let new_focus = if state.focus == BUTTON_1_ID {
BUTTON_2_ID
} else {
BUTTON_1_ID
};
state.set_focus(adapter, new_focus);
window.window.request_redraw();
}
Key::Named(winit::keyboard::NamedKey::Space) => {
let id = state.focus;
state.press_button(id);
window.window.request_redraw();
}
_ => (),
},
_ => (),
}
}
fn user_event(&mut self, _: &ActiveEventLoop, user_event: AccessKitEvent) {
let window = match &mut self.window {
Some(window) => window,
None => return,
};
let adapter = &mut window.adapter;
let state = &mut window.ui;
match user_event.window_event {
AccessKitWindowEvent::InitialTreeRequested => {
adapter.update_if_active(|| state.build_initial_tree());
}
AccessKitWindowEvent::ActionRequested(ActionRequest {
action,
target_node,
..
}) => {
if target_node == BUTTON_1_ID || target_node == BUTTON_2_ID {
match action {
Action::Focus => {
state.set_focus(adapter, target_node);
}
Action::Click => {
state.press_button(target_node);
}
_ => (),
}
}
window.window.request_redraw();
}
AccessKitWindowEvent::AccessibilityDeactivated => (),
}
}
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.window.is_none() {
self.create_window(event_loop)
.expect("failed to create initial window");
}
if let Some(window) = self.window.as_ref() {
window.window.request_redraw();
}
}
fn about_to_wait(&mut self, event_loop: &ActiveEventLoop) {
if let Some(window) = &mut self.window {
if window.ui.flush_announcement(&mut window.adapter) {
event_loop.set_control_flow(ControlFlow::wait_duration(ANNOUNCEMENT_DELAY));
}
} else {
event_loop.exit();
}
}
}
fn main() -> Result<(), Box<dyn Error>> {
println!("This example has no visible GUI, and a keyboard interface:");
println!("- [Tab] switches focus between two logical buttons.");
println!(
"- [Space] 'presses' the button, adding static text in a live region announcing that it was pressed."
);
#[cfg(target_os = "windows")]
println!(
"Enable Narrator with [Win]+[Ctrl]+[Enter] (or [Win]+[Enter] on older versions of Windows)."
);
#[cfg(all(
feature = "accesskit_unix",
any(
target_os = "linux",
target_os = "dragonfly",
target_os = "freebsd",
target_os = "netbsd",
target_os = "openbsd"
)
))]
println!("Enable Orca with [Super]+[Alt]+[S].");
let event_loop = EventLoop::with_user_event().build()?;
let mut state = Application::new(event_loop.create_proxy());
event_loop.run_app(&mut state).map_err(Into::into)
}