papyri 0.1.0

Data visualization based on Cairo
Documentation
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
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
/*Copyright (c) 2022 Diego da Silva Lima. All rights reserved.

This work is licensed under the terms of the MIT license.  
For a copy, see <https://opensource.org/licenses/MIT>.*/

use cairo::Context;
use std::default::Default;
use std::collections::HashMap;
use std::error::Error;
use std::result::Result;
use std::io::{ErrorKind, Write};
use mappings::*;
use std::fmt::Display;
use std::any::Any;
use std::error;
use std::{fmt, fs::File};
use cairo::{SvgSurface, PsSurface, ImageSurface, Format};
use std::path::Path;
use std::cmp::Ordering;
use std::mem;
use std::str::FromStr;
use std::process::Command;
use tempfile;
use std::fs;
use crate::model::Adjustment;

pub mod mappings;

pub mod context_mapper;

use context_mapper::{ContextMapper, Coord2D};

pub mod plot_design;

use plot_design::*;

pub mod scale;

pub use scale::*;

pub use mappings::bar::*;

pub use mappings::scatter::*;

pub use mappings::line::*;

// pub use mappings::surface::*;

pub use mappings::text::*;

pub use mappings::area::*;

pub use mappings::interval::*;

mod text;

use text::FontData;

#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum GroupSplit {
    Unique,
    Vertical,
    Horizontal,
    Four,
    ThreeLeft,
    ThreeTop,
    ThreeRight,
    ThreeBottom
}

impl FromStr for GroupSplit {

    type Err = ();

    fn from_str(s : &str) -> Result<Self, ()> {
        match s {
            "Unique" | "unique" => Ok(Self::Unique),
            "Four" | "four" => Ok(Self::Four),
            "Horizontal" | "horizontal" => Ok(Self::Horizontal),
            "Vertical" | "vertical" => Ok(Self::Vertical),
            "ThreeLeft" | "threeleft"=> Ok(Self::ThreeLeft),
            "ThreeTop" | "threetop" => Ok(Self::ThreeTop),
            "ThreeRight" | "threeright" => Ok(Self::ThreeRight),
            "ThreeBottom" | "threebottom" => Ok(Self::ThreeBottom),
            _ => Err(())
        }
    }

}

fn n_plots_for_split(split : &GroupSplit) -> usize {
    match split {
        GroupSplit::Unique => 1,
        GroupSplit::Vertical | GroupSplit::Horizontal => 2,
        GroupSplit::ThreeLeft | GroupSplit::ThreeTop | GroupSplit::ThreeRight | GroupSplit::ThreeBottom => 3,
        GroupSplit::Four => 4,
    }
}

pub enum LayoutProperty {
    Width(i32),
    Height(i32),
    HorizontalRatio(f64),
    VerticalRatio(f64),
    Split(GroupSplit)
}

pub enum DesignProperty {
    BackgroundColor(String),
    GridColor(String),
    GridWidth(i32),
    Font(String)
}

pub enum ScaleProperty {
    Label(String),
    Min(f64),
    Max(f64),
    Log(bool),
    Invert(bool),
    GridOffset(i32),
    Precision(i32),
    NIntervals(i32),
    Adjustment(Adjustment)
}

pub enum LineProperty {
    Color(String),
    Width(f64),
    Dash(i32),
    X(Vec<f64>),
    Y(Vec<f64>)
}

pub enum ScatterProperty {
    Color(String),
    Radius(f64),
    X(Vec<f64>),
    Y(Vec<f64>)
}

pub enum TextProperty {
    Color(String),
    Font(String),
    X(Vec<f64>),
    Y(Vec<f64>),
    Text(Vec<String>)
}

pub enum IntervalProperty {
    Color(String),
    Width(f64),
    Dash(i32),
    Center(Vec<f64>),
    Lower(Vec<f64>),
    Upper(Vec<f64>),
    Limit(f64),
    Vertical(bool)
}

/// Must come with plot position and mapping position within plot
pub enum MappingProperty {
    Line(LineProperty),
    Scatter(ScatterProperty),
    Text(TextProperty),
    Interval(IntervalProperty)
}

pub enum ScaleMode {
    Horizontal,
    Vertical
}

/// Must come with plot position
pub enum PlotProperty {

    Scale(ScaleMode, ScaleProperty),

    // Carries mapping position and property
    Mapping(usize, MappingProperty)
}

pub enum GroupProperty {

    Layout(LayoutProperty),

    Design(DesignProperty),

    // Carries plot position and property
    Plot(usize, PlotProperty)
}

/// A Panel is a set of 1-4 plots with a given layout. Regions with arbitrary
/// number of plots can be built by splitting it according to some aspect
/// ratio and drawing multiple panels to it. To draw a 3x3 grid, for example,
/// use a 2x2 panel at the top-left, a 1x2 at the bottom, a 2x1 at the right
/// and a 1x1 at the bottom-right, such that the aspect ratios of the regions
/// are such that the different layouts do not matter for the final output.
/// TODO perhaps rename this 1-4 unit to "composition" and rename the set
/// of compositions as "Panel".
#[derive(Clone)]
pub struct Panel {

    design : PlotDesign,

    plots : Vec<Plot>,

    split : GroupSplit,

    h_ratio : f64,

    v_ratio : f64,

    dimensions : (usize, usize),

}

unsafe impl Send for Panel { }

unsafe impl Sync for Panel { }

unsafe impl Send for Plot { }

unsafe impl Sync for Plot { }

impl Default for Panel {

    fn default() -> Self {
        Self {
            design : Default::default(),
            plots : vec![Plot::default()],
            split : GroupSplit::Unique,
            h_ratio : 0.5,
            v_ratio : 0.5,
            dimensions : (800, 600),
            // doc : Document::new().unwrap()
        }
    }

}

impl fmt::Debug for Panel {

    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        write!(
            f,
            "{{ design : {:?}, plots : {:?}, split : {:?}, h_ratio : {:?}, v_ratio : {:?}, dimensions : {:?} }}",
            self.design,
            self.plots,
            self.split,
            self.h_ratio,
            self.v_ratio,
            self.dimensions
        )
    }

}

#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct FileError(String);

#[derive(Debug, Clone, Copy)]
pub enum Orientation {
    Horizontal,
    Vertical
}

fn update_dims_from_env(dims : &mut (usize, usize)) {
    if let Ok(var) = std::env::var("PLOT_DEFAULT_WIDTH") {
        dims.0 = var.parse().unwrap();
    }
    if let Ok(var) = std::env::var("PLOT_DEFAULT_HEIGHT") {
        dims.1 = var.parse().unwrap();
    }
}

impl Panel {

    pub fn get_dimensions(&self) -> (usize, usize) {
        self.dimensions
    }

    pub fn dimensions(mut self, w : u32, h : u32) -> Self {
        self.dimensions.0 = w as usize;
        self.dimensions.1 = h as usize;
        self.adjust_scales();
        self
    }

    pub fn single(p1 : Plot) -> Self {
        let mut panel = Self::default();
        update_dims_from_env(&mut panel.dimensions);
        panel.dimensions = (p1.mapper.w as usize, p1.mapper.h as usize);
        panel.plots[0] = p1;
        panel
    }

    pub fn pair(orientation : Orientation, p1 : Plot, p2 : Plot) -> Self {
        let mut group = Self::default();
        group.plots.push(Plot::default());
        group.split = match orientation {
            Orientation::Vertical => GroupSplit::Vertical,
            Orientation::Horizontal => GroupSplit::Horizontal
        };
        group.plots[0] = p1;
        group.plots[1] = p2;
        update_dims_from_env(&mut group.dimensions);
        group
    }

