Skip to main content

i_slint_core/
debug_log.rs

1// Copyright © SixtyFPS GmbH <info@slint.dev>
2// SPDX-License-Identifier: GPL-3.0-only OR LicenseRef-Slint-Royalty-free-2.0 OR LicenseRef-Slint-Software-3.0
3
4/// Location information attached to a log message.
5#[derive(Clone, Debug)]
6pub struct LogMessageLocation<'a> {
7    /// The file path of the source that emitted the log message
8    pub path: &'a str,
9    /// the line number of the call that emitted the log message (1-based)
10    pub line: usize,
11    /// The column of the call that emitted the log message (1-based)
12    pub column: usize,
13}
14
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16#[non_exhaustive]
17pub enum LogMessageSource {
18    /// The message originates from Slint source code (e.g. the `debug()` function in Slint)
19    SlintCode,
20    /// The message originates from the Slint runtime crates
21    ///
22    /// For example if a file path could not be resolved at runtime.
23    Runtime,
24}
25
26/// Opaque log message, emitted by [`crate::debug_log!`] as well as the Slint `debug()` function.
27pub struct LogMessage<'a> {
28    source: LogMessageSource,
29    location: Option<LogMessageLocation<'a>>,
30    arguments: core::fmt::Arguments<'a>,
31}
32
33impl<'a> LogMessage<'a> {
34    pub fn new(
35        source: LogMessageSource,
36        location: Option<LogMessageLocation<'a>>,
37        arguments: core::fmt::Arguments<'a>,
38    ) -> Self {
39        Self { source, location, arguments }
40    }
41
42    pub fn source(&self) -> LogMessageSource {
43        self.source
44    }
45
46    pub fn location(&self) -> Option<LogMessageLocation<'_>> {
47        self.location.clone()
48    }
49
50    pub fn message_arguments(&self) -> core::fmt::Arguments<'a> {
51        self.arguments
52    }
53}
54
55/// Log message handler type stored in a [`crate::SlintContext`].
56pub type LogMessageHandler = alloc::boxed::Box<dyn for<'a> Fn(LogMessage<'a>) + 'static>;
57
58#[doc(hidden)]
59pub fn log_message(message: LogMessage) {
60    crate::context::GLOBAL_CONTEXT.with(|p| match p.get() {
61        Some(ctx) => ctx.dispatch_log_message(message),
62        None => default_log_message(message.arguments),
63    });
64}
65
66#[doc(hidden)]
67pub fn default_log_message(_arguments: core::fmt::Arguments) {
68    cfg_if::cfg_if! {
69        if #[cfg(feature = "log")] {
70            log::debug!("{_arguments}");
71        } else if #[cfg(target_arch = "wasm32")] {
72            use wasm_bindgen::prelude::*;
73            use std::string::ToString;
74
75            #[wasm_bindgen]
76            extern "C" {
77                #[wasm_bindgen(js_namespace = console)]
78                pub fn log(s: &str);
79            }
80
81            log(&_arguments.to_string());
82        } else if #[cfg(feature = "std")] {
83            use std::io::Write;
84            // We were seeing intermittent, albeit very rare, crashes due to `eprintln` panicking
85            // if the write to stderr fails. Since this is just for debug printing, it's safe
86            // to silently drop this if we can't write (since it wouldn't be written to stderr
87            // anyway)
88            let _ = writeln!(std::io::stderr(), "{_arguments}");
89        }
90    }
91}
92
93#[macro_export]
94/// This macro allows producing debug output that will appear on stderr in regular builds
95/// and in the console log for wasm builds.
96macro_rules! debug_log {
97    ($($t:tt)*) => ($crate::debug_log::log_message(
98        $crate::debug_log::LogMessage::new(
99            $crate::debug_log::LogMessageSource::Runtime,
100            None,
101            format_args!($($t)*),
102        )
103    ))
104}