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
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
//! Logging for Duat.
//!
//! This module defines types and functions for logging in Duat. It
//! defines the [`debug!`], [`info!`], [`warn!`] and [`error!`] macros
//! to directly log [`Text`] to Duat. They are essentially just
//! wrappers around the [`txt!`] macro which log information. This
//! module is also responsible for logging command results and panics.
use std::{
    panic::PanicHookInfo,
    sync::{
        Mutex,
        atomic::{AtomicUsize, Ordering},
    },
};

pub use log::{Level, Metadata};

pub use self::macros::*;
use crate::{hook, text::Text};

mod macros {
    #[doc(inline)]
    pub use crate::{debug, error, info, warn};

    /// Logs an error to Duat.
    ///
    /// Use this, as opposed to [`warn!`], [`info!`] or [`debug!`],
    /// if you want to tell the user that something explicitely
    /// failed, and they need to find a workaround, like failing
    /// to write to/read from a buffer, for example.
    ///
    /// This error follows the same construction as the [`txt!`]
    /// macro, and will create a [`Record`] inside of the [`Logs`],
    /// which can be accessed by anyone, at any time.
    ///
    /// The [`Record`] added to the [`Logs`] is related to
    /// [`log::Record`], from the [`log`] crate. But it differs in the
    /// sense that it is always `'static`, and instead of having an
    /// [`std::fmt::Arguments`] inside, it contains a [`Text`], making
    /// it a better fit for Duat.
    ///
    /// The connection to [`log::Record`] also means that external
    /// libraries can log information using the [`log`] crate, and it
    /// will also show up in Duat's [`Logs`]s, but reformatted to be a
    /// [`Text`] instead.
    ///
    /// # Custom location
    ///
    /// You can make use of a custom location by calling this macro
    /// and surounding the arguments in a `()` pair.
    ///
    /// ```rust
    /// # duat_core::doc_duat!(duat);
    /// use duat::prelude::{context::Location, *};
    ///
    /// # fn test() {
    /// context::error!(
    ///     ("This is my {}", "error"),
    ///     Location::new("some_file", 32, 10),
    /// );
    /// # }
    /// ```
    ///
    /// [`txt!`]: crate::text::txt
    /// [`Record`]: super::Record
    /// [`Logs`]: super::Logs
    /// [`Text`]: crate::text::Text
    #[macro_export]
    macro_rules! error {
        (($($arg:tt)+), $location:expr $(,)?) => {
            $crate::__log__!(
                $crate::context::Level::Error,
                $location,
                $($arg)+
            )
        };
        ($($arg:tt)+) => {
            $crate::__log__!(
                $crate::context::Level::Error,
                $crate::context::Location::from_panic_location(::std::panic::Location::caller()),
                $($arg)+
            )
        }
    }

    /// Logs an warning to Duat.
    ///
    /// Use this, as opposed to [`error!`], [`info!`] or [`debug!`],
    /// if you want to tell the user that something was partially
    /// successful, or that a failure happened, but
    /// it's near inconsequential.
    ///
    /// This error follows the same construction as the [`txt!`]
    /// macro, and will create a [`Record`] inside of the [`Logs`],
    /// which can be accessed by anyone, at any time.
    ///
    /// The [`Record`] added to the [`Logs`] is related to
    /// [`log::Record`], from the [`log`] crate. But it differs in the
    /// sense that it is always `'static`, and instead of having an
    /// [`std::fmt::Arguments`] inside, it contains a [`Text`], making
    /// it a better fit for Duat.
    ///
    /// The connection to [`log::Record`] also means that external
    /// libraries can log information using the [`log`] crate, and it
    /// will also show up in Duat's [`Logs`]s, but reformatted to be a
    /// [`Text`] instead.
    ///
    /// # Custom location
    ///
    /// You can make use of a custom location by calling this macro
    /// and surounding the arguments in a `()` pair.
    ///
    /// ```rust
    /// # duat_core::doc_duat!(duat);
    /// use duat::prelude::{context::Location, *};
    ///
    /// # fn test() {
    /// context::warn!(
    ///     ("This is my {}", "warning"),
    ///     Location::new("some_file", 32, 10),
    /// );
    /// # }
    /// ```
    ///
    /// [`txt!`]: crate::text::txt
    /// [`Record`]: super::Record
    /// [`Logs`]: super::Logs
    /// [`Text`]: crate::text::Text
    #[macro_export]
    macro_rules! warn {
        (($($arg:tt)+), $location:expr $(,)?) => {
            $crate::__log__!(
                $crate::context::Level::Warn,
                $location,
                $($arg)+
            )
        };
        ($($arg:tt)+) => {
            $crate::__log__!(
                $crate::context::Level::Warn,
                $crate::context::Location::from_panic_location(::std::panic::Location::caller()),
                $($arg)+
            )
        }
    }

