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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
/*!
 * Layout-related data.
 *
 * The `View` contains `Row`s and each `Row` contains `Button`s.
 * They carry data relevant to their positioning only,
 * except the Button, which also carries some data
 * about its appearance and function.
 *
 * The layout is determined bottom-up, by measuring `Button` sizes,
 * deriving `Row` sizes from them, and then centering them within the `View`.
 *
 * That makes the `View` position immutable,
 * and therefore different than the other positions.
 *
 * Note that it might be a better idea
 * to make `View` position depend on its contents,
 * and let the renderer scale and center it within the widget.
 */

use std::cmp;
use std::collections::HashMap;
use std::ffi::CString;
use std::fmt;
use std::vec::Vec;

use crate::action::Action;
use crate::actors;
use crate::drawing;
use crate::float_ord::FloatOrd;
use crate::keyboard::{KeyState, KeyCode, PressType};
use crate::logging;
use crate::popover;
use crate::receiver;
use crate::submission::{ Submission, SubmitData, Timestamp };
use crate::util::find_max_double;

use crate::imservice::ContentPurpose;

// Traits
use crate::logging::Warn;

/// Gathers stuff defined in C or called by C
pub mod c {
    use super::*;
    
    use crate::receiver;
    use crate::submission::c::Submission as CSubmission;

    use gtk_sys;
    use std::ops::{ Add, Sub };
    use std::os::raw::c_void;
    
    use crate::util::CloneOwned;
    
    // The following defined in C
    #[repr(transparent)]
    #[derive(Copy, Clone)]
    pub struct EekGtkKeyboard(pub *const gtk_sys::GtkWidget);

    extern "C" {
        #[allow(improper_ctypes)]
        pub fn eek_gtk_keyboard_emit_feedback(
            keyboard: EekGtkKeyboard,
        );
    }

    /// Defined in eek-types.h
    #[repr(C)]
    #[derive(Clone, Debug, PartialEq)]
    pub struct Point {
        pub x: f64,
        pub y: f64,
    }

    impl Add for Point {
        type Output = Self;
        fn add(self, other: Self) -> Self {
            &self + other
        }
    }

    impl Add<Point> for &Point {
        type Output = Point;
        fn add(self, other: Point) -> Point {
            Point {
                x: self.x + other.x,
                y: self.y + other.y,
            }
        }
    }

    impl Sub<&Point> for Point {
        type Output = Point;
        fn sub(self, other: &Point) -> Point {
            Point {
                x: self.x - other.x,
                y: self.y - other.y,
            }
        }
    }

    /// Defined in eek-types.h
    #[repr(C)]
    #[derive(Clone, Debug, PartialEq)]
    pub struct Bounds {
        pub x: f64,
        pub y: f64,
        pub width: f64,
        pub height: f64
    }

    impl Bounds {
        pub fn contains(&self, point: &Point) -> bool {
            point.x > self.x && point.x < self.x + self.width
                && point.y > self.y && point.y < self.y + self.height
        }
    }

    /// Translate and then scale
    #[repr(C)]
    pub struct Transformation {
        pub origin_x: f64,
        pub origin_y: f64,
        pub scale_x: f64,
        pub scale_y: f64,
    }

    impl Transformation {
        /// Applies the new transformation after this one
        pub fn chain(self, next: Transformation) -> Transformation {
            Transformation {
                origin_x: self.origin_x + self.scale_x * next.origin_x,
                origin_y: self.origin_y + self.scale_y * next.origin_y,
                scale_x: self.scale_x * next.scale_x,
                scale_y: self.scale_y * next.scale_y,
            }
        }
        fn forward(&self, p: Point) -> Point {
            Point {
                x: (p.x - self.origin_x) / self.scale_x,
                y: (p.y - self.origin_y) / self.scale_y,
            }
        }
        fn reverse(&self, p: Point) -> Point {
            Point {
                x: p.x * self.scale_x + self.origin_x,
                y: p.y * self.scale_y + self.origin_y,
            }
        }
        pub fn reverse_bounds(&self, b: Bounds) -> Bounds {
            let start = self.reverse(Point { x: b.x, y: b.y });
            let end = self.reverse(Point {
                x: b.x + b.width,
                y: b.y + b.height,
            });
            Bounds {
                x: start.x,
                y: start.y,
                width: end.x - start.x,
                height: end.y - start.y,
            }
        }
    }

    // This is constructed only in C, no need for warnings
    #[allow(dead_code)]
    #[repr(transparent)]
    pub struct LevelKeyboard(*const c_void);

    // The following defined in Rust. TODO: wrap naked pointers to Rust data inside RefCells to prevent multiple writers

    /// Positions the layout contents within the available space.
    /// The origin of the transformation is the point inside the margins.
    #[no_mangle]
    pub extern "C"
    fn squeek_layout_calculate_transformation(
        layout: *const Layout,
        allocation_width: f64,
        allocation_height: f64,
    ) -> Transformation {
        let layout = unsafe { &*layout };
        layout.shape.calculate_transformation(Size {
            width: allocation_width,
            height: allocation_height,
        })
    }

    #[no_mangle]
    pub extern "C"
    fn squeek_layout_get_kind(layout: *const Layout) -> u32 {
        let layout = unsafe { &*layout };
        layout.shape.kind.clone() as u32
    }

    #[no_mangle]
    pub extern "C"
    fn squeek_layout_get_purpose(layout: *const Layout) -> u32 {
        let layout = unsafe { &*layout };
        layout.shape.purpose.clone() as u32
    }

    #[no_mangle]
    pub extern "C"
    fn squeek_layout_free(layout: *mut Layout) {
        unsafe { Box::from_raw(layout) };
    }

    /// Entry points for more complex procedures and algorithms which span multiple modules
    pub mod procedures {
        use super::*;