    pub fn update(&mut self, prop : GroupProperty) {
        match prop {
            GroupProperty::Layout(layout) => {
                match layout {
                    LayoutProperty::Split(split) => { self.split = split },
                    LayoutProperty::VerticalRatio(vr) => { self.v_ratio = vr },
                    LayoutProperty::HorizontalRatio(hr) => { self.h_ratio = hr },
                    LayoutProperty::Width(w) => { self.dimensions.0 = w as usize },
                    LayoutProperty::Height(h) => { self.dimensions.1 = h as usize },
                }
            },
            GroupProperty::Design(design) => {
                match design {
                    DesignProperty::BackgroundColor(color) => { self.design.bg_color = color.parse().unwrap() },
                    DesignProperty::GridColor(color) => { self.design.grid_color = color.parse().unwrap() },
                    DesignProperty::GridWidth(w) => { self.design.grid_width = w },
                    DesignProperty::Font(f) => { self.design.font = FontData::new_from_string(&f[..]) }
                }
            },
            GroupProperty::Plot(ix, prop) => {
                self.plots[ix].update(prop);
            }
        }
    }

    pub fn to_json(&self) -> String {
        unimplemented!()
    }

    /*pub fn update_panel_directly(&mut self, prop : &str, val : &str) {
        match prop {
            "split" => { self.split = GroupSplit::from_str(val).unwrap() },
            "vertical_ratio" => { self.v_ratio = f64::from_str(val).unwrap() },
            "horizontal_ratio" => { self.h_ratio = f64::from_str(val).unwrap() },
            _ => panic!("Unrecognized panel property")
        }
    }*/

    pub fn new() -> Self {
        Default::default()
    }

    pub fn new_from_single(plot : crate::model::Plot) -> Result<Self, String> {
        let design_json = plot.design.clone().unwrap_or_default();
        let layout_json = plot.layout.clone().unwrap_or_default();
        let design = PlotDesign::new_from_json(design_json)
            .map_err(|e| format!("Error parsing design = {}", e))?;
        let area = Plot::new_from_model(plot)
            .map_err(|e| format!("Error parsing area from JSON definition = {}", e) )?;
        Ok(Self {
            design,
            plots : vec![area],
            split : GroupSplit::Unique,
            h_ratio : layout_json.hratio,
            v_ratio : layout_json.vratio,
            dimensions : (layout_json.width as usize, layout_json.height as usize),
        })
    }

    pub fn new_from_model(mut panel_def : crate::model::Panel) -> Result<Self, String> {
        let mut panel : Panel = Default::default();
        panel.plots.clear();

        if panel_def.plots.len() == 1 {
            panel.split = GroupSplit::Unique;
        } else {
            if panel_def.plots.len() == 2 {
                panel.split = GroupSplit::Horizontal;
            } else {
                if panel_def.plots.len() == 3 {
                    panel.split = GroupSplit::ThreeTop;
                } else {
                    if panel_def.plots.len() == 4 {
                        panel.split = GroupSplit::Four;
                    } else {
                        return Err(format!("Invalid number of plots informed"));
                    }
                }
            }
        }

        // Always ignore the layout/design of individual plot elements
        // when they are inside a panel definition. The individual layout/design
        // for separate plots only apply when they are a single element with an
        // implicit panel definition.
        for mut plot_def in panel_def.plots.drain(..) {

            // Just overwrite them if set at the panel level.
            if plot_def.design.is_some() {
                plot_def.design = None;

            }
            if plot_def.layout.is_some() {
                plot_def.layout = None;
            }

            let plot = Plot::new_from_model(plot_def)
                .map_err(|e| format!("Error parsing area from JSON definition = {}", e) )?;
            panel.plots.push(plot);
        }

        if let Some(design) = panel_def.design {
            panel.design = PlotDesign::new_from_json(design)
                .map_err(|e| format!("{}", e) )?;
        }

        if let Some(layout) = panel_def.layout {
            panel.dimensions = (layout.width as usize, layout.height as usize);
            panel.h_ratio = layout.hratio;
            panel.v_ratio = layout.vratio;

            if let Some(split) = &layout.split {
                let split = GroupSplit::from_str(split)
                    .map_err(|_| format!("Invalid split: {}", split))?;
                if n_plots_for_split(&split) == panel.plots.len() {
                    panel.split = split;
                } else {
                    // Do not set user-defined split property in case it was miss-specified, use
                    // the default for the given number of plots informed.
                    let n_plots = panel.plots.len();
                    panel.split = match n_plots  {
                        1 => GroupSplit::Unique,
                        2 => GroupSplit::Horizontal,
                        3 => GroupSplit::ThreeTop,
                        4 => GroupSplit::Four,
                        _ => return Err(String::from("More than four plots found"))
                    };
                }
            }
        }
        assert!(panel.plots.len() == n_plots_for_split(&panel.split), "N plots = {}; split = {:?}", panel.plots.len(), panel.split);
        Ok(panel)
    }

    pub fn new_from_json(json : &str) -> Result<Self, String> {
        let res_panel : Result<crate::model::Panel, _> = serde_json::from_str(json);
        match res_panel {
            Ok(panel_def) => {
                Self::new_from_model(panel_def)
            },
            Err(_e) => {
                // println!("Error parsing panel = {}", e);
                // println!("{}", json);
                let plot : crate::model::Plot = serde_json::from_str(json)
                    .map_err(|e| format!("Error parsing plot = {}", e) )?;
                Self::new_from_single(plot)
            }
        }
    }

    pub fn adjust_scales(&mut self) {
        self.plots.iter_mut().for_each(|pl| pl.adjust_scales() );
    }

    pub fn clear_all_data(&mut self) {
        for area in self.plots.iter_mut() {
            area.clear_all_data();
        }
    }

    pub fn png(&mut self) -> Result<Vec<u8>, Box<dyn Error>> {
        let surf = ImageSurface::create(
            Format::ARgb32,
            self.dimensions.0 as i32,
            self.dimensions.1 as i32,
        )?;
        let ctx = Context::new(&surf).unwrap();
        self.draw_to_context(&ctx, 0, 0, self.dimensions.0 as i32, self.dimensions.1 as i32)?;
        let mut buf = Vec::new();
        surf.write_to_png(&mut buf)?;
        Ok(buf)
    }

    pub fn html_img_tag(&mut self) -> Result<String, Box<dyn Error>> {
        let png = self.png()?;
        Ok(format!("<img src='data:image/png;base64,{}' />", base64::encode(png)))
    }

    pub fn svg(&mut self) -> Result<String, Box<dyn Error>> {
        let svg_buf : Vec<u8> = Vec::new();
        let surf = SvgSurface::for_stream(
            self.dimensions.0 as f64,
            self.dimensions.1 as f64,
            svg_buf
        ).map_err(|e| format!("Error creating SVG surface: {}", e) )?;

        let ctx = Context::new(&surf).unwrap();
        self.draw_to_context(&ctx, 0, 0, self.dimensions.0 as i32, self.dimensions.1 as i32)?;

        let stream = surf.finish_output_stream().unwrap();

        /*
        Requires 14.0
        match surf.status() {
            Ok(_) => {

            },
            Err(e) => {
                panic!("Surface error: {}", e);
            }
        }*/
        surf.flush();

        Ok(String::from_utf8(stream.downcast_ref::<Vec<u8>>().unwrap().clone())?)
    }

    pub fn show_with_eog(&mut self) -> Result<(), Box<dyn Error>> {
        self.show_with_app("eog")
    }

