duat_core/context/
handles.rs

1//! Widget handles for Duat
2//!
3//! These are used pretty much everywhere, and are essentially just an
4//! [`RwData<W>`] conjoined with an [`Area`].
5use std::sync::{
6    Arc, Mutex,
7    atomic::{AtomicBool, Ordering},
8};
9
10use lender::Lender;
11
12use crate::{
13    context,
14    data::{Pass, RwData, WriteableTuple},
15    mode::{Cursor, Cursors, ModSelection, Selection, Selections},
16    opts::PrintOpts,
17    text::{Text, TextMut, TextParts, TwoPoints, txt},
18    ui::{Area, DynSpawnSpecs, PushSpecs, RwArea, Widget},
19};
20
21/// A handle to a [`Widget`] in Duat
22///
23/// The [`Handle`] lets you do all sorts of edits on a [`Widget`]. You
24/// can, for example, make use of the [`Selection`]s in its [`Text`]
25/// in order to edit the [`Text`] in a very declarative way.
26///
27/// One of the places where this is commonly done is within [`Mode`]s,
28/// where you get access to the [`Handle`] of the currently active
29/// [`Widget`]. Below is a very straightforward [`Mode`]:
30///
31/// ```rust
32/// # duat_core::doc_duat!(duat);
33/// use duat::prelude::*;
34///
35/// /// A very basic example Mode.
36/// #[derive(Clone)]
37/// struct PlacesCharactersAndMoves;
38///
39/// impl Mode for PlacesCharactersAndMoves {
40///     type Widget = Buffer;
41///
42///     // ..
43///     fn send_key(&mut self, _: &mut Pass, _: KeyEvent, _: Handle) {
44///         todo!();
45///     }
46/// }
47/// ```
48///
49/// In order to modify the widget, you must implement the
50/// [`Mode::send_key`] method. In it, you receive the following:
51///
52/// - A [`&mut Pass`], which will give you access to all of duat's
53///   shared state;
54/// - The [key] that was sent, may be a [mapped] key.
55/// - The [`Handle`] for a [`Mode::Widget`].
56///
57/// ```rust
58/// # duat_core::doc_duat!(duat);
59/// use duat::prelude::*;
60///
61/// #[derive(Clone)]
62/// struct PlacesCharactersAndMoves;
63/// impl Mode for PlacesCharactersAndMoves {
64///     type Widget = Buffer;
65///
66///     fn send_key(&mut self, pa: &mut Pass, key_event: KeyEvent, handle: Handle) {
67///         match key_event {
68///             // actions based on the key pressed
69///             event!(KeyCode::Char(char)) => {
70///                 // Do something when the character 'c' is typed.
71///             }
72///             _ => todo!("The remaining keys"),
73///         }
74///     }
75/// }
76/// ```
77///
78/// Note the [`event!`] macro. It (alongside [`alt!`], [`ctrl!`] and
79/// [`shift!`]) can be used to easily create [`KeyEvent`]s for
80/// matching purposes. They are very useful for succinctly describing
81/// an exact match in just a short pattern:
82///
83/// ```rust
84/// # duat_core::doc_duat!(duat);
85/// use KeyCode::*;
86/// use duat::prelude::*;
87///
88/// let key_event = KeyEvent::from(Char('a'));
89/// match key_event {
90///     event!('a' | 'b') => { /* .. */ }
91///     shift!(Right | Left) => { /* .. */ }
92///     ctrl!(alt!('d')) => { /* .. */ }
93///     _ => { /* .. */ }
94/// }
95/// ```
96///
97/// With the [`Handle`], you can modify [`Text`] in a simplified
98/// way. This is done by two actions, [editing] and [moving]. You
99/// can only do one of these on any number of selections at the same
100/// time.
101///
102/// ```rust
103/// # duat_core::doc_duat!(duat);
104/// # use duat::prelude::*;
105/// # #[derive(Clone)]
106/// # struct PlacesCharactersAndMoves;
107/// impl Mode for PlacesCharactersAndMoves {
108///     type Widget = Buffer;
109///
110///     // ..
111///     fn send_key(&mut self, pa: &mut Pass, key_event: KeyEvent, handle: Handle) {
112///         use KeyCode::*;
113///         match key_event {
114///             event!(Char(char)) => handle.edit_all(pa, |mut c| {
115///                 c.insert('c');
116///                 c.move_hor(1);
117///             }),
118///             shift!(Right) => handle.edit_all(pa, |mut c| {
119///                 if c.anchor().is_none() {
120///                     c.set_anchor();
121///                 }
122///                 c.move_hor(1);
123///             }),
124///             event!(KeyCode::Right) => handle.edit_all(pa, |mut c| {
125///                 c.unset_anchor();
126///                 c.move_hor(1);
127///             }),
128///             _ => todo!("Predictable remaining implementations"),
129///         }
130///     }
131/// # }
132/// ```
133///
134/// [`Mode`]: crate::mode::Mode
135/// [`Mode::Widget`]: crate::mode::Mode::Widget
136/// [`&mut Pass`]: Pass
137/// [`PromptLine`]: https://docs.rs/duat/latest/duat/widgets/struct.PromptLine.html
138/// [`Mode::send_key`]: crate::mode::Mode::send_key
139/// [key]: crate::mode::KeyEvent
140/// [mapped]: crate::mode::map
141/// [`read`]: RwData::read
142/// [`write`]: RwData::write
143/// [`Self::Widget`]: crate::mode::Mode::Widget
144/// [`Some(selections)`]: Some
145/// [`Area`]: crate::ui::Area
146/// [commands]: crate::cmd
147/// [`KeyEvent`]: crate::mode::KeyEvent
148/// [editing]: Cursor
149/// [moving]: Cursor
150/// [`Mode`]: crate::mode::Mode
151/// [`event!`]: crate::mode::event
152/// [`alt!`]: crate::mode::alt
153/// [`ctrl!`]: crate::mode::ctrl
154/// [`shift!`]: crate::mode::shift
155pub struct Handle<W: Widget + ?Sized = crate::buffer::Buffer> {
156    widget: RwData<W>,
157    pub(crate) area: RwArea,
158    mask: Arc<Mutex<&'static str>>,
159    related: RelatedWidgets,
160    is_closed: RwData<bool>,
161    master: Option<Box<Handle<dyn Widget>>>,
162    pub(crate) update_requested: Arc<AtomicBool>,
163}
164
165impl<W: Widget + ?Sized> Handle<W> {
166    /// Returns a new instance of a [`Handle<W, U>`]
167    pub(crate) fn new(
168        widget: RwData<W>,
169        area: RwArea,
170        mask: Arc<Mutex<&'static str>>,
171        master: Option<Handle<dyn Widget>>,
172    ) -> Self {
173        Self {
174            widget,
175            area,
176            mask,
177            related: RelatedWidgets(RwData::default()),
178            is_closed: RwData::new(false),
179            master: master.map(Box::new),
180            update_requested: Arc::new(AtomicBool::new(false)),
181        }
182    }
183}
184
185impl<W: Widget + ?Sized> Handle<W> {
186    ////////// Read and write access functions
187
188    /// Reads from the [`Widget`], making use of a [`Pass`]
189    ///
190    /// The consistent use of a [`Pass`] for the purposes of
191    /// reading/writing to the values of [`RwData`]s ensures that no
192    /// panic or invalid borrow happens at runtime, even while working
193    /// with untrusted code. More importantly, Duat uses these
194    /// guarantees in order to give the end user a ridiculous amount
195    /// of freedom in where they can do things, whilst keeping Rust's
196    /// number one rule and ensuring thread safety, even with a
197    /// relatively large amount of shareable state.
198    ///
199    /// [`Area`]: crate::ui::Area
200    pub fn read<'a>(&'a self, pa: &'a Pass) -> &'a W {
201        self.widget.read(pa)
202    }
203
204    /// Tries to read as a concrete [`Widget`] implementor
205    pub fn read_as<'a, W2: Widget>(&'a self, pa: &'a Pass) -> Option<&'a W2> {
206        self.widget.read_as(pa)
207    }
208
209    /// Declares the [`Widget`] within as read
210    ///
211    /// Same as calling `handle.widget().declare_as_read()`. You
212    /// should use this function if you want to signal to others that
213    /// the widget was read, even if you don't have access to a
214    /// [`Pass`].
215    pub fn declare_as_read(&self) {
216        self.widget.declare_as_read();
217    }
218
219    /// Writes to the [`Widget`], making use of a [`Pass`]
220    ///
221    /// The consistent use of a [`Pass`] for the purposes of
222    /// reading/writing to the values of [`RwData`]s ensures that no
223    /// panic or invalid borrow happens at runtime, even while working
224    /// with untrusted code. More importantly, Duat uses these
225    /// guarantees in order to give the end user a ridiculous amount
226    /// of freedom in where they can do things, whilst keeping Rust's
227    /// number one rule and ensuring thread safety, even with a
228    /// relatively large amount of shareable state.
229    ///
230    /// [`Area`]: crate::ui::Area
231    pub fn write<'a>(&'a self, pa: &'a mut Pass) -> &'a mut W {
232        self.widget.write(pa)
233    }
234
235    /// Writes to the [`Widget`] and [`Area`], making use of a
236    /// [`Pass`]
237    ///
238    /// The consistent use of a [`Pass`] for the purposes of
239    /// reading/writing to the values of [`RwData`]s ensures that no
240    /// panic or invalid borrow happens at runtime, even while working
241    /// with untrusted code. More importantly, Duat uses these
242    /// guarantees in order to give the end user a ridiculous amount
243    /// of freedom in where they can do things, whilst keeping Rust's
244    /// number one rule and ensuring thread safety, even with a
245    /// relatively large amount of shareable state.
246    ///
247    /// [`Area`]: crate::ui::Area
248    pub fn write_with_area<'p>(&'p self, pa: &'p mut Pass) -> (&'p mut W, &'p mut Area) {
249        pa.write_many((&self.widget, &self.area.0))
250    }
251
252    /// The same as [`RwData::write_then`]
253    ///
254    /// This lets you write to a [`Widget`] and other [`RwData`]-like
255    /// structs within said `Widget` at the same time.
256    pub fn write_then<'p, Tup: WriteableTuple<'p, impl std::any::Any>>(
257        &'p self,
258        pa: &'p mut Pass,
259        tup_fn: impl FnOnce(&'p W) -> Tup,
260    ) -> (&'p mut W, Tup::Return) {
261        self.widget.write_then(pa, tup_fn)
262    }
263
264    /// Declares the [`Widget`] within as written
265    ///
266    /// Same as calling `handle.widget().declare_written()`. You
267    /// should use this function if you want to signal to others that
268    /// the widget was written to, even if you don't have access to a
269    /// [`Pass`].
270    pub fn declare_written(&self) {
271        self.widget.declare_written();
272    }
273
274    /// Tries to downcast from `dyn Widget` to a concrete [`Widget`]
275    pub fn try_downcast<W2: Widget>(&self) -> Option<Handle<W2>> {
276        Some(Handle {
277            widget: self.widget.try_downcast()?,
278            area: self.area.clone(),
279            mask: self.mask.clone(),
280            related: self.related.clone(),
281            is_closed: self.is_closed.clone(),
282            master: self.master.clone(),
283            update_requested: self.update_requested.clone(),
284        })
285    }
286
287    ////////// Refined access functions
288
289    /// A shared reference to the [`Text`] of the [`Widget`]
290    ///
291    /// This is the same as calling `handle.read(pa).text()`.
292    pub fn text<'p>(&'p self, pa: &'p Pass) -> &'p Text {
293        self.read(pa).text()
294    }
295
296    /// A mutable reference to the [`Text`] of the [`Widget`]
297    ///
298    /// This is the same as calling `handle.write(pa).text_mut()`.
299    pub fn text_mut<'p>(&'p self, pa: &'p mut Pass) -> TextMut<'p> {
300        self.write(pa).text_mut()
301    }
302
303    /// The [`TextParts`] of the [`Widget`]
304    ///
305    /// You can use this in order to get a shared reference to the
306    /// [`Bytes`] and [`Selections`], while maintaining a mutable
307    /// reference to the [`Tags`] of the [`Text`], letting you place
308    /// [`Tag`]s while still reading other information from the
309    /// [`Widget`]
310    ///
311    /// This is the same as calling `handle.text_mut().parts()`.
312    ///
313    /// [`Bytes`]: crate::text::Bytes
314    /// [`Tags`]: crate::text::Tags
315    /// [`Tag`]: crate::text::Tag
316    pub fn text_parts<'p>(&'p self, pa: &'p mut Pass) -> TextParts<'p> {
317        self.write(pa).text_mut().parts()
318    }
319
320    /// A shared reference to the [`Selections`] of the [`Widget`]'s
321    /// [`Text`]
322    ///
323    /// This is the same as calling `handle.read(pa).selections()`.
324    pub fn selections<'p>(&'p self, pa: &'p Pass) -> &'p Selections {
325        self.read(pa).text().selections()
326    }
327
328    /// A mutable reference to the [`Selections`] of the [`Widget`]'s
329    /// [`Text`]
330    ///
331    /// This is the same as calling
332    /// `handle.write(pa).selections_mut()`.
333    pub fn selections_mut<'p>(&'p self, pa: &'p mut Pass) -> &'p mut Selections {
334        self.write(pa).text_mut().selections_mut()
335    }
336
337    ////////// Selection Editing functions
338
339    /// Edits the nth [`Selection`] in the [`Text`]
340    ///
341    /// Once dropped, the [`Selection`] in this [`Cursor`] will be
342    /// added back to the list of [`Selection`]s, unless it is
343    /// [destroyed]
344    ///
345    /// If you want to edit on the main selection, see [`edit_main`],
346    /// if you want to edit on many [`Selection`]s, see
347    /// [`edit_iter`].
348    ///
349    /// Just like all other `edit` methods, this one will populate the
350    /// [`Selections`], so if there are no [`Selection`]s, it will
351    /// create one at [`Point::default`].
352    ///
353    /// [destroyed]: Cursor::destroy
354    /// [`edit_main`]: Self::edit_main
355    /// [`edit_iter`]: Self::edit_iter
356    /// [`Point::default`]: crate::text::Point::default
357    pub fn edit_nth<Ret>(
358        &self,
359        pa: &mut Pass,
360        n: usize,
361        edit: impl FnOnce(Cursor<W>) -> Ret,
362    ) -> Ret {
363        fn get_parts<'a, W: Widget + ?Sized>(
364            pa: &'a mut Pass,
365            handle: &'a Handle<W>,
366            n: usize,
367        ) -> (Selection, bool, &'a mut W, &'a Area) {
368            let (widget, area) = handle.write_with_area(pa);
369            let selections = widget.text_mut().selections_mut();
370            selections.populate();
371            let Some((selection, was_main)) = selections.remove(n) else {
372                panic!("Selection index {n} out of bounds");
373            };
374
375            (selection, was_main, widget, area)
376        }
377
378        let (selection, was_main, widget, area) = get_parts(pa, self, n);
379
380        let mut selections = vec![Some(ModSelection::new(selection, n, was_main))];
381
382        let ret = edit(Cursor::new(&mut selections, 0, (widget, area), None));
383
384        crate::mode::reinsert_selections(selections.into_iter().flatten(), widget, None);
385
386        ret
387    }
388
389    /// Edits the main [`Selection`] in the [`Text`]
390    ///
391    /// Once dropped, the [`Selection`] in this [`Cursor`] will be
392    /// added back to the list of [`Selection`]s, unless it is
393    /// [destroyed]
394    ///
395    /// If you want to edit on the `nth` selection, see [`edit_nth`],
396    /// same for [`edit_last`], if you want to edit on many
397    /// [`Selection`]s, see [`edit_iter`].
398    ///
399    /// Just like all other `edit` methods, this one will populate the
400    /// [`Selections`], so if there are no [`Selection`]s, it will
401    /// create one at [`Point::default`].
402    ///
403    /// [destroyed]: Cursor::destroy
404    /// [`edit_nth`]: Self::edit_nth
405    /// [`edit_last`]: Self::edit_last
406    /// [`edit_iter`]: Self::edit_iter
407    /// [`Point::default`]: crate::text::Point::default
408    pub fn edit_main<Ret>(&self, pa: &mut Pass, edit: impl FnOnce(Cursor<W>) -> Ret) -> Ret {
409        self.edit_nth(
410            pa,
411            self.widget.read(pa).text().selections().main_index(),
412            edit,
413        )
414    }
415
416    /// Edits the last [`Selection`] in the [`Text`]
417    ///
418    /// Once dropped, the [`Selection`] in this [`Cursor`] will be
419    /// added back to the list of [`Selection`]s, unless it is
420    /// [destroyed]
421    ///
422    /// If you want to edit on the `nth` selection, see [`edit_nth`],
423    /// same for [`edit_main`], if you want to edit on many
424    /// [`Selection`]s, see [`edit_iter`].
425    ///
426    /// Just like all other `edit` methods, this one will populate the
427    /// [`Selections`], so if there are no [`Selection`]s, it will
428    /// create one at [`Point::default`].
429    ///
430    /// [destroyed]: Cursor::destroy
431    /// [`edit_nth`]: Self::edit_nth
432    /// [`edit_main`]: Self::edit_main
433    /// [`edit_iter`]: Self::edit_iter
434    /// [`Point::default`]: crate::text::Point::default
435    pub fn edit_last<Ret>(&self, pa: &mut Pass, edit: impl FnOnce(Cursor<W>) -> Ret) -> Ret {
436        let len = self.widget.read(pa).text().selections().len();
437        self.edit_nth(pa, len.saturating_sub(1), edit)
438    }
439
440    /// A [`Lender`] over all [`Cursor`]s of the [`Text`]
441    ///
442    /// This lets you easily iterate over all [`Selection`]s, without
443    /// having to worry about insertion affecting the order at which
444    /// they are edited (like what repeated calls to [`edit_nth`]
445    /// would do)
446    ///
447    /// Note however that you can't use a [`Lender`] (also known as a
448    /// lending iterator) in a `for` loop, but you should be able
449    /// to just `while let Some(e) = editors.next() {}` or
450    /// `handle.edit_iter().for_each(|_| {})` instead.
451    ///
452    /// Just like all other `edit` methods, this one will populate the
453    /// [`Selections`], so if there are no [`Selection`]s, it will
454    /// create one at [`Point::default`].
455    ///
456    /// [`edit_nth`]: Self::edit_nth
457    /// [`Point::default`]: crate::text::Point::default
458    pub fn edit_iter<Ret>(&self, pa: &mut Pass, edit: impl FnOnce(Cursors<'_, W>) -> Ret) -> Ret {
459        edit(self.get_iter(pa))
460    }
461
462    /// A shortcut for iterating over all selections
463    ///
464    /// This is the equivalent of calling:
465    ///
466    /// ```rust
467    /// # duat_core::doc_duat!(duat);
468    /// # use duat::prelude::*;
469    /// # fn test(pa: &mut Pass, handle: Handle) {
470    /// handle.edit_iter(pa, |iter| iter.for_each(|e| { /* .. */ }));
471    /// # }
472    /// ```
473    ///
474    /// But it can't return a value, and is meant to reduce the
475    /// indentation that will inevitably come from using the
476    /// equivalent long form call.
477    pub fn edit_all(&self, pa: &mut Pass, edit: impl FnMut(Cursor<W>)) {
478        self.get_iter(pa).for_each(edit);
479    }
480
481    fn get_iter<'a>(&'a self, pa: &'a mut Pass) -> Cursors<'a, W> {
482        let (widget, area) = self.write_with_area(pa);
483        widget.text_mut().selections_mut().populate();
484
485        Cursors::new(0, widget, area)
486    }
487
488    ////////// Area functions
489
490    /// Scrolls the [`Text`] veritcally by an amount
491    ///
492    /// If [`PrintOpts.allow_overscroll`] is set, then the [`Text`]
493    /// will be allowed to scroll beyond the last line, up until
494    /// reaching the `scrolloff.y` value.
495    ///
496    /// [`PrintOpts.allow_overscroll`]: crate::opts::PrintOpts::allow_overscroll
497    pub fn scroll_ver(&self, pa: &mut Pass, dist: i32) {
498        let (widget, area) = self.write_with_area(pa);
499        area.scroll_ver(widget.text(), dist, widget.get_print_opts());
500        self.widget.declare_written();
501    }
502
503    /// Scrolls the [`Text`] to the visual line of a [`TwoPoints`]
504    ///
505    /// If `scroll_beyond` is set, then the [`Text`] will be allowed
506    /// to scroll beyond the last line, up until reaching the
507    /// `scrolloff.y` value.
508    pub fn scroll_to_points(&self, pa: &mut Pass, points: TwoPoints) {
509        let (widget, area) = self.write_with_area(pa);
510        area.scroll_to_points(widget.text(), points, widget.get_print_opts());
511        self.widget.declare_written();
512    }
513
514    /// The start points that should be printed
515    pub fn start_points(&self, pa: &Pass) -> TwoPoints {
516        let widget = self.widget.read(pa);
517        self.area
518            .start_points(pa, widget.text(), widget.get_print_opts())
519    }
520
521    /// The end points that should be printed
522    pub fn end_points(&self, pa: &Pass) -> TwoPoints {
523        let widget = self.widget.read(pa);
524        self.area
525            .end_points(pa, widget.text(), widget.get_print_opts())
526    }
527
528    ////////// Querying functions
529
530    /// This [`Handle`]'s [`Widget`]
531    pub fn widget(&self) -> &RwData<W> {
532        &self.widget
533    }
534
535    /// This [`Handle`]'s [`RwArea`]
536    pub fn area(&self) -> &RwArea {
537        &self.area
538    }
539
540    /// Gets this [`Handle`]'s mask
541    ///
542    /// This mask is going to be used to map [`Form`]s to other
543    /// [`Form`]s when printing. To see more about how masks work, see
544    /// [`form::enable_mask`].
545    ///
546    /// [`Form`]: crate::form::Form
547    /// [`form::enable_mask`]: crate::form::enable_mask
548    pub fn mask(&self) -> &Arc<Mutex<&'static str>> {
549        &self.mask
550    }
551
552    /// Sets this [`Handle`]'s mask, returning the previous one
553    ///
554    /// This mask is going to be used to map [`Form`]s to other
555    /// [`Form`]s when printing. To see more about how masks work, see
556    /// [`form::enable_mask`].
557    ///
558    /// [`Form`]: crate::form::Form
559    /// [`form::enable_mask`]: crate::form::enable_mask
560    pub fn set_mask(&self, mask: &'static str) -> &'static str {
561        self.widget.declare_written();
562        std::mem::replace(&mut self.mask.lock().unwrap(), mask)
563    }
564
565    /// Wether someone else called [`write`] or [`write_as`] since the
566    /// last [`read`] or [`write`]
567    ///
568    /// Do note that this *DOES NOT* mean that the value inside has
569    /// actually been changed, it just means a mutable reference was
570    /// acquired after the last call to [`has_changed`].
571    ///
572    /// Some types like [`Text`], and traits like [`Widget`] offer
573    /// [`needs_update`] methods, you should try to determine what
574    /// parts to look for changes.
575    ///
576    /// Generally though, you can use this method to gauge that.
577    ///
578    /// [`write`]: RwData::write
579    /// [`write_as`]: RwData::write_as
580    /// [`read`]: RwData::read
581    /// [`has_changed`]: RwData::has_changed
582    /// [`Text`]: crate::text::Text
583    /// [`Widget`]: crate::ui::Widget
584    /// [`needs_update`]: crate::ui::Widget::needs_update
585    pub fn has_changed(&self, pa: &Pass) -> bool {
586        self.widget.has_changed() || self.area.has_changed(pa)
587    }
588
589    /// Wether the [`RwData`] within and another point to the same
590    /// value
591    pub fn ptr_eq<T: ?Sized>(&self, other: &RwData<T>) -> bool {
592        self.widget.ptr_eq(other)
593    }
594
595    /// The [`Widget`]'s [`PrintOpts`]
596    pub fn opts(&self, pa: &Pass) -> PrintOpts {
597        self.widget.read(pa).get_print_opts()
598    }
599
600    /// Request that this [`Handle`] be updated
601    ///
602    /// You can use this to request updates from other threads.
603    pub fn request_update(&self) {
604        self.update_requested.store(true, Ordering::Relaxed);
605    }
606
607    ////////// Related Handles
608
609    /// Returns the [`Handle`] this one was pushed to, if it was
610    /// pushed to another
611    ///
612    /// Will return [`Some`] if this `self` was created by calling
613    /// [`Handle::push_outer_widget`], [`Handle::push_inner_widget`],
614    /// [`Handle::spawn_widget`], or if the [`Widget`] was [spawned]
615    /// on the master's [`Text`]
616    ///
617    /// [spawned]: crate::text::SpawnTag
618    pub fn master(&self) -> Result<&Handle<dyn Widget>, Text> {
619        self.master
620            .as_ref()
621            .map(|handle| handle.as_ref())
622            .ok_or_else(|| txt!("Widget was not pushed to another"))
623    }
624
625    /// Returns the [`Handle<Buffer>`] this one was pushed to, if it
626    /// was pushed to one
627    ///
628    /// Will return [`Some`] if this `self` was created by calling
629    /// [`Handle::push_outer_widget`], [`Handle::push_inner_widget`],
630    /// [`Handle::spawn_widget`], or if the [`Widget`] was [spawned]
631    /// on the master's [`Text`]
632    ///
633    /// [spawned]: crate::text::SpawnTag
634    pub fn buffer(&self) -> Result<Handle, Text> {
635        self.master
636            .as_ref()
637            .and_then(|handle| handle.try_downcast())
638            .ok_or_else(|| txt!("Widget was not pushed to a [a]Buffer"))
639    }
640
641    /// Reads related [`Widget`]s of type `W2`, as well as its
642    /// [`Area`]
643    ///
644    /// This can also be done by calling [`Handle::get_related`], and
645    /// [`Handle::read`], but this function should generally be
646    /// faster, since there is no cloning of [`Arc`]s going on.
647    pub fn read_related<'a, W2: Widget>(
648        &'a self,
649        pa: &'a Pass,
650    ) -> impl Iterator<Item = (&'a W2, &'a Area, WidgetRelation)> {
651        self.read_as(pa)
652            .map(|w| (w, self.area().read(pa), WidgetRelation::Main))
653            .into_iter()
654            .chain(self.related.0.read(pa).iter().filter_map(|(handle, rel)| {
655                handle
656                    .read_as(pa)
657                    .map(|w| (w, handle.area().read(pa), *rel))
658            }))
659    }
660
661    /// Gets related [`Handle`]s of type [`Widget`]
662    ///
663    /// If you are doing this just to read the [`Widget`] and
664    /// [`Area`], consider using [`Handle::read_related`].
665    pub fn get_related<'a, W2: Widget>(
666        &'a self,
667        pa: &'a Pass,
668    ) -> impl Iterator<Item = (Handle<W2>, WidgetRelation)> + 'a {
669        self.try_downcast()
670            .zip(Some(WidgetRelation::Main))
671            .into_iter()
672            .chain(
673                self.related
674                    .0
675                    .read(pa)
676                    .iter()
677                    .filter_map(|(handle, rel)| handle.try_downcast().zip(Some(*rel))),
678            )
679    }
680
681    /// Raw access to the related widgets
682    pub(crate) fn related(&self) -> &RwData<Vec<(Handle<dyn Widget>, WidgetRelation)>> {
683        &self.related.0
684    }
685
686    ////////// Other methods
687
688    /// Pushes a [`Widget`] around this one
689    ///
690    /// This `Widget` will be placed internally, i.e., around the
691    /// [`Area`] of `self`. This is in contrast to
692    /// [`Handle::push_outer_widget`], which will push around the
693    /// "cluster master" of `self`.
694    ///
695    /// A cluster master is the collection of every `Widget` that was
696    /// pushed around a central one with [`PushSpecs::cluster`] set to
697    /// `true`.
698    ///
699    /// Both of these functions behave identically in the situation
700    /// where no other [`Widget`]s were pushed around `self`.
701    ///
702    /// However, if, for example, a [`Widget`] was previously pushed
703    /// below `self`, when pushing to the left, the following would
704    /// happen:
705    ///
706    /// ```text
707    /// ╭────────────────╮    ╭─────┬──────────╮
708    /// │                │    │     │          │
709    /// │      self      │    │ new │   self   │
710    /// │                │ -> │     │          │
711    /// ├────────────────┤    ├─────┴──────────┤
712    /// │      old       │    │      old       │
713    /// ╰────────────────╯    ╰────────────────╯
714    /// ```
715    ///
716    /// While in [`Handle::push_outer_widget`], this happens instead:
717    ///
718    /// ```text
719    /// ╭────────────────╮    ╭─────┬──────────╮
720    /// │                │    │     │          │
721    /// │      self      │    │     │   self   │
722    /// │                │ -> │ new │          │
723    /// ├────────────────┤    │     ├──────────┤
724    /// │      old       │    │     │   old    │
725    /// ╰────────────────╯    ╰─────┴──────────╯
726    /// ```
727    ///
728    /// Note that `new` was pushed _around_ other clustered widgets in
729    /// the second case, not just around `self`.
730    pub fn push_inner_widget<PW: Widget>(
731        &self,
732        pa: &mut Pass,
733        widget: PW,
734        specs: PushSpecs,
735    ) -> Handle<PW> {
736        context::windows()
737            .push_widget(pa, (&self.area, None, specs), widget, Some(&self.area))
738            .unwrap()
739    }
740
741    /// Pushes a [`Widget`] around the "cluster master" of this one
742    ///
743    /// A cluster master is the collection of every `Widget` that was
744    /// pushed around a central one with [`PushSpecs::cluster`] set to
745    /// `true`.
746    ///
747    /// This [`Widget`] will be placed externally, i.e., around every
748    /// other [`Widget`] that was pushed around `self`. This is in
749    /// contrast to [`Handle::push_inner_widget`], which will push
750    /// only around `self`.
751    ///
752    /// Both of these functions behave identically in the situation
753    /// where no other [`Widget`]s were pushed around `self`.
754    ///
755    /// However, if, for example, a [`Widget`] was previously pushed
756    /// to the left of `self`, when pushing to the left again, the
757    /// following would happen:
758    ///
759    /// ```text
760    /// ╭──────┬──────────╮    ╭─────┬─────┬──────╮
761    /// │      │          │    │     │     │      │
762    /// │      │          │    │     │     │      │
763    /// │  old │   self   │ -> │ new │ old │ self │
764    /// │      │          │    │     │     │      │
765    /// │      │          │    │     │     │      │
766    /// ╰──────┴──────────╯    ╰─────┴─────┴──────╯
767    /// ```
768    ///
769    /// While in [`Handle::push_inner_widget`], this happens instead:
770    ///
771    /// ```text
772    /// ╭──────┬──────────╮    ╭─────┬─────┬──────╮
773    /// │      │          │    │     │     │      │
774    /// │      │          │    │     │     │      │
775    /// │  old │   self   │ -> │ old │ new │ self │
776    /// │      │          │    │     │     │      │
777    /// │      │          │    │     │     │      │
778    /// ╰──────┴──────────╯    ╰─────┴─────┴──────╯
779    /// ```
780    ///
781    /// Note that `new` was pushed _around_ other clustered widgets in
782    /// the first case, not just around `self`.
783    pub fn push_outer_widget<PW: Widget>(
784        &self,
785        pa: &mut Pass,
786        widget: PW,
787        specs: PushSpecs,
788    ) -> Handle<PW> {
789        if let Some(master) = self.area().get_cluster_master(pa) {
790            context::windows()
791                .push_widget(pa, (&master, None, specs), widget, Some(self.area()))
792                .unwrap()
793        } else {
794            context::windows()
795                .push_widget(pa, (&self.area, None, specs), widget, Some(self.area()))
796                .unwrap()
797        }
798    }
799
800    /// Spawns a floating [`Widget`]
801    pub fn spawn_widget<SW: Widget>(
802        &self,
803        pa: &mut Pass,
804        widget: SW,
805        specs: DynSpawnSpecs,
806    ) -> Option<Handle<SW>> {
807        context::windows().spawn_on_widget(pa, (&self.area, specs), widget)
808    }
809
810    /// Closes this `Handle`, removing the [`Widget`] from the
811    /// [`Window`]
812    ///
813    /// [`Window`]: crate::ui::Window
814    pub fn close(&self, pa: &mut Pass) -> Result<(), Text> {
815        context::windows().close(pa, self)
816    }
817
818    /// Wether this `Handle` was already closed
819    pub fn is_closed(&self, pa: &Pass) -> bool {
820        *self.is_closed.read(pa)
821    }
822
823    /// Declares that this `Handle` has been closed
824    pub(crate) fn declare_closed(&self, pa: &mut Pass) {
825        *self.is_closed.write(pa) = true;
826    }
827}
828
829impl<W: Widget> Handle<W> {
830    /// Transforms this [`Handle`] into a [`Handle<dyn Widget>`]
831    pub fn to_dyn(&self) -> Handle<dyn Widget> {
832        Handle {
833            widget: self.widget.to_dyn_widget(),
834            // TODO: Arc wrapper, and Area: !Clone
835            area: self.area.clone(),
836            mask: self.mask.clone(),
837            related: self.related.clone(),
838            is_closed: self.is_closed.clone(),
839            master: self.master.clone(),
840            update_requested: self.update_requested.clone(),
841        }
842    }
843}
844
845// SAFETY: The only parts that are accessible from other threads are
846// the atomic counters from the Arcs. Everything else can only be
847// acquired when there is a Pass, i.e., on the main thread.
848unsafe impl<W: Widget + ?Sized> Send for Handle<W> {}
849unsafe impl<W: Widget + ?Sized> Sync for Handle<W> {}
850
851impl<W1, W2> PartialEq<Handle<W2>> for Handle<W1>
852where
853    W1: Widget + ?Sized,
854    W2: Widget + ?Sized,
855{
856    fn eq(&self, other: &Handle<W2>) -> bool {
857        self.widget().ptr_eq(other.widget())
858    }
859}
860
861impl<W: Widget + ?Sized> Clone for Handle<W> {
862    fn clone(&self) -> Self {
863        Self {
864            widget: self.widget.clone(),
865            area: self.area.clone(),
866            mask: self.mask.clone(),
867            related: self.related.clone(),
868            is_closed: self.is_closed.clone(),
869            master: self.master.clone(),
870            update_requested: self.update_requested.clone(),
871        }
872    }
873}
874
875impl<W: Widget + ?Sized> std::fmt::Debug for Handle<W> {
876    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
877        f.debug_struct("Handle")
878            .field("mask", &self.mask)
879            .finish_non_exhaustive()
880    }
881}
882
883#[derive(Clone)]
884struct RelatedWidgets(RwData<Vec<(Handle<dyn Widget>, WidgetRelation)>>);
885
886/// What relation this [`Widget`] has to its parent
887#[derive(Clone, Copy, Debug)]
888pub enum WidgetRelation {
889    /// The main widget of the cluster, most commonly a [`Buffer`]
890    ///
891    /// [`Buffer`]: crate::buffer::Buffer
892    Main,
893    /// A [`Widget`] that was pushed around the main `Widget`, e.g.
894    /// [`LineNumbers`]
895    ///
896    /// [`LineNumbers`]: docs.rs/duat/latest/duat/widgets/struct.LineNumbers.html
897    Pushed,
898    /// A [`Widget`] that was spawned on the `Widget`, e.g. completion
899    /// lists
900    Spawned,
901}