File: cairo_gal.cpp

package info (click to toggle)
kicad 9.0.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 770,320 kB
  • sloc: cpp: 961,692; ansic: 121,001; xml: 66,428; python: 18,387; sh: 1,010; awk: 301; asm: 292; makefile: 227; javascript: 167; perl: 10
file content (1888 lines) | stat: -rw-r--r-- 56,240 bytes parent folder | download | duplicates (3)
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
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
/*
 * This program source code file is part of KICAD, a free EDA CAD application.
 *
 * Copyright (C) 2012 Torsten Hueter, torstenhtr <at> gmx.de
 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
 * Copyright (C) 2017-2018 CERN
 *
 * @author Maciej Suminski <maciej.suminski@cern.ch>
 *
 * CairoGal - Graphics Abstraction Layer for Cairo
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, you may find one here:
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * or you may search the http://www.gnu.org website for the version 2 license,
 * or you may write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
 */

#include <wx/image.h>
#include <wx/log.h>

#include <gal/cairo/cairo_gal.h>
#include <gal/cairo/cairo_compositor.h>
#include <gal/definitions.h>
#include <geometry/shape_poly_set.h>
#include <math/vector2wx.h>
#include <math/util.h> // for KiROUND
#include <trigo.h>
#include <bitmap_base.h>

#include <algorithm>
#include <cmath>
#include <limits>

#include <pixman.h>

using namespace KIGFX;


CAIRO_GAL_BASE::CAIRO_GAL_BASE( GAL_DISPLAY_OPTIONS& aDisplayOptions ) : GAL( aDisplayOptions )
{
    // Initialise grouping
    m_isGrouping = false;
    m_isElementAdded = false;
    m_groupCounter = 0;
    m_currentGroup = nullptr;

    m_lineWidth = 1.0;
    m_lineWidthInPixels = 1.0;
    m_lineWidthIsOdd = true;

    // Initialise Cairo state
    cairo_matrix_init_identity( &m_cairoWorldScreenMatrix );
    m_currentContext = nullptr;
    m_context = nullptr;
    m_surface = nullptr;

    // Grid color settings are different in Cairo and OpenGL
    SetGridColor( COLOR4D( 0.1, 0.1, 0.1, 0.8 ) );
    SetAxesColor( COLOR4D( BLUE ) );

    // Avoid uninitialized variables:
    cairo_matrix_init_identity( &m_currentXform );
    cairo_matrix_init_identity( &m_currentWorld2Screen );
}


CAIRO_GAL_BASE::~CAIRO_GAL_BASE()
{
    ClearCache();

    if( m_surface )
        cairo_surface_destroy( m_surface );

    if( m_context )
        cairo_destroy( m_context );

    for( _cairo_surface* imageSurface : m_imageSurfaces )
        cairo_surface_destroy( imageSurface );
}


void CAIRO_GAL_BASE::BeginDrawing()
{
    resetContext();
}


void CAIRO_GAL_BASE::EndDrawing()
{
    // Force remaining objects to be drawn
    Flush();
}


void CAIRO_GAL_BASE::updateWorldScreenMatrix()
{
    cairo_matrix_multiply( &m_currentWorld2Screen, &m_currentXform, &m_cairoWorldScreenMatrix );
}


const VECTOR2D CAIRO_GAL_BASE::xform( double x, double y )
{
    VECTOR2D rv;

    rv.x = m_currentWorld2Screen.xx * x + m_currentWorld2Screen.xy * y + m_currentWorld2Screen.x0;
    rv.y = m_currentWorld2Screen.yx * x + m_currentWorld2Screen.yy * y + m_currentWorld2Screen.y0;
    return rv;
}


const VECTOR2D CAIRO_GAL_BASE::xform( const VECTOR2D& aP )
{
    return xform( aP.x, aP.y );
}


double CAIRO_GAL_BASE::angle_xform( double aAngle )
{
    // calculate rotation angle due to the rotation transform
    // and if flipped on X axis.
    double world_rotation = -std::atan2( m_currentWorld2Screen.xy, m_currentWorld2Screen.xx );

    // When flipped on X axis, the rotation angle is M_PI - initial angle:
    if( IsFlippedX() )
        world_rotation = M_PI - world_rotation;

    return std::fmod( aAngle + world_rotation, 2.0 * M_PI );
}


void CAIRO_GAL_BASE::arc_angles_xform_and_normalize( double& aStartAngle, double& aEndAngle )
{
    // 360 deg arcs have a specific calculation.
    bool is_360deg_arc = std::abs( aEndAngle - aStartAngle ) >= 2 * M_PI;
    double startAngle = aStartAngle;
    double endAngle = aEndAngle;

    // When the view is flipped, the coordinates are flipped by the matrix transform
    // However, arc angles need to be "flipped": the flipped angle is M_PI - initial angle.
    if( IsFlippedX() )
    {
        startAngle = M_PI - startAngle;
        endAngle = M_PI - endAngle;
    }

    // Normalize arc angles
    normalize( startAngle, endAngle );

    // now rotate arc according to the rotation transform matrix
    // Remark:
    // We call angle_xform() to calculate angles according to the flip/rotation
    // transform and normalize between -2M_PI and +2M_PI.
    // Therefore, if aStartAngle = aEndAngle + 2*n*M_PI, the transform gives
    // aEndAngle = aStartAngle
    // So, if this is the case, force the aEndAngle value to draw a circle.
    aStartAngle = angle_xform( startAngle );

    if( is_360deg_arc ) // arc is a full circle
        aEndAngle = aStartAngle + 2 * M_PI;
    else
        aEndAngle = angle_xform( endAngle );
}


double CAIRO_GAL_BASE::xform( double x )
{
    double dx = m_currentWorld2Screen.xx * x;
    double dy = m_currentWorld2Screen.yx * x;
    return sqrt( dx * dx + dy * dy );
}


static double roundp( double x )
{
    return floor( x + 0.5 ) + 0.5;
}


const VECTOR2D CAIRO_GAL_BASE::roundp( const VECTOR2D& v )
{
    if( m_lineWidthIsOdd )
        return VECTOR2D( ::roundp( v.x ), ::roundp( v.y ) );
    else
        return VECTOR2D( floor( v.x + 0.5 ), floor( v.y + 0.5 ) );
}


