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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use gtk::glib::Sender;
use std::cell::RefCell;
use std::collections::BTreeMap;
use super::Widgets;
use crate::factory::{Factory, FactoryPrototype, FactoryView};
#[derive(Debug)]
enum ChangeType {
Add,
Remove,
Recreate,
Update,
}
#[allow(clippy::type_complexity)]
#[derive(Default, Debug)]
pub struct FactoryVec<Data>
where
Data: FactoryPrototype,
{
data: Vec<Data>,
widgets: RefCell<Vec<Widgets<Data::Widgets, <Data::View as FactoryView<Data::Root>>::Root>>>,
changes: RefCell<BTreeMap<usize, ChangeType>>,
}
impl<Data> FactoryVec<Data>
where
Data: FactoryPrototype,
{
#[must_use]
pub fn new() -> Self {
FactoryVec {
data: Vec::new(),
widgets: RefCell::new(Vec::new()),
changes: RefCell::new(BTreeMap::new()),
}
}
#[must_use]
pub fn from_vec(data: Vec<Data>) -> Self {
let changes = (0..data.len())
.map(|data| (data, ChangeType::Add))
.collect();
let length = data.len();
FactoryVec {
data,
widgets: RefCell::new(Vec::with_capacity(length)),
changes: RefCell::new(changes),
}
}
#[must_use]
pub fn as_slice(&self) -> &[Data] {
self.data.as_slice()
}
#[must_use]
pub fn into_vec(self) -> Vec<Data> {
self.data
}
pub fn clear(&mut self) {
while self.pop().is_some() {}
}
pub fn len(&self) -> usize {
self.data.len()
}
pub fn is_empty(&self) -> bool {
self.data.is_empty()
}
pub fn push(&mut self, data: Data) {
let index = self.data.len();
self.data.push(data);
let change = match self.changes.borrow().get(&index) {
None => ChangeType::Add,
Some(ChangeType::Remove) => ChangeType::Recreate,
Some(ChangeType::Add | ChangeType::Recreate | ChangeType::Update) => unreachable!(),
};
self.set_change(index, Some(change));
}
pub fn pop(&mut self) -> Option<Data> {
let data = self.data.pop()?;
let index = self.data.len();
let change = match self.changes.borrow().get(&index) {
None | Some(ChangeType::Update) => Some(ChangeType::Remove),
Some(ChangeType::Add) => None,
Some(ChangeType::Recreate) => Some(ChangeType::Remove),
Some(ChangeType::Remove) => unreachable!(),
};
self.set_change(index, change);
Some(data)
}
#[must_use]
pub fn get(&self, index: usize) -> Option<&Data> {
self.data.get(index)
}
#[must_use]
pub fn get_mut(&mut self, index: usize) -> Option<&mut Data> {
let data = self.data.get_mut(index)?;
let mut changes = self.changes.borrow_mut();
changes.entry(index).or_insert(ChangeType::Update);
Some(data)
}
fn set_change(&self, index: usize, change: Option<ChangeType>) {
if let Some(change) = change {
self.changes.borrow_mut().insert(index, change);
} else {
self.changes.borrow_mut().remove(&index);
}
}
}
impl<Data, View> Factory<Data, View> for FactoryVec<Data>
where
Data: FactoryPrototype<Factory = Self, View = View>,
View: FactoryView<Data::Root>,
{
type Key = usize;
fn generate(&self, view: &View, sender: Sender<Data::Msg>) {
let mut neg_index_adjustment = 0;
for (index, change) in self.changes.borrow().iter() {
let index = *index - neg_index_adjustment;
let mut widgets = self.widgets.borrow_mut();
match change {
ChangeType::Add => {
let data = &self.data[index];
let new_widgets = data.init_view(&index, sender.clone());
let position = data.position(&index);
let root = view.add(Data::root_widget(&new_widgets), &position);
widgets.push(Widgets {
widgets: new_widgets,
root,
});
}
ChangeType::Update => {
self.data[index].view(&index, &widgets[index].widgets);
}
ChangeType::Remove => {
let remove_widget = widgets.remove(index);
view.remove(&remove_widget.root);
neg_index_adjustment += 1;
}
ChangeType::Recreate => {
let data = &self.data[index];
let new_widgets = data.init_view(&index, sender.clone());
let position = data.position(&index);
let root = view.add(Data::root_widget(&new_widgets), &position);
let remove_widget = std::mem::replace(
&mut widgets[index],
Widgets {
widgets: new_widgets,
root,
},
);
view.remove(&remove_widget.root);
}
}
}
self.changes.borrow_mut().clear();
}
}
impl<Data, View> FactoryVec<Data>
where
Data: FactoryPrototype<Factory = Self, View = View>,
View: FactoryView<Data::Root>,
{
pub fn iter(&self) -> std::slice::Iter<'_, Data> {
self.data.iter()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_synced;
use gtk;
use gtk::prelude::*;
enum TestMsg {}
#[derive(Debug, PartialEq, Eq)]
struct TestData(u8);
fn wrap(data: &[u8]) -> Vec<TestData> {
data.iter().map(|d| TestData(*d)).collect()
}
#[relm4_macros::factory_prototype(relm4 = crate)]
impl FactoryPrototype for TestData {
type Factory = FactoryVec<Self>;
type Widgets = FactoryWidgets;
type View = gtk::Box;
type Msg = TestMsg;
view! {
gtk::Label {
set_text: watch! { &self.0.to_string() },
}
}
fn position(&self, _index: &usize) {}
}
fn child_texts(view: >k::Box) -> Vec<String> {
view.children::<gtk::Label>()
.iter()
.map(|l| l.text().into())
.collect()
}
trait BoxExt {
fn children<R: IsA<gtk::Widget>>(&self) -> Vec<R>;
fn len(&self) -> usize;
}
impl<T: IsA<gtk::Widget>> BoxExt for T {
fn children<R: IsA<gtk::Widget>>(&self) -> Vec<R> {
let mut children = vec![];
let mut next_child = self.first_child();
while let Some(child) = next_child {
next_child = child.next_sibling();
children.push(child.downcast().unwrap());
}
children
}
fn len(&self) -> usize {
self.children::<gtk::Widget>().len()
}
}
fn sender<T>() -> gtk::glib::Sender<T> {
let (sender, _) = gtk::glib::MainContext::channel(Default::default());
sender
}
const GET_FUNCS: [fn(&mut FactoryVec<TestData>, usize) -> Option<&TestData>; 2] =
[|v, i| v.get(i), |v, i| v.get_mut(i).map(|d| &*d)];
#[test]
fn simple_changes() {
test_synced(move || {
let view = gtk::Box::new(gtk::Orientation::Horizontal, 0);
let mut vec = FactoryVec::new();
assert_eq!(vec.len(), view.len());
assert_eq!(vec.len(), 0);
assert_eq!(vec.pop(), None);
vec.push(TestData(13));
vec.generate(&view, sender());
assert_eq!(vec.len(), view.len());
assert_eq!(vec.len(), 1);
vec.push(TestData(47));
vec.push(TestData(48));
vec.generate(&view, sender());
assert_eq!(vec.len(), view.len());
assert_eq!(vec.len(), 3);
let el = vec.pop();
vec.generate(&view, sender());
assert_eq!(el, Some(TestData(48)));
assert_eq!(vec.len(), view.len());
assert_eq!(vec.len(), 2);
vec.clear();
vec.generate(&view, sender());
assert_eq!(vec.len(), view.len());
assert_eq!(vec.len(), 0);
assert_eq!(vec.pop(), None);
vec.clear();
vec.generate(&view, sender());
assert_eq!(vec.len(), view.len());
assert_eq!(vec.len(), 0);
});
}
#[test]
fn data_consistent() {
for get in GET_FUNCS {
let vec = &mut FactoryVec::new();
vec.push(TestData(128));
assert_eq!(get(vec, 0), Some(&TestData(128)));
assert_eq!(get(vec, 1), None);
vec.push(TestData(222));
vec.push(TestData(223));
assert_eq!(get(vec, 0), Some(&TestData(128)));
assert_eq!(get(vec, 1), Some(&TestData(222)));
assert_eq!(get(vec, 2), Some(&TestData(223)));
assert_eq!(get(vec, 3), None);
vec.pop();
vec.get_mut(0).unwrap().0 = 13;
assert_eq!(get(vec, 0), Some(&TestData(13)));
assert_eq!(get(vec, 1), Some(&TestData(222)));
assert_eq!(get(vec, 2), None);
assert_eq!(get(vec, 3), None);
vec.clear();
assert_eq!(get(vec, 0), None);
assert_eq!(get(vec, 1), None);
assert_eq!(get(vec, 2), None);
assert_eq!(get(vec, 3), None);
}
}
#[test]
fn unrealized_replace() {
test_synced(move || {
let initial_data = [vec![], vec![1], vec![1, 2, 3]];
let control_data = [vec![], vec![5], vec![5, 7], vec![5, 7, 9]];
let xs = initial_data.iter();
let ys = control_data.iter();
let test_cases = ys.flat_map(|y| xs.clone().map(move |x| (x, y)));
for (initial, control) in test_cases {
let view = gtk::Box::new(gtk::Orientation::Horizontal, 0);
let control_strs = control.iter().map(u8::to_string).collect::<Vec<_>>();
let mut vec = FactoryVec::from_vec(wrap(initial));
vec.generate(&view, sender());
vec.clear();
for data in control {
vec.push(TestData(*data));
}
vec.generate(&view, sender());
assert_eq!(child_texts(&view), control_strs);
}
});
}
#[test]
fn all_state_transitions() {
test_synced(move || {
let view = gtk::Box::new(gtk::Orientation::Horizontal, 0);
let mut vec = FactoryVec::new();
vec.push(TestData(13));
vec.pop();
vec.push(TestData(2));
vec.push(TestData(23));
vec.generate(&view, sender());
vec.get_mut(0).unwrap();
vec.pop().unwrap();
vec.pop().unwrap();
vec.push(TestData(7));
vec.pop().unwrap();
vec.generate(&view, sender());
});
}
#[test]
fn all_states_generated() {
test_synced(move || {
let view = gtk::Box::new(gtk::Orientation::Horizontal, 0);
let mut vec = FactoryVec::from_vec(wrap(&[0, 1, 2, 3])); vec.generate(&view, sender());
vec.get_mut(1).unwrap().0 = 33; vec.pop(); vec.pop();
vec.push(TestData(66)); vec.generate(&view, sender());
assert_eq!(child_texts(&view), ["0", "33", "66"]);
});
}
}