        /// Release pointer in the specified position
        #[no_mangle]
        pub extern "C"
        fn squeek_layout_release(
            layout: *mut Layout,
            submission: CSubmission,
            widget_to_layout: Transformation,
            time: u32,
            popover: actors::popover::c::Actor,
            app_state: receiver::c::State,
            ui_keyboard: EekGtkKeyboard,
        ) {
            let time = Timestamp(time);
            let layout = unsafe { &mut *layout };
            let submission = submission.clone_ref();
            let mut submission = submission.borrow_mut();
            let app_state = app_state.clone_owned();
            let popover_state = popover.clone_owned();
            
            let ui_backend = UIBackend {
                widget_to_layout,
                keyboard: ui_keyboard,
            };

            // The list must be copied,
            // because it will be mutated in the loop
            let pressed_buttons
                = layout.state.active_buttons.clone();
            for (button, _key_state) in pressed_buttons.iter_pressed() {
                seat::handle_release_key(
                    layout,
                    &mut submission,
                    Some(&ui_backend),
                    time,
                    Some((&popover_state, app_state.clone())),
                    button,
                );
            }
            drawing::queue_redraw(ui_keyboard);
        }

        /// Release all buttons but don't redraw
        #[no_mangle]
        pub extern "C"
        fn squeek_layout_release_all_only(
            layout: *mut Layout,
            submission: CSubmission,
            time: u32,
        ) {
            let layout = unsafe { &mut *layout };
            let submission = submission.clone_ref();
            let mut submission = submission.borrow_mut();
            // The list must be copied,
            // because it will be mutated in the loop
            let pressed_buttons = layout.state.active_buttons.clone();
            for (button, _key_state) in pressed_buttons.iter_pressed() {
                seat::handle_release_key(
                    layout,
                    &mut submission,
                    None, // don't update UI
                    Timestamp(time),
                    None, // don't switch layouts
                    button,
                );
            }
        }

        #[no_mangle]
        pub extern "C"
        fn squeek_layout_depress(
            layout: *mut Layout,
            submission: CSubmission,
            x_widget: f64, y_widget: f64,
            widget_to_layout: Transformation,
            time: u32,
            ui_keyboard: EekGtkKeyboard,
        ) {
            let layout = unsafe { &mut *layout };
            let submission = submission.clone_ref();
            let mut submission = submission.borrow_mut();
            let point = widget_to_layout.forward(
                Point { x: x_widget, y: y_widget }
            );

            let index = layout.find_index_by_position(point);

            if let Some((row, position_in_row)) = index {
                let button = ButtonPosition {
                    view: layout.state.current_view.clone(),
                    row,
                    position_in_row,
                };
                seat::handle_press_key(
                    layout,
                    &mut submission,
                    Timestamp(time),
                    &button,
                );
                // maybe TODO: draw on the display buffer here
                drawing::queue_redraw(ui_keyboard);
                unsafe {
                    eek_gtk_keyboard_emit_feedback(ui_keyboard);
                }
            };
        }

        // FIXME: this will work funny
        // when 2 touch points are on buttons and moving one after another
        // Solution is to have separate pressed lists for each point
        #[no_mangle]
        pub extern "C"
        fn squeek_layout_drag(
            layout: *mut Layout,
            submission: CSubmission,
            x_widget: f64, y_widget: f64,
            widget_to_layout: Transformation,
            time: u32,
            popover: actors::popover::c::Actor,
            app_state: receiver::c::State,
            ui_keyboard: EekGtkKeyboard,
        ) {
            let time = Timestamp(time);
            let layout = unsafe { &mut *layout };
            let submission = submission.clone_ref();
            let mut submission = submission.borrow_mut();
            // We only need to query state here, not update.
            // A copy is enough.
            let popover_state = popover.clone_owned();
            let app_state = app_state.clone_owned();
            let ui_backend = UIBackend {
                widget_to_layout,
                keyboard: ui_keyboard,
            };
            let point = ui_backend.widget_to_layout.forward(
                Point { x: x_widget, y: y_widget }
            );

            let pressed_buttons = layout.state.active_buttons.clone();
            let pressed_buttons = pressed_buttons.iter_pressed();
            let button_info = layout.find_index_by_position(point);

            if let Some((row, position_in_row)) = button_info {
                let current_pos = ButtonPosition {
                    view: layout.state.current_view.clone(),
                    row,
                    position_in_row,
                };
                let mut found = false;
                for (button, _key_state) in pressed_buttons {
                    if button == &current_pos {
                        found = true;
                    } else {
                        seat::handle_release_key(
                            layout,
                            &mut submission,
                            Some(&ui_backend),
                            time,
                            Some((&popover_state, app_state.clone())),
                            button,
                        );
                    }
                }
                if !found {
                    let button = ButtonPosition {
                        view: layout.state.current_view.clone(),
                        row,
                        position_in_row,
                    };
                    seat::handle_press_key(
                        layout,
                        &mut submission,
                        time,
                        &button,
                    );
                    // maybe TODO: draw on the display buffer here
                    unsafe {
                        eek_gtk_keyboard_emit_feedback(ui_keyboard);
                    }
                }
            } else {
                for (button, _key_state) in pressed_buttons {
                    seat::handle_release_key(
                        layout,
                        &mut submission,
                        Some(&ui_backend),
                        time,
                        Some((&popover_state, app_state.clone())),
                        button,
                    );
                }
            }
            drawing::queue_redraw(ui_keyboard);
        }

        #[cfg(test)]
        mod test {
            use super::*;

            fn near(a: f64, b: f64) -> bool {
                (a - b).abs() < ((a + b) * 0.001f64).abs()
            }