void CAIRO_GAL_BASE::DrawLine( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
{
    syncLineWidth();

    VECTOR2D p0 = roundp( xform( aStartPoint ) );
    VECTOR2D p1 = roundp( xform( aEndPoint ) );

    cairo_move_to( m_currentContext, p0.x, p0.y );
    cairo_line_to( m_currentContext, p1.x, p1.y );
    flushPath();
    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::syncLineWidth( bool aForceWidth, double aWidth )
{
    double w = floor( xform( aForceWidth ? aWidth : m_lineWidth ) + 0.5 );

    if( w <= 1.0 )
    {
        w = 1.0;
        cairo_set_line_join( m_currentContext, CAIRO_LINE_JOIN_MITER );
        cairo_set_line_cap( m_currentContext, CAIRO_LINE_CAP_BUTT );
        cairo_set_line_width( m_currentContext, 1.0 );
        m_lineWidthIsOdd = true;
    }
    else
    {
        cairo_set_line_join( m_currentContext, CAIRO_LINE_JOIN_ROUND );
        cairo_set_line_cap( m_currentContext, CAIRO_LINE_CAP_ROUND );
        cairo_set_line_width( m_currentContext, w );
        m_lineWidthIsOdd = ( (int) w % 2 ) == 1;
    }

    m_lineWidthInPixels = w;
}


void CAIRO_GAL_BASE::DrawSegmentChain( const std::vector<VECTOR2D>& aPointList, double aWidth )
{
    for( size_t i = 0; i + 1 < aPointList.size(); ++i )
        DrawSegment( aPointList[i], aPointList[i + 1], aWidth );
}


void CAIRO_GAL_BASE::DrawSegmentChain( const SHAPE_LINE_CHAIN& aLineChain, double aWidth )
{
    int numPoints = aLineChain.PointCount();

    if( aLineChain.IsClosed() )
        numPoints += 1;

    for( int i = 0; i + 1 < numPoints; ++i )
        DrawSegment( aLineChain.CPoint( i ), aLineChain.CPoint( i + 1 ), aWidth );
}


void CAIRO_GAL_BASE::DrawSegment( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint,
                                  double aWidth )
{
    if( m_isFillEnabled )
    {
        syncLineWidth( true, aWidth );

        VECTOR2D p0 = roundp( xform( aStartPoint ) );
        VECTOR2D p1 = roundp( xform( aEndPoint ) );

        cairo_move_to( m_currentContext, p0.x, p0.y );
        cairo_line_to( m_currentContext, p1.x, p1.y );
        cairo_set_source_rgba( m_currentContext, m_fillColor.r, m_fillColor.g, m_fillColor.b,
                               m_fillColor.a );
        cairo_stroke( m_currentContext );
    }
    else
    {
        aWidth /= 2.0;
        SetLineWidth( 1.0 );
        syncLineWidth();

        // Outline mode for tracks
        VECTOR2D startEndVector = aEndPoint - aStartPoint;
        double   lineAngle = atan2( startEndVector.y, startEndVector.x );

        double sa = sin( lineAngle + M_PI / 2.0 );
        double ca = cos( lineAngle + M_PI / 2.0 );

        VECTOR2D pa0 = xform( aStartPoint + VECTOR2D( aWidth * ca, aWidth * sa ) );
        VECTOR2D pa1 = xform( aStartPoint - VECTOR2D( aWidth * ca, aWidth * sa ) );
        VECTOR2D pb0 = xform( aEndPoint + VECTOR2D( aWidth * ca, aWidth * sa ) );
        VECTOR2D pb1 = xform( aEndPoint - VECTOR2D( aWidth * ca, aWidth * sa ) );

        cairo_set_source_rgba( m_currentContext, m_strokeColor.r, m_strokeColor.g, m_strokeColor.b,
                               m_strokeColor.a );

        cairo_move_to( m_currentContext, pa0.x, pa0.y );
        cairo_line_to( m_currentContext, pb0.x, pb0.y );

        cairo_move_to( m_currentContext, pa1.x, pa1.y );
        cairo_line_to( m_currentContext, pb1.x, pb1.y );
        flushPath();

        // Calculate the segment angle and arc center in normal/mirrored transform for rounded ends.
        VECTOR2D center_a = xform( aStartPoint );
        VECTOR2D center_b = xform( aEndPoint );
        startEndVector = center_b - center_a;
        lineAngle = atan2( startEndVector.y, startEndVector.x );
        double radius = ( pa0 - center_a ).EuclideanNorm();

        // Draw the rounded end point of the segment
        double arcStartAngle = lineAngle - M_PI / 2.0;
        cairo_arc( m_currentContext, center_b.x, center_b.y, radius, arcStartAngle,
                   arcStartAngle + M_PI );

        // Draw the rounded start point of the segment
        arcStartAngle = lineAngle + M_PI / 2.0;
        cairo_arc( m_currentContext, center_a.x, center_a.y, radius, arcStartAngle,
                   arcStartAngle + M_PI );

        flushPath();
    }

    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::DrawCircle( const VECTOR2D& aCenterPoint, double aRadius )
{
    syncLineWidth();

    VECTOR2D c = roundp( xform( aCenterPoint ) );
    double   r = ::roundp( xform( aRadius ) );

    cairo_set_line_width( m_currentContext, std::min( 2.0 * r, m_lineWidthInPixels ) );
    cairo_new_sub_path( m_currentContext );
    cairo_arc( m_currentContext, c.x, c.y, r, 0.0, 2 * M_PI );
    cairo_close_path( m_currentContext );
    flushPath();
    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::DrawArc( const VECTOR2D& aCenterPoint, double aRadius,
                              const EDA_ANGLE& aStartAngle, const EDA_ANGLE& aAngle )
{
    syncLineWidth();

    double startAngle = aStartAngle.AsRadians();
    double endAngle = startAngle + aAngle.AsRadians();

    // calculate start and end arc angles according to the rotation transform matrix
    // and normalize:
    arc_angles_xform_and_normalize( startAngle, endAngle );

    double r = xform( aRadius );

    // Adjust center and radius slightly to better match the rounding of endpoints.
    VECTOR2D mid = roundp( xform( aCenterPoint ) );

    VECTOR2D startPointS = VECTOR2D( r, 0.0 );
    VECTOR2D endPointS = VECTOR2D( r, 0.0 );
    RotatePoint( startPointS, -EDA_ANGLE( startAngle, RADIANS_T ) );
    RotatePoint( endPointS, -EDA_ANGLE( endAngle, RADIANS_T ) );

    VECTOR2D refStart = roundp( xform( aCenterPoint ) + startPointS );
    VECTOR2D refEnd = roundp( xform( aCenterPoint ) + endPointS );

    r = ( ( refStart - mid ).EuclideanNorm() + ( refEnd - mid ).EuclideanNorm() ) / 2.0;

    cairo_set_line_width( m_currentContext, m_lineWidthInPixels );
    cairo_new_sub_path( m_currentContext );

    if( m_isFillEnabled )
        cairo_move_to( m_currentContext, mid.x, mid.y );

    cairo_arc( m_currentContext, mid.x, mid.y, r, startAngle, endAngle );

    if( m_isFillEnabled )
        cairo_close_path( m_currentContext );

    flushPath();

    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::DrawArcSegment( const VECTOR2D& aCenterPoint, double aRadius,
                                     const EDA_ANGLE& aStartAngle, const EDA_ANGLE& aAngle,
                                     double aWidth, double aMaxError )
{
    // Note: aMaxError is not used because Cairo can draw true arcs
    if( m_isFillEnabled )
    {
        m_lineWidth = aWidth;
        m_isStrokeEnabled = true;
        m_isFillEnabled = false;
        DrawArc( aCenterPoint, aRadius, aStartAngle, aAngle );
        m_isFillEnabled = true;
        m_isStrokeEnabled = false;
        return;
    }

    syncLineWidth();

    // calculate start and end arc angles according to the rotation transform matrix
    // and normalize:
    double startAngleS = aStartAngle.AsRadians();
    double endAngleS = startAngleS + aAngle.AsRadians();
    arc_angles_xform_and_normalize( startAngleS, endAngleS );

    double r = xform( aRadius );

    VECTOR2D mid = xform( aCenterPoint );
    double   width = xform( aWidth / 2.0 );
    VECTOR2D startPointS = VECTOR2D( r, 0.0 );
    VECTOR2D endPointS = VECTOR2D( r, 0.0 );
    RotatePoint( startPointS, -EDA_ANGLE( startAngleS, RADIANS_T ) );
    RotatePoint( endPointS, -EDA_ANGLE( endAngleS, RADIANS_T ) );

    cairo_save( m_currentContext );

    cairo_set_source_rgba( m_currentContext, m_strokeColor.r, m_strokeColor.g, m_strokeColor.b,
                           m_strokeColor.a );

    cairo_translate( m_currentContext, mid.x, mid.y );

    cairo_new_sub_path( m_currentContext );
    cairo_arc( m_currentContext, 0, 0, r - width, startAngleS, endAngleS );

    cairo_new_sub_path( m_currentContext );
    cairo_arc( m_currentContext, 0, 0, r + width, startAngleS, endAngleS );

    cairo_new_sub_path( m_currentContext );
    cairo_arc_negative( m_currentContext, startPointS.x, startPointS.y, width, startAngleS,
                        startAngleS + M_PI );

    cairo_new_sub_path( m_currentContext );
    cairo_arc( m_currentContext, endPointS.x, endPointS.y, width, endAngleS, endAngleS + M_PI );

    cairo_restore( m_currentContext );
    flushPath();

    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::DrawRectangle( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
{
    // Calculate the diagonal points
    syncLineWidth();

    const VECTOR2D p0 = roundp( xform( aStartPoint ) );
    const VECTOR2D p1 = roundp( xform( VECTOR2D( aEndPoint.x, aStartPoint.y ) ) );
    const VECTOR2D p2 = roundp( xform( aEndPoint ) );
    const VECTOR2D p3 = roundp( xform( VECTOR2D( aStartPoint.x, aEndPoint.y ) ) );

    // The path is composed from 4 segments
    cairo_move_to( m_currentContext, p0.x, p0.y );
    cairo_line_to( m_currentContext, p1.x, p1.y );
    cairo_line_to( m_currentContext, p2.x, p2.y );
    cairo_line_to( m_currentContext, p3.x, p3.y );
    cairo_close_path( m_currentContext );
    flushPath();

    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::DrawPolygon( const SHAPE_POLY_SET& aPolySet, bool aStrokeTriangulation )
{
    for( int i = 0; i < aPolySet.OutlineCount(); ++i )
        drawPoly( aPolySet.COutline( i ) );
}


void CAIRO_GAL_BASE::DrawPolygon( const SHAPE_LINE_CHAIN& aPolygon )
{
    drawPoly( aPolygon );
}


void CAIRO_GAL_BASE::DrawCurve( const VECTOR2D& aStartPoint, const VECTOR2D& aControlPointA,
                                const VECTOR2D& aControlPointB, const VECTOR2D& aEndPoint,
                                double aFilterValue )
{
    // Note: aFilterValue is not used because the cubic Bezier curve is
    // supported by Cairo.
    syncLineWidth();

    const VECTOR2D sp = roundp( xform( aStartPoint ) );
    const VECTOR2D cpa = roundp( xform( aControlPointA ) );
    const VECTOR2D cpb = roundp( xform( aControlPointB ) );
    const VECTOR2D ep = roundp( xform( aEndPoint ) );

    cairo_move_to( m_currentContext, sp.x, sp.y );
    cairo_curve_to( m_currentContext, cpa.x, cpa.y, cpb.x, cpb.y, ep.x, ep.y );
    cairo_line_to( m_currentContext, ep.x, ep.y );

    flushPath();
    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::DrawBitmap( const BITMAP_BASE& aBitmap, double alphaBlend )
{
    cairo_save( m_currentContext );

    alphaBlend = std::clamp( alphaBlend, 0.0, 1.0 );

    // We have to calculate the pixel size in users units to draw the image.
    // m_worldUnitLength is a factor used for converting IU to inches
    double scale = 1.0 / ( aBitmap.GetPPI() * m_worldUnitLength );

    // The position of the bitmap is the bitmap center.
    // move the draw origin to the top left bitmap corner:
    int w = aBitmap.GetSizePixels().x;
    int h = aBitmap.GetSizePixels().y;

    cairo_set_matrix( m_currentContext, &m_currentWorld2Screen );
    cairo_scale( m_currentContext, scale, scale );
    cairo_translate( m_currentContext, -w / 2.0, -h / 2.0 );

    cairo_new_path( m_currentContext );
    cairo_surface_t* image = cairo_image_surface_create( CAIRO_FORMAT_ARGB32, w, h );
    cairo_surface_flush( image );

    unsigned char* pix_buffer = cairo_image_surface_get_data( image );

    // The pixel buffer of the initial bitmap:
    const wxImage& bm_pix_buffer = *aBitmap.GetImageData();

    uint32_t mask_color = ( bm_pix_buffer.GetMaskRed() << 16 )
                          + ( bm_pix_buffer.GetMaskGreen() << 8 ) + ( bm_pix_buffer.GetMaskBlue() );

    // Copy the source bitmap to the cairo bitmap buffer.
    // In cairo bitmap buffer, a ARGB32 bitmap is an ARGB pixel packed into a uint_32
    // 24 low bits only are used for color, top 8 are transparency.
    for( int row = 0; row < h; row++ )
    {
        for( int col = 0; col < w; col++ )
        {
            unsigned char r = bm_pix_buffer.GetRed( col, row );
            unsigned char g = bm_pix_buffer.GetGreen( col, row );
            unsigned char b = bm_pix_buffer.GetBlue( col, row );
            unsigned char a = wxALPHA_OPAQUE;

            if( bm_pix_buffer.HasAlpha() )
            {
                a = bm_pix_buffer.GetAlpha( col, row );

                // ARGB32 format needs pre-multiplied alpha
                r = uint32_t( r ) * a / 0xFF;
                g = uint32_t( g ) * a / 0xFF;
                b = uint32_t( b ) * a / 0xFF;
            }
            else if( bm_pix_buffer.HasMask() && (uint32_t)( r << 16 | g << 8 | b ) == mask_color )
            {
                a = wxALPHA_TRANSPARENT;
            }

            // Build the ARGB24 pixel:
            uint32_t pixel = a << 24 | r << 16 | g << 8 | b;

            // Write the pixel to the cairo image buffer:
            uint32_t* pix_ptr = (uint32_t*) pix_buffer;
            *pix_ptr = pixel;
            pix_buffer += 4;
        }
    }

    cairo_surface_mark_dirty( image );
    cairo_set_source_surface( m_currentContext, image, 0, 0 );
    cairo_paint_with_alpha( m_currentContext, alphaBlend );

    // store the image handle so it can be destroyed later
    m_imageSurfaces.push_back( image );

    m_isElementAdded = true;

    cairo_restore( m_currentContext );
}


void CAIRO_GAL_BASE::ResizeScreen( int aWidth, int aHeight )
{
    m_screenSize = VECTOR2I( aWidth, aHeight );
}


void CAIRO_GAL_BASE::Flush()
{
    storePath();
}


void CAIRO_GAL_BASE::ClearScreen()
{
    cairo_set_source_rgb( m_currentContext, m_clearColor.r, m_clearColor.g, m_clearColor.b );
    cairo_rectangle( m_currentContext, 0.0, 0.0, m_screenSize.x, m_screenSize.y );
    cairo_fill( m_currentContext );
}


void CAIRO_GAL_BASE::SetIsFill( bool aIsFillEnabled )
{
    storePath();
    m_isFillEnabled = aIsFillEnabled;

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_SET_FILL;
        groupElement.m_Argument.BoolArg = aIsFillEnabled;
        m_currentGroup->push_back( groupElement );
    }
}


void CAIRO_GAL_BASE::SetIsStroke( bool aIsStrokeEnabled )
{
    storePath();
    m_isStrokeEnabled = aIsStrokeEnabled;

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_SET_STROKE;
        groupElement.m_Argument.BoolArg = aIsStrokeEnabled;
        m_currentGroup->push_back( groupElement );
    }
}


void CAIRO_GAL_BASE::SetStrokeColor( const COLOR4D& aColor )
{
    storePath();
    m_strokeColor = aColor;

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_SET_STROKECOLOR;
        groupElement.m_Argument.DblArg[0] = m_strokeColor.r;
        groupElement.m_Argument.DblArg[1] = m_strokeColor.g;
        groupElement.m_Argument.DblArg[2] = m_strokeColor.b;
        groupElement.m_Argument.DblArg[3] = m_strokeColor.a;
        m_currentGroup->push_back( groupElement );
    }
}


void CAIRO_GAL_BASE::SetFillColor( const COLOR4D& aColor )
{
    storePath();
    m_fillColor = aColor;

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_SET_FILLCOLOR;
        groupElement.m_Argument.DblArg[0] = m_fillColor.r;
        groupElement.m_Argument.DblArg[1] = m_fillColor.g;
        groupElement.m_Argument.DblArg[2] = m_fillColor.b;
        groupElement.m_Argument.DblArg[3] = m_fillColor.a;
        m_currentGroup->push_back( groupElement );
    }
}


void CAIRO_GAL_BASE::SetLineWidth( float aLineWidth )
{
    storePath();
    GAL::SetLineWidth( aLineWidth );

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_SET_LINE_WIDTH;
        groupElement.m_Argument.DblArg[0] = aLineWidth;
        m_currentGroup->push_back( groupElement );
    }
    else
    {
        m_lineWidth = aLineWidth;
    }
}


void CAIRO_GAL_BASE::SetLayerDepth( double aLayerDepth )
{
    super::SetLayerDepth( aLayerDepth );
    storePath();
}


void CAIRO_GAL_BASE::Transform( const MATRIX3x3D& aTransformation )
{
    cairo_matrix_t cairoTransformation, newXform;

    cairo_matrix_init( &cairoTransformation, aTransformation.m_data[0][0],
                       aTransformation.m_data[1][0], aTransformation.m_data[0][1],
                       aTransformation.m_data[1][1], aTransformation.m_data[0][2],
                       aTransformation.m_data[1][2] );

    cairo_matrix_multiply( &newXform, &m_currentXform, &cairoTransformation );
    m_currentXform = newXform;
    updateWorldScreenMatrix();
}


void CAIRO_GAL_BASE::Rotate( double aAngle )
{
    storePath();

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_ROTATE;
        groupElement.m_Argument.DblArg[0] = aAngle;
        m_currentGroup->push_back( groupElement );
    }
    else
    {
        cairo_matrix_rotate( &m_currentXform, aAngle );
        updateWorldScreenMatrix();
    }
}


void CAIRO_GAL_BASE::Translate( const VECTOR2D& aTranslation )
{
    storePath();

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_TRANSLATE;
        groupElement.m_Argument.DblArg[0] = aTranslation.x;
        groupElement.m_Argument.DblArg[1] = aTranslation.y;
        m_currentGroup->push_back( groupElement );
    }
    else
    {
        cairo_matrix_translate( &m_currentXform, aTranslation.x, aTranslation.y );
        updateWorldScreenMatrix();
    }
}


void CAIRO_GAL_BASE::Scale( const VECTOR2D& aScale )
{
    storePath();

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_SCALE;
        groupElement.m_Argument.DblArg[0] = aScale.x;
        groupElement.m_Argument.DblArg[1] = aScale.y;
        m_currentGroup->push_back( groupElement );
    }
    else
    {
        cairo_matrix_scale( &m_currentXform, aScale.x, aScale.y );
        updateWorldScreenMatrix();
    }
}


void CAIRO_GAL_BASE::Save()
{
    storePath();

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_SAVE;
        m_currentGroup->push_back( groupElement );
    }
    else
    {
        m_xformStack.push_back( m_currentXform );
        updateWorldScreenMatrix();
    }
}