    /// Shows plot by saving it at a tempfile and opening with the
    /// informed application, which is assumed to receive the tempfile
    /// path as first argument.
    pub fn show_with_app(&mut self, app : &str) -> Result<(), Box<dyn Error>> {
        let mut tf = tempfile::NamedTempFile::new()?;
        let png = self.png()?;
        tf.write_all(&png)?;
        let path = tf.path();
        let new_path = format!("{}.png", path.to_str().unwrap());
        fs::rename(path, new_path.clone()).unwrap();
        Command::new(app)
            .args(&[&new_path])
            .output()?;
        Ok(())
    }

    pub fn draw_to_file(&mut self, path : &str) -> Result<(), Box<dyn Error>> {
        // TODO Error creating SVG surface: "error while writing to output stream

        let path = Path::new(path);
        if !path.parent().map(|par| par.exists() ).unwrap_or(false) {
            Err(FileError(format!("Parent directory for image path {} does not exists", path.to_str().unwrap())))?;
        }

        match path.extension().and_then(|e| e.to_str() ) {
            Some("svg") => {
                let surf = SvgSurface::new(
                    self.dimensions.0 as f64,
                    self.dimensions.1 as f64,
                    Some(path)
                ).map_err(|e| FileError(format!("Error creating SVG surface: {}", e) ))?;
                let ctx = Context::new(&surf).unwrap();
                self.draw_to_context(&ctx, 0, 0, self.dimensions.0 as i32, self.dimensions.1 as i32)?;
            },
            Some("png") => {
                let surf = ImageSurface::create(
                    Format::ARgb32,
                    self.dimensions.0 as i32,
                    self.dimensions.1 as i32,
                ).map_err(|e| FileError(format!("Error creating PNG image surface: {}", e) ))?;
                let ctx = Context::new(&surf).unwrap();
                // ctx.scale(3.0, 3.0);
                self.draw_to_context(&ctx, 0, 0, self.dimensions.0 as i32, self.dimensions.1 as i32)?;
                let mut f = File::create(path).map_err(|e| FileError(format!("Unable to open PNG file:{}", e)))?;
                surf.write_to_png(&mut f)
                    .map_err(|e| format!("Error writing content to png: {}", e) )?;
            },
            Some("eps") => {
                let surf = PsSurface::new(
                    self.dimensions.0 as f64,
                    self.dimensions.1 as f64,
                    path
                ).map_err(|e| FileError(format!("Error creating Postscript surface: {}", e) ))?;
                surf.set_eps(true);
                let ctx = Context::new(&surf).unwrap();
                self.draw_to_context(&ctx, 0, 0, self.dimensions.0 as i32, self.dimensions.1 as i32)?;
            },
            Some(other) => {
                Err(FileError(format!("Invalid image export extension: {}", other)))?;
            },
            None => {
                Err(FileError(format!("No valid extension informed for image export file")))?;
            }
        };
        Ok(())
    }

    pub fn size(&self) -> usize {
        self.plots.len()
    }

    /// Draws the current Plot definition to a Cairo context.
    /// Used internally by PlotView to draw to the context
    /// of a gtk::DrawingArea. Users can also retrive the context
    /// from cairo::ImageSurface::create() to plot directly to
    /// SVG/PNG/PDF files.
    pub fn draw_to_context(
        &mut self,
        ctx : &Context,
        x : i32,
        y : i32,
        w : i32,
        h : i32
    ) -> Result<(), Box<dyn Error>> {
        let top_left = (0.05, 0.05);
        let top_right = (w as f64 * self.h_ratio, 0.05);
        let bottom_left = (0.05, h as f64 * self.v_ratio);
        let bottom_right = (w as f64 * self.h_ratio, h as f64 * self.v_ratio);

        // The plot context mapper is re-set here, so plot must be mutably-borrowed
        for (i, plot) in self.plots.iter_mut().enumerate() {
            let origin_offset = match (&self.split, i) {
                (GroupSplit::Horizontal, 1) => top_right,
                (GroupSplit::Vertical, 1) => bottom_left,
                (GroupSplit::Four, 1) => top_right,
                (GroupSplit::Four, 2) => bottom_left,
                (GroupSplit::Four, 3) => bottom_right,
                (GroupSplit::ThreeLeft, 1) => top_right,
                (GroupSplit::ThreeLeft, 2) => bottom_right,
                (GroupSplit::ThreeTop, 1) => bottom_left,
                (GroupSplit::ThreeTop, 2) => bottom_right,
                (GroupSplit::ThreeRight, 0) => top_left,
                (GroupSplit::ThreeRight, 1) => top_right,
                (GroupSplit::ThreeRight, 2) => bottom_left,
                (GroupSplit::ThreeBottom, 0) => top_left,
                (GroupSplit::ThreeBottom, 1) => top_right,
                (GroupSplit::ThreeBottom, 2) => bottom_left,
                _ => top_left
            };

            let h_full_v = (1., self.v_ratio);
            let h_full_v_compl = (1., 1. - self.v_ratio);
            let h_v_full = (self.h_ratio, 1.);
            let h_compl_v_full = (1. - self.h_ratio, 1.);
            let h_compl_v = (1. - self.h_ratio, self.v_ratio);
            let h_v_compl = (self.h_ratio, 1. - self.v_ratio);
            let diag = (self.h_ratio, self.v_ratio);
            let diag_compl = (1. - self.h_ratio, 1. - self.v_ratio);
            let scale_factor = match (&self.split, i) {
                (GroupSplit::Horizontal, 0) => h_v_full,
                (GroupSplit::Horizontal, 1) => h_compl_v_full,
                (GroupSplit::Vertical, 0) => h_full_v,
                (GroupSplit::Vertical, 1) => h_full_v_compl,
                (GroupSplit::Four, 0) => diag,
                (GroupSplit::Four, 1) => h_compl_v,
                (GroupSplit::Four, 2) => h_v_compl,
                (GroupSplit::Four, 3) => diag_compl,
                (GroupSplit::ThreeLeft, 0) => h_v_full,
                (GroupSplit::ThreeLeft, 1) => h_compl_v,
                (GroupSplit::ThreeLeft, 2) => diag_compl,
                (GroupSplit::ThreeTop, 0) => h_full_v,
                (GroupSplit::ThreeTop, 1) => h_v_compl,
                (GroupSplit::ThreeTop, 2) => diag_compl,
                (GroupSplit::ThreeRight, 0) => diag,
                (GroupSplit::ThreeRight, 1) => h_compl_v_full,
                (GroupSplit::ThreeRight, 2) => h_v_compl,
                (GroupSplit::ThreeBottom, 0) => diag,
                (GroupSplit::ThreeBottom, 1) => h_compl_v,
                (GroupSplit::ThreeBottom, 2) => h_full_v_compl,
                _ => (1., 1.)
            };
            let origin = (x as f64 + origin_offset.0, y as f64 + origin_offset.1);
            let size = ((w as f64 * scale_factor.0) as i32, (h as f64 * scale_factor.1) as i32);
            ctx.save()?;
            ctx.translate(origin.0, origin.1);
            plot.draw_plot(&ctx, &self.design, size.0, size.1)?;
            ctx.restore()?;
        }
        Ok(())
    }

    pub fn update_mapping(&mut self, ix : usize, id : &str, data : &Vec<Vec<f64>>) -> Result<(), Box<dyn Error>> {
        self.plots[ix].update_mapping(id, data)
    }