            #[test]
            fn transform_back() {
                let transform = Transformation {
                    origin_x: 10f64,
                    origin_y: 11f64,
                    scale_x: 12f64,
                    scale_y: 13f64,
                };
                let point = Point { x: 1f64, y: 1f64 };
                let transformed = transform.reverse(transform.forward(point.clone()));
                assert!(near(point.x, transformed.x));
                assert!(near(point.y, transformed.y));
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct Size {
    pub width: f64,
    pub height: f64,
}

#[derive(Debug, Clone, PartialEq)]
pub enum Label {
    /// Text used to display the symbol
    Text(CString),
    /// Icon name used to render the symbol
    IconName(CString),
}

/// The definition of an interactive button
#[derive(Clone, Debug, PartialEq)]
pub struct Button {
    /// ID string, e.g. for CSS
    pub name: CString,
    /// Label to display to the user
    pub label: Label,
    pub size: Size,
    /// The name of the visual class applied
    pub outline_name: CString,
    // action-related stuff
    /// A cache of raw keycodes derived from Action::Submit given a keymap
    pub keycodes: Vec<KeyCode>,
    /// Static description of what the key does when pressed or released
    pub action: Action,
}

impl Button {
    pub fn get_bounds(&self) -> c::Bounds {
        c::Bounds {
            x: 0.0, y: 0.0,
            width: self.size.width, height: self.size.height,
        }
    }
}

/// The representation of a row of buttons
#[derive(Clone, Debug)]
pub struct Row {
    /// Buttons together with their offset from the left relative to the row.
    /// ie. the first button always start at 0.
    buttons: Vec<(f64, Button)>,

    /// Total size of the row
    size: Size,
}

impl Row {
    pub fn new(buttons: Vec<(f64, Button)>) -> Row {
        // Make sure buttons are sorted by offset.
        debug_assert!({
            let mut sorted = buttons.clone();
            sorted.sort_by(|(f1, _), (f2, _)| f1.partial_cmp(f2).unwrap());

            sorted.iter().map(|(f, _)| *f).collect::<Vec<_>>()
                == buttons.iter().map(|(f, _)| *f).collect::<Vec<_>>()
        });

        let width = buttons.iter().next_back()
            .map(|(x_offset, button)| button.size.width + x_offset)
            .unwrap_or(0.0);

        let height = find_max_double(
            buttons.iter(),
            |(_offset, button)| button.size.height,
        );

        Row { buttons, size: Size { width, height } }
    }

    pub fn get_size(&self) -> Size {
        self.size.clone()
    }

    pub fn get_buttons(&self) -> &Vec<(f64, Button)> {
        &self.buttons
    }

    /// Finds the first button that covers the specified point
    /// relative to row's position's origin.
    /// Returns its index too.
    fn find_button_by_position(&self, x: f64) -> (&Button, usize)
    {
        // Buttons are sorted so we can use a binary search to find the clicked
        // button. Note this doesn't check whether the point is actually within
        // a button. This is on purpose as we want a click past the left edge of
        // the left-most button to register as a click.
        let result = self.buttons.binary_search_by(
            |&(f, _)| f.partial_cmp(&x).unwrap()
        );

        let index = result.unwrap_or_else(|r| r);
        let index = if index > 0 { index - 1 } else { 0 };

        (&self.buttons[index].1, index)
    }
}

#[derive(Clone, Debug)]
pub struct Spacing {
    pub row: f64,
    pub button: f64,
}

#[derive(Clone)]
pub struct View {
    /// Rows together with their offsets from the top left
    rows: Vec<(c::Point, Row)>,

    /// Total size of the view
    size: Size,
}

impl View {
    pub fn new(rows: Vec<(f64, Row)>) -> View {
        // Make sure rows are sorted by offset.
        debug_assert!({
            let mut sorted = rows.clone();
            sorted.sort_by(|(f1, _), (f2, _)| f1.partial_cmp(f2).unwrap());

            sorted.iter().map(|(f, _)| *f).collect::<Vec<_>>()
                == rows.iter().map(|(f, _)| *f).collect::<Vec<_>>()
        });

        // No need to call `get_rows()`,
        // as the biggest row is the most far reaching in both directions
        // because they are all centered.
        let width = find_max_double(rows.iter(), |(_offset, row)| row.size.width);

        let height = rows.iter().next_back()
            .map(|(y_offset, row)| row.size.height + y_offset)
            .unwrap_or(0.0);

        // Center the rows
        let rows = rows.into_iter().map(|(y_offset, row)| {(
                c::Point {
                    x: (width - row.size.width) / 2.0,
                    y: y_offset,
                },
                row,
            )}).collect::<Vec<_>>();

        View { rows, size: Size { width, height } }
    }
    /// Finds the first button that covers the specified point
    /// relative to view's position's origin.
    /// Returns also (row, column) index.
    fn find_button_by_position(&self, point: c::Point)
        -> Option<(&Button, (usize, usize))>
    {
        // Only test bounds of the view here, letting rows/column search extend
        // to the edges of these bounds.
        let bounds = c::Bounds {
            x: 0.0,
            y: 0.0,
            width: self.size.width,
            height: self.size.height,
        };
        if !bounds.contains(&point) {
            return None;
        }

        // Rows are sorted so we can use a binary search to find the row.
        let result = self.rows.binary_search_by(
            |(f, _)| f.y.partial_cmp(&point.y).unwrap()
        );

        let index = result.unwrap_or_else(|r| r);
        let index = if index > 0 { index - 1 } else { 0 };

        let row = &self.rows[index];
        let (button, button_index)
            = row.1.find_button_by_position(point.x - row.0.x);

        Some((
            &button,
            (index, button_index),
        ))
    }

    pub fn get_size(&self) -> Size {
        self.size.clone()
    }

    /// Returns positioned rows, with appropriate x offsets (centered)
    pub fn get_rows(&self) -> &Vec<(c::Point, Row)> {
        &self.rows
    }

    /// Returns a size which contains all the views
    /// if they are all centered on the same point.
    pub fn calculate_super_size(views: Vec<&View>) -> Size {
        Size {
            height: find_max_double(
                views.iter(),
                |view| view.size.height,
            ),
            width: find_max_double(
                views.iter(),
                |view| view.size.width,
            ),
        }
    }
}

/// The physical characteristic of layout for the purpose of styling
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum ArrangementKind {
    Base = 0,
    Wide = 1,
}

#[derive(Debug, PartialEq)]
pub struct Margins {
    pub top: f64,
    pub bottom: f64,
    pub left: f64,
    pub right: f64,
}

#[derive(Clone, Debug, PartialEq)]
pub enum LatchedState {
    /// Holds view to return to.
    FromView(String),
    Not,
}

/// Associates the state of a layout with its definition.
/// Contains everything necessary to present this layout to the user
/// and to determine its reactions to inputs.
pub struct Layout {
    pub state: LayoutState,
    pub shape: LayoutData,
}

/// Button position for the pressed buttons list
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct ButtonPosition {
    // There's only ever going to be a handul of pressed buttons,
    // so as inefficient as String is, it won't make a difference.
    // In the worst case, views can turn into indices in the description.
    pub view: String,
    /// Index to the view's row.
    pub row: usize,
    /// Index to the row's button.
    pub position_in_row: usize,
}

#[derive(Clone)]
pub struct ActiveButtons(HashMap<ButtonPosition, KeyState>);

enum Presence {
    Missing,
    Present,
}

static RELEASED: KeyState = KeyState { pressed: PressType::Released };

impl ActiveButtons {
    fn insert(&mut self, button: ButtonPosition, state: KeyState) -> Presence {
        match self.0.insert(button, state) {
            Some(_) => Presence::Present,
            None => Presence::Missing,
        }
    }
    
    pub fn get(&self, button: &ButtonPosition) -> &KeyState {
        self.0.get(button)
            .unwrap_or(&RELEASED)
    }
    fn remove(&mut self, button: &ButtonPosition) -> Presence {
        match self.0.remove(button) {
            Some(_) => Presence::Present,
            None => Presence::Missing,
        }
    }
    fn iter_pressed(&self) -> impl Iterator<Item=(&ButtonPosition, &KeyState)> {
        self.0.iter().filter(|(_p, s)| s.pressed == PressType::Pressed)
    }
}

/// Changeable state that can't be derived from the definition of the layout.
pub struct LayoutState {
    pub current_view: String,

    // If current view is latched,
    // clicking any button that emits an action (erase, submit, set modifier)
    // will cause lock buttons to unlatch.
    view_latched: LatchedState,
    // a Vec would be enough, but who cares, this will be small & fast enough
    // TODO: turn those into per-input point *_buttons to track dragging.
    // The renderer doesn't need the list of pressed keys any more,
    // because it needs to iterate
    // through all buttons of the current view anyway.
    // When the list tracks actual location,
    // it becomes possible to place popovers and other UI accurately.
    /// Buttons not in this list are in their base state:
    /// not pressed.
    /// Latched/locked appearance is derived from current view
    /// and button metadata.
    pub active_buttons: ActiveButtons,
}

/// A builder structure for picking up layout data from storage
pub struct LayoutParseData {
    /// Point is the offset within the panel
    /// (transformed to layout's coordinate space).
    pub views: HashMap<String, (c::Point, View)>,
    /// xkb keymaps applicable to the contained keys
    pub keymaps: Vec<CString>,
    pub margins: Margins,
}

/// Static, cacheable information for the layout
pub struct LayoutData {
    pub margins: Margins,
    pub kind: ArrangementKind,
    pub purpose: ContentPurpose,

    // Views own the actual buttons which have state
    // Maybe they should own UI only,
    // and keys should be owned by a dedicated non-UI-State?
    /// Point is the offset within the layout
    pub views: HashMap<String, (c::Point, View)>,

    // Non-UI stuff
    /// xkb keymaps applicable to the contained keys. Unchangeable
    pub keymaps: Vec<CString>,
}

#[derive(Debug)]
struct NoSuchView;

impl fmt::Display for NoSuchView {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "No such view")
    }
}


impl LayoutData {
    fn get_button(&self, button: &ButtonPosition) -> Option<&Button> {
        let (_, view) = self.views.get(&button.view)?;
        let (_, row) = view.rows.get(button.row)?;
        let (_, key) = row.buttons.get(button.position_in_row)?;
        Some(key)
    }