void CAIRO_GAL_BASE::Restore()
{
    storePath();

    if( m_isGrouping )
    {
        GROUP_ELEMENT groupElement;
        groupElement.m_Command = CMD_RESTORE;
        m_currentGroup->push_back( groupElement );
    }
    else
    {
        if( !m_xformStack.empty() )
        {
            m_currentXform = m_xformStack.back();
            m_xformStack.pop_back();
            updateWorldScreenMatrix();
        }
    }
}


int CAIRO_GAL_BASE::BeginGroup()
{
    // If the grouping is started: the actual path is stored in the group, when
    // a attribute was changed or when grouping stops with the end group method.
    storePath();

    GROUP group;
    int   groupNumber = getNewGroupNumber();
    m_groups.insert( std::make_pair( groupNumber, group ) );
    m_currentGroup = &m_groups[groupNumber];
    m_isGrouping = true;

    return groupNumber;
}


void CAIRO_GAL_BASE::EndGroup()
{
    storePath();
    m_isGrouping = false;
}


void CAIRO_GAL_BASE::DrawGroup( int aGroupNumber )
{
    // This method implements a small Virtual Machine - all stored commands
    // are executed; nested calling is also possible

    storePath();

    for( auto it = m_groups[aGroupNumber].begin(); it != m_groups[aGroupNumber].end(); ++it )
    {
        switch( it->m_Command )
        {
        case CMD_SET_FILL:
            m_isFillEnabled = it->m_Argument.BoolArg;
            break;

        case CMD_SET_STROKE:
            m_isStrokeEnabled = it->m_Argument.BoolArg;
            break;

        case CMD_SET_FILLCOLOR:
            m_fillColor = COLOR4D( it->m_Argument.DblArg[0], it->m_Argument.DblArg[1],
                                   it->m_Argument.DblArg[2], it->m_Argument.DblArg[3] );
            break;

        case CMD_SET_STROKECOLOR:
            m_strokeColor = COLOR4D( it->m_Argument.DblArg[0], it->m_Argument.DblArg[1],
                                     it->m_Argument.DblArg[2], it->m_Argument.DblArg[3] );
            break;

        case CMD_SET_LINE_WIDTH:
        {
            // Make lines appear at least 1 pixel wide, no matter of zoom
            double x = 1.0, y = 1.0;
            cairo_device_to_user_distance( m_currentContext, &x, &y );
            double minWidth = std::min( fabs( x ), fabs( y ) );
            cairo_set_line_width( m_currentContext,
                                  std::max( it->m_Argument.DblArg[0], minWidth ) );
            break;
        }


        case CMD_STROKE_PATH:
            cairo_set_source_rgba( m_currentContext, m_strokeColor.r, m_strokeColor.g,
                                   m_strokeColor.b, m_strokeColor.a );
            cairo_append_path( m_currentContext, it->m_CairoPath );
            cairo_stroke( m_currentContext );
            break;

        case CMD_FILL_PATH:
            cairo_set_source_rgba( m_currentContext, m_fillColor.r, m_fillColor.g, m_fillColor.b,
                                   m_strokeColor.a );
            cairo_append_path( m_currentContext, it->m_CairoPath );
            cairo_fill( m_currentContext );
            break;

            /*
        case CMD_TRANSFORM:
            cairo_matrix_t matrix;
            cairo_matrix_init( &matrix, it->argument.DblArg[0], it->argument.DblArg[1],
                               it->argument.DblArg[2], it->argument.DblArg[3],
                               it->argument.DblArg[4], it->argument.DblArg[5] );
            cairo_transform( m_currentContext, &matrix );
            break;
            */

        case CMD_ROTATE:
            cairo_rotate( m_currentContext, it->m_Argument.DblArg[0] );
            break;

        case CMD_TRANSLATE:
            cairo_translate( m_currentContext, it->m_Argument.DblArg[0], it->m_Argument.DblArg[1] );
            break;

        case CMD_SCALE:
            cairo_scale( m_currentContext, it->m_Argument.DblArg[0], it->m_Argument.DblArg[1] );
            break;

        case CMD_SAVE:
            cairo_save( m_currentContext );
            break;

        case CMD_RESTORE:
            cairo_restore( m_currentContext );
            break;

        case CMD_CALL_GROUP:
            DrawGroup( it->m_Argument.IntArg );
            break;
        }
    }
}