    pub fn update_mapping_text(&mut self, ix : usize, id : &str, text : &Vec<String>) -> Result<(), Box<dyn Error>> {
        self.plots[ix].update_mapping_text(id, text)
    }

    pub fn update_mapping_columns(&mut self, ix : usize, id : &str, cols : Vec<String>) -> Result<(), Box<dyn Error>> {
        self.plots[ix].update_mapping_columns(id, cols)
    }

    pub fn update_source(&mut self, ix : usize, id : &str, source : String) -> Result<(), Box<dyn Error>> {
        self.plots[ix].update_source(id, source)
    }

    pub fn ordered_col_names(&self, ix : usize, id : &str) -> Vec<(String, String)> {
        self.plots[ix].mapping_column_names(id)
    }

    pub fn scale_info(&self, ix : usize, scale : &str) -> HashMap<String, String> {
        self.plots[ix].scale_info(scale)
    }

    pub fn design_info(&self) -> HashMap<String, String> {
        self.design.description()
    }

    pub fn mapping_info(&self, ix : usize) -> Vec<(String, String, HashMap<String,String>)> {
        self.plots[ix].mapping_info()
    }

    pub fn group_split(&self) -> GroupSplit {
        self.split.clone()
    }

    pub fn aspect_ratio(&self) -> (f64, f64) {
        (self.h_ratio, self.v_ratio)
    }

    pub fn data_limits(&self, ix : usize) -> Option<((f64, f64), (f64, f64))> {
        self.plots[ix].max_data_limits()
    }

    pub fn set_aspect_ratio(&mut self, horiz : Option<f64>, vert : Option<f64>) {
        if let Some(horiz) = horiz {
            self.h_ratio = horiz;
        }
        if let Some(vert) = vert {
            self.v_ratio = vert;
        }
    }

    // Number of mappings, for each plot
    pub fn n_mappings(&self) -> Vec<usize> {
        self.plots.iter().map(|p| p.mappings.len() ).collect()
    }

    // Number of plots
    pub fn n_plots(&self) -> usize {
        self.plots.len()
    }

    pub fn view_all_sources(&self) -> Vec<String> {
        self.plots.iter().map(|plot| plot.view_sources() ).flatten().collect()
    }

    pub fn view_grouped_sources(&self) -> Option<String> {
        let sources = self.view_all_sources();
        let mut sql_text = String::new();
        for source in sources {
            sql_text += &format!("\n{}\n", source)[..];
        }
        if !sql_text.is_empty() {
            Some(sql_text)
        } else {
            None
        }
    }

    pub fn view_dimensions(&self) -> (u32, u32) {
        (self.dimensions.0 as u32, self.dimensions.1 as u32)
    }

}

#[derive(Clone, Debug)]
pub struct Plot {
    mappings : Vec<Box<dyn Mapping>>,
    mapper : ContextMapper,
    x : Scale,
    y : Scale,
}

impl Default for Plot {
    fn default() -> Self {
        let mappings = Vec::new();
        let mapper : ContextMapper = Default::default();
        let x : Scale = Default::default();
        let y : Scale = Default::default();
        Plot{ mappings, mapper, x, y, }
    }
}

#[derive(Debug)]
pub enum PlotError {
    InvalidData(&'static str),
    OutOfBounds(&'static str),
    Other(&'static str),
    Parsing
}

impl PlotError {
    pub fn new() -> Self {
        Self::Other("Unknown error")
    }
}

impl Display for PlotError {

    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Self::InvalidData(msg) => { write!(f, "{}", msg) },
            Self::OutOfBounds(msg) => { write!(f, "{}", msg) },
            Self::Other(msg) => { write!(f, "{}", msg) }
            Self::Parsing => { write!(f, "Parsing error") }
        }
    }

}

impl error::Error for PlotError {

}

impl Plot {

    // This only makes sense if we have a single plot that will be promptly
    // wrappen into a panel for drawing only. All dimensions are overwrritten
    // when we wrap multiple plots into a planel according to the plot split logic
    // (a step done at the drawing stage).
    pub fn dimensions(mut self, w : u32, h : u32) -> Self {
        self.mapper.update_dimensions(w as i32, h as i32);
        self.adjust_scales();
        self
    }

    pub fn wrap(&self) -> Panel {
        Panel::single(self.clone())
    }

    pub fn svg(&self) -> String {
        self.wrap().svg().unwrap()
    }

    pub fn draw_to_file(&self, path : &str) -> Result<(), Box<dyn Error>> {
        self.wrap().draw_to_file(path)
    }

    pub fn scale_x(mut self, scale : Scale) -> Self {
        self.x = scale;
        self.adjust_scales();
        self
    }

    pub fn scale_y(mut self, scale : Scale) -> Self {
        self.y = scale;
        self.adjust_scales();
        self
    }

    pub fn draw(mut self, map : impl Mapping + 'static) -> Self {
        self.mappings.push(Box::new(map) as Box<dyn Mapping>);
        self.adjust_scales();
        self
    }

    pub fn update(&mut self, prop : PlotProperty) {
        match prop {
            PlotProperty::Scale(mode, prop) => {
                match mode {
                    ScaleMode::Horizontal => self.x.update(prop),
                    ScaleMode::Vertical => self.y.update(prop)
                }
            },
            PlotProperty::Mapping(ix, m) => {
                if !self.mappings[ix].update(m) {
                    panic!("Could not update mapping");
                }
            }
        }
        self.adjust_scales();
    }

    pub fn adjust_scales(&mut self) {

        if let Some(((new_xmin, mut new_xmax), (new_ymin, mut new_ymax))) = self.max_data_limits() {

            let min_x_spacing = self.x.n_intervals as f64 * std::f64::EPSILON;
            let min_y_spacing = self.y.n_intervals as f64 * std::f64::EPSILON;

            // Plots with extension zero are not valid - We hard-set the smallest possible difference,
            // or else the scale drawing will be messed up. This might happen if the user provide a single
            // data point for the mapping, in which case xmax == xmin. Each grid point must be distant by at least EPS.
            if (new_xmax - new_xmin).abs() < min_x_spacing {
                new_xmax = new_xmin + min_x_spacing;
            }
            if (new_ymax - new_ymin).abs() < min_y_spacing {
                new_ymax = new_ymin + min_y_spacing;
            }

            let (x_adj, y_adj) = (self.x.adj, self.y.adj);
            scale::adjust_segment(&mut self.x, x_adj, new_xmin, new_xmax);
            scale::adjust_segment(&mut self.y, y_adj, new_ymin, new_ymax);
            self.mapper.update_data_extensions(self.x.from, self.x.to, self.y.from, self.y.to);

        } else {
            // println!("Could not retrieve data limits");
        }
    }

    pub fn new_from_json(json : &str) -> Result<Plot, Box<dyn Error>> {
        let plot : crate::model::Plot = serde_json::from_str(&json)?;
        Self::new_from_model(plot)
    }

    pub fn new_from_model(mut rep : crate::model::Plot) -> Result<Plot, Box<dyn Error>> {

        let mut mappings = Vec::new();

        for mapping in rep.mappings.iter_mut() {
            mappings.push(mappings::new_from_json(mem::take(mapping))?);
        }

        let x = Scale::new_from_json(rep.x.clone())?;
        let y = Scale::new_from_json(rep.y.clone())?;

        let mapper = ContextMapper::new(
            x.from,
            x.to,
            y.from,
            y.to,
            x.log,
            y.log,
            x.invert,
            y.invert
        );

        let mut area = Self {
            mappings,
            mapper,
            x,
            y,
        };
        area.adjust_scales();

        // We do not load any design definitions here, but rather at Panel::new(),
        // since the design might be defined at Panel-level.
        Ok(area)
    }

