use std::borrow::ToOwned;
use std::sync::Arc;
use std::thread;
use backtrace::Backtrace;
use base::id::TopLevelBrowsingContextId;
use compositing_traits::ConstellationMsg as FromCompositorMsg;
use crossbeam_channel::Sender;
use log::{Level, LevelFilter, Log, Metadata, Record};
use parking_lot::ReentrantMutex;
use script_traits::{LogEntry, ScriptMsg as FromScriptMsg, ScriptToConstellationChan};
pub struct FromScriptLogger {
pub script_to_constellation_chan: Arc<ReentrantMutex<ScriptToConstellationChan>>,
}
impl FromScriptLogger {
pub fn new(script_to_constellation_chan: ScriptToConstellationChan) -> FromScriptLogger {
FromScriptLogger {
script_to_constellation_chan: Arc::new(ReentrantMutex::new(
script_to_constellation_chan,
)),
}
}
pub fn filter(&self) -> LevelFilter {
LevelFilter::Warn
}
}
impl Log for FromScriptLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Warn
}
fn log(&self, record: &Record) {
if let Some(entry) = log_entry(record) {
let thread_name = thread::current().name().map(ToOwned::to_owned);
let msg = FromScriptMsg::LogEntry(thread_name, entry);
let chan = self.script_to_constellation_chan.lock();
let _ = chan.send(msg);
}
}
fn flush(&self) {}
}
#[derive(Clone)]
pub struct FromCompositorLogger {
pub constellation_chan: Arc<ReentrantMutex<Sender<FromCompositorMsg>>>,
}
impl FromCompositorLogger {
pub fn new(constellation_chan: Sender<FromCompositorMsg>) -> FromCompositorLogger {
FromCompositorLogger {
constellation_chan: Arc::new(ReentrantMutex::new(constellation_chan)),
}
}
pub fn filter(&self) -> LevelFilter {
LevelFilter::Warn
}
}
impl Log for FromCompositorLogger {
fn enabled(&self, metadata: &Metadata) -> bool {
metadata.level() <= Level::Warn
}
fn log(&self, record: &Record) {
if let Some(entry) = log_entry(record) {
let top_level_id = TopLevelBrowsingContextId::installed();
let thread_name = thread::current().name().map(ToOwned::to_owned);
let msg = FromCompositorMsg::LogEntry(top_level_id, thread_name, entry);
let chan = self.constellation_chan.lock();
let _ = chan.send(msg);
}
}
fn flush(&self) {}
}
fn log_entry(record: &Record) -> Option<LogEntry> {
match record.level() {
Level::Error if thread::panicking() => Some(LogEntry::Panic(
format!("{}", record.args()),
format!("{:?}", Backtrace::new()),
)),
Level::Error => Some(LogEntry::Error(format!("{}", record.args()))),
Level::Warn => Some(LogEntry::Warn(format!("{}", record.args()))),
_ => None,
}
}