void CAIRO_GAL_BASE::ChangeGroupColor( int aGroupNumber, const COLOR4D& aNewColor )
{
    storePath();

    for( auto it = m_groups[aGroupNumber].begin(); it != m_groups[aGroupNumber].end(); ++it )
    {
        if( it->m_Command == CMD_SET_FILLCOLOR || it->m_Command == CMD_SET_STROKECOLOR )
        {
            it->m_Argument.DblArg[0] = aNewColor.r;
            it->m_Argument.DblArg[1] = aNewColor.g;
            it->m_Argument.DblArg[2] = aNewColor.b;
            it->m_Argument.DblArg[3] = aNewColor.a;
        }
    }
}


void CAIRO_GAL_BASE::ChangeGroupDepth( int aGroupNumber, int aDepth )
{
    // Cairo does not have any possibilities to change the depth coordinate of stored items,
    // it depends only on the order of drawing
}


void CAIRO_GAL_BASE::DeleteGroup( int aGroupNumber )
{
    storePath();

    // Delete the Cairo paths
    std::deque<GROUP_ELEMENT>::iterator it, end;

    for( it = m_groups[aGroupNumber].begin(), end = m_groups[aGroupNumber].end(); it != end; ++it )
    {
        if( it->m_Command == CMD_FILL_PATH || it->m_Command == CMD_STROKE_PATH )
            cairo_path_destroy( it->m_CairoPath );
    }

    // Delete the group
    m_groups.erase( aGroupNumber );
}