    pub fn new() -> Self {
        let mut pl : Plot = Default::default();
        if let Ok(var) = std::env::var("PLOT_DEFAULT_WIDTH") {
            pl.mapper.w = var.parse().unwrap();
        }
        if let Ok(var) = std::env::var("PLOT_DEFAULT_HEIGHT") {
            pl.mapper.h = var.parse().unwrap();
        }
        pl
    }

    fn draw_plot(&mut self, ctx: &Context, design : &PlotDesign, w : i32, h : i32) -> Result<(), Box<dyn Error>> {
        self.mapper.update_dimensions(w, h);
        self.draw_background(ctx, design)?;
        self.draw_grid(ctx, design)?;
        for mapping in self.mappings.iter() {
            mapping.draw(&self.mapper, &ctx)?;
        }
        Ok(())
    }

    pub fn max_data_limits(&self) -> Option<((f64, f64), (f64, f64))> {
        let mut x_lims = Vec::new();
        let mut y_lims = Vec::new();
        for (xl, yl) in self.mappings.iter().filter_map(|m| m.data_limits() ) {
            x_lims.push(xl);
            y_lims.push(yl);
        }
        let min_x = x_lims.iter().min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal) )?.0;
        let max_x = x_lims.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal) )?.1;
        let min_y = y_lims.iter().min_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(Ordering::Equal) )?.0;
        let max_y = y_lims.iter().max_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(Ordering::Equal) )?.1;
        Some(((min_x, max_x), (min_y, max_y)))
    }

    /*fn read_grid_segment(
        &self,
        props : HashMap<String, String>
    ) -> Result<Scale, Box<dyn Error>> {
        let from : f64 = props.get("from").unwrap().parse()?;
        let to : f64 = props["to"].parse()?;
        let nint : i32 = props["n_intervals"].parse()?;
        let offset : i32 = props["grid_offset"].parse()?;
        let invert : bool = props["invert"].parse()?;
        let log : bool = props["log_scaling"].parse()?;
        let precision : i32 = props["precision"].parse()?;
        let label = props["label"].clone();
        Ok( Scale::new_full(
            label, precision, from, to, nint, log, invert, offset, Adjustment::Off) )
    }*/

    fn accomodate_dimension(
        &mut self,
        data : &[f64],
        old_min : f64,
        old_max : f64,
        _dim_name : &str
    ) {
        let new_min = data.iter().fold(old_min, |min, el| {
            if *el < min {
                *el
            } else {
                min
            }
        });
        let new_max = data.iter().fold(old_max, |max, el| {
            if *el > max {
                *el
            } else {
                max
            }
        });
        if new_min < old_min {
            /*let ans = self.update_layout(
                &format!("object[@name='{}']/property[@name='from']", dim_name)[..],
                &new_min.to_string()
            );
            if let Err(e) = ans {
                println!("{}", e);
            }*/
        }
        if new_max > old_max {
            /*let ans = self.update_layout(
                &format!("object[@name='{}']/property[@name='to']", dim_name)[..],
                &new_max.to_string()
            );
            if let Err(e) = ans {
                println!("{}", e);
            }*/
        }
    }

    pub fn update_mapping(
        &mut self,
        id : &str,
        data : &Vec<Vec<f64>>
    ) -> Result<(), Box<dyn Error>> {
        if data.len() < 1 {
            return Err(Box::new(PlotError::InvalidData("Invalid data")))
        }
        let (xmin, xmax, ymin, ymax) = self.mapper.data_extensions();
        if data.len() == 1 {
            self.accomodate_dimension(&data[0][..], ymin, ymax, "y");
        } else {
            self.accomodate_dimension(&data[0][..], xmin, xmax, "x");
            self.accomodate_dimension(&data[1][..], ymin, ymax, "y");
        }
        if let Some(mapping) = self.mappings.get_mut(id.parse::<usize>().unwrap()) {
            mapping.update_data(data.clone());
            Ok(())
        } else {
            Err(Box::new(std::io::Error::new(
                ErrorKind::Other,
                "Cannot recover mapping "
            )))
        }
    }

    /*pub fn remove_mapping(&mut self, id : &str) -> Result<(Box<dyn Mapping>, Node), String> {
        let n = self.mappings.len();
        let pos = id.parse::<usize>().map_err(|e| format!("Node id is not an integer: {}", id))?;
        //let mut root = self.doc.get_root_element().expect("No root at remove");
        let xpath = String::from("object[@index='") + id +  "']";
        // println!("Removing mapping at path: {}", xpath);
        let mut nodes = self.node.findnodes(&xpath[..])
            .map_err(|_| format!("No node with informed id: {}", id))?;
        let node = nodes.get_mut(0)
            .ok_or(format!("No first node with informed id: {}", id))?;
        node.unlink_node();
        let mapping = self.mappings.remove(pos);
        for i in (pos + 1)..n {
            let next_xpath = String::from("object[@index='") + &i.to_string()[..] +  "']";
            let mut nodes = self.node.findnodes(&next_xpath[..])
                .map_err(|e| format!("No next node with informed id: {}", i))?;

            // TODO error here at node removal
            let next_node = nodes.get_mut(0).ok_or(format!("No first node with informed id: {}", id))?;
            next_node.set_attribute("index", &((i - 1).to_string())[..])
                .map_err(|e| format!("Node {} missing index property", i));
        }
        self.reload_mappings()?;
        // for m in self.mappings.iter() {
        //    println!("Current remaining mappings: {:?}", m.mapping_type());
        // }
        // println!("Mapping {} removed successfully", id);
        Ok((mapping, node.clone()))
    }*/

    pub fn update_mapping_text(
        &mut self,
        id : &str,
        text : &Vec<String>
    ) -> Result<(), Box<dyn Error>> {
        if let Some(mapping) = self.mappings.get_mut(id.parse::<usize>().unwrap()) {
            mapping.update_extra_data(vec![text.clone()]);
            Ok(())
        } else {
            Err(Box::new(std::io::Error::new(
                ErrorKind::Other,
                "Unable to update text mapping position"
            )))
        }

        /*
            // println!("{}, {:?}", mapping.mapping_type(), mapping.properties());
            {
            // let mapping = mapping as &mut dyn Any;
            // println!("{:?}", (mapping as &mut dyn Any).type_id());
            match (mapping as &mut dyn Any).downcast_mut::<TextMapping>() {
                Some(m) => {
                    m.set_text_data(&text);
                    Ok(())
                },
                None => {
                    Err(Box::new(std::io::Error::new(
                        ErrorKind::Other,
                        "Informed mapping does not support text update"
                    )))
                }
            }
            }
        } else {
            Err(Box::new(std::io::Error::new(
                ErrorKind::Other, "Cannot recover mapping")))
        }*/
    }

    /*/* Given a resolvable full path to a property, update it. */
    pub fn update_layout(&mut self, property : &str, value : &str) -> Result<(), String> {
        // let root = self.doc.get_root_element().expect("No root");
        // println!("{} : {}", property, value);
        if property.is_empty() || value.is_empty() {
            return Err(format!("Informed empty property!"));
        }

        match self.node.findnodes(&property) {
            Ok(mut props) => {
                if let Some(p) = props.iter_mut().next() {
                    if let Err(e) = p.set_content(&value) {
                        println!("Error setting node content: {}", e);
                    }
                    // println!("new node content: {:?}, {:?}", p.get_property("name"), p.get_content());
                    // println!("new node at root: {:?}", self.node.get_content());
                    let parent = p.get_parent().unwrap();
                    match parent.get_attribute("class") {
                        Some(ref class) if class == "mapping" => {
                            if let Some(index) = parent.get_attribute("index") {
                                if let Some(m) = self.mappings.get_mut(index.parse::<usize>().unwrap()) {
                                    m.update_layout( &parent )?;
                                } else {
                                    println!("No mapping at {} available", index);
                                }
                            } else {
                                println!("Invalid mapping index");
                            }
                        },
                        Some(ref class) if class != "mapping" => {
                            //println!(
                            //    "Updated property: {:?}",
                            //    self.node.findnodes(property).unwrap().iter().next().unwrap().get_content()
                            //);
                            if let Err(e) = self.reload_layout_node() {
                                println!("Could not apply property {} ({})", property, e);
                            }
                            //println!(
                            //    "Updated property after reload: {:?}",
                            //    self.node.findnodes(property).unwrap().iter().next().unwrap().get_content()
                            //);
                        },
                        _ => {
                            println!("Layout item missing class attribute.");
                        }
                    }
                } else {
                    println!("{}", "Property ".to_owned() + property + " not found!");
                }
            },
            Err(e) => {
                println!("No property {} found at node {:?} ({:?})", property, self.node, e);
            }
        }
        Ok(())
    }*/

    pub fn clear_all_data(&mut self) {
        for m in self.mappings.iter_mut() {
            let mut empty_data : Vec<Vec<f64>> = Vec::new();
            match &m.mapping_type()[..] {
                "line" => {
                    empty_data.push(Vec::new());
                    empty_data.push(Vec::new());
                },
                "scatter" => {
                    empty_data.push(Vec::new());
                    empty_data.push(Vec::new());
                },
                "bar" => {
                    empty_data.push(Vec::new());
                },
                "area" => {
                    empty_data.push(Vec::new());
                    empty_data.push(Vec::new());
                    empty_data.push(Vec::new());
                },
                "text" => {
                    //TODO clear text
                    empty_data.push(Vec::new());
                    empty_data.push(Vec::new());
                    match (m as &mut dyn Any).downcast_mut::<TextMapping>() {
                        Some(m) => {
                            m.set_text_data(&Vec::new());
                        },
                        _ => { println!("Could not downcast to text when clearing its data"); }
                    }
                },
                "surface" => {
                    empty_data.push(Vec::new());
                    empty_data.push(Vec::new());
                    empty_data.push(Vec::new());
                },
                _ => {
                    println!("Invalid mapping type");
                    return;
                }
            }
            m.update_data(empty_data);
        }
    }

    fn draw_background(&self, ctx : &Context, design : &PlotDesign) -> Result<(), Box<dyn Error>> {
        ctx.save()?;
        ctx.set_line_width(0.0);
        ctx.set_source_rgb(
            design.bg_color.red().into(),
            design.bg_color.green().into(),
            design.bg_color.blue().into()
        );
        ctx.rectangle(
            0.1*(self.mapper.w as f64), 0.1*(self.mapper.h as f64),
            0.8*(self.mapper.w as f64), 0.8*(self.mapper.h as f64));
        ctx.fill()?;
        ctx.restore()?;
        Ok(())
    }

    fn draw_grid_line(
        &self,
        ctx : &Context,
        design : &PlotDesign,
        from : Coord2D,
        to : Coord2D
    ) -> Result<(), Box<dyn Error>> {
        ctx.save()?;
        ctx.set_source_rgb(
            design.grid_color.red().into(),
            design.grid_color.green().into(),
            design.grid_color.blue().into()
        );
        ctx.move_to(from.x, from.y);
        ctx.line_to(to.x, to.y);
        ctx.stroke()?;

        //ctx.set_source_rgb(0.2666, 0.2666, 0.2666);
        //ctx.move_to(from.x + label_off_x, from.y + label_off_y);
        //ctx.show_text(&label);
        //self.draw_centered_label(ctx, &label, Coord2D::new(from.x + label_off_x, from.y + label_off_y), false);
        //self.draw_grid_value(ctx, &label)
        ctx.restore()?;
        Ok(())
    }

    /// Since the y value is always centered, this function accepts the option
    /// to center the x value (true for the x labels; false for the y labels).
    fn draw_grid_value(
        &self,
        ctx : &Context,
        design : &PlotDesign,
        value : &str,
        pos : Coord2D,
        center_x : bool,
        ext_off_x : f64,
        ext_off_y : f64
    ) -> Result<(), Box<dyn Error>> {
        ctx.set_source_rgb(0.2666, 0.2666, 0.2666);
        text::draw_label(
            &design.font.sf,
            ctx,
            &value[..],
            pos,
            false,
            (center_x, true),
            Some(ext_off_x),
            Some(ext_off_y)
        )?;
        Ok(())
    }

    pub fn steps_to_labels(
        steps : &[f64],
        precision : usize
    ) -> Vec<String> {
        steps.iter()
            .map(|s| format!("{:.*}", precision, s))
            .collect()
    }

    fn get_max_extent(
        &self,
        design : &PlotDesign,
        labels : &Vec<String>
    ) -> f64 {
        labels.iter()
            .map(|l| design.font.sf.text_extents(&l[..]).x_advance)
            .fold(0.0, |m, f| f64::max(m,f))
    }

    /*fn shift_coord_by_max_extent(
        base_coord : Coord2D,
        max_extent : f64
    ) -> Coord2D {

            .collect()
    }*/

    fn draw_grid(&self, ctx : &Context, design : &PlotDesign) -> Result<(), Box<dyn Error>> {
        ctx.save()?;
        ctx.set_line_width(design.grid_width as f64);
        design.font.set_font_into_context(&ctx);
        let mut x_labels = Plot::steps_to_labels(
            &self.x.steps[..],
            self.x.precision as usize
        );
        if self.mapper.xinv {
            x_labels.reverse();
        }
        for (x, x_label) in self.x.steps.iter().zip(x_labels.iter()) {
            let from = match (self.mapper.xinv, self.mapper.yinv) {
                (false, false) => self.mapper.map(*x, self.mapper.ymin),
                (false, true) => self.mapper.map(*x, self.mapper.ymax),
                (true, false) => self.mapper.map(self.mapper.xmin + self.mapper.xmax - *x, self.mapper.ymin),
                (true, true) => self.mapper.map(self.mapper.xmin + self.mapper.xmax - *x, self.mapper.ymax)
            };
            let to = match (self.mapper.xinv, self.mapper.yinv) {
                (false, false) => self.mapper.map(*x, self.mapper.ymax),
                (false, true) => self.mapper.map(*x, self.mapper.ymin),
                (true, false) =>  self.mapper.map(self.mapper.xmin + self.mapper.xmax - *x, self.mapper.ymax),
                (true, true) => self.mapper.map(self.mapper.xmin + self.mapper.xmax - *x, self.mapper.ymin)
            };
            // let from = self.mapper.map(*x, self.mapper.ymin);
            // let to = match self.mapper.self.mapper.map(*x, self.mapper.ymax);
            // println!("{:?}, {:?}, {:?}", x, from, to);
            self.draw_grid_line(ctx, design, from, to)?;
            self.draw_grid_value(ctx, design, x_label, from, true, 0.0, 1.5)?;
        }

        let mut y_labels = Plot::steps_to_labels(
            &self.y.steps[..],
            self.y.precision as usize
        );
        if self.mapper.yinv {
            y_labels.reverse();
        }
        let max_extent = self.get_max_extent(design, &y_labels);
        for (y, y_label) in self.y.steps.iter().zip(y_labels.iter()) {
            let mut from = match (self.mapper.xinv, self.mapper.yinv) {
                (false, false) => self.mapper.map(self.mapper.xmin, *y),
                (false, true) => self.mapper.map(self.mapper.xmin, self.mapper.ymin + self.mapper.ymax - *y),
                (true, false) => self.mapper.map(self.mapper.xmax, *y),
                (true, true) => self.mapper.map(self.mapper.xmax, self.mapper.ymin + self.mapper.ymax - *y)
            };
            let to = match (self.mapper.xinv, self.mapper.yinv) {
                (false, false) => self.mapper.map(self.mapper.xmax, *y),
                (false, true) => self.mapper.map(self.mapper.xmax, self.mapper.ymin + self.mapper.ymax - *y),
                (true, false) =>  self.mapper.map(self.mapper.xmin, *y),
                (true, true) => self.mapper.map(self.mapper.xmin, self.mapper.ymin + self.mapper.ymax - *y)
            };
            self.draw_grid_line(ctx, design, from, to)?;
            //let mut y_label_coord = match self.mapper.yinv {
            //    true => to,
            //    false => from
            //};
            from.x -= 1.1*max_extent;
            self.draw_grid_value(ctx, design, y_label, from, false, 0.0, 0.0)?;
        }
        self.draw_scale_names(ctx, design)?;
        ctx.restore()?;
        Ok(())
    }

    fn draw_scale_names(&self, ctx : &Context, design : &PlotDesign) -> Result<(), Box<dyn Error>> {
        let pos_x = Coord2D::new(
            self.mapper.w as f64 * 0.5,
            self.mapper.h as f64 * 0.975
        );
        // export POS_X=0.1
        let pos_y = Coord2D::new(
            self.mapper.w as f64 * 0.025,
            self.mapper.h as f64 * 0.5
        );
        text::draw_label(
            &design.font.sf,
            ctx,
            &self.x.label[..],
            pos_x,
            false,
            (true, true),
            None,
            None
        )?;
        text::draw_label(
            &design.font.sf,
            ctx,
            &self.y.label[..],
            pos_y,
            true,
            (true, true),
            None,
            None
        )?;
        Ok(())
    }

    /*fn update_mapping_name(name : &str) {
        // Verify if mapping name is not x|y|design|
    }*/

    /// For each mapping, return a tuple with (name, type, properties).
    pub fn mapping_info(&self) -> Vec<(String, String, HashMap<String,String>)> {
        let mut info = Vec::new();
        for (i, m) in self.mappings.iter().enumerate() {
            info.push((i.to_string(), m.mapping_type(), m.properties()))
        }
        //println!("{:?}", info);
        info
    }

    pub fn mapping_column_names(&self, id : &str) -> Vec<(String, String)> {
        let mut names = Vec::new();
        if let Some(m) = self.mappings.get(id.parse::<usize>().unwrap()) {
            names.extend(m.get_ordered_col_names());
        }
        names
    }

    pub fn scale_info(&self, scale : &str) -> HashMap<String, String> {
        match scale {
            "x" => self.x.description(),
            "y" => self.y.description(),
            _ => HashMap::new()
        }
    }

    pub fn update_mapping_columns(
        &mut self,
        id : &str,
        columns : Vec<String>
    ) -> Result<(), Box<dyn Error>> {
        if let Some(mapping) = self.mappings.get_mut(id.parse::<usize>().unwrap()) {
            if let Err(e) = mapping.set_col_names(columns) {
                println!("{}", e);
            }
        } else {
            println!("Mapping not found when updating column name");
        }
        // if let Err(e) = self.reload_layout_node() {
        //    println!("{}", e);
        // }
        Ok(())
    }

    pub fn update_source(
        &mut self,
        id : &str,
        source : String
    ) -> Result<(), Box<dyn Error>> {
        if let Some(mapping) = self.mappings.get_mut(id.parse::<usize>().unwrap()) {
            mapping.set_source(source);
        } else {
            println!("Mapping not found when updating column name");
        }
        Ok(())
    }

    pub fn view_sources(&self) -> Vec<String> {
        self.mappings.iter().map(|mapping| mapping.get_source() ).collect()
    }

    /*pub fn update_mapping_column(
        &mut self,
        id : &str,
        column : &str,
        name : &str
    ) {
        if let Some(mapping) = self.mappings.get_mut(id.parse::<usize>().unwrap()) {
            mapping.set_col_name(column, name);
        } else {
            println!("Mapping not found when updating column name");
        }
        if let Err(e) = self.reload_layout_data() {
            println!("{}", e);
        }
    }*/

    /*pub fn get_mapping_column(
        &self,
        id : &str,
        column : &str
    ) -> Option<String> {
        if let Some(mapping) = self.mappings.get(id.parse::<usize>().unwrap()) {
            let col_name = mapping.get_col_name(column);
            if col_name != "None" {
                Some(col_name)
            } else {
                None
            }
        } else {
            println!("Mapping not found when getting column name");
            None
        }
    }*/

}