    /// Logs an info to Duat.
    ///
    /// Use this, as opposed to [`error!`], [`warn!`] or [`debug!`],
    /// when you want to tell the user that something was
    /// successful, and it is important for them to know it was
    /// successful.
    ///
    /// This error follows the same construction as the [`txt!`]
    /// macro, and will create a [`Record`] inside of the [`Logs`],
    /// which can be accessed by anyone, at any time.
    ///
    /// The [`Record`] added to the [`Logs`] is related to
    /// [`log::Record`], from the [`log`] crate. But it differs in the
    /// sense that it is always `'static`, and instead of having an
    /// [`std::fmt::Arguments`] inside, it contains a [`Text`], making
    /// it a better fit for Duat.
    ///
    /// The connection to [`log::Record`] also means that external
    /// libraries can log information using the [`log`] crate, and it
    /// will also show up in Duat's [`Logs`]s, but reformatted to be a
    /// [`Text`] instead.
    ///
    /// # Custom location
    ///
    /// You can make use of a custom location by calling this macro
    /// and surounding the arguments in a `()` pair.
    ///
    /// ```rust
    /// # duat_core::doc_duat!(duat);
    /// use duat::prelude::{context::Location, *};
    ///
    /// # fn test() {
    /// context::info!(
    ///     ("This is my {}", "info"),
    ///     Location::new("some_file", 32, 10),
    /// );
    /// # }
    /// ```
    ///
    /// [`txt!`]: crate::text::txt
    /// [`Record`]: super::Record
    /// [`Logs`]: super::Logs
    /// [`Text`]: crate::text::Text
    #[macro_export]
    macro_rules! info {
        (($($arg:tt)+), $location:expr $(,)?) => {
            $crate::__log__!(
                $crate::context::Level::Info,
                $location,
                $($arg)+
            )
        };
        ($($arg:tt)+) => {
            $crate::__log__!(
                $crate::context::Level::Info,
                $crate::context::Location::from_panic_location(::std::panic::Location::caller()),
                $($arg)+
            )
        }
    }

    /// Logs an debug information to Duat.
    ///
    /// Use this, as opposed to [`error!`], [`warn!`] or [`info!`],
    /// when you want to tell the user that something was
    /// successful, but it is not that important, or the success is
    /// only a smaller part of some bigger operation, or the success
    /// is part of something that was done "silently".
    ///
    /// This error follows the same construction as the [`txt!`]
    /// macro, and will create a [`Record`] inside of the [`Logs`],
    /// which can be accessed by anyone, at any time.
    ///
    /// The [`Record`] added to the [`Logs`] is related to
    /// [`log::Record`], from the [`log`] crate. But it differs in the
    /// sense that it is always `'static`, and instead of having an
    /// [`std::fmt::Arguments`] inside, it contains a [`Text`], making
    /// it a better fit for Duat.
    ///
    /// The connection to [`log::Record`] also means that external
    /// libraries can log information using the [`log`] crate, and it
    /// will also show up in Duat's [`Logs`]s, but reformatted to be a
    /// [`Text`] instead.
    ///
    /// # Custom location
    ///
    /// You can make use of a custom location by calling this macro
    /// and surounding the arguments in a `()` pair.
    ///
    /// ```rust
    /// # duat_core::doc_duat!(duat);
    /// use duat::prelude::{context::Location, *};
    ///
    /// # fn test() {
    /// let text = txt!("Some custom text I want to debug");
    /// context::debug!(("text is {text:#?}"), Location::new("some_file", 32, 10));
    /// # }
    /// ```
    ///
    /// [`txt!`]: crate::text::txt
    /// [`Record`]: super::Record
    /// [`Logs`]: super::Logs
    /// [`Text`]: crate::text::Text
    #[macro_export]
    macro_rules! debug {
        (($($arg:tt)+), $location:expr $(,)?) => {
            $crate::__log__!(
                $crate::context::Level::Debug,
                $location,
                $($arg)+
            )
        };
        ($($arg:tt)+) => {
            $crate::__log__!(
                $crate::context::Level::Debug,
                $crate::context::Location::from_panic_location(::std::panic::Location::caller()),
                $($arg)+
            )
        }
    }
}