void CAIRO_GAL_BASE::ClearCache()
{
    for( auto it = m_groups.begin(); it != m_groups.end(); )
        DeleteGroup( ( it++ )->first );
}


void CAIRO_GAL_BASE::SetNegativeDrawMode( bool aSetting )
{
    cairo_set_operator( m_currentContext, aSetting ? CAIRO_OPERATOR_CLEAR : CAIRO_OPERATOR_OVER );
}


void CAIRO_GAL::StartDiffLayer()
{
    SetTarget( TARGET_TEMP );
    ClearTarget( TARGET_TEMP );
}


void CAIRO_GAL::EndDiffLayer()
{
    m_compositor->DrawBuffer( m_tempBuffer, m_mainBuffer, CAIRO_OPERATOR_ADD );
}


void CAIRO_GAL::StartNegativesLayer()
{
    SetTarget( TARGET_TEMP );
    ClearTarget( TARGET_TEMP );
}


void CAIRO_GAL::EndNegativesLayer()
{
    m_compositor->DrawBuffer( m_tempBuffer, m_mainBuffer, CAIRO_OPERATOR_OVER );
}


void CAIRO_GAL_BASE::DrawCursor( const VECTOR2D& aCursorPosition )
{
    m_cursorPosition = aCursorPosition;
}


void CAIRO_GAL_BASE::EnableDepthTest( bool aEnabled )
{
}


void CAIRO_GAL_BASE::resetContext()
{
    for( _cairo_surface* imageSurface : m_imageSurfaces )
        cairo_surface_destroy( imageSurface );

    m_imageSurfaces.clear();

    ClearScreen();

    // Compute the world <-> screen transformations
    ComputeWorldScreenMatrix();

    cairo_matrix_init( &m_cairoWorldScreenMatrix, m_worldScreenMatrix.m_data[0][0],
                       m_worldScreenMatrix.m_data[1][0], m_worldScreenMatrix.m_data[0][1],
                       m_worldScreenMatrix.m_data[1][1], m_worldScreenMatrix.m_data[0][2],
                       m_worldScreenMatrix.m_data[1][2] );

    // we work in screen-space coordinates and do the transforms outside.
    cairo_identity_matrix( m_context );

    cairo_matrix_init_identity( &m_currentXform );

    // Start drawing with a new path
    cairo_new_path( m_context );
    m_isElementAdded = true;

    updateWorldScreenMatrix();

    m_lineWidth = 0;
}