//#[repr(C)]

/*pub mod utils {

    use super::Node;
    use super::HashMap;
    use super::Document;
    use super::Error;

    /// Return all children of node that satisfy the
    /// informed xpath.
    pub fn children_as_hash(
        node : &Node,
        xpath : &str
    ) -> HashMap<String, String> {
        let mut prop_hash = HashMap::new();
        if let Ok(props) = node.findnodes(xpath) {
            if props.len() == 0 {
                panic!("No children found for node {:?} at path {}", node, xpath);
            }
            for prop in props.iter() {
                // println!("Property = {:?}", prop);
                let name = prop.get_attribute("name")
                    .expect(&format!("No name attribute found for property {:?}", prop));
                let value = prop.get_content();
                prop_hash.insert(name, value);
            }
        } else {
            panic!("Failed to retrieve children of {:?} at path {}", node, xpath);
        }
        prop_hash
    }

    /*pub fn populate_node_with_hash(
        doc : &Document,
        node : &mut Node,
        hash : HashMap<String, String>
    ) -> Result<(), Box<dyn Error>> {
        for (k, v) in hash {
            let mut property = Node::new(
                "property", Option::None, doc).unwrap();
            property.set_attribute("name", &k[..])?;
            property.set_content(&v[..])?;
            node.add_child(&mut property)?;
        }
        Ok(())
    }

    pub fn edit_node_with_hash(
        doc : &Document,
        props : &HashMap<String, String>,
        node : &mut Node
    ) {
        let mut keys : Vec<String> = props.iter().map(|(k, v)| k.clone() ).collect();
        // println!("Keys: {:?}", keys);
        let mut n_changed = 0;
        // println!("Child nodes: {:?}", node.get_child_nodes().iter().map(|node| format!("{} {:?}", node.get_name(), node.get_property("name"))).collect::<Vec<_>>() );
        for mut child in node.get_child_nodes().iter_mut() {
            if &child.get_name()[..] == "property" {
                if let Some(name) = child.get_attribute("name") {
                    // if keys.iter().find(|k| &k[..] == &name[..] ).is_some() {
                    child.set_content(&props[&name]).unwrap();
                    n_changed += 1;
                    //} else {
                    //    println!("No property named {}", name);
                    //}
                } else {
                    println!("Node does not have name property");
                }
            }
        }
        let n_required = props.iter().count();
        if n_changed != n_required {
            println!("Changed only {} nodes (of {} required)", n_changed, n_required);
        }
    }*/

}*/

