duat-core 0.10.0

The core of Duat, a highly customizable text editor.
Documentation
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
//! Traits that should be implemented by interface implementations of
//! Duat.
//!
//! This module contains the traits [`RawUi`] and [`RawArea`], which
//! should be used by RawUi implementations of Duat. By implementing
//! those traits, you will comply with the requirements to run Duat
//! with a custom interface, such as web app or some other type of
//! GUI.
//!
//! Normally, in user code, they will encounter the
//! [`Area`] and (sometimes) the [`Ui`] from the `type_erased` module.
//! These are dynamic containers for the traits in this module, and
//! are used in order to improve ergonomics and compile times.
//!
//! [`Area`]: super::Area
//! [`Ui`]: super::Ui
use std::ffi::OsString;

use bincode::{Decode, Encode};

use crate::{
    context::DuatSender,
    form::Painter,
    mode::{TwoPointsPlace, VPoint},
    opts::PrintOpts,
    text::{Point, Text, TwoPoints},
    ui::{Columns, Coord, DynSpawnSpecs, PrintedLine, PushSpecs, SpawnId, StaticSpawnSpecs},
};

/// All the methods that a working gui/tui will need to implement in
/// order to be used by Duat.
///
/// This includes the following functionalities:
///
/// - Creating new windows, which start out with one [`RawArea`].
/// - Spawning floating `RawArea`s around other `RawArea`s.
/// - Spawning floating `RawArea`s in [`Text`]s, which should be able
///   to move as the `Text` itself does.
/// - Pushing `RawArea`s around other `RawArea`s, which include
///   floating ones.
/// - Closing `RawArea`s at will, which should cascading all pushed or
///   spawned `RawArea`s
///
/// [`TypeId`]: std::any::TypeId
pub trait RawUi: Sized + Send + Sync + 'static {
    /// The [`RawArea`] of this [`RawUi`]
    type Area: RawArea;

    ////////// Application address space functions.

    /// A function to be executed when opening Duat.
    ///
    /// This, alongside [`RawUi::close`] is the only functions that
    /// will be executed from the Duat application. This means
    /// that any changes on `static` variables will not be
    /// reflected on the config [`Command`], so keep that in mind.
    ///
    /// You can additionally provide a list of extra arguments to be
    /// passed to the child process. Duat makes use of the first
    /// six arguments, but after that, you can put in whatever you
    /// want. (Note, you should call something like
    /// `std::env::args().skip(7)`, since the first argument will be
    /// the path of the executed config).
    ///
    /// [`Command`]: std::process::Command
    fn open() -> Vec<OsString>;

    /// A function to be executed when closing Duat.
    ///
    /// This, alongside [`RawUi::open`] is the only functions that
    /// will be executed from the Duat application. This means
    /// that any changes on `static` variables will not be
    /// reflected on the config process, so keep that in mind.
    fn close();

    ////////// Configuration address space functions.

    /// Returns a new `Self`.
    ///
    /// This struct will be kept as a static variable for the duration
    /// of the program. You should make use of this function to do
    /// initialization that takes place _within_ the configuration
    /// crate address space.
    fn load(duat_tx: DuatSender) -> Self;

    /// Unloads the [`RawUi`].
    ///
    /// Unlike [`RawUi::close`], this will happen both when Duat
    /// unloads the configuration or when it closes the app.
    ///
    /// Both of these things will happen inside of the configuration
    /// crate's address space.
    fn unload(&'static self);

    /// Initiates and returns a new "master" [`RawArea`].
    ///
    /// This [`RawArea`] must not have any parents, and must be placed
    /// on a new window, that is, a plain region with nothing in
    /// it.
    ///
    /// [`RawArea`]: RawUi::Area
    fn new_root(&'static self, cache: <Self::Area as RawArea>::Cache) -> Self::Area;

    /// Initiates and returns a new "dynamic spawned" [`RawArea`].
    ///
    /// This is one of three ways of spawning floating [`Widget`]s.
    /// Another is with [`RawArea::spawn`], in which a `Widget` will
    /// be bolted on the edges of another. Another one is through
    /// [`RawUi::new_static_spawned`].
    ///
    /// [`Widget`]: super::Widget
    fn new_dyn_spawned(
        &'static self,
        id: SpawnId,
        specs: DynSpawnSpecs,
        cache: <Self::Area as RawArea>::Cache,
        win: usize,
    ) -> Self::Area;

    /// Initiates and returns a new "static spawned" [`RawArea`].
    ///
    /// This is one of three ways of spawning floating [`Widget`]s.
    /// Another is with [`RawArea::spawn`], in which a `Widget` will
    /// be bolted on the edges of another. Another one is through
    /// [`RawUi::new_dyn_spawned`].
    ///
    /// [`Widget`]: super::Widget
    fn new_static_spawned(
        &'static self,
        id: SpawnId,
        specs: StaticSpawnSpecs,
        cache: <Self::Area as RawArea>::Cache,
        win: usize,
    ) -> Self::Area;

    /// Switches the currently active window.
    ///
    /// This will only happen to with window indices that are actual
    /// windows. If at some point, a window index comes up that is not
    /// actually a window, that's a bug.
    fn switch_window(&'static self, win: usize);

    /// Flush the layout.
    ///
    /// When this function is called, it means that Duat has finished
    /// adding or removing widgets, so the ui should calculate the
    /// layout.
    fn flush_layout(&'static self);

    /// Prints the layout.
    ///
    /// Since printing runs all on the same thread, it is most
    /// efficient to call a printing function after all the widgets
    /// are done updating, I think.
    fn print(&'static self);

    /// Removes a window from the [`RawUi`].
    ///
    /// This should keep the current active window consistent. That
    /// is, if the current window was ahead of the deleted one, it
    /// should be shifted back, so that the same window is still
    /// displayed.
    fn remove_window(&'static self, win: usize);

    /// The bottom right [`Coord`] on the screen.
    ///
    /// Since the top left coord is `Coord { x: 0.0, y: 0.0 }`, this
    /// is also the size of the window.
    fn size(&'static self) -> Coord;
}

/// A region on screen where you can print [`Text`].
///
/// These represent the entire GUI of Duat, the only parts of the
/// screen where text may be printed.
///
/// Depending on your application, you may have areas that don't make
/// use of `Text`, like switches or a button, or a scrollbar.
pub trait RawArea: Sized + PartialEq + 'static {
    /// Something to be kept between app instances/reloads.
    ///
    /// The most useful thing to keep in this case is the
    /// [`PrintInfo`], but you could include other things
    ///
    /// [`PrintInfo`]: RawArea::PrintInfo
    type Cache: Default + std::fmt::Debug + Encode + Decode<()> + 'static;
    /// Information about what parts of a [`Text`] should be printed.
    ///
    /// For the [`term-ui`], for example, this is quite simple, it
    /// only needs to include the [`TwoPoints`]s on the top left
    /// corner in order to print correctly, but your own [`RawUi`]
    /// could differ in what it needs to keep, if it makes
    /// use of smooth scrolling, for example.
    ///
    /// [`term-ui`]: docs.rs/term-ui/latest/term_ui
    type PrintInfo: Default + Clone + Send + Sync + PartialEq + Eq + 'static;

    ////////// RawArea modification

    /// Creates an `RawArea` around this one.
    ///
    /// Will return the newly created `RawArea` as well as a parent
    /// `RawArea`, if one was created to house both of them.
    ///
    /// If this `RawArea` was previously [deleted], will return
    /// [`None`].
    ///
    /// As an example, assuming that [`self`] has an index of `0`,
    /// pushing an area to `self` on [`Side::Left`] would create
    /// 2 new areas:
    ///
    /// ```text
    /// ╭────────0────────╮     ╭────────1────────╮
    /// │                 │     │╭──2───╮╭───0───╮│
    /// │      self       │ --> ││      ││ self  ││
    /// │                 │     │╰──────╯╰───────╯│
    /// ╰─────────────────╯     ╰─────────────────╯
    /// ```
    ///
    /// So now, there is a new area `1`, which is the parent of the
    /// areas `0` and `2`. When a new parent is created, it should be
    /// returned as the second element in the tuple.
    ///
    /// That doesn't always happen though. For example, pushing
    /// another area to the [`Side::Right`] of `1`, `2`, or `0`,
    /// in this situation, should not result in the creation of a
    /// new parent:
    ///
    /// ```text
    /// ╭────────1────────╮     ╭────────1────────╮
    /// │╭──2───╮╭───0───╮│     │╭─2─╮╭──0──╮╭─3─╮│
    /// ││      ││ self  ││     ││   ││self ││   ││
    /// │╰──────╯╰───────╯│     │╰───╯╰─────╯╰───╯│
    /// ╰─────────────────╯     ╰─────────────────╯
    /// ```
    ///
    /// And so this function should return `(3, None)`.
    ///
    /// [deleted]: RawArea::delete
    /// [`Side::Left`]: super::Side::Left
    /// [`Side::Right`]: super::Side::Right
    fn push(
        &self,
        _: UiPass,
        specs: PushSpecs,
        on_files: bool,
        cache: Self::Cache,
    ) -> Option<(Self, Option<Self>)>;

    /// Spawns a floating area on this `RawArea`.
    ///
    /// This function will take a list of [`DynSpawnSpecs`], taking
    /// the first one that fits, and readapting as the constraints
    /// are altered
    ///
    /// If this `RawArea` was previously [deleted], will return
    /// [`None`].
    ///
    /// [deleted]: RawArea::delete
    fn spawn(
        &self,
        _: UiPass,
        id: SpawnId,
        specs: DynSpawnSpecs,
        cache: Self::Cache,
    ) -> Option<Self>;

    /// Deletes this `RawArea`, signaling the closing of a
    /// [`Widget`].
    ///
    /// The first return value shall be `true` if the window housing
    /// this `RawArea` should be removed.
    ///
    /// If the `RawArea`'s parent was also deleted, return it.
    ///
    /// [`Widget`]: super::Widget
    fn delete(&self, _: UiPass) -> (bool, Vec<Self>);

    /// Swaps this `RawArea` with another one.
    ///
    /// The swapped `RawArea`s will be cluster masters of the
    /// respective `RawArea`s. As such, if they belong to the same
    /// master, nothing happens.
    ///
    /// This function will _never_ be called such that one of the
    /// `RawArea`s is a decendant of the other, so the [`RawUi`]
    /// implementor doesn't need to worry about that possibility.
    ///
    /// It can fail if either of the `RawArea`s was already deleted,
    /// or if no swap happened because they belonged to the same
    /// cluster master.
    fn swap(&self, _: UiPass, rhs: &Self) -> bool;

    ////////// Constraint changing functions

    /// Sets a width for the `RawArea`.
    fn set_width(&self, _: UiPass, width: f32) -> Result<(), Text>;

    /// Sets a height for the `RawArea`.
    fn set_height(&self, _: UiPass, height: f32) -> Result<(), Text>;

    /// Hides the `RawArea`.
    fn hide(&self, _: UiPass) -> Result<(), Text>;

    /// Reveals the `RawArea`.
    fn reveal(&self, _: UiPass) -> Result<(), Text>;

    /// What size the given [`Text`] would occupy, if unwrapped.
    ///
    /// The x component represents the width needed to show the
    /// `Text` without wrapping, while the y component represents
    /// the height needed to show all the lines of the `Text`.
    ///
    /// This function does take into account the size of the screen,
    /// and assumes that you will want to iterate from the start of
    /// the `Text`. Therefore, it will preemptively stop iterating
    /// through the `Text` when the remaining characters wouldn't show
    /// up on screen.
    fn size_of_text(&self, _: UiPass, opts: PrintOpts, text: &Text) -> Result<Coord, Text>;

    /// Tells the [`RawUi`] that this `RawArea` is the one that is
    /// currently focused.
    ///
    /// Should make `self` the active `RawArea` while deactivating
    /// any other active `RawArea`.
    fn set_as_active(&self, _: UiPass);

    ////////// Printing functions

    /// Prints the [`Text`].
    fn print(&self, _: UiPass, text: &Text, opts: PrintOpts, painter: Painter);

    /// The current printing information of the area.
    fn get_print_info(&self, _: UiPass) -> Self::PrintInfo;

    /// Sets a previously acquired [`PrintInfo`] to the area.
    ///
    /// [`PrintInfo`]: RawArea::PrintInfo
    fn set_print_info(&self, _: UiPass, info: Self::PrintInfo);

    /// For a given [`Text`], returns a list of [`PrintedLine`]s.
    ///
    /// This should list all lines that are presently on screen. Note
    /// that a "line" in this context represents all characters in a
    /// row, not sequences divided by `\n`.
    ///
    /// Returns [`None`] if the `Area` was deleted.
    fn get_printed_lines(
        &self,
        _: UiPass,
        text: &Text,
        opts: PrintOpts,
    ) -> Option<Vec<PrintedLine>>;

    /// Move vertically from a [`Point`] in the `Text`.
    ///
    /// This should return a [`VPoint`], which is a struct that
    /// describes additional information about a position in the text,
    /// namely the character, visual, and wrapped distances from the
    /// start of the line.
    ///
    /// The `desired_col` parameter describes what visual distance
    /// from the start of the line is desired.
    fn move_ver(
        &self,
        _: UiPass,
        by: i32,
        text: &Text,
        point: Point,
        desired_col: Option<usize>,
        opts: PrintOpts,
    ) -> VPoint;

    /// Move vertically from a [`Point`] in the `Text` with wrapping.
    ///
    /// This should return a [`VPoint`], which is a struct that
    /// describes additional information about a position in the text,
    /// namely the character, visual, and wrapped distances from the
    /// start of the line.
    ///
    /// The `desired_col` parameter describes what visual distance
    /// from the start of the line is desired.
    fn move_ver_wrapped(
        &self,
        _: UiPass,
        by: i32,
        text: &Text,
        point: Point,
        desired_col: Option<usize>,
        opts: PrintOpts,
    ) -> VPoint;

    ////////// Points functions

    /// Scrolls the [`Text`] veritcally by an amount.
    ///
    /// If `scroll_beyond` is set, then the [`Text`] will be allowed
    /// to scroll beyond the last line, up until reaching the
    /// `scrolloff.y` value.
    fn scroll_ver(&self, _: UiPass, text: &Text, dist: i32, opts: PrintOpts);

    /// Scrolls the [`Text`] on all four directions until the given
    /// [`TwoPoints`] is within the [`ScrollOff`] range.
    ///
    /// There are two other scrolling methods for `RawArea`:
    /// [`scroll_ver`] and [`scroll_to_points`]. The difference
    /// between this and [`scroll_to_points`] is that this method
    /// doesn't do anything if the [`TwoPoints`] is already on screen.
    ///
    /// [`ScrollOff`]: crate::opts::ScrollOff
    /// [`scroll_ver`]: RawArea::scroll_ver
    /// [`scroll_to_points`]: RawArea::scroll_to_points
    fn scroll_around_points(&self, _: UiPass, text: &Text, points: TwoPoints, opts: PrintOpts);

    /// Scrolls the [`Text`] to the visual line of a [`TwoPoints`].
    ///
    /// This method takes [line wrapping] into account, so it's not
    /// the same as setting the starting points to the
    /// [`Text::visual_line_start`] of these [`TwoPoints`].
    ///
    /// If `scroll_beyond` is set, then the [`Text`] will be allowed
    /// to scroll beyond the last line, up until reaching the
    /// `scrolloff.y` value.
    ///
    /// [line wrapping]: crate::opts::PrintOpts::wrap_lines.
    fn scroll_to_points(&self, _: UiPass, text: &Text, points: TwoPoints, opts: PrintOpts);

    /// The start points that should be printed
    fn start_points(&self, _: UiPass, text: &Text, opts: PrintOpts) -> TwoPoints;

    /// The [`TwoPoints`] immediately after the last printed one.
    fn end_points(&self, _: UiPass, text: &Text, opts: PrintOpts) -> TwoPoints;

    ////////// Queries

    /// Whether or not [`self`] has changed.
    ///
    /// This would mean anything relevant that wouldn't be determined
    /// by [`PrintInfo`], this is most likely going to be the bounding
    /// box, but it may be something else.
    ///
    /// [`PrintInfo`]: RawArea::PrintInfo
    fn has_changed(&self, _: UiPass) -> bool;

    /// Whether or not [`self`] is the "master" of `other`.
    ///
    /// This can only happen if, by following [`self`]'s children, you
    /// would eventually reach `other`.
    fn is_master_of(&self, _: UiPass, other: &Self) -> bool;

    /// Returns the clustered master of [`self`], if there is one.
    ///
    /// If [`self`] belongs to a clustered group, return the most
    /// senior member of said cluster, which must hold all other
    /// members of the cluster.
    fn get_cluster_master(&self, _: UiPass) -> Option<Self>;

    /// Returns the statics from `self`.
    fn cache(&self, _: UiPass) -> Option<Self::Cache>;

    /// The top left [`Coord`] of this `Area`.
    fn top_left(&self, _: UiPass) -> Coord;

    /// The bottom right [`Coord`] of this `Area`.
    fn bottom_right(&self, _: UiPass) -> Coord;

    /// The [`TwoPoints`] where a [`Coord`] is found.
    ///
    /// Returns [`None`] if either the `RawArea` does not contain
    /// the given `Coord`, or if the `Coord` is in a position where
    /// [`Text`] is not printed.
    fn points_at_coord(
        &self,
        _: UiPass,
        text: &Text,
        coord: Coord,
        opts: PrintOpts,
    ) -> Option<TwoPointsPlace>;

    /// The [`Coord`] where the given [`TwoPoints`] would be printed.
    ///
    /// Returns [`None`] if the `TwoPoints` are not part of the
    /// [`Text`] or if they would be outside the screen.
    ///
    /// If you want to calculate the column of a `TwoPoints`,
    /// regardless of wether or not it would be printed, check out
    /// [`RawArea::column_at_points`].
    fn coord_at_points(
        &self,
        _: UiPass,
        text: &Text,
        points: TwoPoints,
        opts: PrintOpts,
    ) -> Option<Coord>;

    /// Returns column information about a [`TwoPoints`].
    ///
    /// If the points are part of the `Strs`, returns a [`Columns`]
    /// struct. This contains the `visual` column and the `wrapped`
    /// column.
    ///
    /// The former measures the distance since the last `\n` character
    /// or start of `Text`. The latter measures the distance since the
    /// last wrap, i.e., the distance to the left edge of the area.
    fn columns_at(
        &self,
        _: UiPass,
        text: &Text,
        points: TwoPoints,
        opts: PrintOpts,
    ) -> Option<Columns>;

    /// Returns `true` if this is the currently active `RawArea`.
    ///
    /// Only one `RawArea` should be active at any given moment.
    fn is_active(&self, _: UiPass) -> bool;
}

/// Prevents direct use of the [`RawArea`] functions.
///
/// The methods of `RawArea` are all meant to be accessed only
/// through the type erased [`RwArea`] and [`Area`].
///
/// Another guarantee of this struct is that any function that takes
/// it is guaranteed to be taking place in the main thread.
///
/// [`RwArea`]: super::RwArea
/// [`Area`]: super::Area
#[non_exhaustive]
#[derive(Clone, Copy)]
pub struct UiPass {}

impl UiPass {
    pub(super) const fn new() -> Self {
        UiPass {}
    }
}