    fn find_button_place(&self, button: &ButtonPosition) -> Option<procedures::Place> {
        let (_, view) = self.views.get(&button.view)?;
        procedures::find_button_place(view, (button.row, button.position_in_row))
    }
    
    /// Calculates size without margins
    fn calculate_inner_size(&self) -> Size {
        View::calculate_super_size(
            self.views.iter().map(|(_, (_offset, v))| v).collect()
        )
    }

    /// Size including margins
    fn calculate_size(&self) -> Size {
        let inner_size = self.calculate_inner_size();
        Size {
            width: self.margins.left + inner_size.width + self.margins.right,
            height: (
                self.margins.top
                + inner_size.height
                + self.margins.bottom
            ),
        }
    }

    pub fn calculate_transformation(
        &self,
        available: Size,
    ) -> c::Transformation {
        let size = self.calculate_size();
        let h_scale = available.width / size.width;
        let v_scale = available.height / size.height;
        // Allow up to 5% (and a bit more) horizontal stretching for filling up available space
        let scale_x = if (h_scale / v_scale) < 1.055 { h_scale } else { v_scale };
        let scale_y = cmp::min(FloatOrd(h_scale), FloatOrd(v_scale)).0;
        let outside_margins = c::Transformation {
            origin_x: (available.width - (scale_x * size.width)) / 2.0,
            origin_y: (available.height - (scale_y * size.height)) / 2.0,
            scale_x: scale_x,
            scale_y: scale_y,
        };
        outside_margins.chain(c::Transformation {
            origin_x: self.margins.left,
            origin_y: self.margins.top,
            scale_x: 1.0,
            scale_y: 1.0,
        })
    }
}

// Unfortunately, changes are not atomic due to mutability :(
// An error will not be recoverable
// The usage of &mut on Rc<RefCell<KeyState>> doesn't mean anything special.
// Cloning could also be used.
impl Layout {
    pub fn new(data: LayoutParseData, kind: ArrangementKind, purpose: ContentPurpose) -> Layout {
        Layout {
            shape: LayoutData {
                kind,
                views: data.views,
                keymaps: data.keymaps,
                margins: data.margins,
                purpose,
            },
            state: LayoutState {
                current_view: "base".to_owned(),
                view_latched: LatchedState::Not,
                active_buttons: ActiveButtons(HashMap::new()),
            },
        }
    }