/*#[no_mangle]
pub extern "C" fn interactive(engine : &mut interactive::Engine) {
    engine.register_type::<Panel>()
        .register_fn("new_panel", Panel::new )
        .register_fn("show", |panel : &mut Panel| { panel.show_with_eog().unwrap() });
}*/

// fn module_func(a : i64) -> Result<i64, Box<interactive::EvalAltResult>> {
//    Ok(a)
// }

/*#[export_name="panel_module"]
    extern "C" fn module() -> Box<interactive::Module> {

        // use rhai::func::register::*;

        let mut m = interactive::Module::new();
        let hash = m.set_native_fn("module_func", Box::new(|a : i64| -> Result<i64, Box<interactive::EvalAltResult>> { Ok(a) }));
        println!("Inserted hash: {}", hash);
        // m.set_native_fn("module_func", module_func);
        Box::new(m)
    }

    #[export_name="register_panel"]
    extern "C" fn interactive(engine : &mut interactive::Engine) {

        engine.register_fn("do_thing", Box::new(|a : i64| -> i64 { a }));
        engine.register_fn("do_nothing", Box::new(|| { println!("Do nothing") }));

        println!("Symbols loaded from client lib");
        println!("Type id at client: {:?}", std::any::TypeId::of::<i64>());

        println!("Calling from client: {:?}", engine.eval::<i64>("do_thing(44)"));
        println!("Calling do_nothing from client: {:?}", engine.eval::<()>("do_nothing()"));

        //engine.register_type::<Panel>()
        //    .register_fn("new_panel", Box::new(move || Panel::new ) )
        //    .register_fn("show", Box::new(move |panel : &mut Panel| { panel.show_with_eog().unwrap() }) );
    }

    // fn display(engine : &mut interactive::Engine) {
    //      By implementing:
    //      engine.register_fn("to_string",	|x: &mut T| -> String)
    //      engine.register_fn("to_debug",	|x: &mut T| -> String	format!("{:?}", x)
    //      The custom functionality will be available: type.print(); type.debug(); "" + type; type + "", "" += type;
    // }

    // Initializer function - By using a function pointer, we guarantee it will be called only once,
    // no matter how many types we register from this module.
    // let mut module = Module::new();
    // module.set_native_fn("inc", |x: i64| {
    // fn init() -> fn(&mut Engine) {
    //    let mut resolver = StaticModuleResolver::new();
    //    resolver.insert("module_name", module);
    //    Perhaps if we insert each type as a static module (e.g. module "Panel",
    //    and make them readily avaiable, we can use them as if they were associated functions.
    //    q::answer + 1
    // }
    // engine.set_module_resolver(resolver);

    fn fields(engine : &mut interactive::Engine) {
        /*register_get_set("field")
            |panel| panel.field
            |panel, value| panel.field = value*/


        // register_indexer_get_set
        // getter: Fn(&mut T, X) -> V
        // setter: Fn(&mut T, X, V) Where X is an indexer type.
    }*/

