fyrox-core 1.0.1

Shared core for the Fyrox engine and its external crates.
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
// Copyright (c) 2019-present Dmitry Stepanov and Fyrox Engine contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! Simple logger. By default, it writes in the console only. To enable logging into a file, call
//! [`Log::set_file_name`] somewhere in your `main` function.

use crate::instant::Instant;
use crate::parking_lot::Mutex;
#[cfg(target_arch = "wasm32")]
use crate::wasm_bindgen::{self, prelude::*};
use crate::{reflect::prelude::*, visitor::prelude::*};
use fxhash::FxHashMap;
use std::collections::hash_map::Entry;
use std::fmt::{Debug, Display};
#[cfg(not(target_arch = "wasm32"))]
use std::io::{self, Write};
use std::path::Path;
use std::sync::mpsc::Sender;
use std::sync::LazyLock;
use std::time::Duration;

#[cfg(target_arch = "wasm32")]
#[wasm_bindgen]
extern "C" {
    // Use `js_namespace` here to bind `console.log(..)` instead of just
    // `log(..)`
    #[wasm_bindgen(js_namespace = console)]
    fn log(s: &str);
}

/// A message that could be sent by the logger to all listeners.
pub struct LogMessage {
    /// Kind of the message: information, warning or error.
    pub kind: MessageKind,
    /// The source message without logger prefixes.
    pub content: String,
    /// Time point at which the message was recorded. It is relative to the moment when the
    /// logger was initialized.
    pub time: Duration,
}

static LOG: LazyLock<Mutex<Log>> = LazyLock::new(|| {
    Mutex::new(Log {
        #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
        file: None,
        log_info: true,
        log_warning: true,
        log_error: true,
        listeners: Default::default(),
        time_origin: Instant::now(),
        one_shot_sources: Default::default(),
        write_to_stdout: true,
    })
});

/// A kind of message.
#[derive(Debug, Default, Copy, Clone, PartialOrd, PartialEq, Eq, Ord, Hash, Visit, Reflect)]
#[repr(u32)]
pub enum MessageKind {
    /// Some useful information.
    #[default]
    Information = 0,
    /// A warning.
    Warning = 1,
    /// An error of some kind.
    Error = 2,
}

impl MessageKind {
    fn as_str(self) -> &'static str {
        match self {
            MessageKind::Information => "[INFO]: ",
            MessageKind::Warning => "[WARNING]: ",
            MessageKind::Error => "[ERROR]: ",
        }
    }
}

/// See module docs.
pub struct Log {
    #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
    file: Option<std::fs::File>,
    log_info: bool,
    log_warning: bool,
    log_error: bool,
    listeners: Vec<Sender<LogMessage>>,
    time_origin: Instant,
    one_shot_sources: FxHashMap<usize, String>,
    write_to_stdout: bool,
}

impl Log {
    /// Creates a new log file at the specified path.
    pub fn set_file_name<P: AsRef<Path>>(#[allow(unused_variables)] path: P) {
        #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
        {
            let mut guard = LOG.lock();
            guard.file = std::fs::File::create(path).ok();
        }
    }

    /// Sets new file to write the log to.
    pub fn set_file(#[allow(unused_variables)] file: Option<std::fs::File>) {
        #[cfg(all(not(target_arch = "wasm32"), not(target_os = "android")))]
        {
            let mut guard = LOG.lock();
            guard.file = file;
        }
    }

    fn write_internal<S>(&mut self, id: Option<usize>, kind: MessageKind, message: S) -> bool
    where
        S: AsRef<str>,
    {
        match kind {
            MessageKind::Information if !self.log_info => {
                return false;
            }
            MessageKind::Warning if !self.log_warning => {
                return false;
            }
            MessageKind::Error if !self.log_error => {
                return false;
            }
            _ => (),
        }

        let mut msg = message.as_ref().to_owned();

        if let Some(id) = id {
            let mut need_write = false;
            match self.one_shot_sources.entry(id) {
                Entry::Occupied(mut message) => {
                    if message.get() != &msg {
                        message.insert(msg.clone());
                        need_write = true;
                    }
                }
                Entry::Vacant(entry) => {
                    entry.insert(msg.clone());
                    need_write = true;
                }
            }

            if !need_write {
                return false;
            }
        }

        // Notify listeners about the message and remove all disconnected listeners.
        self.listeners.retain(|listener| {
            listener
                .send(LogMessage {
                    kind,
                    content: msg.clone(),
                    time: Instant::now() - self.time_origin,
                })
                .is_ok()
        });

        msg.insert_str(0, kind.as_str());

        #[cfg(target_arch = "wasm32")]
        {
            log(&msg);
        }

        #[cfg(all(not(target_os = "android"), not(target_arch = "wasm32")))]
        {
            if self.write_to_stdout {
                let _ = io::stdout().write_all(msg.as_bytes());
            }

            if let Some(log_file) = self.file.as_mut() {
                let _ = log_file.write_all(msg.as_bytes());
                let _ = log_file.flush();
            }
        }

        #[cfg(target_os = "android")]
        {
            if self.write_to_stdout {
                let _ = io::stdout().write_all(msg.as_bytes());
            }
        }

        true
    }

    fn writeln_internal<S>(&mut self, id: Option<usize>, kind: MessageKind, message: S) -> bool
    where
        S: AsRef<str>,
    {
        let mut msg = message.as_ref().to_owned();
        msg.push('\n');
        self.write_internal(id, kind, msg)
    }

