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
//! A macro for generating a [`ConstraintSystem`](hotdrink_rs::model::ConstraintSystem) that can be compiled to WebAssembly.

/// A macro for generating a [`ConstraintSystem`](hotdrink_rs::model::ConstraintSystem) that can be compiled to WebAssembly.
///
/// By providing an identifier, wrapper type, inner type (the two last generated with [`component_type_wrapper!`]($crate::component_type_wrapper!)),
/// a thread pool implementation, the number of threads to use, and a termination strategy, it will automatically generate
/// a wrapper that can be returned to and used from JavaScript.
#[macro_export]
macro_rules! constraint_system_wrapper {
    ($cs_name:ident, $wrapper_type:ty, $inner_type:ty) => {
        /// A wrapper around the internal constraint system.
        /// A macro is used to construct the type that the library user wants,
        /// since `wasm_bindgen` requires a concrete type.
        #[wasm_bindgen::prelude::wasm_bindgen]
        #[allow(missing_debug_implementations)]
        pub struct $cs_name {
            inner: std::sync::Mutex<hotdrink_rs::model::ConstraintSystem<$inner_type>>,
            event_queue: std::sync::Arc<
                std::sync::Mutex<
                    std::collections::VecDeque<
                        $crate::event::js_event::JsEvent<
                            $inner_type,
                            hotdrink_rs::solver::SolveError,
                        >,
                    >,
                >,
            >,
            event_handler: std::sync::Mutex<
                $crate::event::event_handler::EventHandler<
                    $inner_type,
                    hotdrink_rs::solver::SolveError,
                >,
            >,
            pool: std::sync::Mutex<hotdrink_rs::thread::DummyPool>,
        }

        impl $cs_name {
            /// Wraps an existing constraint system,
            /// and initializes the struct.
            pub fn wrap(
                inner: hotdrink_rs::model::ConstraintSystem<$inner_type>,
            ) -> Result<$cs_name, wasm_bindgen::JsValue> {
                // Create the event listener
                // Create the worker pool for executing methods
                use hotdrink_rs::thread::ThreadPool;
                let pool = hotdrink_rs::thread::DummyPool::new(1)?;
                // Combine it all
                Ok(Self {
                    inner: std::sync::Mutex::new(inner),
                    event_queue: Default::default(),
                    event_handler: std::sync::Mutex::new(
                        $crate::event::event_handler::EventHandler::new(),
                    ),
                    pool: std::sync::Mutex::new(pool),
                })
            }
        }

        #[wasm_bindgen::prelude::wasm_bindgen]
        impl $cs_name {
            fn handle_events(&self) {
                // Call callbacks with initial events
                let mut event_handler = self.event_handler.lock().unwrap();
                let mut event_queue = self.event_queue.lock().unwrap();
                for event in event_queue.drain(..) {
                    if let Err(e) = event_handler.handle_event(event) {
                        log::error!("Failed to handle event: {:?}", e);
                    };
                }
                event_queue.clear();
            }
            /// Sets the callbacks to call when the specified variable changes state.
            /// `on_pending` should not have any parameters, `on_ready` will receive the new value,
            /// and `on_error` will receive information about the error.
            pub fn subscribe(
                &self,
                component: &str,
                variable: &str,
                on_ready: Option<js_sys::Function>,
                on_pending: Option<js_sys::Function>,
                on_error: Option<js_sys::Function>,
            ) {
                {
                    let mut event_handler = self.event_handler.lock().unwrap();
                    if let Some(on_ready) = on_ready {
                        event_handler.set_on_ready(component, variable, on_ready);
                    }
                    if let Some(on_pending) = on_pending {
                        event_handler.set_on_pending(component, variable, on_pending);
                    }
                    if let Some(on_error) = on_error {
                        event_handler.set_on_error(component, variable, on_error);
                    }
                }
                {
                    let component = component.to_owned();
                    let variable = variable.to_owned();
                    let mut inner = self.inner.lock().unwrap();
                    let event_queue = std::sync::Arc::clone(&self.event_queue);
                    let (component_clone, variable_clone) = (component.clone(), variable.clone());
                    let result = inner.subscribe(&component_clone, &variable_clone, move |e| {
                        let js_event = $crate::event::js_event::JsEvent::new(
                            component.clone(),
                            variable.clone(),
                            e.into(),
                        );
                        event_queue.lock().unwrap().push_back(js_event);
                    });

                    if let Err(e) = result {
                        log::error!("Subscribe failed: {}", e);
                    }

                    self.handle_events();
                }
            }

            /// Removes the callbacks from the specified variable.
            pub fn unsubscribe(&self, component: &str, variable: &str) {
                {
                    let mut event_handler = self.event_handler.lock().unwrap();
                    event_handler.unsubscribe(component, variable);
                }
                {
                    let mut inner = self.inner.lock().unwrap();
                    if let Err(e) = inner.unsubscribe(component, variable) {
                        log::error!("Unsubscribe failed: {}", e);
                    }
                }
            }

            /// Runs the planner and solver to re-enforce all constraints.
            pub fn update(&self) {
                let mut inner = self.inner.lock().unwrap();
                let mut pool = self.pool.lock().unwrap();
                match inner.par_update(&mut *pool) {
                    Ok(()) => self.handle_events(),
                    Err(e) => {
                        log::error!("Update failed: {}", e);
                    }
                }
            }

            /// Gives the specified variable a new value.
            pub fn set_variable(&self, component: &str, variable: &str, value: $wrapper_type) {
                let value = value.unwrap();
                self.inner
                    .lock()
                    .unwrap()
                    .set_variable(component, variable, value)
                    .unwrap_or_else(|e| {
                        log::error!("Could not set variable: {}", e);
                    });
            }

            /// Pins the specified variable, stopping it from changing.
            /// Note that this can cause the system to be overconstrained.
            pub fn pin(&self, component: &str, variable: &str) {
                self.inner
                    .lock()
                    .unwrap()
                    .pin(component, variable)
                    .unwrap_or_else(|e| {
                        log::error!("Could not pin variable: {}", e);
                    });
            }

            /// Unpins the specified variable, allowing it to change again.
            pub fn unpin(&self, component: &str, variable: &str) {
                self.inner
                    .lock()
                    .unwrap()
                    .unpin(component, variable)
                    .unwrap_or_else(|e| {
                        log::error!("Could not unpin variable: {}", e);
                    });
            }

            /// Undo the last change.
            pub fn undo(&self) {
                self.inner.lock().unwrap().undo().unwrap_or_else(|e| {
                    log::error!("Undo failed: {}", e);
                });
                self.handle_events();
            }

            /// Undo the last change.
            pub fn redo(&self) {
                self.inner.lock().unwrap().redo().unwrap_or_else(|e| {
                    log::error!("Redo failed: {}", e);
                });
                self.handle_events();
            }

            /// Enables the specified constraint.
            pub fn enable_constraint(&self, component: &str, constraint: &str) {
                self.inner
                    .lock()
                    .unwrap()
                    .enable_constraint(component, constraint)
                    .unwrap_or_else(|e| {
                        log::error!("Could not enable constraint: {}", e);
                    });
            }

            /// Disables the specified constraint.
            pub fn disable_constraint(&self, component: &str, constraint: &str) {
                self.inner
                    .lock()
                    .unwrap()
                    .disable_constraint(component, constraint)
                    .unwrap_or_else(|e| {
                        log::error!("Could not disable constraint: {}", e);
                    });
            }
        }
    };
}

#[cfg(test)]
mod tests {
    #[ignore = "Simply for verification that it compiles"]
    #[test]
    fn it_compiles() {
        // Generate constraint system value and a JS wrapper for it
        crate::component_type_wrapper! {
            pub struct Wrapper {
                #[derive(Clone, Debug)]
                pub enum Inner {
                    i32,
                    f64
                }
            }
        };

        // Generate a JS wrapper for the constraint system
        crate::constraint_system_wrapper!(System, Wrapper, Inner);
    }
}