void CAIRO_GAL_BASE::drawAxes( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
{
    syncLineWidth();

    VECTOR2D p0 = roundp( xform( aStartPoint ) );
    VECTOR2D p1 = roundp( xform( aEndPoint ) );
    VECTOR2D org = roundp( xform( VECTOR2D( 0.0, 0.0 ) ) ); // Axis origin = 0,0 coord

    cairo_set_source_rgba( m_currentContext, m_axesColor.r, m_axesColor.g, m_axesColor.b,
                           m_axesColor.a );
    cairo_move_to( m_currentContext, p0.x, org.y );
    cairo_line_to( m_currentContext, p1.x, org.y );
    cairo_move_to( m_currentContext, org.x, p0.y );
    cairo_line_to( m_currentContext, org.x, p1.y );
    cairo_stroke( m_currentContext );
}


void CAIRO_GAL_BASE::drawGridLine( const VECTOR2D& aStartPoint, const VECTOR2D& aEndPoint )
{
    syncLineWidth();
    VECTOR2D p0 = roundp( xform( aStartPoint ) );
    VECTOR2D p1 = roundp( xform( aEndPoint ) );

    cairo_set_source_rgba( m_currentContext, m_gridColor.r, m_gridColor.g, m_gridColor.b,
                           m_gridColor.a );
    cairo_move_to( m_currentContext, p0.x, p0.y );
    cairo_line_to( m_currentContext, p1.x, p1.y );
    cairo_stroke( m_currentContext );
}


void CAIRO_GAL_BASE::drawGridCross( const VECTOR2D& aPoint )
{
    syncLineWidth();
    VECTOR2D offset( 0, 0 );
    double   size = 2.0 * m_lineWidthInPixels + 0.5;

    VECTOR2D p0 = roundp( xform( aPoint ) ) - VECTOR2D( size, 0 ) + offset;
    VECTOR2D p1 = roundp( xform( aPoint ) ) + VECTOR2D( size, 0 ) + offset;
    VECTOR2D p2 = roundp( xform( aPoint ) ) - VECTOR2D( 0, size ) + offset;
    VECTOR2D p3 = roundp( xform( aPoint ) ) + VECTOR2D( 0, size ) + offset;

    cairo_set_source_rgba( m_currentContext, m_gridColor.r, m_gridColor.g, m_gridColor.b,
                           m_gridColor.a );
    cairo_move_to( m_currentContext, p0.x, p0.y );
    cairo_line_to( m_currentContext, p1.x, p1.y );
    cairo_move_to( m_currentContext, p2.x, p2.y );
    cairo_line_to( m_currentContext, p3.x, p3.y );
    cairo_stroke( m_currentContext );
}


void CAIRO_GAL_BASE::drawGridPoint( const VECTOR2D& aPoint, double aWidth, double aHeight )
{
    VECTOR2D p = roundp( xform( aPoint ) );

    double sw = std::max( 1.0, aWidth );
    double sh = std::max( 1.0, aHeight );

    cairo_set_source_rgba( m_currentContext, m_gridColor.r, m_gridColor.g, m_gridColor.b,
                           m_gridColor.a );
    cairo_rectangle( m_currentContext, p.x - std::floor( sw / 2 ) - 0.5,
                     p.y - std::floor( sh / 2 ) - 0.5, sw, sh );

    cairo_fill( m_currentContext );
}


void CAIRO_GAL_BASE::flushPath()
{
    if( m_isFillEnabled )
    {
        cairo_set_source_rgba( m_currentContext, m_fillColor.r, m_fillColor.g, m_fillColor.b,
                               m_fillColor.a );

        if( m_isStrokeEnabled )
        {
            cairo_set_line_width( m_currentContext, m_lineWidthInPixels );
            cairo_fill_preserve( m_currentContext );
        }
        else
        {
            cairo_fill( m_currentContext );
        }
    }

    if( m_isStrokeEnabled )
    {
        cairo_set_line_width( m_currentContext, m_lineWidthInPixels );
        cairo_set_source_rgba( m_currentContext, m_strokeColor.r, m_strokeColor.g, m_strokeColor.b,
                               m_strokeColor.a );
        cairo_stroke( m_currentContext );
    }
}


void CAIRO_GAL_BASE::storePath()
{
    if( m_isElementAdded )
    {
        m_isElementAdded = false;

        if( !m_isGrouping )
        {
            if( m_isFillEnabled )
            {
                cairo_set_source_rgba( m_currentContext, m_fillColor.r, m_fillColor.g,
                                       m_fillColor.b, m_fillColor.a );
                cairo_fill_preserve( m_currentContext );
            }

            if( m_isStrokeEnabled )
            {
                cairo_set_source_rgba( m_currentContext, m_strokeColor.r, m_strokeColor.g,
                                       m_strokeColor.b, m_strokeColor.a );
                cairo_stroke_preserve( m_currentContext );
            }
        }
        else
        {
            // Copy the actual path, append it to the global path list
            // then check, if the path needs to be stroked/filled and
            // add this command to the group list;
            if( m_isStrokeEnabled )
            {
                GROUP_ELEMENT groupElement;
                groupElement.m_CairoPath = cairo_copy_path( m_currentContext );
                groupElement.m_Command = CMD_STROKE_PATH;
                m_currentGroup->push_back( groupElement );
            }

            if( m_isFillEnabled )
            {
                GROUP_ELEMENT groupElement;
                groupElement.m_CairoPath = cairo_copy_path( m_currentContext );
                groupElement.m_Command = CMD_FILL_PATH;
                m_currentGroup->push_back( groupElement );
            }
        }

        cairo_new_path( m_currentContext );
    }
}


void CAIRO_GAL_BASE::blitCursor( wxMemoryDC& clientDC )
{
    if( !IsCursorEnabled() )
        return;

    VECTOR2D      p = ToScreen( m_cursorPosition );
    const COLOR4D cColor = getCursorColor();
    const int     cursorSize = m_fullscreenCursor ? 8000 : 80;

    wxColour color( cColor.r * cColor.a * 255, cColor.g * cColor.a * 255, cColor.b * cColor.a * 255,
                    255 );
    clientDC.SetPen( wxPen( color ) );
    clientDC.DrawLine( p.x - cursorSize / 2, p.y, p.x + cursorSize / 2, p.y );
    clientDC.DrawLine( p.x, p.y - cursorSize / 2, p.x, p.y + cursorSize / 2 );
}


void CAIRO_GAL_BASE::drawPoly( const std::deque<VECTOR2D>& aPointList )
{
    wxCHECK( aPointList.size() > 1, /* void */ );

    // Iterate over the point list and draw the segments
    std::deque<VECTOR2D>::const_iterator it = aPointList.begin();

    syncLineWidth();

    const VECTOR2D p = roundp( xform( it->x, it->y ) );

    cairo_move_to( m_currentContext, p.x, p.y );

    for( ++it; it != aPointList.end(); ++it )
    {
        const VECTOR2D p2 = roundp( xform( it->x, it->y ) );

        cairo_line_to( m_currentContext, p2.x, p2.y );
    }

    flushPath();
    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::drawPoly( const std::vector<VECTOR2D>& aPointList )
{
    wxCHECK( aPointList.size() > 1, /* void */ );

    // Iterate over the point list and draw the segments
    std::vector<VECTOR2D>::const_iterator it = aPointList.begin();

    syncLineWidth();

    const VECTOR2D p = roundp( xform( it->x, it->y ) );

    cairo_move_to( m_currentContext, p.x, p.y );

    for( ++it; it != aPointList.end(); ++it )
    {
        const VECTOR2D p2 = roundp( xform( it->x, it->y ) );

        cairo_line_to( m_currentContext, p2.x, p2.y );
    }

    flushPath();
    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::drawPoly( const VECTOR2D aPointList[], int aListSize )
{
    wxCHECK( aListSize > 1, /* void */ );

    // Iterate over the point list and draw the segments
    const VECTOR2D* ptr = aPointList;

    syncLineWidth();

    const VECTOR2D p = roundp( xform( ptr->x, ptr->y ) );
    cairo_move_to( m_currentContext, p.x, p.y );

    for( int i = 1; i < aListSize; ++i )
    {
        ++ptr;
        const VECTOR2D p2 = roundp( xform( ptr->x, ptr->y ) );
        cairo_line_to( m_currentContext, p2.x, p2.y );
    }

    flushPath();
    m_isElementAdded = true;
}


void CAIRO_GAL_BASE::drawPoly( const SHAPE_LINE_CHAIN& aLineChain )
{
    wxCHECK( aLineChain.PointCount() > 1, /* void */ );

    syncLineWidth();

    auto numPoints = aLineChain.PointCount();

    if( aLineChain.IsClosed() )
        numPoints += 1;

    const VECTOR2I start = aLineChain.CPoint( 0 );
    const VECTOR2D p = roundp( xform( start.x, start.y ) );
    cairo_move_to( m_currentContext, p.x, p.y );

    for( int i = 1; i < numPoints; ++i )
    {
        const VECTOR2I& pw = aLineChain.CPoint( i );
        const VECTOR2D  ps = roundp( xform( pw.x, pw.y ) );
        cairo_line_to( m_currentContext, ps.x, ps.y );
    }

    flushPath();
    m_isElementAdded = true;
}


unsigned int CAIRO_GAL_BASE::getNewGroupNumber()
{
    wxASSERT_MSG( m_groups.size() < std::numeric_limits<unsigned int>::max(),
                  wxT( "There are no free slots to store a group" ) );

    while( m_groups.find( m_groupCounter ) != m_groups.end() )
        m_groupCounter++;

    return m_groupCounter++;
}


CAIRO_GAL::CAIRO_GAL( GAL_DISPLAY_OPTIONS& aDisplayOptions, wxWindow* aParent,
                      wxEvtHandler* aMouseListener, wxEvtHandler* aPaintListener,
                      const wxString& aName ) :
        CAIRO_GAL_BASE( aDisplayOptions ),
        wxWindow( aParent, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxEXPAND, aName )
{
    // Initialise compositing state
    m_mainBuffer = 0;
    m_overlayBuffer = 0;
    m_tempBuffer = 0;
    m_savedBuffer = 0;
    m_validCompositor = false;
    m_currentTarget = TARGET_NONCACHED;
    SetTarget( TARGET_NONCACHED );

    m_bitmapBuffer = nullptr;
    m_wxOutput = nullptr;

    m_parentWindow = aParent;
    m_mouseListener = aMouseListener;
    m_paintListener = aPaintListener;

    // Connect the native cursor handler
    Connect( wxEVT_SET_CURSOR, wxSetCursorEventHandler( CAIRO_GAL::onSetNativeCursor ), nullptr,
             this );

    // Connecting the event handlers
    Connect( wxEVT_PAINT, wxPaintEventHandler( CAIRO_GAL::onPaint ) );

    // Mouse events are skipped to the parent
    Connect( wxEVT_MOTION, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_LEFT_DOWN, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_LEFT_UP, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_LEFT_DCLICK, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_MIDDLE_DOWN, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_MIDDLE_UP, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_MIDDLE_DCLICK, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_RIGHT_DOWN, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_RIGHT_UP, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_RIGHT_DCLICK, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_AUX1_DOWN, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_AUX1_UP, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_AUX1_DCLICK, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_AUX2_DOWN, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_AUX2_UP, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_AUX2_DCLICK, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
    Connect( wxEVT_MOUSEWHEEL, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );

#if defined _WIN32 || defined _WIN64
    Connect( wxEVT_ENTER_WINDOW, wxMouseEventHandler( CAIRO_GAL::skipMouseEvent ) );
#endif

    Bind( wxEVT_GESTURE_ZOOM, &CAIRO_GAL::skipGestureEvent, this );
    Bind( wxEVT_GESTURE_PAN, &CAIRO_GAL::skipGestureEvent, this );

    SetSize( aParent->GetClientSize() );
    m_screenSize = ToVECTOR2I( aParent->GetClientSize() );

    // Allocate memory for pixel storage
    allocateBitmaps();

    m_isInitialized = false;
}


CAIRO_GAL::~CAIRO_GAL()
{
    deleteBitmaps();
}


void CAIRO_GAL::BeginDrawing()
{
    initSurface();

    CAIRO_GAL_BASE::BeginDrawing();

    if( !m_validCompositor )
        setCompositor();

    m_compositor->SetMainContext( m_context );
    m_compositor->SetBuffer( m_mainBuffer );
}


void CAIRO_GAL::EndDrawing()
{
    CAIRO_GAL_BASE::EndDrawing();

    // Merge buffers on the screen
    m_compositor->DrawBuffer( m_mainBuffer );
    m_compositor->DrawBuffer( m_overlayBuffer );

    // Now translate the raw context data from the format stored
    // by cairo into a format understood by wxImage.
    int height = m_screenSize.y;
    int stride = m_stride;

    unsigned char* srcRow = m_bitmapBuffer;
    unsigned char* dst = m_wxOutput;

    for( int y = 0; y < height; y++ )
    {
        for( int x = 0; x < stride; x += 4 )
        {
            const unsigned char* src = srcRow + x;

#if defined( __BYTE_ORDER__ ) && ( __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ )
            // XRGB
            dst[0] = src[1];
            dst[1] = src[2];
            dst[2] = src[3];
#else
            // BGRX
            dst[0] = src[2];
            dst[1] = src[1];
            dst[2] = src[0];
#endif

            dst += 3;
        }

        srcRow += stride;
    }

    wxImage    img( m_wxBufferWidth, m_screenSize.y, m_wxOutput, true );
    wxBitmap   bmp( img );
    wxMemoryDC mdc( bmp );
    wxClientDC clientDC( this );

    // Now it is the time to blit the mouse cursor
    blitCursor( mdc );
    clientDC.Blit( 0, 0, m_screenSize.x, m_screenSize.y, &mdc, 0, 0, wxCOPY );

    deinitSurface();
}


void CAIRO_GAL::PostPaint( wxPaintEvent& aEvent )
{
    // posts an event to m_paint_listener to ask for redraw the canvas.
    if( m_paintListener )
        wxPostEvent( m_paintListener, aEvent );
}


void CAIRO_GAL::ResizeScreen( int aWidth, int aHeight )
{
    CAIRO_GAL_BASE::ResizeScreen( aWidth, aHeight );

    // Recreate the bitmaps
    deleteBitmaps();
    allocateBitmaps();

    if( m_validCompositor )
        m_compositor->Resize( aWidth, aHeight );

    m_validCompositor = false;

    SetSize( wxSize( aWidth, aHeight ) );
}


bool CAIRO_GAL::Show( bool aShow )
{
    bool s = wxWindow::Show( aShow );

    if( aShow )
        wxWindow::Raise();

    return s;
}


int CAIRO_GAL::BeginGroup()
{
    initSurface();
    return CAIRO_GAL_BASE::BeginGroup();
}


void CAIRO_GAL::EndGroup()
{
    CAIRO_GAL_BASE::EndGroup();
    deinitSurface();
}


void CAIRO_GAL::SetTarget( RENDER_TARGET aTarget )
{
    // If the compositor is not set, that means that there is a recaching process going on
    // and we do not need the compositor now
    if( !m_validCompositor )
        return;

    // Cairo grouping prevents display of overlapping items on the same layer in the lighter color
    if( m_isInitialized )
        storePath();

    switch( aTarget )
    {
    default:
    case TARGET_CACHED:
    case TARGET_NONCACHED: m_compositor->SetBuffer( m_mainBuffer );    break;
    case TARGET_OVERLAY:   m_compositor->SetBuffer( m_overlayBuffer ); break;
    case TARGET_TEMP:      m_compositor->SetBuffer( m_tempBuffer );    break;
    }

    m_currentTarget = aTarget;
}


RENDER_TARGET CAIRO_GAL::GetTarget() const
{
    return m_currentTarget;
}


void CAIRO_GAL::ClearTarget( RENDER_TARGET aTarget )
{
    // Save the current state
    unsigned int currentBuffer = m_compositor->GetBuffer();

    switch( aTarget )
    {
    // Cached and noncached items are rendered to the same buffer
    default:
    case TARGET_CACHED:
    case TARGET_NONCACHED: m_compositor->SetBuffer( m_mainBuffer );    break;
    case TARGET_OVERLAY:   m_compositor->SetBuffer( m_overlayBuffer ); break;
    case TARGET_TEMP:      m_compositor->SetBuffer( m_tempBuffer );    break;
    }

    m_compositor->ClearBuffer( COLOR4D::BLACK );

    // Restore the previous state
    m_compositor->SetBuffer( currentBuffer );
}


void CAIRO_GAL::initSurface()
{
    if( m_isInitialized )
        return;

    m_surface = cairo_image_surface_create_for_data( m_bitmapBuffer, GAL_FORMAT, m_wxBufferWidth,
                                                     m_screenSize.y, m_stride );

    m_context = cairo_create( m_surface );

#ifdef DEBUG
    cairo_status_t status = cairo_status( m_context );
    wxASSERT_MSG( status == CAIRO_STATUS_SUCCESS, wxT( "Cairo context creation error" ) );
#endif /* DEBUG */

    m_currentContext = m_context;

    m_isInitialized = true;
}


void CAIRO_GAL::deinitSurface()
{
    if( !m_isInitialized )
        return;

    cairo_destroy( m_context );
    m_context = nullptr;
    cairo_surface_destroy( m_surface );
    m_surface = nullptr;

    m_isInitialized = false;
}


void CAIRO_GAL::allocateBitmaps()
{
    m_wxBufferWidth = m_screenSize.x;

    // Create buffer, use the system independent Cairo context backend
    m_stride = cairo_format_stride_for_width( GAL_FORMAT, m_wxBufferWidth );
    m_bufferSize = m_stride * m_screenSize.y;

    wxASSERT( m_bitmapBuffer == nullptr );
    m_bitmapBuffer = new unsigned char[m_bufferSize];

    wxASSERT( m_wxOutput == nullptr );
    m_wxOutput = new unsigned char[m_wxBufferWidth * 3 * m_screenSize.y];
}


void CAIRO_GAL::deleteBitmaps()
{
    delete[] m_bitmapBuffer;
    m_bitmapBuffer = nullptr;

    delete[] m_wxOutput;
    m_wxOutput = nullptr;
}


void CAIRO_GAL::setCompositor()
{
    // Recreate the compositor with the new Cairo context
    m_compositor.reset( new CAIRO_COMPOSITOR( &m_currentContext ) );
    m_compositor->Resize( m_screenSize.x, m_screenSize.y );
    m_compositor->SetAntialiasingMode( m_options.cairo_antialiasing_mode );

    // Prepare buffers
    m_mainBuffer = m_compositor->CreateBuffer();
    m_overlayBuffer = m_compositor->CreateBuffer();
    m_tempBuffer = m_compositor->CreateBuffer();

    m_validCompositor = true;
}


void CAIRO_GAL::onPaint( wxPaintEvent& aEvent )
{
    PostPaint( aEvent );
}


void CAIRO_GAL::skipMouseEvent( wxMouseEvent& aEvent )
{
    // Post the mouse event to the event listener registered in constructor, if any
    if( m_mouseListener )
        wxPostEvent( m_mouseListener, aEvent );
}


void CAIRO_GAL::skipGestureEvent( wxGestureEvent& aEvent )
{
    // Post the gesture event to the event listener registered in constructor, if any
    if( m_mouseListener )
        wxPostEvent( m_mouseListener, aEvent );
}


bool CAIRO_GAL::updatedGalDisplayOptions( const GAL_DISPLAY_OPTIONS& aOptions )
{
    bool refresh = false;

    if( m_validCompositor &&
        aOptions.cairo_antialiasing_mode != m_compositor->GetAntialiasingMode() )
    {
        m_compositor->SetAntialiasingMode( m_options.cairo_antialiasing_mode );
        m_validCompositor = false;
        deinitSurface();

        refresh = true;
    }

    if( super::updatedGalDisplayOptions( aOptions ) )
    {
        Refresh();
        refresh = true;
    }

    return refresh;
}


bool CAIRO_GAL::SetNativeCursorStyle( KICURSOR aCursor, bool aHiDPI )
{
    // Store the current cursor type and get the wxCursor for it
    if( !GAL::SetNativeCursorStyle( aCursor, aHiDPI ) )
        return false;

    if( aHiDPI )
        m_currentwxCursor = CURSOR_STORE::GetHiDPICursor( m_currentNativeCursor );
    else
        m_currentwxCursor = CURSOR_STORE::GetCursor( m_currentNativeCursor );

    // Update the cursor in the wx control
    wxWindow::SetCursor( m_currentwxCursor );

    return true;
}


void CAIRO_GAL::onSetNativeCursor( wxSetCursorEvent& aEvent )
{
    aEvent.SetCursor( m_currentwxCursor );
}


void CAIRO_GAL_BASE::DrawGrid()
{
    SetTarget( TARGET_NONCACHED );

    // Draw the grid
    // For the drawing the start points, end points and increments have
    // to be calculated in world coordinates
    VECTOR2D worldStartPoint = m_screenWorldMatrix * VECTOR2D( 0.0, 0.0 );
    VECTOR2D worldEndPoint = m_screenWorldMatrix * VECTOR2D( m_screenSize );

    // Compute the line marker or point radius of the grid
    // Note: generic grids can't handle sub-pixel lines without
    // either losing fine/course distinction or having some dots
    // fail to render
    float marker = std::fmax( 1.0f, m_gridLineWidth ) / m_worldScale;
    float doubleMarker = 2.0f * marker;

    // Draw axes if desired
    if( m_axesEnabled )
    {
        SetLineWidth( marker );
        drawAxes( worldStartPoint, worldEndPoint );
    }

    if( !m_gridVisibility || m_gridSize.x == 0 || m_gridSize.y == 0 )
        return;

    VECTOR2D gridScreenSize( m_gridSize );

    double gridThreshold = KiROUND( computeMinGridSpacing() / m_worldScale );

    if( m_gridStyle == GRID_STYLE::SMALL_CROSS )
        gridThreshold *= 2.0;

    // If we cannot display the grid density, scale down by a tick size and
    // try again.  Eventually, we get some representation of the grid
    while( std::min( gridScreenSize.x, gridScreenSize.y ) <= gridThreshold )
    {
        gridScreenSize = gridScreenSize * static_cast<double>( m_gridTick );
    }

    // Compute grid starting and ending indexes to draw grid points on the
    // visible screen area
    // Note: later any point coordinate will be offsetted by m_gridOrigin
    int gridStartX = KiROUND( ( worldStartPoint.x - m_gridOrigin.x ) / gridScreenSize.x );
    int gridEndX = KiROUND( ( worldEndPoint.x - m_gridOrigin.x ) / gridScreenSize.x );
    int gridStartY = KiROUND( ( worldStartPoint.y - m_gridOrigin.y ) / gridScreenSize.y );
    int gridEndY = KiROUND( ( worldEndPoint.y - m_gridOrigin.y ) / gridScreenSize.y );

    // Ensure start coordinate < end coordinate
    normalize( gridStartX, gridEndX );
    normalize( gridStartY, gridEndY );

    // Ensure the grid fills the screen
    --gridStartX;
    ++gridEndX;
    --gridStartY;
    ++gridEndY;

    // Draw the grid behind all other layers
    SetLayerDepth( m_depthRange.y * 0.75 );

    if( m_gridStyle == GRID_STYLE::LINES )
    {
        // Now draw the grid, every coarse grid line gets the double width

        // Vertical lines
        for( int j = gridStartY; j <= gridEndY; j++ )
        {
            const double y = j * gridScreenSize.y + m_gridOrigin.y;

            if( m_axesEnabled && y == 0.0 )
                continue;

            SetLineWidth( ( j % m_gridTick ) ? marker : doubleMarker );
            drawGridLine( VECTOR2D( gridStartX * gridScreenSize.x + m_gridOrigin.x, y ),
                          VECTOR2D( gridEndX * gridScreenSize.x + m_gridOrigin.x, y ) );
        }

        // Horizontal lines
        for( int i = gridStartX; i <= gridEndX; i++ )
        {
            const double x = i * gridScreenSize.x + m_gridOrigin.x;

            if( m_axesEnabled && x == 0.0 )
                continue;

            SetLineWidth( ( i % m_gridTick ) ? marker : doubleMarker );
            drawGridLine( VECTOR2D( x, gridStartY * gridScreenSize.y + m_gridOrigin.y ),
                          VECTOR2D( x, gridEndY * gridScreenSize.y + m_gridOrigin.y ) );
        }
    }
    else // Dots or Crosses grid
    {
        m_lineWidthIsOdd = true;
        m_isStrokeEnabled = true;

        for( int j = gridStartY; j <= gridEndY; j++ )
        {
            bool tickY = ( j % m_gridTick == 0 );

            for( int i = gridStartX; i <= gridEndX; i++ )
            {
                bool     tickX = ( i % m_gridTick == 0 );
                VECTOR2D pos{ i * gridScreenSize.x + m_gridOrigin.x,
                              j * gridScreenSize.y + m_gridOrigin.y };

                if( m_gridStyle == GRID_STYLE::SMALL_CROSS )
                {
                    SetLineWidth( ( tickX && tickY ) ? doubleMarker : marker );
                    drawGridCross( pos );
                }
                else if( m_gridStyle == GRID_STYLE::DOTS )
                {
                    double doubleGridLineWidth = m_gridLineWidth * 2.0f;
                    drawGridPoint( pos, ( tickX ) ? doubleGridLineWidth : m_gridLineWidth,
                                   ( tickY ) ? doubleGridLineWidth : m_gridLineWidth );
                }
            }
        }
    }
}


void CAIRO_GAL_BASE::DrawGlyph( const KIFONT::GLYPH& aGlyph, int aNth, int aTotal )
{
    if( aGlyph.IsStroke() )
    {
        const KIFONT::STROKE_GLYPH& glyph = static_cast<const KIFONT::STROKE_GLYPH&>( aGlyph );

        for( const std::vector<VECTOR2D>& pointList : glyph )
            drawPoly( pointList );
    }
    else if( aGlyph.IsOutline() )
    {
        const KIFONT::OUTLINE_GLYPH& glyph = static_cast<const KIFONT::OUTLINE_GLYPH&>( aGlyph );

        if( aNth == 0 )
        {
            cairo_close_path( m_currentContext );
            flushPath();

            cairo_new_path( m_currentContext );
            SetIsFill( true );
            SetIsStroke( false );
        }

        // eventually glyphs should not be drawn as polygons at all,
        // but as bitmaps with antialiasing, this is just a stopgap measure
        // of getting some form of outline font display

        glyph.Triangulate(
                [&]( const VECTOR2D& aVertex1, const VECTOR2D& aVertex2, const VECTOR2D& aVertex3 )
                {
                    syncLineWidth();

                    const VECTOR2D p0 = roundp( xform( aVertex1 ) );
                    const VECTOR2D p1 = roundp( xform( aVertex2 ) );
                    const VECTOR2D p2 = roundp( xform( aVertex3 ) );

                    cairo_move_to( m_currentContext, p0.x, p0.y );
                    cairo_line_to( m_currentContext, p1.x, p1.y );
                    cairo_line_to( m_currentContext, p2.x, p2.y );
                    cairo_close_path( m_currentContext );
                    cairo_set_fill_rule( m_currentContext, CAIRO_FILL_RULE_EVEN_ODD );
                    flushPath();
                    cairo_fill( m_currentContext );
                } );

        if( aNth == aTotal - 1 )
        {
            flushPath();
            SetIsFill( false );
            SetIsStroke( true );
            m_isElementAdded = true;
        }
    }
}