    pub fn get_current_view_position(&self) -> &(c::Point, View) {
        &self.shape.views
            .get(&self.state.current_view).expect("Selected nonexistent view")
    }

    pub fn get_current_view(&self) -> &View {
        &self.shape.views.get(&self.state.current_view).expect("Selected nonexistent view").1
    }

    fn set_view(&mut self, view: String) -> Result<(), NoSuchView> {
        if self.shape.views.contains_key(&view) {
            self.state.current_view = view;
            Ok(())
        } else {
            Err(NoSuchView)
        }
    }

    // Layout is passed around mutably,
    // so better keep the field away from direct access.
    pub fn get_view_latched(&self) -> &LatchedState {
        &self.state.view_latched
    }
    
    /// Returns index within current view
    fn find_index_by_position(&self, point: c::Point) -> Option<(usize, usize)> {
        let (offset, view) = self.get_current_view_position();
        view.find_button_by_position(point - offset)
            .map(|(_b, i)| i)
    }

    /// Returns index within current view too.
    pub fn foreach_visible_button<F>(&self, mut f: F)
        where F: FnMut(c::Point, &Button, (usize, usize))
    {
        let (view_offset, view) = self.get_current_view_position();
        let rows = view.get_rows().iter().enumerate();
        for (row_idx, (row_offset, row)) in rows {
            let buttons = row.buttons.iter().enumerate();
            for (button_idx, (x_offset, button)) in buttons {
                let offset = view_offset
                    + row_offset.clone()
                    + c::Point { x: *x_offset, y: 0.0 };
                f(offset, button, (row_idx, button_idx));
            }
        }
    }

    fn apply_view_transition(
        &mut self,
        action: &Action,
    ) {
        let (transition, new_latched) = Layout::process_action_for_view(
            action,
            &self.state.current_view,
            &self.state.view_latched,
        );

        match transition {
            ViewTransition::UnlatchAll => self.unstick_locks(),
            ViewTransition::ChangeTo(view) => try_set_view(self, view.into()),
            ViewTransition::NoChange => {},
        };

        self.state.view_latched = new_latched;
    }

    /// Unlatch all latched keys,
    /// so that the new view is the one before first press.
    fn unstick_locks(&mut self) {
        if let LatchedState::FromView(name) = self.state.view_latched.clone() {
            match self.set_view(name.clone()) {
                Ok(_) => { self.state.view_latched = LatchedState::Not; }
                Err(e) => log_print!(
                    logging::Level::Bug,
                    "Bad view {}, can't unlatch ({:?})",
                    name,
                    e,
                ),
            }
        }
    }

    /// Last bool is new latch state.
    /// It doesn't make sense when the result carries UnlatchAll,
    /// but let's not be picky.
    ///
    /// Although the state is not defined at the keys
    /// (it's in the relationship between view and action),
    /// keys go through the following stages when clicked repeatedly:
    /// unlocked+unlatched -> locked+latched -> locked+unlatched
    /// -> unlocked+unlatched
    fn process_action_for_view<'a>(
        action: &'a Action,
        current_view: &str,
        latched: &LatchedState,
    ) -> (ViewTransition<'a>, LatchedState) {
        match action {
            Action::Submit { text: _, keys: _ }
                | Action::Erase
                | Action::ApplyModifier(_)
            => {
                let t = match latched {
                    LatchedState::FromView(_) => ViewTransition::UnlatchAll,
                    LatchedState::Not => ViewTransition::NoChange,
                };
                (t, LatchedState::Not)
            },
            Action::SetView(view) => (
                ViewTransition::ChangeTo(view),
                LatchedState::Not,
            ),
            Action::LockView { lock, unlock, latches, looks_locked_from: _ } => {
                use self::ViewTransition as VT;
                let locked = action.is_locked(current_view);
                match (locked, latched, latches) {
                    // Was unlocked, now make locked but latched.
                    (false, LatchedState::Not, true) => (
                        VT::ChangeTo(lock),
                        LatchedState::FromView(current_view.into()),
                    ),
                    // Layout is latched for reason other than this button.
                    (false, LatchedState::FromView(view), true) => (
                        VT::ChangeTo(lock),
                        LatchedState::FromView(view.clone()),
                    ),
                    // Was latched, now only locked.
                    (true, LatchedState::FromView(_), true)
                        => (VT::NoChange, LatchedState::Not),
                    // Was unlocked, can't latch so now make fully locked.
                    (false, _, false)
                        => (VT::ChangeTo(lock), LatchedState::Not),
                    // Was locked, now make unlocked.
                    (true, _, _)
                        => (VT::ChangeTo(unlock), LatchedState::Not),
                }
            },
            _ => (ViewTransition::NoChange, latched.clone()),
        }
    }
}

#[derive(Debug, PartialEq)]
enum ViewTransition<'a> {
    ChangeTo(&'a str),
    UnlatchAll,
    NoChange,
}

fn try_set_view(layout: &mut Layout, view_name: &str) {
    layout.set_view(view_name.into())
        .or_print(
            logging::Problem::Bug,
            &format!("Bad view {}, ignoring", view_name),
        );
}


mod procedures {
    use super::*;

