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
use gtk::glib::{self, Sender};

use std::cell::{RefCell, RefMut};
use std::marker::PhantomData;
use std::rc::Rc;
// use std::sync::mpsc::channel;

use crate::{ComponentUpdate, Components, Model as ModelTrait, Widgets as WidgetsTrait};

/// A component that can be part of the main application or other components.
///
/// A [`RelmComponent`] has its own widget, model and message type
/// and can send messages to its parent and its children components.
///
/// Multiple [`RelmComponent`]s that have the same parent are usually bundled in a struct that implements [`Components`].
#[derive(Debug)]
pub struct RelmComponent<Model, ParentModel>
where
    Model: ComponentUpdate<ParentModel> + 'static,
    ParentModel: ModelTrait,
    Model::Widgets: WidgetsTrait<Model, ParentModel> + 'static,
{
    model: PhantomData<Model>,
    parent_model: PhantomData<ParentModel>,
    components: Rc<RefCell<Model::Components>>,
    sender: Sender<Model::Msg>,
    root_widget: <Model::Widgets as WidgetsTrait<Model, ParentModel>>::Root,
    shared_widgets: Rc<RefCell<Model::Widgets>>,
}

impl<Model, ParentModel> RelmComponent<Model, ParentModel>
where
    Model::Widgets: WidgetsTrait<Model, ParentModel> + 'static,
    ParentModel: ModelTrait,
    Model: ComponentUpdate<ParentModel> + 'static,
{
    /// Create a new [`RelmComponent`].
    pub fn new(parent_model: &ParentModel, parent_sender: Sender<ParentModel::Msg>) -> Self {
        let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);

        let mut model = Model::init_model(parent_model);
        let components = Model::Components::init_components(&model, sender.clone());

        let widgets = Model::Widgets::init_view(&model, &components, sender.clone());
        let root_widget = widgets.root_widget();

        let components = Rc::new(RefCell::new(components));
        let handler_components = components.clone();

        let cloned_sender = sender.clone();

        let shared_widgets = Rc::new(RefCell::new(widgets));
        let handler_widgets = shared_widgets.clone();

        {
            let context = glib::MainContext::default();
            let _guard = context
                .acquire()
                .expect("Couldn't acquire glib main context");
            // The main loop executes the closure as soon as it receives the message
            receiver.attach(Some(&context), move |msg: Model::Msg| {
                let components: &Model::Components = &handler_components.borrow();
                model.update(msg, components, sender.clone(), parent_sender.clone());
                if let Ok(ref mut widgets) = handler_widgets.try_borrow_mut() {
                    widgets.view(&model, sender.clone());
                } else {
                    log::warn!("Could not mutably borrow the widgets. Make sure you drop all references to widgets after use");
                }
                glib::Continue(true)
            });
        }

        RelmComponent {
            model: PhantomData,
            parent_model: PhantomData,
            components,
            sender: cloned_sender,
            root_widget,
            shared_widgets,
        }
    }

    /// Connect the widgets to the widgets of the parent widget.
    pub fn connect_parent(&mut self, parent_widgets: &ParentModel::Widgets) {
        self.widgets()
            .expect("TODO: ADD MESSAGE")
            .connect_parent(parent_widgets);
        self.components
            .borrow_mut()
            .connect_parent(&self.shared_widgets.borrow());
    }

    /// Send a message to this component.
    /// This can be used by the parent to send messages to this component.
    pub fn send(&self, msg: Model::Msg) -> Result<(), std::sync::mpsc::SendError<Model::Msg>> {
        self.sender.send(msg)
    }

    /// Get a sender to send messages to this component.
    pub fn sender(&self) -> Sender<Model::Msg> {
        self.sender.clone()
    }

    /// Returns the root widget of this component's widgets.
    /// Can be used by the parent to connect the root widget
    /// to the parent's widgets.
    pub fn root_widget(&self) -> &<Model::Widgets as WidgetsTrait<Model, ParentModel>>::Root {
        &self.root_widget
    }

    /// Returns a mutable reference to the widgets of this component or [`None`] if
    /// you already have a reference to the widgets.
    ///
    /// Use this carefully and make sure the reference to the widgets is dropped after use because
    /// otherwise the view function can't be called as long you own the widgets (it uses [`RefCell`] internally).
    pub fn widgets(&self) -> Option<RefMut<'_, Model::Widgets>> {
        self.shared_widgets
            // .as_ref()
            // .expect("Component wasn't initialized correctly: shared widgets are missing")
            .try_borrow_mut()
            .ok()
    }
}

/*
impl<Model, ParentModel> RelmComponent<Model, ParentModel>
where
    Model: ComponentUpdate<ParentModel> + Send + 'static,
    Model::Widgets: WidgetsTrait<Model, ParentModel> + 'static,
    Model::Components: Send + Sync,
    Model::Msg: Send,
    ParentModel: ModelTrait,
    ParentModel::Msg: Send,
{
    /// Create a new [`RelmComponent`] that runs the [`ComponentUpdate::update`] function in another thread.
    ///
    /// Because GTK4 widgets are neither [`Send`] nor [`Sync`] we must still run the [`Widgets::view`](WidgetsTrait::view) function
    /// on the main thread.
    /// Also the model needs to be sent between threads to run the update and view functions.
    /// So if you look want to send a lot of messages to self using a [`RelmWorker`](crate::RelmWorker) will perform better.
    pub fn with_new_thread(
        parent_model: &ParentModel,
        parent_sender: Sender<ParentModel::Msg>,
    ) -> Self {
        let (global_sender, global_receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);
        let (sender, receiver) = glib::MainContext::channel(glib::PRIORITY_DEFAULT);

        let model = Model::init_model(parent_model);
        let mut components = Model::Components::init_components(&model, sender.clone());

        let widgets = Model::Widgets::init_view(&model, &components, sender.clone());
        let root_widget = widgets.root_widget();

        //components.connect_parent(&widgets);
        let components = Arc::new(components);

        let cloned_sender = sender.clone();

        let shared_widgets = Rc::new(RefCell::new(widgets));
        let handler_widgets = shared_widgets.clone();

        let update_sender = sender.clone();
        let view_sender = sender;

        let (model_tx, model_rx) = channel();
        model_tx.send(model).unwrap();

        std::thread::spawn(move || {
            let context = glib::MainContext::new();
            context.push_thread_default();
            let _guard = context
                .acquire()
                .expect("Couldn't acquire glib main context");

            // The main loop executes the closure as soon as it receives the message
            receiver.attach(Some(&context), move |msg: Model::Msg| {
                let mut model: Model = model_rx.recv().unwrap();
                model.update(
                    msg,
                    &components,
                    update_sender.clone(),
                    parent_sender.clone(),
                );
                global_sender.send(model).unwrap();
                glib::Continue(true)
            });

            let main_loop = glib::MainLoop::new(Some(&context), true);
            main_loop.run();
            context.pop_thread_default();
        });

        let global_context = glib::MainContext::default();
        let _global_guard = global_context.acquire().unwrap();
        global_receiver.attach(Some(&global_context), move |model: Model| {
            if let Ok(ref mut widgets) = handler_widgets.try_borrow_mut() {
                widgets.view(&model, view_sender.clone());
            } else {
                log::warn!("Could not mutably borrow the widgets. Make sure you drop all references to widgets after use");
            }
            model_tx.send(model).unwrap();
            glib::Continue(true)
        });

        RelmComponent {
            model: PhantomData,
            parent_model: PhantomData,
            components,
            sender: cloned_sender,
            root_widget,
            shared_widgets,
        }
    }
}
*/