/*#[cfg(feature="interactive")]
#[export_name="register_methods"]
extern "C" fn reg_methods(engine : &mut interactive::Engine) /*-> Box<interactive::Engine>*/ {

    use interactive::Module;
    use interactive::TypeId;
    // let mut engine = Engine::new();

    engine
        .register_fn("new_panel", Box::new(move || Panel::new() ) )
        .register_fn("show", Box::new(move |panel : &mut Panel| { panel.show_with_eog().unwrap() }) );

    let mut module = Module::new();
    let hash = module.set_native_fn("create", move || Ok(Panel::new()) );
    module.update_fn_metadata(hash, &["Panel"]);

    engine.register_static_module("Panel", module.into());

    engine.register_fn("add_integer", |a : i64| a + 1 );
    println!("Type id of integer at client = {:?}", TypeId::of::<i64>() );

    let mut m = interactive::Module::new();
    let hash = m.set_native_fn("module_func", Box::new(|a : i64| -> Result<i64, Box<interactive::EvalAltResult>> { Ok(a + 1) }));
    println!("Inserted hash: {}", hash);
    engine.register_static_module("mymodule", m.into());

    println!("Symbols loaded from client lib");

    /*Box::new(engine)*/
}*/

/*// nm -gD target/debug/libplots.so
#[cfg(feature="interactive")]
impl interactive::Interactive for Panel {

    #[export_name="register_methods"]
    extern "C" fn interactive(engine : &mut interactive::Engine) -> Box<interactive::RegistrationInfo> {
        self.display(engine);
        self.associated(engine);
        engine
            .register_fn("show", Box::new(move |panel : &mut Panel| { panel.show_with_eog().unwrap() }) );

        self.info()
        // let mut module = Module::new();
        // let hash = module.set_native_fn("create", move || Ok(Panel::new()) );
        // module.update_fn_metadata(hash, &["Panel"]);
        // engine.register_static_module("Panel", module.into());
    }

    // Perhaps we abstract certain details away,
    // and just require the registration of "associated" and "methods",
    // automatically taking care of the plumbing without exposing the engine
    // to the user.

}*/

/*impl interactive::Interactive for Plot {

    #[export_name="register_plot"]
    extern "C" fn interactive(engine : &mut interactive::Engine) {
        /*engine.register_type::<Panel>()
            .register_fn("new_panel", Panel::new )
            .register_fn("show", |panel : &mut Panel| { panel.show_with_eog().unwrap() });*/
    }

}*/

//impl IsA<gtk::DrawingArea> for PlotView {
//}

//Draw
/*impl ObjectImpl for PlotView {

    glib_object_impl!();

    //fn get_type_data(&self) -> NonNull<TypeData> {
    //}

    //glib_wrapper! {
    //}
}*/
//impl AsRef
//unsafe impl IsA<gtk::DrawingArea> for PlotView {
//}
/*impl ObjectSubclass for PlotView {
    const NAME: &'static str = "PlotView";
    type ParentType = gtk::DrawingArea;
    /* Glib classes are global runtime structs that are created
    when the first object of a given class is instantiated,
    and are destroyed when the last object of a given class
    is destroyed. (There is only a single instance of each
    class at any given time). The alias "Class" automatically
    implements a boilerplate struct to hold this class. */
    type Class = subclass::simple::ClassStruct<Self>;
    /* The instante is a global runtime struct (also one for
    each registered object) that describes things like
    memory object layout. Also automatically created. */
    type Instance = subclass::simple::InstanceStruct<Self>;

    glib_object_subclass!();

    fn class_init(klass: &mut Self::Class) {
        klass.install_properties(&PROPERTIES);
    }

    fn new() -> Self {
        let plot_area = Plot::new(String::from("assets/layout.xml"));
        PlotView{plot_area}
    }
}*/
// glib::Object::new(T::get_type(), &[])
// get_type() registers type
// glib_wrapper!

// Used for overriding virtual methods - Must map to
// Impl trait
//unsafe impl IsSubclassable<PlotView>
//for gtk::auto::drawing_area::DrawingAreaClass {

//}

//subclass::types::register_type();

/*impl ObjectSubclass for PlotView {
    const NAME: &'static str = "PlotView";

    type ParentType = gtk::DrawingArea;

    type Instance = PlotView;
    type Class = PlotViewClass;

    glib_object_subclass!();

    fn class_init(klass: &mut PlotView) {
        klass.install_properties(&PROPERTIES);
    }

    fn new() -> Self {
        PlotView::new();
    }
}*/
/*fn add_signal(
    &mut self,
    name: &str,
    flags: SignalFlags,
    arg_types: &[Type],
    ret_type: Type
)*/
//unsafe extern "C" fn