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
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! Access the state of Duat.
use std::{
any::TypeId,
sync::{
atomic::{AtomicUsize, Ordering::Relaxed},
mpsc,
},
time::{Duration, Instant},
};
use crossterm::event::KeyEvent;
pub use self::{global::*, handles::*, log::*};
use crate::{
buffer::Buffer,
data::{Pass, RwData},
session::{DuatEvent, UiMouseEvent},
ui::{Area, Node, Widget},
};
pub mod cache;
mod handles;
mod log;
mod global {
use std::{
path::{Path, PathBuf},
sync::{
LazyLock, Mutex, OnceLock,
atomic::{AtomicBool, AtomicUsize, Ordering},
mpsc,
},
};
use super::{CurWidgetNode, DynBuffer};
use crate::{
context::{DuatReceiver, DuatSender, Handle},
data::{Pass, RwData},
session::DuatEvent,
ui::{Widget, Window, Windows},
};
static WINDOWS: OnceLock<&Windows> = OnceLock::new();
static MODE_NAME: LazyLock<RwData<&str>> = LazyLock::new(RwData::default);
static CUR_DIR: LazyLock<Mutex<PathBuf>> =
LazyLock::new(|| Mutex::new(std::env::current_dir().unwrap()));
static NEW_EVENT_COUNT: AtomicUsize = AtomicUsize::new(0);
static WILL_UNLOAD: AtomicBool = AtomicBool::new(false);
static DUAT_CHANNEL: LazyLock<Mutex<(DuatSender, Option<DuatReceiver>)>> =
LazyLock::new(|| {
let (sender, receiver) = mpsc::channel();
let sender = DuatSender(sender, &NEW_EVENT_COUNT);
let receiver = DuatReceiver(receiver, &NEW_EVENT_COUNT);
Mutex::new((sender, Some(receiver)))
});
/// Queues a function to be done on the main thread with a
/// [`Pass`].
///
/// You can use this whenever you don't have access to a `Pass`,
/// in order to execute an action on the main thread, gaining
/// access to Duat's global state within that function.
///
/// Note that, since this can be called from any thread, it needs
/// to be [`Send`] and `'static`.
pub fn queue(f: impl FnOnce(&mut Pass) + Send + 'static) {
sender().send(DuatEvent::QueuedFunction(Box::new(f)));
}
////////// Internal setters meant to be called internally
/// Attempts to set the current [`Handle`].
///
/// Fails if said [`Handle`] was already deleted.
#[track_caller]
pub(crate) fn set_current_node(pa: &mut Pass, node: crate::ui::Node) {
if let Err(err) = windows().set_current_node(pa, node) {
super::warn!("{err}");
}
}
/// Sets the [`Window`]s for Duat.
pub(crate) fn set_windows(windows: Windows) {
if WINDOWS.set(Box::leak(Box::new(windows))).is_err() {
panic!("Setup ran twice");
}
}
/// Wether Duat has received new events that need to be handled.
///
/// Events can be anything, from a [key press], a [refocus], or
/// even a [queued function].
///
/// You can use this function to set up "timeouts". That is, if
/// the thing you're trying to do is on the main thread and is
/// taking way too long, you can check for this function and stop
/// what you're doing if there's any new events that Duat hasn't
/// handled.
///
/// [key press]: crate::mode::KeyEvent
/// [refocus]: crate::hook::FocusedOnDuat
/// [queued function]: queue
pub fn has_unhandled_events() -> bool {
NEW_EVENT_COUNT.load(Ordering::SeqCst) > 0
}
/// The only receiver of [`DuatEvent`]s.
pub(crate) fn receiver() -> DuatReceiver {
DUAT_CHANNEL.lock().unwrap().1.take().unwrap()
}
////////// Widget Handle getters
/// Returns a "fixed" [`Handle`] for the currently active
/// [`Buffer`].
///
/// This `Handle` will always point to the same `Buffer`,
/// even when it is not active. If you want a `Handle` that
/// always points to the current Buffer, see [`dynamic_buffer`].
///
/// [`Buffer`]: crate::buffer::Buffer
pub fn current_buffer(pa: &Pass) -> Handle {
windows().current_buffer(pa).read(pa).clone()
}
/// Returns a "dynamic" [`Handle`] for the active [`Buffer`].
///
/// This `Handle` will change to point to the current `Buffer`,
/// whenever the user swicthes which `Buffer` is active. If you
/// want a `Handle` that will stay on the current `Buffer`, see
/// [`current_buffer`].
///
/// [`Buffer`]: crate::buffer::Buffer
pub fn dynamic_buffer(pa: &Pass) -> DynBuffer {
let dyn_buffer = windows().current_buffer(pa).clone();
let cur_buffer = RwData::new(dyn_buffer.read(pa).clone());
DynBuffer {
cur_buffer: dyn_buffer,
saved_buffer: cur_buffer,
}
}
/// Returns a [`Handle`] for a [`Buffer`] with the given name.
///
/// [`Buffer`]: crate::buffer::Buffer
pub fn get_buffer(pa: &Pass, name: impl ToString) -> Option<Handle> {
let (.., handle) = windows().named_buffer_entry(pa, &name.to_string())?;
Some(handle)
}
/// Returns a [`Handle`] for a [`Buffer`] with the given [`Path`].
///
/// [`Buffer`]: crate::buffer::Buffer
pub fn get_buffer_by_path(pa: &Pass, path: &Path) -> Option<Handle> {
let (.., handle) = windows().path_buffer_entry(pa, path)?;
Some(handle)
}
/// Get the "most appropriate" [`Handle`] for a given [`Widget`].
///
/// The "most appropriate" `Handle` is determined like this:
///
/// 1. Try to look for those pushed around the current [`Buffer`].
/// 2. Try to look for those pushed around the current [`Window`].
/// 3. Try to look for those pushed around other [`Window`]s.
///
/// [`Buffer`]: crate::buffer::Buffer
pub fn handle_of<W: Widget>(pa: &Pass) -> Option<Handle<W>> {
windows()
.node_of::<W>(pa)
.ok()
.and_then(|node| node.try_downcast())
}
/// Returns the current active [`Handle`].
///
/// Unlike [`current_buffer`], this function will return a
/// [`Handle<dyn Widget>`], which means it could be any
/// [`Widget`], not just a [`Buffer`].
///
/// [`Buffer`]: crate::buffer::Buffer
pub fn current_widget(pa: &Pass) -> &Handle<dyn Widget> {
windows().current_widget(pa).read(pa).handle()
}
/// The [`CurWidgetNode`]
pub(crate) fn current_widget_node(pa: &Pass) -> CurWidgetNode {
CurWidgetNode(windows().current_widget(pa).clone())
}
////////// Other getters
/// The [`Window`]s of Duat.
///
/// This struct gives you reading access to every `Window` in
/// Duat with [`Windows::get`], you also get access to every
/// [`Handle<dyn Widget>`], including every `Handle<Buffer>`,
/// through the [`Windows::handles`] and [`Window::buffers`]
/// function.
pub fn windows() -> &'static Windows {
WINDOWS.get().unwrap()
}
/// Try to get the [`Windows`].
pub(crate) fn get_windows() -> Option<&'static Windows> {
WINDOWS.get().cloned()
}
/// A list of all open [`Buffer`]'s [`Handle`]s.
///
/// [`Buffer`]: crate::buffer::Buffer
pub fn buffers(pa: &Pass) -> Vec<Handle> {
windows().buffers(pa)
}
/// The current [`Window`].
///
/// You can iterate through all [`Handle<Buffer>`]s and
/// `Handle<dyn Widget>` with [`Window::buffers`] and
/// [`Window::handles`] respectively.
///
/// If you wish to access other `Window`s, you can use
/// `context::windows().get(pa, n)` to get the `n`th `Window`.
/// The current window number can be found with
/// [`context::current_win_index`]
///
/// [`context::current_win_index`]: current_win_index
pub fn current_window(pa: &Pass) -> &Window {
let win = current_win_index(pa);
WINDOWS.get().unwrap().get(pa, win).unwrap()
}
/// The index of the currently active window.
pub fn current_win_index(pa: &Pass) -> usize {
windows().current_window(pa)
}
/// The name of the current [`Mode`].
///
/// [`Mode`]: crate::mode::Mode
pub fn mode_name() -> RwData<&'static str> {
MODE_NAME.clone()
}
/// The current directory.
pub fn current_dir() -> PathBuf {
CUR_DIR.lock().unwrap().clone()
}
/// Wether Duat is in the process of unloading.
///
/// You should make use of this function in order to halt spawned
/// threads, as Duat will stall untill all spawned threads are
/// dropped or joined.
///
/// This function will be set to true right before the
/// [`ConfigUnloaded`] hook is triggered.
///
/// [`ConfigUnloaded`]: crate::hook::ConfigUnloaded
pub fn will_unload() -> bool {
WILL_UNLOAD.load(Ordering::Relaxed)
}
/// Declares that Duat will reload or quit.
pub(crate) fn declare_will_unload() {
WILL_UNLOAD.store(true, Ordering::Relaxed)
}
/// A [`mpsc::Sender`] for [`DuatEvent`]s in the main loop.
pub(crate) fn sender() -> DuatSender {
DUAT_CHANNEL.lock().unwrap().0.clone()
}
}
/// A sender of [`DuatEvent`]s.
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct DuatSender(mpsc::Sender<DuatEvent>, &'static AtomicUsize);
impl DuatSender {
/// Sends a [`KeyEvent`].
pub fn send_key(&self, key: KeyEvent) {
self.1.fetch_add(1, Relaxed);
_ = self.0.send(DuatEvent::KeyEventSent(key));
}
/// Sends an [`UiMouseEvent`].
pub fn send_mouse(&self, mouse: UiMouseEvent) {
self.1.fetch_add(1, Relaxed);
_ = self.0.send(DuatEvent::MouseEventSent(mouse));
}
/// Sends a notice that the app has resized.
pub fn send_resize(&self) {
self.1.fetch_add(1, Relaxed);
_ = self.0.send(DuatEvent::Resized);
}
/// Triggers the [`FocusedOnDuat`] [`hook`].
///
/// [`FocusedOnDuat`]: crate::hook::FocusedOnDuat
/// [`hook`]: crate::hook
pub fn send_focused(&self) {
self.1.fetch_add(1, Relaxed);
_ = self.0.send(DuatEvent::FocusedOnDuat);
}
/// Triggers the [`UnfocusedFromDuat`] [`hook`].
///
/// [`UnfocusedFromDuat`]: crate::hook::UnfocusedFromDuat
/// [`hook`]: crate::hook
pub fn send_unfocused(&self) {
self.1.fetch_add(1, Relaxed);
_ = self.0.send(DuatEvent::UnfocusedFromDuat);
}
/// Sends any [`DuatEvent`].
#[track_caller]
pub(crate) fn send(&self, event: DuatEvent) {
self.1.fetch_add(1, Relaxed);
_ = self.0.send(event);
}
}
/// A receiver for [`DuatEvent`]s.
#[doc(hidden)]
pub struct DuatReceiver(mpsc::Receiver<DuatEvent>, &'static AtomicUsize);
impl DuatReceiver {
/// Receive a [`DuatEvent`].
///
/// If less than 5 milliseconds have passed since the [`Instant`]
/// for chained events, then it will attempt to receive until said
/// timeout.
///
/// Otherwise, it will wait until an event shows up.
pub(crate) fn recv(&self, chain_instant: &mut Option<Instant>) -> Option<DuatEvent> {
if let Some(instant) = chain_instant {
if let Some(duration) = Duration::from_micros(500).checked_sub(instant.elapsed()) {
self.0
.recv_timeout(duration)
.inspect(|_| _ = self.1.fetch_sub(1, Relaxed))
.ok()
} else {
*chain_instant = None;
None
}
} else {
self.0
.recv()
.inspect(|_| _ = self.1.fetch_sub(1, Relaxed))
.ok()
}
}
}
/// A "dynamic" [`Handle`] wrapper for [`Buffer`]s.
///
/// This `Handle` wrapper will always point to the presently active
/// `Buffer`. It can also detect when that `Buffer` has been changed
/// or when another `Buffer` becomes the active `Buffer`.
pub struct DynBuffer {
cur_buffer: RwData<Handle>,
saved_buffer: RwData<Handle>,
}
impl DynBuffer {
/// Wether the [`Buffer`] pointed to has changed or swapped with
/// another.
pub fn has_changed(&self, pa: &Pass) -> bool {
if self.cur_buffer.has_changed() {
true
} else {
self.saved_buffer.read(pa).has_changed(pa)
}
}
/// Swaps the [`DynBuffer`] to the currently active [`Buffer`].
pub fn swap_to_current(&mut self) {
// SAFETY: Since this struct uses deep Cloning, no mutable
// references to the RwData exist.
let pa = unsafe { &mut Pass::new() };
if self.cur_buffer.has_changed() {
*self.saved_buffer.write(pa) = self.cur_buffer.read(pa).clone();
}
}
/// Reads the presently active [`Buffer`].
pub fn read<'a>(&'a mut self, pa: &'a Pass) -> &'a Buffer {
self.saved_buffer.read(pa).read(pa)
}
/// The [`Handle<Buffer>`] currently being pointed to.
pub fn handle(&self) -> &Handle {
// SAFETY: Since this struct uses deep Cloning, no mutable
// references to the RwData exist.
static INTERNAL_PASS: &Pass = unsafe { &Pass::new() };
self.saved_buffer.read(INTERNAL_PASS)
}
/// Simulates a [`read`] without actually reading.
///
/// This is useful if you want to tell Duat that you don't want
/// [`has_changed`] to return `true`, but you don't have a
/// [`Pass`] available to [`read`] the value.
///
/// This assumes that you don't care about the active [`Buffer`]
/// possibly being swapped.
///
/// [`read`]: Self::read
/// [`has_changed`]: Self::has_changed
pub fn declare_as_read(&self) {
// SAFETY: Since this struct uses deep Cloning, no mutable
// references to the RwData exist.
static INTERNAL_PASS: &Pass = unsafe { &Pass::new() };
self.cur_buffer.declare_as_read();
self.saved_buffer.read(INTERNAL_PASS).declare_as_read();
}
////////// Writing functions
/// Reads the presently active [`Buffer`].
pub fn write<'a>(&'a self, pa: &'a mut Pass) -> &'a mut Buffer {
// SAFETY: Because I already got a &mut Pass, the RwData can't be
// accessed anyways.
static INTERNAL_PASS: &Pass = unsafe { &Pass::new() };
self.saved_buffer.read(INTERNAL_PASS).write(pa)
}
/// Writes to the [`Buffer`] and [`Area`], making use of a
/// [`Pass`].
///
/// [`Area`]: crate::ui::Area
pub fn write_with_area<'a>(&'a self, pa: &'a mut Pass) -> (&'a mut Buffer, &'a mut Area) {
// SAFETY: Because I already got a &mut Pass, the RwData can't be
// accessed anyways.
static INTERNAL_PASS: &Pass = unsafe { &Pass::new() };
self.saved_buffer.read(INTERNAL_PASS).write_with_area(pa)
}
/// Simulates a [`write`] without actually writing.
///
/// This is useful if you want to tell Duat that you want
/// [`has_changed`] to return `true`, but you don't have a
/// [`Pass`] available to `write` the value with.
///
/// [`write`]: Self::write
/// [`has_changed`]: Self::has_changed
pub fn declare_written(&self) {
// SAFETY: Since this struct uses deep Cloning, no other references to
// the RwData exist.
static INTERNAL_PASS: &Pass = unsafe { &Pass::new() };
self.cur_buffer.read(INTERNAL_PASS).declare_written();
}
}
impl Clone for DynBuffer {
/// Returns a _deep cloned_ duplicate of the value.
///
/// In this case, what this means is that the clone and `self`
/// will have different internal pointers for the current
/// [`Buffer`]. So if, for example, you call
/// [`DynBuffer::swap_to_current`] on `self`, that will switch
/// `self` to point to the current `Buffer`, but the same will not
/// be done in the clone.
fn clone(&self) -> Self {
// SAFETY: Because I already got a &mut Pass, the RwData can't be
// accessed anyways.
static INTERNAL_PASS: &Pass = unsafe { &Pass::new() };
Self {
cur_buffer: RwData::new(self.cur_buffer.read(INTERNAL_PASS).clone()),
saved_buffer: self.saved_buffer.clone(),
}
}
}
/// The current [`Widget`].
pub(crate) struct CurWidgetNode(RwData<Node>);
impl CurWidgetNode {
/// The [`Widget`]'s [`TypeId`].
pub fn type_id(&self, pa: &Pass) -> TypeId {
self.0.read(pa).widget().type_id()
}
/// Reads the [`Widget`] and its [`Area`].
pub fn _read<R>(&self, pa: &Pass, f: impl FnOnce(&dyn Widget, &Area) -> R) -> R {
let node = self.0.read(pa);
f(node.handle().read(pa), node.area().read(pa))
}
/// Reads the [`Widget`] as `W` and its [`Area`].
pub fn _read_as<W: Widget, R>(&self, pa: &Pass, f: impl FnOnce(&W, &Area) -> R) -> Option<R> {
let node = self.0.read(pa);
Some(f(node.read_as(pa)?, node.area().read(pa)))
}
/// Mutates the [`RwData<dyn Widget>`], its [`Area`], and related
/// [`Widget`]s.
pub(crate) fn mutate_data<R>(&self, pa: &Pass, f: impl FnOnce(&Handle<dyn Widget>) -> R) -> R {
f(self.0.read(pa).handle())
}
/// The inner [`Node`].
pub(crate) fn node(&self, pa: &Pass) -> Node {
self.0.read(pa).clone()
}
}