static LOGS: Logs = {
    static LIST: Mutex<Vec<Record>> = Mutex::new(Vec::new());
    static CUR_STATE: AtomicUsize = AtomicUsize::new(1);
    Logs {
        list: &LIST,
        cur_state: &CUR_STATE,
        read_state: AtomicUsize::new(0),
    }
};

/// Notifications for duat.
///
/// This is a mutable, shareable, [`Send`]/[`Sync`] list of
/// notifications in the form of [`Text`]s, you can read this,
/// send new notifications, and check for updates, just like with
/// [`RwData`]s and [`Handle`]s.
///
/// [`RwData`]: crate::data::RwData
/// [`Handle`]: super::Handle
pub fn logs() -> Logs {
    LOGS.clone()
}

/// The notifications sent to Duat.
///
/// This can include command results, failed mappings,
/// recompilation messages, and any other thing that you want
/// to notify about. In order to set the level of severity for these
/// messages, use the [`error!`], [`warn!`] and [`info!`] macros.
#[derive(Debug)]
pub struct Logs {
    list: &'static Mutex<Vec<Record>>,
    cur_state: &'static AtomicUsize,
    read_state: AtomicUsize,
}

impl Clone for Logs {
    fn clone(&self) -> Self {
        Self {
            list: self.list,
            cur_state: self.cur_state,
            read_state: AtomicUsize::new(self.cur_state.load(Ordering::Relaxed) - 1),
        }
    }
}

impl Logs {
    /// Returns an owned valued of a [`SliceIndex`].
    ///
    /// - `&'static Log` for `usize`;
    /// - [`Vec<&'static Log>`] for `impl RangeBounds<usize>`;
    ///
    /// [`SliceIndex`]: std::slice::SliceIndex
    pub fn get<I>(&self, i: I) -> Option<<I::Output as ToOwned>::Owned>
    where
        I: std::slice::SliceIndex<[Record]>,
        I::Output: ToOwned,
    {
        self.read_state
            .store(self.cur_state.load(Ordering::Relaxed), Ordering::Relaxed);
        self.list.lock().unwrap().get(i).map(ToOwned::to_owned)
    }

    /// Returns the last [`Record`], if there was one
    pub fn last(&self) -> Option<(usize, Record)> {
        self.read_state
            .store(self.cur_state.load(Ordering::Relaxed), Ordering::Relaxed);
        let list = self.list.lock().unwrap();
        list.last().cloned().map(|last| (list.len() - 1, last))
    }

    /// Gets the last [`Record`] with a level from a list.
    pub fn last_with_levels(&self, levels: &[Level]) -> Option<(usize, Record)> {
        self.read_state
            .store(self.cur_state.load(Ordering::Relaxed), Ordering::Relaxed);
        self.list
            .lock()
            .unwrap()
            .iter()
            .enumerate()
            .rev()
            .find_map(|(i, rec)| levels.contains(&rec.level()).then(|| (i, rec.clone())))
    }

    /// Wether there are new notifications or not.
    pub fn has_changed(&self) -> bool {
        self.cur_state.load(Ordering::Relaxed) > self.read_state.load(Ordering::Relaxed)
    }

    /// Pushes a [`CmdResult`].
    ///
    /// [`CmdResult`]: crate::cmd::CmdResult
    #[track_caller]
    pub(crate) fn push_cmd_result(&self, result: Result<Option<Text>, Text>) {
        let is_ok = result.is_ok();
        let (Ok(Some(res)) | Err(res)) = result else {
            return;
        };

        self.cur_state.fetch_add(1, Ordering::Relaxed);

        let rec = Record {
            metadata: log::MetadataBuilder::new()
                .level(if is_ok { Level::Info } else { Level::Error })
                .build(),
            text: Box::leak(Box::new(res)),
            location: Location::from_panic_location(std::panic::Location::caller()),
        };

        crate::context::queue(|pa| {
            hook::trigger(pa, hook::MsgLogged(rec.clone()));
            self.list.lock().unwrap().push(rec);
        });
    }

    /// Pushes a new [`Record`] to Duat.
    #[doc(hidden)]
    pub fn push_record(&self, rec: Record) {
        crate::context::queue(|pa| {
            hook::trigger(pa, hook::MsgLogged(rec.clone()));
            self.list.lock().unwrap().push(rec);
        });

        self.cur_state.fetch_add(1, Ordering::Relaxed);
    }