    pub type Place<'v> = (c::Point, &'v Button);

    /// Finds the canvas offset of the button.
    pub fn find_button_place<'v>(
        view: &'v View,
        (row, position_in_row): (usize, usize),
    ) -> Option<Place<'v>> {
        let (row_offset, row) = view.get_rows().get(row)?;
        let (x_offset, button) = row.get_buttons()
            .get(position_in_row)?;
        Some((
            row_offset + c::Point { x: *x_offset, y: 0.0 },
            button,
        ))
    }

    #[cfg(test)]
    mod test {
        use super::*;

        use crate::layout::test::*;

        /// Checks indexing of buttons
        #[test]
        fn view_has_button() {
            let button = make_button("1".into());

            let row = Row::new(vec!((0.1, button)));

            let view = View::new(vec!((1.2, row)));

            assert_eq!(
                find_button_place(&view, (0, 0)),
                Some((
                    c::Point { x: 0.1, y: 1.2 },
                    &make_button("1".into()),
                ))
            );

            let view = View::new(vec![]);
            assert_eq!(
                find_button_place(&view, (0, 0)),
                None,
            );
        }
    }
}

pub struct UIBackend {
    widget_to_layout: c::Transformation,
    keyboard: c::EekGtkKeyboard,
}

/// Top level procedures, dispatching to everything
mod seat {
    use super::*;

    fn handle_press_key_cleaner(
        shape: &LayoutData,
        submission: &mut Submission,
        time: Timestamp,
        button_pos: &ButtonPosition,
    ) {
        let button = shape.get_button(button_pos).unwrap();
        let action = button.action.clone();
        match action {
            Action::Submit {
                text: Some(text),
                keys: _,
            } => submission.handle_press(
                button_pos.into(),
                SubmitData::Text(&text),
                &button.keycodes,
                time,
            ),
            Action::Submit {
                text: None,
                keys: _,
            } => submission.handle_press(
                button_pos.into(),
                SubmitData::Keycodes,
                &button.keycodes,
                time,
            ),
            Action::Erase => submission.handle_press(
                button_pos.into(),
                SubmitData::Erase,
                &button.keycodes,
                time,
            ),
            _ => {},
        };
    }
    
    pub fn handle_press_key(
        layout: &mut Layout,
        submission: &mut Submission,
        time: Timestamp,
        button_pos: &ButtonPosition,
    ) {
        // Send messages
        handle_press_key_cleaner(&layout.shape, submission, time, button_pos);
    
        // Update state
        let find = layout.state.active_buttons.get(button_pos);
        if let KeyState { pressed: PressType::Pressed } = find {
            log_print!(
                logging::Level::Bug,
                "Button {:?} was already pressed", button_pos,
            );
        } else {
            layout.state.active_buttons.insert(
                button_pos.clone(),
                KeyState { pressed: PressType::Pressed },
            );
        }
    }

    fn handle_release_key_cleaner(
        shape: &LayoutData,
        submission: &mut Submission,
        ui: Option<&UIBackend>,
        time: Timestamp,
        // TODO: intermediate measure:
        // passing state conditionally because it's only used for popover.
        // Eventually, it should be used for sumitting button events,
        // and passed always.
        manager: Option<(&actors::popover::State, receiver::State)>,
        button_pos: &ButtonPosition,
    ) -> Action{
        let button = shape.get_button(&button_pos).unwrap();
        let action = button.action.clone();

        // process non-view switching
        match action.clone() {
            Action::Submit { text: _, keys: _ }
                | Action::Erase
            => {
                submission.handle_release(button_pos.into(), time);
            },
            Action::ApplyModifier(modifier) => {
                // FIXME: key id is unneeded with stateless locks
                let key_id = button_pos.into();
                let gets_locked = !submission.is_modifier_active(modifier);
                match gets_locked {
                    true => submission.handle_add_modifier(
                        key_id,
                        modifier, time,
                    ),
                    false => submission.handle_drop_modifier(key_id, time),
                }
            }
            // only show when UI is present
            Action::ShowPreferences => if let Some(ui) = &ui {
                // only show when layout manager is available
                if let Some((manager, app_state)) = manager {
                    let place = shape.find_button_place(button_pos);

                    if let Some((position, button)) = place {
                        let bounds = c::Bounds {
                            x: position.x,
                            y: position.y,
                            width: button.size.width,
                            height: button.size.height,
                        };
                        popover::show(
                            ui.keyboard,
                            ui.widget_to_layout.reverse_bounds(bounds),
                            manager,
                            app_state,
                        );
                    }
                }
            },
            // Other keys are handled in view switcher before.
            _ => {}
        };
        
        action
    }
    
