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
use std::any::TypeId;
use std::sync::{
    atomic::{AtomicPtr, AtomicUsize, Ordering},
    Arc,
};

use colored::Colorize;
use log::debug;

use futures::channel::mpsc::UnboundedSender;

use crate::component::{Component, ComponentTask};

pub struct Scope<C: Component> {
    name: &'static str,
    muted: Arc<AtomicUsize>,
    channel: UnboundedSender<C::Message>,
}

impl<C: Component> Scope<C> {
    pub(crate) fn new(name: &'static str, channel: UnboundedSender<C::Message>) -> Self {
        Scope {
            name,
            muted: Default::default(),
            channel,
        }
    }
}

impl<C: Component> Clone for Scope<C> {
    fn clone(&self) -> Self {
        Scope {
            name: self.name,
            muted: self.muted.clone(),
            channel: self.channel.clone(),
        }
    }
}

impl<C: 'static + Component> Scope<C> {
    pub(crate) fn inherit<Child: Component>(
        &self,
        name: &'static str,
        channel: UnboundedSender<Child::Message>,
    ) -> Scope<Child> {
        Scope {
            name,
            muted: self.muted.clone(),
            channel,
        }
    }

    pub(crate) fn is_muted(&self) -> bool {
        self.muted.load(Ordering::SeqCst) > 0
    }

    pub(crate) fn mute(&self) {
        self.muted.fetch_add(1, Ordering::SeqCst);
    }

    pub(crate) fn unmute(&self) {
        self.muted.fetch_sub(1, Ordering::SeqCst);
    }

    pub(crate) fn current_parent() -> Self {
        ComponentTask::<_, C>::current_parent_scope()
    }

    pub fn send_message(&self, msg: C::Message) {
        debug!(
            "{} {}: {}",
            format!(
                "Scope::send_message{}",
                if self.is_muted() { " [muted]" } else { "" }
            )
            .green(),
            self.name.magenta().bold(),
            format!("{:?}", msg).bright_white().bold()
        );
        if !self.is_muted() {
            self.channel
                .unbounded_send(msg)
                .expect("unable to send message to unbounded channel!")
        }
    }

    pub fn name(&self) -> &str {
        &self.name
    }
}

pub(crate) struct AnyScope {
    type_id: TypeId,
    ptr: AtomicPtr<()>,
    drop: Box<dyn Fn(&mut AtomicPtr<()>) + Send>,
}

impl<C: 'static + Component> From<Scope<C>> for AnyScope {
    fn from(scope: Scope<C>) -> Self {
        let ptr = AtomicPtr::new(Box::into_raw(Box::new(scope)) as *mut ());
        let drop = |ptr: &mut AtomicPtr<()>| {
            let ptr = ptr.swap(std::ptr::null_mut(), Ordering::SeqCst);
            if !ptr.is_null() {
                #[allow(unsafe_code)]
                let scope = unsafe { Box::from_raw(ptr as *mut Scope<C>) };
                std::mem::drop(scope)
            }
        };
        AnyScope {
            type_id: TypeId::of::<C::Properties>(),
            ptr,
            drop: Box::new(drop),
        }
    }
}

impl Drop for AnyScope {
    fn drop(&mut self) {
        (self.drop)(&mut self.ptr)
    }
}

impl AnyScope {
    pub(crate) fn try_get<C: 'static + Component>(&self) -> Option<&'static Scope<C>> {
        if TypeId::of::<C::Properties>() == self.type_id {
            #[allow(unsafe_code)]
            unsafe {
                (self.ptr.load(Ordering::Relaxed) as *const Scope<C>).as_ref()
            }
        } else {
            None
        }
    }
}