    /// Returns the number of [`Record`]s in the `Logs`.
    pub fn len(&self) -> usize {
        self.list.lock().unwrap().len()
    }

    /// Wether there are any [`Record`]s in the `Logs`.
    ///
    /// It's pretty much never `true`.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
}

impl log::Log for Logs {
    fn enabled(&self, metadata: &log::Metadata) -> bool {
        metadata.level() > log::Level::Debug
    }

    #[track_caller]
    fn log(&self, rec: &log::Record) {
        let rec = Record {
            text: Box::leak(Box::new(Text::from(std::fmt::format(*rec.args())))),
            metadata: log::MetadataBuilder::new()
                .level(rec.level())
                .target(rec.target().to_string().leak())
                .build(),
            location: Location::from_panic_location(std::panic::Location::caller()),
        };

        self.cur_state.fetch_add(1, Ordering::Relaxed);
        self.list.lock().unwrap().push(rec)
    }

    fn flush(&self) {}
}

/// A record of something that happened in Duat.
///
/// Differs from [`log::Record`] in that its argument isn't an
/// [`std::fmt::Arguments`], but a [`Text`] instead.
#[derive(Clone, Debug)]
pub struct Record {
    text: &'static Text,
    metadata: log::Metadata<'static>,
    location: Location,
}

impl Record {
    /// Creates a new [`Record`].
    #[doc(hidden)]
    pub fn new(text: Text, level: Level, location: Location) -> Self {
        Self {
            text: Box::leak(Box::new(text)),
            metadata: log::MetadataBuilder::new().level(level).build(),
            location,
        }
    }

    /// The [`Text`] of this [`Record`].
    #[inline]
    pub fn text(&self) -> &Text {
        self.text
    }

    /// Metadata about the log directive.
    #[inline]
    pub fn metadata(&self) -> log::Metadata<'static> {
        self.metadata.clone()
    }

    /// The verbosity level of the message.
    #[inline]
    pub fn level(&self) -> Level {
        self.metadata.level()
    }

    /// The name of the target of the directive.
    #[inline]
    pub fn target(&self) -> &'static str {
        self.metadata.target()
    }

    /// The [`Location`] where the message was sent from.
    #[inline]
    pub fn location(&self) -> Location {
        self.location
    }
}

/// The location where a log came from
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Location {
    filename: &'static str,
    line: u32,
    col: u32,
}

impl Location {
    /// Returns a new custom `Location`.
    ///
    /// You can use this to add a more nuanced location for an error,
    /// instead of just letting duat pick one automatically.
    ///
    /// An example of this is with treesitter query errors, where
    /// [`std::panic::Location::caller`] would return an error within
    /// a rust file, but a more appropriate position would be on the
    /// actual query file.
    pub fn new(filename: impl ToString, line: u32, col: u32) -> Self {
        Self {
            filename: filename.to_string().leak(),
            line,
            col,
        }
    }

    /// Returns a new [`Location`] from a regular panic `Location`
    pub fn from_panic_location(loc: &std::panic::Location) -> Self {
        Self {
            filename: loc.file().to_string().leak(),
            line: loc.line(),
            col: loc.column(),
        }
    }

    /// Returns the name of the source file.
    #[must_use]
    pub const fn file(&self) -> &'static str {
        self.filename
    }

    /// The line where the message originated from. 1 indexed.
    #[must_use]
    pub const fn line(&self) -> usize {
        self.line as usize
    }

    /// The column where the message originated from. 1 indexed.
    #[must_use]
    pub const fn column(&self) -> usize {
        self.col as usize
    }
}

impl std::fmt::Display for Location {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}:{}", self.file(), self.line, self.col)
    }
}

/// Log information about a panic that took place.
#[doc(hidden)]
pub fn log_panic(panic_info: &PanicHookInfo) {
    let (Some(msg), Some(location)) = (panic_info.payload_as_str(), panic_info.location()) else {
        return;
    };

    let rec = Record {
        text: Box::leak(Box::new(Text::from(msg))),
        metadata: Metadata::builder().level(Level::Error).build(),
        location: Location::from_panic_location(location),
    };

    crate::context::queue(|pa| {
        hook::trigger(pa, hook::MsgLogged(rec.clone()));
        LOGS.list.lock().unwrap().push(rec);
    });
}