    /// Writes a string to the console and optionally into the file (if set).
    pub fn write<S>(kind: MessageKind, msg: S)
    where
        S: AsRef<str>,
    {
        LOG.lock().write_internal(None, kind, msg);
    }

    /// Writes a string to the console and optionally into the file (if set). Unlike [`Self::write`]
    /// this method writes the message only once per given id if the message remains the same. If
    /// the message changes, then the new version will be printed to the log. This method is useful
    /// if you need to print error messages, but prevent them from flooding the log.
    pub fn write_once<S>(id: usize, kind: MessageKind, msg: S) -> bool
    where
        S: AsRef<str>,
    {
        LOG.lock().write_internal(Some(id), kind, msg)
    }

    /// Writes a string to the console and optionally into the file (if set), adds a new line to the
    /// end of the message.
    pub fn writeln<S>(kind: MessageKind, msg: S)
    where
        S: AsRef<str>,
    {
        LOG.lock().writeln_internal(None, kind, msg);
    }

    /// Writes a string to the console and optionally into the file (if set), adds a new line to the
    /// end of the message. Prints the message only once. See [`Self::write_once`] for more info.
    pub fn writeln_once<S>(id: usize, kind: MessageKind, msg: S) -> bool
    where
        S: AsRef<str>,
    {
        LOG.lock().writeln_internal(Some(id), kind, msg)
    }

    /// Writes an information message.
    pub fn info<S>(msg: S)
    where
        S: AsRef<str>,
    {
        Self::writeln(MessageKind::Information, msg)
    }

    /// Writes a warning message.
    pub fn warn<S>(msg: S)
    where
        S: AsRef<str>,
    {
        Self::writeln(MessageKind::Warning, msg)
    }

    /// Writes error message.
    pub fn err<S>(msg: S)
    where
        S: AsRef<str>,
    {
        Self::writeln(MessageKind::Error, msg)
    }

    /// Writes an information message once. See [`Self::write_once`] for more info.
    pub fn info_once<S>(id: usize, msg: S) -> bool
    where
        S: AsRef<str>,
    {
        Self::writeln_once(id, MessageKind::Information, msg)
    }

    /// Writes a warning message. See [`Self::write_once`] for more info.
    pub fn warn_once<S>(id: usize, msg: S) -> bool
    where
        S: AsRef<str>,
    {
        Self::writeln_once(id, MessageKind::Warning, msg)
    }

    /// Writes an error message once. See [`Self::write_once`] for more info.
    pub fn err_once<S>(id: usize, msg: S) -> bool
    where
        S: AsRef<str>,
    {
        Self::writeln_once(id, MessageKind::Error, msg)
    }

    /// Enables or disables writing the messages to stdout stream.
    pub fn enable_writing_to_stdout(enabled: bool) {
        LOG.lock().write_to_stdout = enabled;
    }

    /// Returns `true` if the logger allowed writing to stdout stream, `false` - otherwise.
    pub fn is_writing_to_stdout() -> bool {
        LOG.lock().write_to_stdout
    }

    pub fn set_log_info(state: bool) {
        LOG.lock().log_info = state;
    }

    pub fn is_logging_info() -> bool {
        LOG.lock().log_info
    }

    pub fn set_log_warning(state: bool) {
        LOG.lock().log_warning = state;
    }

    pub fn is_logging_warning() -> bool {
        LOG.lock().log_warning
    }

    pub fn set_log_error(state: bool) {
        LOG.lock().log_error = state;
    }

    pub fn is_logging_error() -> bool {
        LOG.lock().log_error
    }

    /// Adds a listener that will receive a copy of every message passed into the log.
    pub fn add_listener(listener: Sender<LogMessage>) {
        LOG.lock().listeners.push(listener)
    }

    /// Allows you to verify that the result of the operation is Ok, or print the error in the log.
    ///
    /// # Use cases
    ///
    /// Typical use case for this method is that when you _can_ ignore errors, but want them to
    /// be in the log.
    pub fn verify<T, E>(result: Result<T, E>)
    where
        E: Display,
    {
        if let Err(e) = result {
            Self::writeln(MessageKind::Error, format!("Operation failed! Reason: {e}"));
        }
    }

    /// Allows you to verify that the result of the operation is Ok, or print the error in the log.
    ///
    /// # Use cases
    ///
    /// Typical use case for this method is that when you _can_ ignore errors, but want them to
    /// be in the log.
    pub fn verify_message<S, T, E>(result: Result<T, E>, msg: S)
    where
        E: Debug,
        S: Display,
    {
        if let Err(e) = result {
            Self::writeln(MessageKind::Error, format!("{msg}. Reason: {e:?}"));
        }
    }
}

#[macro_export]
macro_rules! info {
    ($($arg:tt)*) => {
        $crate::log::Log::info(format!($($arg)*))
    };
}

#[macro_export]
macro_rules! warn {
    ($($arg:tt)*) => {
        $crate::log::Log::warn(format!($($arg)*))
    };
}

#[macro_export]
macro_rules! err {
    ($($arg:tt)*) => {
        $crate::log::Log::err(format!($($arg)*))
    };
}

#[macro_export]
macro_rules! info_once {
    ($id:expr, $($arg:tt)*) => {
        $crate::log::Log::info_once($id, format!($($arg)*))
    };
}

#[macro_export]
macro_rules! warn_once {
    ($id:expr, $($arg:tt)*) => {
        $crate::log::Log::warn_once($id, format!($($arg)*))
    };
}

#[macro_export]
macro_rules! err_once {
    ($id:expr, $($arg:tt)*) => {
        $crate::log::Log::err_once($id, format!($($arg)*))
    };
}