    /// Mutates layout and sends events.
    /// This split away from handle_release_key
    /// in order to pull at least some of the mutation away
    /// from what should some day be core functional logic.
    pub fn handle_release_key(
        layout: &mut Layout,
        submission: &mut Submission,
        ui: Option<&UIBackend>,
        time: Timestamp,
        // TODO: intermediate measure:
        // passing state conditionally because it's only used for popover.
        // Eventually, it should be used for sumitting button events,
        // and passed always.
        manager: Option<(&actors::popover::State, receiver::State)>,
        button_pos: &ButtonPosition,
    ) {
        // Send events
        let action = handle_release_key_cleaner(
            &layout.shape,
            submission,
            ui,
            time,
            manager,
            button_pos,
        );
        
        // Apply state changes
        layout.apply_view_transition(&action);
        
        if let Presence::Missing = layout.state.active_buttons.remove(&button_pos) {
            log_print!(
                logging::Level::Bug,
                "No button to remove from pressed list: {:?}", button_pos
            );
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    use std::ffi::CString;

    pub fn make_button(
        name: String,
    ) -> Button {
        Button {
            name: CString::new(name.clone()).unwrap(),
            size: Size { width: 0f64, height: 0f64 },
            outline_name: CString::new("test").unwrap(),
            label: Label::Text(CString::new(name).unwrap()),
            action: Action::SetView("default".into()),
            keycodes: Vec::new(),
        }
    }

    #[test]
    fn latch_lock_unlock() {
        let action = Action::LockView {
            lock: "lock".into(),
            unlock: "unlock".into(),
            latches: true,
            looks_locked_from: vec![],
        };

        assert_eq!(
            Layout::process_action_for_view(&action, "unlock", &LatchedState::Not),
            (ViewTransition::ChangeTo("lock"), LatchedState::FromView("unlock".into())),
        );

        assert_eq!(
            Layout::process_action_for_view(&action, "lock", &LatchedState::FromView("unlock".into())),
            (ViewTransition::NoChange, LatchedState::Not),
        );

        assert_eq!(
            Layout::process_action_for_view(&action, "lock", &LatchedState::Not),
            (ViewTransition::ChangeTo("unlock"), LatchedState::Not),
        );

        assert_eq!(
            Layout::process_action_for_view(&Action::Erase, "lock", &LatchedState::FromView("base".into())),
            (ViewTransition::UnlatchAll, LatchedState::Not),
        );
    }

    #[test]
    fn latch_pop_layout() {
        let switch = Action::LockView {
            lock: "locked".into(),
            unlock: "base".into(),
            latches: true,
            looks_locked_from: vec![],
        };

        let submit = Action::Erase;

        let view = View::new(vec![(
            0.0,
            Row::new(vec![
                (
                    0.0,
                    Button {
                        action: switch.clone(),
                        ..make_button("switch".into())
                    },
                ),
                (
                    1.0,
                    Button {
                        action: submit.clone(),
                        ..make_button("submit".into())
                    },
                ),
            ]),
        )]);

        let mut layout = Layout {
            state: LayoutState {
                current_view: "base".into(),
                view_latched: LatchedState::Not,
                active_buttons: ActiveButtons(HashMap::new()),
            },
            shape: LayoutData {
                keymaps: Vec::new(),
                kind: ArrangementKind::Base,
                margins: Margins {
                    top: 0.0,
                    left: 0.0,
                    right: 0.0,
                    bottom: 0.0,
                },
                views: hashmap! {
                    // Both can use the same structure.
                    // Switching doesn't depend on the view shape
                    // as long as the switching button is present.
                    "base".into() => (c::Point { x: 0.0, y: 0.0 }, view.clone()),
                    "locked".into() => (c::Point { x: 0.0, y: 0.0 }, view),
                },
                purpose: ContentPurpose::Normal,
            },
        };

        // Basic cycle
        layout.apply_view_transition(&switch);
        assert_eq!(&layout.state.current_view, "locked");
        layout.apply_view_transition(&switch);
        assert_eq!(&layout.state.current_view, "locked");
        layout.apply_view_transition(&submit);
        assert_eq!(&layout.state.current_view, "locked");
        layout.apply_view_transition(&switch);
        assert_eq!(&layout.state.current_view, "base");
        layout.apply_view_transition(&switch);
        // Unlatch
        assert_eq!(&layout.state.current_view, "locked");
        layout.apply_view_transition(&submit);
        assert_eq!(&layout.state.current_view, "base");
    }

    #[test]
    fn reverse_unlatch_layout() {
        let switch = Action::LockView {
            lock: "locked".into(),
            unlock: "base".into(),
            latches: true,
            looks_locked_from: vec![],
        };

        let unswitch = Action::LockView {
            lock: "locked".into(),
            unlock: "unlocked".into(),
            latches: false,
            looks_locked_from: vec![],
        };

        let submit = Action::Erase;

        let view = View::new(vec![(
            0.0,
            Row::new(vec![
                (
                    0.0,
                    Button {
                        action: switch.clone(),
                        ..make_button("switch".into())
                    },
                ),
                (
                    1.0,
                    Button {
                        action: submit.clone(),
                        ..make_button("submit".into())
                    },
                ),
            ]),
        )]);

        let mut layout = Layout {
            state: LayoutState {
                current_view: "base".into(),
                view_latched: LatchedState::Not,
                active_buttons: ActiveButtons(HashMap::new()),
            },
            shape: LayoutData {
                keymaps: Vec::new(),
                kind: ArrangementKind::Base,
                margins: Margins {
                    top: 0.0,
                    left: 0.0,
                    right: 0.0,
                    bottom: 0.0,
                },
                views: hashmap! {
                    // Both can use the same structure.
                    // Switching doesn't depend on the view shape
                    // as long as the switching button is present.
                    "base".into() => (c::Point { x: 0.0, y: 0.0 }, view.clone()),
                    "locked".into() => (c::Point { x: 0.0, y: 0.0 }, view.clone()),
                    "unlocked".into() => (c::Point { x: 0.0, y: 0.0 }, view),
                },
                purpose: ContentPurpose::Normal,
            },
        };

        layout.apply_view_transition(&switch);
        assert_eq!(&layout.state.current_view, "locked");
        layout.apply_view_transition(&unswitch);
        assert_eq!(&layout.state.current_view, "unlocked");
    }

    #[test]
    fn latch_twopop_layout() {
        let switch = Action::LockView {
            lock: "locked".into(),
            unlock: "base".into(),
            latches: true,
            looks_locked_from: vec![],
        };

        let switch_again = Action::LockView {
            lock: "ĄĘ".into(),
            unlock: "locked".into(),
            latches: true,
            looks_locked_from: vec![],
        };

        let submit = Action::Erase;

        let view = View::new(vec![(
            0.0,
            Row::new(vec![
                (
                    0.0,
                    Button {
                        action: switch.clone(),
                        ..make_button("switch".into())
                    },
                ),
                (
                    1.0,
                    Button {
                        action: submit.clone(),
                        ..make_button("submit".into())
                    },
                ),
            ]),
        )]);

        let mut layout = Layout {
            state: LayoutState {
                current_view: "base".into(),
                view_latched: LatchedState::Not,
                active_buttons: ActiveButtons(HashMap::new()),
            },
            shape: LayoutData {
                keymaps: Vec::new(),
                kind: ArrangementKind::Base,
                margins: Margins {
                    top: 0.0,
                    left: 0.0,
                    right: 0.0,
                    bottom: 0.0,
                },
                views: hashmap! {
                    // All can use the same structure.
                    // Switching doesn't depend on the view shape
                    // as long as the switching button is present.
                    "base".into() => (c::Point { x: 0.0, y: 0.0 }, view.clone()),
                    "locked".into() => (c::Point { x: 0.0, y: 0.0 }, view.clone()),
                    "ĄĘ".into() => (c::Point { x: 0.0, y: 0.0 }, view),
                },
                purpose: ContentPurpose::Normal,
            },
        };

        // Latch twice, then Ąto-unlatch across 2 levels
        layout.apply_view_transition(&switch);
        println!("{:?}", layout.state.view_latched);
        assert_eq!(&layout.state.current_view, "locked");
        layout.apply_view_transition(&switch_again);
        println!("{:?}", layout.state.view_latched);
        assert_eq!(&layout.state.current_view, "ĄĘ");
        layout.apply_view_transition(&submit);
        println!("{:?}", layout.state.view_latched);
        assert_eq!(&layout.state.current_view, "base");
    }

    #[test]
    fn check_centering() {
        //    A B
        // ---bar---
        let view = View::new(vec![
            (
                0.0,
                Row::new(vec![
                    (
                        0.0,
                        Button {
                            size: Size { width: 5.0, height: 10.0 },
                            ..make_button("A".into())
                        },
                    ),
                    (
                        5.0,
                        Button {
                            size: Size { width: 5.0, height: 10.0 },
                            ..make_button("B".into())
                        },
                    ),
                ]),
            ),
            (
                10.0,
                Row::new(vec![
                    (
                        0.0,
                        Button {
                            size: Size { width: 30.0, height: 10.0 },
                            ..make_button("bar".into())
                        },
                    ),
                ]),
            )
        ]);
        assert!(
            view.find_button_by_position(c::Point { x: 5.0, y: 5.0 })
                .unwrap().0.name.to_str().unwrap() == "A"
        );
        assert!(
            view.find_button_by_position(c::Point { x: 14.99, y: 5.0 })
                .unwrap().0.name.to_str().unwrap() == "A"
        );
        assert!(
            view.find_button_by_position(c::Point { x: 15.01, y: 5.0 })
                .unwrap().0.name.to_str().unwrap() == "B"
        );
        assert!(
            view.find_button_by_position(c::Point { x: 25.0, y: 5.0 })
                .unwrap().0.name.to_str().unwrap() == "B"
        );
    }

    #[test]
    fn check_bottom_margin() {
        // just one button
        let view = View::new(vec![
            (
                0.0,
                Row::new(vec![(
                    0.0,
                    Button {
                        size: Size { width: 1.0, height: 1.0 },
                        ..make_button("foo".into())
                    },
                )]),
            ),
        ]);
        let layout = LayoutData {
            keymaps: Vec::new(),
            kind: ArrangementKind::Base,
            // Lots of bottom margin
            margins: Margins {
                top: 0.0,
                left: 0.0,
                right: 0.0,
                bottom: 1.0,
            },
            views: hashmap! {
                String::new() => (c::Point { x: 0.0, y: 0.0 }, view),
            },
            purpose: ContentPurpose::Normal,
        };
        assert_eq!(
            layout.calculate_inner_size(),
            Size { width: 1.0, height: 1.0 }
        );
        assert_eq!(
            layout.calculate_size(),
            Size { width: 1.0, height: 2.0 }
        );
        // Don't change those values randomly!
        // They take advantage of incidental precise float representation
        // to even be comparable.
        let transformation = layout.calculate_transformation(
            Size { width: 2.0, height: 2.0 }
        );
        assert_eq!(transformation.scale_x, 1.0);
        assert_eq!(transformation.scale_y, 1.0);
        assert_eq!(transformation.origin_x, 0.5);
        assert_eq!(transformation.origin_y, 0.0);
    }

    #[test]
    fn check_stretching() {
        // just one button
        let view = View::new(vec![
            (
                0.0,
                Row::new(vec![(
                    0.0,
                    Button {
                        size: Size { width: 1.0, height: 1.0 },
                        ..make_button("foo".into())
                    },
                )]),
            ),
        ]);
        let layout = LayoutData {
            keymaps: Vec::new(),
            kind: ArrangementKind::Base,
            margins: Margins {
                top: 0.0,
                left: 0.0,
                right: 0.0,
                bottom: 0.0,
            },
            views: hashmap! {
                String::new() => (c::Point { x: 0.0, y: 0.0 }, view),
            },
            purpose: ContentPurpose::Normal,
        };
        let transformation = layout.calculate_transformation(
            Size { width: 100.0, height: 100.0 }
        );
        assert_eq!(transformation.scale_x, 100.0);
        assert_eq!(transformation.scale_y, 100.0);
        let transformation = layout.calculate_transformation(
            Size { width: 95.0, height: 100.0 }
        );
        assert_eq!(transformation.scale_x, 95.0);
        assert_eq!(transformation.scale_y, 95.0);
        let transformation = layout.calculate_transformation(
            Size { width: 105.0, height: 100.0 }
        );
        assert_eq!(transformation.scale_x, 105.0);
        assert_eq!(transformation.scale_y, 100.0);
        let transformation = layout.calculate_transformation(
            Size { width: 106.0, height: 100.0 }
        );
        assert_eq!(transformation.scale_x, 100.0);
        assert_eq!(transformation.scale_y, 100.0);
    }
}